gnuradio-3.7.2.1/0000755000175000017500000000000012246237611013326 5ustar jcorganjcorgangnuradio-3.7.2.1/CMakeLists.txt0000664000175000017500000003052012246225607016072 0ustar jcorganjcorgan# Copyright 2010-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) message(FATAL_ERROR "Prevented in-tree build. This is bad practice.") endif(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) ######################################################################## # Project setup ######################################################################## cmake_minimum_required(VERSION 2.6) project(gnuradio CXX C) enable_testing() #select the release build type by default to get optimization flags if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") message(STATUS "Build type not specified: defaulting to release.") endif(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "") list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/Modules) # Set the version information here set(VERSION_INFO_MAJOR_VERSION 3) set(VERSION_INFO_API_COMPAT 7) set(VERSION_INFO_MINOR_VERSION 2) set(VERSION_INFO_MAINT_VERSION 1) include(GrVersion) #setup version info # Append -O2 optimization flag for Debug builds SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O2") SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O2") ######################################################################## # Environment setup ######################################################################## IF(NOT DEFINED BOOST_ROOT) SET(BOOST_ROOT ${CMAKE_INSTALL_PREFIX}) ENDIF() if(ENABLE_GR_CTRLPORT) set(GR_CTRLPORT True) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Import executables from a native build (for cross compiling) # http://www.vtk.org/Wiki/CMake_Cross_Compiling#Using_executables_in_the_build_created_during_the_build ######################################################################## if(IMPORT_EXECUTABLES) include(${IMPORT_EXECUTABLES}) endif(IMPORT_EXECUTABLES) #set file that the native build will fill with exports set(EXPORT_FILE ${CMAKE_BINARY_DIR}/ImportExecutables.cmake) file(WRITE ${EXPORT_FILE}) #blank the file (subdirs will append) ######################################################################## # Compiler specific setup ######################################################################## include(GrMiscUtils) #compiler flag check if(CMAKE_COMPILER_IS_GNUCXX AND NOT WIN32) #http://gcc.gnu.org/wiki/Visibility GR_ADD_CXX_COMPILER_FLAG_IF_AVAILABLE(-fvisibility=hidden HAVE_VISIBILITY_HIDDEN) endif() if(CMAKE_COMPILER_IS_GNUCXX) GR_ADD_CXX_COMPILER_FLAG_IF_AVAILABLE(-Wsign-compare HAVE_WARN_SIGN_COMPARE) GR_ADD_CXX_COMPILER_FLAG_IF_AVAILABLE(-Wall HAVE_WARN_ALL) GR_ADD_CXX_COMPILER_FLAG_IF_AVAILABLE(-Wno-uninitialized HAVE_WARN_NO_UNINITIALIZED) endif(CMAKE_COMPILER_IS_GNUCXX) if(MSVC) include_directories(${CMAKE_SOURCE_DIR}/cmake/msvc) #missing headers add_definitions(-D_WIN32_WINNT=0x0501) #minimum version required is windows xp add_definitions(-DNOMINMAX) #disables stupidity and enables std::min and std::max add_definitions( #stop all kinds of compatibility warnings -D_SCL_SECURE_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE ) add_definitions(-DHAVE_CONFIG_H) add_definitions(/MP) #build with multiple processors add_definitions(/bigobj) #allow for larger object files endif(MSVC) ######################################################################## # Install directories ######################################################################## include(GrPlatform) #define LIB_SUFFIX set(GR_RUNTIME_DIR bin) set(GR_LIBRARY_DIR lib${LIB_SUFFIX}) set(GR_INCLUDE_DIR include) set(GR_DATA_DIR share) set(GR_PKG_DATA_DIR ${GR_DATA_DIR}/${CMAKE_PROJECT_NAME}) set(GR_DOC_DIR ${GR_DATA_DIR}/doc) set(GR_PKG_DOC_DIR ${GR_DOC_DIR}/${CMAKE_PROJECT_NAME}-${DOCVER}) set(GR_CONF_DIR etc) set(GR_PKG_CONF_DIR ${GR_CONF_DIR}/${CMAKE_PROJECT_NAME}/conf.d) set(GR_LIBEXEC_DIR libexec) set(GR_PKG_LIBEXEC_DIR ${GR_LIBEXEC_DIR}/${CMAKE_PROJECT_NAME}) set(GRC_BLOCKS_DIR ${GR_PKG_DATA_DIR}/grc/blocks) # Special exception if prefix is /usr so we don't make a /usr/etc. string(COMPARE EQUAL ${CMAKE_INSTALL_PREFIX} "/usr" isusr) if(isusr) set(SYSCONFDIR "/${GR_CONF_DIR}" CACHE PATH "System configuration directory") else(isusr) set(SYSCONFDIR "${CMAKE_INSTALL_PREFIX}/${GR_CONF_DIR}" CACHE PATH "System configuration directory" FORCE) endif(isusr) set(GR_PREFSDIR ${SYSCONFDIR}/${CMAKE_PROJECT_NAME}/conf.d) OPTION(ENABLE_PERFORMANCE_COUNTERS "Enable block performance counters" OFF) if(ENABLE_PERFORMANCE_COUNTERS) message(STATUS "ADDING PERF COUNTERS") SET(GR_PERFORMANCE_COUNTERS True) add_definitions(-DGR_PERFORMANCE_COUNTERS) else(ENABLE_PERFORMANCE_COUNTERS) SET(GR_PERFORMANCE_COUNTERS False) message(STATUS "NO PERF COUNTERS") endif(ENABLE_PERFORMANCE_COUNTERS) ######################################################################## # Variables replaced when configuring the package config files ######################################################################## file(TO_NATIVE_PATH "${CMAKE_INSTALL_PREFIX}" prefix) file(TO_NATIVE_PATH "\${prefix}" exec_prefix) file(TO_NATIVE_PATH "\${exec_prefix}/${GR_LIBRARY_DIR}" libdir) file(TO_NATIVE_PATH "\${prefix}/${GR_INCLUDE_DIR}" includedir) file(TO_NATIVE_PATH "${SYSCONFDIR}" SYSCONFDIR) file(TO_NATIVE_PATH "${GR_PREFSDIR}" GR_PREFSDIR) ######################################################################## # Create uninstall target ######################################################################## configure_file( ${CMAKE_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake @ONLY) add_custom_target(uninstall ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake ) ######################################################################## # Enable python component ######################################################################## find_package(PythonLibs 2) find_package(SWIG) if(SWIG_FOUND) message(STATUS "Minimum SWIG version required is 1.3.31") set(SWIG_VERSION_CHECK FALSE) if("${SWIG_VERSION}" VERSION_GREATER "1.3.30") set(SWIG_VERSION_CHECK TRUE) endif() endif(SWIG_FOUND) include(GrComponent) GR_REGISTER_COMPONENT("python-support" ENABLE_PYTHON PYTHONLIBS_FOUND SWIG_FOUND SWIG_VERSION_CHECK ) find_package(CppUnit) GR_REGISTER_COMPONENT("testing-support" ENABLE_TESTING CPPUNIT_FOUND ) ######################################################################## # Add optional dlls specified in DLL_PATHS ######################################################################## foreach(path ${DLL_PATHS}) file(GLOB _dlls "${path}/*.dll") list(APPEND ALL_DLL_FILES ${_dlls}) endforeach(path) if(DEFINED ALL_DLL_FILES) include(GrPackage) CPACK_COMPONENT("extra_dlls" DISPLAY_NAME "Extra DLLs" DESCRIPTION "Extra DLLs for runtime dependency requirements" ) message(STATUS "") message(STATUS "Including the following dlls into the install:") foreach(_dll ${ALL_DLL_FILES}) message(STATUS " ${_dll}") endforeach(_dll) install(FILES ${ALL_DLL_FILES} DESTINATION ${GR_RUNTIME_DIR} COMPONENT "extra_dlls") endif() ######################################################################## # Setup volk as a subproject ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("volk" ENABLE_VOLK) set(VOLK_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/volk/include ${CMAKE_CURRENT_BINARY_DIR}/volk/include ) if(ENABLE_VOLK) include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_VOLK_DESCRIPTION "Vector optimized library of kernels") CPACK_COMPONENT("volk_runtime" GROUP "Volk" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" ) CPACK_COMPONENT("volk_devel" GROUP "Volk" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" ) add_subdirectory(volk) endif(ENABLE_VOLK) # Handle gr_log enable/disable GR_LOGGING() ######################################################################## # Distribute the README file ######################################################################## install( FILES README README.hacking DESTINATION ${GR_PKG_DOC_DIR} COMPONENT "docs" ) ######################################################################## # The following dependency libraries are needed by all gr modules: ######################################################################## list(APPEND GR_TEST_TARGET_DEPS volk gnuradio-runtime) list(APPEND GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ${CMAKE_SOURCE_DIR}/gnuradio-runtime/python ${CMAKE_BINARY_DIR}/gnuradio-runtime/swig ) # Note that above we put the binary gnuradio-runtime/python directory # before the source directory. This is due to a quirk with ControlPort # and how slice generates files and names. We want the QA and # installed code to import the same names, so we have to grab from the # binary directory first. ######################################################################## # Add subdirectories (in order of deps) ######################################################################## add_subdirectory(docs) add_subdirectory(gnuradio-runtime) add_subdirectory(gr-blocks) add_subdirectory(grc) add_subdirectory(gr-fec) add_subdirectory(gr-fft) add_subdirectory(gr-filter) add_subdirectory(gr-analog) add_subdirectory(gr-digital) add_subdirectory(gr-atsc) add_subdirectory(gr-audio) add_subdirectory(gr-comedi) add_subdirectory(gr-channels) add_subdirectory(gr-noaa) add_subdirectory(gr-pager) add_subdirectory(gr-qtgui) add_subdirectory(gr-trellis) add_subdirectory(gr-uhd) add_subdirectory(gr-utils) add_subdirectory(gr-video-sdl) add_subdirectory(gr-vocoder) add_subdirectory(gr-fcd) add_subdirectory(gr-wavelet) add_subdirectory(gr-wxgui) # Install our Cmake modules into $prefix/lib/cmake/gnuradio # See "Package Configuration Files" on page: # http://www.cmake.org/Wiki/CMake/Tutorials/Packaging configure_file( ${CMAKE_SOURCE_DIR}/cmake/Modules/GnuradioConfigVersion.cmake.in ${CMAKE_BINARY_DIR}/cmake/Modules/GnuradioConfigVersion.cmake @ONLY) SET(cmake_configs ${CMAKE_SOURCE_DIR}/cmake/Modules/GnuradioConfig.cmake ${CMAKE_BINARY_DIR}/cmake/Modules/GnuradioConfigVersion.cmake ) if(NOT CMAKE_MODULES_DIR) set(CMAKE_MODULES_DIR lib${LIB_SUFFIX}/cmake/gnuradio) endif(NOT CMAKE_MODULES_DIR) # Install all other cmake files into same directory file(GLOB cmake_others "cmake/Modules/*.cmake") list(REMOVE_ITEM cmake_others "${CMAKE_SOURCE_DIR}/cmake/Modules/FindGnuradio.cmake" ) install( FILES ${cmake_configs} ${cmake_others} DESTINATION ${CMAKE_MODULES_DIR} COMPONENT "runtime_devel" ) #finalize cpack after subdirs processed include(GrPackage) CPACK_FINALIZE() ######################################################################## # Print summary ######################################################################## GR_PRINT_COMPONENT_SUMMARY() message(STATUS "Using install prefix: ${CMAKE_INSTALL_PREFIX}") message(STATUS "Building for version: ${VERSION} / ${LIBVER}") # Create a config.h with some definitions to export to other projects. CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h ) # Install config.h in include/gnuradio install( FILES ${CMAKE_CURRENT_BINARY_DIR}/config.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio COMPONENT "runtime_devel" ) gnuradio-3.7.2.1/grc/0000755000175000017500000000000012207440367014102 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/CMakeLists.txt0000664000175000017500000001122212207440367016642 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrPython) GR_PYTHON_CHECK_MODULE("python >= 2.5" sys "sys.version.split()[0] >= '2.5'" PYTHON_MIN_VER_FOUND) GR_PYTHON_CHECK_MODULE("Cheetah >= 2.0.0" Cheetah "Cheetah.Version >= '2.0.0'" CHEETAH_FOUND) GR_PYTHON_CHECK_MODULE("lxml >= 1.3.6" lxml.etree "lxml.etree.LXML_VERSION >= (1, 3, 6, 0)" LXML_FOUND) GR_PYTHON_CHECK_MODULE("pygtk >= 2.10.0" gtk "gtk.pygtk_version >= (2, 10, 0)" PYGTK_FOUND) GR_PYTHON_CHECK_MODULE("numpy" numpy True NUMPY_FOUND) ######################################################################## # Register component ######################################################################## include(GrComponent) if(NOT CMAKE_CROSSCOMPILING) set(grc_python_deps PYTHON_MIN_VER_FOUND CHEETAH_FOUND LXML_FOUND PYGTK_FOUND NUMPY_FOUND ) endif(NOT CMAKE_CROSSCOMPILING) GR_REGISTER_COMPONENT("gnuradio-companion" ENABLE_GRC ENABLE_GNURADIO_RUNTIME ENABLE_PYTHON ${grc_python_deps} ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GRC) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_COMPONENT("grc" DISPLAY_NAME "GNU Radio Companion" DESCRIPTION "Graphical flow graph designer" DEPENDS "runtime_python" ) ######################################################################## # Create and install the grc conf file ######################################################################## file(TO_NATIVE_PATH ${CMAKE_INSTALL_PREFIX}/${GRC_BLOCKS_DIR} blocksdir) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/grc.conf.in ${CMAKE_CURRENT_BINARY_DIR}/grc.conf @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/grc.conf DESTINATION ${GR_PREFSDIR} COMPONENT "grc" ) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/grc COMPONENT "grc" ) ######################################################################## # Appens NSIS commands to set environment variables ######################################################################## if(WIN32) file(TO_NATIVE_PATH ${GR_PKG_DOC_DIR} GR_DOC_DIR) string(REPLACE "\\" "\\\\" GR_DOC_DIR ${GR_DOC_DIR}) file(TO_NATIVE_PATH ${GRC_BLOCKS_DIR} GRC_BLOCKS_PATH) string(REPLACE "\\" "\\\\" GRC_BLOCKS_PATH ${GRC_BLOCKS_PATH}) file(TO_NATIVE_PATH ${GR_PYTHON_DIR} GR_PYTHON_POSTFIX) string(REPLACE "\\" "\\\\" GR_PYTHON_POSTFIX ${GR_PYTHON_POSTFIX}) CPACK_SET(CPACK_NSIS_EXTRA_INSTALL_COMMANDS "${CPACK_NSIS_EXTRA_INSTALL_COMMANDS} #!include \\\"winmessages.nsh\\\" WriteRegStr HKLM ${HLKM_ENV} \\\"GRC_BLOCKS_PATH\\\" \\\"$INSTDIR\\\\${GRC_BLOCKS_PATH}\\\" SendMessage \\\${HWND_BROADCAST} \\\${WM_WININICHANGE} 0 \\\"STR:Environment\\\" /TIMEOUT=5000 ") CPACK_SET(CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS "${CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS} #!include \\\"winmessages.nsh\\\" DeleteRegValue HKLM ${HLKM_ENV} \\\"GRC_BLOCKS_PATH\\\" SendMessage \\\${HWND_BROADCAST} \\\${WM_WININICHANGE} 0 \\\"STR:Environment\\\" /TIMEOUT=5000 ") endif(WIN32) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(base) add_subdirectory(blocks) add_subdirectory(freedesktop) add_subdirectory(grc_gnuradio) add_subdirectory(gui) add_subdirectory(python) add_subdirectory(scripts) add_subdirectory(examples) endif(ENABLE_GRC) gnuradio-3.7.2.1/grc/todo.txt0000664000175000017500000000534612207440367015622 0ustar jcorganjcorgan################################################## # Examples ################################################## * Push-to-Talk example * Start/Stop the flow graph ################################################## # Blocks ################################################## * probe: also non-float outputs * log slider gui control * packet mod: whitening offset * wx min window size in options block * gr_adaptive_fir_ccf * size params for the graphical sinks * callbacks for set average on fft, waterfall, number sinks * add units to params: Sps, Hz, dB... * add bool type to command line option store_true or store_false * messages for packet blocks and probe blocks ################################################## # Features ################################################## * extract category from doxygen * fix up block tree to mirror current doxygen group * remove blocks in block tree covered by doxygen * param editor, expand entry boxes in focus * change param dialog to panel within main window * gui grid editor for configuring grid params/placing wxgui plots and controls * drag from one port to another to connect * per parameter docs * extract individual param docs from doxygen * doc tag in param for handwritten notes * separate generated code into top block and gui class * use gui.py in gr-wxgui and remove custom top_block_gui * configuration option for adding block paths * orientations for ports (top, right, bottom, left) * source defaults to right, sink defaults to left * separation of variables and gui controls * speedup w/ background layer and animation layer * multiple doxygen directories (doc_dir becomes doc_path) * use pango markup in tooltips for params * use get_var_make to determine if it is a variable, not regexp * concept of a project, or project flow graph * collection of blocks, hier and top * system-wide, default/work, and user created * use templates/macros to generate the repetative stuff in the xml ################################################## # Problems ################################################## * msg ports dont work with virtual connections * dont fix this until pmts are used? * hier block generation * auto generate hier library on changes * auto clean hier library when block removed * add hier blocks to tree without restart * dont generate py files in saved flowgraph dir * save/restore cwd * threads dont die on exit in probe and variable sink * align param titles in properties dialog * weird grid params misbehaving * gr hier blocks have more diverse IO capabilities than we allow for ################################################## # Future ################################################## * require pygtk 2.12 for treeview tooltips * remove try/except in BlockTreeWindow.py gnuradio-3.7.2.1/grc/freedesktop/0000755000175000017500000000000011744612271016415 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/freedesktop/CMakeLists.txt0000644000175000017500000000311011744612271021150 0ustar jcorganjcorgan# Copyright 2011-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## set(grc_freedesktop_path ${GR_PKG_DATA_DIR}/grc/freedesktop) install(FILES grc-icon-256.png grc-icon-128.png grc-icon-64.png grc-icon-48.png grc-icon-32.png gnuradio-grc.xml gnuradio-grc.desktop DESTINATION ${grc_freedesktop_path} COMPONENT "grc" ) find_program(HAVE_XDG_UTILS xdg-desktop-menu) if(UNIX AND HAVE_XDG_UTILS) set(SRCDIR ${CMAKE_INSTALL_PREFIX}/${grc_freedesktop_path}) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/grc_setup_freedesktop.in ${CMAKE_CURRENT_BINARY_DIR}/grc_setup_freedesktop @ONLY) install( PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/grc_setup_freedesktop DESTINATION ${GR_PKG_LIBEXEC_DIR} COMPONENT "grc" ) endif(UNIX AND HAVE_XDG_UTILS) gnuradio-3.7.2.1/grc/freedesktop/grc-icon-48.png0000644000175000017500000000323311700377701021054 0ustar jcorganjcorganPNG  IHDR00WsRGBbKGD pHYs B(xtIME 99@DIDATh՘Le__8RD*e+q4V Rp3-Ғ-YXmMZkdƖ&e%&e6Je,4]bwGď~p}g>y~>?z± "W=ᴹ,Ilf_{=Xk7n?m_L|E}V_{&^0 =}tWΑ>w 6Oq}'Scj2(Q1wuw׶fzv >ؐs]W6\ΌblpE h9{Ȍ0?M>̀3|e^\!pX @x_}!ۀ Bj]@,P Tε8xP?HU)T.R>9QvEIII%jE"`pxx\.; "GőtaaC DvuJ .T'jڊbAQj5FN#>>ޗʀɬ,Uf(; Nkrj5$??#O n~yҀ7U444PYYҥKB`bw^JKK#22ҫ8 ؀7OI,Z-.LMMEH^^7GjS(ܐ6OhUUpGBՊkNtb Ѵanp8-r%P__իWY~5PPPdj=ޱ? ORS'7%!222DZZo]("L&7x[z5,[LŻ;UUUBQQWW'#) ;w 2,< -c<>ЫhB_Dm`6EYYPTHxK"**Jz nQZ1]?'$B!RRR*zu /RSSZM6 "|ZhDDDHKKpE)FmY/ukꁚykqPXXHFFFn:өWf˔y\`4ޛ;M[7111fΜ9X,`?uze˖=ڽ{7vU+!Y/opRTLU`u`,l2ݵٌ"h>k,waL$N^?/5e |"^Y㎦e^%+ò Ng.R/3R[(Q*TNo;/TχoxWވ+J>o54=))$U(S>τ @vv F?@> ߳mhfŶ=~5dku FyƠx*|]ּ jsw<2 deeqײjv!2e>1" jc0؀ TLz{} b1N } ;6qR6!ĹSCBYYYdd0  /4ĨP[[۠_ :1I"P*Pf'IENDB`gnuradio-3.7.2.1/grc/freedesktop/gnuradio-grc.xml0000644000175000017500000000041111700377701021512 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/freedesktop/grc-icon-128.png0000644000175000017500000000676211700377701021145 0ustar jcorganjcorganPNG  IHDR>asRGBbKGD pHYs B(xtIME  !礁 rIDATx{t?&"G1"A!1zBW)֪E[VBSxE"/OBU!S %9C6qsv'dws$3sw;9Enڪtx/h|iHHH2",,>H;O˷jѳ^*>=ekI @Rn|q$lk5=*x7Z>N-JVGj77$[S*An][^}kV+?պvfJz 9mq9'{n HHHH%_8y}rQ>Nxūu5`QW!<^"e! 2<:hr9t@wIf0`Z֝9_Cũ,5Caa<;{b0q; X˨G ) h Ms|؜2'K >:*Nct`>怸(>mu[| | \Dvj~X%̰!j-6>uzs@ͱQB(֣fd_{7  }Lbp/7l\7OݿLwp3`=59$3 աS ob)/iUeda! \sC+ d ''ŀw@Pف[dޢk'_-J`RR"a$gJ`_T6DssW VCpD#0-L7OB#p1I`9SRd7xe e0!8K]5R0hh ,'*;ߴ EP a#zm kaPWQX9Ο?ŋ)--ł٬*ш` 66XbbbK.-IMM%##Hˀ睜 ,E ^I38tf`eeҿ|Æ Se6Pjin'0a'hӧOQB|lb GA$rvTXXYɓ'G;P@RHׅl=[pK,&--F&[455aZihhW@}}}1[ڸq#9җ45ܫ[nyt܌:cqnݔZ˳Zʴi[B{v8 30?>̙t -"**ؖ-[cȉ_ o1_nٯ_?&Mt]l޼ٗuI[% ^ C\g=EFx. 0X)Yڞ5 !NxMWPݢ`԰rf)S[ p„ t֭eΝ |kG "+QcP'.q2[XnԩSu+;**F |h6=Bf4x|طo6d=&OqDzNzư#G"1PCzŴitĉ۷SWWG\\/f|!"8j#q= F.A78L/::3f{嗽]4< xJ#ڃF8,}DjK PRRەuVoPp႒jWhT;3TWWYX,oxVԤс: 7iPˀ!CA*oҥ>YlYz)MMM m.:4AXs`N&͛gW~J|R#!mTTT(><Êj9,ު>~{n 0ΣF'&vRx%JJJx"'N{(Sƍڵk1|6oxx8S]]r3tyHLL'[\/s%:ѐF߈H2H \ 4~aK]vkSfߓ:˕6{ $JT@zYr%k֬!::IIIa߾}dee]sn.ذu?:X\C&JE.V!r =X MXK8\gϞILL (T^(,,dժU,X3gY֯] ;st\l+& MHiEs,jFy[Ol4ѣɌ5c2~xOQ`00gزe 6mi56ͨ&;bԴb|!{fB$ Q" BHe%%%QUUE(ԩSTVVRSSCZZS5`[e!i^+7U(|#HHHH\Lj#l%@詶Jo̴ q'wQ ۤl@v5d* l rH|o:t\xXxj(Q^MJ:R tu} .TWq{:d=~BݣGnc&`.=U |!@|cQs~!IG{D&  Ł'HY:u~i("y <Zl[v%y]eJ LBvM$@hA131$B ڥ>2=&4 $c1F>ߢ/I3''h:pe2绦 ԪG~eZ}q8B >PD@HjpdHxz;1t[@BzIԯz .*|%M¦@BH1A ޼$v'Ka>B^/%$$H@B@B@B@B@BZmAI ! ! :I ! ! ! ! ! ! Ñ-TJ I I@8#vIENDB`gnuradio-3.7.2.1/grc/freedesktop/gnuradio-grc.desktop0000644000175000017500000000023611700377701022370 0ustar jcorganjcorgan[Desktop Entry] Version=1.0 Type=Application Name=GRC Exec=gnuradio-companion %F Categories=Development; MimeType=application/gnuradio-grc; Icon=gnuradio-grc gnuradio-3.7.2.1/grc/freedesktop/grc-icon-32.png0000644000175000017500000000204411700377701021044 0ustar jcorganjcorganPNG  IHDR szzsBIT|d pHYs:tEXtSoftwarewww.inkscape.org<IDATX_HdU?wtPri d%L@{Ȃ| km! m{"XحZXڶRzrBX%t$nýNWΌ s~{ n3`WsE_.׶x㣯T p=R,Vt]_}Il - _ Y瓊%勅+h{.• U%xADSFEpQD= iTċl6G. . |Y$@DԲ3 hhhhs]^&?PKH$+++}ΙWVYt``s###:88XJ@&Jcu +0??pXwvv<j8e/QHgp02eiOKKKӣ---:33imnn~n`tfM`x ɵa3 ujjJOL~H"q]]]u x1x |‚A6X)&0< ̪Gz.AM]8^i7Z√D :8"@3]!R4=6_P.0 /PѥMzc"ccc% gsUn܏yGDMU=j nCZPTnuTl1^9a3Ԥi jU\*mX+DDҪeJ?%t eIENDB`gnuradio-3.7.2.1/grc/freedesktop/grc-icon-256.svg0000644000175000017500000002245311700377701021155 0ustar jcorganjcorgan image/svg+xml Patrick Strasser <patrick.strasser@tugraz.at> Icon/Symbol for the GNURadio Companion grc-icon.svg 2007-02-23 gnuradio-3.7.2.1/grc/freedesktop/grc_setup_freedesktop.in0000644000175000017500000000544411700377701023340 0ustar jcorganjcorgan#!/bin/bash # # Copyright 2008-2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # setup grc on a freedesktop platform # $1 should be install or uninstall # $2 is the optional path to the files # when $2 is unspecified, the path is: # @SRCDIR@ ################################################## ICON_SIZES="32 48 64 128 256" if [ -n "$2" ]; then SRCDIR="$2" else SRCDIR="@SRCDIR@" fi case "$1" in 'install') echo "Begin freedesktop install..." for size in ${ICON_SIZES}; do \ echo "Install icon: ${size}x${size}" xdg-icon-resource install --noupdate --context mimetypes --theme gnome --size ${size} ${SRCDIR}/grc-icon-${size}.png application-gnuradio-grc; \ xdg-icon-resource install --noupdate --context mimetypes --size ${size} ${SRCDIR}/grc-icon-${size}.png application-gnuradio-grc; \ xdg-icon-resource install --noupdate --context apps --theme gnome --size ${size} ${SRCDIR}/grc-icon-${size}.png gnuradio-grc; \ xdg-icon-resource install --noupdate --context apps --size ${size} ${SRCDIR}/grc-icon-${size}.png gnuradio-grc; \ done xdg-icon-resource forceupdate echo "Install mime type" xdg-mime install ${SRCDIR}/gnuradio-grc.xml echo "Install menu items" xdg-desktop-menu install ${SRCDIR}/*.desktop echo "Done!" echo "" ;; 'uninstall') echo "Begin freedesktop uninstall..." for size in ${ICON_SIZES}; do \ echo "Uninstall icon: ${size}x${size}" xdg-icon-resource uninstall --noupdate --context mimetypes --theme gnome --size ${size} application-gnuradio-grc; \ xdg-icon-resource uninstall --noupdate --context mimetypes --size ${size} application-gnuradio-grc; \ xdg-icon-resource uninstall --noupdate --context apps --theme gnome --size ${size} gnuradio-grc; \ xdg-icon-resource uninstall --noupdate --context apps --size ${size} gnuradio-grc; \ done xdg-icon-resource forceupdate echo "Uninstall mime type" xdg-mime uninstall ${SRCDIR}/gnuradio-grc.xml echo "Uninstall menu items" xdg-desktop-menu uninstall `ls ${SRCDIR}/*.desktop | xargs -n1 basename` echo "Done!" echo "" ;; *) echo "Usage: $0 [install|uninstall]" ;; esac gnuradio-3.7.2.1/grc/freedesktop/grc-icon-256.png0000644000175000017500000001724311700377701021143 0ustar jcorganjcorganPNG  IHDR\rfsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org< IDATxyչ3 ʎDEYE%:cB_+u5}5yըK(+"bE *DV 2?Nꥺs>CwmO]O:uꔨ*Qh0J݁bǑlw-LٟO=<8Scb11f `LYȡvޢ|؇#7LLX؀`QD);0@H kV0&ZMD俁@{P[MDV+ ֌7EƘ( "Tt6n䘈."gD/u;%"򌈜ta"R;ZEFibg%V0& " U/"〹"2k&9;G/Dx\pKƤAD~ B I0W"o骚 'UįoQ3.z _Uz0&$80<te"x cE䗪:83}|Dd5088\=q[sRLD9ސߗ,^"Z `Z&WDdޗR5I;72P>˵Q` zsG\ :H5V'~lI. ܀!wV0E-[xsNI{{,¬o9W`6Yu'πlw;f d#0jʫa p^ǍƳ,BD~ \ 0u@ ;0q4POߊvV̟m3Ed$07ULQ˰ 8pj Ϩ!ߗ\ cUuGbˀ&vTP^2w.~!?=뿰Scxǹ⋣#-eee{r!Q,0b. | |(>{?GH 78ȶ,XMM ={dѢEQ>}Ӵi&?0", wM|^}aCv0&O{wޝ.]PRRTW~mm-7ofӦM;wMMMVϟ?'|QFeB'";Υnp3pzZ T޽{駟e˖>|[lI6mķ~~;{ϻXϞ=O())Nv. ⮭EQYԻcZ/=Z5U^zɷ%ꫯ,jׯoSL,t$=ܣ-.VmK-nW),=?KӦMuŊƸdm֬gƘ > K[v){}|ƒ6nܨ垟墋.:LUUꪫqkqC-OO{:k< |v%7dՂ|)@UU6ms@'qy~2]fMadڵZVVVTI+ }woM`b"&#W;x1@\_Nr_YYI֭M0{'z<4ooHYWpktUͮV wcDY{a K+V`ٞ1"OѤgСg͚EUUUɫpȕZ@OT)UM"D~:a KO=T],-Zpg1LYY6֫ӫ'`PpR:?̖whKYz)2f͚)4`,ͯ_>z.MHI<7>-@>3͛9OV 5<~= P*wPUOVsVF߸ˉt_XȂ_> 5Ӏ}pnݰ;(PnڵFf o~80 I닻|m/eG߁Ir.t?kL*q4,q]wvPJ1&*mѢg7pCaeРASN:ĤHχ|)'W;'/6Ǥ￟7zS `yt$أUt5۬-0U}' ҴzjƎ9O^'MglAUe̘1y(T'Gy%, <_zd M<ѣMjՊJgeN0 3mU5p8p4rOD irT*Qիe˖vUnu9s9u; I{g+_\{VsQdoS}wvշo_׮];:2Lk};"r vm!~doKߥKݲeKԡfo@!g6IA \JY%\wu;mafm˖-ھ}{ٻw!gC| n05F 7FA 鸛~L,tkw2*`ZZZgN j;eԩQ'7}BO%ۆn~R|*+"Y~n!xg @pׯ7·z(Ps;wuEj }.^m"z5r57:?u9ue~+"03Mׄ} 8(I |b|R8vH  4qV"":k֬H0'Wӵ>ɶς+ c=(M?:s}?{וֹ-,L; RVH|v5@CZJ۴i<Ȇ="wImGQT82]wt„ y/ A mذ!eܢuYTx77~<TU׭[C СC[h;Y&j|m^g=\@A_O. `Μ9}FK:,fk΋律uKtjK#O555:q@ʱ6m =Bxbs=֭[3[ p2/~ZwϡE ۻU)SЧO?|.]h^zK/Q^^r[n<쳞Yv-1E!w@d\X!" kg"QDF"fI6!657 /W^yeZuk׮rʜTL&NjҤ^z饺pb IKzB>e ?=E8M@܀%ml+q*e=dmx -[ƪUXj˗/wa]H1c:uqcҥz뭁߾};<<ݻw  @˖-C9^~r~u,KU[plX{YWFRjvX.3_gKctfO[j=zg8?~iG탺(ڵku=YfѡC?s1?֭/୷bԩ9  l;TW=)%K)4oޜɓ'=0j(x㍜%ƶmd= {2״lzCA@ӦMY`Hqׯ_?Ν'~HB*sqc_˃.h .?qѹsg ;v/ ӧO#x=yN~{ U?zw'?__ߺwHuyf[VzmnNҥ  ={ )Ư NʭyN>W'{SU?n䣁h0o6-ۚv2ITX'V^ N8O?JzRtg2x`M/YlryN+{O?qD8׶8w;%Su[n 6mҮ];ڶmۗ-ZDbVRR A4=|gL>iӦfjkkwZ& @%6U];-4:+mj_z]Rռ^y\?VȄLjjjbժU;Jee%[N{]<XDX衪+X0E-0DK)0݅Q^0ǫjQ`bGUq#~Ռ"Vd#)h`=+ ' o޽{l޼> {챌5O "CWDUNVwfkVd[ND4*oR /Ҙ4`."{%kZ ^JsSׁe"r_Â=U %T4WD1"rX Fؘtj5p8\]z lM*`LB&pL =SMTYn'c'm=-LMUg!C N9dm$UupnpͰ=Y0ƃU3#Cy!ח%cPTu9\}^C1iPz-7,ܓwR䍀D798^pd1Kd) %ʣ"RK,@v `LTukEI11f `LY0&,c1KĘ%cb,E0*RQL6`LY0&,c1KĘ%cb11@l:V9e!FjĘ%cb1;ծKIX0&|}KIX0&|})Ci`LL`L#W2/Q$a ٬`L#u A^G X0&\L_KI |f{:&;ahcf2<H*V0&"pl U|ē%cq'gH19'">U!O!9uCH,#"r 2g=G19 "G{C!b ,h`67LWթ!(r-HGD:c $g5c$"?*U"K @DZq]{JX8CU?#lX0ā޾^9A_Y9d x ^/+Q%c18GU#'k4&8~1 pΈ:`L>}/jb ~f~q)!F$yUB 241 (V7hiiahhMӰX,XVl66 ),,m:U |'X_PL n]v׷V($a4|,̚5L&>˥Kx<\.Ξ=KQQ'O$77XO_u`=Aڟ@f4?1g@WWTyy|au6o-| !bzfsXݵk/ [nvVӓ@.xX$qV/TVV*@uttD4M*ɤzzzaS16cʀ6:;;bƌ322C4v-ۃ`K֗Kw#r)V\qFÌinnVIp똠+lGL.\`߯&OuW6HNx8Ć4K/jΜ9 P֭szi&ڈ#Ot lIwcЁzEz\p6uTv U PWV6hJ ,_ ,F*x/YwCUZZۣ.rZZZjU;wjjjR IH .yz:X|(TVV*1JoϞ=`ܫV2b1 /C˖-bpqow SZ&̜9KR__OVVָ… q8lذ۷Ӄ yxxx)o- .nl>}׺ΝSRR2rmĉx<@-"]1,#lٲՊ5k4- %)ڀ;n;H4L$N;'I5gΜA)t&ؤYMw QQ D罍H$@/I<K ClnJTKR5Hf@4>\1#&%2WjuQP5q1P%LN*Zm=iX|8(h[ S)8+f1r:f%5ӉP2 ] k䒐=d; `8H Q E֚f@7wW.IENDB`gnuradio-3.7.2.1/grc/base/0000755000175000017500000000000012237515112015006 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/base/Platform.py0000664000175000017500000001725312237515112017156 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os import sys from .. base import ParseXML, odict from Element import Element as _Element from FlowGraph import FlowGraph as _FlowGraph from Connection import Connection as _Connection from Block import Block as _Block from Port import Port as _Port from Param import Param as _Param from Constants import BLOCK_TREE_DTD, FLOW_GRAPH_DTD class Platform(_Element): def __init__(self, name, version, key, block_paths, block_dtd, default_flow_graph, generator, license='', website=None, colors=[]): """ Make a platform from the arguments. Args: name: the platform name version: the version string key: the unique platform key block_paths: the file paths to blocks in this platform block_dtd: the dtd validator for xml block wrappers default_flow_graph: the default flow graph file path generator: the generator class for this platform colors: a list of title, color_spec tuples license: a multi-line license (first line is copyright) website: the website url for this platform Returns: a platform object """ _Element.__init__(self) self._name = name self._version = version self._key = key self._license = license self._website = website self._block_paths = block_paths self._block_dtd = block_dtd self._default_flow_graph = default_flow_graph self._generator = generator self._colors = colors #create a dummy flow graph for the blocks self._flow_graph = _Element(self) #search for *.xml files in the given search path self.loadblocks(); def loadblocks(self): xml_files = list() for block_path in self._block_paths: if os.path.isfile(block_path): xml_files.append(block_path) elif os.path.isdir(block_path): for dirpath, dirnames, filenames in os.walk(block_path): for filename in sorted(filter(lambda f: f.endswith('.xml'), filenames)): xml_files.append(os.path.join(dirpath, filename)) #load the blocks self._blocks = odict() self._blocks_n = odict() self._block_tree_files = list() for xml_file in xml_files: try: #try to add the xml file as a block wrapper ParseXML.validate_dtd(xml_file, self._block_dtd) n = ParseXML.from_file(xml_file).find('block') #inject block wrapper path n['block_wrapper_path'] = xml_file block = self.Block(self._flow_graph, n) key = block.get_key() #test against repeated keys if key in self.get_block_keys(): print >> sys.stderr, 'Warning: Block with key "%s" already exists.\n\tIgnoring: %s'%(key, xml_file) #store the block else: self._blocks[key] = block self._blocks_n[key] = n except ParseXML.XMLSyntaxError, e: try: #try to add the xml file as a block tree ParseXML.validate_dtd(xml_file, BLOCK_TREE_DTD) self._block_tree_files.append(xml_file) except ParseXML.XMLSyntaxError, e: print >> sys.stderr, 'Warning: Block validation failed:\n\t%s\n\tIgnoring: %s'%(e, xml_file) except Exception, e: print >> sys.stderr, 'Warning: Block loading failed:\n\t%s\n\tIgnoring: %s'%(e, xml_file) def parse_flow_graph(self, flow_graph_file): """ Parse a saved flow graph file. Ensure that the file exists, and passes the dtd check. Args: flow_graph_file: the flow graph file Returns: nested data @throws exception if the validation fails """ flow_graph_file = flow_graph_file or self._default_flow_graph open(flow_graph_file, 'r') #test open ParseXML.validate_dtd(flow_graph_file, FLOW_GRAPH_DTD) return ParseXML.from_file(flow_graph_file) def load_block_tree(self, block_tree): """ Load a block tree with categories and blocks. Step 1: Load all blocks from the xml specification. Step 2: Load blocks with builtin category specifications. Args: block_tree: the block tree object """ #recursive function to load categories and blocks def load_category(cat_n, parent=[]): #add this category parent = parent + [cat_n.find('name')] block_tree.add_block(parent) #recursive call to load sub categories map(lambda c: load_category(c, parent), cat_n.findall('cat')) #add blocks in this category for block_key in cat_n.findall('block'): if block_key not in self.get_block_keys(): print >> sys.stderr, 'Warning: Block key "%s" not found when loading category tree.'%(block_key) continue block = self.get_block(block_key) #if it exists, the block's category shall not be overridden by the xml tree if not block.get_category(): block.set_category(parent) #load the block tree and update the categories for each block for block_tree_file in self._block_tree_files: #recursivly put categories in blocks load_category(ParseXML.from_file(block_tree_file).find('cat')) #add blocks to block tree for block in self.get_blocks(): #blocks with empty categories are hidden if not block.get_category(): continue block_tree.add_block(block.get_category(), block) def __str__(self): return 'Platform - %s(%s)'%(self.get_key(), self.get_name()) def is_platform(self): return True def get_new_flow_graph(self): return self.FlowGraph(platform=self) def get_generator(self): return self._generator ############################################## # Access Blocks ############################################## def get_block_keys(self): return self._blocks.keys() def get_block(self, key): return self._blocks[key] def get_blocks(self): return self._blocks.values() def get_new_block(self, flow_graph, key): return self.Block(flow_graph, n=self._blocks_n[key]) def get_name(self): return self._name def get_version(self): return self._version def get_key(self): return self._key def get_license(self): return self._license def get_website(self): return self._website def get_colors(self): return self._colors ############################################## # Constructors ############################################## FlowGraph = _FlowGraph Connection = _Connection Block = _Block Port = _Port Param = _Param gnuradio-3.7.2.1/grc/base/Port.py0000664000175000017500000000777212207702530016322 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Element import Element class Port(Element): def __init__(self, block, n, dir): """ Make a new port from nested data. Args: block: the parent element n: the nested odict dir: the direction source or sink """ #build the port Element.__init__(self, block) #grab the data self._name = n['name'] self._key = n['key'] self._type = n['type'] self._dir = dir def validate(self): """ Validate the port. The port must be non-empty and type must a possible type. """ Element.validate(self) if self.get_type() not in self.get_types(): self.add_error_message('Type "%s" is not a possible type.'%self.get_type()) def __str__(self): if self.is_source(): return 'Source - %s(%s)'%(self.get_name(), self.get_key()) if self.is_sink(): return 'Sink - %s(%s)'%(self.get_name(), self.get_key()) def get_types(self): """ Get a list of all possible port types. @throw NotImplementedError """ raise NotImplementedError def is_port(self): return True def get_color(self): return '#FFFFFF' def get_name(self): number = '' if self.get_type() == 'bus': busses = filter(lambda a: a._dir == self._dir, self.get_parent().get_ports_gui()); number = str(busses.index(self)) + '#' + str(len(self.get_associated_ports())); return self._name + number def get_key(self): return self._key def is_sink(self): return self._dir == 'sink' def is_source(self): return self._dir == 'source' def get_type(self): return self.get_parent().resolve_dependencies(self._type) def get_connections(self): """ Get all connections that use this port. Returns: a list of connection objects """ connections = self.get_parent().get_parent().get_connections() connections = filter(lambda c: c.get_source() is self or c.get_sink() is self, connections) return connections def get_enabled_connections(self): """ Get all enabled connections that use this port. Returns: a list of connection objects """ return filter(lambda c: c.get_enabled(), self.get_connections()) def get_associated_ports(self): if not self.get_type() == 'bus': return [self]; else: if self.is_source(): get_p = self.get_parent().get_sources; bus_structure = self.get_parent().current_bus_structure['source']; direc = 'source' else: get_p = self.get_parent().get_sinks; bus_structure = self.get_parent().current_bus_structure['sink']; direc = 'sink' ports = [i for i in get_p() if not i.get_type() == 'bus']; if bus_structure: busses = [i for i in get_p() if i.get_type() == 'bus']; bus_index = busses.index(self); ports = filter(lambda a: ports.index(a) in bus_structure[bus_index], ports); return ports; gnuradio-3.7.2.1/grc/base/CMakeLists.txt0000644000175000017500000000233111744612271017553 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## GR_PYTHON_INSTALL(FILES odict.py ParseXML.py Block.py Connection.py Constants.py Element.py FlowGraph.py Param.py Platform.py Port.py __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/grc/base COMPONENT "grc" ) install(FILES block_tree.dtd flow_graph.dtd DESTINATION ${GR_PYTHON_DIR}/gnuradio/grc/base COMPONENT "grc" ) gnuradio-3.7.2.1/grc/base/Constants.py0000644000175000017500000000170411700377701017342 0ustar jcorganjcorgan""" Copyright 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os #data files DATA_DIR = os.path.dirname(__file__) FLOW_GRAPH_DTD = os.path.join(DATA_DIR, 'flow_graph.dtd') BLOCK_TREE_DTD = os.path.join(DATA_DIR, 'block_tree.dtd') gnuradio-3.7.2.1/grc/base/block_tree.dtd0000664000175000017500000000172612207702530017623 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/base/Param.py0000664000175000017500000001601112207702530016420 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from . import odict from Element import Element def _get_keys(lst): return [elem.get_key() for elem in lst] def _get_elem(lst, key): try: return lst[_get_keys(lst).index(key)] except ValueError: raise ValueError, 'Key "%s" not found in %s.'%(key, _get_keys(lst)) class Option(Element): def __init__(self, param, n): Element.__init__(self, param) self._name = n.find('name') self._key = n.find('key') self._opts = dict() opts = n.findall('opt') #test against opts when non enum if not self.get_parent().is_enum() and opts: raise Exception, 'Options for non-enum types cannot have sub-options' #extract opts for opt in opts: #separate the key:value try: key, value = opt.split(':') except: raise Exception, 'Error separating "%s" into key:value'%opt #test against repeated keys if self._opts.has_key(key): raise Exception, 'Key "%s" already exists in option'%key #store the option self._opts[key] = value def __str__(self): return 'Option %s(%s)'%(self.get_name(), self.get_key()) def get_name(self): return self._name def get_key(self): return self._key ############################################## # Access Opts ############################################## def get_opt_keys(self): return self._opts.keys() def get_opt(self, key): return self._opts[key] def get_opts(self): return self._opts.values() class Param(Element): def __init__(self, block, n): """ Make a new param from nested data. Args: block: the parent element n: the nested odict """ #grab the data self._name = n.find('name') self._key = n.find('key') value = n.find('value') or '' self._type = n.find('type') self._hide = n.find('hide') or '' #build the param Element.__init__(self, block) #create the Option objects from the n data self._options = list() for option in map(lambda o: Option(param=self, n=o), n.findall('option')): key = option.get_key() #test against repeated keys if key in self.get_option_keys(): raise Exception, 'Key "%s" already exists in options'%key #store the option self.get_options().append(option) #test the enum options if self.is_enum(): #test against options with identical keys if len(set(self.get_option_keys())) != len(self.get_options()): raise Exception, 'Options keys "%s" are not unique.'%self.get_option_keys() #test against inconsistent keys in options opt_keys = self.get_options()[0].get_opt_keys() for option in self.get_options(): if set(opt_keys) != set(option.get_opt_keys()): raise Exception, 'Opt keys "%s" are not identical across all options.'%opt_keys #if a value is specified, it must be in the options keys self._value = value if value or value in self.get_option_keys() else self.get_option_keys()[0] if self.get_value() not in self.get_option_keys(): raise Exception, 'The value "%s" is not in the possible values of "%s".'%(self.get_value(), self.get_option_keys()) else: self._value = value or '' def validate(self): """ Validate the param. The value must be evaluated and type must a possible type. """ Element.validate(self) if self.get_type() not in self.get_types(): self.add_error_message('Type "%s" is not a possible type.'%self.get_type()) def get_evaluated(self): raise NotImplementedError def to_code(self): """ Convert the value to code. @throw NotImplementedError """ raise NotImplementedError def get_types(self): """ Get a list of all possible param types. @throw NotImplementedError """ raise NotImplementedError def get_color(self): return '#FFFFFF' def __str__(self): return 'Param - %s(%s)'%(self.get_name(), self.get_key()) def is_param(self): return True def get_name(self): return self._name def get_key(self): return self._key def get_hide(self): return self.get_parent().resolve_dependencies(self._hide).strip() def get_value(self): value = self._value if self.is_enum() and value not in self.get_option_keys(): value = self.get_option_keys()[0] self.set_value(value) return value def set_value(self, value): self._value = str(value) #must be a string def get_type(self): return self.get_parent().resolve_dependencies(self._type) def is_enum(self): return self._type == 'enum' def __repr__(self): """ Get the repr (nice string format) for this param. Just return the value (special case enum). Derived classes can handle complex formatting. Returns: the string representation """ if self.is_enum(): return self.get_option(self.get_value()).get_name() return self.get_value() ############################################## # Access Options ############################################## def get_option_keys(self): return _get_keys(self.get_options()) def get_option(self, key): return _get_elem(self.get_options(), key) def get_options(self): return self._options ############################################## # Access Opts ############################################## def get_opt_keys(self): return self.get_option(self.get_value()).get_opt_keys() def get_opt(self, key): return self.get_option(self.get_value()).get_opt(key) def get_opts(self): return self.get_option(self.get_value()).get_opts() ############################################## ## Import/Export Methods ############################################## def export_data(self): """ Export this param's key/value. Returns: a nested data odict """ n = odict() n['key'] = self.get_key() n['value'] = self.get_value() return n gnuradio-3.7.2.1/grc/base/Connection.py0000664000175000017500000001044312207702530017462 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Element import Element from . import odict class Connection(Element): def __init__(self, flow_graph, porta, portb): """ Make a new connection given the parent and 2 ports. Args: flow_graph: the parent of this element porta: a port (any direction) portb: a port (any direction) @throws Error cannot make connection Returns: a new connection """ Element.__init__(self, flow_graph) source = sink = None #separate the source and sink for port in (porta, portb): if port.is_source(): source = port if port.is_sink(): sink = port if not source: raise ValueError('Connection could not isolate source') if not sink: raise ValueError('Connection could not isolate sink') busses = len(filter(lambda a: a.get_type() == 'bus', [source, sink]))%2 if not busses == 0: raise ValueError('busses must get with busses') if not len(source.get_associated_ports()) == len(sink.get_associated_ports()): raise ValueError('port connections must have same cardinality'); #ensure that this connection (source -> sink) is unique for connection in self.get_parent().get_connections(): if connection.get_source() is source and connection.get_sink() is sink: raise Exception('This connection between source and sink is not unique.') self._source = source self._sink = sink if source.get_type() == 'bus': sources = source.get_associated_ports(); sinks = sink.get_associated_ports(); for i in range(len(sources)): try: flow_graph.connect(sources[i], sinks[i]); except: pass def __str__(self): return 'Connection (\n\t%s\n\t\t%s\n\t%s\n\t\t%s\n)'%( self.get_source().get_parent(), self.get_source(), self.get_sink().get_parent(), self.get_sink(), ) def is_connection(self): return True def validate(self): """ Validate the connections. The ports must match in type. """ Element.validate(self) source_type = self.get_source().get_type() sink_type = self.get_sink().get_type() if source_type != sink_type: self.add_error_message('Source type "%s" does not match sink type "%s".'%(source_type, sink_type)) def get_enabled(self): """ Get the enabled state of this connection. Returns: true if source and sink blocks are enabled """ return self.get_source().get_parent().get_enabled() and \ self.get_sink().get_parent().get_enabled() ############################# # Access Ports ############################# def get_sink(self): return self._sink def get_source(self): return self._source ############################################## ## Import/Export Methods ############################################## def export_data(self): """ Export this connection's info. Returns: a nested data odict """ n = odict() n['source_block_id'] = self.get_source().get_parent().get_id() n['sink_block_id'] = self.get_sink().get_parent().get_id() n['source_key'] = self.get_source().get_key() n['sink_key'] = self.get_sink().get_key() return n gnuradio-3.7.2.1/grc/base/Element.py0000664000175000017500000000650112207702530016754 0ustar jcorganjcorgan""" Copyright 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ class Element(object): def __init__(self, parent=None): self._parent = parent ################################################## # Element Validation API ################################################## def validate(self): """ Validate this element and call validate on all children. Call this base method before adding error messages in the subclass. """ self._error_messages = list() for child in self.get_children(): child.validate() def is_valid(self): """ Is this element valid? Returns: true when the element is enabled and has no error messages """ return not self.get_error_messages() or not self.get_enabled() def add_error_message(self, msg): """ Add an error message to the list of errors. Args: msg: the error message string """ self._error_messages.append(msg) def get_error_messages(self): """ Get the list of error messages from this element and all of its children. Do not include the error messages from disabled children. Cleverly indent the children error messages for printing purposes. Returns: a list of error message strings """ error_messages = list(self._error_messages) #make a copy for child in filter(lambda c: c.get_enabled(), self.get_children()): for msg in child.get_error_messages(): error_messages.append("%s:\n\t%s"%(child, msg.replace("\n", "\n\t"))) return error_messages def rewrite(self): """ Rewrite this element and call rewrite on all children. Call this base method before rewriting the element. """ for child in self.get_children(): child.rewrite() def get_enabled(self): return True ############################################## ## Tree-like API ############################################## def get_parent(self): return self._parent def get_children(self): return list() ############################################## ## Type testing methods ############################################## def is_element(self): return True def is_platform(self): return False def is_flow_graph(self): return False def is_connection(self): return False def is_block(self): return False def is_source(self): return False def is_sink(self): return False def is_port(self): return False def is_param(self): return False gnuradio-3.7.2.1/grc/base/ParseXML.py0000664000175000017500000000722612207702530017023 0ustar jcorganjcorgan""" Copyright 2008 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from lxml import etree from . import odict class XMLSyntaxError(Exception): def __init__(self, error_log): self._error_log = error_log def __str__(self): return '\n'.join(map(str, self._error_log.filter_from_errors())) def validate_dtd(xml_file, dtd_file=None): """ Validate an xml file against its dtd. Args: xml_file: the xml file dtd_file: the optional dtd file @throws Exception validation fails """ #perform parsing, use dtd validation if dtd file is not specified parser = etree.XMLParser(dtd_validation=not dtd_file) xml = etree.parse(xml_file, parser=parser) if parser.error_log: raise XMLSyntaxError(parser.error_log) #perform dtd validation if the dtd file is specified if not dtd_file: return dtd = etree.DTD(dtd_file) if not dtd.validate(xml.getroot()): raise XMLSyntaxError(dtd.error_log) def from_file(xml_file): """ Create nested data from an xml file using the from xml helper. Args: xml_file: the xml file path Returns: the nested data """ xml = etree.parse(xml_file).getroot() return _from_file(xml) def _from_file(xml): """ Recursivly parse the xml tree into nested data format. Args: xml: the xml tree Returns: the nested data """ tag = xml.tag if not len(xml): return odict({tag: xml.text or ''}) #store empty tags (text is None) as empty string nested_data = odict() for elem in xml: key, value = _from_file(elem).items()[0] if nested_data.has_key(key): nested_data[key].append(value) else: nested_data[key] = [value] #delistify if the length of values is 1 for key, values in nested_data.iteritems(): if len(values) == 1: nested_data[key] = values[0] return odict({tag: nested_data}) def to_file(nested_data, xml_file): """ Write an xml file and use the to xml helper method to load it. Args: nested_data: the nested data xml_file: the xml file path """ xml = _to_file(nested_data)[0] open(xml_file, 'w').write(etree.tostring(xml, xml_declaration=True, pretty_print=True)) def _to_file(nested_data): """ Recursivly parse the nested data into xml tree format. Args: nested_data: the nested data Returns: the xml tree filled with child nodes """ nodes = list() for key, values in nested_data.iteritems(): #listify the values if not a list if not isinstance(values, (list, set, tuple)): values = [values] for value in values: node = etree.Element(key) if isinstance(value, (str, unicode)): node.text = value else: node.extend(_to_file(value)) nodes.append(node) return nodes if __name__ == '__main__': """Use the main method to test parse xml's functions.""" pass gnuradio-3.7.2.1/grc/base/FlowGraph.py0000664000175000017500000002747012207702530017264 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from . import odict from Element import Element from .. gui import Messages class FlowGraph(Element): def __init__(self, platform): """ Make a flow graph from the arguments. Args: platform: a platforms with blocks and contrcutors Returns: the flow graph object """ #initialize Element.__init__(self, platform) #inital blank import self.import_data() def _get_unique_id(self, base_id=''): """ Get a unique id starting with the base id. Args: base_id: the id starts with this and appends a count Returns: a unique id """ index = 0 while True: id = '%s_%d'%(base_id, index) index = index + 1 #make sure that the id is not used by another block if not filter(lambda b: b.get_id() == id, self.get_blocks()): return id def __str__(self): return 'FlowGraph - %s(%s)'%(self.get_option('title'), self.get_option('id')) def rewrite(self): def refactor_bus_structure(): for block in self.get_blocks(): for direc in ['source', 'sink']: if direc == 'source': get_p = block.get_sources; get_p_gui = block.get_sources_gui; bus_structure = block.form_bus_structure('source'); else: get_p = block.get_sinks; get_p_gui = block.get_sinks_gui bus_structure = block.form_bus_structure('sink'); if 'bus' in map(lambda a: a.get_type(), get_p_gui()): if len(get_p_gui()) > len(bus_structure): times = range(len(bus_structure), len(get_p_gui())); for i in times: for connect in get_p_gui()[-1].get_connections(): block.get_parent().remove_element(connect); get_p().remove(get_p_gui()[-1]); elif len(get_p_gui()) < len(bus_structure): n = {'name':'bus','type':'bus'}; if True in map(lambda a: isinstance(a.get_nports(), int), get_p()): n['nports'] = str(1); times = range(len(get_p_gui()), len(bus_structure)); for i in times: n['key'] = str(len(get_p())); n = odict(n); port = block.get_parent().get_parent().Port(block=block, n=n, dir=direc); get_p().append(port); for child in self.get_children(): child.rewrite() refactor_bus_structure(); def get_option(self, key): """ Get the option for a given key. The option comes from the special options block. Args: key: the param key for the options block Returns: the value held by that param """ return self._options_block.get_param(key).get_evaluated() def is_flow_graph(self): return True ############################################## ## Access Elements ############################################## def get_block(self, id): return filter(lambda b: b.get_id() == id, self.get_blocks())[0] def get_blocks_unordered(self): return filter(lambda e: e.is_block(), self.get_elements()) def get_blocks(self): blocks = self.get_blocks_unordered(); for i in range(len(blocks)): if blocks[i].get_key() == 'variable': blk = blocks[i]; blocks.remove(blk); blocks.insert(1, blk); return blocks; def get_connections(self): return filter(lambda e: e.is_connection(), self.get_elements()) def get_children(self): return self.get_elements() def get_elements(self): """ Get a list of all the elements. Always ensure that the options block is in the list (only once). Returns: the element list """ options_block_count = self._elements.count(self._options_block) if not options_block_count: self._elements.append(self._options_block) for i in range(options_block_count-1): self._elements.remove(self._options_block) return self._elements def get_enabled_blocks(self): """ Get a list of all blocks that are enabled. Returns: a list of blocks """ return filter(lambda b: b.get_enabled(), self.get_blocks()) def get_enabled_connections(self): """ Get a list of all connections that are enabled. Returns: a list of connections """ return filter(lambda c: c.get_enabled(), self.get_connections()) def get_new_block(self, key): """ Get a new block of the specified key. Add the block to the list of elements. Args: key: the block key Returns: the new block or None if not found """ if key not in self.get_parent().get_block_keys(): return None block = self.get_parent().get_new_block(self, key) self.get_elements().append(block); if block._bussify_sink: block.bussify({'name':'bus','type':'bus'}, 'sink') if block._bussify_source: block.bussify({'name':'bus','type':'bus'}, 'source') return block; def connect(self, porta, portb): """ Create a connection between porta and portb. Args: porta: a port portb: another port @throw Exception bad connection Returns: the new connection """ connection = self.get_parent().Connection(flow_graph=self, porta=porta, portb=portb) self.get_elements().append(connection) return connection def remove_element(self, element): """ Remove the element from the list of elements. If the element is a port, remove the whole block. If the element is a block, remove its connections. If the element is a connection, just remove the connection. """ if element not in self.get_elements(): return #found a port, set to parent signal block if element.is_port(): element = element.get_parent() #remove block, remove all involved connections if element.is_block(): for port in element.get_ports(): map(self.remove_element, port.get_connections()) if element.is_connection(): if element.is_bus(): cons_list = [] for i in map(lambda a: a.get_connections(), element.get_source().get_associated_ports()): cons_list.extend(i); map(self.remove_element, cons_list); self.get_elements().remove(element) def evaluate(self, expr): """ Evaluate the expression. Args: expr: the string expression @throw NotImplementedError """ raise NotImplementedError ############################################## ## Import/Export Methods ############################################## def export_data(self): """ Export this flow graph to nested data. Export all block and connection data. Returns: a nested data odict """ import time n = odict() n['timestamp'] = time.ctime() n['block'] = [block.export_data() for block in self.get_blocks()] n['connection'] = [connection.export_data() for connection in self.get_connections()] return odict({'flow_graph': n}) def import_data(self, n=None): """ Import blocks and connections into this flow graph. Clear this flowgraph of all previous blocks and connections. Any blocks or connections in error will be ignored. Args: n: the nested data odict """ #remove previous elements self._elements = list() #use blank data if none provided fg_n = n and n.find('flow_graph') or odict() blocks_n = fg_n.findall('block') connections_n = fg_n.findall('connection') #create option block self._options_block = self.get_parent().get_new_block(self, 'options') #build the blocks for block_n in blocks_n: key = block_n.find('key') if key == 'options': block = self._options_block else: block = self.get_new_block(key) #only load the block when the block key was valid if block: block.import_data(block_n) else: Messages.send_error_load('Block key "%s" not found in %s'%(key, self.get_parent())) #build the connections for connection_n in connections_n: #try to make the connection try: #get the block ids source_block_id = connection_n.find('source_block_id') sink_block_id = connection_n.find('sink_block_id') #get the port keys source_key = connection_n.find('source_key') sink_key = connection_n.find('sink_key') #verify the blocks block_ids = map(lambda b: b.get_id(), self.get_blocks()) if source_block_id not in block_ids: raise LookupError('source block id "%s" not in block ids'%source_block_id) if sink_block_id not in block_ids: raise LookupError('sink block id "%s" not in block ids'%sink_block_id) #get the blocks source_block = self.get_block(source_block_id) sink_block = self.get_block(sink_block_id) #verify the ports if source_key not in source_block.get_source_keys(): raise LookupError('source key "%s" not in source block keys'%source_key) if sink_key not in sink_block.get_sink_keys(): raise LookupError('sink key "%s" not in sink block keys'%sink_key) #get the ports source = source_block.get_source(source_key) sink = sink_block.get_sink(sink_key) #build the connection self.connect(source, sink) except LookupError, e: Messages.send_error_load( 'Connection between %s(%s) and %s(%s) could not be made.\n\t%s'%( source_block_id, source_key, sink_block_id, sink_key, e ) ) self.rewrite() #global rewrite gnuradio-3.7.2.1/grc/base/odict.py0000664000175000017500000000636612207702530016476 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from UserDict import DictMixin class odict(DictMixin): def __init__(self, d={}): self._keys = list(d.keys()) self._data = dict(d.copy()) def __setitem__(self, key, value): if key not in self._data: self._keys.append(key) self._data[key] = value def __getitem__(self, key): return self._data[key] def __delitem__(self, key): del self._data[key] self._keys.remove(key) def keys(self): return list(self._keys) def copy(self): copy_dict = odict() copy_dict._data = self._data.copy() copy_dict._keys = list(self._keys) return copy_dict def insert_after(self, pos_key, key, val): """ Insert the new key, value entry after the entry given by the position key. If the positional key is None, insert at the end. Args: pos_key: the positional key key: the key for the new entry val: the value for the new entry """ index = (pos_key is None) and len(self._keys) or self._keys.index(pos_key) if key in self._keys: raise KeyError('Cannot insert, key "%s" already exists'%str(key)) self._keys.insert(index+1, key) self._data[key] = val def insert_before(self, pos_key, key, val): """ Insert the new key, value entry before the entry given by the position key. If the positional key is None, insert at the begining. Args: pos_key: the positional key key: the key for the new entry val: the value for the new entry """ index = (pos_key is not None) and self._keys.index(pos_key) or 0 if key in self._keys: raise KeyError('Cannot insert, key "%s" already exists'%str(key)) self._keys.insert(index, key) self._data[key] = val def find(self, key): """ Get the value for this key if exists. Args: key: the key to search for Returns: the value or None """ if self.has_key(key): return self[key] return None def findall(self, key): """ Get a list of values for this key. Args: key: the key to search for Returns: a list of values or empty list """ obj = self.find(key) if obj is None: obj = list() if isinstance(obj, list): return obj return [obj] gnuradio-3.7.2.1/grc/base/flow_graph.dtd0000664000175000017500000000264412207702530017642 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/base/__init__.py0000644000175000017500000000144611700377701017130 0ustar jcorganjcorgan""" Copyright 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from odict import odict gnuradio-3.7.2.1/grc/base/Block.py0000664000175000017500000003704212237515112016422 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from . import odict from Element import Element from Cheetah.Template import Template from UserDict import UserDict from .. gui import Actions class TemplateArg(UserDict): """ A cheetah template argument created from a param. The str of this class evaluates to the param's to code method. The use of this class as a dictionary (enum only) will reveal the enum opts. The __call__ or () method can return the param evaluated to a raw python data type. """ def __init__(self, param): UserDict.__init__(self) self._param = param if param.is_enum(): for key in param.get_opt_keys(): self[key] = str(param.get_opt(key)) def __str__(self): return str(self._param.to_code()) def __call__(self): return self._param.get_evaluated() def _get_keys(lst): return [elem.get_key() for elem in lst] def _get_elem(lst, key): try: return lst[_get_keys(lst).index(key)] except ValueError: raise ValueError, 'Key "%s" not found in %s.'%(key, _get_keys(lst)) class Block(Element): def __init__(self, flow_graph, n): """ Make a new block from nested data. Args: flow: graph the parent element n: the nested odict Returns: block a new block """ #build the block Element.__init__(self, flow_graph) #grab the data params = n.findall('param') sources = n.findall('source') sinks = n.findall('sink') self._name = n.find('name') self._key = n.find('key') self._category = n.find('category') or '' self._grc_source = n.find('grc_source') or '' self._block_wrapper_path = n.find('block_wrapper_path') self._bussify_sink = n.find('bus_sink') self._bussify_source = n.find('bus_source') #create the param objects self._params = list() #add the id param self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'ID', 'key': 'id', 'type': 'id', }) )) self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'Enabled', 'key': '_enabled', 'type': 'raw', 'value': 'True', 'hide': 'all', }) )) for param in map(lambda n: self.get_parent().get_parent().Param(block=self, n=n), params): key = param.get_key() #test against repeated keys if key in self.get_param_keys(): raise Exception, 'Key "%s" already exists in params'%key #store the param self.get_params().append(param) #create the source objects self._sources = list() for source in map(lambda n: self.get_parent().get_parent().Port(block=self, n=n, dir='source'), sources): key = source.get_key() #test against repeated keys if key in self.get_source_keys(): raise Exception, 'Key "%s" already exists in sources'%key #store the port self.get_sources().append(source) self.back_ofthe_bus(self.get_sources()) #create the sink objects self._sinks = list() for sink in map(lambda n: self.get_parent().get_parent().Port(block=self, n=n, dir='sink'), sinks): key = sink.get_key() #test against repeated keys if key in self.get_sink_keys(): raise Exception, 'Key "%s" already exists in sinks'%key #store the port self.get_sinks().append(sink) self.back_ofthe_bus(self.get_sinks()) self.current_bus_structure = {'source':'','sink':''}; # Virtual source/sink and pad source/sink blocks are # indistinguishable from normal GR blocks. Make explicit # checks for them here since they have no work function or # buffers to manage. is_not_virtual_or_pad = ((self._key != "virtual_source") \ and (self._key != "virtual_sink") \ and (self._key != "pad_source") \ and (self._key != "pad_sink")) if (len(sources) or len(sinks)) and is_not_virtual_or_pad: self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({'name': 'Core Affinity', 'key': 'affinity', 'type': 'int_vector', 'hide': 'part', }) )) if len(sources) and is_not_virtual_or_pad: self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({'name': 'Min Output Buffer', 'key': 'minoutbuf', 'type': 'int', 'hide': 'part', 'value': '0' }) )) self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({'name': 'Max Output Buffer', 'key': 'maxoutbuf', 'type': 'int', 'hide': 'part', 'value': '0' }) )) def back_ofthe_bus(self, portlist): portlist.sort(key=lambda a: a.get_type() == 'bus'); def filter_bus_port(self, ports): buslist = [i for i in ports if i.get_type() == 'bus']; if len(buslist) == 0: return ports; else: return buslist; def get_enabled(self): """ Get the enabled state of the block. Returns: true for enabled """ try: return eval(self.get_param('_enabled').get_value()) except: return True def set_enabled(self, enabled): """ Set the enabled state of the block. Args: enabled: true for enabled """ self.get_param('_enabled').set_value(str(enabled)) def __str__(self): return 'Block - %s - %s(%s)'%(self.get_id(), self.get_name(), self.get_key()) def get_id(self): return self.get_param('id').get_value() def is_block(self): return True def get_name(self): return self._name def get_key(self): return self._key def get_category(self): return self._category def set_category(self, cat): self._category = cat def get_doc(self): return '' def get_ports(self): return self.get_sources() + self.get_sinks() def get_ports_gui(self): return self.filter_bus_port(self.get_sources()) + self.filter_bus_port(self.get_sinks()); def get_children(self): return self.get_ports() + self.get_params() def get_children_gui(self): return self.get_ports_gui() + self.get_params() def get_block_wrapper_path(self): return self._block_wrapper_path ############################################## # Access Params ############################################## def get_param_keys(self): return _get_keys(self._params) def get_param(self, key): return _get_elem(self._params, key) def get_params(self): return self._params def has_param(self, key): try: _get_elem(self._params, key); return True; except: return False; ############################################## # Access Sinks ############################################## def get_sink_keys(self): return _get_keys(self._sinks) def get_sink(self, key): return _get_elem(self._sinks, key) def get_sinks(self): return self._sinks def get_sinks_gui(self): return self.filter_bus_port(self.get_sinks()) ############################################## # Access Sources ############################################## def get_source_keys(self): return _get_keys(self._sources) def get_source(self, key): return _get_elem(self._sources, key) def get_sources(self): return self._sources def get_sources_gui(self): return self.filter_bus_port(self.get_sources()); def get_connections(self): return sum([port.get_connections() for port in self.get_ports()], []) def resolve_dependencies(self, tmpl): """ Resolve a paramater dependency with cheetah templates. Args: tmpl: the string with dependencies Returns: the resolved value """ tmpl = str(tmpl) if '$' not in tmpl: return tmpl n = dict((p.get_key(), TemplateArg(p)) for p in self.get_params()) try: return str(Template(tmpl, n)) except Exception, e: return "-------->\n%s: %s\n<--------"%(e, tmpl) ############################################## # Controller Modify ############################################## def type_controller_modify(self, direction): """ Change the type controller. Args: direction: +1 or -1 Returns: true for change """ changed = False type_param = None for param in filter(lambda p: p.is_enum(), self.get_params()): children = self.get_ports() + self.get_params() #priority to the type controller if param.get_key() in ' '.join(map(lambda p: p._type, children)): type_param = param #use param if type param is unset if not type_param: type_param = param if type_param: #try to increment the enum by direction try: keys = type_param.get_option_keys() old_index = keys.index(type_param.get_value()) new_index = (old_index + direction + len(keys))%len(keys) type_param.set_value(keys[new_index]) changed = True except: pass return changed def port_controller_modify(self, direction): """ Change the port controller. Args: direction: +1 or -1 Returns: true for change """ return False def form_bus_structure(self, direc): if direc == 'source': get_p = self.get_sources; get_p_gui = self.get_sources_gui; bus_structure = self.get_bus_structure('source'); else: get_p = self.get_sinks; get_p_gui = self.get_sinks_gui bus_structure = self.get_bus_structure('sink'); struct = [range(len(get_p()))]; if True in map(lambda a: isinstance(a.get_nports(), int), get_p()): structlet = []; last = 0; for j in [i.get_nports() for i in get_p() if isinstance(i.get_nports(), int)]: structlet.extend(map(lambda a: a+last, range(j))); last = structlet[-1] + 1; struct = [structlet]; if bus_structure: struct = bus_structure self.current_bus_structure[direc] = struct; return struct def bussify(self, n, direc): if direc == 'source': get_p = self.get_sources; get_p_gui = self.get_sources_gui; bus_structure = self.get_bus_structure('source'); else: get_p = self.get_sinks; get_p_gui = self.get_sinks_gui bus_structure = self.get_bus_structure('sink'); for elt in get_p(): for connect in elt.get_connections(): self.get_parent().remove_element(connect); if (not 'bus' in map(lambda a: a.get_type(), get_p())) and len(get_p()) > 0: struct = self.form_bus_structure(direc); self.current_bus_structure[direc] = struct; if get_p()[0].get_nports(): n['nports'] = str(1); for i in range(len(struct)): n['key'] = str(len(get_p())); n = odict(n); port = self.get_parent().get_parent().Port(block=self, n=n, dir=direc); get_p().append(port); elif 'bus' in map(lambda a: a.get_type(), get_p()): for elt in get_p_gui(): get_p().remove(elt); self.current_bus_structure[direc] = '' ############################################## ## Import/Export Methods ############################################## def export_data(self): """ Export this block's params to nested data. Returns: a nested data odict """ n = odict() n['key'] = self.get_key() n['param'] = map(lambda p: p.export_data(), self.get_params()) if 'bus' in map(lambda a: a.get_type(), self.get_sinks()): n['bus_sink'] = str(1); if 'bus' in map(lambda a: a.get_type(), self.get_sources()): n['bus_source'] = str(1); return n def import_data(self, n): """ Import this block's params from nested data. Any param keys that do not exist will be ignored. Since params can be dynamically created based another param, call rewrite, and repeat the load until the params stick. This call to rewrite will also create any dynamic ports that are needed for the connections creation phase. Args: n: the nested data odict """ get_hash = lambda: hash(tuple(map(hash, self.get_params()))) my_hash = 0 while get_hash() != my_hash: params_n = n.findall('param') for param_n in params_n: key = param_n.find('key') value = param_n.find('value') #the key must exist in this block's params if key in self.get_param_keys(): self.get_param(key).set_value(value) #store hash and call rewrite my_hash = get_hash() self.rewrite() bussinks = n.findall('bus_sink'); if len(bussinks) > 0 and not self._bussify_sink: self.bussify({'name':'bus','type':'bus'}, 'sink') elif len(bussinks) > 0: self.bussify({'name':'bus','type':'bus'}, 'sink') self.bussify({'name':'bus','type':'bus'}, 'sink') bussrcs = n.findall('bus_source'); if len(bussrcs) > 0 and not self._bussify_source: self.bussify({'name':'bus','type':'bus'}, 'source') elif len(bussrcs) > 0: self.bussify({'name':'bus','type':'bus'}, 'source') self.bussify({'name':'bus','type':'bus'}, 'source') gnuradio-3.7.2.1/grc/python/0000755000175000017500000000000012237515112015415 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/python/Platform.py0000664000175000017500000000460412207702530017560 0ustar jcorganjcorgan__doc__ = """ Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os from gnuradio import gr from .. base.Platform import Platform as _Platform from .. gui.Platform import Platform as _GUIPlatform from FlowGraph import FlowGraph as _FlowGraph from Connection import Connection as _Connection from Block import Block as _Block from Port import Port as _Port from Param import Param as _Param from Generator import Generator from Constants import \ HIER_BLOCKS_LIB_DIR, BLOCK_DTD, \ DEFAULT_FLOW_GRAPH, BLOCKS_DIRS import Constants COLORS = [(name, color) for name, key, sizeof, color in Constants.CORE_TYPES] class Platform(_Platform, _GUIPlatform): def __init__(self): """ Make a platform for gnuradio. """ #ensure hier dir if not os.path.exists(HIER_BLOCKS_LIB_DIR): os.mkdir(HIER_BLOCKS_LIB_DIR) #convert block paths to absolute paths block_paths = set(map(os.path.abspath, BLOCKS_DIRS)) #init _Platform.__init__( self, name='GNU Radio Companion', version=gr.version(), key='grc', license=__doc__.strip(), website='http://gnuradio.org/redmine/wiki/gnuradio/GNURadioCompanion', block_paths=block_paths, block_dtd=BLOCK_DTD, default_flow_graph=DEFAULT_FLOW_GRAPH, generator=Generator, colors=COLORS, ) _GUIPlatform.__init__(self) ############################################## # Constructors ############################################## FlowGraph = _FlowGraph Connection = _Connection Block = _Block Port = _Port Param = _Param gnuradio-3.7.2.1/grc/python/Port.py0000664000175000017500000002136012207702530016716 0ustar jcorganjcorgan""" Copyright 2008-2012 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from .. base.Port import Port as _Port from .. gui.Port import Port as _GUIPort import Constants def _get_source_from_virtual_sink_port(vsp): """ Resolve the source port that is connected to the given virtual sink port. Use the get source from virtual source to recursively resolve subsequent ports. """ try: return _get_source_from_virtual_source_port( vsp.get_enabled_connections()[0].get_source()) except: raise Exception, 'Could not resolve source for virtual sink port %s'%vsp def _get_source_from_virtual_source_port(vsp, traversed=[]): """ Recursively resolve source ports over the virtual connections. Keep track of traversed sources to avoid recursive loops. """ if not vsp.get_parent().is_virtual_source(): return vsp if vsp in traversed: raise Exception, 'Loop found when resolving virtual source %s'%vsp try: return _get_source_from_virtual_source_port( _get_source_from_virtual_sink_port( filter(#get all virtual sinks with a matching stream id lambda vs: vs.get_param('stream_id').get_value() == vsp.get_parent().get_param('stream_id').get_value(), filter(#get all enabled blocks that are also virtual sinks lambda b: b.is_virtual_sink(), vsp.get_parent().get_parent().get_enabled_blocks(), ), )[0].get_sinks()[0] ), traversed + [vsp], ) except: raise Exception, 'Could not resolve source for virtual source port %s'%vsp def _get_sink_from_virtual_source_port(vsp): """ Resolve the sink port that is connected to the given virtual source port. Use the get sink from virtual sink to recursively resolve subsequent ports. """ try: return _get_sink_from_virtual_sink_port( vsp.get_enabled_connections()[0].get_sink()) # Could have many connections, but use first except: raise Exception, 'Could not resolve source for virtual source port %s'%vsp def _get_sink_from_virtual_sink_port(vsp, traversed=[]): """ Recursively resolve sink ports over the virtual connections. Keep track of traversed sinks to avoid recursive loops. """ if not vsp.get_parent().is_virtual_sink(): return vsp if vsp in traversed: raise Exception, 'Loop found when resolving virtual sink %s'%vsp try: return _get_sink_from_virtual_sink_port( _get_sink_from_virtual_source_port( filter(#get all virtual source with a matching stream id lambda vs: vs.get_param('stream_id').get_value() == vsp.get_parent().get_param('stream_id').get_value(), filter(#get all enabled blocks that are also virtual sinks lambda b: b.is_virtual_source(), vsp.get_parent().get_parent().get_enabled_blocks(), ), )[0].get_sources()[0] ), traversed + [vsp], ) except: raise Exception, 'Could not resolve source for virtual sink port %s'%vsp class Port(_Port, _GUIPort): def __init__(self, block, n, dir): """ Make a new port from nested data. Args: block: the parent element n: the nested odict dir: the direction """ self._n = n if n['type'] == 'msg': n['key'] = 'msg' if n['type'] == 'message': n['key'] = n['name'] if dir == 'source' and not n.find('key'): n['key'] = str(block._source_count) block._source_count += 1 if dir == 'sink' and not n.find('key'): n['key'] = str(block._sink_count) block._sink_count += 1 #build the port _Port.__init__( self, block=block, n=n, dir=dir, ) _GUIPort.__init__(self) self._nports = n.find('nports') or '' self._vlen = n.find('vlen') or '' self._optional = bool(n.find('optional')) def get_types(self): return Constants.TYPE_TO_SIZEOF.keys() def is_type_empty(self): return not self._n['type'] def validate(self): _Port.validate(self) if not self.get_enabled_connections() and not self.get_optional(): self.add_error_message('Port is not connected.') if not self.is_source() and (not self.get_type() == "message") and len(self.get_enabled_connections()) > 1: self.add_error_message('Port has too many connections.') #message port logic if self.get_type() == 'msg': if self.get_nports(): self.add_error_message('A port of type "msg" cannot have "nports" set.') if self.get_vlen() != 1: self.add_error_message('A port of type "msg" must have a "vlen" of 1.') def rewrite(self): """ Handle the port cloning for virtual blocks. """ _Port.rewrite(self) if self.is_type_empty(): try: #clone type and vlen source = self.resolve_empty_type() self._type = str(source.get_type()) self._vlen = str(source.get_vlen()) except: #reset type and vlen self._type = '' self._vlen = '' def resolve_virtual_source(self): if self.get_parent().is_virtual_sink(): return _get_source_from_virtual_sink_port(self) if self.get_parent().is_virtual_source(): return _get_source_from_virtual_source_port(self) def resolve_empty_type(self): if self.is_sink(): try: src = _get_source_from_virtual_sink_port(self) if not src.is_type_empty(): return src except: pass sink = _get_sink_from_virtual_sink_port(self) if not sink.is_type_empty(): return sink if self.is_source(): try: src = _get_source_from_virtual_source_port(self) if not src.is_type_empty(): return src except: pass sink = _get_sink_from_virtual_source_port(self) if not sink.is_type_empty(): return sink def get_vlen(self): """ Get the vector length. If the evaluation of vlen cannot be cast to an integer, return 1. Returns: the vector length or 1 """ vlen = self.get_parent().resolve_dependencies(self._vlen) try: return int(self.get_parent().get_parent().evaluate(vlen)) except: return 1 def get_nports(self): """ Get the number of ports. If already blank, return a blank If the evaluation of nports cannot be cast to an integer, return 1. Returns: the number of ports or 1 """ nports = self.get_parent().resolve_dependencies(self._nports) #return blank if nports is blank if not nports: return '' try: nports = int(self.get_parent().get_parent().evaluate(nports)) if 0 < nports: return nports except: return 1 def get_optional(self): return bool(self._optional) def get_color(self): """ Get the color that represents this port's type. Codes differ for ports where the vec length is 1 or greater than 1. Returns: a hex color code. """ try: color = Constants.TYPE_TO_COLOR[self.get_type()] vlen = self.get_vlen() if vlen == 1: return color color_val = int(color[1:], 16) r = (color_val >> 16) & 0xff g = (color_val >> 8) & 0xff b = (color_val >> 0) & 0xff dark = (0, 0, 30, 50, 70)[min(4, vlen)] r = max(r-dark, 0) g = max(g-dark, 0) b = max(b-dark, 0) return '#%.2x%.2x%.2x'%(r, g, b) except: return _Port.get_color(self) def copy(self, new_key=None): n = self._n.copy() #remove nports from the key so the copy cannot be a duplicator if n.has_key('nports'): n.pop('nports') if new_key: n['key'] = new_key return self.__class__(self.get_parent(), n, self._dir) gnuradio-3.7.2.1/grc/python/CMakeLists.txt0000644000175000017500000000242311744612271020164 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## GR_PYTHON_INSTALL(FILES convert_hier.py expr_utils.py extract_docs.py Block.py Connection.py Constants.py FlowGraph.py Generator.py Param.py Platform.py Port.py __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/grc/python COMPONENT "grc" ) install(FILES block.dtd default_flow_graph.grc flow_graph.tmpl DESTINATION ${GR_PYTHON_DIR}/gnuradio/grc/python COMPONENT "grc" ) gnuradio-3.7.2.1/grc/python/Constants.py0000664000175000017500000000647612207702530017761 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os import stat from gnuradio import gr _gr_prefs = gr.prefs() #setup paths PATH_SEP = {'/':':', '\\':';'}[os.path.sep] HIER_BLOCKS_LIB_DIR = os.path.join(os.path.expanduser('~'), '.grc_gnuradio') BLOCKS_DIRS = filter( #filter blank strings lambda x: x, PATH_SEP.join([ os.environ.get('GRC_BLOCKS_PATH', ''), _gr_prefs.get_string('grc', 'local_blocks_path', ''), _gr_prefs.get_string('grc', 'global_blocks_path', ''), ]).split(PATH_SEP), ) + [HIER_BLOCKS_LIB_DIR] #file creation modes TOP_BLOCK_FILE_MODE = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH HIER_BLOCK_FILE_MODE = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH #data files DATA_DIR = os.path.dirname(__file__) FLOW_GRAPH_TEMPLATE = os.path.join(DATA_DIR, 'flow_graph.tmpl') BLOCK_DTD = os.path.join(DATA_DIR, 'block.dtd') DEFAULT_FLOW_GRAPH = os.path.join(DATA_DIR, 'default_flow_graph.grc') CORE_TYPES = ( #name, key, sizeof, color ('Complex Float 64', 'fc64', 16, '#CC8C69'), ('Complex Float 32', 'fc32', 8, '#3399FF'), ('Complex Integer 64', 'sc64', 16, '#66CC00'), ('Complex Integer 32', 'sc32', 8, '#33cc66'), ('Complex Integer 16', 'sc16', 4, '#cccc00'), ('Complex Integer 8', 'sc8', 2, '#cc00cc'), ('Float 64', 'f64', 8, '#66CCCC'), ('Float 32', 'f32', 4, '#FF8C69'), ('Integer 64', 's64', 8, '#99FF33'), ('Integer 32', 's32', 4, '#00FF99'), ('Integer 16', 's16', 2, '#FFFF66'), ('Integer 8', 's8', 1, '#FF66FF'), ('Message Queue', 'msg', 0, '#777777'), ('Async Message', 'message', 0, '#C0C0C0'), ('Bus Connection', 'bus', 0, '#FFFFFF'), ('Wildcard', '', 0, '#FFFFFF'), ) ALIAS_TYPES = { 'complex' : (8, '#3399FF'), 'float' : (4, '#FF8C69'), 'int' : (4, '#00FF99'), 'short' : (2, '#FFFF66'), 'byte' : (1, '#FF66FF'), } TYPE_TO_COLOR = dict() TYPE_TO_SIZEOF = dict() for name, key, sizeof, color in CORE_TYPES: TYPE_TO_COLOR[key] = color TYPE_TO_SIZEOF[key] = sizeof for key, (sizeof, color) in ALIAS_TYPES.iteritems(): TYPE_TO_COLOR[key] = color TYPE_TO_SIZEOF[key] = sizeof #coloring COMPLEX_COLOR_SPEC = '#3399FF' FLOAT_COLOR_SPEC = '#FF8C69' INT_COLOR_SPEC = '#00FF99' SHORT_COLOR_SPEC = '#FFFF66' BYTE_COLOR_SPEC = '#FF66FF' COMPLEX_VECTOR_COLOR_SPEC = '#3399AA' FLOAT_VECTOR_COLOR_SPEC = '#CC8C69' INT_VECTOR_COLOR_SPEC = '#00CC99' SHORT_VECTOR_COLOR_SPEC = '#CCCC33' BYTE_VECTOR_COLOR_SPEC = '#CC66CC' ID_COLOR_SPEC = '#DDDDDD' WILDCARD_COLOR_SPEC = '#FFFFFF' MSG_COLOR_SPEC = '#777777' gnuradio-3.7.2.1/grc/python/expr_utils.py0000664000175000017500000001255612207702530020177 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import string VAR_CHARS = string.letters + string.digits + '_' class graph(object): """ Simple graph structure held in a dictionary. """ def __init__(self): self._graph = dict() def __str__(self): return str(self._graph) def add_node(self, node_key): if self._graph.has_key(node_key): return self._graph[node_key] = set() def remove_node(self, node_key): if not self._graph.has_key(node_key): return for edges in self._graph.values(): if node_key in edges: edges.remove(node_key) self._graph.pop(node_key) def add_edge(self, src_node_key, dest_node_key): self._graph[src_node_key].add(dest_node_key) def remove_edge(self, src_node_key, dest_node_key): self._graph[src_node_key].remove(dest_node_key) def get_nodes(self): return self._graph.keys() def get_edges(self, node_key): return self._graph[node_key] def expr_split(expr): """ Split up an expression by non alphanumeric characters, including underscore. Leave strings in-tact. #TODO ignore escaped quotes, use raw strings. Args: expr: an expression string Returns: a list of string tokens that form expr """ toks = list() tok = '' quote = '' for char in expr: if quote or char in VAR_CHARS: if char == quote: quote = '' tok += char elif char in ("'", '"'): toks.append(tok) tok = char quote = char else: toks.append(tok) toks.append(char) tok = '' toks.append(tok) return filter(lambda t: t, toks) def expr_replace(expr, replace_dict): """ Search for vars in the expression and add the prepend. Args: expr: an expression string replace_dict: a dict of find:replace Returns: a new expression with the prepend """ expr_splits = expr_split(expr) for i, es in enumerate(expr_splits): if es in replace_dict.keys(): expr_splits[i] = replace_dict[es] return ''.join(expr_splits) def get_variable_dependencies(expr, vars): """ Return a set of variables used in this expression. Args: expr: an expression string vars: a list of variable names Returns: a subset of vars used in the expression """ expr_toks = expr_split(expr) return set(filter(lambda v: v in expr_toks, vars)) def get_graph(exprs): """ Get a graph representing the variable dependencies Args: exprs: a mapping of variable name to expression Returns: a graph of variable deps """ vars = exprs.keys() #get dependencies for each expression, load into graph var_graph = graph() for var in vars: var_graph.add_node(var) for var, expr in exprs.iteritems(): for dep in get_variable_dependencies(expr, vars): if dep != var: var_graph.add_edge(dep, var) return var_graph def sort_variables(exprs): """ Get a list of variables in order of dependencies. Args: exprs: a mapping of variable name to expression Returns: a list of variable names @throws Exception circular dependencies """ var_graph = get_graph(exprs) sorted_vars = list() #determine dependency order while var_graph.get_nodes(): #get a list of nodes with no edges indep_vars = filter(lambda var: not var_graph.get_edges(var), var_graph.get_nodes()) if not indep_vars: raise Exception('circular dependency caught in sort_variables') #add the indep vars to the end of the list sorted_vars.extend(sorted(indep_vars)) #remove each edge-less node from the graph for var in indep_vars: var_graph.remove_node(var) return reversed(sorted_vars) def sort_objects(objects, get_id, get_expr): """ Sort a list of objects according to their expressions. Args: objects: the list of objects to sort get_id: the function to extract an id from the object get_expr: the function to extract an expression from the object Returns: a list of sorted objects """ id2obj = dict([(get_id(obj), obj) for obj in objects]) #map obj id to expression code id2expr = dict([(get_id(obj), get_expr(obj)) for obj in objects]) #sort according to dependency sorted_ids = sort_variables(id2expr) #return list of sorted objects return [id2obj[id] for id in sorted_ids] if __name__ == '__main__': for i in sort_variables({'x':'1', 'y':'x+1', 'a':'x+y', 'b':'y+1', 'c':'a+b+x+y'}): print i gnuradio-3.7.2.1/grc/python/convert_hier.py0000664000175000017500000001100612207702530020455 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Constants import BLOCK_DTD from .. base import ParseXML from .. base import odict def convert_hier(flow_graph, python_file): #extract info from the flow graph input_sigs = flow_graph.get_io_signaturev('in') output_sigs = flow_graph.get_io_signaturev('out') input_msgp = flow_graph.get_msg_pad_sources(); output_msgp = flow_graph.get_msg_pad_sinks(); parameters = flow_graph.get_parameters() bussink = flow_graph.get_bussink() bussrc = flow_graph.get_bussrc() bus_struct_sink = flow_graph.get_bus_structure_sink() bus_struct_src = flow_graph.get_bus_structure_src() block_key = flow_graph.get_option('id') block_name = flow_graph.get_option('title') or flow_graph.get_option('id').replace('_', ' ').title() block_category = flow_graph.get_option('category') block_desc = flow_graph.get_option('description') block_author = flow_graph.get_option('author') #build the nested data block_n = odict() block_n['name'] = block_name block_n['key'] = block_key block_n['category'] = block_category block_n['import'] = 'execfile("%s")'%python_file #make data if parameters: block_n['make'] = '%s(\n %s,\n)'%( block_key, ',\n '.join(['%s=$%s'%(param.get_id(), param.get_id()) for param in parameters]), ) else: block_n['make'] = '%s()'%block_key #callback data block_n['callback'] = ['set_%s($%s)'%(param.get_id(), param.get_id()) for param in parameters] #param data params_n = list() for param in parameters: param_n = odict() param_n['name'] = param.get_param('label').get_value() or param.get_id() param_n['key'] = param.get_id() param_n['value'] = param.get_param('value').get_value() param_n['type'] = 'raw' params_n.append(param_n) block_n['param'] = params_n #sink data stream ports if bussink: block_n['bus_sink'] = '1'; if bussrc: block_n['bus_source'] = '1'; block_n['sink'] = list() for input_sig in input_sigs: sink_n = odict() sink_n['name'] = input_sig['label'] sink_n['type'] = input_sig['type'] sink_n['vlen'] = input_sig['vlen'] if input_sig['optional']: sink_n['optional'] = '1' block_n['sink'].append(sink_n) #sink data msg ports for input_sig in input_msgp: sink_n = odict() sink_n['name'] = input_sig.get_param("label").get_value(); sink_n['type'] = "message" sink_n['optional'] = input_sig.get_param("optional").get_value(); block_n['sink'].append(sink_n) #source data stream ports block_n['source'] = list() if bus_struct_sink: block_n['bus_structure_sink'] = bus_struct_sink[0].get_param('struct').get_value(); if bus_struct_src: block_n['bus_structure_source'] = bus_struct_src[0].get_param('struct').get_value(); for output_sig in output_sigs: source_n = odict() source_n['name'] = output_sig['label'] source_n['type'] = output_sig['type'] source_n['vlen'] = output_sig['vlen'] if output_sig['optional']: source_n['optional'] = '1' block_n['source'].append(source_n) #source data msg ports for output_sig in output_msgp: source_n = odict() source_n['name'] = output_sig.get_param("label").get_value(); source_n['type'] = "message" source_n['optional'] = output_sig.get_param("optional").get_value(); block_n['source'].append(source_n) #doc data block_n['doc'] = "%s\n%s\n%s"%(block_author, block_desc, python_file) block_n['grc_source'] = "%s"%(flow_graph.grc_file_path) #write the block_n to file xml_file = python_file + '.xml' ParseXML.to_file({'block': block_n}, xml_file) ParseXML.validate_dtd(xml_file, BLOCK_DTD) gnuradio-3.7.2.1/grc/python/Param.py0000664000175000017500000005166012207702530017040 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from .. base.Param import Param as _Param from .. gui.Param import Param as _GUIParam from .. gui.Param import EntryParam import Constants import numpy import os import pygtk pygtk.require('2.0') import gtk from gnuradio import eng_notation import re from gnuradio import gr _check_id_matcher = re.compile('^[a-z|A-Z]\w*$') _show_id_matcher = re.compile('^(variable\w*|parameter|options|notebook)$') class FileParam(EntryParam): """Provide an entry box for filename and a button to browse for a file.""" def __init__(self, *args, **kwargs): EntryParam.__init__(self, *args, **kwargs) input = gtk.Button('...') input.connect('clicked', self._handle_clicked) self.pack_start(input, False) def _handle_clicked(self, widget=None): """ If the button was clicked, open a file dialog in open/save format. Replace the text in the entry with the new filename from the file dialog. """ #get the paths file_path = self.param.is_valid() and self.param.get_evaluated() or '' (dirname, basename) = os.path.isfile(file_path) and os.path.split(file_path) or (file_path, '') if not os.path.exists(dirname): dirname = os.getcwd() #fix bad paths #build the dialog if self.param.get_type() == 'file_open': file_dialog = gtk.FileChooserDialog('Open a Data File...', None, gtk.FILE_CHOOSER_ACTION_OPEN, ('gtk-cancel',gtk.RESPONSE_CANCEL,'gtk-open',gtk.RESPONSE_OK)) elif self.param.get_type() == 'file_save': file_dialog = gtk.FileChooserDialog('Save a Data File...', None, gtk.FILE_CHOOSER_ACTION_SAVE, ('gtk-cancel',gtk.RESPONSE_CANCEL, 'gtk-save',gtk.RESPONSE_OK)) file_dialog.set_do_overwrite_confirmation(True) file_dialog.set_current_name(basename) #show the current filename file_dialog.set_current_folder(dirname) #current directory file_dialog.set_select_multiple(False) file_dialog.set_local_only(True) if gtk.RESPONSE_OK == file_dialog.run(): #run the dialog file_path = file_dialog.get_filename() #get the file path self._input.set_text(file_path) self._handle_changed() file_dialog.destroy() #destroy the dialog #blacklist certain ids, its not complete, but should help import __builtin__ ID_BLACKLIST = ['self', 'options', 'gr', 'blks2', 'wxgui', 'wx', 'math', 'forms', 'firdes'] + \ filter(lambda x: not x.startswith('_'), dir(gr.top_block())) + dir(__builtin__) #define types, native python + numpy VECTOR_TYPES = (tuple, list, set, numpy.ndarray) COMPLEX_TYPES = [complex, numpy.complex, numpy.complex64, numpy.complex128] REAL_TYPES = [float, numpy.float, numpy.float32, numpy.float64] INT_TYPES = [int, long, numpy.int, numpy.int8, numpy.int16, numpy.int32, numpy.uint64, numpy.uint, numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64] #cast to tuple for isinstance, concat subtypes COMPLEX_TYPES = tuple(COMPLEX_TYPES + REAL_TYPES + INT_TYPES) REAL_TYPES = tuple(REAL_TYPES + INT_TYPES) INT_TYPES = tuple(INT_TYPES) class Param(_Param, _GUIParam): def __init__(self, **kwargs): _Param.__init__(self, **kwargs) _GUIParam.__init__(self) self._init = False self._hostage_cells = list() def get_types(self): return ( 'raw', 'enum', 'complex', 'real', 'float', 'int', 'complex_vector', 'real_vector', 'float_vector', 'int_vector', 'hex', 'string', 'bool', 'file_open', 'file_save', 'id', 'stream_id', 'grid_pos', 'notebook', 'gui_hint', 'import', ) def __repr__(self): """ Get the repr (nice string format) for this param. Returns: the string representation """ ################################################## # truncate helper method ################################################## def _truncate(string, style=0): max_len = max(27 - len(self.get_name()), 3) if len(string) > max_len: if style < 0: #front truncate string = '...' + string[3-max_len:] elif style == 0: #center truncate string = string[:max_len/2 -3] + '...' + string[-max_len/2:] elif style > 0: #rear truncate string = string[:max_len-3] + '...' return string ################################################## # simple conditions ################################################## if not self.is_valid(): return _truncate(self.get_value()) if self.get_value() in self.get_option_keys(): return self.get_option(self.get_value()).get_name() ################################################## # display logic for numbers ################################################## def num_to_str(num): if isinstance(num, COMPLEX_TYPES): num = complex(num) #cast to python complex if num == 0: return '0' #value is zero elif num.imag == 0: return '%s'%eng_notation.num_to_str(num.real) #value is real elif num.real == 0: return '%sj'%eng_notation.num_to_str(num.imag) #value is imaginary elif num.imag < 0: return '%s-%sj'%(eng_notation.num_to_str(num.real), eng_notation.num_to_str(abs(num.imag))) else: return '%s+%sj'%(eng_notation.num_to_str(num.real), eng_notation.num_to_str(num.imag)) else: return str(num) ################################################## # split up formatting by type ################################################## truncate = 0 #default center truncate e = self.get_evaluated() t = self.get_type() if isinstance(e, bool): return str(e) elif isinstance(e, COMPLEX_TYPES): dt_str = num_to_str(e) elif isinstance(e, VECTOR_TYPES): #vector types if len(e) > 8: dt_str = self.get_value() #large vectors use code truncate = 1 else: dt_str = ', '.join(map(num_to_str, e)) #small vectors use eval elif t in ('file_open', 'file_save'): dt_str = self.get_value() truncate = -1 else: dt_str = str(e) #other types ################################################## # done ################################################## return _truncate(dt_str, truncate) def get_input(self, *args, **kwargs): if self.get_type() in ('file_open', 'file_save'): return FileParam(self, *args, **kwargs) return _GUIParam.get_input(self, *args, **kwargs) def get_color(self): """ Get the color that represents this param's type. Returns: a hex color code. """ try: return { #number types 'complex': Constants.COMPLEX_COLOR_SPEC, 'real': Constants.FLOAT_COLOR_SPEC, 'float': Constants.FLOAT_COLOR_SPEC, 'int': Constants.INT_COLOR_SPEC, #vector types 'complex_vector': Constants.COMPLEX_VECTOR_COLOR_SPEC, 'real_vector': Constants.FLOAT_VECTOR_COLOR_SPEC, 'float_vector': Constants.FLOAT_VECTOR_COLOR_SPEC, 'int_vector': Constants.INT_VECTOR_COLOR_SPEC, #special 'bool': Constants.INT_COLOR_SPEC, 'hex': Constants.INT_COLOR_SPEC, 'string': Constants.BYTE_VECTOR_COLOR_SPEC, 'id': Constants.ID_COLOR_SPEC, 'stream_id': Constants.ID_COLOR_SPEC, 'grid_pos': Constants.INT_VECTOR_COLOR_SPEC, 'notebook': Constants.INT_VECTOR_COLOR_SPEC, 'raw': Constants.WILDCARD_COLOR_SPEC, }[self.get_type()] except: return _Param.get_color(self) def get_hide(self): """ Get the hide value from the base class. Hide the ID parameter for most blocks. Exceptions below. If the parameter controls a port type, vlen, or nports, return part. If the parameter is an empty grid position, return part. These parameters are redundant to display in the flow graph view. Returns: hide the hide property string """ hide = _Param.get_hide(self) if hide: return hide #hide ID in non variable blocks if self.get_key() == 'id' and not _show_id_matcher.match(self.get_parent().get_key()): return 'part' #hide port controllers for type and nports if self.get_key() in ' '.join(map( lambda p: ' '.join([p._type, p._nports]), self.get_parent().get_ports()) ): return 'part' #hide port controllers for vlen, when == 1 if self.get_key() in ' '.join(map( lambda p: p._vlen, self.get_parent().get_ports()) ): try: if int(self.get_evaluated()) == 1: return 'part' except: pass #hide empty grid positions if self.get_key() in ('grid_pos', 'notebook') and not self.get_value(): return 'part' return hide def validate(self): """ Validate the param. A test evaluation is performed """ _Param.validate(self) #checks type self._evaluated = None try: self._evaluated = self.evaluate() except Exception, e: self.add_error_message(str(e)) def get_evaluated(self): return self._evaluated def evaluate(self): """ Evaluate the value. Returns: evaluated type """ self._init = True self._lisitify_flag = False self._stringify_flag = False self._hostage_cells = list() def eval_string(v): try: e = self.get_parent().get_parent().evaluate(v) if isinstance(e, str): return e raise Exception #want to stringify except: self._stringify_flag = True return v t = self.get_type() v = self.get_value() ######################### # Enum Type ######################### if self.is_enum(): return v ######################### # Numeric Types ######################### elif t in ('raw', 'complex', 'real', 'float', 'int', 'hex', 'bool'): #raise exception if python cannot evaluate this value try: e = self.get_parent().get_parent().evaluate(v) except Exception, e: raise Exception, 'Value "%s" cannot be evaluated:\n%s'%(v, e) #raise an exception if the data is invalid if t == 'raw': return e elif t == 'complex': if not isinstance(e, COMPLEX_TYPES): raise Exception, 'Expression "%s" is invalid for type complex.'%str(e) return e elif t == 'real' or t == 'float': if not isinstance(e, REAL_TYPES): raise Exception, 'Expression "%s" is invalid for type float.'%str(e) return e elif t == 'int': if not isinstance(e, INT_TYPES): raise Exception, 'Expression "%s" is invalid for type integer.'%str(e) return e elif t == 'hex': return hex(e) elif t == 'bool': if not isinstance(e, bool): raise Exception, 'Expression "%s" is invalid for type bool.'%str(e) return e else: raise TypeError, 'Type "%s" not handled'%t ######################### # Numeric Vector Types ######################### elif t in ('complex_vector', 'real_vector', 'float_vector', 'int_vector'): if not v: v = '()' #turn a blank string into an empty list, so it will eval #raise exception if python cannot evaluate this value try: e = self.get_parent().get_parent().evaluate(v) except Exception, e: raise Exception, 'Value "%s" cannot be evaluated:\n%s'%(v, e) #raise an exception if the data is invalid if t == 'complex_vector': if not isinstance(e, VECTOR_TYPES): self._lisitify_flag = True e = [e] if not all([isinstance(ei, COMPLEX_TYPES) for ei in e]): raise Exception, 'Expression "%s" is invalid for type complex vector.'%str(e) return e elif t == 'real_vector' or t == 'float_vector': if not isinstance(e, VECTOR_TYPES): self._lisitify_flag = True e = [e] if not all([isinstance(ei, REAL_TYPES) for ei in e]): raise Exception, 'Expression "%s" is invalid for type float vector.'%str(e) return e elif t == 'int_vector': if not isinstance(e, VECTOR_TYPES): self._lisitify_flag = True e = [e] if not all([isinstance(ei, INT_TYPES) for ei in e]): raise Exception, 'Expression "%s" is invalid for type integer vector.'%str(e) return e ######################### # String Types ######################### elif t in ('string', 'file_open', 'file_save'): #do not check if file/directory exists, that is a runtime issue e = eval_string(v) return str(e) ######################### # Unique ID Type ######################### elif t == 'id': #can python use this as a variable? if not _check_id_matcher.match(v): raise Exception, 'ID "%s" must begin with a letter and may contain letters, numbers, and underscores.'%v ids = [param.get_value() for param in self.get_all_params(t)] if ids.count(v) > 1: #id should only appear once, or zero times if block is disabled raise Exception, 'ID "%s" is not unique.'%v if v in ID_BLACKLIST: raise Exception, 'ID "%s" is blacklisted.'%v return v ######################### # Stream ID Type ######################### elif t == 'stream_id': #get a list of all stream ids used in the virtual sinks ids = [param.get_value() for param in filter( lambda p: p.get_parent().is_virtual_sink(), self.get_all_params(t), )] #check that the virtual sink's stream id is unique if self.get_parent().is_virtual_sink(): if ids.count(v) > 1: #id should only appear once, or zero times if block is disabled raise Exception, 'Stream ID "%s" is not unique.'%v #check that the virtual source's steam id is found if self.get_parent().is_virtual_source(): if v not in ids: raise Exception, 'Stream ID "%s" is not found.'%v return v ######################### # GUI Position/Hint ######################### elif t == 'gui_hint': if ':' in v: tab, pos = v.split(':') elif '@' in v: tab, pos = v, '' else: tab, pos = '', v if '@' in tab: tab, index = tab.split('@') else: index = '?' widget_str = ({ (True, True): 'self.%(tab)s_grid_layout_%(index)s.addWidget(%(widget)s, %(pos)s)', (True, False): 'self.%(tab)s_layout_%(index)s.addWidget(%(widget)s)', (False, True): 'self.top_grid_layout.addWidget(%(widget)s, %(pos)s)', (False, False): 'self.top_layout.addWidget(%(widget)s)', }[bool(tab), bool(pos)])%{'tab': tab, 'index': index, 'widget': '%s', 'pos': pos} def gui_hint(ws, w): if 'layout' in w: ws = ws.replace('addWidget', 'addLayout') return ws%w return lambda w: gui_hint(widget_str, w) ######################### # Grid Position Type ######################### elif t == 'grid_pos': if not v: return '' #allow for empty grid pos e = self.get_parent().get_parent().evaluate(v) if not isinstance(e, (list, tuple)) or len(e) != 4 or not all([isinstance(ei, int) for ei in e]): raise Exception, 'A grid position must be a list of 4 integers.' row, col, row_span, col_span = e #check row, col if row < 0 or col < 0: raise Exception, 'Row and column must be non-negative.' #check row span, col span if row_span <= 0 or col_span <= 0: raise Exception, 'Row and column span must be greater than zero.' #get hostage cell parent try: my_parent = self.get_parent().get_param('notebook').evaluate() except: my_parent = '' #calculate hostage cells for r in range(row_span): for c in range(col_span): self._hostage_cells.append((my_parent, (row+r, col+c))) #avoid collisions params = filter(lambda p: p is not self, self.get_all_params('grid_pos')) for param in params: for parent, cell in param._hostage_cells: if (parent, cell) in self._hostage_cells: raise Exception, 'Another graphical element is using parent "%s", cell "%s".'%(str(parent), str(cell)) return e ######################### # Notebook Page Type ######################### elif t == 'notebook': if not v: return '' #allow for empty notebook #get a list of all notebooks notebook_blocks = filter(lambda b: b.get_key() == 'notebook', self.get_parent().get_parent().get_enabled_blocks()) #check for notebook param syntax try: notebook_id, page_index = map(str.strip, v.split(',')) except: raise Exception, 'Bad notebook page format.' #check that the notebook id is valid try: notebook_block = filter(lambda b: b.get_id() == notebook_id, notebook_blocks)[0] except: raise Exception, 'Notebook id "%s" is not an existing notebook id.'%notebook_id #check that page index exists if int(page_index) not in range(len(notebook_block.get_param('labels').evaluate())): raise Exception, 'Page index "%s" is not a valid index number.'%page_index return notebook_id, page_index ######################### # Import Type ######################### elif t == 'import': n = dict() #new namespace try: exec v in n except ImportError: raise Exception, 'Import "%s" failed.'%v except Exception: raise Exception, 'Bad import syntax: "%s".'%v return filter(lambda k: str(k) != '__builtins__', n.keys()) ######################### else: raise TypeError, 'Type "%s" not handled'%t def to_code(self): """ Convert the value to code. For string and list types, check the init flag, call evaluate(). This ensures that evaluate() was called to set the xxxify_flags. Returns: a string representing the code """ v = self.get_value() t = self.get_type() if t in ('string', 'file_open', 'file_save'): #string types if not self._init: self.evaluate() if self._stringify_flag: return '"%s"'%v.replace('"', '\"') else: return v elif t in ('complex_vector', 'real_vector', 'float_vector', 'int_vector'): #vector types if not self._init: self.evaluate() if self._lisitify_flag: return '(%s, )'%v else: return '(%s)'%v else: return v def get_all_params(self, type): """ Get all the params from the flowgraph that have the given type. Args: type: the specified type Returns: a list of params """ return sum([filter(lambda p: p.get_type() == type, block.get_params()) for block in self.get_parent().get_parent().get_enabled_blocks()], []) gnuradio-3.7.2.1/grc/python/Connection.py0000664000175000017500000000365712207702530020102 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import Constants from .. base.Element import Element from .. base.Connection import Connection as _Connection from .. gui.Connection import Connection as _GUIConnection class Connection(_Connection, _GUIConnection): def __init__(self, **kwargs): _Connection.__init__(self, **kwargs) _GUIConnection.__init__(self) def is_msg(self): return self.get_source().get_type() == self.get_sink().get_type() == 'msg' def is_message(self): return self.get_source().get_type() == self.get_sink().get_type() == 'message' def is_bus(self): return self.get_source().get_type() == self.get_sink().get_type() == 'bus' def validate(self): """ Validate the connections. The ports must match in io size. """ Element.validate(self) source_size = Constants.TYPE_TO_SIZEOF[self.get_source().get_type()] * self.get_source().get_vlen() sink_size = Constants.TYPE_TO_SIZEOF[self.get_sink().get_type()] * self.get_sink().get_vlen() if source_size != sink_size: self.add_error_message('Source IO size "%s" does not match sink IO size "%s".'%(source_size, sink_size)) gnuradio-3.7.2.1/grc/python/FlowGraph.py0000664000175000017500000002171712232637747017710 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import expr_utils from .. base.FlowGraph import FlowGraph as _FlowGraph from .. gui.FlowGraph import FlowGraph as _GUIFlowGraph from .. base.odict import odict import re _variable_matcher = re.compile('^(variable\w*)$') _parameter_matcher = re.compile('^(parameter)$') _monitors_searcher = re.compile('(ctrlport_monitor)') _bussink_searcher = re.compile('^(bus_sink)$') _bussrc_searcher = re.compile('^(bus_source)$') _bus_struct_sink_searcher = re.compile('^(bus_structure_sink)$') _bus_struct_src_searcher = re.compile('^(bus_structure_source)$') class FlowGraph(_FlowGraph, _GUIFlowGraph): def __init__(self, **kwargs): _FlowGraph.__init__(self, **kwargs) _GUIFlowGraph.__init__(self) self._eval_cache = dict() def _eval(self, code, namespace, namespace_hash): """ Evaluate the code with the given namespace. Args: code: a string with python code namespace: a dict representing the namespace namespace_hash: a unique hash for the namespace Returns: the resultant object """ if not code: raise Exception, 'Cannot evaluate empty statement.' my_hash = hash(code) ^ namespace_hash #cache if does not exist if not self._eval_cache.has_key(my_hash): self._eval_cache[my_hash] = eval(code, namespace, namespace) #return from cache return self._eval_cache[my_hash] def get_io_signaturev(self, direction): """ Get a list of io signatures for this flow graph. Args: direction: a string of 'in' or 'out' Returns: a list of dicts with: type, label, vlen, size """ sorted_pads = { 'in': self.get_pad_sources(), 'out': self.get_pad_sinks(), }[direction] # we only want stream ports sorted_pads = filter(lambda b: b.get_param('type').get_evaluated() != 'message', sorted_pads); expanded_pads = []; for i in sorted_pads: for j in range(i.get_param('num_streams').get_evaluated()): expanded_pads.append(i); #load io signature return [{ 'label': str(pad.get_param('label').get_evaluated()), 'type': str(pad.get_param('type').get_evaluated()), 'vlen': str(pad.get_param('vlen').get_value()), 'size': pad.get_param('type').get_opt('size'), 'optional': bool(pad.get_param('optional').get_evaluated()), } for pad in expanded_pads] def get_pad_sources(self): """ Get a list of pad source blocks sorted by id order. Returns: a list of pad source blocks in this flow graph """ pads = filter(lambda b: b.get_key() == 'pad_source', self.get_enabled_blocks()) return sorted(pads, lambda x, y: cmp(x.get_id(), y.get_id())) def get_pad_sinks(self): """ Get a list of pad sink blocks sorted by id order. Returns: a list of pad sink blocks in this flow graph """ pads = filter(lambda b: b.get_key() == 'pad_sink', self.get_enabled_blocks()) return sorted(pads, lambda x, y: cmp(x.get_id(), y.get_id())) def get_msg_pad_sources(self): ps = self.get_pad_sources(); return filter(lambda b: b.get_param('type').get_evaluated() == 'message', ps); def get_msg_pad_sinks(self): ps = self.get_pad_sinks(); return filter(lambda b: b.get_param('type').get_evaluated() == 'message', ps); def get_imports(self): """ Get a set of all import statments in this flow graph namespace. Returns: a set of import statements """ imports = sum([block.get_imports() for block in self.get_enabled_blocks()], []) imports = sorted(set(imports)) return imports def get_variables(self): """ Get a list of all variables in this flow graph namespace. Exclude paramterized variables. Returns: a sorted list of variable blocks in order of dependency (indep -> dep) """ variables = filter(lambda b: _variable_matcher.match(b.get_key()), self.get_enabled_blocks()) return expr_utils.sort_objects(variables, lambda v: v.get_id(), lambda v: v.get_var_make()) def get_parameters(self): """ Get a list of all paramterized variables in this flow graph namespace. Returns: a list of paramterized variables """ parameters = filter(lambda b: _parameter_matcher.match(b.get_key()), self.get_enabled_blocks()) return parameters def get_monitors(self): """ Get a list of all ControlPort monitors """ monitors = filter(lambda b: _monitors_searcher.search(b.get_key()), self.get_enabled_blocks()) return monitors def get_bussink(self): bussink = filter(lambda b: _bussink_searcher.search(b.get_key()), self.get_enabled_blocks()) for i in bussink: for j in i.get_params(): if j.get_name() == 'On/Off' and j.get_value() == 'on': return True; return False def get_bussrc(self): bussrc = filter(lambda b: _bussrc_searcher.search(b.get_key()), self.get_enabled_blocks()) for i in bussrc: for j in i.get_params(): if j.get_name() == 'On/Off' and j.get_value() == 'on': return True; return False def get_bus_structure_sink(self): bussink = filter(lambda b: _bus_struct_sink_searcher.search(b.get_key()), self.get_enabled_blocks()) return bussink def get_bus_structure_src(self): bussrc = filter(lambda b: _bus_struct_src_searcher.search(b.get_key()), self.get_enabled_blocks()) return bussrc def rewrite(self): """ Flag the namespace to be renewed. """ def reconnect_bus_blocks(): for block in self.get_blocks(): if 'bus' in map(lambda a: a.get_type(), block.get_sources_gui()): for i in range(len(block.get_sources_gui())): if len(block.get_sources_gui()[i].get_connections()) > 0: source = block.get_sources_gui()[i] sink = [] for j in range(len(source.get_connections())): sink.append(source.get_connections()[j].get_sink()); for elt in source.get_connections(): self.remove_element(elt); for j in sink: self.connect(source, j); self._renew_eval_ns = True _FlowGraph.rewrite(self); reconnect_bus_blocks(); def evaluate(self, expr): """ Evaluate the expression. Args: expr: the string expression @throw Exception bad expression Returns: the evaluated data """ if self._renew_eval_ns: self._renew_eval_ns = False #reload namespace n = dict() #load imports for imp in self.get_imports(): try: exec imp in n except: pass #load parameters np = dict() for parameter in self.get_parameters(): try: e = eval(parameter.get_param('value').to_code(), n, n) np[parameter.get_id()] = e except: pass n.update(np) #merge param namespace #load variables for variable in self.get_variables(): try: e = eval(variable.get_param('value').to_code(), n, n) n[variable.get_id()] = e except: pass #make namespace public self.n = n self.n_hash = hash(str(n)) #evaluate e = self._eval(expr, self.n, self.n_hash) return e gnuradio-3.7.2.1/grc/python/__init__.py0000644000175000017500000000000111700377701017521 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/python/flow_graph.tmpl0000664000175000017500000003034712237515112020454 0ustar jcorganjcorgan#!/usr/bin/env python ######################################################## ##Cheetah template - gnuradio_python ## ##@param imports the import statements ##@param flow_graph the flow_graph ##@param variables the variable blocks ##@param parameters the paramater blocks ##@param blocks the signal blocks ##@param connections the connections ##@param messages the msg type connections ##@param generate_options the type of flow graph ##@param var_id2cbs variable id map to callback strings ######################################################## #def indent($code) #set $code = '\n '.join(str($code).splitlines()) $code#slurp #end def #import time #set $DIVIDER = '#'*50 $DIVIDER # Gnuradio Python Flow Graph # Title: $title #if $flow_graph.get_option('author') # Author: $flow_graph.get_option('author') #end if #if $flow_graph.get_option('description') # Description: $flow_graph.get_option('description') #end if # Generated: $time.ctime() $DIVIDER ######################################################## ##Create Imports ######################################################## #for $imp in $imports $imp #end for ######################################################## ##Create Class ## Write the class declaration for a top or hier block. ## The parameter names are the arguments to __init__. ## Determine the absolute icon path (wx gui only). ## Setup the IO signature (hier block only). ######################################################## #set $class_name = $flow_graph.get_option('id') #set $param_str = ', '.join(['self'] + ['%s=%s'%(param.get_id(), param.get_make()) for param in $parameters]) #if $generate_options == 'wx_gui' #import gtk #set $icon = gtk.IconTheme().lookup_icon('gnuradio-grc', 32, 0) class $(class_name)(grc_wxgui.top_block_gui): def __init__($param_str): grc_wxgui.top_block_gui.__init__(self, title="$title") #if $icon _icon_path = "$icon.get_filename()" self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY)) #end if #elif $generate_options == 'qt_gui' class $(class_name)(gr.top_block, Qt.QWidget): def __init__($param_str): gr.top_block.__init__(self, "$title") Qt.QWidget.__init__(self) self.setWindowTitle("$title") try: self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc')) except: pass self.top_scroll_layout = Qt.QVBoxLayout() self.setLayout(self.top_scroll_layout) self.top_scroll = Qt.QScrollArea() self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame) self.top_scroll_layout.addWidget(self.top_scroll) self.top_scroll.setWidgetResizable(True) self.top_widget = Qt.QWidget() self.top_scroll.setWidget(self.top_widget) self.top_layout = Qt.QVBoxLayout(self.top_widget) self.top_grid_layout = Qt.QGridLayout() self.top_layout.addLayout(self.top_grid_layout) self.settings = Qt.QSettings("GNU Radio", "$class_name") self.restoreGeometry(self.settings.value("geometry").toByteArray()) #elif $generate_options == 'no_gui' class $(class_name)(gr.top_block): def __init__($param_str): gr.top_block.__init__(self, "$title") #elif $generate_options == 'hb' #set $in_sigs = $flow_graph.get_io_signaturev('in') #set $out_sigs = $flow_graph.get_io_signaturev('out') class $(class_name)(gr.hier_block2): #def make_io_sig($io_sigs) #set $size_strs = ['%s*%s'%(io_sig['size'], io_sig['vlen']) for io_sig in $io_sigs] #if len($io_sigs) == 0 gr.io_signature(0, 0, 0)#slurp #elif len($io_sigs) == 1 gr.io_signature(1, 1, $size_strs[0])#slurp #else gr.io_signaturev($(len($io_sigs)), $(len($io_sigs)), [$(', '.join($size_strs))])#slurp #end if #end def def __init__($param_str): gr.hier_block2.__init__( self, "$title", $make_io_sig($in_sigs), $make_io_sig($out_sigs), ) #end if ######################################################## ##Create Parameters ## Set the parameter to a property of self. ######################################################## #if $parameters $DIVIDER # Parameters $DIVIDER #end if #for $param in $parameters $indent($param.get_var_make()) #end for ######################################################## ##Create Variables ######################################################## #if $variables $DIVIDER # Variables $DIVIDER #end if #for $var in $variables $indent($var.get_var_make()) #end for ######################################################## ##Create Message Queues ######################################################## #if $messages $DIVIDER # Message Queues $DIVIDER #end if #for $msg in $messages $(msg.get_source().get_parent().get_id())_msgq_out = $(msg.get_sink().get_parent().get_id())_msgq_in = gr.msg_queue(2) #end for ######################################################## ##Create Blocks ######################################################## #if $blocks $DIVIDER # Blocks $DIVIDER #end if #for $blk in filter(lambda b: b.get_make(), $blocks) #if $blk in $variables $indent($blk.get_make()) #else self.$blk.get_id() = $indent($blk.get_make()) #if $blk.has_param('affinity') and $blk.get_param('affinity').get_evaluated() (self.$blk.get_id()).set_processor_affinity($blk.get_param('affinity').get_evaluated()) #end if #if (len($blk.get_sources())>0) and $blk.has_param('minoutbuf') and (int($blk.get_param('minoutbuf').get_evaluated()) > 0) (self.$blk.get_id()).set_min_output_buffer($blk.get_param('minoutbuf').get_evaluated()) #end if #if (len($blk.get_sources())>0) and $blk.has_param('maxoutbuf') and (int($blk.get_param('maxoutbuf').get_evaluated()) > 0) (self.$blk.get_id()).set_max_output_buffer($blk.get_param('maxoutbuf').get_evaluated()) #end if #end if #end for ######################################################## ##Create Connections ## The port name should be the id of the parent block. ## However, port names for IO pads should be self. ######################################################## #def make_port_sig($port) #if $port.get_parent().get_key() == 'pad_source' (self, $flow_graph.get_pad_sources().index($port.get_parent()))#slurp #elif $port.get_parent().get_key() == 'pad_sink' (self, $flow_graph.get_pad_sinks().index($port.get_parent()))#slurp #else (self.$port.get_parent().get_id(), $port.get_key())#slurp #end if #end def #if $connections $DIVIDER # Connections $DIVIDER #end if #for $con in $connections #set $source = $con.get_source() #set $sink = $con.get_sink() ##resolve virtual sources to the actual sources #if $source.get_parent().is_virtual_source() #set $source = $source.resolve_virtual_source() #end if ##do not generate connections with virtual sinks #if not $sink.get_parent().is_virtual_sink() self.connect($make_port_sig($source), $make_port_sig($sink)) #end if #end for ######################################################## ##Create Asynch Message Connections ######################################################## #if $messages2 $DIVIDER # Asynch Message Connections $DIVIDER #end if #for $msg in $messages2 #set $sr = $msg.get_source() #set $source = "self.%s"%($sr.get_parent().get_id()) #set $source_port = $sr.get_name(); #if $sr.get_parent().get_key() == "pad_source" #set $source = "self" #set $source_port = $sr.get_parent().get_param("label").get_value(); #end if #set $sk = $msg.get_sink() #set $sink = "self.%s"%($sk.get_parent().get_id()) #set $sink_port = $sk.get_name(); #if $sk.get_parent().get_key() == "pad_sink" #set $sink = "self" #set $sink_port = $sk.get_parent().get_param("label").get_value(); #end if self.msg_connect($source, "$source_port", $sink, "$sink_port") #end for ######################################################## # QT sink close method reimplementation ######################################################## #if $generate_options == 'qt_gui' def closeEvent(self, event): self.settings = Qt.QSettings("GNU Radio", "$class_name") self.settings.setValue("geometry", self.saveGeometry()) event.accept() #end if ######################################################## ##Create Callbacks ## Write a set method for this variable that calls the callbacks ######################################################## #for $var in $parameters + $variables #set $id = $var.get_id() def get_$(id)(self): return self.$id def set_$(id)(self, $id): self.$id = $id #for $callback in $var_id2cbs[$id] $indent($callback) #end for #end for ######################################################## ##Create Main ## For top block code, generate a main routine. ## Instantiate the top block and run as gui or cli. ######################################################## #def make_default($type, $param) #if $type == 'eng_float' eng_notation.num_to_str($param.get_make())#slurp #else $param.get_make()#slurp #end if #end def #def make_short_id($param) #set $short_id = $param.get_param('short_id').get_evaluated() #if $short_id #set $short_id = '-' + $short_id #end if $short_id#slurp #end def #if $generate_options != 'hb' if __name__ == '__main__': #if $generate_options in ('wx_gui', 'qt_gui') import ctypes import os if os.name == 'posix': try: x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: print "Warning: failed to XInitThreads()" #end if parser = OptionParser(option_class=eng_option, usage="%prog: [options]") #set $params_eq_list = list() #for $param in $parameters #set $type = $param.get_param('type').get_value() #if $type #silent $params_eq_list.append('%s=options.%s'%($param.get_id(), $param.get_id())) parser.add_option("$make_short_id($param)", "--$param.get_id().replace('_', '-')", dest="$param.get_id()", type="$type", default=$make_default($type, $param), help="Set $($param.get_param('label').get_evaluated() or $param.get_id()) [default=%default]") #end if #end for (options, args) = parser.parse_args() #if $flow_graph.get_option('realtime_scheduling') if gr.enable_realtime_scheduling() != gr.RT_OK: print "Error: failed to enable realtime scheduling." #end if #if $generate_options == 'wx_gui' tb = $(class_name)($(', '.join($params_eq_list))) #if $flow_graph.get_option('max_nouts') tb.Run($flow_graph.get_option('run'), $flow_graph.get_option('max_nouts')) #else tb.Start($flow_graph.get_option('run')) #for $m in $monitors (tb.$m.get_id()).start() #end for tb.Wait() #end if #elif $generate_options == 'qt_gui' qapp = Qt.QApplication(sys.argv) tb = $(class_name)($(', '.join($params_eq_list))) #if $flow_graph.get_option('run') #if $flow_graph.get_option('max_nouts') tb.start($flow_graph.get_option('max_nouts')) #else tb.start() #end if #end if tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) #for $m in $monitors (tb.$m.get_id()).start() #end for qapp.exec_() tb = None #to clean up Qt widgets #elif $generate_options == 'no_gui' tb = $(class_name)($(', '.join($params_eq_list))) #set $run_options = $flow_graph.get_option('run_options') #if $run_options == 'prompt' #if $flow_graph.get_option('max_nouts') tb.start($flow_graph.get_option('max_nouts')) #else tb.start() #end if #for $m in $monitors (tb.$m.get_id()).start() #end for raw_input('Press Enter to quit: ') tb.stop() #elif $run_options == 'run' #if $flow_graph.get_option('max_nouts') tb.start($flow_graph.get_option('max_nouts')) #else tb.start() #end if #end if #for $m in $monitors (tb.$m.get_id()).start() #end for tb.wait() #end if #end if gnuradio-3.7.2.1/grc/python/Generator.py0000664000175000017500000001472612207702530017730 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os import sys import subprocess import tempfile from Cheetah.Template import Template import expr_utils from Constants import \ TOP_BLOCK_FILE_MODE, HIER_BLOCK_FILE_MODE, \ HIER_BLOCKS_LIB_DIR, FLOW_GRAPH_TEMPLATE import convert_hier from .. gui import Messages class Generator(object): def __init__(self, flow_graph, file_path): """ Initialize the generator object. Determine the file to generate. Args: flow_graph: the flow graph object file_path: the path to write the file to """ self._flow_graph = flow_graph self._generate_options = self._flow_graph.get_option('generate_options') if self._generate_options == 'hb': self._mode = HIER_BLOCK_FILE_MODE dirname = HIER_BLOCKS_LIB_DIR else: self._mode = TOP_BLOCK_FILE_MODE dirname = os.path.dirname(file_path) #handle the case where the directory is read-only #in this case, use the system's temp directory if not os.access(dirname, os.W_OK): dirname = tempfile.gettempdir() filename = self._flow_graph.get_option('id') + '.py' self._file_path = os.path.join(dirname, filename) def get_file_path(self): return self._file_path def write(self): #do throttle warning throttled = any(map(lambda b: b.throttle(), self._flow_graph.get_enabled_blocks())) if not throttled and self._generate_options != 'hb': Messages.send_warning('''\ This flow graph may not have flow control: no audio or usrp blocks found. \ Add a Misc->Throttle block to your flow graph to avoid CPU congestion.''') #generate open(self.get_file_path(), 'w').write(str(self)) if self._generate_options == 'hb': #convert hier block to xml wrapper convert_hier.convert_hier(self._flow_graph, self.get_file_path()) os.chmod(self.get_file_path(), self._mode) def get_popen(self): """ Execute this python flow graph. Returns: a popen object """ #extract the path to the python executable python_exe = sys.executable #when using wx gui on mac os, execute with pythonw #using pythonw is not necessary anymore, disabled below #if self._generate_options == 'wx_gui' and 'darwin' in sys.platform.lower(): # python_exe = 'pythonw' #setup the command args to run cmds = [python_exe, '-u', self.get_file_path()] #-u is unbuffered stdio #when in no gui mode on linux, use an xterm (looks nice) if self._generate_options == 'no_gui' and 'linux' in sys.platform.lower(): cmds = ['xterm', '-e'] + cmds p = subprocess.Popen(args=cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, universal_newlines=True) return p def __str__(self): """ Convert the flow graph to python code. Returns: a string of python code """ title = self._flow_graph.get_option('title') or self._flow_graph.get_option('id').replace('_', ' ').title() imports = self._flow_graph.get_imports() variables = self._flow_graph.get_variables() parameters = self._flow_graph.get_parameters() monitors = self._flow_graph.get_monitors() #list of blocks not including variables and imports and parameters and disabled def _get_block_sort_text(block): code = block.get_make().replace(block.get_id(), ' ') try: code += block.get_param('notebook').get_value() #older gui markup w/ wxgui except: pass try: code += block.get_param('gui_hint').get_value() #newer gui markup w/ qtgui except: pass return code blocks = expr_utils.sort_objects( self._flow_graph.get_enabled_blocks(), lambda b: b.get_id(), _get_block_sort_text ) #list of regular blocks (all blocks minus the special ones) blocks = filter(lambda b: b not in (imports + parameters), blocks) #list of connections where each endpoint is enabled connections = filter(lambda c: not (c.is_bus() or c.is_msg() or c.is_message()), self._flow_graph.get_enabled_connections()) messages = filter(lambda c: c.is_msg(), self._flow_graph.get_enabled_connections()) messages2 = filter(lambda c: c.is_message(), self._flow_graph.get_enabled_connections()) #list of variable names var_ids = [var.get_id() for var in parameters + variables] #prepend self. replace_dict = dict([(var_id, 'self.%s'%var_id) for var_id in var_ids]) #list of callbacks callbacks = [ expr_utils.expr_replace(cb, replace_dict) for cb in sum([block.get_callbacks() for block in self._flow_graph.get_enabled_blocks()], []) ] #map var id to callbacks var_id2cbs = dict( [(var_id, filter(lambda c: expr_utils.get_variable_dependencies(c, [var_id]), callbacks)) for var_id in var_ids] ) #load the namespace namespace = { 'title': title, 'imports': imports, 'flow_graph': self._flow_graph, 'variables': variables, 'parameters': parameters, 'monitors': monitors, 'blocks': blocks, 'connections': connections, 'messages': messages, 'messages2': messages2, 'generate_options': self._generate_options, 'var_id2cbs': var_id2cbs, } #build the template t = Template(open(FLOW_GRAPH_TEMPLATE, 'r').read(), namespace) return str(t) gnuradio-3.7.2.1/grc/python/default_flow_graph.grc0000664000175000017500000000201412207702530021744 0ustar jcorganjcorgan options id top_block _coordinate (10, 10) _rotation 0 variable id samp_rate value 32000 _coordinate (10, 170) _rotation 0 gnuradio-3.7.2.1/grc/python/extract_docs.py0000664000175000017500000000441212207702530020453 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import re def _extract(key): """ Extract the documentation from the python __doc__ strings. If multiple modules match, combine the docs. Args: key: the block key Returns: a string with documentation """ #extract matches try: module_name, constructor_name = key.split('_', 1) module = __import__('gnuradio.'+module_name) module = getattr(module, module_name) except ImportError: try: module_name, constructor_name = key.split('_', 1) module = __import__(module_name) except: return '' except: return '' pattern = constructor_name.replace('_', '_*').replace('x', '\w') pattern_matcher = re.compile('^%s\w*$'%pattern) matches = filter(lambda x: pattern_matcher.match(x), dir(module)) #combine all matches doc_strs = list() for match in matches: try: title = ' --- ' + match + ' --- ' doc_strs.append('\n\n'.join([title, getattr(module, match).__doc__]).strip()) except: pass return '\n\n'.join(doc_strs) _docs_cache = dict() def extract(key): """ Call the private extract and cache the result. Args: key: the block key Returns: a string with documentation """ if not _docs_cache.has_key(key): _docs_cache[key] = _extract(key) return _docs_cache[key] if __name__ == '__main__': import sys print extract(sys.argv[1]) gnuradio-3.7.2.1/grc/python/Block.py0000664000175000017500000001701012207702530017021 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from .. base.Block import Block as _Block from .. gui.Block import Block as _GUIBlock import extract_docs class Block(_Block, _GUIBlock): def is_virtual_sink(self): return self.get_key() == 'virtual_sink' def is_virtual_source(self): return self.get_key() == 'virtual_source' ##for make source to keep track of indexes _source_count = 0 ##for make sink to keep track of indexes _sink_count = 0 def __init__(self, flow_graph, n): """ Make a new block from nested data. Args: flow: graph the parent element n: the nested odict Returns: block a new block """ #grab the data self._doc = n.find('doc') or '' self._imports = map(lambda i: i.strip(), n.findall('import')) self._make = n.find('make') self._var_make = n.find('var_make') self._checks = n.findall('check') self._callbacks = n.findall('callback') self._throttle = n.find('throttle') or '' self._bus_structure_source = n.find('bus_structure_source') or '' self._bus_structure_sink = n.find('bus_structure_sink') or '' #build the block _Block.__init__( self, flow_graph=flow_graph, n=n, ) _GUIBlock.__init__(self) def get_bus_structure(self, direction): if direction == 'source': bus_structure = self._bus_structure_source; else: bus_structure = self._bus_structure_sink; bus_structure = self.resolve_dependencies(bus_structure); if not bus_structure: return '' try: clean_bus_structure = self.get_parent().evaluate(bus_structure) return clean_bus_structure except: return '' def throttle(self): return bool(self._throttle) def validate(self): """ Validate this block. Call the base class validate. Evaluate the checks: each check must evaluate to True. """ _Block.validate(self) #evaluate the checks for check in self._checks: check_res = self.resolve_dependencies(check) try: if not self.get_parent().evaluate(check_res): self.add_error_message('Check "%s" failed.'%check) except: self.add_error_message('Check "%s" did not evaluate.'%check) def rewrite(self): """ Add and remove ports to adjust for the nports. """ _Block.rewrite(self) def rectify(ports): #restore integer contiguity after insertion #rectify the port names with the index self.back_ofthe_bus(ports); for i, port in enumerate(ports): port._key = str(i) port._name = port._n['name'] if len(ports) > 1 and not port._type == 'bus': port._name += str(i) def insert_port(get_ports, get_port, key): prev_port = get_port(str(int(key)-1)) get_ports().insert( get_ports().index(prev_port)+1, prev_port.copy(new_key=key), ) rectify(get_ports()) def remove_port(get_ports, get_port, key): port = get_port(key) for connection in port.get_connections(): self.get_parent().remove_element(connection) get_ports().remove(port) rectify(get_ports()) #adjust nports for get_ports, get_port in ( (self.get_sources, self.get_source), (self.get_sinks, self.get_sink), ): master_ports = filter(lambda p: p.get_nports(), get_ports()) for i, master_port in enumerate(master_ports): nports = master_port.get_nports() index_first = get_ports().index(master_port) try: index_last = get_ports().index(master_ports[i+1]) except IndexError: index_last = len(get_ports()) num_ports = index_last - index_first #do nothing if nports is already num ports if nports == num_ports: continue #remove excess ports and connections if nports < num_ports: for key in reversed(map(str, range(index_first+nports, index_first+num_ports))): remove_port(get_ports, get_port, key); continue #add more ports if nports > num_ports: for key in map(str, range(index_first+num_ports, index_first+nports)): insert_port(get_ports, get_port, key) continue def port_controller_modify(self, direction): """ Change the port controller. Args: direction: +1 or -1 Returns: true for change """ changed = False #concat the nports string from the private nports settings of all ports nports_str = ' '.join([port._nports for port in self.get_ports()]) #modify all params whose keys appear in the nports string for param in self.get_params(): if param.is_enum() or param.get_key() not in nports_str: continue #try to increment the port controller by direction try: value = param.get_evaluated() value = value + direction if 0 < value: param.set_value(value) changed = True except: pass return changed def get_doc(self): doc = self._doc.strip('\n').replace('\\\n', '') #merge custom doc with doxygen docs return '\n'.join([doc, extract_docs.extract(self.get_key())]).strip('\n') def get_category(self): return _Block.get_category(self) def get_imports(self): """ Resolve all import statements. Split each import statement at newlines. Combine all import statments into a list. Filter empty imports. Returns: a list of import statements """ return filter(lambda i: i, sum(map(lambda i: self.resolve_dependencies(i).split('\n'), self._imports), [])) def get_make(self): return self.resolve_dependencies(self._make) def get_var_make(self): return self.resolve_dependencies(self._var_make) def get_callbacks(self): """ Get a list of function callbacks for this block. Returns: a list of strings """ def make_callback(callback): callback = self.resolve_dependencies(callback) if 'self.' in callback: return callback return 'self.%s.%s'%(self.get_id(), callback) return map(make_callback, self._callbacks) gnuradio-3.7.2.1/grc/python/block.dtd0000664000175000017500000000413412207702530017207 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/scripts/0000755000175000017500000000000012207702530015562 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/scripts/CMakeLists.txt0000644000175000017500000000167711744612271020344 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## GR_PYTHON_INSTALL( PROGRAMS gnuradio-companion DESTINATION ${GR_RUNTIME_DIR} COMPONENT "grc" ) gnuradio-3.7.2.1/grc/scripts/gnuradio-companion0000775000175000017500000000462412207702530021311 0ustar jcorganjcorgan#!/usr/bin/env python """ Copyright 2009-2012 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk try: from gnuradio import gr except ImportError, e: d = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=""" Cannot import gnuradio. Is the python path environment variable set correctly? All OS: PYTHONPATH Is the library path environment variable set correctly? Linux: LD_LIBRARY_PATH Windows: PATH MacOSX: DYLD_LIBRARY_PATH """) d.set_title(str(e)) d.run() exit(-1) from optparse import OptionParser import os if __name__ == "__main__": if ('GR_DONT_LOAD_PREFS' in os.environ.keys() and (not 'GRC_BLOCKS_PATH' in os.environ.keys() or len(os.environ['GRC_BLOCKS_PATH']) == 0)): d = gtk.MessageDialog( type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format="""Can't find block definitions. Use config.conf or GRC_BLOCKS_PATH. """) d.set_title("No block definitions available.") d.run() exit(-1) usage = 'usage: %prog [options] [saved flow graphs]' version = """ GNU Radio Companion %s This program is part of GNU Radio GRC comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it. """%gr.version() parser = OptionParser(usage=usage, version=version) (options, args) = parser.parse_args() from gnuradio.grc.python.Platform import Platform from gnuradio.grc.gui.ActionHandler import ActionHandler #setup icon using icon theme try: gtk.window_set_default_icon(gtk.IconTheme().load_icon('gnuradio-grc', 256, 0)) except: pass ActionHandler(args, Platform()) gnuradio-3.7.2.1/grc/grc_gnuradio/0000755000175000017500000000000011744612271016545 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/grc_gnuradio/CMakeLists.txt0000644000175000017500000000221511700377701021303 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/grc_gnuradio COMPONENT "grc" ) GR_PYTHON_INSTALL(FILES blks2/__init__.py blks2/error_rate.py blks2/packet.py blks2/selector.py blks2/tcp.py DESTINATION ${GR_PYTHON_DIR}/grc_gnuradio/blks2 COMPONENT "grc" ) gnuradio-3.7.2.1/grc/grc_gnuradio/blks2/0000755000175000017500000000000012237515112017554 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/grc_gnuradio/blks2/packet.py0000664000175000017500000002361212237515112021403 0ustar jcorganjcorgan# Copyright 2008,2009,2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, digital from gnuradio import blocks from gnuradio.digital import packet_utils import gnuradio.gr.gr_threading as _threading ##payload length in bytes DEFAULT_PAYLOAD_LEN = 512 ##how many messages in a queue DEFAULT_MSGQ_LIMIT = 2 ##threshold for unmaking packets DEFAULT_THRESHOLD = 12 ################################################## ## Options Class for OFDM ################################################## class options(object): def __init__(self, **kwargs): for key, value in kwargs.iteritems(): setattr(self, key, value) ################################################## ## Packet Encoder ################################################## class _packet_encoder_thread(_threading.Thread): def __init__(self, msgq, payload_length, send): self._msgq = msgq self._payload_length = payload_length self._send = send _threading.Thread.__init__(self) self.setDaemon(1) self.keep_running = True self.start() def run(self): sample = '' #residual sample while self.keep_running: msg = self._msgq.delete_head() #blocking read of message queue sample = sample + msg.to_string() #get the body of the msg as a string while len(sample) >= self._payload_length: payload = sample[:self._payload_length] sample = sample[self._payload_length:] self._send(payload) class packet_encoder(gr.hier_block2): """ Hierarchical block for wrapping packet-based modulators. """ def __init__(self, samples_per_symbol, bits_per_symbol, preamble='', access_code='', pad_for_usrp=True): """ packet_mod constructor. Args: samples_per_symbol: number of samples per symbol bits_per_symbol: number of bits per symbol access_code: AKA sync vector pad_for_usrp: If true, packets are padded such that they end up a multiple of 128 samples payload_length: number of bytes in a data-stream slice """ #setup parameters self._samples_per_symbol = samples_per_symbol self._bits_per_symbol = bits_per_symbol self._pad_for_usrp = pad_for_usrp if not preamble: #get preamble preamble = packet_utils.default_preamble if not access_code: #get access code access_code = packet_utils.default_access_code if not packet_utils.is_1_0_string(preamble): raise ValueError, "Invalid preamble %r. Must be string of 1's and 0's" % (preamble,) if not packet_utils.is_1_0_string(access_code): raise ValueError, "Invalid access_code %r. Must be string of 1's and 0's" % (access_code,) self._preamble = preamble self._access_code = access_code self._pad_for_usrp = pad_for_usrp #create blocks msg_source = blocks.message_source(gr.sizeof_char, DEFAULT_MSGQ_LIMIT) self._msgq_out = msg_source.msgq() #initialize hier2 gr.hier_block2.__init__( self, "packet_encoder", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_char) # Output signature ) #connect self.connect(msg_source, self) def send_pkt(self, payload): """ Wrap the payload in a packet and push onto the message queue. Args: payload: string, data to send """ packet = packet_utils.make_packet( payload, self._samples_per_symbol, self._bits_per_symbol, self._preamble, self._access_code, self._pad_for_usrp ) msg = gr.message_from_string(packet) self._msgq_out.insert_tail(msg) ################################################## ## Packet Decoder ################################################## class _packet_decoder_thread(_threading.Thread): def __init__(self, msgq, callback): _threading.Thread.__init__(self) self.setDaemon(1) self._msgq = msgq self.callback = callback self.keep_running = True self.start() def run(self): while self.keep_running: msg = self._msgq.delete_head() ok, payload = packet_utils.unmake_packet(msg.to_string(), int(msg.arg1())) if self.callback: self.callback(ok, payload) class packet_decoder(gr.hier_block2): """ Hierarchical block for wrapping packet-based demodulators. """ def __init__(self, access_code='', threshold=-1, callback=None): """ packet_demod constructor. Args: access_code: AKA sync vector threshold: detect access_code with up to threshold bits wrong (0 -> use default) callback: a function of args: ok, payload """ #access code if not access_code: #get access code access_code = packet_utils.default_access_code if not packet_utils.is_1_0_string(access_code): raise ValueError, "Invalid access_code %r. Must be string of 1's and 0's" % (access_code,) self._access_code = access_code #threshold if threshold < 0: threshold = DEFAULT_THRESHOLD self._threshold = threshold #blocks msgq = gr.msg_queue(DEFAULT_MSGQ_LIMIT) #holds packets from the PHY correlator = digital.correlate_access_code_bb(self._access_code, self._threshold) framer_sink = digital.framer_sink_1(msgq) #initialize hier2 gr.hier_block2.__init__( self, "packet_decoder", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(0, 0, 0) # Output signature ) #connect self.connect(self, correlator, framer_sink) #start thread _packet_decoder_thread(msgq, callback) ################################################## ## Packet Mod for OFDM Mod and Packet Encoder ################################################## class packet_mod_base(gr.hier_block2): """ Hierarchical block for wrapping packet source block. """ def __init__(self, packet_source=None, payload_length=0): if not payload_length: #get payload length payload_length = DEFAULT_PAYLOAD_LEN if payload_length%self._item_size_in != 0: #verify that packet length is a multiple of the stream size raise ValueError, 'The payload length: "%d" is not a mutiple of the stream size: "%d".'%(payload_length, self._item_size_in) #initialize hier2 gr.hier_block2.__init__( self, "ofdm_mod", gr.io_signature(1, 1, self._item_size_in), # Input signature gr.io_signature(1, 1, packet_source._hb.output_signature().sizeof_stream_item(0)) # Output signature ) #create blocks msgq = gr.msg_queue(DEFAULT_MSGQ_LIMIT) msg_sink = blocks.message_sink(self._item_size_in, msgq, False) #False -> blocking #connect self.connect(self, msg_sink) self.connect(packet_source, self) #start thread _packet_encoder_thread(msgq, payload_length, packet_source.send_pkt) class packet_mod_b(packet_mod_base): _item_size_in = gr.sizeof_char class packet_mod_s(packet_mod_base): _item_size_in = gr.sizeof_short class packet_mod_i(packet_mod_base): _item_size_in = gr.sizeof_int class packet_mod_f(packet_mod_base): _item_size_in = gr.sizeof_float class packet_mod_c(packet_mod_base): _item_size_in = gr.sizeof_gr_complex ################################################## ## Packet Demod for OFDM Demod and Packet Decoder ################################################## class packet_demod_base(gr.hier_block2): """ Hierarchical block for wrapping packet sink block. """ def __init__(self, packet_sink=None): #initialize hier2 gr.hier_block2.__init__( self, "ofdm_mod", gr.io_signature(1, 1, packet_sink._hb.input_signature().sizeof_stream_item(0)), # Input signature gr.io_signature(1, 1, self._item_size_out) # Output signature ) #create blocks msg_source = blocks.message_source(self._item_size_out, DEFAULT_MSGQ_LIMIT) self._msgq_out = msg_source.msgq() #connect self.connect(self, packet_sink) self.connect(msg_source, self) if packet_sink._hb.output_signature().sizeof_stream_item(0): self.connect(packet_sink, blocks.null_sink(packet_sink._hb.output_signature().sizeof_stream_item(0))) def recv_pkt(self, ok, payload): msg = gr.message_from_string(payload, 0, self._item_size_out, len(payload)/self._item_size_out) if ok: self._msgq_out.insert_tail(msg) class packet_demod_b(packet_demod_base): _item_size_out = gr.sizeof_char class packet_demod_s(packet_demod_base): _item_size_out = gr.sizeof_short class packet_demod_i(packet_demod_base): _item_size_out = gr.sizeof_int class packet_demod_f(packet_demod_base): _item_size_out = gr.sizeof_float class packet_demod_c(packet_demod_base): _item_size_out = gr.sizeof_gr_complex gnuradio-3.7.2.1/grc/grc_gnuradio/blks2/selector.py0000664000175000017500000001331112233246672021757 0ustar jcorganjcorgan# # Copyright 2008,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks class selector(gr.hier_block2): """A hier2 block with N inputs and M outputs, where data is only forwarded through input n to output m.""" def __init__(self, item_size, num_inputs, num_outputs, input_index, output_index): """ Selector constructor. Args: item_size: the size of the gr data stream in bytes num_inputs: the number of inputs (integer) num_outputs: the number of outputs (integer) input_index: the index for the source data output_index: the index for the destination data """ gr.hier_block2.__init__( self, 'selector', gr.io_signature(num_inputs, num_inputs, item_size), gr.io_signature(num_outputs, num_outputs, item_size), ) #terminator blocks for unused inputs and outputs self.input_terminators = [blocks.null_sink(item_size) for i in range(num_inputs)] self.output_terminators = [blocks.head(item_size, 0) for i in range(num_outputs)] self.copy = blocks.copy(item_size) #connections for i in range(num_inputs): self.connect((self, i), self.input_terminators[i]) for i in range(num_outputs): self.connect(blocks.null_source(item_size), self.output_terminators[i], (self, i)) self.item_size = item_size self.input_index = input_index self.output_index = output_index self.num_inputs = num_inputs self.num_outputs = num_outputs self._connect_current() def _indexes_valid(self): """ Are the input and output indexes within range of the number of inputs and outputs? Returns: true if input index and output index are in range """ return self.input_index in range(self.num_inputs) and self.output_index in range(self.num_outputs) def _connect_current(self): """If the input and output indexes are valid: disconnect the blocks at the input and output index from their terminators, and connect them to one another. Then connect the terminators to one another.""" if self._indexes_valid(): self.disconnect((self, self.input_index), self.input_terminators[self.input_index]) self.disconnect(self.output_terminators[self.output_index], (self, self.output_index)) self.connect((self, self.input_index), self.copy) self.connect(self.copy, (self, self.output_index)) self.connect(self.output_terminators[self.output_index], self.input_terminators[self.input_index]) def _disconnect_current(self): """If the input and output indexes are valid: disconnect the blocks at the input and output index from one another, and the terminators at the input and output index from one another. Reconnect the blocks to the terminators.""" if self._indexes_valid(): self.disconnect((self, self.input_index), self.copy) self.disconnect(self.copy, (self, self.output_index)) self.disconnect(self.output_terminators[self.output_index], self.input_terminators[self.input_index]) self.connect((self, self.input_index), self.input_terminators[self.input_index]) self.connect(self.output_terminators[self.output_index], (self, self.output_index)) def set_input_index(self, input_index): """ Change the block to the new input index if the index changed. Args: input_index: the new input index """ if self.input_index != input_index: self.lock() self._disconnect_current() self.input_index = input_index self._connect_current() self.unlock() def set_output_index(self, output_index): """ Change the block to the new output index if the index changed. Args: output_index: the new output index """ if self.output_index != output_index: self.lock() self._disconnect_current() self.output_index = output_index self._connect_current() self.unlock() class valve(selector): """Wrapper for selector with 1 input and 1 output.""" def __init__(self, item_size, open): """ Constructor for valve. Args: item_size: the size of the gr data stream in bytes open: true if initial valve state is open """ if open: output_index = -1 else: output_index = 0 selector.__init__(self, item_size, 1, 1, 0, output_index) def set_open(self, open): """ Callback to set open state. Args: open: true to set valve state to open """ if open: output_index = -1 else: output_index = 0 self.set_output_index(output_index) gnuradio-3.7.2.1/grc/grc_gnuradio/blks2/error_rate.py0000664000175000017500000001221612233246672022306 0ustar jcorganjcorgan# Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # default_win_size = 1000 from gnuradio import gr from gnuradio import blocks import gnuradio.gr.gr_threading as _threading import numpy #generate 1s counts array _1s_counts = [sum([1&(i>>j) for j in range(8)]) for i in range(2**8)] class input_watcher(_threading.Thread): """ Read samples from the message queue and hand them to the callback. """ def __init__(self, msgq, callback): self._msgq = msgq self._callback = callback _threading.Thread.__init__(self) self.setDaemon(1) self.keep_running = True self.start() def run(self): r = '' while True: msg = self._msgq.delete_head() itemsize = int(msg.arg1()) nitems = int(msg.arg2()) s = r + msg.to_string() i = (nitems-nitems%2)*itemsize r = s[i:] s = s[:i] samples = numpy.fromstring(s, numpy.int8) self._callback(samples) class error_rate(gr.hier_block2): """ Sample the incoming data streams (byte) and calculate the bit or symbol error rate. Write the running rate to the output data stream (float). """ def __init__(self, type='BER', win_size=default_win_size, bits_per_symbol=2): """ Error rate constructor. Args: type: a string 'BER' or 'SER' win_size: the number of samples to calculate over bits_per_symbol: the number of information bits per symbol (BER only) """ #init gr.hier_block2.__init__( self, 'error_rate', gr.io_signature(2, 2, gr.sizeof_char), gr.io_signature(1, 1, gr.sizeof_float), ) assert type in ('BER', 'SER') self._max_samples = win_size self._bits_per_symbol = bits_per_symbol #setup message queue msg_source = blocks.message_source(gr.sizeof_float, 1) self._msgq_source = msg_source.msgq() msgq_sink = gr.msg_queue(2) msg_sink = blocks.message_sink(gr.sizeof_char, msgq_sink, False) #False -> blocking inter = blocks.interleave(gr.sizeof_char) #start thread self._num_errs = 0 self._err_index = 0 self._num_samps = 0 self._err_array = numpy.zeros(self._max_samples, numpy.int8) if type == 'BER': input_watcher(msgq_sink, self._handler_ber) elif type == 'SER': input_watcher(msgq_sink, self._handler_ser) #connect self.connect(msg_source, self) self.connect((self, 0), (inter, 0)) self.connect((self, 1), (inter, 1)) self.connect(inter, msg_sink) def _handler_ber(self, samples): num = len(samples)/2 arr = numpy.zeros(num, numpy.float32) for i in range(num): old_err = self._err_array[self._err_index] #record error self._err_array[self._err_index] = _1s_counts[samples[i*2] ^ samples[i*2 + 1]] self._num_errs = self._num_errs + self._err_array[self._err_index] - old_err #increment index self._err_index = (self._err_index + 1)%self._max_samples self._num_samps = min(self._num_samps + 1, self._max_samples) #write sample arr[i] = float(self._num_errs)/float(self._num_samps*self._bits_per_symbol) #write message msg = gr.message_from_string(arr.tostring(), 0, gr.sizeof_float, num) self._msgq_source.insert_tail(msg) def _handler_ser(self, samples): num = len(samples)/2 arr = numpy.zeros(num, numpy.float32) for i in range(num): old_err = self._err_array[self._err_index] #record error ref = samples[i*2] res = samples[i*2 + 1] if ref == res: self._err_array[self._err_index] = 0 else: self._err_array[self._err_index] = 1 #update number of errors self._num_errs = self._num_errs + self._err_array[self._err_index] - old_err #increment index self._err_index = (self._err_index + 1)%self._max_samples self._num_samps = min(self._num_samps + 1, self._max_samples) #write sample arr[i] = float(self._num_errs)/float(self._num_samps) #write message msg = gr.message_from_string(arr.tostring(), 0, gr.sizeof_float, num) self._msgq_source.insert_tail(msg) gnuradio-3.7.2.1/grc/grc_gnuradio/blks2/__init__.py0000664000175000017500000000213312233246672021676 0ustar jcorganjcorgan# Copyright 2008-2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from selector import selector, valve from packet import options, packet_encoder, packet_decoder, \ packet_mod_b, packet_mod_s, packet_mod_i, packet_mod_f, packet_mod_c, \ packet_demod_b, packet_demod_s, packet_demod_i, packet_demod_f, packet_demod_c from error_rate import error_rate from tcp import tcp_source, tcp_sink gnuradio-3.7.2.1/grc/grc_gnuradio/blks2/tcp.py0000664000175000017500000000445012233246672020731 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blocks import socket import os def _get_sock_fd(addr, port, server): """ Get the file descriptor for the socket. As a client, block on connect, dup the socket descriptor. As a server, block on accept, dup the client descriptor. Args: addr: the ip address string port: the tcp port number server: true for server mode, false for client mode Returns: the file descriptor number """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if server: sock.bind((addr, port)) sock.listen(1) clientsock, address = sock.accept() return os.dup(clientsock.fileno()) else: sock.connect((addr, port)) return os.dup(sock.fileno()) class tcp_source(gr.hier_block2): def __init__(self, itemsize, addr, port, server=True): #init hier block gr.hier_block2.__init__( self, 'tcp_source', gr.io_signature(0, 0, 0), gr.io_signature(1, 1, itemsize), ) fd = _get_sock_fd(addr, port, server) self.connect(blocks.file_descriptor_source(itemsize, fd), self) class tcp_sink(gr.hier_block2): def __init__(self, itemsize, addr, port, server=False): #init hier block gr.hier_block2.__init__( self, 'tcp_sink', gr.io_signature(1, 1, itemsize), gr.io_signature(0, 0, 0), ) fd = _get_sock_fd(addr, port, server) self.connect(self, blocks.file_descriptor_sink(itemsize, fd)) gnuradio-3.7.2.1/grc/grc_gnuradio/README0000644000175000017500000000106111700377701017421 0ustar jcorganjcorganThis is the grc_gnuradio module. It contains supplemental python modules that grc uses at runtime. The supplemental modules are meant to mimic modules in gnuradio. These will be phased-out as new functionaility is merged into gnuradio. The blk2s module wraps many blocks in blks2 and gives them streaming outputs. Will be phased-out by new message passing implementations. Other blks2 blocks will hopefully make their way into blks2impl. The wxgui module contains a top_block + wxgui frame. Will be phased-out by gui.py in wxgui and a new top block template. gnuradio-3.7.2.1/grc/grc_gnuradio/__init__.py0000644000175000017500000000000111700377701020643 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/__init__.py0000644000175000017500000000000011700377701016177 0ustar jcorganjcorgangnuradio-3.7.2.1/grc/cpp/0000755000175000017500000000000011700377701014662 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/cpp/README0000644000175000017500000000031211700377701015536 0ustar jcorganjcorganGRC could be used to generate c++ based flowgraphs: * A few base and gui classes would be overridden. * Block info could be extracted from the doxygen xml. * New flowgraph templates would be designed. gnuradio-3.7.2.1/grc/grc.conf.in0000644000175000017500000000032711700377701016131 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [grc] global_blocks_path = @blocksdir@ local_blocks_path = gnuradio-3.7.2.1/grc/examples/0000755000175000017500000000000011744612271015720 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/examples/CMakeLists.txt0000644000175000017500000000216011744612271020457 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # SIMPLE install( FILES simple/variable_config.grc DESTINATION ${GR_PKG_DATA_DIR}/examples/grc/simple COMPONENT "grc" ) # XMLRPC install( FILES xmlrpc/readme.txt xmlrpc/xmlrpc_client.grc xmlrpc/xmlrpc_client_script.py xmlrpc/xmlrpc_server.grc DESTINATION ${GR_PKG_DATA_DIR}/examples/grc/xmlrpc COMPONENT "grc" ) gnuradio-3.7.2.1/grc/examples/simple/0000755000175000017500000000000012207440367017211 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/examples/simple/variable_config.grc0000664000175000017500000001616112207440367023027 0ustar jcorganjcorgan Sat Nov 10 15:20:12 2012 options id variable_config_demo _enabled True title Variable Config Block Demonstration author Example description Save/Load freq from a config file. window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (10, 170) _rotation 0 variable_config id freq_init _enabled True value 1000 type real config_file config.conf section main option freq writeback freq _coordinate (255, 17) _rotation 0 variable_slider id freq _enabled True label Frequency (Hz) value freq_init min -samp_rate/2 max samp_rate/2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (429, 24) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 50 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook freqvar None _coordinate (671, 233) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (392, 233) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq freq amp 1 offset 0 _coordinate (173, 201) _rotation 0 blocks_throttle_0 wxgui_fftsink2_0 0 0 analog_sig_source_x_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/grc/examples/xmlrpc/0000755000175000017500000000000012207702530017216 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/examples/xmlrpc/xmlrpc_server.grc0000664000175000017500000002112512207440367022620 0ustar jcorganjcorgan Sat Nov 10 15:20:55 2012 options id server_block _enabled True title XMLRPC Server author Example description example flow graph window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id offset _enabled True value 0 _coordinate (12, 390) _rotation 0 xmlrpc_server id xmlrpc_server _enabled True addr localhost port 1234 _coordinate (395, 240) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2 _enabled True type float title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale .001 ac_couple False xy_mode False num_inputs 1 win_size grid_pos 0, 0, 2, 4 notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (623, 28) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2 _enabled True type float title FFT Plot samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 8 ref_level 50 ref_scale 2.0 fft_size 512 fft_rate 15 peak_hold False average False avg_alpha 0 win None win_size grid_pos 2, 0, 2, 4 notebook freqvar None _coordinate (630, 233) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (11, 160) _rotation 0 variable id freq _enabled True value 1000 _coordinate (11, 237) _rotation 0 variable id ampl _enabled True value 1 _coordinate (13, 315) _rotation 0 blocks_throttle id blocks_throttle _enabled True type float samples_per_second samp_rate vlen 1 _coordinate (386, 93) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq freq amp ampl offset offset _coordinate (164, 154) _rotation 0 blocks_throttle wxgui_scopesink2 0 0 blocks_throttle wxgui_fftsink2 0 0 analog_sig_source_x_0 blocks_throttle 0 0 gnuradio-3.7.2.1/grc/examples/xmlrpc/xmlrpc_client_script.py0000664000175000017500000000076012207702530024024 0ustar jcorganjcorgan#!/usr/bin/env python import time import random import xmlrpclib #create server object s = xmlrpclib.Server("http://localhost:1234") #randomly change parameters of the sinusoid for i in range(10): #generate random values new_freq = random.uniform(0, 5000) new_ampl = random.uniform(0, 2) new_offset = random.uniform(-1, 1) #set new values time.sleep(1) s.set_freq(new_freq) time.sleep(1) s.set_ampl(new_ampl) time.sleep(1) s.set_offset(new_offset) gnuradio-3.7.2.1/grc/examples/xmlrpc/xmlrpc_client.grc0000644000175000017500000001376211744612271022576 0ustar jcorganjcorgan Thu Jul 24 14:27:44 2008 options id client_block _enabled True title XMLRPC Client author Example description example flow graph window_size 1280, 1024 generate_options wx_gui category Custom _coordinate (10, 10) _rotation 0 xmlrpc_client id xmlrpc_client0 _enabled True addr localhost port 1234 callback set_ampl variable ampl _coordinate (409, 35) _rotation 0 xmlrpc_client id xmlrpc_client _enabled True addr localhost port 1234 callback set_freq variable freq _coordinate (222, 34) _rotation 0 variable_slider id freq _enabled True label Frequency (Hz) value 1000 min 0 max 5000 num_steps 100 slider_type horizontal grid_pos 0, 0, 1, 2 _coordinate (207, 162) _rotation 0 variable_slider id ampl _enabled True label Amplitude value 1 min 0 max 2 num_steps 100 slider_type horizontal grid_pos 1, 0, 1, 2 _coordinate (397, 167) _rotation 0 variable_chooser id offset _enabled True label Offset value_index 1 choices [-1, 0, 1] labels ["neg", "zero", "pos"] chooser_type radio_buttons_horizontal grid_pos 2, 0, 1, 2 _coordinate (596, 177) _rotation 0 xmlrpc_client id xmlrpc_client1 _enabled True addr localhost port 1234 callback set_offset variable offset*ampl _coordinate (608, 39) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (13, 172) _rotation 0 gnuradio-3.7.2.1/grc/examples/xmlrpc/readme.txt0000644000175000017500000000157211744612271021230 0ustar jcorganjcorgan################################################## # XMLRPC example ################################################## XMLRPC allows software to make remote function calls over http. In the case of GRC, one can use XMLRPC to modify variables in a running flow graph. See http://www.xmlrpc.com/ --- Server Example --- Place an "XMLRPC Server" block inside of any flow graph. The server will provide set functions for every variable in the flow graph. If a variable is called "freq", the server will provide a function set_freq(new_freq). Run the server example and experiment with the example client script. -- Client Example -- The "XMLRPC Client" block will give a variable control over one remove function. In the example client, there is one client block and gui control per variable. This technique can be used to remotely control a flow graph, perhaps running on a non-gui machine. gnuradio-3.7.2.1/grc/blocks/0000755000175000017500000000000012237515112015351 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/blocks/CMakeLists.txt0000664000175000017500000000167412207440367020131 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "grc") gnuradio-3.7.2.1/grc/blocks/block_tree.xml0000664000175000017500000000174412207440367020222 0ustar jcorganjcorgan Misc pad_source pad_sink virtual_source virtual_sink note import blks2_selector blks2_valve blks2_error_rate xmlrpc_server xmlrpc_client Networking Tools blks2_tcp_source blks2_tcp_sink Packet Operators blks2_packet_decoder blks2_packet_encoder Variables variable variable_config variable_function_probe parameter gnuradio-3.7.2.1/grc/blocks/blks2_packet_decoder.xml0000644000175000017500000000301411700377701022126 0ustar jcorganjcorgan Packet Decoder blks2_packet_decoder from grc_gnuradio import blks2 as grc_blks2 grc_blks2.packet_demod_$(type.fcn)(grc_blks2.packet_decoder( access_code=$access_code, threshold=$threshold, callback=lambda ok, payload: self.$(id).recv_pkt(ok, payload), ), ) Output Type type float enum Access Code access_code string Threshold threshold -1 int in byte out $type Packet decoder block, for use with the gnuradio demodulator blocks: gmsk, psk, qam. Access Code: string of 1's and 0's, leave blank for automatic. Threshold: -1 for automatic. gnuradio-3.7.2.1/grc/blocks/import.xml0000664000175000017500000000102212207440367017410 0ustar jcorganjcorgan Import import $import Import import import Import additional python modules into the namespace. Examples: from gnuradio.filter import firdes import math,cmath from math import pi gnuradio-3.7.2.1/grc/blocks/note.xml0000644000175000017500000000050211700377701017041 0ustar jcorganjcorgan Note note Note note string gnuradio-3.7.2.1/grc/blocks/pad_sink.xml0000664000175000017500000000401012207702530017657 0ustar jcorganjcorgan Pad Sink pad_sink #if str($type) == "message" None;self.message_port_register_hier_in($label) #end if Label label out string Input Type type enum Vec Length vlen 1 int Num Streams num_streams 1 int Optional optional False bool part $vlen > 0 $num_streams > 0 in $type $vlen $num_streams The inputs of this block will become the outputs to this flow graph when it is instantiated as a hierarchical block. Pad sink will be ordered alphabetically by their ids. The first pad sink will have an index of 0. gnuradio-3.7.2.1/grc/blocks/parameter.xml0000644000175000017500000000416411700377701020064 0ustar jcorganjcorgan Parameter parameter self.$(id) = $(id) $value Label label string #if $label() then 'none' else 'part'# Value value 0 $type.type Type type enum #if $type() then 'none' else 'part'# Short ID short_id string #if not $type() all#slurp #elif $short_id() none#slurp #else part#slurp #end if len($short_id) in (0, 1) $short_id == '' or $(short_id).isalpha() This block represents a parameter to the flow graph. \ A parameter can be used to pass command line arguments into a top block. \ Or, parameters can pass arguments into an instantiated hierarchical block. The paramater value cannot depend on any variables. Leave the label blank to use the parameter id as the label. When type is not None, this parameter also becomes a command line option of the form: -[short_id] --[id] [value] The Short ID field may be left blank. gnuradio-3.7.2.1/grc/blocks/bus_structure_source.xml0000664000175000017500000000054312207702530022367 0ustar jcorganjcorgan Bus Source Structure bus_structure_source None Structure struct raw gnuradio-3.7.2.1/grc/blocks/blks2_valve.xml0000644000175000017500000000274211700377701020316 0ustar jcorganjcorgan Valve blks2_valve from grc_gnuradio import blks2 as grc_blks2 grc_blks2.valve(item_size=$type.size*$vlen, open=bool($open)) set_open(bool($open)) Type type enum Open open 0 raw Vec Length vlen 1 int $vlen > 0 in $type $vlen $num_inputs out $type $vlen $num_outputs Connect output to input when valve is closed (not open). gnuradio-3.7.2.1/grc/blocks/variable_function_probe.xml0000644000175000017500000000376011700377701022766 0ustar jcorganjcorgan Function Probe variable_function_probe import time import threading self.$(id) = $(id) = $value #slurp def _$(id)_probe(): while True: val = self.$(block_id()).$(function_name())($(function_args())) try: self.set_$(id)(val) except AttributeError, e: pass time.sleep(1.0/($poll_rate)) _$(id)_thread = threading.Thread(target=_$(id)_probe) _$(id)_thread.daemon = True _$(id)_thread.start() self.set_$(id)($value) Value value 0 raw Block ID block_id my_block_0 string Function Name function_name get_number string Function Args function_args string #if $function_args() then 'none' else 'part'# Poll Rate (Hz) poll_rate 10 real Periodically probe a function and set its value to this variable. Set the values for block ID, function name, and function args appropriately: \ Block ID should be the ID of another block in this flow graph. \ Function name should be the name of a class method on that block. \ Function args are the parameters passed into that function. \ For a function with no arguments, leave function args blank. \ When passing a string for the function arguments, quote the string literal: '"arg"'. The values will used literally, and generated into the following form: self.block_id.function_name(function_args) To poll a stream for a level, use this with the probe signal block. gnuradio-3.7.2.1/grc/blocks/bus_structure_sink.xml0000664000175000017500000000053712207702530022036 0ustar jcorganjcorgan Bus Sink Structure bus_structure_sink None Structure struct raw gnuradio-3.7.2.1/grc/blocks/blks2_packet_encoder.xml0000664000175000017500000000444712237515112022151 0ustar jcorganjcorgan Packet Encoder blks2_packet_encoder from grc_gnuradio import blks2 as grc_blks2 grc_blks2.packet_mod_$(type.fcn)(grc_blks2.packet_encoder( samples_per_symbol=$samples_per_symbol, bits_per_symbol=$bits_per_symbol, preamble=$preamble, access_code=$access_code, pad_for_usrp=$pad_for_usrp, ), payload_length=$payload_length, ) Input Type type float enum Samples/Symbol samples_per_symbol int Bits/Symbol bits_per_symbol int Preamble preamble string Access Code access_code string Pad for USRP pad_for_usrp enum Payload Length payload_length 0 int in $type out byte Packet encoder block, for use with the gnuradio modulator blocks: gmsk, dpsk, qam. Preamble: string of 1's and 0's, leave blank for automatic. Access Code: string of 1's and 0's, leave blank for automatic. Payload Length: 0 for automatic. Bits/Symbol should be set accordingly: gmsk -> 1 dbpsk -> 1 dqpsk -> 2 d8psk -> 3 qam8 -> 3 qam16 -> 4 qam64 -> 6 qam256 -> 8 gnuradio-3.7.2.1/grc/blocks/xmlrpc_server.xml0000644000175000017500000000215511700377701020775 0ustar jcorganjcorgan XMLRPC Server xmlrpc_server import SimpleXMLRPCServer import threading SimpleXMLRPCServer.SimpleXMLRPCServer(($addr, $port), allow_none=True) self.$(id).register_instance(self) threading.Thread(target=self.$(id).serve_forever).start() Address addr localhost string Port port 8080 int This block will start an XMLRPC server. \ The server provides access to the run, start, stop, wait functions of the flow graph. \ The server also provides access to the variable callbacks in the flow graph. \ Ex: If the variable is called freq, the function provided by the server will be called set_freq(new_freq). Example client in python: import xmlrpclib s = xmlrpclib.Server('http://localhost:8080') s.set_freq(5000) gnuradio-3.7.2.1/grc/blocks/blks2_selector.xml0000644000175000017500000000402311700377701021013 0ustar jcorganjcorgan Selector blks2_selector from grc_gnuradio import blks2 as grc_blks2 grc_blks2.selector( item_size=$type.size*$vlen, num_inputs=$num_inputs, num_outputs=$num_outputs, input_index=$input_index, output_index=$output_index, ) set_input_index(int($input_index)) set_output_index(int($output_index)) Type type enum Num Inputs num_inputs 2 int Num Outputs num_outputs 2 int Input Index input_index 0 int Output Index output_index 0 int Vec Length vlen 1 int $vlen > 0 in $type $vlen $num_inputs out $type $vlen $num_outputs Connect the sink at input index to the source at output index. Leave all other ports disconnected. gnuradio-3.7.2.1/grc/blocks/blks2_tcp_sink.xml0000644000175000017500000000343511700377701021013 0ustar jcorganjcorgan TCP Sink blks2_tcp_sink from grc_gnuradio import blks2 as grc_blks2 grc_blks2.tcp_sink( itemsize=$type.size*$vlen, addr=$addr, port=$port, server=$server, ) Input Type type enum Address addr 127.0.0.1 string Port port 0 int Mode server False enum Vec Length vlen 1 int $vlen > 0 in $type $vlen In client mode, we attempt to connect to a server at the given address and port. \ In server mode, we bind a socket to the given address and port and accept the first client. gnuradio-3.7.2.1/grc/blocks/blks2_tcp_source.xml0000644000175000017500000000345111700377701021345 0ustar jcorganjcorgan TCP Source blks2_tcp_source from grc_gnuradio import blks2 as grc_blks2 grc_blks2.tcp_source( itemsize=$type.size*$vlen, addr=$addr, port=$port, server=$server, ) Output Type type enum Address addr 127.0.0.1 string Port port 0 int Mode server True enum Vec Length vlen 1 int $vlen > 0 out $type $vlen In client mode, we attempt to connect to a server at the given address and port. \ In server mode, we bind a socket to the given address and port and accept the first client. gnuradio-3.7.2.1/grc/blocks/variable_config.xml0000644000175000017500000000422211700377701021211 0ustar jcorganjcorgan Variable Config variable_config import ConfigParser self._$(id)_config = ConfigParser.ConfigParser() self._$(id)_config.read($config_file) try: $(id) = self._$(id)_config.$(type.get)($section, $option) except: $(id) = $value self.$(id) = $(id) self.set_$(id)($value) self._$(id)_config = ConfigParser.ConfigParser() self._$(id)_config.read($config_file) if not self._$(id)_config.has_section($section): self._$(id)_config.add_section($section) self._$(id)_config.set($section, $option, str($writeback)) self._$(id)_config.write(open($config_file, 'w')) Default Value value 0 $type Type type real enum Config File config_file default file_open Section section main string Option option key string WriteBack writeback None raw This block represents a variable that can be read from a config file. To save the value back into the config file: \ enter the name of another variable into the writeback param. \ When the other variable is changed at runtime, the config file will be re-written. gnuradio-3.7.2.1/grc/blocks/options.xml0000664000175000017500000001107212207440367017577 0ustar jcorganjcorgan Options options from gnuradio import gr from gnuradio.filter import firdes #if $generate_options() == 'wx_gui' from grc_gnuradio import wxgui as grc_wxgui import wx #end if #if $generate_options() == 'qt_gui' from PyQt4 import Qt import sys #end if #if $generate_options() != 'hb' from optparse import OptionParser from gnuradio.eng_option import eng_option from gnuradio import eng_notation #end if if $run: self.start() else: self.stop(); self.wait() Title title string #if $title() then 'none' else 'part'# Author author string #if $author() then 'none' else 'part'# Description description string #if $description() then 'none' else 'part'# Window Size window_size 1280, 1024 int_vector part Generate Options generate_options wx_gui enum Category category Custom string #if $generate_options() == 'hb' then 'none' else 'all'# Run Options run_options prompt enum #if $generate_options() == 'no_gui' then 'none' else 'all'# Run run True bool #if $generate_options() in ('qt_gui', 'wx_gui') #if $run() part #else none #end if #else all #end if Max Number of Output max_nouts 0 int #if $generate_options() == 'hb' all#slurp #elif $max_nouts() none#slurp #else part#slurp #end if Realtime Scheduling realtime_scheduling enum #if $generate_options() == 'hb' all#slurp #elif $realtime_scheduling() none#slurp #else part#slurp #end if len($window_size) == 2 300 <= $(window_size)[0] <= 4096 300 <= $(window_size)[1] <= 4096 The options block sets special parameters for the flow graph. \ Only one option block is allowed per flow graph. Title, author, and description parameters are for identification purposes. The window size controls the dimensions of the flow graph editor. \ The window size (width, height) must be between (300, 300) and (4096, 4096). The generate options controls the type of code generated. \ Non-graphical flow graphs should avoid using graphical sinks or graphical variable controls. In a graphical application, \ run can be controlled by a variable to start and stop the flowgraph at runtime. The id of this block determines the name of the generated file and the name of the class. \ For example, an id of my_block will generate the file my_block.py and class my_block(gr.... The category parameter determines the placement of the block in the block selection window. \ The category only applies when creating hier blocks. \ To put hier blocks into the root category, enter / for the category. The Max Number of Output is the maximum number of output items allowed for any block \ in the flowgraph; to disable this set the max_nouts equal to 0.\ Use this to adjust the maximum latency a flowgraph can exhibit. gnuradio-3.7.2.1/grc/blocks/virtual_source.xml0000644000175000017500000000062711700377701021152 0ustar jcorganjcorgan Virtual Source virtual_source Stream ID stream_id stream_id out gnuradio-3.7.2.1/grc/blocks/virtual_sink.xml0000644000175000017500000000061411700377701020612 0ustar jcorganjcorgan Virtual Sink virtual_sink Stream ID stream_id stream_id in gnuradio-3.7.2.1/grc/blocks/variable.xml0000644000175000017500000000107111700377701017663 0ustar jcorganjcorgan Variable variable self.$(id) = $(id) = $value self.set_$(id)($value) Value value 0 raw This block maps a value to a unique variable. \ This variable block has no graphical representation. gnuradio-3.7.2.1/grc/blocks/pad_source.xml0000664000175000017500000000403312207702530020220 0ustar jcorganjcorgan Pad Source pad_source #if str($type) == "message" None;self.message_port_register_hier_out($label) #end if Label label in string Output Type type enum Vec Length vlen 1 int Num Streams num_streams 1 int Optional optional False bool part $vlen > 0 $num_streams > 0 out $type $vlen $num_streams The outputs of this block will become the inputs to this flow graph when it is instantiated as a hierarchical block. Pad sources will be ordered alphabetically by their ids. The first pad source will have an index of 0. gnuradio-3.7.2.1/grc/blocks/bus_sink.xml0000664000175000017500000000075412207702530017717 0ustar jcorganjcorgan Bus Sink bus_sink $yesno.yesno On/Off yesno enum gnuradio-3.7.2.1/grc/blocks/xmlrpc_client.xml0000644000175000017500000000206411700377701020744 0ustar jcorganjcorgan XMLRPC Client xmlrpc_client import xmlrpclib xmlrpclib.Server('http://$(addr()):$(port)') $(callback())($variable) Address addr localhost string Port port 8080 int Callback callback set_ string Variable variable raw This block will create an XMLRPC client. \ The client will execute the callback on the server when the variable is changed. \ The callback should be a the name of a function registered on the server. \ The variable should be an expression containing a the name of a variable in flow graph. gnuradio-3.7.2.1/grc/blocks/bus_source.xml0000664000175000017500000000076012207702530020250 0ustar jcorganjcorgan Bus Source bus_source $yesno.yesno On/Off yesno enum gnuradio-3.7.2.1/grc/blocks/blks2_error_rate.xml0000644000175000017500000000342511700377701021344 0ustar jcorganjcorgan Error Rate blks2_error_rate from grc_gnuradio import blks2 as grc_blks2 grc_blks2.error_rate( type=$type, win_size=$win_size, bits_per_symbol=$bits_per_symbol, ) Type type enum Window Size win_size 1000 int Bits per Symbol bits_per_symbol 2 int $type.hide_bps ref byte in byte out float Calculate the bit error rate (BER) or the symbol error rate (SER) over a number of samples given by the window size. \ The actual window size will start at size one and grow to the full window size as new samples arrive. \ Once the window has reached full size, old samples are shifted out of the window and new samples shfited in. The error block compares the input byte stream to the reference byte stream. \ For example, the reference byte stream could be the input to a modulator, \ and the input byte stream could be the output of a modulator. Each byte in the incoming stream represents one symbol. \ The bits per symbol parameter is only useful for calculating the BER. gnuradio-3.7.2.1/grc/gui/0000755000175000017500000000000012245466767014704 5ustar jcorganjcorgangnuradio-3.7.2.1/grc/gui/Platform.py0000664000175000017500000000157112207702530017023 0ustar jcorganjcorgan""" Copyright 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Element import Element class Platform(Element): def __init__(self): Element.__init__(self) gnuradio-3.7.2.1/grc/gui/Port.py0000664000175000017500000001776012207702530016172 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Element import Element from Constants import \ PORT_SEPARATION, CONNECTOR_EXTENSION_MINIMAL, \ CONNECTOR_EXTENSION_INCREMENT, \ PORT_LABEL_PADDING, PORT_MIN_WIDTH import Utils import Colors import pygtk pygtk.require('2.0') import gtk PORT_MARKUP_TMPL="""\ $encode($port.get_name())""" class Port(Element): """The graphical port.""" def __init__(self): """ Port contructor. Create list of connector coordinates. """ Element.__init__(self) self.connector_coordinates = dict() def create_shapes(self): """Create new areas and labels for the port.""" Element.create_shapes(self) #get current rotation rotation = self.get_rotation() #get all sibling ports if self.is_source(): ports = self.get_parent().get_sources_gui() elif self.is_sink(): ports = self.get_parent().get_sinks_gui() #get the max width self.W = max([port.W for port in ports] + [PORT_MIN_WIDTH]) #get a numeric index for this port relative to its sibling ports try: index = ports.index(self) except: if hasattr(self, '_connector_length'): del self._connector_length; return length = len(ports) #reverse the order of ports for these rotations if rotation in (180, 270): index = length-index-1 offset = (self.get_parent().H - length*self.H - (length-1)*PORT_SEPARATION)/2 #create areas and connector coordinates if (self.is_sink() and rotation == 0) or (self.is_source() and rotation == 180): x = -1*self.W y = (PORT_SEPARATION+self.H)*index+offset self.add_area((x, y), (self.W, self.H)) self._connector_coordinate = (x-1, y+self.H/2) elif (self.is_source() and rotation == 0) or (self.is_sink() and rotation == 180): x = self.get_parent().W y = (PORT_SEPARATION+self.H)*index+offset self.add_area((x, y), (self.W, self.H)) self._connector_coordinate = (x+1+self.W, y+self.H/2) elif (self.is_source() and rotation == 90) or (self.is_sink() and rotation == 270): y = -1*self.W x = (PORT_SEPARATION+self.H)*index+offset self.add_area((x, y), (self.H, self.W)) self._connector_coordinate = (x+self.H/2, y-1) elif (self.is_sink() and rotation == 90) or (self.is_source() and rotation == 270): y = self.get_parent().W x = (PORT_SEPARATION+self.H)*index+offset self.add_area((x, y), (self.H, self.W)) self._connector_coordinate = (x+self.H/2, y+1+self.W) #the connector length self._connector_length = CONNECTOR_EXTENSION_MINIMAL + CONNECTOR_EXTENSION_INCREMENT*index def modify_height(self, start_height): type_dict = {'bus':(lambda a: a * 3)}; if self.get_type() in type_dict: return type_dict[self.get_type()](start_height); else: return start_height; def create_labels(self): """Create the labels for the socket.""" Element.create_labels(self) self._bg_color = Colors.get_color(self.get_color()) #create the layout layout = gtk.DrawingArea().create_pango_layout('') layout.set_markup(Utils.parse_template(PORT_MARKUP_TMPL, port=self)) self.w, self.h = layout.get_pixel_size() self.W, self.H = 2*PORT_LABEL_PADDING+self.w, 2*PORT_LABEL_PADDING+self.h self.H = self.modify_height(self.H); #create the pixmap pixmap = self.get_parent().get_parent().new_pixmap(self.w, self.h) gc = pixmap.new_gc() gc.set_foreground(self._bg_color) pixmap.draw_rectangle(gc, True, 0, 0, self.w, self.h) pixmap.draw_layout(gc, 0, 0, layout) #create vertical and horizontal pixmaps self.horizontal_label = pixmap if self.is_vertical(): self.vertical_label = self.get_parent().get_parent().new_pixmap(self.h, self.w) Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label) def draw(self, gc, window): """ Draw the socket with a label. Args: gc: the graphics context window: the gtk window to draw on """ Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR or Colors.BORDER_COLOR, ) X,Y = self.get_coordinate() (x,y),(w,h) = self._areas_list[0] #use the first area's sizes to place the labels if self.is_horizontal(): window.draw_drawable(gc, self.horizontal_label, 0, 0, x+X+(self.W-self.w)/2, y+Y+(self.H-self.h)/2, -1, -1) elif self.is_vertical(): window.draw_drawable(gc, self.vertical_label, 0, 0, x+X+(self.H-self.h)/2, y+Y+(self.W-self.w)/2, -1, -1) def get_connector_coordinate(self): """ Get the coordinate where connections may attach to. Returns: the connector coordinate (x, y) tuple """ x,y = self._connector_coordinate X,Y = self.get_coordinate() return (x+X, y+Y) def get_connector_direction(self): """ Get the direction that the socket points: 0,90,180,270. This is the rotation degree if the socket is an output or the rotation degree + 180 if the socket is an input. Returns: the direction in degrees """ if self.is_source(): return self.get_rotation() elif self.is_sink(): return (self.get_rotation() + 180)%360 def get_connector_length(self): """ Get the length of the connector. The connector length increases as the port index changes. Returns: the length in pixels """ return self._connector_length def get_rotation(self): """ Get the parent's rotation rather than self. Returns: the parent's rotation """ return self.get_parent().get_rotation() def move(self, delta_coor): """ Move the parent rather than self. Args: delta_corr: the (delta_x, delta_y) tuple """ self.get_parent().move(delta_coor) def rotate(self, direction): """ Rotate the parent rather than self. Args: direction: degrees to rotate """ self.get_parent().rotate(direction) def get_coordinate(self): """ Get the parent's coordinate rather than self. Returns: the parents coordinate """ return self.get_parent().get_coordinate() def set_highlighted(self, highlight): """ Set the parent highlight rather than self. Args: highlight: true to enable highlighting """ self.get_parent().set_highlighted(highlight) def is_highlighted(self): """ Get the parent's is highlight rather than self. Returns: the parent's highlighting status """ return self.get_parent().is_highlighted() gnuradio-3.7.2.1/grc/gui/NotebookPage.py0000664000175000017500000001417112207702530017614 0ustar jcorganjcorgan""" Copyright 2008, 2009, 2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk import Actions from StateCache import StateCache from Constants import MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT from DrawingArea import DrawingArea import os ############################################################ ## Notebook Page ############################################################ class NotebookPage(gtk.HBox): """A page in the notebook.""" def __init__(self, main_window, flow_graph, file_path=''): """ Page constructor. Args: main_window: main window file_path: path to a flow graph file """ self._flow_graph = flow_graph self.set_proc(None) #import the file self.main_window = main_window self.set_file_path(file_path) initial_state = flow_graph.get_parent().parse_flow_graph(file_path) self.state_cache = StateCache(initial_state) self.set_saved(True) #import the data to the flow graph self.get_flow_graph().import_data(initial_state) #initialize page gui gtk.HBox.__init__(self, False, 0) self.show() #tab box to hold label and close button self.tab = gtk.HBox(False, 0) #setup tab label self.label = gtk.Label() self.tab.pack_start(self.label, False) #setup button image image = gtk.Image() image.set_from_stock('gtk-close', gtk.ICON_SIZE_MENU) #setup image box image_box = gtk.HBox(False, 0) image_box.pack_start(image, True, False, 0) #setup the button button = gtk.Button() button.connect("clicked", self._handle_button) button.set_relief(gtk.RELIEF_NONE) button.add(image_box) #button size w, h = gtk.icon_size_lookup_for_settings(button.get_settings(), gtk.ICON_SIZE_MENU) button.set_size_request(w+6, h+6) self.tab.pack_start(button, False) self.tab.show_all() #setup scroll window and drawing area self.scrolled_window = gtk.ScrolledWindow() self.scrolled_window.set_size_request(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT) self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.drawing_area = DrawingArea(self.get_flow_graph()) self.scrolled_window.add_with_viewport(self.get_drawing_area()) self.pack_start(self.scrolled_window) #inject drawing area into flow graph self.get_flow_graph().drawing_area = self.get_drawing_area() self.show_all() def get_drawing_area(self): return self.drawing_area def get_generator(self): """ Get the generator object for this flow graph. Returns: generator """ return self.get_flow_graph().get_parent().get_generator()( self.get_flow_graph(), self.get_file_path(), ) def _handle_button(self, button): """ The button was clicked. Make the current page selected, then close. Args: the: button """ self.main_window.page_to_be_closed = self Actions.FLOW_GRAPH_CLOSE() def set_markup(self, markup): """ Set the markup in this label. Args: markup: the new markup text """ self.label.set_markup(markup) def get_tab(self): """ Get the gtk widget for this page's tab. Returns: gtk widget """ return self.tab def get_proc(self): """ Get the subprocess for the flow graph. Returns: the subprocess object """ return self.process def set_proc(self, process): """ Set the subprocess object. Args: process: the new subprocess """ self.process = process def get_flow_graph(self): """ Get the flow graph. Returns: the flow graph """ return self._flow_graph def get_read_only(self): """ Get the read-only state of the file. Always false for empty path. Returns: true for read-only """ if not self.get_file_path(): return False return os.path.exists(self.get_file_path()) and \ not os.access(self.get_file_path(), os.W_OK) def get_file_path(self): """ Get the file path for the flow graph. Returns: the file path or '' """ return self.file_path def set_file_path(self, file_path=''): """ Set the file path, '' for no file path. Args: file_path: file path string """ if file_path: self.file_path = os.path.abspath(file_path) else: self.file_path = '' def get_saved(self): """ Get the saved status for the flow graph. Returns: true if saved """ return self.saved def set_saved(self, saved=True): """ Set the saved status. Args: saved: boolean status """ self.saved = saved def get_state_cache(self): """ Get the state cache for the flow graph. Returns: the state cache """ return self.state_cache gnuradio-3.7.2.1/grc/gui/CMakeLists.txt0000644000175000017500000000250211700377701017423 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## GR_PYTHON_INSTALL(FILES Block.py Colors.py Constants.py Connection.py Element.py FlowGraph.py Param.py Platform.py Port.py Utils.py ActionHandler.py Actions.py Bars.py BlockTreeWindow.py Dialogs.py DrawingArea.py FileDialogs.py MainWindow.py Messages.py NotebookPage.py PropsDialog.py Preferences.py StateCache.py __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/grc/gui COMPONENT "grc" ) gnuradio-3.7.2.1/grc/gui/Constants.py0000644000175000017500000000454711700377701017224 0ustar jcorganjcorgan""" Copyright 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk import os ##default path for the open/save dialogs DEFAULT_FILE_PATH = os.getcwd() ##file extensions IMAGE_FILE_EXTENSION = '.png' ##name for new/unsaved flow graphs NEW_FLOGRAPH_TITLE = 'untitled' ##main window constraints MIN_WINDOW_WIDTH = 600 MIN_WINDOW_HEIGHT = 400 ##dialog constraints MIN_DIALOG_WIDTH = 500 MIN_DIALOG_HEIGHT = 500 ##default sizes DEFAULT_BLOCKS_WINDOW_WIDTH = 100 DEFAULT_REPORTS_WINDOW_WIDTH = 100 ##The size of the state saving cache in the flow graph (for undo/redo functionality) STATE_CACHE_SIZE = 42 ##Shared targets for drag and drop of blocks DND_TARGETS = [('STRING', gtk.TARGET_SAME_APP, 0)] #label constraint dimensions LABEL_SEPARATION = 3 BLOCK_LABEL_PADDING = 7 PORT_LABEL_PADDING = 2 #port constraint dimensions PORT_SEPARATION = 17 PORT_BORDER_SEPARATION = 9 PORT_MIN_WIDTH = 20 #minimal length of connector CONNECTOR_EXTENSION_MINIMAL = 11 #increment length for connector CONNECTOR_EXTENSION_INCREMENT = 11 #connection arrow dimensions CONNECTOR_ARROW_BASE = 13 CONNECTOR_ARROW_HEIGHT = 17 #possible rotations in degrees POSSIBLE_ROTATIONS = (0, 90, 180, 270) #How close can the mouse get to the window border before mouse events are ignored. BORDER_PROXIMITY_SENSITIVITY = 50 #How close the mouse can get to the edge of the visible window before scrolling is invoked. SCROLL_PROXIMITY_SENSITIVITY = 30 #When the window has to be scrolled, move it this distance in the required direction. SCROLL_DISTANCE = 15 #How close the mouse click can be to a line and register a connection select. LINE_SELECT_SENSITIVITY = 5 gnuradio-3.7.2.1/grc/gui/FileDialogs.py0000664000175000017500000001676212207702530017431 0ustar jcorganjcorgan""" Copyright 2007 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk from Dialogs import MessageDialogHelper from Constants import \ DEFAULT_FILE_PATH, IMAGE_FILE_EXTENSION, \ NEW_FLOGRAPH_TITLE import Preferences from os import path import Utils ################################################## # Constants ################################################## OPEN_FLOW_GRAPH = 'open flow graph' SAVE_FLOW_GRAPH = 'save flow graph' SAVE_IMAGE = 'save image' FILE_OVERWRITE_MARKUP_TMPL="""\ File $encode($filename) Exists!\nWould you like to overwrite the existing file?""" FILE_DNE_MARKUP_TMPL="""\ File $encode($filename) Does not Exist!""" ################################################## # File Filters ################################################## ##the filter for flow graph files def get_flow_graph_files_filter(): filter = gtk.FileFilter() filter.set_name('Flow Graph Files') filter.add_pattern('*'+Preferences.file_extension()) return filter ##the filter for image files def get_image_files_filter(): filter = gtk.FileFilter() filter.set_name('Image Files') filter.add_pattern('*'+IMAGE_FILE_EXTENSION) return filter ##the filter for all files def get_all_files_filter(): filter = gtk.FileFilter() filter.set_name('All Files') filter.add_pattern('*') return filter ################################################## # File Dialogs ################################################## class FileDialogHelper(gtk.FileChooserDialog): """ A wrapper class for the gtk file chooser dialog. Implement a file chooser dialog with only necessary parameters. """ def __init__(self, action, title): """ FileDialogHelper contructor. Create a save or open dialog with cancel and ok buttons. Use standard settings: no multiple selection, local files only, and the * filter. Args: action: gtk.FILE_CHOOSER_ACTION_OPEN or gtk.FILE_CHOOSER_ACTION_SAVE title: the title of the dialog (string) """ ok_stock = {gtk.FILE_CHOOSER_ACTION_OPEN : 'gtk-open', gtk.FILE_CHOOSER_ACTION_SAVE : 'gtk-save'}[action] gtk.FileChooserDialog.__init__(self, title, None, action, ('gtk-cancel', gtk.RESPONSE_CANCEL, ok_stock, gtk.RESPONSE_OK)) self.set_select_multiple(False) self.set_local_only(True) self.add_filter(get_all_files_filter()) class FileDialog(FileDialogHelper): """A dialog box to save or open flow graph files. This is a base class, do not use.""" def __init__(self, current_file_path=''): """ FileDialog constructor. Args: current_file_path: the current directory or path to the open flow graph """ if not current_file_path: current_file_path = path.join(DEFAULT_FILE_PATH, NEW_FLOGRAPH_TITLE + Preferences.file_extension()) if self.type == OPEN_FLOW_GRAPH: FileDialogHelper.__init__(self, gtk.FILE_CHOOSER_ACTION_OPEN, 'Open a Flow Graph from a File...') self.add_and_set_filter(get_flow_graph_files_filter()) self.set_select_multiple(True) elif self.type == SAVE_FLOW_GRAPH: FileDialogHelper.__init__(self, gtk.FILE_CHOOSER_ACTION_SAVE, 'Save a Flow Graph to a File...') self.add_and_set_filter(get_flow_graph_files_filter()) self.set_current_name(path.basename(current_file_path)) #show the current filename elif self.type == SAVE_IMAGE: FileDialogHelper.__init__(self, gtk.FILE_CHOOSER_ACTION_SAVE, 'Save a Flow Graph Screen Shot...') self.add_and_set_filter(get_image_files_filter()) current_file_path = current_file_path + IMAGE_FILE_EXTENSION self.set_current_name(path.basename(current_file_path)) #show the current filename self.set_current_folder(path.dirname(current_file_path)) #current directory def add_and_set_filter(self, filter): """ Add the gtk file filter to the list of filters and set it as the default file filter. Args: filter: a gtk file filter. """ self.add_filter(filter) self.set_filter(filter) def get_rectified_filename(self): """ Run the dialog and get the filename. If this is a save dialog and the file name is missing the extension, append the file extension. If the file name with the extension already exists, show a overwrite dialog. If this is an open dialog, return a list of filenames. Returns: the complete file path """ if gtk.FileChooserDialog.run(self) != gtk.RESPONSE_OK: return None #response was cancel ############################################# # Handle Save Dialogs ############################################# if self.type in (SAVE_FLOW_GRAPH, SAVE_IMAGE): filename = self.get_filename() extension = { SAVE_FLOW_GRAPH: Preferences.file_extension(), SAVE_IMAGE: IMAGE_FILE_EXTENSION, }[self.type] #append the missing file extension if the filter matches if path.splitext(filename)[1].lower() != extension: filename += extension self.set_current_name(path.basename(filename)) #show the filename with extension if path.exists(filename): #ask the user to confirm overwrite if MessageDialogHelper( gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, 'Confirm Overwrite!', Utils.parse_template(FILE_OVERWRITE_MARKUP_TMPL, filename=filename), ) == gtk.RESPONSE_NO: return self.get_rectified_filename() return filename ############################################# # Handle Open Dialogs ############################################# elif self.type in (OPEN_FLOW_GRAPH,): filenames = self.get_filenames() for filename in filenames: if not path.exists(filename): #show a warning and re-run MessageDialogHelper( gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, 'Cannot Open!', Utils.parse_template(FILE_DNE_MARKUP_TMPL, filename=filename), ) return self.get_rectified_filename() return filenames def run(self): """ Get the filename and destroy the dialog. Returns: the filename or None if a close/cancel occured. """ filename = self.get_rectified_filename() self.destroy() return filename class OpenFlowGraphFileDialog(FileDialog): type = OPEN_FLOW_GRAPH class SaveFlowGraphFileDialog(FileDialog): type = SAVE_FLOW_GRAPH class SaveImageFileDialog(FileDialog): type = SAVE_IMAGE gnuradio-3.7.2.1/grc/gui/DrawingArea.py0000664000175000017500000001354412244173003017424 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009, 2010 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk from Constants import MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT, DND_TARGETS class DrawingArea(gtk.DrawingArea): """ DrawingArea is the gtk pixel map that graphical elements may draw themselves on. The drawing area also responds to mouse and key events. """ def __init__(self, flow_graph): """ DrawingArea contructor. Connect event handlers. Args: main_window: the main_window containing all flow graphs """ self.ctrl_mask = False self._flow_graph = flow_graph gtk.DrawingArea.__init__(self) self.set_size_request(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT) self.connect('realize', self._handle_window_realize) self.connect('configure-event', self._handle_window_configure) self.connect('expose-event', self._handle_window_expose) self.connect('motion-notify-event', self._handle_mouse_motion) self.connect('button-press-event', self._handle_mouse_button_press) self.connect('button-release-event', self._handle_mouse_button_release) self.add_events( gtk.gdk.BUTTON_PRESS_MASK | \ gtk.gdk.POINTER_MOTION_MASK | \ gtk.gdk.BUTTON_RELEASE_MASK | \ gtk.gdk.LEAVE_NOTIFY_MASK | \ gtk.gdk.ENTER_NOTIFY_MASK | \ gtk.gdk.FOCUS_CHANGE_MASK ) #setup drag and drop self.drag_dest_set(gtk.DEST_DEFAULT_ALL, DND_TARGETS, gtk.gdk.ACTION_COPY) self.connect('drag-data-received', self._handle_drag_data_received) #setup the focus flag self._focus_flag = False self.get_focus_flag = lambda: self._focus_flag def _handle_notify_event(widget, event, focus_flag): self._focus_flag = focus_flag self.connect('leave-notify-event', _handle_notify_event, False) self.connect('enter-notify-event', _handle_notify_event, True) self.set_can_focus(True) self.connect('focus-out-event', self._handle_focus_lost_event) def new_pixmap(self, width, height): return gtk.gdk.Pixmap(self.window, width, height, -1) def get_pixbuf(self): width, height = self._pixmap.get_size() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8, width, height) pixbuf.get_from_drawable(self._pixmap, self._pixmap.get_colormap(), 0, 0, 0, 0, width, height) return pixbuf ########################################################################## ## Handlers ########################################################################## def _handle_drag_data_received(self, widget, drag_context, x, y, selection_data, info, time): """ Handle a drag and drop by adding a block at the given coordinate. """ self._flow_graph.add_new_block(selection_data.data, (x, y)) def _handle_mouse_button_press(self, widget, event): """ Forward button click information to the flow graph. """ self.grab_focus() self.ctrl_mask = event.state & gtk.gdk.CONTROL_MASK if event.button == 1: self._flow_graph.handle_mouse_selector_press( double_click=(event.type == gtk.gdk._2BUTTON_PRESS), coordinate=(event.x, event.y), ) if event.button == 3: self._flow_graph.handle_mouse_context_press( coordinate=(event.x, event.y), event=event, ) def _handle_mouse_button_release(self, widget, event): """ Forward button release information to the flow graph. """ self.ctrl_mask = event.state & gtk.gdk.CONTROL_MASK if event.button == 1: self._flow_graph.handle_mouse_selector_release( coordinate=(event.x, event.y), ) def _handle_mouse_motion(self, widget, event): """ Forward mouse motion information to the flow graph. """ self.ctrl_mask = event.state & gtk.gdk.CONTROL_MASK self._flow_graph.handle_mouse_motion( coordinate=(event.x, event.y), ) def _handle_window_realize(self, widget): """ Called when the window is realized. Update the flowgraph, which calls new pixmap. """ self._flow_graph.update() def _handle_window_configure(self, widget, event): """ Called when the window is resized. Create a new pixmap for background buffer. """ self._pixmap = self.new_pixmap(*self.get_size_request()) def _handle_window_expose(self, widget, event): """ Called when window is exposed, or queue_draw is called. Double buffering: draw to pixmap, then draw pixmap to window. """ gc = self.window.new_gc() self._flow_graph.draw(gc, self._pixmap) self.window.draw_drawable(gc, self._pixmap, 0, 0, 0, 0, -1, -1) def _handle_focus_lost_event(self, widget, event): # don't clear selection while context menu is active if self._flow_graph.get_context_menu().get_visible(): return self._flow_graph.unselect() self._flow_graph.update_selected() self._flow_graph.queue_draw() gnuradio-3.7.2.1/grc/gui/Utils.py0000664000175000017500000000674212207702530016344 0ustar jcorganjcorgan""" Copyright 2008-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Constants import POSSIBLE_ROTATIONS from Cheetah.Template import Template import pygtk pygtk.require('2.0') import gtk import gobject def rotate_pixmap(gc, src_pixmap, dst_pixmap, angle=gtk.gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE): """ Load the destination pixmap with a rotated version of the source pixmap. The source pixmap will be loaded into a pixbuf, rotated, and drawn to the destination pixmap. The pixbuf is a client-side drawable, where a pixmap is a server-side drawable. Args: gc: the graphics context src_pixmap: the source pixmap dst_pixmap: the destination pixmap angle: the angle to rotate by """ width, height = src_pixmap.get_size() pixbuf = gtk.gdk.Pixbuf( colorspace=gtk.gdk.COLORSPACE_RGB, has_alpha=False, bits_per_sample=8, width=width, height=height, ) pixbuf.get_from_drawable(src_pixmap, src_pixmap.get_colormap(), 0, 0, 0, 0, -1, -1) pixbuf = pixbuf.rotate_simple(angle) dst_pixmap.draw_pixbuf(gc, pixbuf, 0, 0, 0, 0) def get_rotated_coordinate(coor, rotation): """ Rotate the coordinate by the given rotation. Args: coor: the coordinate x, y tuple rotation: the angle in degrees Returns: the rotated coordinates """ #handles negative angles rotation = (rotation + 360)%360 if rotation not in POSSIBLE_ROTATIONS: raise ValueError('unusable rotation angle "%s"'%str(rotation)) #determine the number of degrees to rotate cos_r, sin_r = { 0: (1, 0), 90: (0, 1), 180: (-1, 0), 270: (0, -1), }[rotation] x, y = coor return (x*cos_r + y*sin_r, -x*sin_r + y*cos_r) def get_angle_from_coordinates((x1,y1), (x2,y2)): """ Given two points, calculate the vector direction from point1 to point2, directions are multiples of 90 degrees. Args: (x1,y1): the coordinate of point 1 (x2,y2): the coordinate of point 2 Returns: the direction in degrees """ if y1 == y2:#0 or 180 if x2 > x1: return 0 else: return 180 else:#90 or 270 if y2 > y1: return 270 else: return 90 def parse_template(tmpl_str, **kwargs): """ Parse the template string with the given args. Pass in the xml encode method for pango escape chars. Args: tmpl_str: the template as a string Returns: a string of the parsed template """ kwargs['encode'] = gobject.markup_escape_text #try: # cat = str(Template(tmpl_str, kwargs)) #except TypeError: # print 'guppy' # print tmpl_str # print str(kwargs['param'].get_error_messages()) return str(Template(tmpl_str, kwargs)) gnuradio-3.7.2.1/grc/gui/Bars.py0000664000175000017500000001121112245466767016143 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import Actions import pygtk pygtk.require('2.0') import gtk ##The list of actions for the toolbar. TOOLBAR_LIST = ( Actions.FLOW_GRAPH_NEW, Actions.FLOW_GRAPH_OPEN, Actions.FLOW_GRAPH_SAVE, Actions.FLOW_GRAPH_CLOSE, None, Actions.FLOW_GRAPH_SCREEN_CAPTURE, None, Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE, None, Actions.FLOW_GRAPH_UNDO, Actions.FLOW_GRAPH_REDO, None, Actions.ERRORS_WINDOW_DISPLAY, Actions.FLOW_GRAPH_GEN, Actions.FLOW_GRAPH_EXEC, Actions.FLOW_GRAPH_KILL, None, Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, None, Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, None, Actions.FIND_BLOCKS, Actions.RELOAD_BLOCKS, Actions.OPEN_HIER, Actions.BUSSIFY_SOURCES, ) ##The list of actions and categories for the menu bar. MENU_BAR_LIST = ( (gtk.Action('File', '_File', None, None), [ Actions.FLOW_GRAPH_NEW, Actions.FLOW_GRAPH_OPEN, None, Actions.FLOW_GRAPH_SAVE, Actions.FLOW_GRAPH_SAVE_AS, None, Actions.FLOW_GRAPH_SCREEN_CAPTURE, None, Actions.FLOW_GRAPH_CLOSE, Actions.APPLICATION_QUIT, ]), (gtk.Action('Edit', '_Edit', None, None), [ Actions.FLOW_GRAPH_UNDO, Actions.FLOW_GRAPH_REDO, None, Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE, None, Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, None, Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, None, Actions.BLOCK_PARAM_MODIFY, ]), (gtk.Action('View', '_View', None, None), [ Actions.ERRORS_WINDOW_DISPLAY, Actions.FIND_BLOCKS, ]), (gtk.Action('Build', '_Build', None, None), [ Actions.FLOW_GRAPH_GEN, Actions.FLOW_GRAPH_EXEC, Actions.FLOW_GRAPH_KILL, ]), (gtk.Action('Help', '_Help', None, None), [ Actions.HELP_WINDOW_DISPLAY, Actions.TYPES_WINDOW_DISPLAY, None, Actions.ABOUT_WINDOW_DISPLAY, ]), ) class Toolbar(gtk.Toolbar): """The gtk toolbar with actions added from the toolbar list.""" def __init__(self): """ Parse the list of action names in the toolbar list. Look up the action for each name in the action list and add it to the toolbar. """ gtk.Toolbar.__init__(self) self.set_style(gtk.TOOLBAR_ICONS) for action in TOOLBAR_LIST: if action: #add a tool item self.add(action.create_tool_item()) #this reset of the tooltip property is required (after creating the tool item) for the tooltip to show action.set_property('tooltip', action.get_property('tooltip')) else: self.add(gtk.SeparatorToolItem()) class MenuBar(gtk.MenuBar): """The gtk menu bar with actions added from the menu bar list.""" def __init__(self): """ Parse the list of submenus from the menubar list. For each submenu, get a list of action names. Look up the action for each name in the action list and add it to the submenu. Add the submenu to the menu bar. """ gtk.MenuBar.__init__(self) for main_action, actions in MENU_BAR_LIST: #create the main menu item main_menu_item = main_action.create_menu_item() self.append(main_menu_item) #create the menu main_menu = gtk.Menu() main_menu_item.set_submenu(main_menu) for action in actions: if action: #append a menu item main_menu.append(action.create_menu_item()) else: main_menu.append(gtk.SeparatorMenuItem()) main_menu.show_all() #this show all is required for the separators to show gnuradio-3.7.2.1/grc/gui/PropsDialog.py0000664000175000017500000001525012207702530017461 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk from Dialogs import TextDisplay from Constants import MIN_DIALOG_WIDTH, MIN_DIALOG_HEIGHT def get_title_label(title): """ Get a title label for the params window. The title will be bold, underlined, and left justified. Args: title: the text of the title Returns: a gtk object """ label = gtk.Label() label.set_markup('\n%s:\n'%title) hbox = gtk.HBox() hbox.pack_start(label, False, False, padding=11) return hbox class PropsDialog(gtk.Dialog): """ A dialog to set block parameters, view errors, and view documentation. """ def __init__(self, block): """ Properties dialog contructor. Args: block: a block instance """ self._hash = 0 LABEL_SPACING = 7 gtk.Dialog.__init__(self, title='Properties: %s'%block.get_name(), buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT), ) self._block = block self.set_size_request(MIN_DIALOG_WIDTH, MIN_DIALOG_HEIGHT) vbox = gtk.VBox() #Create the scrolled window to hold all the parameters scrolled_window = gtk.ScrolledWindow() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scrolled_window.add_with_viewport(vbox) self.vbox.pack_start(scrolled_window, True) #Params box for block parameters self._params_box = gtk.VBox() self._params_box.pack_start(get_title_label('Parameters'), False) self._input_object_params = list() #Error Messages for the block self._error_box = gtk.VBox() self._error_messages_text_display = TextDisplay() self._error_box.pack_start(gtk.Label(), False, False, LABEL_SPACING) self._error_box.pack_start(get_title_label('Error Messages'), False) self._error_box.pack_start(self._error_messages_text_display, False) #Docs for the block self._docs_box = err_box = gtk.VBox() self._docs_text_display = TextDisplay() self._docs_box.pack_start(gtk.Label(), False, False, LABEL_SPACING) self._docs_box.pack_start(get_title_label('Documentation'), False) self._docs_box.pack_start(self._docs_text_display, False) #Add the boxes vbox.pack_start(self._params_box, False) vbox.pack_start(self._error_box, False) vbox.pack_start(self._docs_box, False) #connect events self.connect('key-press-event', self._handle_key_press) self.connect('show', self._update_gui) #show all (performs initial gui update) self.show_all() def _params_changed(self): """ Have the params in this dialog changed? Ex: Added, removed, type change, hide change... To the props dialog, the hide setting of 'none' and 'part' are identical. Therfore, the props dialog only cares if the hide setting is/not 'all'. Make a hash that uniquely represents the params' state. Returns: true if changed """ old_hash = self._hash #create a tuple of things from each param that affects the params box self._hash = hash(tuple([( hash(param), param.get_type(), param.get_hide() == 'all', ) for param in self._block.get_params()])) return self._hash != old_hash def _handle_changed(self, *args): """ A change occured within a param: Rewrite/validate the block and update the gui. """ #update for the block self._block.rewrite() self._block.validate() self._update_gui() def _update_gui(self, *args): """ Repopulate the parameters box (if changed). Update all the input parameters. Update the error messages box. Hide the box if there are no errors. Update the documentation block. Hide the box if there are no docs. """ #update the params box if self._params_changed(): #hide params box before changing self._params_box.hide_all() #empty the params box for io_param in list(self._input_object_params): self._params_box.remove(io_param) self._input_object_params.remove(io_param) io_param.destroy() #repopulate the params box for param in self._block.get_params(): if param.get_hide() == 'all': continue io_param = param.get_input(self._handle_changed) self._input_object_params.append(io_param) self._params_box.pack_start(io_param, False) #show params box with new params self._params_box.show_all() #update the errors box if self._block.is_valid(): self._error_box.hide() else: self._error_box.show() messages = '\n\n'.join(self._block.get_error_messages()) self._error_messages_text_display.set_text(messages) #update the docs box if self._block.get_doc(): self._docs_box.show() else: self._docs_box.hide() self._docs_text_display.set_text(self._block.get_doc()) def _handle_key_press(self, widget, event): """ Handle key presses from the keyboard. Call the ok response when enter is pressed. Returns: false to forward the keypress """ if event.keyval == gtk.keysyms.Return: self.response(gtk.RESPONSE_ACCEPT) return True #handled here return False #forward the keypress def run(self): """ Run the dialog and get its response. Returns: true if the response was accept """ response = gtk.Dialog.run(self) self.destroy() return response == gtk.RESPONSE_ACCEPT gnuradio-3.7.2.1/grc/gui/Param.py0000664000175000017500000001674312207702530016306 0ustar jcorganjcorgan""" Copyright 2007-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import Utils from Element import Element import pygtk pygtk.require('2.0') import gtk import Colors class InputParam(gtk.HBox): """The base class for an input parameter inside the input parameters dialog.""" def __init__(self, param, callback=None): gtk.HBox.__init__(self) self.param = param self._callback = callback self.label = gtk.Label() #no label, markup is added by set_markup self.label.set_size_request(150, -1) self.pack_start(self.label, False) self.set_markup = lambda m: self.label.set_markup(m) self.tp = None #connect events self.connect('show', self._update_gui) def set_color(self, color): pass def set_tooltip_text(self, text): pass def _update_gui(self, *args): """ Set the markup, color, tooltip, show/hide. """ #set the markup has_cb = \ hasattr(self.param.get_parent(), 'get_callbacks') and \ filter(lambda c: self.param.get_key() in c, self.param.get_parent()._callbacks) self.set_markup(Utils.parse_template(PARAM_LABEL_MARKUP_TMPL, param=self.param, has_cb=has_cb)) #set the color self.set_color(self.param.get_color()) #set the tooltip self.set_tooltip_text( Utils.parse_template(TIP_MARKUP_TMPL, param=self.param).strip(), ) #show/hide if self.param.get_hide() == 'all': self.hide_all() else: self.show_all() def _handle_changed(self, *args): """ Handle a gui change by setting the new param value, calling the callback (if applicable), and updating. """ #set the new value self.param.set_value(self.get_text()) #call the callback if self._callback: self._callback(*args) else: self.param.validate() #gui update self._update_gui() class EntryParam(InputParam): """Provide an entry box for strings and numbers.""" def __init__(self, *args, **kwargs): InputParam.__init__(self, *args, **kwargs) self._input = gtk.Entry() self._input.set_text(self.param.get_value()) self._input.connect('changed', self._handle_changed) self.pack_start(self._input, True) def get_text(self): return self._input.get_text() def set_color(self, color): self._input.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse(color)) self._input.modify_text(gtk.STATE_NORMAL, Colors.PARAM_ENTRY_TEXT_COLOR) def set_tooltip_text(self, text): self._input.set_tooltip_text(text) class EnumParam(InputParam): """Provide an entry box for Enum types with a drop down menu.""" def __init__(self, *args, **kwargs): InputParam.__init__(self, *args, **kwargs) self._input = gtk.combo_box_new_text() for option in self.param.get_options(): self._input.append_text(option.get_name()) self._input.set_active(self.param.get_option_keys().index(self.param.get_value())) self._input.connect('changed', self._handle_changed) self.pack_start(self._input, False) def get_text(self): return self.param.get_option_keys()[self._input.get_active()] def set_tooltip_text(self, text): self._input.set_tooltip_text(text) class EnumEntryParam(InputParam): """Provide an entry box and drop down menu for Raw Enum types.""" def __init__(self, *args, **kwargs): InputParam.__init__(self, *args, **kwargs) self._input = gtk.combo_box_entry_new_text() for option in self.param.get_options(): self._input.append_text(option.get_name()) try: self._input.set_active(self.param.get_option_keys().index(self.param.get_value())) except: self._input.set_active(-1) self._input.get_child().set_text(self.param.get_value()) self._input.connect('changed', self._handle_changed) self._input.get_child().connect('changed', self._handle_changed) self.pack_start(self._input, False) def get_text(self): if self._input.get_active() == -1: return self._input.get_child().get_text() return self.param.get_option_keys()[self._input.get_active()] def set_tooltip_text(self, text): if self._input.get_active() == -1: #custom entry self._input.get_child().set_tooltip_text(text) else: self._input.set_tooltip_text(text) def set_color(self, color): if self._input.get_active() == -1: #custom entry, use color self._input.get_child().modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse(color)) self._input.get_child().modify_text(gtk.STATE_NORMAL, Colors.PARAM_ENTRY_TEXT_COLOR) else: #from enum, make pale background self._input.get_child().modify_base(gtk.STATE_NORMAL, Colors.ENTRYENUM_CUSTOM_COLOR) self._input.get_child().modify_text(gtk.STATE_NORMAL, Colors.PARAM_ENTRY_TEXT_COLOR) PARAM_MARKUP_TMPL="""\ #set $foreground = $param.is_valid() and 'black' or 'red' $encode($param.get_name()): $encode(repr($param))""" PARAM_LABEL_MARKUP_TMPL="""\ #set $foreground = $param.is_valid() and 'black' or 'red' #set $underline = $has_cb and 'low' or 'none' $encode($param.get_name())""" TIP_MARKUP_TMPL="""\ ######################################## #def truncate(string) #set $max_len = 100 #set $string = str($string) #if len($string) > $max_len $('%s...%s'%($string[:$max_len/2], $string[-$max_len/2:]))#slurp #else $string#slurp #end if #end def ######################################## Key: $param.get_key() Type: $param.get_type() #if $param.is_valid() Value: $truncate($param.get_evaluated()) #elif len($param.get_error_messages()) == 1 Error: $(param.get_error_messages()[0]) #else Error: #for $error_msg in $param.get_error_messages() * $error_msg #end for #end if""" class Param(Element): """The graphical parameter.""" def __init__(self): Element.__init__(self) def get_input(self, *args, **kwargs): """ Get the graphical gtk class to represent this parameter. An enum requires and combo parameter. A non-enum with options gets a combined entry/combo parameter. All others get a standard entry parameter. Returns: gtk input class """ if self.is_enum(): return EnumParam(self, *args, **kwargs) if self.get_options(): return EnumEntryParam(self, *args, **kwargs) return EntryParam(self, *args, **kwargs) def get_markup(self): """ Get the markup for this param. Returns: a pango markup string """ return Utils.parse_template(PARAM_MARKUP_TMPL, param=self) gnuradio-3.7.2.1/grc/gui/StateCache.py0000664000175000017500000000713112207702530017241 0ustar jcorganjcorgan""" Copyright 2007 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import Actions from Constants import STATE_CACHE_SIZE class StateCache(object): """ The state cache is an interface to a list to record data/states and to revert to previous states. States are recorded into the list in a circular fassion by using an index for the current state, and counters for the range where states are stored. """ def __init__(self, initial_state): """ StateCache constructor. Args: initial_state: the intial state (nested data) """ self.states = [None] * STATE_CACHE_SIZE #fill states self.current_state_index = 0 self.num_prev_states = 0 self.num_next_states = 0 self.states[0] = initial_state self.update_actions() def save_new_state(self, state): """ Save a new state. Place the new state at the next index and add one to the number of previous states. Args: state: the new state """ self.current_state_index = (self.current_state_index + 1)%STATE_CACHE_SIZE self.states[self.current_state_index] = state self.num_prev_states = self.num_prev_states + 1 if self.num_prev_states == STATE_CACHE_SIZE: self.num_prev_states = STATE_CACHE_SIZE - 1 self.num_next_states = 0 self.update_actions() def get_current_state(self): """ Get the state at the current index. Returns: the current state (nested data) """ self.update_actions() return self.states[self.current_state_index] def get_prev_state(self): """ Get the previous state and decrement the current index. Returns: the previous state or None """ if self.num_prev_states > 0: self.current_state_index = (self.current_state_index + STATE_CACHE_SIZE -1)%STATE_CACHE_SIZE self.num_next_states = self.num_next_states + 1 self.num_prev_states = self.num_prev_states - 1 return self.get_current_state() return None def get_next_state(self): """ Get the nest state and increment the current index. Returns: the next state or None """ if self.num_next_states > 0: self.current_state_index = (self.current_state_index + 1)%STATE_CACHE_SIZE self.num_next_states = self.num_next_states - 1 self.num_prev_states = self.num_prev_states + 1 return self.get_current_state() return None def update_actions(self): """ Update the undo and redo actions based on the number of next and prev states. """ Actions.FLOW_GRAPH_REDO.set_sensitive(self.num_next_states != 0) Actions.FLOW_GRAPH_UNDO.set_sensitive(self.num_prev_states != 0) gnuradio-3.7.2.1/grc/gui/Actions.py0000664000175000017500000002347212245466767016670 0ustar jcorganjcorgan""" Copyright 2007-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk NO_MODS_MASK = 0 ######################################################################## # Actions API ######################################################################## _actions_keypress_dict = dict() _keymap = gtk.gdk.keymap_get_default() _used_mods_mask = NO_MODS_MASK def handle_key_press(event): """ Call the action associated with the key press event. Both the key value and the mask must have a match. Args: event: a gtk key press event Returns: true if handled """ _used_mods_mask = reduce(lambda x, y: x | y, [mod_mask for keyval, mod_mask in _actions_keypress_dict], NO_MODS_MASK) #extract the key value and the consumed modifiers keyval, egroup, level, consumed = _keymap.translate_keyboard_state( event.hardware_keycode, event.state, event.group) #get the modifier mask and ignore irrelevant modifiers mod_mask = event.state & ~consumed & _used_mods_mask #look up the keypress and call the action try: _actions_keypress_dict[(keyval, mod_mask)]() except KeyError: return False #not handled return True #handled here _all_actions_list = list() def get_all_actions(): return _all_actions_list _accel_group = gtk.AccelGroup() def get_accel_group(): return _accel_group class Action(gtk.Action): """ A custom Action class based on gtk.Action. Pass additional arguments such as keypresses. Register actions and keypresses with this module. """ def __init__(self, keypresses=(), name=None, label=None, tooltip=None, stock_id=None): """ Create a new Action instance. Args: key_presses: a tuple of (keyval1, mod_mask1, keyval2, mod_mask2, ...) the: regular gtk.Action parameters (defaults to None) """ if name is None: name = label gtk.Action.__init__(self, name=name, label=label, tooltip=tooltip, stock_id=stock_id, ) #register this action _all_actions_list.append(self) for i in range(len(keypresses)/2): keyval, mod_mask = keypresses[i*2:(i+1)*2] #register this keypress if _actions_keypress_dict.has_key((keyval, mod_mask)): raise KeyError('keyval/mod_mask pair already registered "%s"'%str((keyval, mod_mask))) _actions_keypress_dict[(keyval, mod_mask)] = self #set the accelerator group, and accelerator path #register the key name and mod mask with the accelerator path if label is None: continue #dont register accel accel_path = '
/'+self.get_name() self.set_accel_group(get_accel_group()) self.set_accel_path(accel_path) gtk.accel_map_add_entry(accel_path, keyval, mod_mask) def __str__(self): """ The string representation should be the name of the action id. Try to find the action id for this action by searching this module. """ try: import Actions return filter(lambda attr: getattr(Actions, attr) == self, dir(Actions))[0] except: return self.get_name() def __repr__(self): return str(self) def __call__(self): """ Emit the activate signal when called with (). """ self.emit('activate') ######################################################################## # Actions ######################################################################## PAGE_CHANGE = Action() FLOW_GRAPH_NEW = Action( label='_New', tooltip='Create a new flow graph', stock_id=gtk.STOCK_NEW, keypresses=(gtk.keysyms.n, gtk.gdk.CONTROL_MASK), ) FLOW_GRAPH_OPEN = Action( label='_Open', tooltip='Open an existing flow graph', stock_id=gtk.STOCK_OPEN, keypresses=(gtk.keysyms.o, gtk.gdk.CONTROL_MASK), ) FLOW_GRAPH_SAVE = Action( label='_Save', tooltip='Save the current flow graph', stock_id=gtk.STOCK_SAVE, keypresses=(gtk.keysyms.s, gtk.gdk.CONTROL_MASK), ) FLOW_GRAPH_SAVE_AS = Action( label='Save _As', tooltip='Save the current flow graph as...', stock_id=gtk.STOCK_SAVE_AS, keypresses=(gtk.keysyms.s, gtk.gdk.CONTROL_MASK | gtk.gdk.SHIFT_MASK), ) FLOW_GRAPH_CLOSE = Action( label='_Close', tooltip='Close the current flow graph', stock_id=gtk.STOCK_CLOSE, keypresses=(gtk.keysyms.w, gtk.gdk.CONTROL_MASK), ) APPLICATION_INITIALIZE = Action() APPLICATION_QUIT = Action( label='_Quit', tooltip='Quit program', stock_id=gtk.STOCK_QUIT, keypresses=(gtk.keysyms.q, gtk.gdk.CONTROL_MASK), ) FLOW_GRAPH_UNDO = Action( label='_Undo', tooltip='Undo a change to the flow graph', stock_id=gtk.STOCK_UNDO, keypresses=(gtk.keysyms.z, gtk.gdk.CONTROL_MASK), ) FLOW_GRAPH_REDO = Action( label='_Redo', tooltip='Redo a change to the flow graph', stock_id=gtk.STOCK_REDO, keypresses=(gtk.keysyms.y, gtk.gdk.CONTROL_MASK), ) NOTHING_SELECT = Action() ELEMENT_SELECT = Action() ELEMENT_CREATE = Action() ELEMENT_DELETE = Action( label='_Delete', tooltip='Delete the selected blocks', stock_id=gtk.STOCK_DELETE, keypresses=(gtk.keysyms.Delete, NO_MODS_MASK), ) BLOCK_MOVE = Action() BLOCK_ROTATE_CCW = Action( label='Rotate Counterclockwise', tooltip='Rotate the selected blocks 90 degrees to the left', stock_id=gtk.STOCK_GO_BACK, keypresses=(gtk.keysyms.Left, NO_MODS_MASK), ) BLOCK_ROTATE_CW = Action( label='Rotate Clockwise', tooltip='Rotate the selected blocks 90 degrees to the right', stock_id=gtk.STOCK_GO_FORWARD, keypresses=(gtk.keysyms.Right, NO_MODS_MASK), ) BLOCK_PARAM_MODIFY = Action( label='_Properties', tooltip='Modify params for the selected block', stock_id=gtk.STOCK_PROPERTIES, keypresses=(gtk.keysyms.Return, NO_MODS_MASK), ) BLOCK_ENABLE = Action( label='E_nable', tooltip='Enable the selected blocks', stock_id=gtk.STOCK_CONNECT, keypresses=(gtk.keysyms.e, NO_MODS_MASK), ) BLOCK_DISABLE = Action( label='D_isable', tooltip='Disable the selected blocks', stock_id=gtk.STOCK_DISCONNECT, keypresses=(gtk.keysyms.d, NO_MODS_MASK), ) BLOCK_CREATE_HIER = Action( label='C_reate Hier', tooltip='Create hier block from selected blocks', stock_id=gtk.STOCK_CONNECT, # keypresses=(gtk.keysyms.c, NO_MODS_MASK), ) BLOCK_CUT = Action( label='Cu_t', tooltip='Cut', stock_id=gtk.STOCK_CUT, keypresses=(gtk.keysyms.x, gtk.gdk.CONTROL_MASK), ) BLOCK_COPY = Action( label='_Copy', tooltip='Copy', stock_id=gtk.STOCK_COPY, keypresses=(gtk.keysyms.c, gtk.gdk.CONTROL_MASK), ) BLOCK_PASTE = Action( label='_Paste', tooltip='Paste', stock_id=gtk.STOCK_PASTE, keypresses=(gtk.keysyms.v, gtk.gdk.CONTROL_MASK), ) ERRORS_WINDOW_DISPLAY = Action( label='_Errors', tooltip='View flow graph errors', stock_id=gtk.STOCK_DIALOG_ERROR, ) ABOUT_WINDOW_DISPLAY = Action( label='_About', tooltip='About this program', stock_id=gtk.STOCK_ABOUT, ) HELP_WINDOW_DISPLAY = Action( label='_Help', tooltip='Usage tips', stock_id=gtk.STOCK_HELP, keypresses=(gtk.keysyms.F1, NO_MODS_MASK), ) TYPES_WINDOW_DISPLAY = Action( label='_Types', tooltip='Types color mapping', stock_id=gtk.STOCK_DIALOG_INFO, ) FLOW_GRAPH_GEN = Action( label='_Generate', tooltip='Generate the flow graph', stock_id=gtk.STOCK_CONVERT, keypresses=(gtk.keysyms.F5, NO_MODS_MASK), ) FLOW_GRAPH_EXEC = Action( label='_Execute', tooltip='Execute the flow graph', stock_id=gtk.STOCK_EXECUTE, keypresses=(gtk.keysyms.F6, NO_MODS_MASK), ) FLOW_GRAPH_KILL = Action( label='_Kill', tooltip='Kill the flow graph', stock_id=gtk.STOCK_STOP, keypresses=(gtk.keysyms.F7, NO_MODS_MASK), ) FLOW_GRAPH_SCREEN_CAPTURE = Action( label='S_creen Capture', tooltip='Create a screen capture of the flow graph', stock_id=gtk.STOCK_PRINT, keypresses=(gtk.keysyms.Print, NO_MODS_MASK), ) PORT_CONTROLLER_DEC = Action( keypresses=(gtk.keysyms.minus, NO_MODS_MASK, gtk.keysyms.KP_Subtract, NO_MODS_MASK), ) PORT_CONTROLLER_INC = Action( keypresses=(gtk.keysyms.plus, NO_MODS_MASK, gtk.keysyms.KP_Add, NO_MODS_MASK), ) BLOCK_INC_TYPE = Action( keypresses=(gtk.keysyms.Down, NO_MODS_MASK), ) BLOCK_DEC_TYPE = Action( keypresses=(gtk.keysyms.Up, NO_MODS_MASK), ) RELOAD_BLOCKS = Action( label='Reload _Blocks', tooltip='Reload Blocks', stock_id=gtk.STOCK_REFRESH ) FIND_BLOCKS = Action( label='_Find Blocks', tooltip='Search for a block by name (and key)', stock_id=gtk.STOCK_FIND, keypresses=(gtk.keysyms.f, gtk.gdk.CONTROL_MASK, gtk.keysyms.slash, NO_MODS_MASK), ) OPEN_HIER = Action( label='Open H_ier', tooltip='Open the source of the selected hierarchical block', stock_id=gtk.STOCK_JUMP_TO, ) BUSSIFY_SOURCES = Action( label='Toggle So_urce Bus', tooltip='Gang source ports into a single bus port', stock_id=gtk.STOCK_JUMP_TO, ) BUSSIFY_SINKS = Action( label='Toggle S_ink Bus', tooltip='Gang sink ports into a single bus port', stock_id=gtk.STOCK_JUMP_TO, ) gnuradio-3.7.2.1/grc/gui/MainWindow.py0000664000175000017500000003065712245466767017347 0ustar jcorganjcorgan""" Copyright 2008, 2009, 2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Constants import \ NEW_FLOGRAPH_TITLE, DEFAULT_REPORTS_WINDOW_WIDTH import Actions import pygtk pygtk.require('2.0') import gtk import Bars from BlockTreeWindow import BlockTreeWindow from Dialogs import TextDisplay, MessageDialogHelper from NotebookPage import NotebookPage import Preferences import Messages import Utils import os MAIN_WINDOW_TITLE_TMPL = """\ #if not $saved *#slurp #end if #if $basename $basename#slurp #else $new_flowgraph_title#slurp #end if #if $read_only (read only)#slurp #end if #if $dirname - $dirname#slurp #end if - $platform_name#slurp """ PAGE_TITLE_MARKUP_TMPL = """\ #set $foreground = $saved and 'black' or 'red' $encode($title or $new_flowgraph_title)#slurp #if $read_only (ro)#slurp #end if """ ############################################################ # Main window ############################################################ class MainWindow(gtk.Window): """The topmost window with menus, the tool bar, and other major windows.""" def __init__(self, platform): """ MainWindow contructor Setup the menu, toolbar, flowgraph editor notebook, block selection window... """ self._platform = platform #setup window gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) vbox = gtk.VBox() self.hpaned = gtk.HPaned() self.add(vbox) #create the menu bar and toolbar self.add_accel_group(Actions.get_accel_group()) vbox.pack_start(Bars.MenuBar(), False) vbox.pack_start(Bars.Toolbar(), False) vbox.pack_start(self.hpaned) #create the notebook self.notebook = gtk.Notebook() self.page_to_be_closed = None self.current_page = None self.notebook.set_show_border(False) self.notebook.set_scrollable(True) #scroll arrows for page tabs self.notebook.connect('switch-page', self._handle_page_change) #setup containers self.flow_graph_vpaned = gtk.VPaned() #flow_graph_box.pack_start(self.scrolled_window) self.flow_graph_vpaned.pack1(self.notebook) self.hpaned.pack1(self.flow_graph_vpaned) self.btwin = BlockTreeWindow(platform, self.get_flow_graph); self.hpaned.pack2(self.btwin, False) #dont allow resize #create the reports window self.text_display = TextDisplay() #house the reports in a scrolled window self.reports_scrolled_window = gtk.ScrolledWindow() self.reports_scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.reports_scrolled_window.add_with_viewport(self.text_display) self.reports_scrolled_window.set_size_request(-1, DEFAULT_REPORTS_WINDOW_WIDTH) self.flow_graph_vpaned.pack2(self.reports_scrolled_window, False) #dont allow resize #load preferences and show the main window Preferences.load(platform) self.resize(*Preferences.main_window_size()) self.flow_graph_vpaned.set_position(Preferences.reports_window_position()) self.hpaned.set_position(Preferences.blocks_window_position()) self.show_all() ############################################################ # Event Handlers ############################################################ def _quit(self, window, event): """ Handle the delete event from the main window. Generated by pressing X to close, alt+f4, or right click+close. This method in turns calls the state handler to quit. Returns: true """ Actions.APPLICATION_QUIT() return True def _handle_page_change(self, notebook, page, page_num): """ Handle a page change. When the user clicks on a new tab, reload the flow graph to update the vars window and call handle states (select nothing) to update the buttons. Args: notebook: the notebook page: new page page_num: new page number """ self.current_page = self.notebook.get_nth_page(page_num) Messages.send_page_switch(self.current_page.get_file_path()) Actions.PAGE_CHANGE() ############################################################ # Report Window ############################################################ def add_report_line(self, line): """ Place line at the end of the text buffer, then scroll its window all the way down. Args: line: the new text """ self.text_display.insert(line) vadj = self.reports_scrolled_window.get_vadjustment() vadj.value = vadj.upper - vadj.page_size vadj.changed() ############################################################ # Pages: create and close ############################################################ def new_page(self, file_path='', show=False): """ Create a new notebook page. Set the tab to be selected. Args: file_path: optional file to load into the flow graph show: true if the page should be shown after loading """ #if the file is already open, show the open page and return if file_path and file_path in self._get_files(): #already open page = self.notebook.get_nth_page(self._get_files().index(file_path)) self._set_page(page) return try: #try to load from file if file_path: Messages.send_start_load(file_path) flow_graph = self._platform.get_new_flow_graph() flow_graph.grc_file_path = file_path; #print flow_graph page = NotebookPage( self, flow_graph=flow_graph, file_path=file_path, ) if file_path: Messages.send_end_load() except Exception, e: #return on failure Messages.send_fail_load(e) if isinstance(e, KeyError) and str(e) == "'options'": # This error is unrecoverable, so crash gracefully exit(-1) return #add this page to the notebook self.notebook.append_page(page, page.get_tab()) try: self.notebook.set_tab_reorderable(page, True) except: pass #gtk too old self.notebook.set_tab_label_packing(page, False, False, gtk.PACK_START) #only show if blank or manual if not file_path or show: self._set_page(page) def close_pages(self): """ Close all the pages in this notebook. Returns: true if all closed """ open_files = filter(lambda file: file, self._get_files()) #filter blank files open_file = self.get_page().get_file_path() #close each page for page in self._get_pages(): self.page_to_be_closed = page self.close_page(False) if self.notebook.get_n_pages(): return False #save state before closing Preferences.files_open(open_files) Preferences.file_open(open_file) Preferences.main_window_size(self.get_size()) Preferences.reports_window_position(self.flow_graph_vpaned.get_position()) Preferences.blocks_window_position(self.hpaned.get_position()) Preferences.save() return True def close_page(self, ensure=True): """ Close the current page. If the notebook becomes empty, and ensure is true, call new page upon exit to ensure that at least one page exists. Args: ensure: boolean """ if not self.page_to_be_closed: self.page_to_be_closed = self.get_page() #show the page if it has an executing flow graph or is unsaved if self.page_to_be_closed.get_proc() or not self.page_to_be_closed.get_saved(): self._set_page(self.page_to_be_closed) #unsaved? ask the user if not self.page_to_be_closed.get_saved() and self._save_changes(): Actions.FLOW_GRAPH_SAVE() #try to save if not self.page_to_be_closed.get_saved(): #still unsaved? self.page_to_be_closed = None #set the page to be closed back to None return #stop the flow graph if executing if self.page_to_be_closed.get_proc(): Actions.FLOW_GRAPH_KILL() #remove the page self.notebook.remove_page(self.notebook.page_num(self.page_to_be_closed)) if ensure and self.notebook.get_n_pages() == 0: self.new_page() #no pages, make a new one self.page_to_be_closed = None #set the page to be closed back to None ############################################################ # Misc ############################################################ def update(self): """ Set the title of the main window. Set the titles on the page tabs. Show/hide the reports window. Args: title: the window title """ gtk.Window.set_title(self, Utils.parse_template(MAIN_WINDOW_TITLE_TMPL, basename=os.path.basename(self.get_page().get_file_path()), dirname=os.path.dirname(self.get_page().get_file_path()), new_flowgraph_title=NEW_FLOGRAPH_TITLE, read_only=self.get_page().get_read_only(), saved=self.get_page().get_saved(), platform_name=self._platform.get_name(), ) ) #set tab titles for page in self._get_pages(): page.set_markup( Utils.parse_template(PAGE_TITLE_MARKUP_TMPL, #get filename and strip out file extension title=os.path.splitext(os.path.basename(page.get_file_path()))[0], read_only=page.get_read_only(), saved=page.get_saved(), new_flowgraph_title=NEW_FLOGRAPH_TITLE, ) ) #show/hide notebook tabs self.notebook.set_show_tabs(len(self._get_pages()) > 1) def get_page(self): """ Get the selected page. Returns: the selected page """ return self.current_page def get_flow_graph(self): """ Get the selected flow graph. Returns: the selected flow graph """ return self.get_page().get_flow_graph() def get_focus_flag(self): """ Get the focus flag from the current page. Returns: the focus flag """ return self.get_page().get_drawing_area().get_focus_flag() ############################################################ # Helpers ############################################################ def _set_page(self, page): """ Set the current page. Args: page: the page widget """ self.current_page = page self.notebook.set_current_page(self.notebook.page_num(self.current_page)) def _save_changes(self): """ Save changes to flow graph? Returns: true if yes """ return MessageDialogHelper( gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, 'Unsaved Changes!', 'Would you like to save changes before closing?' ) == gtk.RESPONSE_YES def _get_files(self): """ Get the file names for all the pages, in order. Returns: list of file paths """ return map(lambda page: page.get_file_path(), self._get_pages()) def _get_pages(self): """ Get a list of all pages in the notebook. Returns: list of pages """ return [self.notebook.get_nth_page(page_num) for page_num in range(self.notebook.get_n_pages())] gnuradio-3.7.2.1/grc/gui/BlockTreeWindow.py0000664000175000017500000002453312245466767020331 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Constants import DEFAULT_BLOCKS_WINDOW_WIDTH, DND_TARGETS import Actions import Utils import pygtk pygtk.require('2.0') import gtk import gobject NAME_INDEX = 0 KEY_INDEX = 1 DOC_INDEX = 2 DOC_MARKUP_TMPL="""\ #if $doc $encode($doc)#slurp #else undocumented#slurp #end if""" CAT_MARKUP_TMPL="""Category: $cat""" class BlockTreeWindow(gtk.VBox): """The block selection panel.""" def __init__(self, platform, get_flow_graph): """ BlockTreeWindow constructor. Create a tree view of the possible blocks in the platform. The tree view nodes will be category names, the leaves will be block names. A mouse double click or button press action will trigger the add block event. Args: platform: the particular platform will all block prototypes get_flow_graph: get the selected flow graph """ gtk.VBox.__init__(self) self.platform = platform self.get_flow_graph = get_flow_graph # search entry self.search_entry = gtk.Entry() self.search_entry.set_icon_from_stock(gtk.ENTRY_ICON_PRIMARY, gtk.STOCK_FIND) self.search_entry.set_icon_activatable(gtk.ENTRY_ICON_PRIMARY, False) self.search_entry.set_icon_from_stock(gtk.ENTRY_ICON_SECONDARY, gtk.STOCK_CLOSE) self.search_entry.connect('icon-release', self._handle_icon_event) self.search_entry.connect('changed', self._update_search_tree) self.search_entry.connect('key-press-event', self._handle_search_key_press) self.pack_start(self.search_entry, False) #make the tree model for holding blocks and a temporary one for search results self.treestore = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING) self.treestore_search = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING) self.treeview = gtk.TreeView(self.treestore) self.treeview.set_enable_search(False) #disable pop up search box self.treeview.set_search_column(-1) # really disable search self.treeview.set_headers_visible(False) self.treeview.add_events(gtk.gdk.BUTTON_PRESS_MASK) self.treeview.connect('button-press-event', self._handle_mouse_button_press) self.treeview.connect('key-press-event', self._handle_search_key_press) self.treeview.get_selection().set_mode('single') renderer = gtk.CellRendererText() column = gtk.TreeViewColumn('Blocks', renderer, text=NAME_INDEX) self.treeview.append_column(column) #try to enable the tooltips (available in pygtk 2.12 and above) try: self.treeview.set_tooltip_column(DOC_INDEX) except: pass #setup sort order column.set_sort_column_id(0) self.treestore.set_sort_column_id(0, gtk.SORT_ASCENDING) #setup drag and drop self.treeview.enable_model_drag_source(gtk.gdk.BUTTON1_MASK, DND_TARGETS, gtk.gdk.ACTION_COPY) self.treeview.connect('drag-data-get', self._handle_drag_get_data) #make the scrolled window to hold the tree view scrolled_window = gtk.ScrolledWindow() scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scrolled_window.add_with_viewport(self.treeview) scrolled_window.set_size_request(DEFAULT_BLOCKS_WINDOW_WIDTH, -1) self.pack_start(scrolled_window) #map categories to iters, automatic mapping for root self._categories = {tuple(): None} self._categories_search = {tuple(): None} #add blocks and categories self.platform.load_block_tree(self) def clear(self): self.treestore.clear(); self._categories = {tuple(): None} ############################################################ ## Block Tree Methods ############################################################ def add_block(self, category, block=None, treestore=None, categories=None): """ Add a block with category to this selection window. Add only the category when block is None. Args: category: the category list or path string block: the block object or None """ if treestore is None: treestore = self.treestore if categories is None: categories = self._categories if isinstance(category, str): category = category.split('/') category = tuple(filter(lambda x: x, category)) #tuple is hashable #add category and all sub categories for i, cat_name in enumerate(category): sub_category = category[:i+1] if sub_category not in categories: iter = treestore.insert_before(categories[sub_category[:-1]], None) treestore.set_value(iter, NAME_INDEX, '[ %s ]'%cat_name) treestore.set_value(iter, KEY_INDEX, '') treestore.set_value(iter, DOC_INDEX, Utils.parse_template(CAT_MARKUP_TMPL, cat=cat_name)) categories[sub_category] = iter #add block if block is None: return iter = treestore.insert_before(categories[category], None) treestore.set_value(iter, NAME_INDEX, block.get_name()) treestore.set_value(iter, KEY_INDEX, block.get_key()) treestore.set_value(iter, DOC_INDEX, Utils.parse_template(DOC_MARKUP_TMPL, doc=block.get_doc())) ############################################################ ## Helper Methods ############################################################ def _get_selected_block_key(self): """ Get the currently selected block key. Returns: the key of the selected block or a empty string """ selection = self.treeview.get_selection() treestore, iter = selection.get_selected() return iter and treestore.get_value(iter, KEY_INDEX) or '' def _add_selected_block(self): """ Add the selected block with the given key to the flow graph. """ key = self._get_selected_block_key() if key: self.get_flow_graph().add_new_block(key) return True return False def _expand_category(self): treestore, iter = self.treeview.get_selection().get_selected() if iter and treestore.iter_has_child(iter): path = self.treestore.get_path(iter) self.treeview.expand_to_path(path) ############################################################ ## Event Handlers ############################################################ def _handle_icon_event(self, widget, icon, event): if icon == gtk.ENTRY_ICON_PRIMARY: pass elif icon == gtk.ENTRY_ICON_SECONDARY: widget.set_text('') self.search_entry.hide() def _update_search_tree(self, widget): key = widget.get_text().lower() if not key: self.treeview.set_model(self.treestore) self.treeview.collapse_all() else: blocks = self.get_flow_graph().get_parent().get_blocks() matching_blocks = filter(lambda b: key in b.get_key().lower() or key in b.get_name().lower(), blocks) self.treestore_search.clear() self._categories_search = {tuple(): None} for block in matching_blocks: self.add_block(block.get_category() or 'None', block, self.treestore_search, self._categories_search) self.treeview.set_model(self.treestore_search) self.treeview.expand_all() def _handle_search_key_press(self, widget, event): """Handle Return and Escape key events in search entry and treeview""" if event.keyval == gtk.keysyms.Return: # add block on enter if widget == self.search_entry: # Get the first block in the search tree and add it selected = self.treestore_search.get_iter_first() while self.treestore_search.iter_children(selected): selected = self.treestore_search.iter_children(selected) if selected is not None: key = self.treestore_search.get_value(selected, KEY_INDEX) if key: self.get_flow_graph().add_new_block(key) elif widget == self.treeview: self._add_selected_block() or self._expand_category() else: return False # propagate event elif event.keyval == gtk.keysyms.Escape: # reset the search self.search_entry.set_text('') self.search_entry.hide() elif (event.state & gtk.gdk.CONTROL_MASK and event.keyval == gtk.keysyms.f) \ or event.keyval == gtk.keysyms.slash: # propagation doesn't work although treeview search is disabled =( # manually trigger action... Actions.FIND_BLOCKS.activate() else: return False # propagate event return True def _handle_drag_get_data(self, widget, drag_context, selection_data, info, time): """ Handle a drag and drop by setting the key to the selection object. This will call the destination handler for drag and drop. Only call set when the key is valid to ignore DND from categories. """ key = self._get_selected_block_key() if key: selection_data.set(selection_data.target, 8, key) def _handle_mouse_button_press(self, widget, event): """ Handle the mouse button press. If a left double click is detected, call add selected block. """ if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS: self._add_selected_block() gnuradio-3.7.2.1/grc/gui/Messages.py0000664000175000017500000000675312207702530017015 0ustar jcorganjcorgan""" Copyright 2007 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import traceback import sys ## A list of functions that can receive a message. MESSENGERS_LIST = list() def register_messenger(messenger): """ Append the given messenger to the list of messengers. Args: messenger: a method thats takes a string """ MESSENGERS_LIST.append(messenger) def send(message): """ Give the message to each of the messengers. Args: message: a message string """ for messenger in MESSENGERS_LIST: messenger(message) #register stdout by default register_messenger(sys.stdout.write) ########################################################################### # Special functions for specific program functionalities ########################################################################### def send_init(platform): send("""<<< Welcome to %s %s >>>\n"""%(platform.get_name(), platform.get_version())) def send_page_switch(file_path): send('\nShowing: "%s"\n'%file_path) ################# functions for loading flow graphs ######################################## def send_start_load(file_path): send('\nLoading: "%s"'%file_path + '\n') def send_error_load(error): send('>>> Error: %s\n'%error) traceback.print_exc() def send_end_load(): send('>>> Done\n') def send_fail_load(error): send('Error: %s\n'%error) send('>>> Failure\n') traceback.print_exc() ################# functions for generating flow graphs ######################################## def send_start_gen(file_path): send('\nGenerating: "%s"'%file_path + '\n') def send_fail_gen(error): send('Generate Error: %s\n'%error) send('>>> Failure\n') traceback.print_exc() ################# functions for executing flow graphs ######################################## def send_start_exec(file_path): send('\nExecuting: "%s"'%file_path + '\n') def send_verbose_exec(verbose): send(verbose) def send_end_exec(): send('\n>>> Done\n') ################# functions for saving flow graphs ######################################## def send_fail_save(file_path): send('>>> Error: Cannot save: %s\n'%file_path) ################# functions for connections ######################################## def send_fail_connection(): send('>>> Error: Cannot create connection.\n') ################# functions for preferences ######################################## def send_fail_load_preferences(prefs_file_path): send('>>> Error: Cannot load preferences file: "%s"\n'%prefs_file_path) def send_fail_save_preferences(prefs_file_path): send('>>> Error: Cannot save preferences file: "%s"\n'%prefs_file_path) ################# functions for warning ######################################## def send_warning(warning): send('>>> Warning: %s\n'%warning) gnuradio-3.7.2.1/grc/gui/Connection.py0000664000175000017500000001566212245466767017371 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import Utils from Element import Element import Colors from Constants import CONNECTOR_ARROW_BASE, CONNECTOR_ARROW_HEIGHT class Connection(Element): """ A graphical connection for ports. The connection has 2 parts, the arrow and the wire. The coloring of the arrow and wire exposes the status of 3 states: enabled/disabled, valid/invalid, highlighted/non-highlighted. The wire coloring exposes the enabled and highlighted states. The arrow coloring exposes the enabled and valid states. """ def __init__(self): Element.__init__(self) def get_coordinate(self): """ Get the 0,0 coordinate. Coordinates are irrelevant in connection. Returns: 0, 0 """ return (0, 0) def get_rotation(self): """ Get the 0 degree rotation. Rotations are irrelevant in connection. Returns: 0 """ return 0 def create_shapes(self): """Precalculate relative coordinates.""" Element.create_shapes(self) self._sink_rot = None self._source_rot = None self._sink_coor = None self._source_coor = None #get the source coordinate try: connector_length = self.get_source().get_connector_length() except: return self.x1, self.y1 = Utils.get_rotated_coordinate((connector_length, 0), self.get_source().get_rotation()) #get the sink coordinate connector_length = self.get_sink().get_connector_length() + CONNECTOR_ARROW_HEIGHT self.x2, self.y2 = Utils.get_rotated_coordinate((-connector_length, 0), self.get_sink().get_rotation()) #build the arrow self.arrow = [(0, 0), Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()), Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()), ] self._update_after_move() if not self.get_enabled(): self._arrow_color = Colors.CONNECTION_DISABLED_COLOR elif not self.is_valid(): self._arrow_color = Colors.CONNECTION_ERROR_COLOR else: self._arrow_color = Colors.CONNECTION_ENABLED_COLOR def _update_after_move(self): """Calculate coordinates.""" self.clear() #FIXME do i want this here? #source connector source = self.get_source() X, Y = source.get_connector_coordinate() x1, y1 = self.x1 + X, self.y1 + Y self.add_line((x1, y1), (X, Y)) #sink connector sink = self.get_sink() X, Y = sink.get_connector_coordinate() x2, y2 = self.x2 + X, self.y2 + Y self.add_line((x2, y2), (X, Y)) #adjust arrow self._arrow = [(x+X, y+Y) for x,y in self.arrow] #add the horizontal and vertical lines in this connection if abs(source.get_connector_direction() - sink.get_connector_direction()) == 180: #2 possible point sets to create a 3-line connector mid_x, mid_y = (x1 + x2)/2.0, (y1 + y2)/2.0 points = [((mid_x, y1), (mid_x, y2)), ((x1, mid_y), (x2, mid_y))] #source connector -> points[0][0] should be in the direction of source (if possible) if Utils.get_angle_from_coordinates((x1, y1), points[0][0]) != source.get_connector_direction(): points.reverse() #points[0][0] -> sink connector should not be in the direction of sink if Utils.get_angle_from_coordinates(points[0][0], (x2, y2)) == sink.get_connector_direction(): points.reverse() #points[0][0] -> source connector should not be in the direction of source if Utils.get_angle_from_coordinates(points[0][0], (x1, y1)) == source.get_connector_direction(): points.reverse() #create 3-line connector p1, p2 = map(int, points[0][0]), map(int, points[0][1]) self.add_line((x1, y1), p1) self.add_line(p1, p2) self.add_line((x2, y2), p2) else: #2 possible points to create a right-angled connector points = [(x1, y2), (x2, y1)] #source connector -> points[0] should be in the direction of source (if possible) if Utils.get_angle_from_coordinates((x1, y1), points[0]) != source.get_connector_direction(): points.reverse() #points[0] -> sink connector should not be in the direction of sink if Utils.get_angle_from_coordinates(points[0], (x2, y2)) == sink.get_connector_direction(): points.reverse() #points[0] -> source connector should not be in the direction of source if Utils.get_angle_from_coordinates(points[0], (x1, y1)) == source.get_connector_direction(): points.reverse() #create right-angled connector self.add_line((x1, y1), points[0]) self.add_line((x2, y2), points[0]) def draw(self, gc, window): """ Draw the connection. Args: gc: the graphics context window: the gtk window to draw on """ sink = self.get_sink() source = self.get_source() #check for changes if self._sink_rot != sink.get_rotation() or self._source_rot != source.get_rotation(): self.create_shapes() elif self._sink_coor != sink.get_coordinate() or self._source_coor != source.get_coordinate(): try: self._update_after_move() except: return #cache values self._sink_rot = sink.get_rotation() self._source_rot = source.get_rotation() self._sink_coor = sink.get_coordinate() self._source_coor = source.get_coordinate() #draw if self.is_highlighted(): border_color = Colors.HIGHLIGHT_COLOR elif self.get_enabled(): border_color = Colors.CONNECTION_ENABLED_COLOR else: border_color = Colors.CONNECTION_DISABLED_COLOR Element.draw(self, gc, window, bg_color=None, border_color=border_color) #draw arrow on sink port try: gc.set_foreground(self._arrow_color) window.draw_polygon(gc, True, self._arrow) except: return gnuradio-3.7.2.1/grc/gui/Dialogs.py0000664000175000017500000001200112237027233016612 0ustar jcorganjcorgan""" Copyright 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import pygtk pygtk.require('2.0') import gtk import Utils class TextDisplay(gtk.TextView): """A non editable gtk text view.""" def __init__(self, text=''): """ TextDisplay constructor. Args: text: the text to display (string) """ text_buffer = gtk.TextBuffer() text_buffer.set_text(text) self.set_text = text_buffer.set_text gtk.TextView.__init__(self, text_buffer) self.set_editable(False) self.set_cursor_visible(False) self.set_wrap_mode(gtk.WRAP_WORD_CHAR) def insert(self, line): # make backspaces work line = self._consume_backspaces(line) # add the remaining text to buffer self.get_buffer().insert(self.get_buffer().get_end_iter(), line) def _consume_backspaces(self, line): """removes text from the buffer if line starts with \b*""" if not line: return # for each \b delete one char from the buffer back_count = 0 start_iter = self.get_buffer().get_end_iter() while line[back_count] == '\b': # stop at the beginning of a line if not start_iter.starts_line(): start_iter.backward_char() back_count += 1 # remove chars self.get_buffer().delete(start_iter, self.get_buffer().get_end_iter()) # return remaining text return line[back_count:] def MessageDialogHelper(type, buttons, title=None, markup=None): """ Create a modal message dialog and run it. Args: type: the type of message: gtk.MESSAGE_INFO, gtk.MESSAGE_WARNING, gtk.MESSAGE_QUESTION or gtk.MESSAGE_ERROR buttons: the predefined set of buttons to use: gtk.BUTTONS_NONE, gtk.BUTTONS_OK, gtk.BUTTONS_CLOSE, gtk.BUTTONS_CANCEL, gtk.BUTTONS_YES_NO, gtk.BUTTONS_OK_CANCEL Args: tittle: the title of the window (string) markup: the message text with pango markup Returns: the gtk response from run() """ message_dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, type, buttons) if title: message_dialog.set_title(title) if markup: message_dialog.set_markup(markup) response = message_dialog.run() message_dialog.destroy() return response ERRORS_MARKUP_TMPL="""\ #for $i, $err_msg in enumerate($errors) Error $i: $encode($err_msg.replace('\t', ' ')) #end for""" def ErrorsDialog(flowgraph): MessageDialogHelper( type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, title='Flow Graph Errors', markup=Utils.parse_template(ERRORS_MARKUP_TMPL, errors=flowgraph.get_error_messages()), ) class AboutDialog(gtk.AboutDialog): """A cute little about dialog.""" def __init__(self, platform): """AboutDialog constructor.""" gtk.AboutDialog.__init__(self) self.set_name(platform.get_name()) self.set_version(platform.get_version()) self.set_license(platform.get_license()) self.set_copyright(platform.get_license().splitlines()[0]) self.set_website(platform.get_website()) self.run() self.destroy() def HelpDialog(): MessageDialogHelper( type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_CLOSE, title='Help', markup="""\ Usage Tips Add block: drag and drop or double click a block in the block selection window. Rotate block: Select a block, press left/right on the keyboard. Change type: Select a block, press up/down on the keyboard. Edit parameters: double click on a block in the flow graph. Make connection: click on the source port of one block, then click on the sink port of another block. Remove connection: select the connection and press delete, or drag the connection. * See the menu for other keyboard shortcuts.""") COLORS_DIALOG_MARKUP_TMPL = """\ Color Mapping #if $colors #set $max_len = max([len(color[0]) for color in $colors]) + 10 #for $title, $color_spec in $colors $($encode($title).center($max_len)) #end for #end if """ def TypesDialog(platform): MessageDialogHelper( type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_CLOSE, title='Types', markup=Utils.parse_template(COLORS_DIALOG_MARKUP_TMPL, colors=platform.get_colors())) gnuradio-3.7.2.1/grc/gui/Preferences.py0000664000175000017500000000605612245466767017530 0ustar jcorganjcorgan""" Copyright 2008 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import ConfigParser import os _platform = None _config_parser = ConfigParser.ConfigParser() def file_extension(): return '.'+_platform.get_key() def _prefs_file(): return os.path.join(os.path.expanduser('~'), file_extension()) def load(platform): global _platform _platform = platform #create sections _config_parser.add_section('main') _config_parser.add_section('files_open') try: _config_parser.read(_prefs_file()) except: pass def save(): try: _config_parser.write(open(_prefs_file(), 'w')) except: pass ########################################################################### # Special methods for specific program functionalities ########################################################################### def main_window_size(size=None): if size is not None: _config_parser.set('main', 'main_window_width', size[0]) _config_parser.set('main', 'main_window_height', size[1]) else: try: return ( _config_parser.getint('main', 'main_window_width'), _config_parser.getint('main', 'main_window_height'), ) except: return (1, 1) def file_open(file=None): if file is not None: _config_parser.set('main', 'file_open', file) else: try: return _config_parser.get('main', 'file_open') except: return '' def files_open(files=None): if files is not None: _config_parser.remove_section('files_open') #clear section _config_parser.add_section('files_open') for i, file in enumerate(files): _config_parser.set('files_open', 'file_open_%d'%i, file) else: files = list() i = 0 while True: try: files.append(_config_parser.get('files_open', 'file_open_%d'%i)) except: return files i = i + 1 def reports_window_position(pos=None): if pos is not None: _config_parser.set('main', 'reports_window_position', pos) else: try: return _config_parser.getint('main', 'reports_window_position') or 1 #greater than 0 except: return -1 def blocks_window_position(pos=None): if pos is not None: _config_parser.set('main', 'blocks_window_position', pos) else: try: return _config_parser.getint('main', 'blocks_window_position') or 1 #greater than 0 except: return -1 gnuradio-3.7.2.1/grc/gui/Element.py0000664000175000017500000002143112207702530016625 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Constants import LINE_SELECT_SENSITIVITY from Constants import POSSIBLE_ROTATIONS class Element(object): """ GraphicalElement is the base class for all graphical elements. It contains an X,Y coordinate, a list of rectangular areas that the element occupies, and methods to detect selection of those areas. """ def __init__(self): """ Make a new list of rectangular areas and lines, and set the coordinate and the rotation. """ self.set_rotation(POSSIBLE_ROTATIONS[0]) self.set_coordinate((0, 0)) self.clear() self.set_highlighted(False) def is_horizontal(self, rotation=None): """ Is this element horizontal? If rotation is None, use this element's rotation. Args: rotation: the optional rotation Returns: true if rotation is horizontal """ rotation = rotation or self.get_rotation() return rotation in (0, 180) def is_vertical(self, rotation=None): """ Is this element vertical? If rotation is None, use this element's rotation. Args: rotation: the optional rotation Returns: true if rotation is vertical """ rotation = rotation or self.get_rotation() return rotation in (90, 270) def create_labels(self): """ Create labels (if applicable) and call on all children. Call this base method before creating labels in the element. """ for child in self.get_children():child.create_labels() def create_shapes(self): """ Create shapes (if applicable) and call on all children. Call this base method before creating shapes in the element. """ self.clear() for child in self.get_children(): child.create_shapes() def draw(self, gc, window, border_color, bg_color): """ Draw in the given window. Args: gc: the graphics context window: the gtk window to draw on border_color: the color for lines and rectangle borders bg_color: the color for the inside of the rectangle """ X,Y = self.get_coordinate() for (rX,rY),(W,H) in self._areas_list: aX = X + rX aY = Y + rY gc.set_foreground(bg_color) window.draw_rectangle(gc, True, aX, aY, W, H) gc.set_foreground(border_color) window.draw_rectangle(gc, False, aX, aY, W, H) for (x1, y1),(x2, y2) in self._lines_list: gc.set_foreground(border_color) window.draw_line(gc, X+x1, Y+y1, X+x2, Y+y2) def rotate(self, rotation): """ Rotate all of the areas by 90 degrees. Args: rotation: multiple of 90 degrees """ self.set_rotation((self.get_rotation() + rotation)%360) def clear(self): """Empty the lines and areas.""" self._areas_list = list() self._lines_list = list() def set_coordinate(self, coor): """ Set the reference coordinate. Args: coor: the coordinate tuple (x,y) """ self.coor = coor def get_parent(self): """ Get the parent of this element. Returns: the parent """ return self.parent def set_highlighted(self, highlighted): """ Set the highlight status. Args: highlighted: true to enable highlighting """ self.highlighted = highlighted def is_highlighted(self): """ Get the highlight status. Returns: true if highlighted """ return self.highlighted def get_coordinate(self): """Get the coordinate. Returns: the coordinate tuple (x,y) """ return self.coor def move(self, delta_coor): """ Move the element by adding the delta_coor to the current coordinate. Args: delta_coor: (delta_x,delta_y) tuple """ deltaX, deltaY = delta_coor X, Y = self.get_coordinate() self.set_coordinate((X+deltaX, Y+deltaY)) def add_area(self, rel_coor, area): """ Add an area to the area list. An area is actually a coordinate relative to the main coordinate with a width/height pair relative to the area coordinate. A positive width is to the right of the coordinate. A positive height is above the coordinate. The area is associated with a rotation. Args: rel_coor: (x,y) offset from this element's coordinate area: (width,height) tuple """ self._areas_list.append((rel_coor, area)) def add_line(self, rel_coor1, rel_coor2): """ Add a line to the line list. A line is defined by 2 relative coordinates. Lines must be horizontal or vertical. The line is associated with a rotation. Args: rel_coor1: relative (x1,y1) tuple rel_coor2: relative (x2,y2) tuple """ self._lines_list.append((rel_coor1, rel_coor2)) def what_is_selected(self, coor, coor_m=None): """ One coordinate specified: Is this element selected at given coordinate? ie: is the coordinate encompassed by one of the areas or lines? Both coordinates specified: Is this element within the rectangular region defined by both coordinates? ie: do any area corners or line endpoints fall within the region? Args: coor: the selection coordinate, tuple x, y coor_m: an additional selection coordinate. Returns: self if one of the areas/lines encompasses coor, else None. """ #function to test if p is between a and b (inclusive) in_between = lambda p, a, b: p >= min(a, b) and p <= max(a, b) #relative coordinate x, y = [a-b for a,b in zip(coor, self.get_coordinate())] if coor_m: x_m, y_m = [a-b for a,b in zip(coor_m, self.get_coordinate())] #handle rectangular areas for (x1,y1), (w,h) in self._areas_list: if in_between(x1, x, x_m) and in_between(y1, y, y_m) or \ in_between(x1+w, x, x_m) and in_between(y1, y, y_m) or \ in_between(x1, x, x_m) and in_between(y1+h, y, y_m) or \ in_between(x1+w, x, x_m) and in_between(y1+h, y, y_m): return self #handle horizontal or vertical lines for (x1, y1), (x2, y2) in self._lines_list: if in_between(x1, x, x_m) and in_between(y1, y, y_m) or \ in_between(x2, x, x_m) and in_between(y2, y, y_m): return self return None else: #handle rectangular areas for (x1,y1), (w,h) in self._areas_list: if in_between(x, x1, x1+w) and in_between(y, y1, y1+h): return self #handle horizontal or vertical lines for (x1, y1), (x2, y2) in self._lines_list: if x1 == x2: x1, x2 = x1-LINE_SELECT_SENSITIVITY, x2+LINE_SELECT_SENSITIVITY if y1 == y2: y1, y2 = y1-LINE_SELECT_SENSITIVITY, y2+LINE_SELECT_SENSITIVITY if in_between(x, x1, x2) and in_between(y, y1, y2): return self return None def get_rotation(self): """ Get the rotation in degrees. Returns: the rotation """ return self.rotation def set_rotation(self, rotation): """ Set the rotation in degrees. Args: rotation: the rotation""" if rotation not in POSSIBLE_ROTATIONS: raise Exception('"%s" is not one of the possible rotations: (%s)'%(rotation, POSSIBLE_ROTATIONS)) self.rotation = rotation gnuradio-3.7.2.1/grc/gui/FlowGraph.py0000664000175000017500000005454012237515112017135 0ustar jcorganjcorgan""" Copyright 2007-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Constants import SCROLL_PROXIMITY_SENSITIVITY, SCROLL_DISTANCE import Actions import Colors import Utils from Element import Element import pygtk pygtk.require('2.0') import gtk import random import Messages class FlowGraph(Element): """ FlowGraph is the data structure to store graphical signal blocks, graphical inputs and outputs, and the connections between inputs and outputs. """ def __init__(self): """ FlowGraph contructor. Create a list for signal blocks and connections. Connect mouse handlers. """ Element.__init__(self) #when is the flow graph selected? (used by keyboard event handler) self.is_selected = lambda: bool(self.get_selected_elements()) #important vars dealing with mouse event tracking self.element_moved = False self.mouse_pressed = False self.unselect() self.press_coor = (0, 0) #selected ports self._old_selected_port = None self._new_selected_port = None #context menu self._context_menu = gtk.Menu() for action in [ Actions.BLOCK_CUT, Actions.BLOCK_COPY, Actions.BLOCK_PASTE, Actions.ELEMENT_DELETE, None, Actions.BLOCK_ROTATE_CCW, Actions.BLOCK_ROTATE_CW, Actions.BLOCK_ENABLE, Actions.BLOCK_DISABLE, None, Actions.BLOCK_CREATE_HIER, Actions.OPEN_HIER, Actions.BUSSIFY_SOURCES, Actions.BUSSIFY_SINKS, None, Actions.BLOCK_PARAM_MODIFY ]: self._context_menu.append(action.create_menu_item() if action else gtk.SeparatorMenuItem()) self.get_context_menu = lambda: self._context_menu ########################################################################### # Access Drawing Area ########################################################################### def get_drawing_area(self): return self.drawing_area def queue_draw(self): self.get_drawing_area().queue_draw() def get_size(self): return self.get_drawing_area().get_size_request() def set_size(self, *args): self.get_drawing_area().set_size_request(*args) def get_scroll_pane(self): return self.drawing_area.get_parent() def get_ctrl_mask(self): return self.drawing_area.ctrl_mask def new_pixmap(self, *args): return self.get_drawing_area().new_pixmap(*args) def add_new_block(self, key, coor=None): """ Add a block of the given key to this flow graph. Args: key: the block key coor: an optional coordinate or None for random """ id = self._get_unique_id(key) #calculate the position coordinate h_adj = self.get_scroll_pane().get_hadjustment() v_adj = self.get_scroll_pane().get_vadjustment() if coor is None: coor = ( int(random.uniform(.25, .75)*h_adj.page_size + h_adj.get_value()), int(random.uniform(.25, .75)*v_adj.page_size + v_adj.get_value()), ) #get the new block block = self.get_new_block(key) block.set_coordinate(coor) block.set_rotation(0) block.get_param('id').set_value(id) Actions.ELEMENT_CREATE() return id ########################################################################### # Copy Paste ########################################################################### def copy_to_clipboard(self): """ Copy the selected blocks and connections into the clipboard. Returns: the clipboard """ #get selected blocks blocks = self.get_selected_blocks() if not blocks: return None #calc x and y min x_min, y_min = blocks[0].get_coordinate() for block in blocks: x, y = block.get_coordinate() x_min = min(x, x_min) y_min = min(y, y_min) #get connections between selected blocks connections = filter( lambda c: c.get_source().get_parent() in blocks and c.get_sink().get_parent() in blocks, self.get_connections(), ) clipboard = ( (x_min, y_min), [block.export_data() for block in blocks], [connection.export_data() for connection in connections], ) return clipboard def paste_from_clipboard(self, clipboard): """ Paste the blocks and connections from the clipboard. Args: clipboard: the nested data of blocks, connections """ selected = set() (x_min, y_min), blocks_n, connections_n = clipboard old_id2block = dict() #recalc the position h_adj = self.get_scroll_pane().get_hadjustment() v_adj = self.get_scroll_pane().get_vadjustment() x_off = h_adj.get_value() - x_min + h_adj.page_size/4 y_off = v_adj.get_value() - y_min + v_adj.page_size/4 #create blocks for block_n in blocks_n: block_key = block_n.find('key') if block_key == 'options': continue block = self.get_new_block(block_key) selected.add(block) #set params params_n = block_n.findall('param') for param_n in params_n: param_key = param_n.find('key') param_value = param_n.find('value') #setup id parameter if param_key == 'id': old_id2block[param_value] = block #if the block id is not unique, get a new block id if param_value in [bluck.get_id() for bluck in self.get_blocks()]: param_value = self._get_unique_id(param_value) #set value to key block.get_param(param_key).set_value(param_value) #move block to offset coordinate block.move((x_off, y_off)) #update before creating connections self.update() #create connections for connection_n in connections_n: source = old_id2block[connection_n.find('source_block_id')].get_source(connection_n.find('source_key')) sink = old_id2block[connection_n.find('sink_block_id')].get_sink(connection_n.find('sink_key')) self.connect(source, sink) #set all pasted elements selected for block in selected: selected = selected.union(set(block.get_connections())) self._selected_elements = list(selected) ########################################################################### # Modify Selected ########################################################################### def type_controller_modify_selected(self, direction): """ Change the registered type controller for the selected signal blocks. Args: direction: +1 or -1 Returns: true for change """ return any([sb.type_controller_modify(direction) for sb in self.get_selected_blocks()]) def port_controller_modify_selected(self, direction): """ Change port controller for the selected signal blocks. Args: direction: +1 or -1 Returns: true for changed """ return any([sb.port_controller_modify(direction) for sb in self.get_selected_blocks()]) def enable_selected(self, enable): """ Enable/disable the selected blocks. Args: enable: true to enable Returns: true if changed """ changed = False for selected_block in self.get_selected_blocks(): if selected_block.get_enabled() != enable: selected_block.set_enabled(enable) changed = True return changed def move_selected(self, delta_coordinate): """ Move the element and by the change in coordinates. Args: delta_coordinate: the change in coordinates """ for selected_block in self.get_selected_blocks(): selected_block.move(delta_coordinate) self.element_moved = True def rotate_selected(self, rotation): """ Rotate the selected blocks by multiples of 90 degrees. Args: rotation: the rotation in degrees Returns: true if changed, otherwise false. """ if not self.get_selected_blocks(): return False #initialize min and max coordinates min_x, min_y = self.get_selected_block().get_coordinate() max_x, max_y = self.get_selected_block().get_coordinate() #rotate each selected block, and find min/max coordinate for selected_block in self.get_selected_blocks(): selected_block.rotate(rotation) #update the min/max coordinate x, y = selected_block.get_coordinate() min_x, min_y = min(min_x, x), min(min_y, y) max_x, max_y = max(max_x, x), max(max_y, y) #calculate center point of slected blocks ctr_x, ctr_y = (max_x + min_x)/2, (max_y + min_y)/2 #rotate the blocks around the center point for selected_block in self.get_selected_blocks(): x, y = selected_block.get_coordinate() x, y = Utils.get_rotated_coordinate((x - ctr_x, y - ctr_y), rotation) selected_block.set_coordinate((x + ctr_x, y + ctr_y)) return True def remove_selected(self): """ Remove selected elements Returns: true if changed. """ changed = False for selected_element in self.get_selected_elements(): self.remove_element(selected_element) changed = True return changed def draw(self, gc, window): """ Draw the background and grid if enabled. Draw all of the elements in this flow graph onto the pixmap. Draw the pixmap to the drawable window of this flow graph. """ W,H = self.get_size() #draw the background gc.set_foreground(Colors.FLOWGRAPH_BACKGROUND_COLOR) window.draw_rectangle(gc, True, 0, 0, W, H) #draw multi select rectangle if self.mouse_pressed and (not self.get_selected_elements() or self.get_ctrl_mask()): #coordinates x1, y1 = self.press_coor x2, y2 = self.get_coordinate() #calculate top-left coordinate and width/height x, y = int(min(x1, x2)), int(min(y1, y2)) w, h = int(abs(x1 - x2)), int(abs(y1 - y2)) #draw gc.set_foreground(Colors.HIGHLIGHT_COLOR) window.draw_rectangle(gc, True, x, y, w, h) gc.set_foreground(Colors.BORDER_COLOR) window.draw_rectangle(gc, False, x, y, w, h) #draw blocks on top of connections for element in self.get_connections() + self.get_blocks(): element.draw(gc, window) #draw selected blocks on top of selected connections for selected_element in self.get_selected_connections() + self.get_selected_blocks(): selected_element.draw(gc, window) def update_selected(self): """ Remove deleted elements from the selected elements list. Update highlighting so only the selected are highlighted. """ selected_elements = self.get_selected_elements() elements = self.get_elements() #remove deleted elements for selected in selected_elements: if selected in elements: continue selected_elements.remove(selected) if self._old_selected_port and self._old_selected_port.get_parent() not in elements: self._old_selected_port = None if self._new_selected_port and self._new_selected_port.get_parent() not in elements: self._new_selected_port = None #update highlighting for element in elements: element.set_highlighted(element in selected_elements) def update(self): """ Call the top level rewrite and validate. Call the top level create labels and shapes. """ self.rewrite() self.validate() self.create_labels() self.create_shapes() ########################################################################## ## Get Selected ########################################################################## def unselect(self): """ Set selected elements to an empty set. """ self._selected_elements = [] def what_is_selected(self, coor, coor_m=None): """ What is selected? At the given coordinate, return the elements found to be selected. If coor_m is unspecified, return a list of only the first element found to be selected: Iterate though the elements backwards since top elements are at the end of the list. If an element is selected, place it at the end of the list so that is is drawn last, and hence on top. Update the selected port information. Args: coor: the coordinate of the mouse click coor_m: the coordinate for multi select Returns: the selected blocks and connections or an empty list """ selected_port = None selected = set() #check the elements for element in reversed(self.get_elements()): selected_element = element.what_is_selected(coor, coor_m) if not selected_element: continue #update the selected port information if selected_element.is_port(): if not coor_m: selected_port = selected_element selected_element = selected_element.get_parent() selected.add(selected_element) #place at the end of the list self.get_elements().remove(element) self.get_elements().append(element) #single select mode, break if not coor_m: break #update selected ports self._old_selected_port = self._new_selected_port self._new_selected_port = selected_port return list(selected) def get_selected_connections(self): """ Get a group of selected connections. Returns: sub set of connections in this flow graph """ selected = set() for selected_element in self.get_selected_elements(): if selected_element.is_connection(): selected.add(selected_element) return list(selected) def get_selected_blocks(self): """ Get a group of selected blocks. Returns: sub set of blocks in this flow graph """ selected = set() for selected_element in self.get_selected_elements(): if selected_element.is_block(): selected.add(selected_element) return list(selected) def get_selected_block(self): """ Get the selected block when a block or port is selected. Returns: a block or None """ return self.get_selected_blocks() and self.get_selected_blocks()[0] or None def get_selected_elements(self): """ Get the group of selected elements. Returns: sub set of elements in this flow graph """ return self._selected_elements def get_selected_element(self): """ Get the selected element. Returns: a block, port, or connection or None """ return self.get_selected_elements() and self.get_selected_elements()[0] or None def update_selected_elements(self): """ Update the selected elements. The update behavior depends on the state of the mouse button. When the mouse button pressed the selection will change when the control mask is set or the new selection is not in the current group. When the mouse button is released the selection will change when the mouse has moved and the control mask is set or the current group is empty. Attempt to make a new connection if the old and ports are filled. If the control mask is set, merge with the current elements. """ selected_elements = None if self.mouse_pressed: new_selections = self.what_is_selected(self.get_coordinate()) #update the selections if the new selection is not in the current selections #allows us to move entire selected groups of elements if self.get_ctrl_mask() or not ( new_selections and new_selections[0] in self.get_selected_elements() ): selected_elements = new_selections else: #called from a mouse release if not self.element_moved and (not self.get_selected_elements() or self.get_ctrl_mask()): selected_elements = self.what_is_selected(self.get_coordinate(), self.press_coor) #this selection and the last were ports, try to connect them if self._old_selected_port and self._new_selected_port and \ self._old_selected_port is not self._new_selected_port: try: self.connect(self._old_selected_port, self._new_selected_port) Actions.ELEMENT_CREATE() except: Messages.send_fail_connection() self._old_selected_port = None self._new_selected_port = None return #update selected elements if selected_elements is None: return old_elements = set(self.get_selected_elements()) self._selected_elements = list(set(selected_elements)) new_elements = set(self.get_selected_elements()) #if ctrl, set the selected elements to the union - intersection of old and new if self.get_ctrl_mask(): self._selected_elements = list( set.union(old_elements, new_elements) - set.intersection(old_elements, new_elements) ) Actions.ELEMENT_SELECT() ########################################################################## ## Event Handlers ########################################################################## def handle_mouse_context_press(self, coordinate, event): """ The context mouse button was pressed: If no elements were selected, perform re-selection at this coordinate. Then, show the context menu at the mouse click location. """ selections = self.what_is_selected(coordinate) if not set(selections).intersection(self.get_selected_elements()): self.set_coordinate(coordinate) self.mouse_pressed = True self.update_selected_elements() self.mouse_pressed = False self._context_menu.popup(None, None, None, event.button, event.time) def handle_mouse_selector_press(self, double_click, coordinate): """ The selector mouse button was pressed: Find the selected element. Attempt a new connection if possible. Open the block params window on a double click. Update the selection state of the flow graph. """ self.press_coor = coordinate self.set_coordinate(coordinate) self.time = 0 self.mouse_pressed = True if double_click: self.unselect() self.update_selected_elements() #double click detected, bring up params dialog if possible if double_click and self.get_selected_block(): self.mouse_pressed = False Actions.BLOCK_PARAM_MODIFY() def handle_mouse_selector_release(self, coordinate): """ The selector mouse button was released: Update the state, handle motion (dragging). And update the selected flowgraph elements. """ self.set_coordinate(coordinate) self.time = 0 self.mouse_pressed = False if self.element_moved: Actions.BLOCK_MOVE() self.element_moved = False self.update_selected_elements() def handle_mouse_motion(self, coordinate): """ The mouse has moved, respond to mouse dragging. Move a selected element to the new coordinate. Auto-scroll the scroll bars at the boundaries. """ #to perform a movement, the mouse must be pressed # (no longer checking pending events via gtk.events_pending() - always true in Windows) if not self.mouse_pressed: return #perform autoscrolling width, height = self.get_size() x, y = coordinate h_adj = self.get_scroll_pane().get_hadjustment() v_adj = self.get_scroll_pane().get_vadjustment() for pos, length, adj, adj_val, adj_len in ( (x, width, h_adj, h_adj.get_value(), h_adj.page_size), (y, height, v_adj, v_adj.get_value(), v_adj.page_size), ): #scroll if we moved near the border if pos-adj_val > adj_len-SCROLL_PROXIMITY_SENSITIVITY and adj_val+SCROLL_DISTANCE < length-adj_len: adj.set_value(adj_val+SCROLL_DISTANCE) adj.emit('changed') elif pos-adj_val < SCROLL_PROXIMITY_SENSITIVITY: adj.set_value(adj_val-SCROLL_DISTANCE) adj.emit('changed') #remove the connection if selected in drag event if len(self.get_selected_elements()) == 1 and self.get_selected_element().is_connection(): Actions.ELEMENT_DELETE() #move the selected elements and record the new coordinate X, Y = self.get_coordinate() if not self.get_ctrl_mask(): self.move_selected((int(x - X), int(y - Y))) self.set_coordinate((x, y)) #queue draw for animation self.queue_draw() gnuradio-3.7.2.1/grc/gui/Colors.py0000664000175000017500000000315112207440367016503 0ustar jcorganjcorgan""" Copyright 2008,2013 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ try: import pygtk pygtk.require('2.0') import gtk _COLORMAP = gtk.gdk.colormap_get_system() #create all of the colors def get_color(color_code): return _COLORMAP.alloc_color(color_code, True, True) HIGHLIGHT_COLOR = get_color('#00FFFF') BORDER_COLOR = get_color('black') #param entry boxes PARAM_ENTRY_TEXT_COLOR = get_color('black') ENTRYENUM_CUSTOM_COLOR = get_color('#EEEEEE') #flow graph color constants FLOWGRAPH_BACKGROUND_COLOR = get_color('#FFF9FF') #block color constants BLOCK_ENABLED_COLOR = get_color('#F1ECFF') BLOCK_DISABLED_COLOR = get_color('#CCCCCC') #connection color constants CONNECTION_ENABLED_COLOR = get_color('black') CONNECTION_DISABLED_COLOR = get_color('#999999') CONNECTION_ERROR_COLOR = get_color('red') except: print 'Unable to import Colors' gnuradio-3.7.2.1/grc/gui/__init__.py0000644000175000017500000000000111700377701016764 0ustar jcorganjcorgan gnuradio-3.7.2.1/grc/gui/ActionHandler.py0000664000175000017500000007001312245466767017774 0ustar jcorganjcorgan""" Copyright 2007-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ import os import signal from Constants import IMAGE_FILE_EXTENSION import Actions import pygtk pygtk.require('2.0') import gtk import gobject import Preferences from threading import Thread import Messages from .. base import ParseXML from MainWindow import MainWindow from PropsDialog import PropsDialog import Dialogs from FileDialogs import OpenFlowGraphFileDialog, SaveFlowGraphFileDialog, SaveImageFileDialog gobject.threads_init() class ActionHandler: """ The action handler will setup all the major window components, and handle button presses and flow graph operations from the GUI. """ def __init__(self, file_paths, platform): """ ActionHandler constructor. Create the main window, setup the message handler, import the preferences, and connect all of the action handlers. Finally, enter the gtk main loop and block. Args: file_paths: a list of flow graph file passed from command line platform: platform module """ self.clipboard = None for action in Actions.get_all_actions(): action.connect('activate', self._handle_action) #setup the main window self.platform = platform; self.main_window = MainWindow(platform) self.main_window.connect('delete-event', self._quit) self.main_window.connect('key-press-event', self._handle_key_press) self.get_page = self.main_window.get_page self.get_flow_graph = self.main_window.get_flow_graph self.get_focus_flag = self.main_window.get_focus_flag #setup the messages Messages.register_messenger(self.main_window.add_report_line) Messages.send_init(platform) #initialize self.init_file_paths = file_paths Actions.APPLICATION_INITIALIZE() #enter the mainloop gtk.main() def _handle_key_press(self, widget, event): """ Handle key presses from the keyboard and translate key combinations into actions. This key press handler is called prior to the gtk key press handler. This handler bypasses built in accelerator key handling when in focus because * some keys are ignored by the accelerators like the direction keys, * some keys are not registered to any accelerators but are still used. When not in focus, gtk and the accelerators handle the the key press. Returns: false to let gtk handle the key action """ # prevent key event stealing while the search box is active if self.main_window.btwin.search_entry.has_focus(): return False if not self.get_focus_flag(): return False return Actions.handle_key_press(event) def _quit(self, window, event): """ Handle the delete event from the main window. Generated by pressing X to close, alt+f4, or right click+close. This method in turns calls the state handler to quit. Returns: true """ Actions.APPLICATION_QUIT() return True def _handle_action(self, action): #print action ################################################## # Initalize/Quit ################################################## if action == Actions.APPLICATION_INITIALIZE: for action in Actions.get_all_actions(): action.set_sensitive(False) #set all actions disabled #enable a select few actions for action in ( Actions.APPLICATION_QUIT, Actions.FLOW_GRAPH_NEW, Actions.FLOW_GRAPH_OPEN, Actions.FLOW_GRAPH_SAVE_AS, Actions.FLOW_GRAPH_CLOSE, Actions.ABOUT_WINDOW_DISPLAY, Actions.FLOW_GRAPH_SCREEN_CAPTURE, Actions.HELP_WINDOW_DISPLAY, Actions.TYPES_WINDOW_DISPLAY, ): action.set_sensitive(True) if not self.init_file_paths: self.init_file_paths = Preferences.files_open() if not self.init_file_paths: self.init_file_paths = [''] for file_path in self.init_file_paths: if file_path: self.main_window.new_page(file_path) #load pages from file paths if Preferences.file_open() in self.init_file_paths: self.main_window.new_page(Preferences.file_open(), show=True) if not self.get_page(): self.main_window.new_page() #ensure that at least a blank page exists self.main_window.btwin.search_entry.hide() elif action == Actions.APPLICATION_QUIT: if self.main_window.close_pages(): gtk.main_quit() exit(0) ################################################## # Selections ################################################## elif action == Actions.ELEMENT_SELECT: pass #do nothing, update routines below elif action == Actions.NOTHING_SELECT: self.get_flow_graph().unselect() ################################################## # Enable/Disable ################################################## elif action == Actions.BLOCK_ENABLE: if self.get_flow_graph().enable_selected(True): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_DISABLE: if self.get_flow_graph().enable_selected(False): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) ################################################## # Cut/Copy/Paste ################################################## elif action == Actions.BLOCK_CUT: Actions.BLOCK_COPY() Actions.ELEMENT_DELETE() elif action == Actions.BLOCK_COPY: self.clipboard = self.get_flow_graph().copy_to_clipboard() elif action == Actions.BLOCK_PASTE: if self.clipboard: self.get_flow_graph().paste_from_clipboard(self.clipboard) self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) ################################################## # Create heir block ################################################## elif action == Actions.BLOCK_CREATE_HIER: # keeping track of coordinates for pasting later coords = self.get_flow_graph().get_selected_blocks()[0].get_coordinate() x,y = coords x_min = x y_min = y pads = []; params = []; # Save the state of the leaf blocks for block in self.get_flow_graph().get_selected_blocks(): # Check for string variables within the blocks for param in block.get_params(): for variable in self.get_flow_graph().get_variables(): # If a block parameter exists that is a variable, create a parameter for it if param.get_value() == variable.get_id(): params.append(param.get_value()) for flow_param in self.get_flow_graph().get_parameters(): # If a block parameter exists that is a parameter, create a parameter for it if param.get_value() == flow_param.get_id(): params.append(param.get_value()) # keep track of x,y mins for pasting later (x,y) = block.get_coordinate() if x < x_min: x_min = x if y < y_min: y_min = y for connection in block.get_connections(): # Get id of connected blocks source_id = connection.get_source().get_parent().get_id() sink_id = connection.get_sink().get_parent().get_id() # If connected block is not in the list of selected blocks create a pad for it if self.get_flow_graph().get_block(source_id) not in self.get_flow_graph().get_selected_blocks(): pads.append({'key': connection.get_sink().get_key(), 'coord': connection.get_source().get_coordinate(), 'block_id' : block.get_id(), 'direction': 'source'}) if self.get_flow_graph().get_block(sink_id) not in self.get_flow_graph().get_selected_blocks(): pads.append({'key': connection.get_source().get_key(), 'coord': connection.get_sink().get_coordinate(), 'block_id' : block.get_id(), 'direction': 'sink'}) # Copy the selected blocks and paste them into a new page # then move the flowgraph to a reasonable position Actions.BLOCK_COPY() self.main_window.new_page() Actions.BLOCK_PASTE() coords = (x_min,y_min) self.get_flow_graph().move_selected(coords) # Set flow graph to heir block type top_block = self.get_flow_graph().get_block("top_block") top_block.get_param('generate_options').set_value('hb') # this needs to be a unique name top_block.get_param('id').set_value('new_heir') # Remove the default samp_rate variable block that is created remove_me = self.get_flow_graph().get_block("samp_rate") self.get_flow_graph().remove_element(remove_me) # Add the param blocks along the top of the window x_pos = 150 for param in params: param_id = self.get_flow_graph().add_new_block('parameter',(x_pos,10)) param_block = self.get_flow_graph().get_block(param_id) param_block.get_param('id').set_value(param) x_pos = x_pos + 100 for pad in pads: # Add the pad sources and sinks within the new heir block if pad['direction'] == 'sink': # Add new PAD_SINK block to the canvas pad_id = self.get_flow_graph().add_new_block('pad_sink', pad['coord']) # setup the references to the sink and source pad_block = self.get_flow_graph().get_block(pad_id) pad_sink = pad_block.get_sinks()[0] source_block = self.get_flow_graph().get_block(pad['block_id']) source = source_block.get_source(pad['key']) # Ensure the port types match while pad_sink.get_type() != source.get_type(): # Special case for some blocks that have non-standard type names, e.g. uhd if pad_sink.get_type() == 'complex' and source.get_type() == 'fc32': break; pad_block.type_controller_modify(1) # Connect the pad to the proper sinks new_connection = self.get_flow_graph().connect(source,pad_sink) elif pad['direction'] == 'source': pad_id = self.get_flow_graph().add_new_block('pad_source', pad['coord']) # setup the references to the sink and source pad_block = self.get_flow_graph().get_block(pad_id) pad_source = pad_block.get_sources()[0] sink_block = self.get_flow_graph().get_block(pad['block_id']) sink = sink_block.get_sink(pad['key']) # Ensure the port types match while sink.get_type() != pad_source.get_type(): # Special case for some blocks that have non-standard type names, e.g. uhd if pad_source.get_type() == 'complex' and sink.get_type() == 'fc32': break; pad_block.type_controller_modify(1) # Connect the pad to the proper sinks new_connection = self.get_flow_graph().connect(pad_source,sink) # update the new heir block flow graph self.get_flow_graph().update() ################################################## # Move/Rotate/Delete/Create ################################################## elif action == Actions.BLOCK_MOVE: self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_ROTATE_CCW: if self.get_flow_graph().rotate_selected(90): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_ROTATE_CW: if self.get_flow_graph().rotate_selected(-90): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.ELEMENT_DELETE: if self.get_flow_graph().remove_selected(): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) Actions.NOTHING_SELECT() self.get_page().set_saved(False) elif action == Actions.ELEMENT_CREATE: self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) Actions.NOTHING_SELECT() self.get_page().set_saved(False) elif action == Actions.BLOCK_INC_TYPE: if self.get_flow_graph().type_controller_modify_selected(1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.BLOCK_DEC_TYPE: if self.get_flow_graph().type_controller_modify_selected(-1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.PORT_CONTROLLER_INC: if self.get_flow_graph().port_controller_modify_selected(1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) elif action == Actions.PORT_CONTROLLER_DEC: if self.get_flow_graph().port_controller_modify_selected(-1): self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) ################################################## # Window stuff ################################################## elif action == Actions.ABOUT_WINDOW_DISPLAY: Dialogs.AboutDialog(self.get_flow_graph().get_parent()) elif action == Actions.HELP_WINDOW_DISPLAY: Dialogs.HelpDialog() elif action == Actions.TYPES_WINDOW_DISPLAY: Dialogs.TypesDialog(self.get_flow_graph().get_parent()) elif action == Actions.ERRORS_WINDOW_DISPLAY: Dialogs.ErrorsDialog(self.get_flow_graph()) ################################################## # Param Modifications ################################################## elif action == Actions.BLOCK_PARAM_MODIFY: selected_block = self.get_flow_graph().get_selected_block() if selected_block: if PropsDialog(selected_block).run(): #save the new state self.get_flow_graph().update() self.get_page().get_state_cache().save_new_state(self.get_flow_graph().export_data()) self.get_page().set_saved(False) else: #restore the current state n = self.get_page().get_state_cache().get_current_state() self.get_flow_graph().import_data(n) self.get_flow_graph().update() ################################################## # Undo/Redo ################################################## elif action == Actions.FLOW_GRAPH_UNDO: n = self.get_page().get_state_cache().get_prev_state() if n: self.get_flow_graph().unselect() self.get_flow_graph().import_data(n) self.get_flow_graph().update() self.get_page().set_saved(False) elif action == Actions.FLOW_GRAPH_REDO: n = self.get_page().get_state_cache().get_next_state() if n: self.get_flow_graph().unselect() self.get_flow_graph().import_data(n) self.get_flow_graph().update() self.get_page().set_saved(False) ################################################## # New/Open/Save/Close ################################################## elif action == Actions.FLOW_GRAPH_NEW: self.main_window.new_page() elif action == Actions.FLOW_GRAPH_OPEN: file_paths = OpenFlowGraphFileDialog(self.get_page().get_file_path()).run() if file_paths: #open a new page for each file, show only the first for i,file_path in enumerate(file_paths): self.main_window.new_page(file_path, show=(i==0)) elif action == Actions.FLOW_GRAPH_CLOSE: self.main_window.close_page() elif action == Actions.FLOW_GRAPH_SAVE: #read-only or undefined file path, do save-as if self.get_page().get_read_only() or not self.get_page().get_file_path(): Actions.FLOW_GRAPH_SAVE_AS() #otherwise try to save else: try: ParseXML.to_file(self.get_flow_graph().export_data(), self.get_page().get_file_path()) self.get_flow_graph().grc_file_path = self.get_page().get_file_path() self.get_page().set_saved(True) except IOError: Messages.send_fail_save(self.get_page().get_file_path()) self.get_page().set_saved(False) elif action == Actions.FLOW_GRAPH_SAVE_AS: file_path = SaveFlowGraphFileDialog(self.get_page().get_file_path()).run() if file_path is not None: self.get_page().set_file_path(file_path) Actions.FLOW_GRAPH_SAVE() elif action == Actions.FLOW_GRAPH_SCREEN_CAPTURE: file_path = SaveImageFileDialog(self.get_page().get_file_path()).run() if file_path is not None: pixbuf = self.get_flow_graph().get_drawing_area().get_pixbuf() pixbuf.save(file_path, IMAGE_FILE_EXTENSION[1:]) ################################################## # Gen/Exec/Stop ################################################## elif action == Actions.FLOW_GRAPH_GEN: if not self.get_page().get_proc(): if not self.get_page().get_saved() or not self.get_page().get_file_path(): Actions.FLOW_GRAPH_SAVE() #only save if file path missing or not saved if self.get_page().get_saved() and self.get_page().get_file_path(): generator = self.get_page().get_generator() try: Messages.send_start_gen(generator.get_file_path()) generator.write() except Exception,e: Messages.send_fail_gen(e) else: self.generator = None elif action == Actions.FLOW_GRAPH_EXEC: if not self.get_page().get_proc(): Actions.FLOW_GRAPH_GEN() if self.get_page().get_saved() and self.get_page().get_file_path(): ExecFlowGraphThread(self) elif action == Actions.FLOW_GRAPH_KILL: if self.get_page().get_proc(): try: self.get_page().get_proc().kill() except: print "could not kill process: %d"%self.get_page().get_proc().pid elif action == Actions.PAGE_CHANGE: #pass and run the global actions pass elif action == Actions.RELOAD_BLOCKS: self.platform.loadblocks() self.main_window.btwin.clear(); self.platform.load_block_tree(self.main_window.btwin); elif action == Actions.FIND_BLOCKS: self.main_window.btwin.search_entry.show() self.main_window.set_focus(self.main_window.btwin.search_entry) elif action == Actions.OPEN_HIER: bn = []; for b in self.get_flow_graph().get_selected_blocks(): if b._grc_source: self.main_window.new_page(b._grc_source, show=True); elif action == Actions.BUSSIFY_SOURCES: n = {'name':'bus', 'type':'bus'} for b in self.get_flow_graph().get_selected_blocks(): b.bussify(n, 'source'); self.get_flow_graph()._old_selected_port = None; self.get_flow_graph()._new_selected_port = None; Actions.ELEMENT_CREATE(); elif action == Actions.BUSSIFY_SINKS: n = {'name':'bus', 'type':'bus'} for b in self.get_flow_graph().get_selected_blocks(): b.bussify(n, 'sink') self.get_flow_graph()._old_selected_port = None; self.get_flow_graph()._new_selected_port = None; Actions.ELEMENT_CREATE(); else: print '!!! Action "%s" not handled !!!'%action ################################################## # Global Actions for all States ################################################## #update general buttons Actions.ERRORS_WINDOW_DISPLAY.set_sensitive(not self.get_flow_graph().is_valid()) Actions.ELEMENT_DELETE.set_sensitive(bool(self.get_flow_graph().get_selected_elements())) Actions.BLOCK_PARAM_MODIFY.set_sensitive(bool(self.get_flow_graph().get_selected_block())) Actions.BLOCK_ROTATE_CCW.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BLOCK_ROTATE_CW.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) #update cut/copy/paste Actions.BLOCK_CUT.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BLOCK_COPY.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BLOCK_PASTE.set_sensitive(bool(self.clipboard)) #update enable/disable Actions.BLOCK_ENABLE.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BLOCK_DISABLE.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BLOCK_CREATE_HIER.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.OPEN_HIER.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BUSSIFY_SOURCES.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.BUSSIFY_SINKS.set_sensitive(bool(self.get_flow_graph().get_selected_blocks())) Actions.RELOAD_BLOCKS.set_sensitive(True) Actions.FIND_BLOCKS.set_sensitive(True) #set the exec and stop buttons self.update_exec_stop() #saved status Actions.FLOW_GRAPH_SAVE.set_sensitive(not self.get_page().get_saved()) self.main_window.update() try: #set the size of the flow graph area (if changed) new_size = self.get_flow_graph().get_option('window_size') if self.get_flow_graph().get_size() != tuple(new_size): self.get_flow_graph().set_size(*new_size) except: pass #draw the flow graph self.get_flow_graph().update_selected() self.get_flow_graph().queue_draw() return True #action was handled def update_exec_stop(self): """ Update the exec and stop buttons. Lock and unlock the mutex for race conditions with exec flow graph threads. """ sensitive = self.get_flow_graph().is_valid() and not self.get_page().get_proc() Actions.FLOW_GRAPH_GEN.set_sensitive(sensitive) Actions.FLOW_GRAPH_EXEC.set_sensitive(sensitive) Actions.FLOW_GRAPH_KILL.set_sensitive(self.get_page().get_proc() != None) class ExecFlowGraphThread(Thread): """Execute the flow graph as a new process and wait on it to finish.""" def __init__ (self, action_handler): """ ExecFlowGraphThread constructor. Args: action_handler: an instance of an ActionHandler """ Thread.__init__(self) self.update_exec_stop = action_handler.update_exec_stop self.flow_graph = action_handler.get_flow_graph() #store page and dont use main window calls in run self.page = action_handler.get_page() Messages.send_start_exec(self.page.get_generator().get_file_path()) #get the popen try: self.p = self.page.get_generator().get_popen() self.page.set_proc(self.p) #update self.update_exec_stop() self.start() except Exception, e: Messages.send_verbose_exec(str(e)) Messages.send_end_exec() def run(self): """ Wait on the executing process by reading from its stdout. Use gobject.idle_add when calling functions that modify gtk objects. """ #handle completion r = "\n" while(r): gobject.idle_add(Messages.send_verbose_exec, r) r = os.read(self.p.stdout.fileno(), 1024) gobject.idle_add(self.done) def done(self): """Perform end of execution tasks.""" Messages.send_end_exec() self.page.set_proc(None) self.update_exec_stop() gnuradio-3.7.2.1/grc/gui/Block.py0000664000175000017500000001773312207702530016300 0ustar jcorganjcorgan""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ from Element import Element import Utils import Colors from .. base import odict from Constants import BORDER_PROXIMITY_SENSITIVITY from Constants import \ BLOCK_LABEL_PADDING, \ PORT_SEPARATION, LABEL_SEPARATION, \ PORT_BORDER_SEPARATION, POSSIBLE_ROTATIONS import pygtk pygtk.require('2.0') import gtk import pango BLOCK_MARKUP_TMPL="""\ #set $foreground = $block.is_valid() and 'black' or 'red' $encode($block.get_name())""" class Block(Element): """The graphical signal block.""" def __init__(self): """ Block contructor. Add graphics related params to the block. """ #add the position param self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Coordinate', 'key': '_coordinate', 'type': 'raw', 'value': '(0, 0)', 'hide': 'all', }) )) self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Rotation', 'key': '_rotation', 'type': 'raw', 'value': '0', 'hide': 'all', }) )) Element.__init__(self) def get_coordinate(self): """ Get the coordinate from the position param. Returns: the coordinate tuple (x, y) or (0, 0) if failure """ try: #should evaluate to tuple coor = eval(self.get_param('_coordinate').get_value()) x, y = map(int, coor) fgW,fgH = self.get_parent().get_size() if x <= 0: x = 0 elif x >= fgW - BORDER_PROXIMITY_SENSITIVITY: x = fgW - BORDER_PROXIMITY_SENSITIVITY if y <= 0: y = 0 elif y >= fgH - BORDER_PROXIMITY_SENSITIVITY: y = fgH - BORDER_PROXIMITY_SENSITIVITY return (x, y) except: self.set_coordinate((0, 0)) return (0, 0) def set_coordinate(self, coor): """ Set the coordinate into the position param. Args: coor: the coordinate tuple (x, y) """ self.get_param('_coordinate').set_value(str(coor)) def get_rotation(self): """ Get the rotation from the position param. Returns: the rotation in degrees or 0 if failure """ try: #should evaluate to dict rotation = eval(self.get_param('_rotation').get_value()) return int(rotation) except: self.set_rotation(POSSIBLE_ROTATIONS[0]) return POSSIBLE_ROTATIONS[0] def set_rotation(self, rot): """ Set the rotation into the position param. Args: rot: the rotation in degrees """ self.get_param('_rotation').set_value(str(rot)) def create_shapes(self): """Update the block, parameters, and ports when a change occurs.""" Element.create_shapes(self) if self.is_horizontal(): self.add_area((0, 0), (self.W, self.H)) elif self.is_vertical(): self.add_area((0, 0), (self.H, self.W)) def create_labels(self): """Create the labels for the signal block.""" Element.create_labels(self) self._bg_color = self.get_enabled() and Colors.BLOCK_ENABLED_COLOR or Colors.BLOCK_DISABLED_COLOR layouts = list() #create the main layout layout = gtk.DrawingArea().create_pango_layout('') layouts.append(layout) layout.set_markup(Utils.parse_template(BLOCK_MARKUP_TMPL, block=self)) self.label_width, self.label_height = layout.get_pixel_size() #display the params markups = [param.get_markup() for param in self.get_params() if param.get_hide() not in ('all', 'part')] if markups: layout = gtk.DrawingArea().create_pango_layout('') layout.set_spacing(LABEL_SEPARATION*pango.SCALE) layout.set_markup('\n'.join(markups)) layouts.append(layout) w,h = layout.get_pixel_size() self.label_width = max(w, self.label_width) self.label_height += h + LABEL_SEPARATION width = self.label_width height = self.label_height #setup the pixmap pixmap = self.get_parent().new_pixmap(width, height) gc = pixmap.new_gc() gc.set_foreground(self._bg_color) pixmap.draw_rectangle(gc, True, 0, 0, width, height) #draw the layouts h_off = 0 for i,layout in enumerate(layouts): w,h = layout.get_pixel_size() if i == 0: w_off = (width-w)/2 else: w_off = 0 pixmap.draw_layout(gc, w_off, h_off, layout) h_off = h + h_off + LABEL_SEPARATION #create vertical and horizontal pixmaps self.horizontal_label = pixmap if self.is_vertical(): self.vertical_label = self.get_parent().new_pixmap(height, width) Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label) #calculate width and height needed self.W = self.label_width + 2*BLOCK_LABEL_PADDING self.H = max(*( [self.label_height+2*BLOCK_LABEL_PADDING] + [2*PORT_BORDER_SEPARATION + \ sum([port.H + PORT_SEPARATION for port in ports]) - PORT_SEPARATION for ports in (self.get_sources_gui(), self.get_sinks_gui())] + [4*PORT_BORDER_SEPARATION + \ sum([(port.H) + PORT_SEPARATION for port in ports]) - PORT_SEPARATION for ports in ([i for i in self.get_sources_gui() if i.get_type() == 'bus'], [i for i in self.get_sinks_gui() if i.get_type() == 'bus'])] )) def draw(self, gc, window): """ Draw the signal block with label and inputs/outputs. Args: gc: the graphics context window: the gtk window to draw on """ x, y = self.get_coordinate() #draw main block Element.draw( self, gc, window, bg_color=self._bg_color, border_color=self.is_highlighted() and Colors.HIGHLIGHT_COLOR or Colors.BORDER_COLOR, ) #draw label image if self.is_horizontal(): window.draw_drawable(gc, self.horizontal_label, 0, 0, x+BLOCK_LABEL_PADDING, y+(self.H-self.label_height)/2, -1, -1) elif self.is_vertical(): window.draw_drawable(gc, self.vertical_label, 0, 0, x+(self.H-self.label_height)/2, y+BLOCK_LABEL_PADDING, -1, -1) #draw ports for port in self.get_ports_gui(): port.draw(gc, window) def what_is_selected(self, coor, coor_m=None): """ Get the element that is selected. Args: coor: the (x,y) tuple coor_m: the (x_m, y_m) tuple Returns: this block, a port, or None """ for port in self.get_ports_gui(): port_selected = port.what_is_selected(coor, coor_m) if port_selected: return port_selected return Element.what_is_selected(self, coor, coor_m) gnuradio-3.7.2.1/gr-filter/0000755000175000017500000000000012237515112015214 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/CMakeLists.txt0000664000175000017500000000727512237515112017771 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-filter" ENABLE_GR_FILTER ENABLE_VOLK Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_FFT ENABLE_GR_BLOCKS ) GR_SET_GLOBAL(GR_FILTER_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/lib ${CMAKE_CURRENT_BINARY_DIR}/include ${GR_FFT_INCLUDE_DIRS} ) SET(GR_PKG_FILTER_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/filter) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_FILTER) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_FILTER_DESCRIPTION "GNU Radio Filter Blocks") CPACK_COMPONENT("filter_runtime" GROUP "Filter" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("filter_devel" GROUP "Filter" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("filter_python" GROUP "Filter" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;filter_runtime" ) CPACK_COMPONENT("filter_swig" GROUP "Filter" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;filter_python;filter_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/filter) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/filter) add_subdirectory(python/filter/design) add_subdirectory(python/filter/gui) add_subdirectory(grc) add_subdirectory(apps) endif(ENABLE_PYTHON) add_subdirectory(examples) add_subdirectory(doc) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-filter.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-filter.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-filter.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "filter_devel" ) endif(ENABLE_GR_FILTER) gnuradio-3.7.2.1/gr-filter/include/0000775000175000017500000000000012207440367016647 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/include/gnuradio/0000775000175000017500000000000012207440367020457 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/0000775000175000017500000000000012245466767021762 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/CMakeLists.txt0000664000175000017500000000732512245466767024531 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict2(name, sig, 'filter') build_utils.expand_template(d, inp) ") macro(expand_h root) #make a list of all the generated files unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the files add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #install rules for the generated h files list(APPEND generated_includes ${expanded_files_h}) endmacro(expand_h) ######################################################################## # Invoke macro to generate various sources ####################################################################### expand_h(fir_filter_XXX ccc ccf fcc fff fsf scc) expand_h(freq_xlating_fir_filter_XXX ccc ccf fcc fcf scf scc) expand_h(interp_fir_filter_XXX ccc ccf fcc fff fsf scc) expand_h(rational_resampler_base_XXX ccc ccf fcc fff fsf scc) add_custom_target(filter_generated_includes DEPENDS ${generated_includes} ) ######################################################################## # Install header files ######################################################################## install(FILES ${generated_includes} api.h adaptive_fir.h firdes.h fir_filter.h fir_filter_with_buffer.h fft_filter.h iir_filter.h interpolator_taps.h mmse_fir_interpolator_cc.h mmse_fir_interpolator_ff.h pm_remez.h polyphase_filterbank.h single_pole_iir.h adaptive_fir_ccc.h adaptive_fir_ccf.h dc_blocker_cc.h dc_blocker_ff.h filter_delay_fc.h fft_filter_ccc.h fft_filter_fff.h fractional_interpolator_cc.h fractional_interpolator_ff.h fractional_resampler_cc.h fractional_resampler_ff.h hilbert_fc.h iir_filter_ffd.h pfb_arb_resampler.h pfb_arb_resampler_ccf.h pfb_arb_resampler_fff.h pfb_channelizer_ccf.h pfb_decimator_ccf.h pfb_interpolator_ccf.h pfb_synthesizer_ccf.h single_pole_iir_filter_cc.h single_pole_iir_filter_ff.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/filter COMPONENT "filter_devel" ) gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/adaptive_fir_ccc.h0000664000175000017500000000576112245466767025411 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_ADAPTIVE_FIR_CCC_H #define INCLUDED_FILTER_ADAPTIVE_FIR_CCC_H #include #include namespace gr { namespace filter { /*! * \brief Adaptive FIR filter with gr_complex input, gr_complex output and gr_complex taps * \ingroup filter_blk * * \details * This is a base class to implement an adaptive FIR * filter. Generally, another block will inherit from this one to * build a new type of adaptive filter such as an equalizer. * * This class implements two functions that are designed to be * overloaded by the child class: error(gr_complex out) and * update_tap(gr_complex tap, gr_complex in). * * The error() function calculates the error value that will be * used to adjust the taps. The update_tap function then uses the * error and the input signal value to update a particular * tap. Typically, the error is calculated for a given output and * then this is used in a loop to update all of the filter taps in * a loop: * * \code * d_error = error(sum); * for(k = 0; k < l; k++) { * update_tap(d_taps[ntaps-k-1], in[i+k]); * } * \endcode * * See digital::cma_equalizer_cc and digital::lms_dd_equalizer_cc * for example usage. */ class FILTER_API adaptive_fir_ccc : virtual public sync_decimator { protected: public: // gr::filter::adaptive_fir_ccc::sptr typedef boost::shared_ptr sptr; /*! * \brief Adaptive FIR filter with gr_complex input, gr_complex output and gr_complex taps * * \param name Provides a name to identify this type of algorithm * \param decimation (interger) decimation rate of the filter * \param taps (complex) filter taps */ static sptr make(const char *name, int decimation, const std::vector &taps); virtual void set_taps(const std::vector &taps) = 0; virtual std::vector taps() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_ADAPTIVE_FIR_CCC_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fractional_resampler_cc.h0000664000175000017500000000370612207440367026764 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_RESAMPLER_CC_H #define INCLUDED_FRACTIONAL_RESAMPLER_CC_H #include #include namespace gr { namespace filter { /*! * \brief resampling MMSE filter with complex input, complex output * \ingroup resamplers_blk */ class FILTER_API fractional_resampler_cc : virtual public block { public: // gr::filter::fractional_resampler_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Build the resampling MMSE filter (complex input, complex output) * * \param phase_shift The phase shift of the output signal to the input * \param resamp_ratio The resampling ratio = input_rate / output_rate. */ static sptr make(float phase_shift, float resamp_ratio); virtual float mu() const = 0; virtual float resamp_ratio() const = 0; virtual void set_mu (float mu) = 0; virtual void set_resamp_ratio(float resamp_ratio) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_RESAMPLER_FF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/iir_filter_ffd.h0000664000175000017500000000525612244272666025102 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_IIR_FILTER_FFD_H #define INCLUDED_IIR_FILTER_FFD_H #include #include namespace gr { namespace filter { /*! * \brief IIR filter with float input, float output and double taps * \ingroup filter_blk * * \details * This filter uses the Direct Form I implementation, where * \p fftaps contains the feed-forward taps, and \p fbtaps the feedback ones. * * \p oldstyle: The old style of the IIR filter uses feedback * taps that are negative of what most definitions use (scipy * and Matlab among them). This parameter keeps using the old * GNU Radio style and is set to TRUE by default. When taps * generated from scipy, Matlab, or gr_filter_design, use the * new style by setting this to FALSE. * * The input and output satisfy a difference equation of the form \f[ y[n] - \sum_{k=1}^{M} a_k y[n-k] = \sum_{k=0}^{N} b_k x[n-k] \f] \xmlonly y[n] - \sum_{k=1}^{M} a_k y[n-k] = \sum_{k=0}^{N} b_k x[n-k] \endxmlonly * with the corresponding rational system function \f[ H(z) = \frac{\sum_{k=0}^{M} b_k z^{-k}}{1 - \sum_{k=1}^{N} a_k z^{-k}} \f] \xmlonly H(z) = \ frac{\sum_{k=0}^{M} b_k z^{-k}}{1 - \sum_{k=1}^{N} a_k z^{-k}} \endxmlonly */ class FILTER_API iir_filter_ffd : virtual public sync_block { public: // gr::filter::iir_filter_ffd::sptr typedef boost::shared_ptr sptr; static sptr make(const std::vector &fftaps, const std::vector &fbtaps, bool oldstyle=true); virtual void set_taps(const std::vector &fftaps, const std::vector &fbtaps) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_IIR_FILTER_FFD_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fractional_resampler_ff.h0000664000175000017500000000367612207440367027000 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_RESAMPLER_FF_H #define INCLUDED_FRACTIONAL_RESAMPLER_FF_H #include #include namespace gr { namespace filter { /*! * \brief Resampling MMSE filter with float input, float output * \ingroup resamplers_blk */ class FILTER_API fractional_resampler_ff : virtual public block { public: // gr::filter::fractional_resampler_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Build the resampling MMSE filter (float input, float output) * * \param phase_shift The phase shift of the output signal to the input * \param resamp_ratio The resampling ratio = input_rate / output_rate. */ static sptr make(float phase_shift, float resamp_ratio); virtual float mu() const = 0; virtual float resamp_ratio() const = 0; virtual void set_mu (float mu) = 0; virtual void set_resamp_ratio(float resamp_ratio) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_RESAMPLER_FF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/mmse_fir_interpolator_ff.h0000664000175000017500000000477712207440367027212 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _MMSE_FIR_INTERPOLATOR_FF_H_ #define _MMSE_FIR_INTERPOLATOR_FF_H_ #include #include #include namespace gr { namespace filter { /*! * \brief Compute intermediate samples between signal samples x(k*Ts) * \ingroup filter_primitive * * \details * This implements a Mininum Mean Squared Error interpolator with * 8 taps. It is suitable for signals where the bandwidth of * interest B = 1/(4*Ts) Where Ts is the time between samples. * * Although mu, the fractional delay, is specified as a float, it * is actually quantized. 0.0 <= mu <= 1.0. That is, mu is * quantized in the interpolate method to 32nd's of a sample. * * For more information, in the GNU Radio source code, see: * \li gr-filter/lib/gen_interpolator_taps/README * \li gr-filter/lib/gen_interpolator_taps/praxis.txt */ class FILTER_API mmse_fir_interpolator_ff { public: mmse_fir_interpolator_ff(); ~mmse_fir_interpolator_ff(); unsigned ntaps() const; unsigned nsteps() const; /*! * \brief compute a single interpolated output value. * \p input must have ntaps() valid entries. * input[0] .. input[ntaps() - 1] are referenced to compute the output value. * * \p mu must be in the range [0, 1] and specifies the fractional delay. * * \returns the interpolated input value. */ float interpolate(const float input[], float mu) const; protected: std::vector filters; }; } /* namespace filter */ } /* namespace gr */ #endif /* _MMSE_FIR_INTERPOLATOR_FF_H_ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/rational_resampler_base_XXX.h.t0000664000175000017500000000335612207440367030012 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace filter { /*! * \brief Rational Resampling Polyphase FIR filter with @I_TYPE@ * input, @O_TYPE@ output and @TAP_TYPE@ taps. * \ingroup resamplers_blk */ class FILTER_API @NAME@ : virtual public block { public: // gr::filter::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(unsigned interpolation, unsigned decimation, const std::vector<@TAP_TYPE@> &taps); virtual unsigned interpolation() const = 0; virtual unsigned decimation() const = 0; virtual void set_taps(const std::vector<@TAP_TYPE@> &taps) = 0; virtual std::vector<@TAP_TYPE@> taps() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_arb_resampler_ccf.h0000664000175000017500000001015112207440367026373 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_ARB_RESAMPLER_CCF_H #define INCLUDED_PFB_ARB_RESAMPLER_CCF_H #include #include namespace gr { namespace filter { /*! * \brief Polyphase filterbank arbitrary resampler with * gr_complex input, gr_complex output and float taps * \ingroup resamplers_blk * * \details * This block takes in a signal stream and calls * gr::filter::kernel::pfb_arb_resampler_ccf to perform * arbitrary resampling on the stream. * * Output sampling rate is \p rate * input rate. */ class FILTER_API pfb_arb_resampler_ccf : virtual public block { public: // gr::filter::pfb_arb_resampler_ccf::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank arbitray resampler. * \param rate (float) Specifies the resampling rate to use * \param taps (vector/list of floats) The prototype filter to populate the filterbank. The taps * should be generated at the filter_size sampling rate. * \param filter_size (unsigned int) The number of filters in the filter bank. This is directly * related to quantization noise introduced during the resampling. * Defaults to 32 filters. */ static sptr make(float rate, const std::vector &taps, unsigned int filter_size=32); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. */ virtual void set_taps(const std::vector &taps) = 0; /*! * Return a vector> of the filterbank taps */ virtual std::vector > taps() const = 0; /*! * Print all of the filterbank taps to screen. */ virtual void print_taps() = 0; /*! * Sets the resampling rate of the block. */ virtual void set_rate (float rate) = 0; /*! * Sets the current phase offset in radians (0 to 2pi). */ virtual void set_phase(float ph) = 0; /*! * Gets the current phase of the resampler in radians (2 to 2pi). */ virtual float phase() const = 0; /*! * Gets the number of taps per filter. */ virtual unsigned int taps_per_filter() const = 0; /*! * Gets the interpolation rate of the filter. */ virtual unsigned int interpolation_rate() const = 0; /*! * Gets the decimation rate of the filter. */ virtual unsigned int decimation_rate() const =0; /*! * Gets the fractional rate of the filter. */ virtual float fractional_rate() const = 0; /*! * Get the group delay of the filter. */ virtual int group_delay() const = 0; /*! * Calculates the phase offset expected by a sine wave of * frequency \p freq and sampling rate \p fs (assuming input * sine wave has 0 degree phase). */ virtual float phase_offset(float freq, float fs) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_ARB_RESAMPLER_CCF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/adaptive_fir_ccf.h0000664000175000017500000000551212245466767025406 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_ADAPTIVE_FIR_CCF_H #define INCLUDED_FILTER_ADAPTIVE_FIR_CCF_H #include #include namespace gr { namespace filter { /*! * \brief Adaptive FIR filter with gr_complex input, gr_complex output and float taps * \ingroup filter_blk * * \details * This is a base class to implement an adaptive FIR * filter. Generally, another block will inherit from this one to * build a new type of adaptive filter such as an equalizer. * * This class implements two functions that are designed to be * overloaded by the child class: error(gr_complex out) and * update_tap(float tap, gr_complex in). * * The error() function calculates the error value that will be * used to adjust the taps. The update_tap function then uses the * error and the input signal value to update a particular * tap. Typically, the error is calculated for a given output and * then this is used in a loop to update all of the filter taps in * a loop: * * \code * d_error = error(sum); * for(k = 0; k < l; k++) { * update_tap(d_taps[ntaps-k-1], in[i+k]); * } * \endcode */ class FILTER_API adaptive_fir_ccf : virtual public sync_decimator { public: // gr::filter::adaptive_fir_ccf::sptr typedef boost::shared_ptr sptr; /*! * \brief Adaptive FIR filter with gr_complex input, gr_complex output and float taps * * \param name Provides a name to identify this type of algorithm * \param decimation (interger) decimation rate of the filter * \param taps (real) filter taps */ static sptr make(const char *name, int decimation, const std::vector &taps); virtual void set_taps(const std::vector &taps) = 0; virtual std::vector taps() = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_ADAPTIVE_FIR_CCF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fir_filter.h0000664000175000017500000001365212207440367024251 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FIR_FILTER_H #define INCLUDED_FILTER_FIR_FILTER_H #include #include #include namespace gr { namespace filter { namespace kernel { class FILTER_API fir_filter_fff { public: fir_filter_fff(int decimation, const std::vector &taps); ~fir_filter_fff(); void set_taps(const std::vector &taps); void update_tap(float t, unsigned int index); std::vector taps() const; unsigned int ntaps() const; float filter(const float input[]); void filterN(float output[], const float input[], unsigned long n); void filterNdec(float output[], const float input[], unsigned long n, unsigned int decimate); protected: std::vector d_taps; unsigned int d_ntaps; float **d_aligned_taps; float *d_output; int d_align; int d_naligned; }; /**************************************************************/ class FILTER_API fir_filter_ccf { public: fir_filter_ccf(int decimation, const std::vector &taps); ~fir_filter_ccf(); void set_taps(const std::vector &taps); void update_tap(float t, unsigned int index); std::vector taps() const; unsigned int ntaps() const; gr_complex filter(const gr_complex input[]); void filterN(gr_complex output[], const gr_complex input[], unsigned long n); void filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned int decimate); protected: std::vector d_taps; unsigned int d_ntaps; float **d_aligned_taps; gr_complex *d_output; int d_align; int d_naligned; }; /**************************************************************/ class FILTER_API fir_filter_fcc { public: fir_filter_fcc(int decimation, const std::vector &taps); ~fir_filter_fcc(); void set_taps(const std::vector &taps); void update_tap(gr_complex t, unsigned int index); std::vector taps() const; unsigned int ntaps() const; gr_complex filter(const float input[]); void filterN(gr_complex output[], const float input[], unsigned long n); void filterNdec(gr_complex output[], const float input[], unsigned long n, unsigned int decimate); protected: std::vector d_taps; unsigned int d_ntaps; gr_complex **d_aligned_taps; gr_complex *d_output; int d_align; int d_naligned; }; /**************************************************************/ class FILTER_API fir_filter_ccc { public: fir_filter_ccc(int decimation, const std::vector &taps); ~fir_filter_ccc(); void set_taps(const std::vector &taps); void update_tap(gr_complex t, unsigned int index); std::vector taps() const; unsigned int ntaps() const; gr_complex filter(const gr_complex input[]); void filterN(gr_complex output[], const gr_complex input[], unsigned long n); void filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned int decimate); protected: std::vector d_taps; unsigned int d_ntaps; gr_complex **d_aligned_taps; gr_complex *d_output; int d_align; int d_naligned; }; /**************************************************************/ class FILTER_API fir_filter_scc { public: fir_filter_scc(int decimation, const std::vector &taps); ~fir_filter_scc(); void set_taps(const std::vector &taps); void update_tap(gr_complex t, unsigned int index); std::vector taps() const; unsigned int ntaps() const; gr_complex filter(const short input[]); void filterN(gr_complex output[], const short input[], unsigned long n); void filterNdec(gr_complex output[], const short input[], unsigned long n, unsigned int decimate); protected: std::vector d_taps; unsigned int d_ntaps; gr_complex **d_aligned_taps; gr_complex *d_output; int d_align; int d_naligned; }; /**************************************************************/ class FILTER_API fir_filter_fsf { public: fir_filter_fsf(int decimation, const std::vector &taps); ~fir_filter_fsf(); void set_taps(const std::vector &taps); void update_tap(float t, unsigned int index); std::vector taps() const; unsigned int ntaps() const; short filter(const float input[]); void filterN(short output[], const float input[], unsigned long n); void filterNdec(short output[], const float input[], unsigned long n, unsigned int decimate); protected: std::vector d_taps; unsigned int d_ntaps; float **d_aligned_taps; short *d_output; int d_align; int d_naligned; }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FIR_FILTER_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/single_pole_iir_filter_ff.h0000664000175000017500000000441312207440367027302 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SINGLE_POLE_IIR_FILTER_FF_H #define INCLUDED_SINGLE_POLE_IIR_FILTER_FF_H #include #include #include #include namespace gr { namespace filter { /*! * \brief single pole IIR filter with float input, float output * \ingroup filter_blk * * \details * The input and output satisfy a difference equation of the form \htmlonly \f{ y[n] - (1-alpha) y[n-1] = alpha x[n] \f} \endhtmlonly \xmlonly y[n] - (1-alpha) y[n-1] = alpha x[n] \endxmlonly * with the corresponding rational system function \htmlonly \f{ H(z) = \frac{alpha}{1 - (1-alpha) z^{-1}} \f} \endhtmlonly \xmlonly H(z) = \ frac{alpha}{1 - (1-alpha) z^{-1}} \endxmlonly * Note that some texts define the system function with a + in the * denominator. If you're using that convention, you'll need to * negate the feedback tap. */ class FILTER_API single_pole_iir_filter_ff : virtual public sync_block { public: // gr::filter::single_pole_iir_filter_ff::sptr typedef boost::shared_ptr sptr; static sptr make(double alpha, unsigned int vlen=1); virtual void set_taps (double alpha) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_SINGLE_POLE_IIR_FILTER_FF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_decimator_ccf.h0000664000175000017500000001211312245466767025542 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_DECIMATOR_CCF_H #define INCLUDED_PFB_DECIMATOR_CCF_H #include #include namespace gr { namespace filter { /*! * \brief Polyphase filterbank bandpass decimator with gr_complex * input, gr_complex output and float taps * \ingroup channelizers_blk * * \details * This block takes in a signal stream and performs interger down- * sampling (decimation) with a polyphase filterbank. The first * input is the integer specifying how much to decimate by. The * second input is a vector (Python list) of floating-point taps * of the prototype filter. The third input specifies the channel * to extract. By default, the zeroth channel is used, which is * the baseband channel (first Nyquist zone). * * The channel parameter specifies which channel to use * since this class is capable of bandpass decimation. Given a * complex input stream at a sampling rate of fs and a * decimation rate of decim, the input frequency domain * is split into decim channels that represent the * Nyquist zones. Using the polyphase filterbank, we can select * any one of these channels to decimate. * * The output signal will be the basebanded and decimated signal * from that channel. This concept is very similar to the PFB * channelizer (see #gr::filter::pfb_channelizer_ccf) where only a single * channel is extracted at a time. * * The filter's taps should be based on the sampling rate before * decimation. * * For example, using the GNU Radio's firdes utility to building * filters, we build a low-pass filter with a sampling rate of * fs, a 3-dB bandwidth of BW and a transition * bandwidth of TB. We can also specify the out-of-band * attenuation to use, ATT, and the filter window * function (a Blackman-harris window in this case). The first * input is the gain of the filter, which we specify here as * unity. * * self._taps = filter.firdes.low_pass_2(1, fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * The PFB decimator code takes the taps generated above and * builds a set of filters. The set contains decim number * of filters and each filter contains ceil(taps.size()/decim) * number of taps. Each tap from the filter prototype is * sequentially inserted into the next filter. When all of the * input taps are used, the remaining filters in the filterbank * are filled out with 0's to make sure each filter has the same * number of taps. * * The theory behind this block can be found in Chapter 6 of * the following book. * * f. harris, "Multirate Signal Processing for Communication * Systems," Upper Saddle River, NJ: Prentice Hall, Inc. 2004. */ class FILTER_API pfb_decimator_ccf : virtual public sync_block { public: // gr::filter::pfb_decimator_ccf::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank decimator. * \param decim (unsigned integer) Specifies the decimation rate to use * \param taps (vector/list of floats) The prototype filter to populate the filterbank. * \param channel (unsigned integer) Selects the channel to return [default=0]. */ static sptr make(unsigned int decim, const std::vector &taps, unsigned int channel); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. */ virtual void set_taps(const std::vector &taps) = 0; /*! * Return a vector> of the filterbank taps */ virtual std::vector > taps() const = 0; /*! * Print all of the filterbank taps to screen. */ virtual void print_taps() = 0; //virtual void set_channel(unsigned int channel) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_DECIMATOR_CCF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fir_filter_with_buffer.h0000664000175000017500000002067512207440367026640 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FIR_FILTER_WITH_BUFFER_H #define INCLUDED_FILTER_FIR_FILTER_WITH_BUFFER_H #include #include #include namespace gr { namespace filter { namespace kernel { /*! * \brief FIR with internal buffer for float input, float output and float taps. * \ingroup filter */ class FILTER_API fir_filter_with_buffer_fff { private: std::vector d_taps; unsigned int d_ntaps; float *d_buffer_ptr; float *d_buffer; unsigned int d_idx; float **d_aligned_taps; float *d_output; int d_align; int d_naligned; public: // CONSTRUCTORS /*! * \brief construct new FIR with given taps. * * Note that taps must be in forward order, e.g., coefficient 0 is * stored in new_taps[0], coefficient 1 is stored in * new_taps[1], etc. */ fir_filter_with_buffer_fff(const std::vector &taps); ~fir_filter_with_buffer_fff(); // MANIPULATORS /*! * \brief compute a single output value. * * \p input is a single input value of the filter type * * \returns the filtered input value. */ float filter(float input); /*! * \brief compute a single output value; designed for decimating filters. * * \p input is a single input value of the filter type. The value of dec is the * decimating value of the filter, so input[] must have dec valid values. * The filter pushes dec number of items onto the circ. buffer before computing * a single output. * * \returns the filtered input value. */ float filter(const float input[], unsigned long dec); /*! * \brief compute an array of N output values. * * \p input must have (n - 1 + ntaps()) valid entries. * input[0] .. input[n - 1 + ntaps() - 1] are referenced to compute the output values. */ void filterN(float output[], const float input[], unsigned long n); /*! * \brief compute an array of N output values, decimating the input * * \p input must have (decimate * (n - 1) + ntaps()) valid entries. * input[0] .. input[decimate * (n - 1) + ntaps() - 1] are referenced to * compute the output values. */ void filterNdec(float output[], const float input[], unsigned long n, unsigned long decimate); // ACCESSORS /*! * \return number of taps in filter. */ unsigned int ntaps() const { return d_ntaps; } /*! * \brief install \p new_taps as the current taps. */ void set_taps(const std::vector &taps); /*! * \return current taps */ std::vector taps() const; }; /**************************************************************/ /*! * \brief FIR with internal buffer for gr_complex input, gr_complex output and gr_complex taps. * \ingroup filter */ class FILTER_API fir_filter_with_buffer_ccc { private: std::vector d_taps; unsigned int d_ntaps; gr_complex *d_buffer_ptr; gr_complex *d_buffer; unsigned int d_idx; gr_complex **d_aligned_taps; gr_complex *d_output; int d_align; int d_naligned; public: // CONSTRUCTORS /*! * \brief construct new FIR with given taps. * * Note that taps must be in forward order, e.g., coefficient 0 is * stored in new_taps[0], coefficient 1 is stored in * new_taps[1], etc. */ fir_filter_with_buffer_ccc(const std::vector &taps); ~fir_filter_with_buffer_ccc(); // MANIPULATORS /*! * \brief compute a single output value. * * \p input is a single input value of the filter type * * \returns the filtered input value. */ gr_complex filter(gr_complex input); /*! * \brief compute a single output value; designed for decimating filters. * * \p input is a single input value of the filter type. The value of dec is the * decimating value of the filter, so input[] must have dec valid values. * The filter pushes dec number of items onto the circ. buffer before computing * a single output. * * \returns the filtered input value. */ gr_complex filter(const gr_complex input[], unsigned long dec); /*! * \brief compute an array of N output values. * * \p input must have (n - 1 + ntaps()) valid entries. * input[0] .. input[n - 1 + ntaps() - 1] are referenced to compute the output values. */ void filterN(gr_complex output[], const gr_complex input[], unsigned long n); /*! * \brief compute an array of N output values, decimating the input * * \p input must have (decimate * (n - 1) + ntaps()) valid entries. * input[0] .. input[decimate * (n - 1) + ntaps() - 1] are referenced to * compute the output values. */ void filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned long decimate); // ACCESSORS /*! * \return number of taps in filter. */ unsigned int ntaps() const { return d_ntaps; } /*! * \brief install \p new_taps as the current taps. */ void set_taps(const std::vector &taps); /*! * \return current taps */ std::vector taps() const; }; /**************************************************************/ /*! * \brief FIR with internal buffer for gr_complex input, gr_complex output and gr_complex taps. * \ingroup filter */ class FILTER_API fir_filter_with_buffer_ccf { private: std::vector d_taps; unsigned int d_ntaps; gr_complex *d_buffer_ptr; gr_complex *d_buffer; unsigned int d_idx; float **d_aligned_taps; gr_complex *d_output; int d_align; int d_naligned; public: // CONSTRUCTORS /*! * \brief construct new FIR with given taps. * * Note that taps must be in forward order, e.g., coefficient 0 is * stored in new_taps[0], coefficient 1 is stored in * new_taps[1], etc. */ fir_filter_with_buffer_ccf(const std::vector &taps); ~fir_filter_with_buffer_ccf(); // MANIPULATORS /*! * \brief compute a single output value. * * \p input is a single input value of the filter type * * \returns the filtered input value. */ gr_complex filter(gr_complex input); /*! * \brief compute a single output value; designed for decimating filters. * * \p input is a single input value of the filter type. The value of dec is the * decimating value of the filter, so input[] must have dec valid values. * The filter pushes dec number of items onto the circ. buffer before computing * a single output. * * \returns the filtered input value. */ gr_complex filter(const gr_complex input[], unsigned long dec); /*! * \brief compute an array of N output values. * * \p input must have (n - 1 + ntaps()) valid entries. * input[0] .. input[n - 1 + ntaps() - 1] are referenced to compute the output values. */ void filterN(gr_complex output[], const gr_complex input[], unsigned long n); /*! * \brief compute an array of N output values, decimating the input * * \p input must have (decimate * (n - 1) + ntaps()) valid entries. * input[0] .. input[decimate * (n - 1) + ntaps() - 1] are referenced to * compute the output values. */ void filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned long decimate); // ACCESSORS /*! * \return number of taps in filter. */ unsigned int ntaps() const { return d_ntaps; } /*! * \brief install \p new_taps as the current taps. */ void set_taps(const std::vector &taps); /*! * \return current taps */ std::vector taps() const; }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FIR_FILTER_WITH_BUFFER_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/freq_xlating_fir_filter_XXX.h.t0000664000175000017500000000600712207440367030021 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * WARNING: This file is automatically generated by cmake. * Any changes made to this file will be overwritten. */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace filter { /*! * \brief FIR filter combined with frequency translation with * @I_TYPE@ input, @O_TYPE@ output and @TAP_TYPE@ taps * * \ingroup channelizers_blk * * This class efficiently combines a frequency translation * (typically "down conversion") with a FIR filter (typically * low-pass) and decimation. It is ideally suited for a "channel * selection filter" and can be efficiently used to select and * decimate a narrow band signal out of wide bandwidth input. * * Uses a single input array to produce a single output array. * Additional inputs and/or outputs are ignored. */ class FILTER_API @BASE_NAME@ : virtual public sync_decimator { public: // gr::filter::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! * \brief FIR filter with @I_TYPE@ input, @O_TYPE@ output, and * @TAP_TYPE@ taps that also frequency translates a signal from * \p center_freq. * * Construct a FIR filter with the given taps and a composite * frequency translation that shifts center_freq down to zero * Hz. The frequency translation logically comes before the * filtering operation. * * \param decimation set the integer decimation rate * \param taps a vector/list of taps of type @TAP_TYPE@ * \param center_freq Center frequency of signal to down convert from (Hz) * \param sampling_freq Sampling rate of signal (in Hz) */ static sptr make(int decimation, const std::vector<@TAP_TYPE@> &taps, double center_freq, double sampling_freq); virtual void set_center_freq(double center_freq) = 0; virtual double center_freq() const = 0; virtual void set_taps(const std::vector<@TAP_TYPE@> &taps) = 0; virtual std::vector<@TAP_TYPE@> taps() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fft_filter_ccc.h0000664000175000017500000000611612207440367025055 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FFT_FILTER_CCC_H #define INCLUDED_FILTER_FFT_FILTER_CCC_H #include #include namespace gr { namespace filter { /*! * \brief Fast FFT filter with gr_complex input, gr_complex output and gr_complex taps * \ingroup filter_blk * * \details * This block implements a complex decimating filter using the * fast convolution method via an FFT. The decimation factor is an * interger that is greater than or equal to 1. * * The filter takes a set of complex (or real) taps to use in the * filtering operation. These taps can be defined as anything that * satisfies the user's filtering needs. For standard filters such * as lowpass, highpass, bandpass, etc., the filter.firdes and * filter.optfir classes provide convenient generating methods. * * This filter is implemented by using the FFTW package to perform * the required FFTs. An optional argument, nthreads, may be * passed to the constructor (or set using the set_nthreads member * function) to split the FFT among N number of threads. This can * improve performance on very large FFTs (that is, if the number * of taps used is very large) if you have enough threads/cores to * support it. */ class FILTER_API fft_filter_ccc : virtual public sync_decimator { public: // gr::filter::fft_filter_ccc::sptr typedef boost::shared_ptr sptr; /*! * Build an FFT filter blocks. * * \param decimation >= 1 * \param taps complex filter taps * \param nthreads number of threads for the FFT to use */ static sptr make(int decimation, const std::vector &taps, int nthreads=1); virtual void set_taps(const std::vector &taps) = 0; virtual std::vector taps() const = 0; /*! * \brief Set number of threads to use. */ virtual void set_nthreads(int n) = 0; /*! * \brief Get number of threads being used. */ virtual int nthreads() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FFT_FILTER_CCC_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fractional_interpolator_cc.h0000664000175000017500000000371312207440367027512 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_INTERPOLATOR_CC_H #define INCLUDED_FRACTIONAL_INTERPOLATOR_CC_H #include #include namespace gr { namespace filter { /*! * \brief Interpolating MMSE filter with complex input, complex output * \ingroup resamplers_blk */ class FILTER_API fractional_interpolator_cc : virtual public block { public: // gr::filter::fractional_interpolator_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Build the interpolating MMSE filter (complex input, complex output) * * \param phase_shift The phase shift of the output signal to the input * \param interp_ratio The interpolation ratio = input_rate / output_rate. */ static sptr make(float phase_shift, float interp_ratio); virtual float mu() const = 0; virtual float interp_ratio() const = 0; virtual void set_mu (float mu) = 0; virtual void set_interp_ratio(float interp_ratio) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_INTERPOLATOR_FF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fractional_interpolator_ff.h0000664000175000017500000000370312207440367027517 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_INTERPOLATOR_FF_H #define INCLUDED_FRACTIONAL_INTERPOLATOR_FF_H #include #include namespace gr { namespace filter { /*! * \brief Interpolating MMSE filter with float input, float output * \ingroup resamplers_blk */ class FILTER_API fractional_interpolator_ff : virtual public block { public: // gr::filter::fractional_interpolator_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Build the interpolating MMSE filter (float input, float output) * * \param phase_shift The phase shift of the output signal to the input * \param interp_ratio The interpolation ratio = input_rate / output_rate. */ static sptr make(float phase_shift, float interp_ratio); virtual float mu() const = 0; virtual float interp_ratio() const = 0; virtual void set_mu (float mu) = 0; virtual void set_interp_ratio(float interp_ratio) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_INTERPOLATOR_FF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fir_filter_XXX.h.t0000664000175000017500000000474412207440367025264 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace filter { /*! * \brief FIR filter with @I_TYPE@ input, @O_TYPE@ output, and @TAP_TYPE@ taps * \ingroup filter_blk * * \details * The fir_filter_XXX blocks create finite impulse response * (FIR) filters that perform the convolution in the time * domain: * * \code * out = 0 * for i in ntaps: * out += input[n-i] * taps[i] * \endcode * * The taps are a C++ vector (or Python list) of values of the * type specified by the third letter in the block's suffix. For * this block, the value is of type @TAP_TYPE@. Taps can be * created using the firdes or optfir tools. * * These versions of the filter can also act as down-samplers * (or decimators) by specifying an integer value for \p * decimation. */ class FILTER_API @BASE_NAME@ : virtual public sync_decimator { public: // gr::filter::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! * \brief FIR filter with @I_TYPE@ input, @O_TYPE@ output, and @TAP_TYPE@ taps * * \param decimation set the integer decimation rate * \param taps a vector/list of taps of type @TAP_TYPE@ */ static sptr make(int decimation, const std::vector<@TAP_TYPE@> &taps); virtual void set_taps(const std::vector<@TAP_TYPE@> &taps) = 0; virtual std::vector<@TAP_TYPE@> taps() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/iir_filter.h0000664000175000017500000001211512207440367024245 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_IIR_FILTER_H #define INCLUDED_IIR_FILTER_H #include #include #include namespace gr { namespace filter { namespace kernel { /*! * \brief base class template for Infinite Impulse Response filter (IIR) */ template class iir_filter { public: /*! * \brief Construct an IIR with the given taps. * * This filter uses the Direct Form I implementation, where * \p fftaps contains the feed-forward taps, and \p fbtaps the feedback ones. * * \p fftaps and \p fbtaps must have equal numbers of taps * * \p oldstyle: The old style of the IIR filter uses feedback * taps that are negative of what most definitions use (scipy * and Matlab among them). This parameter keeps using the old * GNU Radio style and is set to TRUE by default. When taps * generated from scipy, Matlab, or gr_filter_design, use the * new style by setting this to FALSE. * * The input and output satisfy a difference equation of the form \f[ y[n] \pm \sum_{k=1}^{M} a_k y[n-k] = \sum_{k=0}^{N} b_k x[n-k] \f] * with the corresponding rational system function \f[ H(z) = \frac{\sum_{k=0}^{N} b_k z^{-k}}{1 \pm \sum_{k=1}^{M} a_k z^{-k}} \f] */ iir_filter(const std::vector& fftaps, const std::vector& fbtaps, bool oldstyle=true) throw (std::invalid_argument) { d_oldstyle = oldstyle; set_taps(fftaps, fbtaps); } iir_filter() : d_latest_n(0),d_latest_m(0) { } ~iir_filter() {} /*! * \brief compute a single output value. * \returns the filtered input value. */ o_type filter(const i_type input); /*! * \brief compute an array of N output values. * \p input must have N valid entries. */ void filter_n(o_type output[], const i_type input[], long n); /*! * \return number of taps in filter. */ unsigned ntaps_ff() const { return d_fftaps.size(); } unsigned ntaps_fb() const { return d_fbtaps.size(); } /*! * \brief install new taps. */ void set_taps(const std::vector &fftaps, const std::vector &fbtaps) throw (std::invalid_argument) { d_latest_n = 0; d_latest_m = 0; d_fftaps = fftaps; if(d_oldstyle) { d_fbtaps = fbtaps; } else { // New style negates taps a[1:N-1] to fit with most IIR // tap generating programs. d_fbtaps.resize(fbtaps.size()); d_fbtaps[0] = fbtaps[0]; for(size_t i = 1; i < fbtaps.size(); i++) { d_fbtaps[i] = -fbtaps[i]; } } int n = fftaps.size(); int m = fbtaps.size(); d_prev_input.clear(); d_prev_output.clear(); d_prev_input.resize(2 * n, 0); d_prev_output.resize(2 * m, 0); } protected: bool d_oldstyle; std::vector d_fftaps; std::vector d_fbtaps; int d_latest_n; int d_latest_m; std::vector d_prev_output; std::vector d_prev_input; }; // // general case. We may want to specialize this // template o_type iir_filter::filter(const i_type input) { tap_type acc; unsigned i = 0; unsigned n = ntaps_ff(); unsigned m = ntaps_fb(); if(n == 0) return (o_type)0; int latest_n = d_latest_n; int latest_m = d_latest_m; acc = d_fftaps[0] * input; for(i = 1; i < n; i ++) acc += (d_fftaps[i] * d_prev_input[latest_n + i]); for(i = 1; i < m; i ++) acc += (d_fbtaps[i] * d_prev_output[latest_m + i]); // store the values twice to avoid having to handle wrap-around in the loop d_prev_output[latest_m] = acc; d_prev_output[latest_m+m] = acc; d_prev_input[latest_n] = input; d_prev_input[latest_n+n] = input; latest_n--; latest_m--; if(latest_n < 0) latest_n += n; if(latest_m < 0) latest_m += m; d_latest_m = latest_m; d_latest_n = latest_n; return (o_type)acc; } template void iir_filter::filter_n(o_type output[], const i_type input[], long n) { for(int i = 0; i < n; i++) output[i] = filter(input[i]); } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_IIR_FILTER_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/dc_blocker_cc.h0000664000175000017500000000527612207440367024663 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_DC_BLOCKER_CC_H #define INCLUDED_FILTER_DC_BLOCKER_CC_H #include #include namespace gr { namespace filter { /*! * \brief a computationally efficient controllable DC blocker * \ingroup filter_blk * * \details * This block implements a computationally efficient DC blocker that produces * a tighter notch filter around DC for a smaller group delay than an * equivalent FIR filter or using a single pole IIR filter (though the IIR * filter is computationally cheaper). * * The block defaults to using a delay line of length 32 and the long form * of the filter. Optionally, the delay line length can be changed to alter * the width of the DC notch (longer lines will decrease the width). * * The long form of the filter produces a nearly flat response outside of * the notch but at the cost of a group delay of 2D-2. * * The short form of the filter does not have as flat a response in the * passband but has a group delay of only D-1 and is cheaper to compute. * * The theory behind this block can be found in the paper: * * R. Yates, "DC Blocker Algorithms," IEEE Signal Processing Magazine, * Mar. 2008, pp 132-134. */ class FILTER_API dc_blocker_cc : virtual public sync_block { public: // gr::filter::dc_blocker_cc::sptr typedef boost::shared_ptr sptr; /*! * Make a DC blocker block. * * \param D (int) the length of the delay line * \param long_form (bool) whether to use long (true, default) or short form */ static sptr make(int D, bool long_form); virtual int group_delay() = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_DC_BLOCKER_CC_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_arb_resampler.h0000664000175000017500000004372712207440367025577 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_ARB_RESAMPLER_H #define INCLUDED_PFB_ARB_RESAMPLER_H #include namespace gr { namespace filter { namespace kernel { /*! * \brief Polyphase filterbank arbitrary resampler with * gr_complex input, gr_complex output and float taps * \ingroup resamplers_blk * * \details * This takes in a signal stream and performs arbitrary * resampling. The resampling rate can be any real number * r. The resampling is done by constructing N * filters where N is the interpolation rate. We then * calculate D where D = floor(N/r). * * Using N and D, we can perform rational * resampling where N/D is a rational number close to * the input rate r where we have N filters * and we cycle through them as a polyphase filterbank with a * stride of D so that i+1 = (i + D) % N. * * To get the arbitrary rate, we want to interpolate between two * points. For each value out, we take an output from the * current filter, i, and the next filter i+1 * and then linearly interpolate between the two based on the * real resampling rate we want. * * The linear interpolation only provides us with an * approximation to the real sampling rate specified. The error * is a quantization error between the two filters we used as * our interpolation points. To this end, the number of * filters, N, used determines the quantization error; * the larger N, the smaller the noise. You can design * for a specified noise floor by setting the filter size * (parameters filter_size). The size defaults to 32 * filters, which is about as good as most implementations need. * * The trick with designing this filter is in how to specify the * taps of the prototype filter. Like the PFB interpolator, the * taps are specified using the interpolated filter rate. In * this case, that rate is the input sample rate multiplied by * the number of filters in the filterbank, which is also the * interpolation rate. All other values should be relative to * this rate. * * For example, for a 32-filter arbitrary resampler and using * the GNU Radio's firdes utility to build the filter, we build * a low-pass filter with a sampling rate of fs, a 3-dB * bandwidth of BW and a transition bandwidth of * TB. We can also specify the out-of-band attenuation * to use, ATT, and the filter window function (a * Blackman-harris window in this case). The first input is the * gain of the filter, which we specify here as the * interpolation rate (32). * * self._taps = filter.firdes.low_pass_2(32, 32*fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * The theory behind this block can be found in Chapter 7.5 of * the following book. * * f. harris, "Multirate Signal Processing for Communication * Systems", Upper Saddle River, NJ: Prentice Hall, Inc. 2004. */ class FILTER_API pfb_arb_resampler_ccf { private: std::vector d_filters; std::vector d_diff_filters; std::vector< std::vector > d_taps; std::vector< std::vector > d_dtaps; unsigned int d_int_rate; // the number of filters (interpolation rate) unsigned int d_dec_rate; // the stride through the filters (decimation rate) float d_flt_rate; // residual rate for the linear interpolation float d_acc; // accumulator; holds fractional part of sample unsigned int d_last_filter; // stores filter for re-entry unsigned int d_taps_per_filter; // num taps for each arm of the filterbank int d_delay; // filter's group delay float d_est_phase_change; // est. of phase change of a sine wave through filt. /*! * Takes in the taps and convolves them with [-1,0,1], which * creates a differential set of taps that are used in the * difference filterbank. * \param newtaps (vector of floats) The prototype filter. * \param difftaps (vector of floats) (out) The differential filter taps. */ void create_diff_taps(const std::vector &newtaps, std::vector &difftaps); /*! * Resets the filterbank's filter taps with the new prototype filter * \param newtaps (vector of floats) The prototype filter to populate the filterbank. * The taps should be generated at the interpolated sampling rate. * \param ourtaps (vector of floats) Reference to our internal member of holding the taps. * \param ourfilter (vector of filters) Reference to our internal filter to set the taps for. */ void create_taps(const std::vector &newtaps, std::vector< std::vector > &ourtaps, std::vector &ourfilter); public: /*! * Creates a kernel to perform arbitrary resampling on a set of samples. * \param rate (float) Specifies the resampling rate to use * \param taps (vector/list of floats) The prototype filter to populate the filterbank. The taps * should be generated at the filter_size sampling rate. * \param filter_size (unsigned int) The number of filters in the filter bank. This is directly * related to quantization noise introduced during the resampling. * Defaults to 32 filters. */ pfb_arb_resampler_ccf(float rate, const std::vector &taps, unsigned int filter_size); ~pfb_arb_resampler_ccf(); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. */ void set_taps(const std::vector &taps); /*! * Return a vector> of the filterbank taps */ std::vector > taps() const; /*! * Print all of the filterbank taps to screen. */ void print_taps(); /*! * Sets the resampling rate of the block. */ void set_rate(float rate); /*! * Sets the current phase offset in radians (0 to 2pi). */ void set_phase(float ph); /*! * Gets the current phase of the resampler in radians (2 to 2pi). */ float phase() const; /*! * Gets the number of taps per filter. */ unsigned int taps_per_filter() const; unsigned int interpolation_rate() const { return d_int_rate; } unsigned int decimation_rate() const { return d_dec_rate; } float fractional_rate() const { return d_flt_rate; } /*! * Get the group delay of the filter. */ int group_delay() const { return d_delay; } /*! * Calculates the phase offset expected by a sine wave of * frequency \p freq and sampling rate \p fs (assuming input * sine wave has 0 degree phase). */ float phase_offset(float freq, float fs); /*! * Performs the filter operation that resamples the signal. * * This block takes in a stream of samples and outputs a * resampled and filtered stream. This block should be called * such that the output has \p rate * \p n_to_read amount of * space available in the \p output buffer. * * \param input An input vector of samples to be resampled * \param output The output samples at the new sample rate. * \param n_to_read Number of samples to read from \p input. * \param n_read (out) Number of samples actually read from \p input. * \return Number of samples put into \p output. */ int filter(gr_complex *input, gr_complex *output, int n_to_read, int &n_read); }; /**************************************************************/ /*! * \brief Polyphase filterbank arbitrary resampler with * float input, float output and float taps * \ingroup resamplers_blk * * \details * This takes in a signal stream and performs arbitrary * resampling. The resampling rate can be any real number * r. The resampling is done by constructing N * filters where N is the interpolation rate. We then * calculate D where D = floor(N/r). * * Using N and D, we can perform rational * resampling where N/D is a rational number close to * the input rate r where we have N filters * and we cycle through them as a polyphase filterbank with a * stride of D so that i+1 = (i + D) % N. * * To get the arbitrary rate, we want to interpolate between two * points. For each value out, we take an output from the * current filter, i, and the next filter i+1 * and then linearly interpolate between the two based on the * real resampling rate we want. * * The linear interpolation only provides us with an * approximation to the real sampling rate specified. The error * is a quantization error between the two filters we used as * our interpolation points. To this end, the number of * filters, N, used determines the quantization error; * the larger N, the smaller the noise. You can design * for a specified noise floor by setting the filter size * (parameters filter_size). The size defaults to 32 * filters, which is about as good as most implementations need. * * The trick with designing this filter is in how to specify the * taps of the prototype filter. Like the PFB interpolator, the * taps are specified using the interpolated filter rate. In * this case, that rate is the input sample rate multiplied by * the number of filters in the filterbank, which is also the * interpolation rate. All other values should be relative to * this rate. * * For example, for a 32-filter arbitrary resampler and using * the GNU Radio's firdes utility to build the filter, we build * a low-pass filter with a sampling rate of fs, a 3-dB * bandwidth of BW and a transition bandwidth of * TB. We can also specify the out-of-band attenuation * to use, ATT, and the filter window function (a * Blackman-harris window in this case). The first input is the * gain of the filter, which we specify here as the * interpolation rate (32). * * self._taps = filter.firdes.low_pass_2(32, 32*fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * The theory behind this block can be found in Chapter 7.5 of * the following book. * * f. harris, "Multirate Signal Processing for Communication * Systems", Upper Saddle River, NJ: Prentice Hall, Inc. 2004. */ class FILTER_API pfb_arb_resampler_fff { private: std::vector d_filters; std::vector d_diff_filters; std::vector< std::vector > d_taps; std::vector< std::vector > d_dtaps; unsigned int d_int_rate; // the number of filters (interpolation rate) unsigned int d_dec_rate; // the stride through the filters (decimation rate) float d_flt_rate; // residual rate for the linear interpolation float d_acc; // accumulator; holds fractional part of sample unsigned int d_last_filter; // stores filter for re-entry unsigned int d_taps_per_filter; // num taps for each arm of the filterbank int d_delay; // filter's group delay float d_est_phase_change; // est. of phase change of a sine wave through filt. /*! * Takes in the taps and convolves them with [-1,0,1], which * creates a differential set of taps that are used in the * difference filterbank. * \param newtaps (vector of floats) The prototype filter. * \param difftaps (vector of floats) (out) The differential filter taps. */ void create_diff_taps(const std::vector &newtaps, std::vector &difftaps); /*! * Resets the filterbank's filter taps with the new prototype filter * \param newtaps (vector of floats) The prototype filter to populate the filterbank. * The taps should be generated at the interpolated sampling rate. * \param ourtaps (vector of floats) Reference to our internal member of holding the taps. * \param ourfilter (vector of filters) Reference to our internal filter to set the taps for. */ void create_taps(const std::vector &newtaps, std::vector< std::vector > &ourtaps, std::vector &ourfilter); public: /*! * Creates a kernel to perform arbitrary resampling on a set of samples. * \param rate (float) Specifies the resampling rate to use * \param taps (vector/list of floats) The prototype filter to populate the filterbank. The taps * should be generated at the filter_size sampling rate. * \param filter_size (unsigned int) The number of filters in the filter bank. This is directly * related to quantization noise introduced during the resampling. * Defaults to 32 filters. */ pfb_arb_resampler_fff(float rate, const std::vector &taps, unsigned int filter_size); ~pfb_arb_resampler_fff(); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. */ void set_taps(const std::vector &taps); /*! * Return a vector> of the filterbank taps */ std::vector > taps() const; /*! * Print all of the filterbank taps to screen. */ void print_taps(); /*! * Sets the resampling rate of the block. */ void set_rate(float rate); /*! * Sets the current phase offset in radians (0 to 2pi). */ void set_phase(float ph); /*! * Gets the current phase of the resampler in radians (2 to 2pi). */ float phase() const; /*! * Gets the number of taps per filter. */ unsigned int taps_per_filter() const; unsigned int interpolation_rate() const { return d_int_rate; } unsigned int decimation_rate() const { return d_dec_rate; } float fractional_rate() const { return d_flt_rate; } /*! * Get the group delay of the filter. */ int group_delay() const { return d_delay; } /*! * Calculates the phase offset expected by a sine wave of * frequency \p freq and sampling rate \p fs (assuming input * sine wave has 0 degree phase). */ float phase_offset(float freq, float fs); /*! * Performs the filter operation that resamples the signal. * * This block takes in a stream of samples and outputs a * resampled and filtered stream. This block should be called * such that the output has \p rate * \p n_to_read amount of * space available in the \p output buffer. * * \param input An input vector of samples to be resampled * \param output The output samples at the new sample rate. * \param n_to_read Number of samples to read from \p input. * \param n_read (out) Number of samples actually read from \p input. * \return Number of samples put into \p output. */ int filter(float *input, float *output, int n_to_read, int &n_read); }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_ARB_RESAMPLER_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_synthesizer_ccf.h0000664000175000017500000000701312207440367026147 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_SYNTHESIZER_CCF_H #define INCLUDED_PFB_SYNTHESIZER_CCF_H #include #include namespace gr { namespace filter { /*! * \brief Polyphase synthesis filterbank with * gr_complex input, gr_complex output and float taps * \ingroup channelizers_blk */ class FILTER_API pfb_synthesizer_ccf : virtual public sync_interpolator { public: // gr::filter::pfb_synthesizer_ccf::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase synthesis filterbank. * \param numchans (unsigned integer) Specifies the number of * channels M * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. * \param twox (bool) use 2x oversampling or not (default is no) */ static sptr make(unsigned int numchans, const std::vector &taps, bool twox=false); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. */ virtual void set_taps(const std::vector &taps) = 0; /*! * Print all of the filterbank taps to screen. */ virtual void print_taps() = 0; /*! * Return a vector> of the filterbank taps */ virtual std::vector > taps() const = 0; /*! * Set the channel map. Channels are numbers as: * N/2+1 | ... | N-1 | 0 | 1 | 2 | ... | N/2 * <------------------- 0 --------------------> * freq * * So input stream 0 goes to channel 0, etc. Setting a new channel * map allows the user to specify where in frequency he/she wants * the input stream to go. This is especially useful to avoid * putting signals into the channels on the edge of the spectrum * which can either wrap around (in the case of odd number of * channels) and be affected by filter rolloff in the transmitter. * * The map must be at least the number of streams being sent to the * block. Less and the algorithm will not have enough data to * properly setup the buffers. Any more channels specified will be * ignored. */ virtual void set_channel_map(const std::vector &map) = 0; /*! * Gets the current channel map. */ virtual std::vector channel_map() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_SYNTHESIZER_CCF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pm_remez.h0000664000175000017500000000506712207440367023743 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_PM_REMEZ_H #define INCLUDED_FILTER_PM_REMEZ_H #include #include #include #include namespace gr { namespace filter { /*! * \brief Parks-McClellan FIR filter design using Remez algorithm. * \ingroup filter_design * * \details * Calculates the optimal (in the Chebyshev/minimax sense) FIR * filter inpulse reponse given a set of band edges, the desired * reponse on those bands, and the weight given to the error in * those bands. * * \param order filter order (number of taps in the returned filter - 1) * \param bands frequency at the band edges [ b1 e1 b2 e2 b3 e3 ...] * \param ampl desired amplitude at the band edges [ a(b1) a(e1) a(b2) a(e2) ...] * \param error_weight weighting applied to each band (usually 1) * \param filter_type one of "bandpass", "hilbert" or "differentiator" * \param grid_density determines how accurately the filter will be constructed. \ * The minimum value is 16; higher values are slower to compute. * * Frequency is in the range [0, 1], with 1 being the Nyquist * frequency (Fs/2) * * \returns vector of computed taps * * \throws std::runtime_error if args are invalid or calculation * fails to converge. */ FILTER_API std::vector pm_remez(int order, const std::vector &bands, const std::vector &l, const std::vector &error_weight, const std::string filter_type = "bandpass", int grid_density = 16 ) throw (std::runtime_error); } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_PM_REMEZ_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_interpolator_ccf.h0000664000175000017500000001077712207440367026315 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_INTERPOLATOR_CCF_H #define INCLUDED_PFB_INTERPOLATOR_CCF_H #include #include namespace gr { namespace filter { /*! * \brief Polyphase filterbank interpolator with gr_complex input, * gr_complex output and float taps * \ingroup channelizers_blk * * \details * This block takes in a signal stream and performs interger up- * sampling (interpolation) with a polyphase filterbank. The first * input is the integer specifying how much to interpolate by. The * second input is a vector (Python list) of floating-point taps * of the prototype filter. * * The filter's taps should be based on the interpolation rate * specified. That is, the bandwidth specified is relative to the * bandwidth after interpolation. * * For example, using the GNU Radio's firdes utility to building * filters, we build a low-pass filter with a sampling rate of * fs, a 3-dB bandwidth of BW and a transition * bandwidth of TB. We can also specify the out-of-band * attenuation to use, ATT, and the filter window function (a * Blackman-harris window in this case). The first input is the * gain, which is also specified as the interpolation rate so that * the output levels are the same as the input (this creates an * overall increase in power). * * self._taps = filter.firdes.low_pass_2(interp, interp*fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * The PFB interpolator code takes the taps generated above and * builds a set of filters. The set contains interp * number of filters and each filter contains * ceil(taps.size()/interp) number of taps. Each tap from the * filter prototype is sequentially inserted into the next * filter. When all of the input taps are used, the remaining * filters in the filterbank are filled out with 0's to make sure * each filter has the same number of taps. * * The theory behind this block can be found in Chapter 7.1 of the * following book. * * f. harris, "Multirate Signal Processing for Communication * Systems," Upper Saddle River, NJ: Prentice Hall, * Inc. 2004. */ class FILTER_API pfb_interpolator_ccf : virtual public sync_interpolator { public: // gr::filter::pfb_interpolator_ccf::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank interpolator. * \param interp (unsigned integer) Specifies the interpolation rate to use * \param taps (vector/list of floats) The prototype filter to populate the filterbank. The taps * should be generated at the interpolated sampling rate. */ static sptr make(unsigned int interp, const std::vector &taps); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. * The taps should be generated at the interpolated sampling rate. */ virtual void set_taps(const std::vector &taps) = 0; /*! * Return a vector> of the filterbank taps */ virtual std::vector > taps() const = 0; /*! * Print all of the filterbank taps to screen. */ virtual void print_taps() = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_PFB_INTERPOLATOR_CCF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/single_pole_iir.h0000664000175000017500000001177512207440367025273 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SINGLE_POLE_IIR_H #define INCLUDED_SINGLE_POLE_IIR_H #include #include #include namespace gr { namespace filter { /*! * \brief class template for single pole IIR filter */ template class single_pole_iir { public: /*! * \brief construct new single pole IIR with given alpha * * computes y(i) = (1-alpha) * y(i-1) + alpha * x(i) */ single_pole_iir(tap_type alpha = 1.0) { d_prev_output = 0; set_taps(alpha); } /*! * \brief compute a single output value. * \returns the filtered input value. */ o_type filter(const i_type input); /*! * \brief compute an array of N output values. * \p input must have n valid entries. */ void filterN(o_type output[], const i_type input[], unsigned long n); /*! * \brief install \p alpha as the current taps. */ void set_taps(tap_type alpha) { if(alpha < 0 || alpha > 1) throw std::out_of_range("Alpha must be in [0, 1]\n"); d_alpha = alpha; d_one_minus_alpha = 1.0 - alpha; } //! reset state to zero void reset() { d_prev_output = 0; } o_type prev_output() const { return d_prev_output; } protected: tap_type d_alpha; tap_type d_one_minus_alpha; o_type d_prev_output; }; // // general case. We may want to specialize this // template o_type single_pole_iir::filter(const i_type input) { o_type output; output = d_alpha * input + d_one_minus_alpha * d_prev_output; d_prev_output = output; return (o_type) output; } template void single_pole_iir::filterN(o_type output[], const i_type input[], unsigned long n) { for(unsigned i = 0; i < n; i++) output[i] = filter(input[i]); } // // Specialized case for gr_complex output and double taps // We need to have a gr_complexd type for the calculations and prev_output variable (in stead of double) template class single_pole_iir { public: /*! * \brief construct new single pole IIR with given alpha * * computes y(i) = (1-alpha) * y(i-1) + alpha * x(i) */ single_pole_iir(double alpha = 1.0) { d_prev_output = 0; set_taps(alpha); } /*! * \brief compute a single output value. * \returns the filtered input value. */ gr_complex filter(const i_type input); /*! * \brief compute an array of N output values. * \p input must have n valid entries. */ void filterN(gr_complex output[], const i_type input[], unsigned long n); /*! * \brief install \p alpha as the current taps. */ void set_taps(double alpha) { if(alpha < 0 || alpha > 1) throw std::out_of_range("Alpha must be in [0, 1]\n"); d_alpha = alpha; d_one_minus_alpha = 1.0 - alpha; } //! reset state to zero void reset() { d_prev_output = 0; } gr_complexd prev_output() const { return d_prev_output; } protected: double d_alpha; double d_one_minus_alpha; gr_complexd d_prev_output; }; template< class i_type> gr_complex single_pole_iir::filter(const i_type input) { gr_complexd output; output = d_alpha * (gr_complexd)input + d_one_minus_alpha * d_prev_output; d_prev_output = output; return (gr_complex) output; } //Do we need to specialize this, although it is the same as the general case? template void single_pole_iir::filterN(gr_complex output[], const i_type input[], unsigned long n) { for(unsigned i = 0; i < n; i++) output[i] = filter(input[i]); } } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_SINGLE_POLE_IIR_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fft_filter.h0000664000175000017500000001316012237515112024234 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FFT_FILTER_H #define INCLUDED_FILTER_FFT_FILTER_H #include #include #include #include namespace gr { namespace filter { namespace kernel { /*! * \brief Fast FFT filter with float input, float output and float taps * \ingroup filter_blk */ class FILTER_API fft_filter_fff { private: int d_ntaps; int d_nsamples; int d_fftsize; // fftsize = ntaps + nsamples - 1 int d_decimation; fft::fft_real_fwd *d_fwdfft; // forward "plan" fft::fft_real_rev *d_invfft; // inverse "plan" int d_nthreads; // number of FFTW threads to use std::vector d_tail; // state carried between blocks for overlap-add std::vector d_taps; // stores time domain taps gr_complex *d_xformed_taps; // Fourier xformed taps void compute_sizes(int ntaps); int tailsize() const { return d_ntaps - 1; } public: /*! * \brief Construct an FFT filter for float vectors with the given taps and decimation rate. * * This is the basic implementation for performing FFT filter for fast convolution * in other blocks for complex vectors (such as fft_filter_ccc). * * \param decimation The decimation rate of the filter (int) * \param taps The filter taps (complex) * \param nthreads The number of threads for the FFT to use (int) */ fft_filter_fff(int decimation, const std::vector &taps, int nthreads=1); ~fft_filter_fff(); /*! * \brief Set new taps for the filter. * * Sets new taps and resets the class properties to handle different sizes * \param taps The filter taps (complex) */ int set_taps(const std::vector &taps); /*! * \brief Set number of threads to use. */ void set_nthreads(int n); /*! * \brief Returns the taps. */ std::vector taps() const; /*! * \brief Returns the number of taps in the filter. */ unsigned int ntaps() const; /*! * \brief Get number of threads being used. */ int nthreads() const; /*! l * \brief Perform the filter operation * * \param nitems The number of items to produce * \param input The input vector to be filtered * \param output The result of the filter operation */ int filter(int nitems, const float *input, float *output); }; /*! * \brief Fast FFT filter with gr_complex input, gr_complex output and gr_complex taps * \ingroup filter_blk */ class FILTER_API fft_filter_ccc { private: int d_ntaps; int d_nsamples; int d_fftsize; // fftsize = ntaps + nsamples - 1 int d_decimation; fft::fft_complex *d_fwdfft; // forward "plan" fft::fft_complex *d_invfft; // inverse "plan" int d_nthreads; // number of FFTW threads to use std::vector d_tail; // state carried between blocks for overlap-add std::vector d_taps; // stores time domain taps gr_complex *d_xformed_taps; // Fourier xformed taps void compute_sizes(int ntaps); int tailsize() const { return d_ntaps - 1; } public: /*! * \brief Construct an FFT filter for complex vectors with the given taps and decimation rate. * * This is the basic implementation for performing FFT filter for fast convolution * in other blocks for complex vectors (such as fft_filter_ccc). * * \param decimation The decimation rate of the filter (int) * \param taps The filter taps (complex) * \param nthreads The number of threads for the FFT to use (int) */ fft_filter_ccc(int decimation, const std::vector &taps, int nthreads=1); ~fft_filter_ccc(); /*! * \brief Set new taps for the filter. * * Sets new taps and resets the class properties to handle different sizes * \param taps The filter taps (complex) */ int set_taps(const std::vector &taps); /*! * \brief Set number of threads to use. */ void set_nthreads(int n); /*! * \brief Returns the taps. */ std::vector taps() const; /*! * \brief Returns the number of taps in the filter. */ unsigned int ntaps() const; /*! * \brief Get number of threads being used. */ int nthreads() const; /*! * \brief Perform the filter operation * * \param nitems The number of items to produce * \param input The input vector to be filtered * \param output The result of the filter operation */ int filter(int nitems, const gr_complex *input, gr_complex *output); }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FFT_FILTER_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/firdes.h0000664000175000017500000003640612237515112023374 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _FILTER_FIRDES_H_ #define _FILTER_FIRDES_H_ #include #include #include #include #include namespace gr { namespace filter { /*! * \brief Finite Impulse Response (FIR) filter design functions. * \ingroup filter_design */ class FILTER_API firdes { public: // WARNING: deprecated, now located in gr::fft::window. // We will be removing this in 3.8. enum win_type { WIN_NONE = -1, //!< don't use a window WIN_HAMMING = 0, //!< Hamming window; max attenuation 53 dB WIN_HANN = 1, //!< Hann window; max attenuation 44 dB WIN_BLACKMAN = 2, //!< Blackman window; max attenuation 74 dB WIN_RECTANGULAR = 3, //!< Basic rectangular window WIN_KAISER = 4, //!< Kaiser window; max attenuation a function of beta, google it WIN_BLACKMAN_hARRIS = 5, //!< Blackman-harris window WIN_BLACKMAN_HARRIS = 5, //!< alias to WIN_BLACKMAN_hARRIS for capitalization consistency WIN_BARTLETT = 6, //!< Barlett (triangular) window WIN_FLATTOP = 7, //!< flat top window; useful in FFTs }; static std::vector window(win_type type, int ntaps, double beta); // ... class methods ... /*! * \brief use "window method" to design a low-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * The normalized width of the transition * band is what sets the number of taps * required. Narrow --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector low_pass(double gain, double sampling_freq, double cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a low-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * \p attenuation_dB required stopband attenuation * The normalized width of the transition * band and the required stop band * attenuation is what sets the number of taps * required. Narrow --> more taps * More attenuatin --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector low_pass_2(double gain, double sampling_freq, double cutoff_freq, // Hz beginning transition band double transition_width, // Hz width of transition band double attenuation_dB, // out of band attenuation dB win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a high-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * The normalized width of the transition * band is what sets the number of taps * required. Narrow --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector high_pass(double gain, double sampling_freq, double cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a high-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * \p attenuation_dB out of band attenuation * The normalized width of the transition * band and the required stop band * attenuation is what sets the number of taps * required. Narrow --> more taps * More attenuation --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector high_pass_2(double gain, double sampling_freq, double cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band double attenuation_dB, // out of band attenuation dB win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a band-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p low_cutoff_freq: center of transition band (Hz) * \p high_cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * The normalized width of the transition * band is what sets the number of taps * required. Narrow --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector band_pass(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a band-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p low_cutoff_freq: center of transition band (Hz) * \p high_cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * \p attenuation_dB out of band attenuation * The normalized width of the transition * band and the required stop band * attenuation is what sets the number of taps * required. Narrow --> more taps * More attenuation --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector band_pass_2(double gain, double sampling_freq, double low_cutoff_freq, // Hz beginning transition band double high_cutoff_freq, // Hz beginning transition band double transition_width, // Hz width of transition band double attenuation_dB, // out of band attenuation dB win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a complex band-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p low_cutoff_freq: center of transition band (Hz) * \p high_cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * The normalized width of the transition * band is what sets the number of taps * required. Narrow --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector complex_band_pass(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a complex band-pass FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p low_cutoff_freq: center of transition band (Hz) * \p high_cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * \p attenuation_dB out of band attenuation * The normalized width of the transition * band and the required stop band * attenuation is what sets the number of taps * required. Narrow --> more taps * More attenuation --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector complex_band_pass_2(double gain, double sampling_freq, double low_cutoff_freq, // Hz beginning transition band double high_cutoff_freq, // Hz beginning transition band double transition_width, // Hz width of transition band double attenuation_dB, // out of band attenuation dB win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a band-reject FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p low_cutoff_freq: center of transition band (Hz) * \p high_cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * The normalized width of the transition * band is what sets the number of taps * required. Narrow --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector band_reject(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*! * \brief use "window method" to design a band-reject FIR filter * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p low_cutoff_freq: center of transition band (Hz) * \p high_cutoff_freq: center of transition band (Hz) * \p transition_width: width of transition band (Hz). * \p attenuation_dB out of band attenuation * The normalized width of the transition * band and the required stop band * attenuation is what sets the number of taps * required. Narrow --> more taps * More attenuation --> more taps * \p window_type: What kind of window to use. Determines * maximum attenuation and passband ripple. * \p beta: parameter for Kaiser window */ static std::vector band_reject_2(double gain, double sampling_freq, double low_cutoff_freq, // Hz beginning transition band double high_cutoff_freq, // Hz beginning transition band double transition_width, // Hz width of transition band double attenuation_dB, // out of band attenuation dB win_type window = WIN_HAMMING, double beta = 6.76); // used only with Kaiser /*!\brief design a Hilbert Transform Filter * * \p ntaps: Number of taps, must be odd * \p window_type: What kind of window to use * \p beta: Only used for Kaiser */ static std::vector hilbert(unsigned int ntaps = 19, win_type windowtype = WIN_RECTANGULAR, double beta = 6.76); /*! * \brief design a Root Cosine FIR Filter (do we need a window?) * * \p gain: overall gain of filter (typically 1.0) * \p sampling_freq: sampling freq (Hz) * \p symbol rate: symbol rate, must be a factor of sample rate * \p alpha: excess bandwidth factor * \p ntaps: number of taps */ static std::vector root_raised_cosine(double gain, double sampling_freq, double symbol_rate, // Symbol rate, NOT bitrate (unless BPSK) double alpha, // Excess Bandwidth Factor int ntaps); /*! * \brief design a Gaussian filter * * \p gain: overall gain of filter (typically 1.0) * \p symbols per bit: symbol rate, must be a factor of sample rate * \p ntaps: number of taps */ static std::vector gaussian(double gain, double spb, double bt, // Bandwidth to bitrate ratio int ntaps); private: static double bessi0(double x); static void sanity_check_1f(double sampling_freq, double f1, double transition_width); static void sanity_check_2f(double sampling_freq, double f1, double f2, double transition_width); static void sanity_check_2f_c(double sampling_freq, double f1, double f2, double transition_width); static int compute_ntaps(double sampling_freq, double transition_width, win_type window_type, double beta); static int compute_ntaps_windes(double sampling_freq, double transition_width, double attenuation_dB); }; } /* namespace filter */ } /* namespace gr */ #endif /* _FILTER_FIRDES_H_ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/polyphase_filterbank.h0000664000175000017500000001261412207440367026326 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_POLYPHASE_FILTERBANK_H #define INCLUDED_FILTER_POLYPHASE_FILTERBANK_H #include #include #include namespace gr { namespace filter { namespace kernel { /*! * \brief Polyphase filterbank parent class * \ingroup filter_blk * \ingroup pfb_blk * * \details * This block takes in complex inputs and channelizes it to * M channels of equal bandwidth. Each of the resulting * channels is decimated to the new rate that is the input * sampling rate fs divided by the number of channels, * M. * * The PFB channelizer code takes the taps generated above and * builds a set of filters. The set contains M number * of filters and each filter contains ceil(taps.size()/decim) * number of taps. Each tap from the filter prototype is * sequentially inserted into the next filter. When all of the * input taps are used, the remaining filters in the filterbank * are filled out with 0's to make sure each filter has the same * number of taps. * * Each filter operates using the gr::filter::fir_filter_XXX * classs of GNU Radio, which takes the input stream at * i and performs the inner product calculation to * i+(n-1) where n is the number of filter * taps. To efficiently handle this in the GNU Radio structure, * each filter input must come from its own input stream. So the * channelizer must be provided with M streams where * the input stream has been deinterleaved. This is most easily * done using the gr::blocks::stream_to_streams block. * * The output is then produced as a vector, where index * i in the vector is the next sample from the * ith channel. This is most easily handled by sending * the output to a gr::blocks::vector_to_streams block to handle * the conversion and passing M streams out. * * The input and output formatting is done using a hier_block2 * called pfb_channelizer_ccf. This can take in a single stream * and outputs M streams based on the behavior * described above. * * The filter's taps should be based on the input sampling rate. * * For example, using the GNU Radio's firdes utility to building * filters, we build a low-pass filter with a sampling rate of * fs, a 3-dB bandwidth of BW and a transition * bandwidth of TB. We can also specify the out-of-band * attenuation to use, ATT, and the filter window * function (a Blackman-harris window in this case). The first * input is the gain of the filter, which we specify here as * unity. * * self._taps = filter.firdes.low_pass_2(1, fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * More on the theory of polyphase filterbanks can be found in * the following book. * * f. harris, "Multirate Signal Processing for * Communication Systems," Upper Saddle River, NJ: * Prentice Hall, Inc. 2004. * */ class FILTER_API polyphase_filterbank { protected: unsigned int d_nfilts; std::vector d_filters; std::vector< std::vector > d_taps; unsigned int d_taps_per_filter; fft::fft_complex *d_fft; public: /*! * Build the polyphase filterbank decimator. * \param nfilts (unsigned integer) Specifies the number of * channels M * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. */ polyphase_filterbank(unsigned int nfilts, const std::vector &taps); ~polyphase_filterbank(); /*! * Update the filterbank's filter taps from a prototype * filter. * * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. */ void set_taps(const std::vector &taps); /*! * Print all of the filterbank taps to screen. */ void print_taps(); /*! * Return a vector> of the filterbank taps */ std::vector > taps() const; }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_POLYPHASE_FILTERBANK_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/interpolator_taps.h0000664000175000017500000004111412207440367025667 0ustar jcorganjcorgan/* * This file was machine generated by gen_interpolator_taps. * DO NOT EDIT BY HAND. */ static const int NTAPS = 8; static const int NSTEPS = 128; static const float taps[NSTEPS+1][NTAPS] = { // -4 -3 -2 -1 0 1 2 3 mu { 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 }, // 0/128 { -1.54700e-04, 8.53777e-04, -2.76968e-03, 7.89295e-03, 9.98534e-01, -5.41054e-03, 1.24642e-03, -1.98993e-04 }, // 1/128 { -3.09412e-04, 1.70888e-03, -5.55134e-03, 1.58840e-02, 9.96891e-01, -1.07209e-02, 2.47942e-03, -3.96391e-04 }, // 2/128 { -4.64053e-04, 2.56486e-03, -8.34364e-03, 2.39714e-02, 9.95074e-01, -1.59305e-02, 3.69852e-03, -5.92100e-04 }, // 3/128 { -6.18544e-04, 3.42130e-03, -1.11453e-02, 3.21531e-02, 9.93082e-01, -2.10389e-02, 4.90322e-03, -7.86031e-04 }, // 4/128 { -7.72802e-04, 4.27773e-03, -1.39548e-02, 4.04274e-02, 9.90917e-01, -2.60456e-02, 6.09305e-03, -9.78093e-04 }, // 5/128 { -9.26747e-04, 5.13372e-03, -1.67710e-02, 4.87921e-02, 9.88580e-01, -3.09503e-02, 7.26755e-03, -1.16820e-03 }, // 6/128 { -1.08030e-03, 5.98883e-03, -1.95925e-02, 5.72454e-02, 9.86071e-01, -3.57525e-02, 8.42626e-03, -1.35627e-03 }, // 7/128 { -1.23337e-03, 6.84261e-03, -2.24178e-02, 6.57852e-02, 9.83392e-01, -4.04519e-02, 9.56876e-03, -1.54221e-03 }, // 8/128 { -1.38589e-03, 7.69462e-03, -2.52457e-02, 7.44095e-02, 9.80543e-01, -4.50483e-02, 1.06946e-02, -1.72594e-03 }, // 9/128 { -1.53777e-03, 8.54441e-03, -2.80746e-02, 8.31162e-02, 9.77526e-01, -4.95412e-02, 1.18034e-02, -1.90738e-03 }, // 10/128 { -1.68894e-03, 9.39154e-03, -3.09033e-02, 9.19033e-02, 9.74342e-01, -5.39305e-02, 1.28947e-02, -2.08645e-03 }, // 11/128 { -1.83931e-03, 1.02356e-02, -3.37303e-02, 1.00769e-01, 9.70992e-01, -5.82159e-02, 1.39681e-02, -2.26307e-03 }, // 12/128 { -1.98880e-03, 1.10760e-02, -3.65541e-02, 1.09710e-01, 9.67477e-01, -6.23972e-02, 1.50233e-02, -2.43718e-03 }, // 13/128 { -2.13733e-03, 1.19125e-02, -3.93735e-02, 1.18725e-01, 9.63798e-01, -6.64743e-02, 1.60599e-02, -2.60868e-03 }, // 14/128 { -2.28483e-03, 1.27445e-02, -4.21869e-02, 1.27812e-01, 9.59958e-01, -7.04471e-02, 1.70776e-02, -2.77751e-03 }, // 15/128 { -2.43121e-03, 1.35716e-02, -4.49929e-02, 1.36968e-01, 9.55956e-01, -7.43154e-02, 1.80759e-02, -2.94361e-03 }, // 16/128 { -2.57640e-03, 1.43934e-02, -4.77900e-02, 1.46192e-01, 9.51795e-01, -7.80792e-02, 1.90545e-02, -3.10689e-03 }, // 17/128 { -2.72032e-03, 1.52095e-02, -5.05770e-02, 1.55480e-01, 9.47477e-01, -8.17385e-02, 2.00132e-02, -3.26730e-03 }, // 18/128 { -2.86289e-03, 1.60193e-02, -5.33522e-02, 1.64831e-01, 9.43001e-01, -8.52933e-02, 2.09516e-02, -3.42477e-03 }, // 19/128 { -3.00403e-03, 1.68225e-02, -5.61142e-02, 1.74242e-01, 9.38371e-01, -8.87435e-02, 2.18695e-02, -3.57923e-03 }, // 20/128 { -3.14367e-03, 1.76185e-02, -5.88617e-02, 1.83711e-01, 9.33586e-01, -9.20893e-02, 2.27664e-02, -3.73062e-03 }, // 21/128 { -3.28174e-03, 1.84071e-02, -6.15931e-02, 1.93236e-01, 9.28650e-01, -9.53307e-02, 2.36423e-02, -3.87888e-03 }, // 22/128 { -3.41815e-03, 1.91877e-02, -6.43069e-02, 2.02814e-01, 9.23564e-01, -9.84679e-02, 2.44967e-02, -4.02397e-03 }, // 23/128 { -3.55283e-03, 1.99599e-02, -6.70018e-02, 2.12443e-01, 9.18329e-01, -1.01501e-01, 2.53295e-02, -4.16581e-03 }, // 24/128 { -3.68570e-03, 2.07233e-02, -6.96762e-02, 2.22120e-01, 9.12947e-01, -1.04430e-01, 2.61404e-02, -4.30435e-03 }, // 25/128 { -3.81671e-03, 2.14774e-02, -7.23286e-02, 2.31843e-01, 9.07420e-01, -1.07256e-01, 2.69293e-02, -4.43955e-03 }, // 26/128 { -3.94576e-03, 2.22218e-02, -7.49577e-02, 2.41609e-01, 9.01749e-01, -1.09978e-01, 2.76957e-02, -4.57135e-03 }, // 27/128 { -4.07279e-03, 2.29562e-02, -7.75620e-02, 2.51417e-01, 8.95936e-01, -1.12597e-01, 2.84397e-02, -4.69970e-03 }, // 28/128 { -4.19774e-03, 2.36801e-02, -8.01399e-02, 2.61263e-01, 8.89984e-01, -1.15113e-01, 2.91609e-02, -4.82456e-03 }, // 29/128 { -4.32052e-03, 2.43930e-02, -8.26900e-02, 2.71144e-01, 8.83893e-01, -1.17526e-01, 2.98593e-02, -4.94589e-03 }, // 30/128 { -4.44107e-03, 2.50946e-02, -8.52109e-02, 2.81060e-01, 8.77666e-01, -1.19837e-01, 3.05345e-02, -5.06363e-03 }, // 31/128 { -4.55932e-03, 2.57844e-02, -8.77011e-02, 2.91006e-01, 8.71305e-01, -1.22047e-01, 3.11866e-02, -5.17776e-03 }, // 32/128 { -4.67520e-03, 2.64621e-02, -9.01591e-02, 3.00980e-01, 8.64812e-01, -1.24154e-01, 3.18153e-02, -5.28823e-03 }, // 33/128 { -4.78866e-03, 2.71272e-02, -9.25834e-02, 3.10980e-01, 8.58189e-01, -1.26161e-01, 3.24205e-02, -5.39500e-03 }, // 34/128 { -4.89961e-03, 2.77794e-02, -9.49727e-02, 3.21004e-01, 8.51437e-01, -1.28068e-01, 3.30021e-02, -5.49804e-03 }, // 35/128 { -5.00800e-03, 2.84182e-02, -9.73254e-02, 3.31048e-01, 8.44559e-01, -1.29874e-01, 3.35600e-02, -5.59731e-03 }, // 36/128 { -5.11376e-03, 2.90433e-02, -9.96402e-02, 3.41109e-01, 8.37557e-01, -1.31581e-01, 3.40940e-02, -5.69280e-03 }, // 37/128 { -5.21683e-03, 2.96543e-02, -1.01915e-01, 3.51186e-01, 8.30432e-01, -1.33189e-01, 3.46042e-02, -5.78446e-03 }, // 38/128 { -5.31716e-03, 3.02507e-02, -1.04150e-01, 3.61276e-01, 8.23188e-01, -1.34699e-01, 3.50903e-02, -5.87227e-03 }, // 39/128 { -5.41467e-03, 3.08323e-02, -1.06342e-01, 3.71376e-01, 8.15826e-01, -1.36111e-01, 3.55525e-02, -5.95620e-03 }, // 40/128 { -5.50931e-03, 3.13987e-02, -1.08490e-01, 3.81484e-01, 8.08348e-01, -1.37426e-01, 3.59905e-02, -6.03624e-03 }, // 41/128 { -5.60103e-03, 3.19495e-02, -1.10593e-01, 3.91596e-01, 8.00757e-01, -1.38644e-01, 3.64044e-02, -6.11236e-03 }, // 42/128 { -5.68976e-03, 3.24843e-02, -1.12650e-01, 4.01710e-01, 7.93055e-01, -1.39767e-01, 3.67941e-02, -6.18454e-03 }, // 43/128 { -5.77544e-03, 3.30027e-02, -1.14659e-01, 4.11823e-01, 7.85244e-01, -1.40794e-01, 3.71596e-02, -6.25277e-03 }, // 44/128 { -5.85804e-03, 3.35046e-02, -1.16618e-01, 4.21934e-01, 7.77327e-01, -1.41727e-01, 3.75010e-02, -6.31703e-03 }, // 45/128 { -5.93749e-03, 3.39894e-02, -1.18526e-01, 4.32038e-01, 7.69305e-01, -1.42566e-01, 3.78182e-02, -6.37730e-03 }, // 46/128 { -6.01374e-03, 3.44568e-02, -1.20382e-01, 4.42134e-01, 7.61181e-01, -1.43313e-01, 3.81111e-02, -6.43358e-03 }, // 47/128 { -6.08674e-03, 3.49066e-02, -1.22185e-01, 4.52218e-01, 7.52958e-01, -1.43968e-01, 3.83800e-02, -6.48585e-03 }, // 48/128 { -6.15644e-03, 3.53384e-02, -1.23933e-01, 4.62289e-01, 7.44637e-01, -1.44531e-01, 3.86247e-02, -6.53412e-03 }, // 49/128 { -6.22280e-03, 3.57519e-02, -1.25624e-01, 4.72342e-01, 7.36222e-01, -1.45004e-01, 3.88454e-02, -6.57836e-03 }, // 50/128 { -6.28577e-03, 3.61468e-02, -1.27258e-01, 4.82377e-01, 7.27714e-01, -1.45387e-01, 3.90420e-02, -6.61859e-03 }, // 51/128 { -6.34530e-03, 3.65227e-02, -1.28832e-01, 4.92389e-01, 7.19116e-01, -1.45682e-01, 3.92147e-02, -6.65479e-03 }, // 52/128 { -6.40135e-03, 3.68795e-02, -1.30347e-01, 5.02377e-01, 7.10431e-01, -1.45889e-01, 3.93636e-02, -6.68698e-03 }, // 53/128 { -6.45388e-03, 3.72167e-02, -1.31800e-01, 5.12337e-01, 7.01661e-01, -1.46009e-01, 3.94886e-02, -6.71514e-03 }, // 54/128 { -6.50285e-03, 3.75341e-02, -1.33190e-01, 5.22267e-01, 6.92808e-01, -1.46043e-01, 3.95900e-02, -6.73929e-03 }, // 55/128 { -6.54823e-03, 3.78315e-02, -1.34515e-01, 5.32164e-01, 6.83875e-01, -1.45993e-01, 3.96678e-02, -6.75943e-03 }, // 56/128 { -6.58996e-03, 3.81085e-02, -1.35775e-01, 5.42025e-01, 6.74865e-01, -1.45859e-01, 3.97222e-02, -6.77557e-03 }, // 57/128 { -6.62802e-03, 3.83650e-02, -1.36969e-01, 5.51849e-01, 6.65779e-01, -1.45641e-01, 3.97532e-02, -6.78771e-03 }, // 58/128 { -6.66238e-03, 3.86006e-02, -1.38094e-01, 5.61631e-01, 6.56621e-01, -1.45343e-01, 3.97610e-02, -6.79588e-03 }, // 59/128 { -6.69300e-03, 3.88151e-02, -1.39150e-01, 5.71370e-01, 6.47394e-01, -1.44963e-01, 3.97458e-02, -6.80007e-03 }, // 60/128 { -6.71985e-03, 3.90083e-02, -1.40136e-01, 5.81063e-01, 6.38099e-01, -1.44503e-01, 3.97077e-02, -6.80032e-03 }, // 61/128 { -6.74291e-03, 3.91800e-02, -1.41050e-01, 5.90706e-01, 6.28739e-01, -1.43965e-01, 3.96469e-02, -6.79662e-03 }, // 62/128 { -6.76214e-03, 3.93299e-02, -1.41891e-01, 6.00298e-01, 6.19318e-01, -1.43350e-01, 3.95635e-02, -6.78902e-03 }, // 63/128 { -6.77751e-03, 3.94578e-02, -1.42658e-01, 6.09836e-01, 6.09836e-01, -1.42658e-01, 3.94578e-02, -6.77751e-03 }, // 64/128 { -6.78902e-03, 3.95635e-02, -1.43350e-01, 6.19318e-01, 6.00298e-01, -1.41891e-01, 3.93299e-02, -6.76214e-03 }, // 65/128 { -6.79662e-03, 3.96469e-02, -1.43965e-01, 6.28739e-01, 5.90706e-01, -1.41050e-01, 3.91800e-02, -6.74291e-03 }, // 66/128 { -6.80032e-03, 3.97077e-02, -1.44503e-01, 6.38099e-01, 5.81063e-01, -1.40136e-01, 3.90083e-02, -6.71985e-03 }, // 67/128 { -6.80007e-03, 3.97458e-02, -1.44963e-01, 6.47394e-01, 5.71370e-01, -1.39150e-01, 3.88151e-02, -6.69300e-03 }, // 68/128 { -6.79588e-03, 3.97610e-02, -1.45343e-01, 6.56621e-01, 5.61631e-01, -1.38094e-01, 3.86006e-02, -6.66238e-03 }, // 69/128 { -6.78771e-03, 3.97532e-02, -1.45641e-01, 6.65779e-01, 5.51849e-01, -1.36969e-01, 3.83650e-02, -6.62802e-03 }, // 70/128 { -6.77557e-03, 3.97222e-02, -1.45859e-01, 6.74865e-01, 5.42025e-01, -1.35775e-01, 3.81085e-02, -6.58996e-03 }, // 71/128 { -6.75943e-03, 3.96678e-02, -1.45993e-01, 6.83875e-01, 5.32164e-01, -1.34515e-01, 3.78315e-02, -6.54823e-03 }, // 72/128 { -6.73929e-03, 3.95900e-02, -1.46043e-01, 6.92808e-01, 5.22267e-01, -1.33190e-01, 3.75341e-02, -6.50285e-03 }, // 73/128 { -6.71514e-03, 3.94886e-02, -1.46009e-01, 7.01661e-01, 5.12337e-01, -1.31800e-01, 3.72167e-02, -6.45388e-03 }, // 74/128 { -6.68698e-03, 3.93636e-02, -1.45889e-01, 7.10431e-01, 5.02377e-01, -1.30347e-01, 3.68795e-02, -6.40135e-03 }, // 75/128 { -6.65479e-03, 3.92147e-02, -1.45682e-01, 7.19116e-01, 4.92389e-01, -1.28832e-01, 3.65227e-02, -6.34530e-03 }, // 76/128 { -6.61859e-03, 3.90420e-02, -1.45387e-01, 7.27714e-01, 4.82377e-01, -1.27258e-01, 3.61468e-02, -6.28577e-03 }, // 77/128 { -6.57836e-03, 3.88454e-02, -1.45004e-01, 7.36222e-01, 4.72342e-01, -1.25624e-01, 3.57519e-02, -6.22280e-03 }, // 78/128 { -6.53412e-03, 3.86247e-02, -1.44531e-01, 7.44637e-01, 4.62289e-01, -1.23933e-01, 3.53384e-02, -6.15644e-03 }, // 79/128 { -6.48585e-03, 3.83800e-02, -1.43968e-01, 7.52958e-01, 4.52218e-01, -1.22185e-01, 3.49066e-02, -6.08674e-03 }, // 80/128 { -6.43358e-03, 3.81111e-02, -1.43313e-01, 7.61181e-01, 4.42134e-01, -1.20382e-01, 3.44568e-02, -6.01374e-03 }, // 81/128 { -6.37730e-03, 3.78182e-02, -1.42566e-01, 7.69305e-01, 4.32038e-01, -1.18526e-01, 3.39894e-02, -5.93749e-03 }, // 82/128 { -6.31703e-03, 3.75010e-02, -1.41727e-01, 7.77327e-01, 4.21934e-01, -1.16618e-01, 3.35046e-02, -5.85804e-03 }, // 83/128 { -6.25277e-03, 3.71596e-02, -1.40794e-01, 7.85244e-01, 4.11823e-01, -1.14659e-01, 3.30027e-02, -5.77544e-03 }, // 84/128 { -6.18454e-03, 3.67941e-02, -1.39767e-01, 7.93055e-01, 4.01710e-01, -1.12650e-01, 3.24843e-02, -5.68976e-03 }, // 85/128 { -6.11236e-03, 3.64044e-02, -1.38644e-01, 8.00757e-01, 3.91596e-01, -1.10593e-01, 3.19495e-02, -5.60103e-03 }, // 86/128 { -6.03624e-03, 3.59905e-02, -1.37426e-01, 8.08348e-01, 3.81484e-01, -1.08490e-01, 3.13987e-02, -5.50931e-03 }, // 87/128 { -5.95620e-03, 3.55525e-02, -1.36111e-01, 8.15826e-01, 3.71376e-01, -1.06342e-01, 3.08323e-02, -5.41467e-03 }, // 88/128 { -5.87227e-03, 3.50903e-02, -1.34699e-01, 8.23188e-01, 3.61276e-01, -1.04150e-01, 3.02507e-02, -5.31716e-03 }, // 89/128 { -5.78446e-03, 3.46042e-02, -1.33189e-01, 8.30432e-01, 3.51186e-01, -1.01915e-01, 2.96543e-02, -5.21683e-03 }, // 90/128 { -5.69280e-03, 3.40940e-02, -1.31581e-01, 8.37557e-01, 3.41109e-01, -9.96402e-02, 2.90433e-02, -5.11376e-03 }, // 91/128 { -5.59731e-03, 3.35600e-02, -1.29874e-01, 8.44559e-01, 3.31048e-01, -9.73254e-02, 2.84182e-02, -5.00800e-03 }, // 92/128 { -5.49804e-03, 3.30021e-02, -1.28068e-01, 8.51437e-01, 3.21004e-01, -9.49727e-02, 2.77794e-02, -4.89961e-03 }, // 93/128 { -5.39500e-03, 3.24205e-02, -1.26161e-01, 8.58189e-01, 3.10980e-01, -9.25834e-02, 2.71272e-02, -4.78866e-03 }, // 94/128 { -5.28823e-03, 3.18153e-02, -1.24154e-01, 8.64812e-01, 3.00980e-01, -9.01591e-02, 2.64621e-02, -4.67520e-03 }, // 95/128 { -5.17776e-03, 3.11866e-02, -1.22047e-01, 8.71305e-01, 2.91006e-01, -8.77011e-02, 2.57844e-02, -4.55932e-03 }, // 96/128 { -5.06363e-03, 3.05345e-02, -1.19837e-01, 8.77666e-01, 2.81060e-01, -8.52109e-02, 2.50946e-02, -4.44107e-03 }, // 97/128 { -4.94589e-03, 2.98593e-02, -1.17526e-01, 8.83893e-01, 2.71144e-01, -8.26900e-02, 2.43930e-02, -4.32052e-03 }, // 98/128 { -4.82456e-03, 2.91609e-02, -1.15113e-01, 8.89984e-01, 2.61263e-01, -8.01399e-02, 2.36801e-02, -4.19774e-03 }, // 99/128 { -4.69970e-03, 2.84397e-02, -1.12597e-01, 8.95936e-01, 2.51417e-01, -7.75620e-02, 2.29562e-02, -4.07279e-03 }, // 100/128 { -4.57135e-03, 2.76957e-02, -1.09978e-01, 9.01749e-01, 2.41609e-01, -7.49577e-02, 2.22218e-02, -3.94576e-03 }, // 101/128 { -4.43955e-03, 2.69293e-02, -1.07256e-01, 9.07420e-01, 2.31843e-01, -7.23286e-02, 2.14774e-02, -3.81671e-03 }, // 102/128 { -4.30435e-03, 2.61404e-02, -1.04430e-01, 9.12947e-01, 2.22120e-01, -6.96762e-02, 2.07233e-02, -3.68570e-03 }, // 103/128 { -4.16581e-03, 2.53295e-02, -1.01501e-01, 9.18329e-01, 2.12443e-01, -6.70018e-02, 1.99599e-02, -3.55283e-03 }, // 104/128 { -4.02397e-03, 2.44967e-02, -9.84679e-02, 9.23564e-01, 2.02814e-01, -6.43069e-02, 1.91877e-02, -3.41815e-03 }, // 105/128 { -3.87888e-03, 2.36423e-02, -9.53307e-02, 9.28650e-01, 1.93236e-01, -6.15931e-02, 1.84071e-02, -3.28174e-03 }, // 106/128 { -3.73062e-03, 2.27664e-02, -9.20893e-02, 9.33586e-01, 1.83711e-01, -5.88617e-02, 1.76185e-02, -3.14367e-03 }, // 107/128 { -3.57923e-03, 2.18695e-02, -8.87435e-02, 9.38371e-01, 1.74242e-01, -5.61142e-02, 1.68225e-02, -3.00403e-03 }, // 108/128 { -3.42477e-03, 2.09516e-02, -8.52933e-02, 9.43001e-01, 1.64831e-01, -5.33522e-02, 1.60193e-02, -2.86289e-03 }, // 109/128 { -3.26730e-03, 2.00132e-02, -8.17385e-02, 9.47477e-01, 1.55480e-01, -5.05770e-02, 1.52095e-02, -2.72032e-03 }, // 110/128 { -3.10689e-03, 1.90545e-02, -7.80792e-02, 9.51795e-01, 1.46192e-01, -4.77900e-02, 1.43934e-02, -2.57640e-03 }, // 111/128 { -2.94361e-03, 1.80759e-02, -7.43154e-02, 9.55956e-01, 1.36968e-01, -4.49929e-02, 1.35716e-02, -2.43121e-03 }, // 112/128 { -2.77751e-03, 1.70776e-02, -7.04471e-02, 9.59958e-01, 1.27812e-01, -4.21869e-02, 1.27445e-02, -2.28483e-03 }, // 113/128 { -2.60868e-03, 1.60599e-02, -6.64743e-02, 9.63798e-01, 1.18725e-01, -3.93735e-02, 1.19125e-02, -2.13733e-03 }, // 114/128 { -2.43718e-03, 1.50233e-02, -6.23972e-02, 9.67477e-01, 1.09710e-01, -3.65541e-02, 1.10760e-02, -1.98880e-03 }, // 115/128 { -2.26307e-03, 1.39681e-02, -5.82159e-02, 9.70992e-01, 1.00769e-01, -3.37303e-02, 1.02356e-02, -1.83931e-03 }, // 116/128 { -2.08645e-03, 1.28947e-02, -5.39305e-02, 9.74342e-01, 9.19033e-02, -3.09033e-02, 9.39154e-03, -1.68894e-03 }, // 117/128 { -1.90738e-03, 1.18034e-02, -4.95412e-02, 9.77526e-01, 8.31162e-02, -2.80746e-02, 8.54441e-03, -1.53777e-03 }, // 118/128 { -1.72594e-03, 1.06946e-02, -4.50483e-02, 9.80543e-01, 7.44095e-02, -2.52457e-02, 7.69462e-03, -1.38589e-03 }, // 119/128 { -1.54221e-03, 9.56876e-03, -4.04519e-02, 9.83392e-01, 6.57852e-02, -2.24178e-02, 6.84261e-03, -1.23337e-03 }, // 120/128 { -1.35627e-03, 8.42626e-03, -3.57525e-02, 9.86071e-01, 5.72454e-02, -1.95925e-02, 5.98883e-03, -1.08030e-03 }, // 121/128 { -1.16820e-03, 7.26755e-03, -3.09503e-02, 9.88580e-01, 4.87921e-02, -1.67710e-02, 5.13372e-03, -9.26747e-04 }, // 122/128 { -9.78093e-04, 6.09305e-03, -2.60456e-02, 9.90917e-01, 4.04274e-02, -1.39548e-02, 4.27773e-03, -7.72802e-04 }, // 123/128 { -7.86031e-04, 4.90322e-03, -2.10389e-02, 9.93082e-01, 3.21531e-02, -1.11453e-02, 3.42130e-03, -6.18544e-04 }, // 124/128 { -5.92100e-04, 3.69852e-03, -1.59305e-02, 9.95074e-01, 2.39714e-02, -8.34364e-03, 2.56486e-03, -4.64053e-04 }, // 125/128 { -3.96391e-04, 2.47942e-03, -1.07209e-02, 9.96891e-01, 1.58840e-02, -5.55134e-03, 1.70888e-03, -3.09412e-04 }, // 126/128 { -1.98993e-04, 1.24642e-03, -5.41054e-03, 9.98534e-01, 7.89295e-03, -2.76968e-03, 8.53777e-04, -1.54700e-04 }, // 127/128 { 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 }, // 128/128 }; gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/fft_filter_fff.h0000664000175000017500000000605212207440367025065 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FFT_FILTER_FFF_H #define INCLUDED_FILTER_FFT_FILTER_FFF_H #include #include namespace gr { namespace filter { /*! * \brief Fast FFT filter with float input, float output and float taps * \ingroup filter_blk * * \details * This block implements a real-value decimating filter using the * fast convolution method via an FFT. The decimation factor is an * interger that is greater than or equal to 1. * * The filter takes a set of real-valued taps to use in the * filtering operation. These taps can be defined as anything that * satisfies the user's filtering needs. For standard filters such * as lowpass, highpass, bandpass, etc., the filter.firdes and * filter.optfir classes provide convenient generating methods. * * This filter is implemented by using the FFTW package to perform * the required FFTs. An optional argument, nthreads, may be * passed to the constructor (or set using the set_nthreads member * function) to split the FFT among N number of threads. This can * improve performance on very large FFTs (that is, if the number * of taps used is very large) if you have enough threads/cores to * support it. */ class FILTER_API fft_filter_fff : virtual public sync_decimator { public: // gr::filter::fft_filter_fff::sptr typedef boost::shared_ptr sptr; /*! * Build an FFT filter block. * * \param decimation >= 1 * \param taps float filter taps * \param nthreads number of threads for the FFT to use */ static sptr make(int decimation, const std::vector &taps, int nthreads=1); virtual void set_taps(const std::vector &taps) = 0; virtual std::vector taps() const = 0; /*! * \brief Set number of threads to use. */ virtual void set_nthreads(int n) = 0; /*! * \brief Get number of threads being used. */ virtual int nthreads() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FFT_FILTER_FFF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_channelizer_ccf.h0000664000175000017500000002137612207440367026072 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_PFB_CHANNELIZER_CCF_H #define INCLUDED_FILTER_PFB_CHANNELIZER_CCF_H #include #include namespace gr { namespace filter { /*! * \brief Polyphase filterbank channelizer with * gr_complex input, gr_complex output and float taps * \ingroup channelizers_blk * * \details * This block takes in complex inputs and channelizes it to M * channels of equal bandwidth. Each of the resulting channels is * decimated to the new rate that is the input sampling rate * fs divided by the number of channels, M. * * The PFB channelizer code takes the taps generated above and builds * a set of filters. The set contains M number of filters * and each filter contains ceil(taps.size()/decim) number of taps. * Each tap from the filter prototype is sequentially inserted into * the next filter. When all of the input taps are used, the remaining * filters in the filterbank are filled out with 0's to make sure each * filter has the same number of taps. * * Each filter operates using the gr::blocks::fir_filter_XXX * classs of GNU Radio, which takes the input stream at i * and performs the inner product calculation to i+(n-1) * where n is the number of filter taps. To efficiently * handle this in the GNU Radio structure, each filter input must * come from its own input stream. So the channelizer must be * provided with M streams where the input stream has * been deinterleaved. This is most easily done using the * gr::blocks::stream_to_streams block. * * The output is then produced as a vector, where index i * in the vector is the next sample from the ith * channel. This is most easily handled by sending the output to a * gr::blocks::vector_to_streams block to handle the conversion * and passing M streams out. * * The input and output formatting is done using a hier_block2 called * pfb_channelizer_ccf. This can take in a single stream and outputs * M streams based on the behavior described above. * * The filter's taps should be based on the input sampling rate. * * For example, using the GNU Radio's firdes utility to building * filters, we build a low-pass filter with a sampling rate of * fs, a 3-dB bandwidth of BW and a transition * bandwidth of TB. We can also specify the out-of-band * attenuation to use, ATT, and the filter window * function (a Blackman-harris window in this case). The first input * is the gain of the filter, which we specify here as unity. * * self._taps = filter.firdes.low_pass_2(1, fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * The filter output can also be overs ampled. The over sampling rate * is the ratio of the the actual output sampling rate to the normal * output sampling rate. It must be rationally related to the number * of channels as N/i for i in [1,N], which gives an outputsample rate * of [fs/N, fs] where fs is the input sample rate and N is the number * of channels. * * For example, for 6 channels with fs = 6000 Hz, the normal rate is * 6000/6 = 1000 Hz. Allowable oversampling rates are 6/6, 6/5, 6/4, * 6/3, 6/2, and 6/1 where the output sample rate of a 6/1 oversample * ratio is 6000 Hz, or 6 times the normal 1000 Hz. A rate of 6/5 = 1.2, * so the output rate would be 1200 Hz. * * The theory behind this block can be found in Chapter 6 of * the following book. * * f. harris, "Multirate Signal Processing for Communication * Systems," Upper Saddle River, NJ: Prentice Hall, Inc. 2004. * */ class FILTER_API pfb_channelizer_ccf : virtual public block { public: // gr::filter::pfb_channelizer_ccf::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank decimator. * \param numchans (unsigned integer) Specifies the number of * channels M * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. * \param oversample_rate (float) The over sampling rate is the * ratio of the the actual output * sampling rate to the normal * output sampling rate. It must * be rationally related to the * number of channels as N/i for * i in [1,N], which gives an * outputsample rate of [fs/N, * fs] where fs is the input * sample rate and N is the * number of channels. * * For example, for 6 channels * with fs = 6000 Hz, the normal * rateis 6000/6 = 1000 * Hz. Allowable oversampling * rates are 6/6, 6/5, 6/4, 6/3, * 6/2, and 6/1 where the output * sample rate of a 6/1 * oversample ratio is 6000 Hz, * or 6 times the normal 1000 Hz. */ static sptr make(unsigned int numchans, const std::vector &taps, float oversample_rate); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. */ virtual void set_taps(const std::vector &taps) = 0; /*! * Print all of the filterbank taps to screen. */ virtual void print_taps() = 0; /*! * Return a vector> of the filterbank taps */ virtual std::vector > taps() const = 0; /*! * Set the channel map. Channels are numbers as: * * N/2+1 | ... | N-1 | 0 | 1 | 2 | ... | N/2 * <------------------- 0 --------------------> * freq * * So output stream 0 comes from channel 0, etc. Setting a new * channel map allows the user to specify which channel in frequency * he/she wants to got to which output stream. * * The map should have the same number of elements as the number * of output connections from the block. The minimum value of * the map is 0 (for the 0th channel) and the maximum number is * N-1 where N is the number of channels. * * We specify M as the number of output connections made where M * <= N, so only M out of N channels are driven to an output * stream. The number of items in the channel map should be at * least M long. If there are more channels specified, any value * in the map over M-1 will be ignored. If the size of the map * is less than M the behavior is unknown (we don't wish to * check every entry into the work function). * * This means that if the channelizer is splitting the signal up * into N channels but only M channels are specified in the map * (where M <= N), then M output streams must be connected and * the map and the channel numbers used must be less than * N-1. Output channel number can be reused, too. By default, * the map is [0...M-1] with M = N. */ virtual void set_channel_map(const std::vector &map) = 0; /*! * Gets the current channel map. */ virtual std::vector channel_map() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_PFB_CHANNELIZER_CCF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/adaptive_fir.h0000664000175000017500000000520212245466767024567 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_ADAPTIVE_FIR_H #define INCLUDED_FILTER_ADAPTIVE_FIR_H #include #include namespace gr { namespace filter { namespace kernel { /*! * \brief Adaptive FIR filter kernel with gr_complex input, * gr_complex output and gr_complex taps * * This class implements an adaptive FIR filter. Any class * actually wanting to use adaptive FIRs will contain an object of * this class. */ class FILTER_API adaptive_fir_ccc : public fir_filter_ccc { public: adaptive_fir_ccc(int decimation, const std::vector &taps); ~adaptive_fir_ccc(); protected: // Override to calculate error signal per output virtual gr_complex error(const gr_complex &out) = 0; // Override to calculate new weight from old, corresponding input virtual void update_tap(gr_complex &tap, const gr_complex &in) = 0; gr_complex d_error; }; /*! * \brief Adaptive FIR filter kernel with gr_complex input, * gr_complex output and float taps * * This class implements an adaptive FIR filter. Any class * actually wanting to use adaptive FIRs will contain an object of * this class. */ class FILTER_API adaptive_fir_ccf : public fir_filter_ccf { public: adaptive_fir_ccf(int decimation, const std::vector &taps); ~adaptive_fir_ccf(); protected: // Override to calculate error signal per output virtual float error(const gr_complex &out) = 0; // Override to calculate new weight from old, corresponding input virtual void update_tap(float &tap, const gr_complex &in) = 0; float d_error; }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_ADAPTIVE_FIR_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/mmse_fir_interpolator_cc.h0000664000175000017500000000523512207440367027172 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _GRI_MMSE_FIR_INTERPOLATOR_CC_H_ #define _GRI_MMSE_FIR_INTERPOLATOR_CC_H_ #include #include #include #include namespace gr { namespace filter { /*! * \brief Compute intermediate samples between signal samples x(k*Ts) * \ingroup filter_primitive * * \details * This implements a Mininum Mean Squared Error interpolator with * 8 taps. It is suitable for signals where the bandwidth of * interest B = 1/(4*Ts) Where Ts is the time between samples. * * Although mu, the fractional delay, is specified as a float, it * is actually quantized. 0.0 <= mu <= 1.0. That is, mu is * quantized in the interpolate method to 32nd's of a sample. * * For more information, in the GNU Radio source code, see: * \li gr-filter/lib/gen_interpolator_taps/README * \li gr-filter/lib/gen_interpolator_taps/praxis.txt */ class FILTER_API mmse_fir_interpolator_cc { public: mmse_fir_interpolator_cc(); ~mmse_fir_interpolator_cc(); unsigned ntaps() const; unsigned nsteps() const; /*! * \brief compute a single interpolated output value. * * \p input must have ntaps() valid entries and be 8-byte aligned. * input[0] .. input[ntaps() - 1] are referenced to compute the output value. * \throws std::invalid_argument if input is not 8-byte aligned. * * \p mu must be in the range [0, 1] and specifies the fractional delay. * * \returns the interpolated input value. */ gr_complex interpolate(const gr_complex input[], float mu) const; protected: std::vector filters; }; } /* namespace filter */ } /* namespace gr */ #endif /* _MMSE_FIR_INTERPOLATOR_CC_H_ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/hilbert_fc.h0000664000175000017500000000371212221050153024203 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_HILBERT_FC_H #define INCLUDED_FILTER_HILBERT_FC_H #include #include #include #include namespace gr { namespace filter { /*! * \brief Hilbert transformer. * \ingroup filter_blk * * \details * real output is input appropriately delayed. * imaginary output is hilbert filtered (90 degree phase shift) * version of input. */ class FILTER_API hilbert_fc : virtual public sync_block { public: // gr::filter::hilbert_fc::sptr typedef boost::shared_ptr sptr; /*! * Build a Hilbert transformer filter block. * * \param ntaps The number of taps for the filter. * \param window Window type (see firdes::win_type) to use. * \param beta Beta value for a Kaiser window. */ static sptr make(unsigned int ntaps, firdes::win_type window=firdes::WIN_HAMMING, double beta=6.76); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_HILBERT_FC_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/dc_blocker_ff.h0000664000175000017500000000533012207440367024660 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_DC_BLOCKER_FF_H #define INCLUDED_FILTER_DC_BLOCKER_FF_H #include #include namespace gr { namespace filter { /*! * \brief a computationally efficient controllable DC blocker * \ingroup filter_blk * * \details * This block implements a computationally efficient DC blocker * that produces a tighter notch filter around DC for a smaller * group delay than an equivalent FIR filter or using a single * pole IIR filter (though the IIR filter is computationally * cheaper). * * The block defaults to using a delay line of length 32 and the * long form of the filter. Optionally, the delay line length can * be changed to alter the width of the DC notch (longer lines * will decrease the width). * * The long form of the filter produces a nearly flat response * outside of the notch but at the cost of a group delay of 2D-2. * * The short form of the filter does not have as flat a response * in the passband but has a group delay of only D-1 and is * cheaper to compute. * * The theory behind this block can be found in the paper: * * R. Yates, "DC Blocker Algorithms," IEEE Signal Processing Magazine, * Mar. 2008, pp 132-134. */ class FILTER_API dc_blocker_ff : virtual public sync_block { public: // gr::filter::dc_blocker_ff::sptr typedef boost::shared_ptr sptr; /*! * Make a DC blocker block. * * \param D (int) the length of the delay line * \param long_form (bool) whether to use long (true, default) or short form */ static sptr make(int D, bool long_form=true); virtual int group_delay() = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_DC_BLOCKER_FF_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/single_pole_iir_filter_cc.h0000664000175000017500000000442212207440367027274 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SINGLE_POLE_IIR_FILTER_CC_H #define INCLUDED_SINGLE_POLE_IIR_FILTER_CC_H #include #include #include #include namespace gr { namespace filter { /*! * \brief single pole IIR filter with complex input, complex output * \ingroup filter_blk * * \details * The input and output satisfy a difference equation of the form \htmlonly \f{ y[n] - (1-alpha) y[n-1] = alpha x[n] \f} \endhtmlonly \xmlonly y[n] - (1-alpha) y[n-1] = alpha x[n] \endxmlonly * with the corresponding rational system function \htmlonly \f{ H(z) = \frac{alpha}{1 - (1-alpha) z^{-1}} \f} \endhtmlonly \xmlonly H(z) = \ frac{alpha}{1 - (1-alpha) z^{-1}} \endxmlonly * Note that some texts define the system function with a + in the * denominator. If you're using that convention, you'll need to * negate the feedback tap. */ class FILTER_API single_pole_iir_filter_cc : virtual public sync_block { public: // gr::filter::single_pole_iir_filter_cc::sptr typedef boost::shared_ptr sptr; static sptr make(double alpha, unsigned int vlen=1); virtual void set_taps(double alpha) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_SINGLE_POLE_IIR_FILTER_CC_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/api.h0000664000175000017500000000203712207440367022670 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_API_H #define INCLUDED_FILTER_API_H #include #ifdef gnuradio_filter_EXPORTS # define FILTER_API __GR_ATTR_EXPORT #else # define FILTER_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_FILTER_API_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/filter_delay_fc.h0000664000175000017500000000417212207440367025234 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FILTER_DELAY_FC_H #define INCLUDED_FILTER_FILTER_DELAY_FC_H #include #include namespace gr { namespace filter { /*! * \brief Filter-Delay Combination Block. * \ingroup filter_blk * * \details * The block takes one or two float stream and outputs a complex * stream. * * If only one float stream is input, the real output is a delayed * version of this input and the imaginary output is the filtered * output. * * If two floats are connected to the input, then the real output * is the delayed version of the first input, and the imaginary * output is the filtered output. * * The delay in the real path accounts for the group delay * introduced by the filter in the imaginary path. The filter taps * needs to be calculated before initializing this block. */ class FILTER_API filter_delay_fc : virtual public sync_block { public: // gr::filter::filter_delay_fc::sptr typedef boost::shared_ptr sptr; /*! * Build a filter with delay block. */ static sptr make(const std::vector &taps); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FILTER_DELAY_FC_H */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/interp_fir_filter_XXX.h.t0000664000175000017500000000501412207440367026634 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace filter { /*! * \brief Interpolating FIR filter with @I_TYPE@ input, @O_TYPE@ output and @TAP_TYPE@ taps * \ingroup filter_blk * * \details * The fir_filter_XXX blocks create finite impulse response * (FIR) filters that perform the convolution in the time * domain: * * \code * out = 0 * for i in ntaps: * out += input[n-i] * taps[i] * \endcode * * The taps are a C++ vector (or Python list) of values of the * type specified by the third letter in the block's suffix. For * this block, the value is of type @TAP_TYPE@. Taps can be * created using the firdes or optfir tools. * * These versions of the filter can also act as up-samplers * (or interpolators) by specifying an integer value for \p * interpolation. * */ class FILTER_API @BASE_NAME@ : virtual public sync_interpolator { public: // gr::filter::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! * \brief Interpolating FIR filter with @I_TYPE@ input, @O_TYPE@ output, and @TAP_TYPE@ taps * * \param interpolation set the integer interpolation rate * \param taps a vector/list of taps of type @TAP_TYPE@ */ static sptr make(unsigned interpolation, const std::vector<@TAP_TYPE@> &taps); virtual void set_taps(const std::vector<@TAP_TYPE@> &taps) = 0; virtual std::vector<@TAP_TYPE@> taps() const = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/include/gnuradio/filter/pfb_arb_resampler_fff.h0000664000175000017500000001550512207440367026411 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_ARB_RESAMPLER_FFF_H #define INCLUDED_PFB_ARB_RESAMPLER_FFF_H #include #include namespace gr { namespace filter { /*! * \brief Polyphase filterbank arbitrary resampler with * float input, float output and float taps * \ingroup resamplers_blk * * \details * This block takes in a signal stream and performs arbitrary * resampling. The resampling rate can be any real number * r. The resampling is done by constructing N * filters where N is the interpolation rate. We then * calculate D where D = floor(N/r). * * Using N and D, we can perform rational * resampling where N/D is a rational number close to the * input rate r where we have N filters and we * cycle through them as a polyphase filterbank with a stride of * D so that i+1 = (i + D) % N. * * To get the arbitrary rate, we want to interpolate between two * points. For each value out, we take an output from the current * filter, i, and the next filter i+1 and then * linearly interpolate between the two based on the real * resampling rate we want. * * The linear interpolation only provides us with an approximation * to the real sampling rate specified. The error is a * quantization error between the two filters we used as our * interpolation points. To this end, the number of filters, * N, used determines the quantization error; the larger * N, the smaller the noise. You can design for a * specified noise floor by setting the filter size (parameters * filter_size). The size defaults to 32 filters, which * is about as good as most implementations need. * * The trick with designing this filter is in how to specify the * taps of the prototype filter. Like the PFB interpolator, the * taps are specified using the interpolated filter rate. In this * case, that rate is the input sample rate multiplied by the * number of filters in the filterbank, which is also the * interpolation rate. All other values should be relative to this * rate. * * For example, for a 32-filter arbitrary resampler and using the * GNU Radio's firdes utility to build the filter, we build a * low-pass filter with a sampling rate of fs, a 3-dB * bandwidth of BW and a transition bandwidth of * TB. We can also specify the out-of-band attenuation to * use, ATT, and the filter window function (a * Blackman-harris window in this case). The first input is the * gain of the filter, which we specify here as the interpolation * rate (32). * * self._taps = filter.firdes.low_pass_2(32, 32*fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS) * * The theory behind this block can be found in Chapter 7.5 of the * following book. * * f. harris, "Multirate Signal Processing for Communication * Systems", Upper Saddle River, NJ: Prentice Hall, Inc. 2004. */ class FILTER_API pfb_arb_resampler_fff : virtual public block { public: // gr::filter::pfb_arb_resampler_fff::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank arbitray resampler. * \param rate (float) Specifies the resampling rate to use * \param taps (vector/list of floats) The prototype filter to populate the filterbank. The taps * should be generated at the filter_size sampling rate. * \param filter_size (unsigned int) The number of filters in the filter bank. This is directly * related to quantization noise introduced during the resampling. * Defaults to 32 filters. */ static sptr make(float rate, const std::vector &taps, unsigned int filter_size=32); /*! * Resets the filterbank's filter taps with the new prototype filter * \param taps (vector/list of floats) The prototype filter to populate the filterbank. */ virtual void set_taps(const std::vector &taps) = 0; /*! * Return a vector> of the filterbank taps */ virtual std::vector > taps() const = 0; /*! * Print all of the filterbank taps to screen. */ virtual void print_taps() = 0; /*! * Sets the resampling rate of the block. */ virtual void set_rate (float rate) = 0; /*! * Sets the current phase offset in radians (0 to 2pi). */ virtual void set_phase(float ph) = 0; /*! * Gets the current phase of the resampler in radians (2 to 2pi). */ virtual float phase() const = 0; /*! * Gets the number of taps per filter. */ virtual unsigned int taps_per_filter() const = 0; /*! * Gets the interpolation rate of the filter. */ virtual unsigned int interpolation_rate() const = 0; /*! * Gets the decimation rate of the filter. */ virtual unsigned int decimation_rate() const =0; /*! * Gets the fractional rate of the filter. */ virtual float fractional_rate() const = 0; /*! * Get the group delay of the filter. */ virtual int group_delay() const = 0; /*! * Calculates the phase offset expected by a sine wave of * frequency \p freq and sampling rate \p fs (assuming input * sine wave has 0 degree phase). */ virtual float phase_offset(float freq, float fs) = 0; }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_ARB_RESAMPLER_FFF_H */ gnuradio-3.7.2.1/gr-filter/grc/0000755000175000017500000000000012245466767016013 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/grc/filter_block_tree.xml0000664000175000017500000000372012207440367022201 0ustar jcorganjcorgan Filters low_pass_filter high_pass_filter band_pass_filter band_reject_filter root_raised_cosine_filter dc_blocker_xx fft_filter_xxx fir_filter_xxx filter_delay_fc hilbert_fc iir_filter_ffd interp_fir_filter_xxx single_pole_iir_filter_xx Resamplers fractional_resampler_xx pfb_arb_resampler_xxx rational_resampler_xxx rational_resampler_base_xxx Channelizers freq_xlating_fir_filter_xxx pfb_channelizer_ccf pfb_decimator_ccf pfb_interpolator_ccf pfb_synthesizer_ccf gnuradio-3.7.2.1/gr-filter/grc/filter_single_pole_iir_filter_xx.xml0000664000175000017500000000203312207440367025313 0ustar jcorganjcorgan Single Pole IIR Filter single_pole_iir_filter_xx from gnuradio import filter filter.single_pole_iir_filter_$(type.fcn)($alpha, $vlen) set_taps($alpha) Type type enum Alpha alpha 1.0 real Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-filter/grc/CMakeLists.txt0000664000175000017500000000320612207440367020540 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install(FILES filter_block_tree.xml filter_dc_blocker_xx.xml filter_fft_filter_xxx.xml filter_fir_filter_xxx.xml filter_filter_delay_fc.xml filter_fractional_interpolator_xx.xml filter_fractional_resampler_xx.xml filter_freq_xlating_fir_filter_xxx.xml filter_hilbert_fc.xml filter_iir_filter_ffd.xml filter_interp_fir_filter_xxx.xml filter_pfb_arb_resampler.xml filter_pfb_channelizer.xml filter_pfb_decimator.xml filter_pfb_interpolator.xml filter_pfb_synthesizer.xml filter_rational_resampler_xxx.xml filter_rational_resampler_base_xxx.xml filter_single_pole_iir_filter_xx.xml filter_low_pass_filter.xml filter_high_pass_filter.xml filter_band_pass_filter.xml filter_band_reject_filter.xml filter_root_raised_cosine_filter.xml DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "filter_python" ) gnuradio-3.7.2.1/gr-filter/grc/filter_fractional_resampler_xx.xml0000664000175000017500000000207512207702530024776 0ustar jcorganjcorgan Fractional Resampler fractional_resampler_xx from gnuradio import filter filter.fractional_resampler_$(type.fcn)($phase_shift, $resamp_ratio) set_resamp_ratio($resamp_ratio) Type type enum Phase Shift phase_shift real Resampling Ratio resamp_ratio real in $type rate float 1 out $type gnuradio-3.7.2.1/gr-filter/grc/filter_interp_fir_filter_xxx.xml0000664000175000017500000000405212237515112024476 0ustar jcorganjcorgan Interpolating FIR Filter interp_fir_filter_xxx from gnuradio import filter from gnuradio.filter import firdes filter.interp_fir_filter_$(type)($interp, $taps) self.$(id).declare_sample_delay($samp_delay) set_taps($taps) Type type enum Interpolation interp 1 int Taps taps $type.taps Sample Delay samp_delay 0 int part in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_low_pass_xlating_filter.xml0000664000175000017500000001016412207440367025012 0ustar jcorganjcorgan Xlating Low Pass Filter xlating_low_pass_filter from gnuradio import filter from gnuradio.filter import firdes filter.freq_xlating_fir_filter_$(type)($decim, firdes.low_pass( $gain, 2*$samp_rate, $cutoff_freq, $width, $win, $beta), $center_freq, $samp_rate) set_taps(firdes.low_pass($gain, 2*$samp_rate, $cutoff_freq, $width, $win, $beta)) set_center_freq($center_freq) Type type enum Decimation decim 1 int Gain gain 1 real Sample Rate samp_rate samp_rate real Center Frequency center_freq 0 real Cutoff Freq cutoff_freq real Transition Width width real Window win firdes.WIN_HAMMING int Beta beta 6.76 real in $type.input out $type.output This filter is a convenience wrapper for an xlating fir filter and a firdes taps generating function. Sample rate, cutoff frequency, and transition width are in Hertz. The beta paramater only applies to the Kaiser window. gnuradio-3.7.2.1/gr-filter/grc/filter_pfb_arb_resampler.xml0000664000175000017500000000301312207440367023530 0ustar jcorganjcorgan Polyphase Arbitrary Resampler pfb_arb_resampler_xxx from gnuradio.filter import pfb from gnuradio.filter import firdes pfb.arb_resampler_$(type)( $rrate, #if $taps() taps=$taps, #else taps=None, #end if flt_size=$nfilts) set_taps($taps) set_rate($rrate) Type type enum Resampling Rate rrate real Taps taps $type.taps Number of Filters nfilts 32 int Stop-band Attenuation atten 100 real in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_fir_filter_xxx.xml0000664000175000017500000000402112237515112023111 0ustar jcorganjcorgan Decimating FIR Filter fir_filter_xxx from gnuradio import filter from gnuradio.filter import firdes filter.fir_filter_$(type)($decim, $taps) self.$(id).declare_sample_delay($samp_delay) set_taps($taps) Type type enum Decimation decim 1 int Taps taps $type.taps Sample Delay samp_delay 0 int part in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_root_raised_cosine_filter.xml0000664000175000017500000000470712207440367025315 0ustar jcorganjcorgan Root Raised Cosine Filter root_raised_cosine_filter from gnuradio import filter from gnuradio.filter import firdes filter.$(type)(#if str($type).startswith('interp') then $interp else $decim#, firdes.root_raised_cosine( $gain, $samp_rate, $sym_rate, $alpha, $ntaps)) set_taps(firdes.root_raised_cosine($gain, $samp_rate, $sym_rate, $alpha, $ntaps)) FIR Type type enum Decimation decim 1 int #if str($type).startswith('interp') then 'all' else 'none'# Interpolation interp 1 int #if str($type).startswith('interp') then 'none' else 'all'# Gain gain 1 real Sample Rate samp_rate samp_rate real Symbol Rate sym_rate 1.0 real Alpha alpha 0.35 real Num Taps ntaps 11*samp_rate int in $type.input out $type.output This filter is a convenience wrapper for an fir filter and a firdes taps generating function. Sample rate in Hertz. gnuradio-3.7.2.1/gr-filter/grc/filter_band_reject_filter.xml0000664000175000017500000000621412207440367023676 0ustar jcorganjcorgan Band Reject Filter band_reject_filter from gnuradio import filter from gnuradio.filter import firdes filter.$(type)(#if str($type).startswith('interp') then $interp else $decim#, firdes.band_reject( $gain, $samp_rate, $low_cutoff_freq, $high_cutoff_freq, $width, $win, $beta)) set_taps(firdes.band_reject($gain, $samp_rate, $low_cutoff_freq, $high_cutoff_freq, $width, $win, $beta)) FIR Type type enum Decimation decim 1 int #if str($type).startswith('interp') then 'all' else 'none'# Interpolation interp 1 int #if str($type).startswith('interp') then 'none' else 'all'# Gain gain 1 real Sample Rate samp_rate samp_rate real Low Cutoff Freq low_cutoff_freq real High Cutoff Freq high_cutoff_freq real Transition Width width real Window win firdes.WIN_HAMMING int Beta beta 6.76 real in $type.input out $type.output This filter is a convenience wrapper for an fir filter and a firdes taps generating function. Sample rate, cutoff frequency, and transition width are in Hertz. The beta paramater only applies to the Kaiser window. gnuradio-3.7.2.1/gr-filter/grc/filter_rational_resampler_xxx.xml0000664000175000017500000000370412214652673024667 0ustar jcorganjcorgan Rational Resampler rational_resampler_xxx from gnuradio import filter from gnuradio.filter import firdes filter.rational_resampler_$(type)( interpolation=$interp, decimation=$decim, #if $taps() taps=$taps, #else taps=None, #end if #if $fbw() != 0 fractional_bw=$fbw, #else fractional_bw=None, #end if ) set_taps($taps) Type type enum Interpolation interp 1 int Decimation decim 1 int Taps taps $type.taps Fractional BW fbw 0 real in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_filter_delay_fc.xml0000664000175000017500000000121212207440367023175 0ustar jcorganjcorgan Filter Delay filter_delay_fc from gnuradio import filter from gnuradio.filter import firdes filter.filter_delay_fc($taps) Taps taps real_vector in float in float 1 out complex gnuradio-3.7.2.1/gr-filter/grc/filter_fractional_interpolator_xx.xml0000664000175000017500000000175312207440367025537 0ustar jcorganjcorgan Fractional Interpolator fractional_interpolator_xx from gnuradio import filter filter.fractional_interpolator_$(type.fcn)($phase_shift, $interp_ratio) set_interp_ratio($interp_ratio) Type type enum Phase Shift phase_shift real Interpolation Ratio interp_ratio real in $type out $type gnuradio-3.7.2.1/gr-filter/grc/filter_fft_filter_xxx.xml0000664000175000017500000000275312237515112023122 0ustar jcorganjcorgan FFT Filter fft_filter_xxx from gnuradio import filter from gnuradio.filter import firdes filter.fft_filter_$(type)($decim, $taps, $nthreads) self.$(id).declare_sample_delay($samp_delay) set_taps($taps) set_nthreads($nthreads) Type type enum Decimation decim 1 int Taps taps $type.taps Sample Delay samp_delay 0 int part Num. Threads nthreads 1 int in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_band_pass_filter.xml0000664000175000017500000001017312207440367023367 0ustar jcorganjcorgan Band Pass Filter band_pass_filter from gnuradio import filter from gnuradio.filter import firdes filter.$(type)(#if str($type).startswith('interp') then $interp else $decim#, firdes.$(type.fcn)( $gain, $samp_rate, $low_cutoff_freq, $high_cutoff_freq, $width, $win, $beta)) set_taps(firdes.$(type.fcn)($gain, $samp_rate, $low_cutoff_freq, $high_cutoff_freq, $width, $win, $beta)) FIR Type type enum Decimation decim 1 int #if str($type).startswith('interp') then 'all' else 'none'# Interpolation interp 1 int #if str($type).startswith('interp') then 'none' else 'all'# Gain gain 1 real Sample Rate samp_rate samp_rate real Low Cutoff Freq low_cutoff_freq real High Cutoff Freq high_cutoff_freq real Transition Width width real Window win firdes.WIN_HAMMING int Beta beta 6.76 real in $type.input out $type.output This filter is a convenience wrapper for an fir filter and a firdes taps generating function. Sample rate, cutoff frequency, and transition width are in Hertz. The beta paramater only applies to the Kaiser window. gnuradio-3.7.2.1/gr-filter/grc/filter_hilbert_fc.xml0000664000175000017500000000256112221050153022155 0ustar jcorganjcorgan Hilbert hilbert_fc from gnuradio import filter filter.hilbert_fc($num_taps, $win, $beta) Num Taps num_taps 65 int Window win firdes.WIN_HAMMING int part Beta beta 6.76 real part in float out complex gnuradio-3.7.2.1/gr-filter/grc/filter_pfb_channelizer.xml0000664000175000017500000000237212207440367023223 0ustar jcorganjcorgan Polyphase Channelizer pfb_channelizer_ccf from gnuradio.filter import pfb from gnuradio.filter import firdes pfb.channelizer_ccf( $nchans, $taps, $osr, $atten) self.$(id).set_channel_map($ch_map) set_channel_map($ch_map) Channels nchans int Taps taps real_vector Over Sample Ratio osr 1.0 real Attenuation atten 100 real Channel Map ch_map [] int_vector in complex out complex $nchans gnuradio-3.7.2.1/gr-filter/grc/filter_iir_filter_ffd.xml0000664000175000017500000000147112207440367023040 0ustar jcorganjcorgan IIR Filter iir_filter_ffd from gnuradio import filter filter.iir_filter_ffd($fftaps, $fbtaps, $oldstyle) set_taps($fftaps, $fbtaps) Feed-forward Taps fftaps real_vector Feedback Taps fbtaps real_vector Old Style of Taps oldstyle True bool part in float out float gnuradio-3.7.2.1/gr-filter/grc/filter_freq_xlating_fir_filter_xxx.xml0000664000175000017500000000424712207440367025674 0ustar jcorganjcorgan Frequency Xlating FIR Filter freq_xlating_fir_filter_xxx from gnuradio import filter from gnuradio.filter import firdes filter.freq_xlating_fir_filter_$(type)($decim, $taps, $center_freq, $samp_rate) set_taps($taps) set_center_freq($center_freq) Type type enum Decimation decim 1 int Taps taps $type.taps Center Frequency center_freq 0 real Sample Rate samp_rate samp_rate real in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_high_pass_filter.xml0000664000175000017500000000574712207440367023415 0ustar jcorganjcorgan High Pass Filter high_pass_filter from gnuradio import filter from gnuradio.filter import firdes filter.$(type)(#if str($type).startswith('interp') then $interp else $decim#, firdes.high_pass( $gain, $samp_rate, $cutoff_freq, $width, $win, $beta)) set_taps(firdes.high_pass($gain, $samp_rate, $cutoff_freq, $width, $win, $beta)) FIR Type type enum Decimation decim 1 int #if str($type).startswith('interp') then 'all' else 'none'# Interpolation interp 1 int #if str($type).startswith('interp') then 'none' else 'all'# Gain gain 1 real Sample Rate samp_rate samp_rate real Cutoff Freq cutoff_freq real Transition Width width real Window win firdes.WIN_HAMMING int Beta beta 6.76 real in $type.input out $type.output This filter is a convenience wrapper for an fir filter and a firdes taps generating function. Sample rate, cutoff frequency, and transition width are in Hertz. The beta paramater only applies to the Kaiser window. gnuradio-3.7.2.1/gr-filter/grc/filter_pfb_decimator.xml0000664000175000017500000000175012245466767022705 0ustar jcorganjcorgan Polyphase Decimator pfb_decimator_ccf from gnuradio.filter import pfb from gnuradio.filter import firdes pfb.decimator_ccf( $decim, $taps, $channel, $atten) set_taps($taps) Decimation decim int Taps taps real_vector Output Channel channel 0 int Stop-band Attenuation atten 100 real in complex out complex gnuradio-3.7.2.1/gr-filter/grc/filter_pfb_synthesizer.xml0000664000175000017500000000232012207440367023301 0ustar jcorganjcorgan Polyphase Synthesizer pfb_synthesizer_ccf from gnuradio import filter from gnuradio.filter import firdes filter.pfb_synthesizer_ccf( $numchans, $taps, $twox) self.$(id).set_channel_map($ch_map) set_taps($taps) set_channel_map($ch_map) Channels numchans 2 int Connections connections 2 int Taps taps real_vector 2x Sample Rate twox False bool Channel Map ch_map [] int_vector in complex $connections out complex gnuradio-3.7.2.1/gr-filter/grc/filter_dc_blocker_xx.xml0000664000175000017500000000202512207440367022673 0ustar jcorganjcorgan DC Blocker dc_blocker_xx from gnuradio import filter filter.dc_blocker_$(type)($length, $long_form) Type type enum Length length 32 int Long Form long_form True bool in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_low_pass_filter.xml0000664000175000017500000000574212207440367023272 0ustar jcorganjcorgan Low Pass Filter low_pass_filter from gnuradio import filter from gnuradio.filter import firdes filter.$(type)(#if str($type).startswith('interp') then $interp else $decim#, firdes.low_pass( $gain, $samp_rate, $cutoff_freq, $width, $win, $beta)) set_taps(firdes.low_pass($gain, $samp_rate, $cutoff_freq, $width, $win, $beta)) FIR Type type enum Decimation decim 1 int #if str($type).startswith('interp') then 'all' else 'none'# Interpolation interp 1 int #if str($type).startswith('interp') then 'none' else 'all'# Gain gain 1 real Sample Rate samp_rate samp_rate real Cutoff Freq cutoff_freq real Transition Width width real Window win firdes.WIN_HAMMING int Beta beta 6.76 real in $type.input out $type.output This filter is a convenience wrapper for an fir filter and a firdes taps generating function. Sample rate, cutoff frequency, and transition width are in Hertz. The beta paramater only applies to the Kaiser window. gnuradio-3.7.2.1/gr-filter/grc/filter_rational_resampler_base_xxx.xml0000664000175000017500000000372712207440367025663 0ustar jcorganjcorgan Rational Resampler Base rational_resampler_base_xxx from gnuradio import filter from gnuradio.filter import firdes filter.rational_resampler_base_$(type)($interp, $decim, $taps) set_taps($taps) Type type enum Interpolation interp 1 int Decimation decim 1 int Taps taps $type.taps in $type.input out $type.output gnuradio-3.7.2.1/gr-filter/grc/filter_pfb_interpolator.xml0000664000175000017500000000156612207440367023447 0ustar jcorganjcorgan Polyphase Interpolator pfb_interpolator_ccf from gnuradio.filter import pfb from gnuradio.filter import firdes pfb.interpolator_ccf( $interp, $taps, $atten) set_taps($taps) Interpolation interp int Taps taps real_vector Attenuation atten 100 real in complex out complex gnuradio-3.7.2.1/gr-filter/doc/0000755000175000017500000000000012245466767016005 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/doc/CMakeLists.txt0000644000175000017500000000152012021532024020507 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.filter DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-filter/doc/README.filter0000644000175000017500000000062112021532024020114 0ustar jcorganjcorganThis is the gr-filter package. It contains signal processing blocks to perform filtering operations. The Python namespace is in gnuradio.filter, which would be normally imported as: from gnuradio import filter See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(filter) gnuradio-3.7.2.1/gr-filter/doc/filter.dox0000664000175000017500000002325112245466767020013 0ustar jcorganjcorgan/*! \page page_filter Filter Signal Processing Blocks \section Introduction This is the gr-filter package. It contains signal processing blocks to perform filtering operations. The Python namespace is in gnuradio.filter, which would be normally imported as: \code from gnuradio import filter \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(filter) \endcode \section Dependencies The filter blocks depend on \ref page_fft. \section Usage There are many filter blocks and kernels in GNU Radio. Filter blocks are standard GNU Radio blocks that fit into a flowgraph. Filter kernels are the guts of the filtering operations that are C++ classes which are designed to be useful within other blocks. The filtering module also comes with a number of filter design tools. \subsection filter_kernels Kernels \li FIR filters (see fir_filter.h): filters that compute finite impulse response (FIR) filtering in the time domain. \li FFT filters (see fft_filter.h): filters that compute FIR filtering in the frequency domain (i.e., fast convolution). \li FIR filters with internal buffers (see fir_filter_with_buffer.h): filters that perform time-domain FIR filtering but keep an internal buffer so the input vectors are not affected or used. This is not as efficient as the normal FIR filters but can be necessary under certain conditions. \li IIR filters (see iir_filter.h): filters that compute infinite impulse response (IIR) filtering. \li Single-pole IIR filters (see single_pole_iir.h): a special case of an IIR filter with a single pole (also known as a moving average filter). \li Adaptive FIR filters (see adaptive_fir.h): FIR filters that define an \b error and \b update_tap virtual interface to create filters that update the taps based on some criteria. \sa gr::digital::lms_dd_equalizer_cc, gr::digital::cma_equalizer_cc \li PFB arbitrary resampler (see pfb_arb_resampler.h): performs arbitrary resampling (i.e., using any real number) using the polyphase filterbank method. \sa \ref pfb_arb_resampl \li Polyphase filterbank (see polyphase_filterbank.h): a set of base classes with standard functions for building many polyphase filterbank blocks. \subsection filter_blocks Blocks
  • FIR Filters
    • gr::filter::fir_filter_ccc
    • gr::filter::fir_filter_ccf
    • gr::filter::fir_filter_fcc
    • gr::filter::fir_filter_fff
    • gr::filter::fir_filter_fsf
    • gr::filter::fir_filter_scc
  • FFT Filters
    • gr::filter::fft_filter_ccc
    • gr::filter::fft_filter_fff
  • IIR Filters
    • gr::filter::iir_filter_ffd
  • Single-Pole IIR Filters
    • gr::filter::single_pole_iir_filter_cc
    • gr::filter::single_pole_iir_filter_ff
  • Adaptive FIR Filters
    • gr::filter::adaptive_fir_ccc
    • gr::filter::adaptive_fir_ccf
  • Polyphase Filterbanks
    • gr::filter::pfb_arb_resampler_ccf
    • gr::filter::pfb_arb_resampler_fff
    • gr::filter::pfb_channelizer_ccf
    • gr::filter::pfb_decimator_ccf
    • gr::filter::pfb_interpolator_ccf
    • gr::filter::pfb_synthesizer_ccf
    • gr::digital::pfb_clock_sync_ccf
    • gr::digital::pfb_clock_sync_fff
\subsection filter_design_tools Design Tools To help build filters, GNU Radio includes a number of design tools. These tools build standard filters like low pass, high pass, band pass, etc. There are two main flavors of the filter design tools: \li Windowed filters (see firdes.h): filters defined as sinc functions and a window function. \li Equiripple filters (see optfir.py): filters defined by using the Parks-McClellen algorithm given a set of conditions. The GNU Radio filter library also exports the Parks-McClellen algorithm in both C++ and Python as gr::filter::pm_remez. The firdes.h filter contains functions to design the following types of filters (see gr::filter::firdes): \li gr::filter::firdes::low_pass: defines a low pass filter based on a pass band bandwidth and transition bandwidth. \li gr::filter::firdes::low_pass_2: same as the low pass filter with added argument to set the out-of-band attenuation (in dB). \li gr::filter::firdes::high_pass: defines a high pass filter based on a pass band bandwidth and transition bandwidth. \li gr::filter::firdes::high_pass_2: same as the high pass filter with added argument to set the out-of-band attenuation (in dB). \li gr::filter::firdes::band_pass: defines a band pass filter based on the pass band start and stop frequencies and transition bandwidth. \li gr::filter::firdes::band_pass_2: same as the band pass filter with added argument to set the out-of-band attenuation (in dB). \li gr::filter::firdes::complex_band_pass: defines a complex band pass filter based on the pass band start and stop frequencies and transition bandwidth. Returns complex taps for one-sided spectrum. \li gr::filter::firdes::complex_band_pass_2: same as the complex band pass filter with added argument to set the out-of-band attenuation (in dB). \li gr::filter::firdes::band_reject: defines a band reject filter based on a stop band bandwidth and transition bandwidth. \li gr::filter::firdes::band_reject_2: same as the band reject filter with added argument to set the out-of-band attenuation (in dB). \li gr::filter::firdes::hilbert: creates a Hilbert transform filter. \li gr::filter::firdes::root_raised_cosine: creates a root raised cosine (RRC) pulse shaping filter. \li gr::filter::firdes::guassian: creates a Gaussian pulse shaping filter. \li gr::filter::firdes::window: Returns the window function for the given window at the given number of taps. The optfir.py contains a set of Python-only functions that define equiripple filters using the Parks-McClellen algorithm: \li low_pass: defines a low pass filter based off the end of the pass band, the start of the stop band, the pass band ripple, and the stop band attenuation. \li band_pass: defines a band pass filter based the end of the first stop band, the start of the pass band, the end of the pass band, the start of the second stop band, the pass band ripple, and the stop band attenuation. \li complex_band_pass: defines a band pass filter based the end of the first stop band, the start of the pass band, the end of the pass band, the start of the second stop band, the pass band ripple, and the stop band attenuation. Returns complex taps for one-sided spectrum. \li band_reject: defines a band reject filter based the end of the first pass band, the start of the stop band, the end of the stop band, the start of the second pass band, the pass band ripple, and the stop band attenuation. Unlike the firdes.h band_reject filter, this filter does not have to be symmetrical. \li high_pass defines a high pass filter based off the end of the stop band, the start of the pass band, the pass band ripple, and the stop band attenuation. \subsection filter_design Filter Design GUI Tool GNU Radio has a filter design GUI tool called \b gr_filter_design. This tool allows us to build filters using the filter design methods above and look at the results immediately. The frequency and time domain along with other aspects of the filter like the phase profile, group delay, the filter taps as a list, impulse response, and step response. Also displayed is a pole-zero plot. The filter design tool is useful to provide immediate feedback on the shape, behavior, and complexity of the filter from the design parameters. The tool also includes a \b save capability to save the taps and parameters in a simple comma-separated value (CSV) format. Furthermore, the filter design program can be called and used for interaction within a Python program. There are a few ways in which we can interact with the tool programmatically. The tool can be simply launched from Python, and when closed, it returns an object filled with the filter parameters and taps. An example of this can be found in \b examples/filter/gr_filtdes_api.py. \code filtobj = filter_design.launch(sys.argv) print "Filter Count:", filtobj.get_filtercount() print "Filter type:", filtobj.get_restype() print "Filter params", filtobj.get_params() print "Filter Coefficients", filtobj.get_taps() \endcode Another way of using the filter design tool is to give it a callback function that is called whenever the "Design" button is pressed in the GUI. The following code comes from the \b examples/filter/gr_filtdes_callback.py example. Whenever "Design" is pressed, the "print_params" function is called with the filter parameters and taps inside of the "filtobj" object. \code def print_params(filtobj): print "Filter Count:", filtobj.get_filtercount() print "Filter type:", filtobj.get_restype() print "Filter params", filtobj.get_params() print "Filter Coefficients", filtobj.get_taps() app = Qt.QApplication(sys.argv) main_win = filter_design.launch(sys.argv, print_params) main_win.show() app.exec_() \endcode Changing one line in the above code allows us to set restrictions on what type of filter the design tool can build. This concept is shown in \b examples/filter/gr_filtdes_restrict.py. Here, the filter type is restricted to using IIR filters. \code main_win = filter_design.launch(sys.argv, callback = print_params, restype = "iir") \endcode An application running a full GNU Radio flowgraph can actually launch the filter design tool and have it update a filter while the system is running. This concept is an extension of the callback function and is shown in the example \b examples/filter/gr_filtdes_live_upd.py. The code is not shown here as the full code is quite long. */ gnuradio-3.7.2.1/gr-filter/python/0000775000175000017500000000000012207440367016545 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/python/filter/0000775000175000017500000000000012245466767020050 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/python/filter/qa_hilbert.py0000775000175000017500000000425012221050153022504 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.sin(2.*math.pi*freq*x), t) return y def fir_filter(x, taps): y = [] x2 = (len(taps)-1)*[0,] + x delay = (len(taps)-1)/2 for i in range(len(x)): yi = 0 for j in range(len(taps)): yi += taps[len(taps)-1-j] * x2[i+j] y.append(complex(x2[i+delay], yi)) return y class test_hilbert(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_hilbert(self): tb = self.tb ntaps = 51 sampling_freq = 100 N = int(ntaps + sampling_freq * 0.10) data = sig_source_f(sampling_freq, sampling_freq * 0.10, 1.0, N) src1 = blocks.vector_source_f(data) taps = filter.firdes.hilbert(ntaps, filter.firdes.WIN_HAMMING) expected_result = fir_filter(data, taps) hilb = filter.hilbert_fc(ntaps) dst1 = blocks.vector_sink_c() tb.connect(src1, hilb) tb.connect(hilb, dst1) tb.run() dst_data = dst1.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) if __name__ == '__main__': gr_unittest.run(test_hilbert, "test_hilbert.xml") gnuradio-3.7.2.1/gr-filter/python/filter/CMakeLists.txt0000664000175000017500000000327412207440367022600 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py filterbank.py optfir.py pfb.py rational_resampler.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/filter COMPONENT "filter_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-filter/python/filter/qa_adaptive_fir_filter.py0000775000175000017500000000654612245466767025123 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from gnuradio import gr, gr_unittest, filter, blocks def fir_filter(x, taps, decim=1): y = [] x2 = (len(taps)-1)*[0,] + x for i in range(0, len(x), decim): yi = 0 for j in range(len(taps)): yi += taps[len(taps)-1-j] * x2[i+j] y.append(yi) return y class test_adaptive_filter(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_adaptive_fir_filter_ccf_001(self): decim = 1 taps = 20*[0.5, 0.5] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.adaptive_fir_ccf("test", decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_adaptive_fir_filter_ccf_002(self): decim = 4 taps = 20*[0.5, 0.5] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.adaptive_fir_ccf("test", decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_adaptive_fir_filter_ccc_001(self): decim = 1 taps = 20*[0.5+1j, 0.5+1j] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.adaptive_fir_ccc("test", decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_adaptive_fir_filter_ccc_002(self): decim = 4 taps = 20*[0.5+1j, 0.5+1j] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.adaptive_fir_ccc("test", decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_adaptive_filter, "test_adaptive_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_pfb_arb_resampler.py0000775000175000017500000001020012207440367024526 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y def sig_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.sin(2.*math.pi*freq*x), t) return y class test_pfb_arb_resampler(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_fff_000(self): N = 500 # number of samples to use fs = 5000.0 # baseband sampling rate rrate = 2.3421 # resampling rate nfilts = 32 taps = filter.firdes.low_pass_2(nfilts, nfilts*fs, fs/2, fs/10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS) freq = 121.213 data = sig_source_f(fs, freq, 1, N) signal = blocks.vector_source_f(data) pfb = filter.pfb_arb_resampler_fff(rrate, taps, nfilts) snk = blocks.vector_sink_f() self.tb.connect(signal, pfb, snk) self.tb.run() Ntest = 50 L = len(snk.data()) # Get group delay and estimate of phase offset from the filter itself. delay = pfb.group_delay() phase = pfb.phase_offset(freq, fs) # Create a timeline offset by the filter's group delay t = map(lambda x: float(x)/(fs*rrate), xrange(delay, L+delay)) # Data of the sinusoid at frequency freq with the delay and phase offset. expected_data = map(lambda x: math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 2) def test_ccf_000(self): N = 5000 # number of samples to use fs = 5000.0 # baseband sampling rate rrate = 2.4321 # resampling rate nfilts = 32 taps = filter.firdes.low_pass_2(nfilts, nfilts*fs, fs/2, fs/10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS) freq = 211.123 data = sig_source_c(fs, freq, 1, N) signal = blocks.vector_source_c(data) pfb = filter.pfb_arb_resampler_ccf(rrate, taps, nfilts) snk = blocks.vector_sink_c() self.tb.connect(signal, pfb, snk) self.tb.run() Ntest = 50 L = len(snk.data()) # Get group delay and estimate of phase offset from the filter itself. delay = pfb.group_delay() phase = pfb.phase_offset(freq, fs) # Create a timeline offset by the filter's group delay t = map(lambda x: float(x)/(fs*rrate), xrange(delay, L+delay)) # Data of the sinusoid at frequency freq with the delay and phase offset. expected_data = map(lambda x: math.cos(2.*math.pi*freq*x+phase) + \ 1j*math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 2) if __name__ == '__main__': gr_unittest.run(test_pfb_arb_resampler, "test_pfb_arb_resampler.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_filter_delay_fc.py0000775000175000017500000001071512221050153024171 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sin_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.sin(2.*math.pi*freq*x), t) return y def cos_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x), t) return y def fir_filter(x, taps, delay): y = [] x2 = (len(taps)-1)*[0,] + x for i in range(len(x)): yi = 0 for j in range(len(taps)): yi += taps[len(taps)-1-j] * x2[i+j] y.append(complex(x2[i+delay], yi)) return y def fir_filter2(x1, x2, taps, delay): y = [] x1_2 = (len(taps)-1)*[0,] + x1 x2_2 = (len(taps)-1)*[0,] + x2 for i in range(len(x2)): yi = 0 for j in range(len(taps)): yi += taps[len(taps)-1-j] * x2_2[i+j] y.append(complex(x1_2[i+delay], yi)) return y class test_filter_delay_fc(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001_filter_delay_one_input(self): tb = self.tb sampling_freq = 100 ntaps = 51 N = int(ntaps + sampling_freq * 0.10) data = sin_source_f(sampling_freq, sampling_freq * 0.10, 1.0, N) src1 = blocks.vector_source_f(data) dst2 = blocks.vector_sink_c() # calculate taps taps = filter.firdes.hilbert(ntaps, filter.firdes.WIN_HAMMING) hd = filter.filter_delay_fc(taps) expected_result = fir_filter(data, taps, (ntaps-1)/2) tb.connect(src1, hd) tb.connect(hd, dst2) tb.run() # get output result_data = dst2.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) def test_002_filter_delay_two_inputs(self): # giving the same signal to both the inputs should fetch the same results # as above tb = self.tb sampling_freq = 100 ntaps = 51 N = int(ntaps + sampling_freq * 0.10) data = sin_source_f(sampling_freq, sampling_freq * 0.10, 1.0, N) src1 = blocks.vector_source_f(data) dst2 = blocks.vector_sink_c() # calculate taps taps = filter.firdes.hilbert(ntaps, filter.firdes.WIN_HAMMING) hd = filter.filter_delay_fc(taps) expected_result = fir_filter2(data, data, taps, (ntaps-1)/2) tb.connect(src1, (hd,0)) tb.connect(src1, (hd,1)) tb.connect(hd,dst2) tb.run() # get output result_data = dst2.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) def test_003_filter_delay_two_inputs(self): # give two different inputs tb = self.tb sampling_freq = 100 ntaps = 51 N = int(ntaps + sampling_freq * 0.10) data1 = sin_source_f(sampling_freq, sampling_freq * 0.10, 1.0, N) data2 = cos_source_f(sampling_freq, sampling_freq * 0.10, 1.0, N) src1 = blocks.vector_source_f(data1) src2 = blocks.vector_source_f(data2) taps = filter.firdes.hilbert(ntaps, filter.firdes.WIN_HAMMING) hd = filter.filter_delay_fc(taps) expected_result = fir_filter2(data1, data2, taps, (ntaps-1)/2) dst2 = blocks.vector_sink_c() tb.connect(src1, (hd,0)) tb.connect(src2, (hd,1)) tb.connect(hd, dst2) tb.run() # get output result_data = dst2.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_filter_delay_fc, "test_filter_delay_fc.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_rational_resampler.py0000775000175000017500000002115412207440367024756 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math import random import sys def random_floats(n): r = [] for x in xrange(n): # r.append(float(random.randint(-32768, 32768))) r.append(float(random.random())) return tuple(r) def reference_dec_filter(src_data, decim, taps): tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.fir_filter_fff(decim, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() tb = None return result_data def reference_interp_filter(src_data, interp, taps): tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.interp_fir_filter_fff(interp, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() tb = None return result_data def reference_interp_dec_filter(src_data, interp, decim, taps): tb = gr.top_block() src = blocks.vector_source_f(src_data) up = filter.interp_fir_filter_fff(interp, (1,)) dn = filter.fir_filter_fff(decim, taps) dst = blocks.vector_sink_f() tb.connect(src, up, dn, dst) tb.run() result_data = dst.data() tb = None return result_data class test_rational_resampler (gr_unittest.TestCase): def setUp(self): random.seed(0) def tearDown(self): pass def test_000_1_to_1(self): taps = (-4, 5) src_data = (234, -4, 23, -56, 45, 98, -23, -7) xr = (1186, -112, 339, -460, -167, 582) expected_result = tuple([float(x) for x in xr]) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(1, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_001_interp(self): taps = [1, 10, 100, 1000, 10000] src_data = (0, 2, 3, 5, 7, 11, 13, 17) interpolation = 3 xr = (0,2,20,200,2003,20030, 300,3005,30050, 500,5007,50070, 700,7011,70110, 1100,11013,110130, 1300,13017,130170, 1700.0,17000.0,170000.0) expected_result = tuple([float(x) for x in xr]) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(interpolation, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_002_interp(self): taps = random_floats(31) src_data = random_floats(10000) interpolation = 3 expected_result = reference_interp_filter(src_data, interpolation, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(interpolation, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 1000 offset = len(taps)-1 self.assertEqual(expected_result[offset:offset+N], result_data[0:N]) def xtest_003_interp(self): taps = random_floats(9) src_data = random_floats(10000) decimation = 3 expected_result = reference_dec_filter(src_data, decimation, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(1, decimation, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 10 offset = 10#len(taps)-1 print expected_result[100+offset:100+offset+N] print result_data[100:100+N] #self.assertEqual(expected_result[offset:offset+N], result_data[0:N]) # FIXME disabled. Triggers hang on SuSE 10.0 def xtest_004_decim_random_vals(self): MAX_TAPS = 9 MAX_DECIM = 7 OUTPUT_LEN = 9 random.seed(0) # we want reproducibility for ntaps in xrange(1, MAX_TAPS + 1): for decim in xrange(1, MAX_DECIM+1): for ilen in xrange(ntaps + decim, ntaps + OUTPUT_LEN*decim): src_data = random_floats(ilen) taps = random_floats(ntaps) expected_result = reference_dec_filter(src_data, decim, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(1, decim, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() tb = None result_data = dst.data() L1 = len(result_data) L2 = len(expected_result) L = min(L1, L2) if False: sys.stderr.write('delta = %2d: ntaps = %d decim = %d ilen = %d\n' % (L2 - L1, ntaps, decim, ilen)) sys.stderr.write(' len(result_data) = %d len(expected_result) = %d\n' % (len(result_data), len(expected_result))) self.assertEqual(expected_result[0:L], result_data[0:L]) # FIXME disabled. Triggers hang on SuSE 10.0 def xtest_005_interp_random_vals(self): MAX_TAPS = 9 MAX_INTERP = 7 INPUT_LEN = 9 random.seed(0) # we want reproducibility for ntaps in xrange(1, MAX_TAPS + 1): for interp in xrange(1, MAX_INTERP+1): for ilen in xrange(ntaps, ntaps + INPUT_LEN): src_data = random_floats(ilen) taps = random_floats(ntaps) expected_result = reference_interp_filter(src_data, interp, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(interp, 1, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() tb = None result_data = dst.data() L1 = len(result_data) L2 = len(expected_result) L = min(L1, L2) #if True or abs(L1-L2) > 1: if False: sys.stderr.write('delta = %2d: ntaps = %d interp = %d ilen = %d\n' % (L2 - L1, ntaps, interp, ilen)) #sys.stderr.write(' len(result_data) = %d len(expected_result) = %d\n' % # (len(result_data), len(expected_result))) #self.assertEqual(expected_result[0:L], result_data[0:L]) # FIXME check first ntaps+1 answers self.assertEqual(expected_result[ntaps+1:L], result_data[ntaps+1:L]) def test_006_interp_decim(self): taps = random_floats(31) src_data = random_floats(10000) interp = 3 decimation = 2 expected_result = reference_interp_dec_filter(src_data, interp, decimation, taps) tb = gr.top_block() src = blocks.vector_source_f(src_data) op = filter.rational_resampler_base_fff(interp, decimation, taps) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() result_data = dst.data() N = 1000 offset = len(taps)/2 self.assertFloatTuplesAlmostEqual(expected_result[offset:offset+N], result_data[0:N], 5) if __name__ == '__main__': # FIXME: Disabled, see ticket:210 gr_unittest.run(test_rational_resampler, "test_rational_resampler.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_fir_filter.py0000775000175000017500000001533612221050153023207 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from gnuradio import gr, gr_unittest, filter, blocks def fir_filter(x, taps, decim=1): y = [] x2 = (len(taps)-1)*[0,] + x for i in range(0, len(x), decim): yi = 0 for j in range(len(taps)): yi += taps[len(taps)-1-j] * x2[i+j] y.append(yi) return y class test_filter(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_fir_filter_fff_001(self): decim = 1 taps = 20*[0.5, 0.5] src_data = 40*[1, 2, 3, 4] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_f(src_data) op = filter.fir_filter_fff(decim, taps) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fff_002(self): decim = 4 taps = 20*[0.5, 0.5] src_data = 40*[1, 2, 3, 4] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_f(src_data) op = filter.fir_filter_fff(decim, taps) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccf_001(self): decim = 1 taps = 20*[0.5, 0.5] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.fir_filter_ccf(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccf_002(self): decim = 4 taps = 20*[0.5, 0.5] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.fir_filter_ccf(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccc_001(self): decim = 1 taps = 20*[0.5+1j, 0.5+1j] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.fir_filter_ccc(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccc_002(self): decim = 1 taps = filter.firdes.low_pass(1, 1, 0.1, 0.01) src_data = 10*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.fir_filter_ccc(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccc_003(self): decim = 4 taps = 20*[0.5+1j, 0.5+1j] src_data = 40*[1+1j, 2+2j, 3+3j, 4+4j] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_c(src_data) op = filter.fir_filter_ccc(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_scc_001(self): decim = 1 taps = 20*[0.5+1j, 0.5+1j] src_data = 40*[1, 2, 3, 4] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_s(src_data) op = filter.fir_filter_scc(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_scc_002(self): decim = 4 taps = 20*[0.5+1j, 0.5+1j] src_data = 40*[1, 2, 3, 4] expected_data = fir_filter(src_data, taps, decim) src = blocks.vector_source_s(src_data) op = filter.fir_filter_scc(decim, taps) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fsf_001(self): decim = 1 taps = 20*[0.5, 0.5] src_data = 40*[1, 2, 3, 4] expected_data = fir_filter(src_data, taps, decim) expected_data = [int(e) for e in expected_data] src = blocks.vector_source_f(src_data) op = filter.fir_filter_fsf(decim, taps) dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fsf_002(self): decim = 4 taps = 20*[0.5, 0.5] src_data = 40*[1, 2, 3, 4] expected_data = fir_filter(src_data, taps, decim) expected_data = [int(e) for e in expected_data] src = blocks.vector_source_f(src_data) op = filter.fir_filter_fsf(decim, taps) dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_filter, "test_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_pfb_channelizer.py0000775000175000017500000001105612207440367024224 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y class test_pfb_channelizer(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): N = 1000 # number of samples to use M = 5 # Number of channels to channelize fs = 5000 # baseband sampling rate ifs = M*fs # input samp rate to channelizer taps = filter.firdes.low_pass_2(1, ifs, fs/2, fs/10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS) signals = list() add = blocks.add_cc() freqs = [-230., 121., 110., -513., 203.] for i in xrange(len(freqs)): f = freqs[i] + (M/2-M+i+1)*fs data = sig_source_c(ifs, f, 1, N) signals.append(blocks.vector_source_c(data)) self.tb.connect(signals[i], (add,i)) s2ss = blocks.stream_to_streams(gr.sizeof_gr_complex, M) pfb = filter.pfb_channelizer_ccf(M, taps, 1) self.tb.connect(add, s2ss) snks = list() for i in xrange(M): snks.append(blocks.vector_sink_c()) self.tb.connect((s2ss,i), (pfb,i)) self.tb.connect((pfb, i), snks[i]) self.tb.run() Ntest = 50 L = len(snks[0].data()) # Adjusted phase rotations for data p0 = -2*math.pi * 0 / M p1 = -2*math.pi * 1 / M p2 = -2*math.pi * 2 / M p3 = -2*math.pi * 3 / M p4 = -2*math.pi * 4 / M # Filter delay is the normal delay of each arm tpf = math.ceil(len(taps) / float(M)) delay = -(tpf - 1.0) / 2.0 delay = int(delay) # Create a time scale that's delayed to match the filter delay t = map(lambda x: float(x)/fs, xrange(delay, L+delay)) # Create known data as complex sinusoids at the different baseband freqs # the different channel numbering is due to channelizer output order. expected0_data = map(lambda x: math.cos(2.*math.pi*freqs[2]*x+p0) + \ 1j*math.sin(2.*math.pi*freqs[2]*x+p0), t) expected1_data = map(lambda x: math.cos(2.*math.pi*freqs[3]*x+p1) + \ 1j*math.sin(2.*math.pi*freqs[3]*x+p1), t) expected2_data = map(lambda x: math.cos(2.*math.pi*freqs[4]*x+p2) + \ 1j*math.sin(2.*math.pi*freqs[4]*x+p2), t) expected3_data = map(lambda x: math.cos(2.*math.pi*freqs[0]*x+p3) + \ 1j*math.sin(2.*math.pi*freqs[0]*x+p3), t) expected4_data = map(lambda x: math.cos(2.*math.pi*freqs[1]*x+p4) + \ 1j*math.sin(2.*math.pi*freqs[1]*x+p4), t) dst0_data = snks[0].data() dst1_data = snks[1].data() dst2_data = snks[2].data() dst3_data = snks[3].data() dst4_data = snks[4].data() self.assertComplexTuplesAlmostEqual(expected0_data[-Ntest:], dst0_data[-Ntest:], 3) self.assertComplexTuplesAlmostEqual(expected1_data[-Ntest:], dst1_data[-Ntest:], 3) self.assertComplexTuplesAlmostEqual(expected2_data[-Ntest:], dst2_data[-Ntest:], 3) self.assertComplexTuplesAlmostEqual(expected3_data[-Ntest:], dst3_data[-Ntest:], 3) self.assertComplexTuplesAlmostEqual(expected4_data[-Ntest:], dst4_data[-Ntest:], 3) if __name__ == '__main__': gr_unittest.run(test_pfb_channelizer, "test_pfb_channelizer.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_pfb_interpolator.py0000775000175000017500000000545312207440367024450 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y class test_pfb_interpolator(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): N = 1000 # number of samples to use M = 5 # Number of channels fs = 1000 # baseband sampling rate ifs = M*fs # input samp rate to decimator taps = filter.firdes.low_pass_2(M, ifs, fs/2, fs/10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS) freq = 123.456 data = sig_source_c(fs, freq, 1, N) signal = blocks.vector_source_c(data) pfb = filter.pfb_interpolator_ccf(M, taps) snk = blocks.vector_sink_c() self.tb.connect(signal, pfb) self.tb.connect(pfb, snk) self.tb.run() Ntest = 50 L = len(snk.data()) # Can only get channel 0 out; no phase rotation phase = 0 # Calculate the filter delay delay = -(len(taps) - 1) / 2.0 - (M-1) delay = int(delay) # Create a time scale that's delayed to match the filter delay t = map(lambda x: float(x)/ifs, xrange(delay, L+delay)) # Create known data as complex sinusoids for the baseband freq # of the extracted channel is due to decimator output order. expected_data = map(lambda x: math.cos(2.*math.pi*freq*x+phase) + \ 1j*math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4) if __name__ == '__main__': gr_unittest.run(test_pfb_interpolator, "test_pfb_interpolator.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_firdes.py0000775000175000017500000002432412245466767022367 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter import sys class test_firdes(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_low_pass(self): known_taps = (0.0030193300917744637, -0.004960992839187384, 0.006678304169327021, -1.132049690556083e-17, -0.0251916591078043, 0.07206480950117111, -0.13062666356563568, 0.18007083237171173, 0.7978920936584473, 0.18007083237171173, -0.13062666356563568, 0.07206480950117111, -0.0251916591078043, -1.132049690556083e-17, 0.006678304169327021, -0.004960992839187384, 0.0030193300917744637) new_taps = filter.firdes.low_pass(1, 1, 0.4, 0.2) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_low_pass_2(self): known_taps = (0.0024871660862118006, -4.403502608370943e-18, -0.014456653036177158, 0.0543283149600029, -0.116202212870121, 0.17504146695137024, 0.7976038455963135, 0.17504146695137024, -0.116202212870121, 0.0543283149600029, -0.014456653036177158, -4.403502608370943e-18, 0.0024871660862118006) new_taps = filter.firdes.low_pass_2(1, 1, 0.4, 0.2, 60) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_high_pass(self): known_taps = (-0.003062003292143345, 0.005031108390539885, -0.0067726909182965755, 1.1480492661182674e-17, 0.025547700002789497, -0.0730833187699318, 0.13247284293174744, -0.18261581659317017, 0.20229223370552063, -0.18261581659317017, 0.13247284293174744, -0.0730833187699318, 0.025547700002789497, 1.1480492661182674e-17, -0.0067726909182965755, 0.005031108390539885, -0.003062003292143345) new_taps = filter.firdes.high_pass(1, 1, 0.4, 0.2) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_high_pass_2(self): known_taps = (-0.0027197482995688915, 4.815287179370254e-18, 0.01580853760242462, -0.05940871313214302, 0.1270686239004135, -0.1914101094007492, 0.21804752945899963, -0.1914101094007492, 0.1270686239004135, -0.05940871313214302, 0.01580853760242462, 4.815287179370254e-18, -0.0027197482995688915) new_taps = filter.firdes.high_pass_2(1, 1, 0.4, 0.2, 60) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_band_pass(self): known_taps = (0.004961997736245394, -0.008152946829795837, -0.004192151129245758, -5.749020235348687e-18, 0.01581347920000553, 0.11843203753232956, -0.21467317640781403, -0.11303528398275375, 0.40520283579826355, -0.11303528398275375, -0.21467317640781403, 0.11843203753232956, 0.01581347920000553, -5.749020235348687e-18, -0.004192151129245758, -0.008152946829795837, 0.004961997736245394) new_taps = filter.firdes.band_pass(1, 1, 0.2, 0.4, 0.2) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_band_pass_2(self): known_taps = (-0.001676854444667697, -2.4018533253972557e-18, 0.009746716357767582, 0.09589414298534393, -0.20510689914226532, -0.11801345646381378, 0.4350462853908539, -0.11801345646381378, -0.20510689914226532, 0.09589414298534393, 0.009746716357767582, -2.4018533253972557e-18, -0.001676854444667697) new_taps = filter.firdes.band_pass_2(1, 1, 0.2, 0.4, 0.2, 60) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_complex_band_pass(self): known_taps = ((0.0024772135075181723+0.0017997993854805827j), (-0.004070250317454338+0.002957213670015335j), (-0.0020928815938532352-0.006441210396587849j), (-2.8701231652956686e-18+2.805614574993832e-24j), (0.007894645445048809-0.024297315627336502j), (0.05912570655345917+0.04295721650123596j), (-0.10717268288135529+0.07786571979522705j), (-0.0564316064119339-0.17367789149284363j), (0.20229223370552063-2.4115112751132983e-07j), (-0.05643119290471077+0.17367802560329437j), (-0.10717286914587021-0.07786546647548676j), (0.05912560224533081-0.0429573580622673j), (0.007894691079854965+0.024297300726175308j), (-2.8701231652956686e-18+2.6687109203363464e-24j), (-0.0020928694866597652+0.006441214121878147j), (-0.004070255905389786-0.0029572059866040945j), (0.0024772100150585175-0.0017998040420934558j)) new_taps = filter.firdes.complex_band_pass(1, 1, 0.2, 0.4, 0.2) self.assertComplexTuplesAlmostEqual(known_taps, new_taps, 5) def test_complex_band_pass_2(self): known_taps = ((-0.0008404505206272006-0.0025866336654871702j), (-1.2038217948425635e-18+1.1767648157397848e-24j), (0.0048850891180336475-0.015034818090498447j), (0.048062704503536224+0.03491950035095215j), (-0.10280057787895203+0.07468919456005096j), (-0.05914920195937157-0.18204176425933838j), (0.21804752945899963-2.5993290364567656e-07j), (-0.059148769825696945+0.18204189836978912j), (-0.10280075669288635-0.07468894869089127j), (0.04806262254714966-0.0349196158349514j), (0.004885117989033461+0.015034808777272701j), (-1.2038217948425635e-18+1.1193430388030685e-24j), (-0.000840445572976023+0.002586635295301676j)) new_taps = filter.firdes.complex_band_pass_2(1, 1, 0.2, 0.4, 0.2, 60) self.assertComplexTuplesAlmostEqual(known_taps, new_taps, 5) def test_band_reject(self): known_taps = (-0.004915320314466953, 0.008076251484453678, 0.00415271520614624, 5.694938753309664e-18, -0.01566472090780735, -0.11731793731451035, 0.2126537412405014, 0.11197195947170258, 0.6020866632461548, 0.11197195947170258, 0.2126537412405014, -0.11731793731451035, -0.01566472090780735, 5.694938753309664e-18, 0.00415271520614624, 0.008076251484453678, -0.004915320314466953) new_taps = filter.firdes.band_reject(1, 1, 0.2, 0.4, 0.2) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_band_reject_2(self): known_taps = (0.0015371545450761914, 2.201753372137003e-18, -0.00893471110612154, -0.08790513873100281, 0.1880193054676056, 0.1081816703081131, 0.5982034206390381, 0.1081816703081131, 0.1880193054676056, -0.08790513873100281, -0.00893471110612154, 2.201753372137003e-18, 0.0015371545450761914) new_taps = filter.firdes.band_reject_2(1, 1, 0.2, 0.4, 0.2, 60) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_hilbert(self): known_taps = (-0.010056184604763985, 0.0, -0.08335155993700027, 0.0, -0.5732954144477844, 0.0, 0.5732954144477844, 0.0, 0.08335155993700027, 0.0, 0.010056184604763985) new_taps = filter.firdes.hilbert(11, filter.firdes.WIN_HAMMING) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_root_raised_cosine(self): known_taps = (-0.04609205573797226, -0.02069387212395668, 0.050548505038022995, 0.14850808680057526, 0.23387153446674347, 0.2677156329154968, 0.23387153446674347, 0.14850808680057526, 0.050548505038022995, -0.02069387212395668, -0.04609205573797226) new_taps = filter.firdes.root_raised_cosine(1, 4, 1, 0.35, 11) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) def test_gaussian(self): known_taps = (0.0003600157215259969, 0.0031858310103416443, 0.0182281993329525, 0.06743486225605011, 0.16130395233631134, 0.24947398900985718, 0.24947398900985718, 0.16130395233631134, 0.06743486225605011, 0.0182281993329525, 0.0031858310103416443, 0.0003600157215259969, 2.630509879963938e-05) new_taps = filter.firdes.gaussian(1, 4, 0.35, 13) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) if __name__ == '__main__': gr_unittest.run(test_firdes, "test_firdes.xml") gnuradio-3.7.2.1/gr-filter/python/filter/optfir.py0000664000175000017500000003075512207440367021721 0ustar jcorganjcorgan# # Copyright 2004,2005,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Routines for designing optimal FIR filters. For a great intro to how all this stuff works, see section 6.6 of "Digital Signal Processing: A Practical Approach", Emmanuael C. Ifeachor and Barrie W. Jervis, Adison-Wesley, 1993. ISBN 0-201-54413-X. ''' import math, cmath import filter_swig as filter # ---------------------------------------------------------------- def low_pass (gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, nextra_taps=2): """ Builds a low pass filter. Args: gain: Filter gain in the passband (linear) Fs: Sampling rate (sps) freq1: End of pass band (in Hz) freq2: Start of stop band (in Hz) passband_ripple_db: Pass band ripple in dB (should be small, < 1) stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ passband_dev = passband_ripple_to_dev (passband_ripple_db) stopband_dev = stopband_atten_to_dev (stopband_atten_db) desired_ampls = (gain, 0) (n, fo, ao, w) = remezord ([freq1, freq2], desired_ampls, [passband_dev, stopband_dev], Fs) # The remezord typically under-estimates the filter order, so add 2 taps by default taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") return taps def band_pass (gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, passband_ripple_db, stopband_atten_db, nextra_taps=2): """ Builds a band pass filter. Args: gain: Filter gain in the passband (linear) Fs: Sampling rate (sps) freq_sb1: End of stop band (in Hz) freq_pb1: Start of pass band (in Hz) freq_pb2: End of pass band (in Hz) freq_sb2: Start of stop band (in Hz) passband_ripple_db: Pass band ripple in dB (should be small, < 1) stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ passband_dev = passband_ripple_to_dev (passband_ripple_db) stopband_dev = stopband_atten_to_dev (stopband_atten_db) desired_ampls = (0, gain, 0) desired_freqs = [freq_sb1, freq_pb1, freq_pb2, freq_sb2] desired_ripple = [stopband_dev, passband_dev, stopband_dev] (n, fo, ao, w) = remezord (desired_freqs, desired_ampls, desired_ripple, Fs) # The remezord typically under-estimates the filter order, so add 2 taps by default taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") return taps def complex_band_pass (gain, Fs, freq_sb1, freq_pb1, freq_pb2, freq_sb2, passband_ripple_db, stopband_atten_db, nextra_taps=2): """ Builds a band pass filter with complex taps by making an LPF and spinning it up to the right center frequency Args: gain: Filter gain in the passband (linear) Fs: Sampling rate (sps) freq_sb1: End of stop band (in Hz) freq_pb1: Start of pass band (in Hz) freq_pb2: End of pass band (in Hz) freq_sb2: Start of stop band (in Hz) passband_ripple_db: Pass band ripple in dB (should be small, < 1) stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ center_freq = (freq_pb2 + freq_pb1) / 2.0 lp_pb = (freq_pb2 - center_freq)/1.0 lp_sb = freq_sb2 - center_freq lptaps = low_pass(gain, Fs, lp_pb, lp_sb, passband_ripple_db, stopband_atten_db, nextra_taps) spinner = [cmath.exp(2j*cmath.pi*center_freq/Fs*i) for i in xrange(len(lptaps))] taps = [s*t for s,t in zip(spinner, lptaps)] return taps def band_reject (gain, Fs, freq_pb1, freq_sb1, freq_sb2, freq_pb2, passband_ripple_db, stopband_atten_db, nextra_taps=2): """ Builds a band reject filter spinning it up to the right center frequency Args: gain: Filter gain in the passband (linear) Fs: Sampling rate (sps) freq_pb1: End of pass band (in Hz) freq_sb1: Start of stop band (in Hz) freq_sb2: End of stop band (in Hz) freq_pb2: Start of pass band (in Hz) passband_ripple_db: Pass band ripple in dB (should be small, < 1) stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ passband_dev = passband_ripple_to_dev (passband_ripple_db) stopband_dev = stopband_atten_to_dev (stopband_atten_db) desired_ampls = (gain, 0, gain) desired_freqs = [freq_pb1, freq_sb1, freq_sb2, freq_pb2] desired_ripple = [passband_dev, stopband_dev, passband_dev] (n, fo, ao, w) = remezord (desired_freqs, desired_ampls, desired_ripple, Fs) # Make sure we use an odd number of taps if((n+nextra_taps)%2 == 1): n += 1 # The remezord typically under-estimates the filter order, so add 2 taps by default taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") return taps def high_pass (gain, Fs, freq1, freq2, passband_ripple_db, stopband_atten_db, nextra_taps=2): """ Builds a high pass filter. Args: gain: Filter gain in the passband (linear) Fs: Sampling rate (sps) freq1: End of stop band (in Hz) freq2: Start of pass band (in Hz) passband_ripple_db: Pass band ripple in dB (should be small, < 1) stopband_atten_db: Stop band attenuation in dB (should be large, >= 60) nextra_taps: Extra taps to use in the filter (default=2) """ passband_dev = passband_ripple_to_dev (passband_ripple_db) stopband_dev = stopband_atten_to_dev (stopband_atten_db) desired_ampls = (0, 1) (n, fo, ao, w) = remezord ([freq1, freq2], desired_ampls, [stopband_dev, passband_dev], Fs) # For a HPF, we need to use an odd number of taps # In filter.remez, ntaps = n+1, so n must be even if((n+nextra_taps)%2 == 1): n += 1 # The remezord typically under-estimates the filter order, so add 2 taps by default taps = filter.pm_remez (n + nextra_taps, fo, ao, w, "bandpass") return taps # ---------------------------------------------------------------- def stopband_atten_to_dev (atten_db): """Convert a stopband attenuation in dB to an absolute value""" return 10**(-atten_db/20) def passband_ripple_to_dev (ripple_db): """Convert passband ripple spec expressed in dB to an absolute value""" return (10**(ripple_db/20)-1)/(10**(ripple_db/20)+1) # ---------------------------------------------------------------- def remezord (fcuts, mags, devs, fsamp = 2): ''' FIR order estimator (lowpass, highpass, bandpass, mulitiband). (n, fo, ao, w) = remezord (f, a, dev) (n, fo, ao, w) = remezord (f, a, dev, fs) (n, fo, ao, w) = remezord (f, a, dev) finds the approximate order, normalized frequency band edges, frequency band amplitudes, and weights that meet input specifications f, a, and dev, to use with the remez command. * f is a sequence of frequency band edges (between 0 and Fs/2, where Fs is the sampling frequency), and a is a sequence specifying the desired amplitude on the bands defined by f. The length of f is twice the length of a, minus 2. The desired function is piecewise constant. * dev is a sequence the same size as a that specifies the maximum allowable deviation or ripples between the frequency response and the desired amplitude of the output filter, for each band. Use remez with the resulting order n, frequency sequence fo, amplitude response sequence ao, and weights w to design the filter b which approximately meets the specifications given by remezord input parameters f, a, and dev: b = remez (n, fo, ao, w) (n, fo, ao, w) = remezord (f, a, dev, Fs) specifies a sampling frequency Fs. Fs defaults to 2 Hz, implying a Nyquist frequency of 1 Hz. You can therefore specify band edges scaled to a particular applications sampling frequency. In some cases remezord underestimates the order n. If the filter does not meet the specifications, try a higher order such as n+1 or n+2. ''' # get local copies fcuts = fcuts[:] mags = mags[:] devs = devs[:] for i in range (len (fcuts)): fcuts[i] = float (fcuts[i]) / fsamp nf = len (fcuts) nm = len (mags) nd = len (devs) nbands = nm if nm != nd: raise ValueError, "Length of mags and devs must be equal" if nf != 2 * (nbands - 1): raise ValueError, "Length of f must be 2 * len (mags) - 2" for i in range (len (mags)): if mags[i] != 0: # if not stopband, get relative deviation devs[i] = devs[i] / mags[i] # separate the passband and stopband edges f1 = fcuts[0::2] f2 = fcuts[1::2] n = 0 min_delta = 2 for i in range (len (f1)): if f2[i] - f1[i] < min_delta: n = i min_delta = f2[i] - f1[i] if nbands == 2: # lowpass or highpass case (use formula) l = lporder (f1[n], f2[n], devs[0], devs[1]) else: # bandpass or multipass case # try different lowpasses and take the worst one that # goes through the BP specs l = 0 for i in range (1, nbands-1): l1 = lporder (f1[i-1], f2[i-1], devs[i], devs[i-1]) l2 = lporder (f1[i], f2[i], devs[i], devs[i+1]) l = max (l, l1, l2) n = int (math.ceil (l)) - 1 # need order, not length for remez # cook up remez compatible result ff = [0] + fcuts + [1] for i in range (1, len (ff) - 1): ff[i] *= 2 aa = [] for a in mags: aa = aa + [a, a] max_dev = max (devs) wts = [1] * len(devs) for i in range (len (wts)): wts[i] = max_dev / devs[i] return (n, ff, aa, wts) # ---------------------------------------------------------------- def lporder (freq1, freq2, delta_p, delta_s): ''' FIR lowpass filter length estimator. freq1 and freq2 are normalized to the sampling frequency. delta_p is the passband deviation (ripple), delta_s is the stopband deviation (ripple). Note, this works for high pass filters too (freq1 > freq2), but doesnt work well if the transition is near f == 0 or f == fs/2 From Herrmann et al (1973), Practical design rules for optimum finite impulse response filters. Bell System Technical J., 52, 769-99 ''' df = abs (freq2 - freq1) ddp = math.log10 (delta_p) dds = math.log10 (delta_s) a1 = 5.309e-3 a2 = 7.114e-2 a3 = -4.761e-1 a4 = -2.66e-3 a5 = -5.941e-1 a6 = -4.278e-1 b1 = 11.01217 b2 = 0.5124401 t1 = a1 * ddp * ddp t2 = a2 * ddp t3 = a4 * ddp * ddp t4 = a5 * ddp dinf=((t1 + t2 + a3) * dds) + (t3 + t4 + a6) ff = b1 + b2 * (ddp - dds) n = dinf / df - ff * df + 1 return n def bporder (freq1, freq2, delta_p, delta_s): ''' FIR bandpass filter length estimator. freq1 and freq2 are normalized to the sampling frequency. delta_p is the passband deviation (ripple), delta_s is the stopband deviation (ripple). From Mintzer and Liu (1979) ''' df = abs (freq2 - freq1) ddp = math.log10 (delta_p) dds = math.log10 (delta_s) a1 = 0.01201 a2 = 0.09664 a3 = -0.51325 a4 = 0.00203 a5 = -0.57054 a6 = -0.44314 t1 = a1 * ddp * ddp t2 = a2 * ddp t3 = a4 * ddp * ddp t4 = a5 * ddp cinf = dds * (t1 + t2 + a3) + t3 + t4 + a6 ginf = -14.6 * math.log10 (delta_p / delta_s) - 16.9 n = cinf / df + ginf * df + 1 return n gnuradio-3.7.2.1/gr-filter/python/filter/qa_interp_fir_filter.py0000775000175000017500000000363512207440367024605 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math class test_interp_fir_filter(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_fff(self): taps = [1, 10, 100, 1000, 10000] src_data = (0, 2, 3, 5, 7, 11, 13, 17) interpolation = 3 xr = (0,0,0,0, 2,20,200,2003,20030, 300,3005,30050, 500,5007,50070, 700,7011,70110, 1100,11013,110130, 1300,13017,130170) expected_result = tuple([float(x) for x in xr]) src = blocks.vector_source_f(src_data) op = filter.interp_fir_filter_fff(interpolation, taps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() L = min(len(result_data), len(expected_result)) self.assertEqual(expected_result[0:L], result_data[0:L]) if __name__ == '__main__': gr_unittest.run(test_interp_fir_filter, "test_interp_fir_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_single_pole_iir.py0000775000175000017500000001122712207440367024236 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks class test_single_pole_iir_filter(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_ff_001(self): src_data = (0, 1000, 2000, 3000, 4000, 5000) expected_result = src_data src = blocks.vector_source_f(src_data) op = filter.single_pole_iir_filter_ff(1.0) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_ff_002(self): src_data = (0, 1000, 2000, 3000, 4000, 5000) expected_result = (0, 125, 359.375, 689.453125, 1103.271484, 1590.36255) src = blocks.vector_source_f(src_data) op = filter.single_pole_iir_filter_ff(0.125) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 3) def test_ff_003(self): block_size = 2 src_data = (0, 1000, 2000, 3000, 4000, 5000) expected_result = (0, 125, 250, 484.375, 718.75, 1048.828125) src = blocks.vector_source_f(src_data) s2p = blocks.stream_to_vector(gr.sizeof_float, block_size) op = filter.single_pole_iir_filter_ff (0.125, block_size) p2s = blocks.vector_to_stream(gr.sizeof_float, block_size) dst = blocks.vector_sink_f() self.tb.connect(src, s2p, op, p2s, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 3) def test_cc_001(self): src_data = (0+0j, 1000+1000j, 2000+2000j, 3000+3000j, 4000+4000j, 5000+5000j) expected_result = src_data src = blocks.vector_source_c(src_data) op = filter.single_pole_iir_filter_cc(1.0) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data) def test_cc_002(self): src_data = (complex(0,0), complex(1000,-1000), complex(2000,-2000), complex(3000,-3000), complex(4000,-4000), complex(5000,-5000)) expected_result = (complex(0,0), complex(125,-125), complex(359.375,-359.375), complex(689.453125,-689.453125), complex(1103.271484,-1103.271484), complex(1590.36255,-1590.36255)) src = blocks.vector_source_c(src_data) op = filter.single_pole_iir_filter_cc(0.125) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 3) def test_cc_003(self): block_size = 2 src_data = (complex(0,0), complex(1000,-1000), complex(2000,-2000), complex(3000,-3000), complex(4000,-4000), complex(5000,-5000)) expected_result = (complex(0,0), complex(125,-125), complex(250,-250), complex(484.375,-484.375), complex(718.75,-718.75), complex(1048.828125,-1048.828125)) src = blocks.vector_source_c(src_data) s2p = blocks.stream_to_vector(gr.sizeof_gr_complex, block_size) op = filter.single_pole_iir_filter_cc(0.125, block_size) p2s = blocks.vector_to_stream(gr.sizeof_gr_complex, block_size) dst = blocks.vector_sink_c() self.tb.connect(src, s2p, op, p2s, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 3) if __name__ == '__main__': gr_unittest.run(test_single_pole_iir_filter, "test_single_pole_iir_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_dc_blocker.py0000775000175000017500000000713512207440367023165 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks class test_dc_blocker(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): ''' Test impulse response - long form, cc ''' src_data = [1,] + 100*[0,] expected_result = ((-0.02072429656982422+0j), (-0.02081298828125+0j), (0.979156494140625+0j), (-0.02081298828125+0j), (-0.02072429656982422+0j)) src = blocks.vector_source_c(src_data) op = filter.dc_blocker_cc(32, True) dst = blocks.vector_sink_c() self.tb.connect (src, op, dst) self.tb.run() # only test samples around 2D-2 result_data = dst.data()[60:65] self.assertComplexTuplesAlmostEqual (expected_result, result_data) def test_002(self): ''' Test impulse response - short form, cc ''' src_data = [1,] + 100*[0,] expected_result = ((-0.029296875+0j), (-0.0302734375+0j), (0.96875+0j), (-0.0302734375+0j), (-0.029296875+0j)) src = blocks.vector_source_c(src_data) op = filter.dc_blocker_cc(32, False) dst = blocks.vector_sink_c() self.tb.connect (src, op, dst) self.tb.run() # only test samples around D-1 result_data = dst.data()[29:34] self.assertComplexTuplesAlmostEqual (expected_result, result_data) def test_003(self): ''' Test impulse response - long form, ff ''' src_data = [1,] + 100*[0,] expected_result = ((-0.02072429656982422), (-0.02081298828125), (0.979156494140625), (-0.02081298828125), (-0.02072429656982422)) src = blocks.vector_source_f(src_data) op = filter.dc_blocker_ff(32, True) dst = blocks.vector_sink_f() self.tb.connect (src, op, dst) self.tb.run() # only test samples around 2D-2 result_data = dst.data()[60:65] self.assertFloatTuplesAlmostEqual (expected_result, result_data) def test_004(self): ''' Test impulse response - short form, ff ''' src_data = [1,] + 100*[0,] expected_result = ((-0.029296875), (-0.0302734375), (0.96875), (-0.0302734375), (-0.029296875)) src = blocks.vector_source_f(src_data) op = filter.dc_blocker_ff(32, False) dst = blocks.vector_sink_f() self.tb.connect (src, op, dst) self.tb.run() # only test samples around D-1 result_data = dst.data()[29:34] self.assertFloatTuplesAlmostEqual (expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_dc_blocker, "test_dc_blocker.xml") gnuradio-3.7.2.1/gr-filter/python/filter/filterbank.py0000664000175000017500000001357712207440367022542 0ustar jcorganjcorgan# # Copyright 2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from gnuradio import gr from gnuradio import fft from gnuradio import blocks from filter_swig import fft_filter_ccc def _generate_synthesis_taps(mpoints): return [] # FIXME def _split_taps(taps, mpoints): assert (len(taps) % mpoints) == 0 result = [list() for x in range(mpoints)] for i in xrange(len(taps)): (result[i % mpoints]).append(taps[i]) return [tuple(x) for x in result] class synthesis_filterbank(gr.hier_block2): """ Uniformly modulated polyphase DFT filter bank: synthesis See http://cnx.org/content/m10424/latest """ def __init__(self, mpoints, taps=None): """ Takes M complex streams in, produces single complex stream out that runs at M times the input sample rate Args: mpoints: number of freq bins/interpolation factor/subbands taps: filter taps for subband filter The channel spacing is equal to the input sample rate. The total bandwidth and output sample rate are equal the input sample rate * nchannels. Output stream to frequency mapping: channel zero is at zero frequency. if mpoints is odd: Channels with increasing positive frequencies come from channels 1 through (N-1)/2. Channel (N+1)/2 is the maximum negative frequency, and frequency increases through N-1 which is one channel lower than the zero frequency. if mpoints is even: Channels with increasing positive frequencies come from channels 1 through (N/2)-1. Channel (N/2) is evenly split between the max positive and negative bins. Channel (N/2)+1 is the maximum negative frequency, and frequency increases through N-1 which is one channel lower than the zero frequency. Channels near the frequency extremes end up getting cut off by subsequent filters and therefore have diminished utility. """ item_size = gr.sizeof_gr_complex gr.hier_block2.__init__(self, "synthesis_filterbank", gr.io_signature(mpoints, mpoints, item_size), # Input signature gr.io_signature(1, 1, item_size)) # Output signature if taps is None: taps = _generate_synthesis_taps(mpoints) # pad taps to multiple of mpoints r = len(taps) % mpoints if r != 0: taps = taps + (mpoints - r) * (0,) # split in mpoints separate set of taps sub_taps = _split_taps(taps, mpoints) self.ss2v = blocks.streams_to_vector(item_size, mpoints) self.ifft = fft.fft_vcc(mpoints, False, []) self.v2ss = blocks.vector_to_streams(item_size, mpoints) # mpoints filters go in here... self.ss2s = blocks.streams_to_stream(item_size, mpoints) for i in range(mpoints): self.connect((self, i), (self.ss2v, i)) self.connect(self.ss2v, self.ifft, self.v2ss) # build mpoints fir filters... for i in range(mpoints): f = fft_filter_ccc(1, sub_taps[i]) self.connect((self.v2ss, i), f) self.connect(f, (self.ss2s, i)) self.connect(self.ss2s, self) class analysis_filterbank(gr.hier_block2): """ Uniformly modulated polyphase DFT filter bank: analysis See http://cnx.org/content/m10424/latest """ def __init__(self, mpoints, taps=None): """ Takes 1 complex stream in, produces M complex streams out that runs at 1/M times the input sample rate Args: mpoints: number of freq bins/interpolation factor/subbands taps: filter taps for subband filter Same channel to frequency mapping as described above. """ item_size = gr.sizeof_gr_complex gr.hier_block2.__init__(self, "analysis_filterbank", gr.io_signature(1, 1, item_size), # Input signature gr.io_signature(mpoints, mpoints, item_size)) # Output signature if taps is None: taps = _generate_synthesis_taps(mpoints) # pad taps to multiple of mpoints r = len(taps) % mpoints if r != 0: taps = taps + (mpoints - r) * (0,) # split in mpoints separate set of taps sub_taps = _split_taps(taps, mpoints) # print >> sys.stderr, "mpoints =", mpoints, "len(sub_taps) =", len(sub_taps) self.s2ss = blocks.stream_to_streams(item_size, mpoints) # filters here self.ss2v = blocks.streams_to_vector(item_size, mpoints) self.fft = fft.fft_vcc(mpoints, True, []) self.v2ss = blocks.vector_to_streams(item_size, mpoints) self.connect(self, self.s2ss) # build mpoints fir filters... for i in range(mpoints): f = fft_filter_ccc(1, sub_taps[mpoints-i-1]) self.connect((self.s2ss, i), f) self.connect(f, (self.ss2v, i)) self.connect((self.v2ss, i), (self, i)) self.connect(self.ss2v, self.fft, self.v2ss) gnuradio-3.7.2.1/gr-filter/python/filter/qa_freq_xlating_fir_filter.py0000775000175000017500000002527612245466767026012 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from gnuradio import gr, gr_unittest, filter, blocks import cmath, math def fir_filter(x, taps, decim=1): y = [] x2 = (len(taps)-1)*[0,] + x for i in range(0, len(x), decim): yi = 0 for j in range(len(taps)): yi += taps[len(taps)-1-j] * x2[i+j] y.append(yi) return y def sig_source_s(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: int(100*math.sin(2.*math.pi*freq*x)), t) return y def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y def mix(lo, data): y = [lo_i*data_i for lo_i, data_i in zip(lo, data)] return y class test_freq_xlating_filter(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def generate_ccf_source(self): self.fs = fs = 1 self.fc = fc = 0.3 self.bw = bw = 0.1 self.taps = filter.firdes.low_pass(1, fs, bw, bw/4) times = xrange(100) self.src_data = map(lambda t: cmath.exp(-2j*cmath.pi*fc/fs*(t/100.0)), times) def generate_ccc_source(self): self.fs = fs = 1 self.fc = fc = 0.3 self.bw = bw = 0.1 self.taps = filter.firdes.complex_band_pass(1, fs, -bw/2, bw/2, bw/4) times = xrange(100) self.src_data = map(lambda t: cmath.exp(-2j*cmath.pi*fc/fs*(t/100.0)), times) def generate_fcf_source(self): self.fs = fs = 1 self.fc = fc = 0.3 self.bw = bw = 0.1 self.taps = filter.firdes.low_pass(1, fs, bw, bw/4) times = xrange(100) self.src_data = map(lambda t: math.sin(2*cmath.pi*fc/fs*(t/100.0)), times) def generate_fcc_source(self): self.fs = fs = 1 self.fc = fc = 0.3 self.bw = bw = 0.1 self.taps = filter.firdes.complex_band_pass(1, fs, -bw/2, bw/2, bw/4) times = xrange(100) self.src_data = map(lambda t: math.sin(2*cmath.pi*fc/fs*(t/100.0)), times) def generate_scf_source(self): self.fs = fs = 1 self.fc = fc = 0.3 self.bw = bw = 0.1 self.taps = filter.firdes.low_pass(1, fs, bw, bw/4) times = xrange(100) self.src_data = map(lambda t: int(100*math.sin(2*cmath.pi*fc/fs*(t/100.0))), times) def generate_scc_source(self): self.fs = fs = 1 self.fc = fc = 0.3 self.bw = bw = 0.1 self.taps = filter.firdes.complex_band_pass(1, fs, -bw/2, bw/2, bw/4) times = xrange(100) self.src_data = map(lambda t: int(100*math.sin(2*cmath.pi*fc/fs*(t/100.0))), times) def test_fir_filter_ccf_001(self): self.generate_ccf_source() decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_c(self.src_data) op = filter.freq_xlating_fir_filter_ccf(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccf_002(self): self.generate_ccf_source() decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_c(self.src_data) op = filter.freq_xlating_fir_filter_ccf(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccc_001(self): self.generate_ccc_source() decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_c(self.src_data) op = filter.freq_xlating_fir_filter_ccc(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_ccc_002(self): self.generate_ccc_source() decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_c(self.src_data) op = filter.freq_xlating_fir_filter_ccc(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fcf_001(self): self.generate_fcf_source() decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_f(self.src_data) op = filter.freq_xlating_fir_filter_fcf(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fcf_002(self): self.generate_fcf_source() decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_f(self.src_data) op = filter.freq_xlating_fir_filter_fcf(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fcc_001(self): self.generate_fcc_source() decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_f(self.src_data) op = filter.freq_xlating_fir_filter_fcc(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_fcc_002(self): self.generate_fcc_source() decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_f(self.src_data) op = filter.freq_xlating_fir_filter_fcc(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 5) def test_fir_filter_scf_001(self): self.generate_scf_source() decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_s(self.src_data) op = filter.freq_xlating_fir_filter_scf(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 4) def test_fir_filter_scf_002(self): self.generate_scf_source() decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_s(self.src_data) op = filter.freq_xlating_fir_filter_scf(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 4) def test_fir_filter_scc_001(self): self.generate_scc_source() decim = 1 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_s(self.src_data) op = filter.freq_xlating_fir_filter_scc(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 4) def test_fir_filter_scc_002(self): self.generate_scc_source() decim = 4 lo = sig_source_c(self.fs, -self.fc, 1, len(self.src_data)) despun = mix(lo, self.src_data) expected_data = fir_filter(despun, self.taps, decim) src = blocks.vector_source_s(self.src_data) op = filter.freq_xlating_fir_filter_scc(decim, self.taps, self.fc, self.fs) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_data, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_freq_xlating_filter, "test_freq_xlating_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_pfb_decimator.py0000775000175000017500000001022312207440367023664 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y def run_test(tb, channel): N = 1000 # number of samples to use M = 5 # Number of channels fs = 5000.0 # baseband sampling rate ifs = M*fs # input samp rate to decimator taps = filter.firdes.low_pass_2(1, ifs, fs/2, fs/10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS) signals = list() add = blocks.add_cc() freqs = [-230., 121., 110., -513., 203.] Mch = ((len(freqs)-1)/2 + channel) % len(freqs) for i in xrange(len(freqs)): f = freqs[i] + (M/2-M+i+1)*fs data = sig_source_c(ifs, f, 1, N) signals.append(blocks.vector_source_c(data)) tb.connect(signals[i], (add,i)) s2ss = blocks.stream_to_streams(gr.sizeof_gr_complex, M) pfb = filter.pfb_decimator_ccf(M, taps, channel) snk = blocks.vector_sink_c() tb.connect(add, s2ss) for i in xrange(M): tb.connect((s2ss,i), (pfb,i)) tb.connect(pfb, snk) tb.run() L = len(snk.data()) # Each channel is rotated by 2pi/M phase = -2*math.pi * channel / M # Filter delay is the normal delay of each arm tpf = math.ceil(len(taps) / float(M)) delay = -(tpf - 1.0) / 2.0 delay = int(delay) # Create a time scale that's delayed to match the filter delay t = map(lambda x: float(x)/fs, xrange(delay, L+delay)) # Create known data as complex sinusoids for the baseband freq # of the extracted channel is due to decimator output order. expected_data = map(lambda x: math.cos(2.*math.pi*freqs[Mch]*x+phase) + \ 1j*math.sin(2.*math.pi*freqs[Mch]*x+phase), t) dst_data = snk.data() return (dst_data, expected_data) class test_pfb_decimator(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): Ntest = 50 dst_data, expected_data = run_test(self.tb, 0) self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4) def test_001(self): Ntest = 50 dst_data, expected_data = run_test(self.tb, 1) self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4) def test_002(self): Ntest = 50 dst_data, expected_data = run_test(self.tb, 2) self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4) def test_003(self): Ntest = 50 dst_data, expected_data = run_test(self.tb, 3) self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4) def test_004(self): Ntest = 50 dst_data, expected_data = run_test(self.tb, 4) self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4) if __name__ == '__main__': gr_unittest.run(test_pfb_decimator, "test_pfb_decimator.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_fft_filter.py0000775000175000017500000003125712207440367023224 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import sys import random def make_random_complex_tuple(L): result = [] for x in range(L): result.append(complex(2*random.random()-1, 2*random.random()-1)) return tuple(result) def make_random_float_tuple(L): result = [] for x in range(L): result.append(float(int(2*random.random()-1))) return tuple(result) def reference_filter_ccc(dec, taps, input): """ compute result using conventional fir filter """ tb = gr.top_block() #src = blocks.vector_source_c(((0,) * (len(taps) - 1)) + input) src = blocks.vector_source_c(input) op = filter.fir_filter_ccc(dec, taps) dst = blocks.vector_sink_c() tb.connect(src, op, dst) tb.run() return dst.data() def reference_filter_fff(dec, taps, input): """ compute result using conventional fir filter """ tb = gr.top_block() #src = blocks.vector_source_f(((0,) * (len(taps) - 1)) + input) src = blocks.vector_source_f(input) op = filter.fir_filter_fff(dec, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() return dst.data() def print_complex(x): for i in x: i = complex(i) sys.stdout.write("(%6.3f,%6.3fj), " % (i.real, i.imag)) sys.stdout.write('\n') class test_fft_filter(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def assert_fft_ok2(self, expected_result, result_data): expected_result = expected_result[:len(result_data)] self.assertComplexTuplesAlmostEqual2 (expected_result, result_data, abs_eps=1e-9, rel_eps=4e-4) def assert_fft_float_ok2(self, expected_result, result_data, abs_eps=1e-9, rel_eps=4e-4): expected_result = expected_result[:len(result_data)] self.assertFloatTuplesAlmostEqual2 (expected_result, result_data, abs_eps, rel_eps) def test_ccc_001(self): tb = gr.top_block() src_data = (0,1,2,3,4,5,6,7) taps = (1,) expected_result = tuple([complex(x) for x in (0,1,2,3,4,5,6,7)]) src = blocks.vector_source_c(src_data) op = filter.fft_filter_ccc(1, taps) dst = blocks.vector_sink_c() tb.connect(src, op, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data self.assertComplexTuplesAlmostEqual (expected_result, result_data, 5) def test_ccc_002(self): # Test nthreads tb = gr.top_block() src_data = (0,1,2,3,4,5,6,7) taps = (2,) nthreads = 2 expected_result = tuple([2 * complex(x) for x in (0,1,2,3,4,5,6,7)]) src = blocks.vector_source_c(src_data) op = filter.fft_filter_ccc(1, taps, nthreads) dst = blocks.vector_sink_c() tb.connect(src, op, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data self.assertComplexTuplesAlmostEqual (expected_result, result_data, 5) def test_ccc_003(self): tb = gr.top_block() src_data = (0,1,2,3,4,5,6,7) taps = (2,) expected_result = tuple([2 * complex(x) for x in (0,1,2,3,4,5,6,7)]) src = blocks.vector_source_c(src_data) op = filter.fft_filter_ccc(1, taps) dst = blocks.vector_sink_c() tb.connect(src, op, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data self.assertComplexTuplesAlmostEqual (expected_result, result_data, 5) def test_ccc_004(self): random.seed(0) for i in xrange(25): # sys.stderr.write("\n>>> Loop = %d\n" % (i,)) src_len = 4*1024 src_data = make_random_complex_tuple(src_len) ntaps = int(random.uniform(2, 1000)) taps = make_random_complex_tuple(ntaps) expected_result = reference_filter_ccc(1, taps, src_data) src = blocks.vector_source_c(src_data) op = filter.fft_filter_ccc(1, taps) dst = blocks.vector_sink_c() tb = gr.top_block() tb.connect(src, op, dst) tb.run() result_data = dst.data() del tb self.assert_fft_ok2(expected_result, result_data) def test_ccc_005(self): random.seed(0) for i in xrange(25): # sys.stderr.write("\n>>> Loop = %d\n" % (i,)) dec = i + 1 src_len = 4*1024 src_data = make_random_complex_tuple(src_len) ntaps = int(random.uniform(2, 100)) taps = make_random_complex_tuple(ntaps) expected_result = reference_filter_ccc(dec, taps, src_data) src = blocks.vector_source_c(src_data) op = filter.fft_filter_ccc(dec, taps) dst = blocks.vector_sink_c() tb = gr.top_block() tb.connect(src, op, dst) tb.run() del tb result_data = dst.data() self.assert_fft_ok2(expected_result, result_data) def test_ccc_006(self): # Test decimating with nthreads=2 random.seed(0) nthreads = 2 for i in xrange(25): # sys.stderr.write("\n>>> Loop = %d\n" % (i,)) dec = i + 1 src_len = 4*1024 src_data = make_random_complex_tuple(src_len) ntaps = int(random.uniform(2, 100)) taps = make_random_complex_tuple(ntaps) expected_result = reference_filter_ccc(dec, taps, src_data) src = blocks.vector_source_c(src_data) op = filter.fft_filter_ccc(dec, taps, nthreads) dst = blocks.vector_sink_c() tb = gr.top_block() tb.connect(src, op, dst) tb.run() del tb result_data = dst.data() self.assert_fft_ok2(expected_result, result_data) # ---------------------------------------------------------------- # test _fff version # ---------------------------------------------------------------- def test_fff_001(self): tb = gr.top_block() src_data = (0,1,2,3,4,5,6,7) taps = (1,) expected_result = tuple([float(x) for x in (0,1,2,3,4,5,6,7)]) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(1, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data self.assertFloatTuplesAlmostEqual (expected_result, result_data, 5) def test_fff_002(self): tb = gr.top_block() src_data = (0,1,2,3,4,5,6,7) taps = (2,) expected_result = tuple([2 * float(x) for x in (0,1,2,3,4,5,6,7)]) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(1, taps) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data self.assertFloatTuplesAlmostEqual (expected_result, result_data, 5) def test_fff_003(self): # Test 02 with nthreads tb = gr.top_block() src_data = (0,1,2,3,4,5,6,7) taps = (2,) nthreads = 2 expected_result = tuple([2 * float(x) for x in (0,1,2,3,4,5,6,7)]) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(1, taps, nthreads) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual (expected_result, result_data, 5) def xtest_fff_004(self): random.seed(0) for i in xrange(25): sys.stderr.write("\n>>> Loop = %d\n" % (i,)) src_len = 4096 src_data = make_random_float_tuple(src_len) ntaps = int(random.uniform(2, 1000)) taps = make_random_float_tuple(ntaps) expected_result = reference_filter_fff(1, taps, src_data) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(1, taps) dst = blocks.vector_sink_f() tb = gr.top_block() tb.connect(src, op, dst) tb.run() result_data = dst.data() #print "src_len =", src_len, " ntaps =", ntaps try: self.assert_fft_float_ok2(expected_result, result_data, abs_eps=1.0) except: expected = open('expected', 'w') for x in expected_result: expected.write(`x` + '\n') actual = open('actual', 'w') for x in result_data: actual.write(`x` + '\n') raise def xtest_fff_005(self): random.seed(0) for i in xrange(25): sys.stderr.write("\n>>> Loop = %d\n" % (i,)) src_len = 4*1024 src_data = make_random_float_tuple(src_len) ntaps = int(random.uniform(2, 1000)) taps = make_random_float_tuple(ntaps) expected_result = reference_filter_fff(1, taps, src_data) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(1, taps) dst = blocks.vector_sink_f() tb = gr.top_block() tb.connect(src, op, dst) tb.run() result_data = dst.data() self.assert_fft_float_ok2(expected_result, result_data, abs_eps=2.0) def xtest_fff_006(self): random.seed(0) for i in xrange(25): sys.stderr.write("\n>>> Loop = %d\n" % (i,)) dec = i + 1 src_len = 4*1024 src_data = make_random_float_tuple(src_len) ntaps = int(random.uniform(2, 100)) taps = make_random_float_tuple(ntaps) expected_result = reference_filter_fff(dec, taps, src_data) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(dec, taps) dst = blocks.vector_sink_f() tb = gr.top_block() tb.connect(src, op, dst) tb.run() result_data = dst.data() self.assert_fft_float_ok2(expected_result, result_data) def xtest_fff_007(self): # test decimation with nthreads random.seed(0) nthreads = 2 for i in xrange(25): sys.stderr.write("\n>>> Loop = %d\n" % (i,)) dec = i + 1 src_len = 4*1024 src_data = make_random_float_tuple(src_len) ntaps = int(random.uniform(2, 100)) taps = make_random_float_tuple(ntaps) expected_result = reference_filter_fff(dec, taps, src_data) src = blocks.vector_source_f(src_data) op = filter.fft_filter_fff(dec, taps, nthreads) dst = blocks.vector_sink_f() tb = gr.top_block() tb.connect(src, op, dst) tb.run() result_data = dst.data() self.assert_fft_float_ok2(expected_result, result_data) def test_fff_get0(self): random.seed(0) for i in xrange(25): ntaps = int(random.uniform(2, 100)) taps = make_random_float_tuple(ntaps) op = filter.fft_filter_fff(1, taps) result_data = op.taps() #print result_data self.assertEqual(taps, result_data) def test_ccc_get0(self): random.seed(0) for i in xrange(25): ntaps = int(random.uniform(2, 100)) taps = make_random_complex_tuple(ntaps) op = filter.fft_filter_ccc(1, taps) result_data = op.taps() #print result_data self.assertComplexTuplesAlmostEqual(taps, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_fft_filter, "test_fft_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_fractional_resampler.py0000664000175000017500000001170112207702530025252 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, filter, blocks def sig_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.sin(2.*math.pi*freq*x), t) return y def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y def const_source_f(amp, N): y = N*[amp,] return y class test_fractional_resampler(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001_ff(self): N = 10000 # number of samples to use fs = 1000 # baseband sampling rate rrate = 1.123 # resampling rate freq = 10 data = sig_source_f(fs, freq, 1, N) signal = blocks.vector_source_f(data) op = filter.fractional_resampler_ff(0, rrate) snk = blocks.vector_sink_f() self.tb.connect(signal, op, snk) self.tb.run() Ntest = 5000 L = len(snk.data()) t = map(lambda x: float(x)/(fs/rrate), xrange(L)) phase = 0.1884 expected_data = map(lambda x: math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 3) def test_002_cc(self): N = 10000 # number of samples to use fs = 1000 # baseband sampling rate rrate = 1.123 # resampling rate freq = 10 data = sig_source_c(fs, freq, 1, N) signal = blocks.vector_source_c(data) op = filter.fractional_resampler_cc(0.0, rrate) snk = blocks.vector_sink_c() self.tb.connect(signal, op, snk) self.tb.run() Ntest = 5000 L = len(snk.data()) t = map(lambda x: float(x)/(fs/rrate), xrange(L)) phase = 0.1884 expected_data = map(lambda x: math.cos(2.*math.pi*freq*x+phase) + \ 1j*math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 3) def test_003_ff(self): N = 10000 # number of samples to use fs = 1000 # baseband sampling rate rrate = 1.123 # resampling rate freq = 10 data = sig_source_f(fs, freq, 1, N) ctrl = const_source_f(rrate, N) signal = blocks.vector_source_f(data) control = blocks.vector_source_f(ctrl) op = filter.fractional_resampler_ff(0, 1) snk = blocks.vector_sink_f() self.tb.connect(signal, op, snk) self.tb.connect(control, (op,1)) self.tb.run() Ntest = 5000 L = len(snk.data()) t = map(lambda x: float(x)/(fs/rrate), xrange(L)) phase = 0.1884 expected_data = map(lambda x: math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 3) def test_004_cc(self): N = 10000 # number of samples to use fs = 1000 # baseband sampling rate rrate = 1.123 # resampling rate freq = 10 data = sig_source_c(fs, freq, 1, N) ctrl = const_source_f(rrate, N) signal = blocks.vector_source_c(data) control = blocks.vector_source_f(ctrl) op = filter.fractional_resampler_cc(0.0, 1) snk = blocks.vector_sink_c() self.tb.connect(signal, op, snk) self.tb.connect(control, (op,1)) self.tb.run() Ntest = 5000 L = len(snk.data()) t = map(lambda x: float(x)/(fs/rrate), xrange(L)) phase = 0.1884 expected_data = map(lambda x: math.cos(2.*math.pi*freq*x+phase) + \ 1j*math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 3) if __name__ == '__main__': gr_unittest.run(test_fractional_resampler, "test_fractional_resampler.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_iir_filter.py0000775000175000017500000001253712207440367023230 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks class test_iir_filter(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_iir_direct_001(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) fftaps = () fbtaps = () expected_result = (0, 0, 0, 0, 0, 0, 0, 0) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_002(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) fftaps = (2,) fbtaps = (0,) expected_result = (2, 4, 6, 8, 10, 12, 14, 16) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_003(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) fftaps = (2, 11) fbtaps = (0, 0) expected_result = (2, 15, 28, 41, 54, 67, 80, 93) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_004(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) fftaps = (2, 11) fbtaps = (0, -1) expected_result = (2, 13, 15, 26, 28, 39, 41, 52) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_005(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) fftaps = (2, 11, 0) fbtaps = (0, -1, 3) expected_result = (2, 13, 21, 59, 58, 186, 68, 583) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_006(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) expected_result = (2, 13, 21, 59, 58, 186, 68, 583) fftaps = (2, 1) fbtaps = (0, -1) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) fftaps = (2, 11, 0) fbtaps = (0, -1, 3) op.set_taps(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_007(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) expected_result = (2,2,5,5,8,8,11,11) fftaps = (2, 1) fbtaps = (0, -1) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) fftaps = (2,0,1) fbtaps = (0, -1) op.set_taps(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_iir_direct_008(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8) expected_result = (2,4,4,10,18,14,26,56) fftaps = (2,) fbtaps = (0, 1) src = blocks.vector_source_f(src_data) op = filter.iir_filter_ffd(fftaps, fbtaps) fftaps_data = (1) fbtaps = (0,0, -1,3) op.set_taps(fftaps, fbtaps) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual (expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_iir_filter, "test_iir_filter.xml") gnuradio-3.7.2.1/gr-filter/python/filter/qa_fractional_interpolator.py0000775000175000017500000000611512207440367026017 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.sin(2.*math.pi*freq*x), t) return y def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y class test_fractional_resampler(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001_ff(self): N = 10000 # number of samples to use fs = 1000 # baseband sampling rate rrate = 1.123 # resampling rate freq = 10 data = sig_source_f(fs, freq, 1, N) signal = blocks.vector_source_f(data) op = filter.fractional_interpolator_ff(0, rrate) snk = blocks.vector_sink_f() self.tb.connect(signal, op, snk) self.tb.run() Ntest = 5000 L = len(snk.data()) t = map(lambda x: float(x)/(fs/rrate), xrange(L)) phase = 0.1884 expected_data = map(lambda x: math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertFloatTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 3) def test_002_cc(self): N = 10000 # number of samples to use fs = 1000 # baseband sampling rate rrate = 1.123 # resampling rate freq = 10 data = sig_source_c(fs, freq, 1, N) signal = blocks.vector_source_c(data) op = filter.fractional_interpolator_cc(0.0, rrate) snk = blocks.vector_sink_c() self.tb.connect(signal, op, snk) self.tb.run() Ntest = 5000 L = len(snk.data()) t = map(lambda x: float(x)/(fs/rrate), xrange(L)) phase = 0.1884 expected_data = map(lambda x: math.cos(2.*math.pi*freq*x+phase) + \ 1j*math.sin(2.*math.pi*freq*x+phase), t) dst_data = snk.data() self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 3) if __name__ == '__main__': gr_unittest.run(test_fractional_resampler, "test_fractional_resampler.xml") gnuradio-3.7.2.1/gr-filter/python/filter/__init__.py0000664000175000017500000000226312207440367022146 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Filter blocks and related functions. ''' import os try: from filter_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from filter_swig import * from filterbank import * from rational_resampler import * import pfb import optfir # Pull this into the filter module from gnuradio.fft import window gnuradio-3.7.2.1/gr-filter/python/filter/qa_pfb_synthesizer.py0000775000175000017500000000656212207440367024317 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter, blocks import math def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y class test_pfb_synthesizer(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): N = 10000 # number of samples to use M = 5 # Number of channels fs = 1000 # baseband sampling rate ofs = M*fs # input samp rate to decimator taps = filter.firdes.low_pass_2(M, ofs, fs/2, fs/10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS) signals = list() freqs = [0, 100, 200, -200, -100] for i in xrange(len(freqs)): data = sig_source_c(fs, freqs[i], 1, N) signals.append(blocks.vector_source_c(data)) pfb = filter.pfb_synthesizer_ccf(M, taps) snk = blocks.vector_sink_c() for i in xrange(M): self.tb.connect(signals[i], (pfb,i)) self.tb.connect(pfb, snk) self.tb.run() Ntest = 1000 L = len(snk.data()) t = map(lambda x: float(x)/ofs, xrange(L)) # Create known data as sum of complex sinusoids at freqs # of the output channels. freqs = [-2200, -1100, 0, 1100, 2200] expected_data = len(t)*[0,] for i in xrange(len(t)): expected_data[i] = math.cos(2.*math.pi*freqs[0]*t[i]) + \ 1j*math.sin(2.*math.pi*freqs[0]*t[i]) + \ math.cos(2.*math.pi*freqs[1]*t[i]) + \ 1j*math.sin(2.*math.pi*freqs[1]*t[i]) + \ math.cos(2.*math.pi*freqs[2]*t[i]) + \ 1j*math.sin(2.*math.pi*freqs[2]*t[i]) + \ math.cos(2.*math.pi*freqs[3]*t[i]) + \ 1j*math.sin(2.*math.pi*freqs[3]*t[i]) + \ math.cos(2.*math.pi*freqs[4]*t[i]) + \ 1j*math.sin(2.*math.pi*freqs[4]*t[i]) dst_data = snk.data() offset = 25 self.assertComplexTuplesAlmostEqual(expected_data[2000-offset:2000-offset+Ntest], dst_data[2000:2000+Ntest], 4) if __name__ == '__main__': gr_unittest.run(test_pfb_synthesizer, "test_pfb_synthesizer.xml") gnuradio-3.7.2.1/gr-filter/python/filter/rational_resampler.py0000664000175000017500000001155112207440367024272 0ustar jcorganjcorgan# # Copyright 2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru import filter_swig as filter _plot = None def design_filter(interpolation, decimation, fractional_bw): """ Given the interpolation rate, decimation rate and a fractional bandwidth, design a set of taps. Args: interpolation: interpolation factor (integer > 0) decimation: decimation factor (integer > 0) fractional_bw: fractional bandwidth in (0, 0.5) 0.4 works well. (float) Returns: : sequence of numbers """ if fractional_bw >= 0.5 or fractional_bw <= 0: raise ValueError, "Invalid fractional_bandwidth, must be in (0, 0.5)" beta = 5.0 trans_width = 0.5 - fractional_bw mid_transition_band = 0.5 - trans_width/2 taps = filter.firdes.low_pass(interpolation, # gain 1, # Fs mid_transition_band/interpolation, # trans mid point trans_width/interpolation, # transition width filter.firdes.WIN_KAISER, beta) # beta return taps class _rational_resampler_base(gr.hier_block2): """ base class for all rational resampler variants. """ def __init__(self, resampler_base, interpolation, decimation, taps=None, fractional_bw=None): """ Rational resampling polyphase FIR filter. Either taps or fractional_bw may be specified, but not both. If neither is specified, a reasonable default, 0.4, is used as the fractional_bw. Args: interpolation: interpolation factor (integer > 0) decimation: decimation factor (integer > 0) taps: optional filter coefficients (sequence) fractional_bw: fractional bandwidth in (0, 0.5), measured at final freq (use 0.4) (float) """ if not isinstance(interpolation, int) or interpolation < 1: raise ValueError, "interpolation must be an integer >= 1" if not isinstance(decimation, int) or decimation < 1: raise ValueError, "decimation must be an integer >= 1" if taps is None and fractional_bw is None: fractional_bw = 0.4 d = gru.gcd(interpolation, decimation) interpolation = interpolation // d decimation = decimation // d if taps is None: taps = design_filter(interpolation, decimation, fractional_bw) resampler = resampler_base(interpolation, decimation, taps) gr.hier_block2.__init__(self, "rational_resampler", gr.io_signature(1, 1, resampler.input_signature().sizeof_stream_item(0)), gr.io_signature(1, 1, resampler.output_signature().sizeof_stream_item(0))) self.connect(self, resampler, self) class rational_resampler_fff(_rational_resampler_base): def __init__(self, interpolation, decimation, taps=None, fractional_bw=None): """ Rational resampling polyphase FIR filter with float input, float output and float taps. """ _rational_resampler_base.__init__(self, filter.rational_resampler_base_fff, interpolation, decimation, taps, fractional_bw) class rational_resampler_ccf(_rational_resampler_base): def __init__(self, interpolation, decimation, taps=None, fractional_bw=None): """ Rational resampling polyphase FIR filter with complex input, complex output and float taps. """ _rational_resampler_base.__init__(self, filter.rational_resampler_base_ccf, interpolation, decimation, taps, fractional_bw) class rational_resampler_ccc(_rational_resampler_base): def __init__(self, interpolation, decimation, taps=None, fractional_bw=None): """ Rational resampling polyphase FIR filter with complex input, complex output and complex taps. """ _rational_resampler_base.__init__(self, filter.rational_resampler_base_ccc, interpolation, decimation, taps, fractional_bw) gnuradio-3.7.2.1/gr-filter/python/filter/pfb.py0000664000175000017500000002506012245466767021174 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import filter_swig as filter import optfir try: from gnuradio import blocks except ImportError: import blocks_swig as blocks class channelizer_ccf(gr.hier_block2): ''' Make a Polyphase Filter channelizer (complex in, complex out, floating-point taps) This simplifies the interface by allowing a single input stream to connect to this block. It will then output a stream for each channel. ''' def __init__(self, numchans, taps=None, oversample_rate=1, atten=100): gr.hier_block2.__init__(self, "pfb_channelizer_ccf", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(numchans, numchans, gr.sizeof_gr_complex)) self._nchans = numchans self._oversample_rate = oversample_rate if (taps is not None) and (len(taps) > 0): self._taps = taps else: # Create a filter that covers the full bandwidth of the input signal bw = 0.4 tb = 0.2 ripple = 0.1 made = False while not made: try: self._taps = optfir.low_pass(1, self._nchans, bw, bw+tb, ripple, atten) made = True except RuntimeError: ripple += 0.01 made = False print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): raise RuntimeError("optfir could not generate an appropriate filter.") self.s2ss = blocks.stream_to_streams(gr.sizeof_gr_complex, self._nchans) self.pfb = filter.pfb_channelizer_ccf(self._nchans, self._taps, self._oversample_rate) self.connect(self, self.s2ss) for i in xrange(self._nchans): self.connect((self.s2ss,i), (self.pfb,i)) self.connect((self.pfb,i), (self,i)) def set_channel_map(self, newmap): self.pfb.set_channel_map(newmap) class interpolator_ccf(gr.hier_block2): ''' Make a Polyphase Filter interpolator (complex in, complex out, floating-point taps) The block takes a single complex stream in and outputs a single complex stream out. As such, it requires no extra glue to handle the input/output streams. This block is provided to be consistent with the interface to the other PFB block. ''' def __init__(self, interp, taps=None, atten=100): gr.hier_block2.__init__(self, "pfb_interpolator_ccf", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_gr_complex)) self._interp = interp self._taps = taps if (taps is not None) and (len(taps) > 0): self._taps = taps else: # Create a filter that covers the full bandwidth of the input signal bw = 0.4 tb = 0.2 ripple = 0.99 made = False while not made: try: self._taps = optfir.low_pass(self._interp, self._interp, bw, bw+tb, ripple, atten) made = True except RuntimeError: ripple += 0.01 made = False print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): raise RuntimeError("optfir could not generate an appropriate filter.") self.pfb = filter.pfb_interpolator_ccf(self._interp, self._taps) self.connect(self, self.pfb) self.connect(self.pfb, self) class decimator_ccf(gr.hier_block2): ''' Make a Polyphase Filter decimator (complex in, complex out, floating-point taps) This simplifies the interface by allowing a single input stream to connect to this block. It will then output a stream that is the decimated output stream. ''' def __init__(self, decim, taps=None, channel=0, atten=100): gr.hier_block2.__init__(self, "pfb_decimator_ccf", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_gr_complex)) self._decim = decim self._channel = channel if (taps is not None) and (len(taps) > 0): self._taps = taps else: # Create a filter that covers the full bandwidth of the input signal bw = 0.4 tb = 0.2 ripple = 0.1 made = False while not made: try: self._taps = optfir.low_pass(1, self._decim, bw, bw+tb, ripple, atten) made = True except RuntimeError: ripple += 0.01 made = False print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): raise RuntimeError("optfir could not generate an appropriate filter.") self.s2ss = blocks.stream_to_streams(gr.sizeof_gr_complex, self._decim) self.pfb = filter.pfb_decimator_ccf(self._decim, self._taps, self._channel) self.connect(self, self.s2ss) for i in xrange(self._decim): self.connect((self.s2ss,i), (self.pfb,i)) self.connect(self.pfb, self) class arb_resampler_ccf(gr.hier_block2): ''' Convenience wrapper for the polyphase filterbank arbitrary resampler. The block takes a single complex stream in and outputs a single complex stream out. As such, it requires no extra glue to handle the input/output streams. This block is provided to be consistent with the interface to the other PFB block. ''' def __init__(self, rate, taps=None, flt_size=32, atten=100): gr.hier_block2.__init__(self, "pfb_arb_resampler_ccf", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._rate = rate self._size = flt_size if (taps is not None) and (len(taps) > 0): self._taps = taps else: # Create a filter that covers the full bandwidth of the input signal bw = 0.4 tb = 0.2 ripple = 0.1 #self._taps = filter.firdes.low_pass_2(self._size, self._size, bw, tb, atten) made = False while not made: try: self._taps = optfir.low_pass(self._size, self._size, bw, bw+tb, ripple, atten) made = True except RuntimeError: ripple += 0.01 made = False print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): raise RuntimeError("optfir could not generate an appropriate filter.") self.pfb = filter.pfb_arb_resampler_ccf(self._rate, self._taps, self._size) #print "PFB has %d taps\n" % (len(self._taps),) self.connect(self, self.pfb) self.connect(self.pfb, self) # Note -- set_taps not implemented in base class yet def set_taps(self, taps): self.pfb.set_taps(taps) def set_rate(self, rate): self.pfb.set_rate(rate) class arb_resampler_fff(gr.hier_block2): ''' Convenience wrapper for the polyphase filterbank arbitrary resampler. The block takes a single float stream in and outputs a single float stream out. As such, it requires no extra glue to handle the input/output streams. This block is provided to be consistent with the interface to the other PFB block. ''' def __init__(self, rate, taps=None, flt_size=32, atten=100): gr.hier_block2.__init__(self, "pfb_arb_resampler_fff", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature self._rate = rate self._size = flt_size if (taps is not None) and (len(taps) > 0): self._taps = taps else: # Create a filter that covers the full bandwidth of the input signal bw = 0.4 tb = 0.2 ripple = 0.1 #self._taps = filter.firdes.low_pass_2(self._size, self._size, bw, tb, atten) made = False while not made: try: self._taps = optfir.low_pass(self._size, self._size, bw, bw+tb, ripple, atten) made = True except RuntimeError: ripple += 0.01 made = False print("Warning: set ripple to %.4f dB. If this is a problem, adjust the attenuation or create your own filter taps." % (ripple)) # Build in an exit strategy; if we've come this far, it ain't working. if(ripple >= 1.0): raise RuntimeError("optfir could not generate an appropriate filter.") self.pfb = filter.pfb_arb_resampler_fff(self._rate, self._taps, self._size) #print "PFB has %d taps\n" % (len(self._taps),) self.connect(self, self.pfb) self.connect(self.pfb, self) # Note -- set_taps not implemented in base class yet def set_taps(self, taps): self.pfb.set_taps(taps) def set_rate(self, rate): self.pfb.set_rate(rate) gnuradio-3.7.2.1/gr-filter/python/filter/qa_pm_remez.py0000775000175000017500000001336412207440367022715 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, filter import sys, math # ---------------------------------------------------------------- # See optfir for an explanation of these. def stopband_atten_to_dev (atten_db): """Convert a stopband attenuation in dB to an absolute value""" return 10**(-atten_db/20) def passband_ripple_to_dev (ripple_db): """Convert passband ripple spec expressed in dB to an absolute value""" return (10**(ripple_db/20)-1)/(10**(ripple_db/20)+1) # ---------------------------------------------------------------- def remezord (fcuts, mags, devs, fsamp = 2): ''' FIR order estimator (lowpass, highpass, bandpass, mulitiband). ''' # get local copies fcuts = fcuts[:] mags = mags[:] devs = devs[:] for i in range (len (fcuts)): fcuts[i] = float (fcuts[i]) / fsamp nf = len (fcuts) nm = len (mags) nd = len (devs) nbands = nm if nm != nd: raise ValueError, "Length of mags and devs must be equal" if nf != 2 * (nbands - 1): raise ValueError, "Length of f must be 2 * len (mags) - 2" for i in range (len (mags)): if mags[i] != 0: # if not stopband, get relative deviation devs[i] = devs[i] / mags[i] # separate the passband and stopband edges f1 = fcuts[0::2] f2 = fcuts[1::2] n = 0 min_delta = 2 for i in range (len (f1)): if f2[i] - f1[i] < min_delta: n = i min_delta = f2[i] - f1[i] if nbands == 2: # lowpass or highpass case (use formula) l = lporder (f1[n], f2[n], devs[0], devs[1]) else: # bandpass or multipass case # try different lowpasses and take the worst one that # goes through the BP specs l = 0 for i in range (1, nbands-1): l1 = lporder (f1[i-1], f2[i-1], devs[i], devs[i-1]) l2 = lporder (f1[i], f2[i], devs[i], devs[i+1]) l = max (l, l1, l2) n = int (math.ceil (l)) - 1 # need order, not length for remez # cook up remez compatible result ff = [0] + fcuts + [1] for i in range (1, len (ff) - 1): ff[i] *= 2 aa = [] for a in mags: aa = aa + [a, a] max_dev = max (devs) wts = [1] * len(devs) for i in range (len (wts)): wts[i] = max_dev / devs[i] return (n, ff, aa, wts) def lporder (freq1, freq2, delta_p, delta_s): ''' FIR lowpass filter length estimator. ''' df = abs (freq2 - freq1) ddp = math.log10 (delta_p) dds = math.log10 (delta_s) a1 = 5.309e-3 a2 = 7.114e-2 a3 = -4.761e-1 a4 = -2.66e-3 a5 = -5.941e-1 a6 = -4.278e-1 b1 = 11.01217 b2 = 0.5124401 t1 = a1 * ddp * ddp t2 = a2 * ddp t3 = a4 * ddp * ddp t4 = a5 * ddp dinf=((t1 + t2 + a3) * dds) + (t3 + t4 + a6) ff = b1 + b2 * (ddp - dds) n = dinf / df - ff * df + 1 return n # ---------------------------------------------------------------- class test_pm_remez(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_low_pass(self): gain = 1 Fs = 1 freq1 = 0.1 freq2 = 0.2 passband_ripple_db = 0.01 stopband_atten_db = 60 passband_dev = passband_ripple_to_dev(passband_ripple_db) stopband_dev = stopband_atten_to_dev(stopband_atten_db) desired_ampls = (gain, 0) (n, fo, ao, w) = remezord([freq1, freq2], desired_ampls, [passband_dev, stopband_dev], Fs) new_taps = filter.pm_remez(n + 2, fo, ao, w, "bandpass") known_taps = (-0.0008370135734511828, -0.0006622211673134374, 0.0008501079576365787, 0.003059609130249229, 0.003202235537205373, -0.001000899296974219, -0.007589728680590891, -0.009790921118281865, -0.001524210202628562, 0.014373535837200111, 0.02392881326993834, 0.011798133085019008, -0.021954446348997188, -0.05293436740264934, -0.04375787096766848, 0.028038890498420392, 0.14612655590172896, 0.25738578419108626, 0.302967004188747, 0.25738578419108626, 0.14612655590172896, 0.028038890498420392, -0.04375787096766848, -0.05293436740264934, -0.021954446348997188, 0.011798133085019008, 0.02392881326993834, 0.014373535837200111, -0.001524210202628562, -0.009790921118281865, -0.007589728680590891, -0.001000899296974219, 0.003202235537205373, 0.003059609130249229, 0.0008501079576365787, -0.0006622211673134374, -0.0008370135734511828) self.assertFloatTuplesAlmostEqual(known_taps, new_taps, 5) if __name__ == '__main__': gr_unittest.run(test_pm_remez, "test_pm_remez.xml") gnuradio-3.7.2.1/gr-filter/python/filter/design/0000775000175000017500000000000012207440367021303 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/python/filter/design/CMakeLists.txt0000664000175000017500000000200612207440367024041 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES api_object.py filter_design.py fir_design.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/filter COMPONENT "filter_python" ) gnuradio-3.7.2.1/gr-filter/python/filter/design/api_object.py0000664000175000017500000000514312207440367023757 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # class ApiObject(): ''' Filter count variable if the filter design tool has to return multiple filter paramters in future e.g Cascaded Filters ''' def __init__(self, filtcount = 1): self.filtercount = filtcount self.restype = [''] * self.filtercount self.params = [''] * self.filtercount self.taps = [''] * self.filtercount ''' Updates params dictionary for the given filter number ''' def update_params(self, params, filtno): if (filtno <= self.filtercount): self.params[filtno - 1] = params ''' Updates filter type for the given filter number ''' def update_filttype(self, filttype, filtno): if (filtno <= self.filtercount): self.filttype[filtno - 1] = filttype ''' updates taps for the given filter number. taps will contain a list of coefficients in the case of fir design and (b,a) tuple in the case of iir design ''' def update_taps(self, taps, filtno): if (filtno <= self.filtercount): self.taps[filtno - 1] = taps ''' updates all of them in a single call ''' def update_all(self, filttype, params, taps, filtno): if (filtno <= self.filtercount): self.taps[filtno - 1] = taps self.params[filtno - 1] = params self.restype[filtno - 1] = filttype def get_filtercount(self): return self.filtercount def get_restype(self, filtno=1): if (filtno <= self.filtercount): return self.restype[filtno - 1] def get_params(self, filtno=1): if (filtno <= self.filtercount): return self.params[filtno - 1] def get_taps(self, filtno=1): if (filtno <= self.filtercount): return self.taps[filtno - 1] gnuradio-3.7.2.1/gr-filter/python/filter/design/filter_design.py0000664000175000017500000030171712207440367024504 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys, os, re, csv, copy import warnings from optparse import OptionParser from gnuradio import filter try: import scipy from scipy import fftpack, poly1d, signal except ImportError: print "Please install SciPy to run this script (http://www.scipy.org/)" raise SystemExit, 1 try: from PyQt4 import Qt, QtCore, QtGui except ImportError: print "Please install PyQt4 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)" raise SystemExit, 1 try: import PyQt4.Qwt5 as Qwt except ImportError: print "Please install PyQwt5 to run this script (http://pyqwt.sourceforge.net/)" raise SystemExit, 1 try: from gnuradio.filter.pyqt_filter_stacked import Ui_MainWindow except ImportError: print "Could not import from pyqt_filter_stacked. Please build with \"pyuic4 pyqt_filter_stacked.ui -o pyqt_filter_stacked.py\"" raise SystemExit, 1 try: from gnuradio.filter.banditems import * except ImportError: print "Could not import from banditems. Please check whether banditems.py is in the library path" raise SystemExit, 1 try: from gnuradio.filter.polezero_plot import * except ImportError: print "Could not import from polezero_plot. Please check whether polezero_plot.py is in the library path" raise SystemExit, 1 try: from gnuradio.filter.idealbanditems import * except ImportError: print "Could not import from idealbanditems. Please check whether idealbanditems.py is in the library path" raise SystemExit, 1 try: from gnuradio.filter.api_object import * except ImportError: print "Could not import from api_object. Please check whether api_object.py is in the library path" raise SystemExit, 1 try: from gnuradio.filter.fir_design import * except ImportError: print "Could not import from fir_design. Please check whether fir_design.py is in the library path" raise SystemExit, 1 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s # Gnuradio Filter design tool main window class gr_plot_filter(QtGui.QMainWindow): def __init__(self, options, callback=None, restype=""): QtGui.QWidget.__init__(self, None) self.gui = Ui_MainWindow() self.callback = callback self.gui.setupUi(self) #Remove other filter combobox entry if #some restriction is specified if restype == "iir": ind = self.gui.fselectComboBox.findText("FIR") if ind != -1: self.gui.fselectComboBox.removeItem(ind) elif restype == "fir": ind = self.gui.fselectComboBox.findText("IIR(scipy)") if ind != -1: self.gui.fselectComboBox.removeItem(ind) self.connect(self.gui.action_save, Qt.SIGNAL("activated()"), self.action_save_dialog) self.connect(self.gui.action_open, Qt.SIGNAL("activated()"), self.action_open_dialog) self.connect(self.gui.filterTypeComboBox, Qt.SIGNAL("currentIndexChanged(const QString&)"), self.changed_filter_type) self.connect(self.gui.iirfilterBandComboBox, Qt.SIGNAL("currentIndexChanged(const QString&)"), self.changed_iirfilter_band) self.connect(self.gui.filterDesignTypeComboBox, Qt.SIGNAL("currentIndexChanged(const QString&)"), self.changed_filter_design_type) self.connect(self.gui.fselectComboBox, Qt.SIGNAL("currentIndexChanged(const QString&)"), self.changed_fselect) self.connect(self.gui.iirfilterTypeComboBox, Qt.SIGNAL("currentIndexChanged(const QString&)"), self.set_order) self.connect(self.gui.designButton, Qt.SIGNAL("released()"), self.design) # self.connect(self.gui.tabGroup, # Qt.SIGNAL("currentChanged(int)"), # self.tab_changed) self.connect(self.gui.nfftEdit, Qt.SIGNAL("textEdited(QString)"), self.nfft_edit_changed) self.connect(self.gui.actionQuick_Access, Qt.SIGNAL("activated()"), self.action_quick_access) self.connect(self.gui.actionSpec_Widget, Qt.SIGNAL("activated()"), self.action_spec_widget) self.connect(self.gui.actionResponse_Widget, Qt.SIGNAL("activated()"), self.action_response_widget) self.connect(self.gui.actionDesign_Widget, Qt.SIGNAL("activated()"), self.action_design_widget) self.connect(self.gui.actionMagnitude_Response, Qt.SIGNAL("activated()"), self.set_actmagresponse) self.connect(self.gui.actionGrid_2, Qt.SIGNAL("activated()"), self.set_actgrid) self.connect(self.gui.actionPhase_Respone, Qt.SIGNAL("activated()"), self.set_actphase) self.connect(self.gui.actionGroup_Delay, Qt.SIGNAL("activated()"), self.set_actgdelay) self.connect(self.gui.actionFilter_Coefficients, Qt.SIGNAL("activated()"), self.set_actfcoeff) self.connect(self.gui.actionBand_Diagram, Qt.SIGNAL("activated()"), self.set_actband) self.connect(self.gui.actionIdeal_Band, Qt.SIGNAL("activated()"), self.set_drawideal) self.connect(self.gui.actionPole_Zero_Plot_2, Qt.SIGNAL("activated()"), self.set_actpzplot) self.connect(self.gui.actionGridview, Qt.SIGNAL("activated()"), self.set_switchview) self.connect(self.gui.actionPlot_select, Qt.SIGNAL("activated()"), self.set_plotselect) self.connect(self.gui.actionPhase_Delay, Qt.SIGNAL("activated()"), self.set_actpdelay) self.connect(self.gui.actionImpulse_Response, Qt.SIGNAL("activated()"), self.set_actimpres) self.connect(self.gui.actionStep_Response, Qt.SIGNAL("activated()"), self.set_actstepres) self.connect(self.gui.mfmagPush, Qt.SIGNAL("released()"), self.set_mfmagresponse) self.connect(self.gui.mfphasePush, Qt.SIGNAL("released()"), self.set_mfphaseresponse) self.connect(self.gui.mfgpdlyPush, Qt.SIGNAL("released()"), self.set_mfgroupdelay) self.connect(self.gui.mfphdlyPush, Qt.SIGNAL("released()"), self.set_mfphasedelay) self.connect(self.gui.mfoverlayPush, Qt.SIGNAL("clicked()"), self.set_mfoverlay) self.connect(self.gui.conjPush, Qt.SIGNAL("clicked()"), self.set_conj) self.connect(self.gui.mconjPush, Qt.SIGNAL("clicked()"), self.set_mconj) self.connect(self.gui.addzeroPush, Qt.SIGNAL("clicked()"), self.set_zeroadd) self.connect(self.gui.maddzeroPush, Qt.SIGNAL("clicked()"), self.set_mzeroadd) self.connect(self.gui.addpolePush, Qt.SIGNAL("clicked()"), self.set_poleadd) self.connect(self.gui.maddpolePush, Qt.SIGNAL("clicked()"), self.set_mpoleadd) self.connect(self.gui.delPush, Qt.SIGNAL("clicked()"), self.set_delpz) self.connect(self.gui.mdelPush, Qt.SIGNAL("clicked()"), self.set_mdelpz) self.connect(self.gui.mttapsPush, Qt.SIGNAL("clicked()"), self.set_mttaps) self.connect(self.gui.mtstepPush, Qt.SIGNAL("clicked()"), self.set_mtstep) self.connect(self.gui.mtimpPush, Qt.SIGNAL("clicked()"), self.set_mtimpulse) self.connect(self.gui.checkKeepcur, Qt.SIGNAL("stateChanged(int)"), self.set_bufferplots) self.connect(self.gui.checkGrid, Qt.SIGNAL("stateChanged(int)"), self.set_grid) self.connect(self.gui.checkMagres, Qt.SIGNAL("stateChanged(int)"), self.set_magresponse) self.connect(self.gui.checkGdelay, Qt.SIGNAL("stateChanged(int)"), self.set_gdelay) self.connect(self.gui.checkPhase, Qt.SIGNAL("stateChanged(int)"), self.set_phase) self.connect(self.gui.checkFcoeff, Qt.SIGNAL("stateChanged(int)"), self.set_fcoeff) self.connect(self.gui.checkBand, Qt.SIGNAL("stateChanged(int)"), self.set_band) self.connect(self.gui.checkPzplot, Qt.SIGNAL("stateChanged(int)"), self.set_pzplot) self.connect(self.gui.checkPdelay, Qt.SIGNAL("stateChanged(int)"), self.set_pdelay) self.connect(self.gui.checkImpulse, Qt.SIGNAL("stateChanged(int)"), self.set_impres) self.connect(self.gui.checkStep, Qt.SIGNAL("stateChanged(int)"), self.set_stepres) self.gridenable = False self.mfoverlay = False self.mtoverlay = False self.iir = False self.gui.designButton.setShortcut(QtCore.Qt.Key_Return) self.taps = [] self.a = [] self.b = [] self.fftdB = [] self.fftDeg = [] self.groupDelay = [] self.phaseDelay = [] self.gridview = 0 self.params = [] self.nfftpts = int(10000) self.gui.nfftEdit.setText(Qt.QString("%1").arg(self.nfftpts)) self.firFilters = ("Low Pass", "Band Pass", "Complex Band Pass", "Band Notch", "High Pass", "Root Raised Cosine", "Gaussian", "Half Band") self.optFilters = ("Low Pass", "Band Pass", "Complex Band Pass", "Band Notch", "High Pass", "Half Band") self.set_windowed() # Initialize to LPF self.gui.filterTypeWidget.setCurrentWidget(self.gui.firlpfPage) self.gui.iirfilterTypeComboBox.hide() self.gui.iirfilterBandComboBox.hide() self.gui.adComboBox.hide() self.gui.addpolePush.setEnabled(False) self.gui.maddpolePush.setEnabled(False) # Set Axis labels fxtitle = Qwt.QwtText("Frequency (Hz)") fxtitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) fytitle = Qwt.QwtText("Magnitude (dB)") fytitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.xBottom, fxtitle) self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.yLeft, fytitle) txtitle = Qwt.QwtText("Tap number") txtitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) tytitle = Qwt.QwtText("Amplitude") tytitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) self.gui.timePlot.setAxisTitle(self.gui.timePlot.xBottom, txtitle) self.gui.timePlot.setAxisTitle(self.gui.timePlot.yLeft, tytitle) pytitle = Qwt.QwtText("Phase (Radians)") pytitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) self.gui.phasePlot.setAxisTitle(self.gui.phasePlot.xBottom, fxtitle) self.gui.phasePlot.setAxisTitle(self.gui.phasePlot.yLeft, pytitle) gytitle = Qwt.QwtText("Delay (sec)") gytitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) self.gui.groupPlot.setAxisTitle(self.gui.groupPlot.xBottom, fxtitle) self.gui.groupPlot.setAxisTitle(self.gui.groupPlot.yLeft, gytitle) impytitle = Qwt.QwtText("Amplitude") impytitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) impxtitle = Qwt.QwtText("n (Samples)") impxtitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) self.gui.impresPlot.setAxisTitle(self.gui.freqPlot.xBottom, impxtitle) self.gui.impresPlot.setAxisTitle(self.gui.freqPlot.yLeft, impytitle) self.gui.stepresPlot.setAxisTitle(self.gui.freqPlot.xBottom, impxtitle) self.gui.stepresPlot.setAxisTitle(self.gui.freqPlot.yLeft, impytitle) mtytitle = Qwt.QwtText("Amplitude") mtytitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) mtxtitle = Qwt.QwtText("n (Samples/taps)") mtxtitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) self.gui.mtimePlot.setAxisTitle(self.gui.freqPlot.xBottom, mtxtitle) self.gui.mtimePlot.setAxisTitle(self.gui.freqPlot.yLeft, mtytitle) phytitle = Qwt.QwtText("Phase Delay") phytitle.setFont(Qt.QFont("Helvetica", 11, Qt.QFont.Bold)) self.gui.pdelayPlot.setAxisTitle(self.gui.groupPlot.xBottom, fxtitle) self.gui.pdelayPlot.setAxisTitle(self.gui.groupPlot.yLeft, phytitle) # Set up plot curves self.rcurve = Qwt.QwtPlotCurve("Real") self.rcurve.attach(self.gui.timePlot) self.icurve = Qwt.QwtPlotCurve("Imag") self.icurve.attach(self.gui.timePlot) self.freqcurve = Qwt.QwtPlotCurve("PSD") self.freqcurve.attach(self.gui.freqPlot) self.phasecurve = Qwt.QwtPlotCurve("Phase") self.phasecurve.attach(self.gui.phasePlot) self.groupcurve = Qwt.QwtPlotCurve("Group Delay") self.groupcurve.attach(self.gui.groupPlot) self.imprescurve = Qwt.QwtPlotCurve("Impulse Response") self.imprescurve.attach(self.gui.impresPlot) self.imprescurve_i = Qwt.QwtPlotCurve("Impulse Response Imag") self.imprescurve_i.attach(self.gui.impresPlot) self.steprescurve = Qwt.QwtPlotCurve("Step Response") self.steprescurve.attach(self.gui.stepresPlot) self.steprescurve_i = Qwt.QwtPlotCurve("Step Response Imag") self.steprescurve_i.attach(self.gui.stepresPlot) self.pdelaycurve = Qwt.QwtPlotCurve("Phase Delay") self.pdelaycurve.attach(self.gui.pdelayPlot) self.idbanditems = IdealBandItems() self.set_defaultpen() #Antialiasing self.rcurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.icurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.freqcurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.phasecurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.groupcurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.imprescurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.imprescurve_i.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.steprescurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.steprescurve_i.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) self.pdelaycurve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased); #Create grid for plots self.freqgrid = Qwt.QwtPlotGrid() self.phasegrid = Qwt.QwtPlotGrid() self.groupgrid = Qwt.QwtPlotGrid() self.impresgrid = Qwt.QwtPlotGrid() self.stepresgrid = Qwt.QwtPlotGrid() self.pdelaygrid = Qwt.QwtPlotGrid() self.ftapsgrid = Qwt.QwtPlotGrid() self.freqgrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) self.phasegrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) self.groupgrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) self.impresgrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) self.stepresgrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) self.pdelaygrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) self.ftapsgrid.setPen(Qt.QPen(Qt.Qt.black, 0, Qt.Qt.DotLine)) # Create zoom functionality for the plots self.timeZoomer = Qwt.QwtPlotZoomer(self.gui.timePlot.xBottom, self.gui.timePlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.timePlot.canvas()) self.mtimeZoomer = Qwt.QwtPlotZoomer(self.gui.mtimePlot.xBottom, self.gui.mtimePlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.mtimePlot.canvas()) self.mtimeZoomer2 = Qwt.QwtPlotZoomer(self.gui.mtimePlot.xBottom, self.gui.mtimePlot.yRight, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOff, self.gui.mtimePlot.canvas()) self.freqZoomer = Qwt.QwtPlotZoomer(self.gui.freqPlot.xBottom, self.gui.freqPlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.freqPlot.canvas()) self.mfreqZoomer = Qwt.QwtPlotZoomer(self.gui.mfreqPlot.xBottom, self.gui.mfreqPlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.mfreqPlot.canvas()) self.mfreqZoomer2 = Qwt.QwtPlotZoomer(self.gui.mfreqPlot.xBottom, self.gui.mfreqPlot.yRight, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOff, self.gui.mfreqPlot.canvas()) self.phaseZoomer = Qwt.QwtPlotZoomer(self.gui.phasePlot.xBottom, self.gui.phasePlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.phasePlot.canvas()) self.groupZoomer = Qwt.QwtPlotZoomer(self.gui.groupPlot.xBottom, self.gui.groupPlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.groupPlot.canvas()) self.impresZoomer = Qwt.QwtPlotZoomer(self.gui.groupPlot.xBottom, self.gui.groupPlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.impresPlot.canvas()) self.stepresZoomer = Qwt.QwtPlotZoomer(self.gui.groupPlot.xBottom, self.gui.groupPlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.stepresPlot.canvas()) self.pdelayZoomer = Qwt.QwtPlotZoomer(self.gui.groupPlot.xBottom, self.gui.groupPlot.yLeft, Qwt.QwtPicker.PointSelection, Qwt.QwtPicker.AlwaysOn, self.gui.pdelayPlot.canvas()) #Assigning items self.lpfitems = lpfItems self.hpfitems = hpfItems self.bpfitems = bpfItems self.bnfitems = bnfItems #Connect signals self.lpfitems[0].attenChanged.connect(self.set_fatten) self.hpfitems[0].attenChanged.connect(self.set_fatten) self.bpfitems[0].attenChanged.connect(self.set_fatten) self.bnfitems[0].attenChanged.connect(self.set_fatten) #Populate the Band-diagram scene self.scene = QtGui.QGraphicsScene() self.scene.setSceneRect(0,0,250,250) lightback = QtGui.qRgb(0xf8, 0xf8, 0xff) backbrush = Qt.QBrush(Qt.QColor(lightback)) self.scene.setBackgroundBrush(backbrush) self.gui.bandView.setScene(self.scene) self.gui.mbandView.setScene(self.scene) #Install Canvas picker for pz-plot self.cpicker = CanvasPicker(self.gui.pzPlot) self.cpicker.curveChanged.connect(self.set_curvetaps) self.cpicker.mouseposChanged.connect(self.set_statusbar) self.cpicker2 = CanvasPicker(self.gui.mpzPlot) self.cpicker2.curveChanged.connect(self.set_mcurvetaps) self.cpicker2.mouseposChanged.connect(self.set_mstatusbar) #Edit boxes for band-diagrams (Not required as far as now) """ self.lpfpassEdit=QtGui.QLineEdit() self.lpfpassEdit.setMaximumSize(QtCore.QSize(75,20)) self.lpfpassEdit.setText(Qt.QString("Not set")) self.lpfstartproxy=QtGui.QGraphicsProxyWidget() self.lpfstartproxy.setWidget(self.lpfpassEdit) self.lpfstartproxy.setPos(400,30) self.lpfstopEdit=QtGui.QLineEdit() self.lpfstopEdit.setMaximumSize(QtCore.QSize(75,20)) self.lpfstopEdit.setText(Qt.QString("Not set")) self.lpfstopproxy=QtGui.QGraphicsProxyWidget() self.lpfstopproxy.setWidget(self.lpfstopEdit) self.lpfstopproxy.setPos(400,50) self.lpfitems.append(self.lpfstartproxy) self.lpfitems.append(self.lpfstopproxy) """ self.populate_bandview(self.lpfitems) # Set up validators for edit boxes self.intVal = Qt.QIntValidator(None) self.dblVal = Qt.QDoubleValidator(None) self.gui.nfftEdit.setValidator(self.intVal) self.gui.sampleRateEdit.setValidator(self.dblVal) self.gui.filterGainEdit.setValidator(self.dblVal) self.gui.endofLpfPassBandEdit.setValidator(self.dblVal) self.gui.startofLpfStopBandEdit.setValidator(self.dblVal) self.gui.lpfStopBandAttenEdit.setValidator(self.dblVal) self.gui.lpfPassBandRippleEdit.setValidator(self.dblVal) self.gui.startofBpfPassBandEdit.setValidator(self.dblVal) self.gui.endofBpfPassBandEdit.setValidator(self.dblVal) self.gui.bpfTransitionEdit.setValidator(self.dblVal) self.gui.bpfStopBandAttenEdit.setValidator(self.dblVal) self.gui.bpfPassBandRippleEdit.setValidator(self.dblVal) self.gui.startofBnfStopBandEdit.setValidator(self.dblVal) self.gui.endofBnfStopBandEdit.setValidator(self.dblVal) self.gui.bnfTransitionEdit.setValidator(self.dblVal) self.gui.bnfStopBandAttenEdit.setValidator(self.dblVal) self.gui.bnfPassBandRippleEdit.setValidator(self.dblVal) self.gui.endofHpfStopBandEdit.setValidator(self.dblVal) self.gui.startofHpfPassBandEdit.setValidator(self.dblVal) self.gui.hpfStopBandAttenEdit.setValidator(self.dblVal) self.gui.hpfPassBandRippleEdit.setValidator(self.dblVal) self.gui.rrcSymbolRateEdit.setValidator(self.dblVal) self.gui.rrcAlphaEdit.setValidator(self.dblVal) self.gui.rrcNumTapsEdit.setValidator(self.dblVal) self.gui.gausSymbolRateEdit.setValidator(self.dblVal) self.gui.gausBTEdit.setValidator(self.dblVal) self.gui.gausNumTapsEdit.setValidator(self.dblVal) self.gui.nTapsEdit.setText("0") self.filterWindows = {"Hamming Window" : filter.firdes.WIN_HAMMING, "Hann Window" : filter.firdes.WIN_HANN, "Blackman Window" : filter.firdes.WIN_BLACKMAN, "Rectangular Window" : filter.firdes.WIN_RECTANGULAR, "Kaiser Window" : filter.firdes.WIN_KAISER, "Blackman-harris Window" : filter.firdes.WIN_BLACKMAN_hARRIS} self.EQUIRIPPLE_FILT = 6 # const for equiripple filter window types self.show() # Set up pen for colors and line width def set_defaultpen(self): blue = QtGui.qRgb(0x00, 0x00, 0xFF) blueBrush = Qt.QBrush(Qt.QColor(blue)) red = QtGui.qRgb(0xFF, 0x00, 0x00) redBrush = Qt.QBrush(Qt.QColor(red)) self.freqcurve.setPen(Qt.QPen(blueBrush, 1)) self.rcurve.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) self.rcurve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(Qt.Qt.blue), Qt.QSize(8, 8))) self.icurve.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) self.icurve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(Qt.Qt.red), Qt.QSize(8, 8))) self.imprescurve.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) self.imprescurve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(Qt.Qt.blue), Qt.QSize(8, 8))) self.imprescurve_i.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) self.imprescurve_i.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(Qt.Qt.red), Qt.QSize(8, 8))) self.steprescurve.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) self.steprescurve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(Qt.Qt.blue), Qt.QSize(8, 8))) self.steprescurve_i.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) self.steprescurve_i.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(Qt.Qt.red), Qt.QSize(8, 8))) self.phasecurve.setPen(Qt.QPen(blueBrush, 1)) self.groupcurve.setPen(Qt.QPen(blueBrush, 1)) self.pdelaycurve.setPen(Qt.QPen(blueBrush, 1)) self.idbanditems.setLinetype() def changed_fselect(self, ftype): strftype = str(ftype.toAscii()) if(ftype == "FIR"): self.gui.iirfilterTypeComboBox.hide() self.gui.iirfilterBandComboBox.hide() self.gui.adComboBox.hide() self.gui.filterDesignTypeComboBox.show() self.gui.globalParamsBox.show() self.gui.filterTypeComboBox.show() self.gui.filterTypeWidget.setCurrentWidget(self.gui.firlpfPage) self.gui.tabGroup.addTab(self.gui.timeTab, _fromUtf8("Filter Taps")) self.gui.mttapsPush.setEnabled(True) self.gui.addpolePush.setEnabled(False) self.gui.maddpolePush.setEnabled(False) elif(ftype == "IIR(scipy)"): self.gui.filterDesignTypeComboBox.hide() self.gui.globalParamsBox.hide() self.gui.filterTypeComboBox.hide() self.gui.iirfilterTypeComboBox.show() self.gui.adComboBox.show() self.gui.iirfilterBandComboBox.show() self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirlpfPage) self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.timeTab)) self.gui.mttapsPush.setEnabled(False) self.gui.addpolePush.setEnabled(True) self.gui.maddpolePush.setEnabled(True) #self.design() def set_order(self, ftype): strftype = str(ftype.toAscii()) if(ftype == "Bessel"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) else: self.changed_iirfilter_band(self.gui.iirfilterBandComboBox.currentText()) #self.design() def changed_iirfilter_band(self, ftype): strftype = str(ftype.toAscii()) iirftype = str(self.gui.iirfilterTypeComboBox.currentText().toAscii()) if(ftype == "Low Pass"): if(iirftype == "Bessel"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirlpfPage) elif(ftype == "Band Pass"): if(iirftype == "Bessel"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbpfPage) elif(ftype == "Band Stop"): if(iirftype == "Bessel"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbsfPage) elif(ftype == "High Pass"): if(iirftype == "Bessel"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirbesselPage) else: self.gui.filterTypeWidget.setCurrentWidget(self.gui.iirhpfPage) #self.design() def changed_filter_type(self, ftype): strftype = str(ftype.toAscii()) if(ftype == "Low Pass"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firlpfPage) self.remove_bandview() self.populate_bandview(self.lpfitems) elif(ftype == "Band Pass"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firbpfPage) self.remove_bandview() self.populate_bandview(self.bpfitems) elif(ftype == "Complex Band Pass"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firbpfPage) self.remove_bandview() self.populate_bandview(self.bpfitems) elif(ftype == "Band Notch"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firbnfPage) self.remove_bandview() self.populate_bandview(self.bnfitems) elif(ftype == "High Pass"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firhpfPage) self.remove_bandview() self.populate_bandview(self.hpfitems) elif(ftype == "Root Raised Cosine"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.rrcPage) elif(ftype == "Gaussian"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.gausPage) elif(ftype == "Half Band"): self.gui.filterTypeWidget.setCurrentWidget(self.gui.firhbPage) #self.design() def changed_filter_design_type(self, design): if(design == "Equiripple"): self.set_equiripple() else: self.set_windowed() #self.design() def set_equiripple(self): # Stop sending the signal for this function self.gui.filterTypeComboBox.blockSignals(True) self.equiripple = True self.gui.lpfPassBandRippleLabel.setVisible(True) self.gui.lpfPassBandRippleEdit.setVisible(True) self.gui.bpfPassBandRippleLabel.setVisible(True) self.gui.bpfPassBandRippleEdit.setVisible(True) self.gui.bnfPassBandRippleLabel.setVisible(True) self.gui.bnfPassBandRippleEdit.setVisible(True) self.gui.hpfPassBandRippleLabel.setVisible(True) self.gui.hpfPassBandRippleEdit.setVisible(True) # Save current type and repopulate the combo box for # filters this window type can handle currenttype = self.gui.filterTypeComboBox.currentText() items = self.gui.filterTypeComboBox.count() for i in xrange(items): self.gui.filterTypeComboBox.removeItem(0) self.gui.filterTypeComboBox.addItems(self.optFilters) # If the last filter type was valid for this window type, # go back to it; otherwise, reset try: index = self.optFilters.index(currenttype) self.gui.filterTypeComboBox.setCurrentIndex(index) except ValueError: pass # Tell gui its ok to start sending this signal again self.gui.filterTypeComboBox.blockSignals(False) def set_windowed(self): # Stop sending the signal for this function self.gui.filterTypeComboBox.blockSignals(True) self.equiripple = False self.gui.lpfPassBandRippleLabel.setVisible(False) self.gui.lpfPassBandRippleEdit.setVisible(False) self.gui.bpfPassBandRippleLabel.setVisible(False) self.gui.bpfPassBandRippleEdit.setVisible(False) self.gui.bnfPassBandRippleLabel.setVisible(False) self.gui.bnfPassBandRippleEdit.setVisible(False) self.gui.hpfPassBandRippleLabel.setVisible(False) self.gui.hpfPassBandRippleEdit.setVisible(False) # Save current type and repopulate the combo box for # filters this window type can handle currenttype = self.gui.filterTypeComboBox.currentText() items = self.gui.filterTypeComboBox.count() for i in xrange(items): self.gui.filterTypeComboBox.removeItem(0) self.gui.filterTypeComboBox.addItems(self.firFilters) # If the last filter type was valid for this window type, # go back to it; otherwise, reset try: index = self.optFilters.index(currenttype) self.gui.filterTypeComboBox.setCurrentIndex(index) except ValueError: pass # Tell gui its ok to start sending this signal again self.gui.filterTypeComboBox.blockSignals(False) def design(self): ret = True fs,r = self.gui.sampleRateEdit.text().toDouble() ret = r and ret gain,r = self.gui.filterGainEdit.text().toDouble() ret = r and ret winstr = str(self.gui.filterDesignTypeComboBox.currentText().toAscii()) ftype = str(self.gui.filterTypeComboBox.currentText().toAscii()) fsel = str(self.gui.fselectComboBox.currentText().toAscii()) if (fsel == "FIR"): self.b, self.a=[],[] if(ret): self.design_fir(ftype, fs, gain, winstr) elif (fsel == "IIR(scipy)"): with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") self.design_iir() if len(w): reply = QtGui.QMessageBox.information(self, "BadCoefficients", str(w[-1].message),"&Ok") # Do FIR design def design_fir(self, ftype, fs, gain, winstr): self.iir = False self.cpicker.set_iir(False) self.cpicker2.set_iir(False) if(winstr == "Equiripple"): designer = {"Low Pass" : design_opt_lpf, "Band Pass" : design_opt_bpf, "Complex Band Pass" : design_opt_cbpf, "Band Notch" : design_opt_bnf, "Half Band" : design_opt_hb, "High Pass" : design_opt_hpf} taps,params,r = designer[ftype](fs, gain, self) else: designer = {"Low Pass" : design_win_lpf, "Band Pass" : design_win_bpf, "Complex Band Pass" : design_win_cbpf, "Band Notch" : design_win_bnf, "High Pass" : design_win_hpf, "Half Band" : design_win_hb, "Root Raised Cosine" : design_win_rrc, "Gaussian" : design_win_gaus} wintype = self.filterWindows[winstr] taps,params,r = designer[ftype](fs, gain, wintype, self) if(r): if self.gridview: self.params = params self.update_fft(taps, params) self.set_mfmagresponse() self.set_mttaps() self.gui.nTapsEdit.setText(Qt.QString("%1").arg(self.taps.size)) else: self.draw_plots(taps,params) zeros=self.get_zeros() poles=self.get_poles() self.gui.pzPlot.insertZeros(zeros) self.gui.pzPlot.insertPoles(poles) self.gui.mpzPlot.insertZeros(zeros) self.gui.mpzPlot.insertPoles(poles) self.update_fcoeff() self.set_drawideal() #return taps if callback is enabled if self.callback: retobj = ApiObject() retobj.update_all("fir", self.params, self.taps, 1) self.callback(retobj) # Do IIR design def design_iir(self): iirftype = str(self.gui.iirfilterTypeComboBox.currentText().toAscii()) iirbtype = str(self.gui.iirfilterBandComboBox.currentText().toAscii()) atype = str(self.gui.adComboBox.currentText().toAscii()) self.taps = [] self.iir = True ret = True params = [] besselparams = [] self.cpicker.set_iir(True) self.cpicker2.set_iir(True) iirft = {"Elliptic" : 'ellip', "Butterworth" : 'butter', "Chebyshev-1" : 'cheby1', "Chebyshev-2" : 'cheby2', "Bessel" : 'bessel' } sanalog = {"Analog (rad/second)" : 1, "Digital (normalized 0-1)" : 0 } paramtype = { 1 : "analog", 0 : "digital" } iirabbr = { "Low Pass" : "lpf", "High Pass" : "hpf", "Band Pass" : "bpf", "Band Stop" : "bnf" } iirboxes = {"Low Pass" : [self.gui.iirendofLpfPassBandEdit.text().toDouble(), self.gui.iirstartofLpfStopBandEdit.text().toDouble(), self.gui.iirLpfPassBandAttenEdit.text().toDouble(), self.gui.iirLpfStopBandRippleEdit.text().toDouble()], "High Pass" : [self.gui.iirstartofHpfPassBandEdit.text().toDouble(), self.gui.iirendofHpfStopBandEdit.text().toDouble(), self.gui.iirHpfPassBandAttenEdit.text().toDouble(), self.gui.iirHpfStopBandRippleEdit.text().toDouble()], "Band Pass" : [self.gui.iirstartofBpfPassBandEdit.text().toDouble(), self.gui.iirendofBpfPassBandEdit.text().toDouble(), self.gui.iirendofBpfStopBandEdit1.text().toDouble(), self.gui.iirstartofBpfStopBandEdit2.text().toDouble(), self.gui.iirBpfPassBandAttenEdit.text().toDouble(), self.gui.iirBpfStopBandRippleEdit.text().toDouble()], "Band Stop" : [self.gui.iirendofBsfPassBandEdit1.text().toDouble(), self.gui.iirstartofBsfPassBandEdit2.text().toDouble(), self.gui.iirstartofBsfStopBandEdit.text().toDouble(), self.gui.iirendofBsfStopBandEdit.text().toDouble(), self.gui.iirBsfPassBandAttenEdit.text().toDouble(), self.gui.iirBsfStopBandRippleEdit.text().toDouble()] } #Remove Ideal band-diagrams if IIR self.set_drawideal() for i in range(len(iirboxes[iirbtype])): params.append(iirboxes[iirbtype][i][0]) ret = iirboxes[iirbtype][i][1] and ret if len(iirboxes[iirbtype]) == 6: params=[params[:2],params[2:4],params[4],params[5]] if(iirftype == "Bessel"): ret = True order,r = self.gui.besselordEdit.text().toDouble() if iirbtype == "Low Pass" or iirbtype == "High Pass": val,r = self.gui.iirbesselcritEdit1.text().toDouble() ret = ret and r besselparams.append(val) else: val,r = self.gui.iirbesselcritEdit1.text().toDouble() ret = ret and r besselparams.append(val) val,r = self.gui.iirbesselcritEdit2.text().toDouble() ret = ret and r besselparams.append(val) if(ret): if(iirftype == "Bessel"): try: (self.b,self.a) = signal.iirfilter(order, besselparams, btype=iirbtype.replace(' ','').lower(), analog=sanalog[atype], ftype=iirft[iirftype], output='ba') except StandardError, e: reply = QtGui.QMessageBox.information(self, "IIR design error", e.args[0], "&Ok") (self.z,self.p,self.k) = signal.tf2zpk(self.b,self.a) iirparams = { "filttype": iirft[iirftype],"bandtype": iirabbr[iirbtype], "filtord": order, "paramtype":paramtype[sanalog[atype]], "critfreq": besselparams} else: try: (self.b,self.a) = signal.iirdesign(params[0], params[1], params[2], params[3], analog=sanalog[atype], ftype=iirft[iirftype], output='ba') except StandardError, e: reply = QtGui.QMessageBox.information(self, "IIR design error", e.args[0], "&Ok") (self.z,self.p,self.k) = signal.tf2zpk(self.b,self.a) #Create params iirparams = { "filttype": iirft[iirftype], "bandtype": iirabbr[iirbtype],"paramtype":paramtype[sanalog[atype]], "pbedge": params[0], "sbedge": params[1],"gpass": params[2], "gstop": params[3]} self.gui.pzPlot.insertZeros(self.z) self.gui.pzPlot.insertPoles(self.p) self.gui.mpzPlot.insertZeros(self.z) self.gui.mpzPlot.insertPoles(self.p) self.iir_plot_all(self.z,self.p,self.k) self.update_fcoeff() self.gui.nTapsEdit.setText("-") self.params = iirparams #return api_object if callback is enabled if self.callback: retobj = ApiObject() retobj.update_all("iir", self.params, (self.b, self.a), 1) self.callback(retobj) # IIR Filter design plot updates def iir_plot_all(self,z,p,k): self.b,self.a = signal.zpk2tf(z,p,k) w,h = signal.freqz(self.b,self.a) self.fftdB = 20 * scipy.log10 (abs(h)) self.freq = w/max(w) self.fftDeg = scipy.unwrap(scipy.arctan2(imag(h),real(h))) self.groupDelay = -scipy.diff(self.fftDeg) self.phaseDelay = -self.fftDeg[1:]/self.freq[1:] if self.gridview: self.set_mfmagresponse() self.set_mtimpulse() else: self.update_freq_curves() self.update_phase_curves() self.update_group_curves() self.update_pdelay_curves() self.update_step_curves() self.update_imp_curves() def nfft_edit_changed(self, nfft): infft,r = nfft.toInt() if(r and (infft != self.nfftpts)): self.nfftpts = infft self.update_freq_curves() # def tab_changed(self, tab): # if(tab == 0): # self.update_freq_curves() # if(tab == 1): # self.update_time_curves() # if(tab == 2): # self.update_phase_curves() # if(tab == 3): # self.update_group_curves() def get_fft(self, fs, taps, Npts): Ts = 1.0/fs fftpts = fftpack.fft(taps, Npts) self.freq = scipy.arange(0, fs, 1.0/(Npts*Ts)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") self.fftdB = 20.0*scipy.log10(abs(fftpts)) if any(self.fftdB == float('-inf')): sys.stderr.write('Filter design failed (taking log10 of 0).\n') self.fftdB = scipy.zeros([len(fftpts)]) self.fftDeg = scipy.unwrap(scipy.angle(fftpts)) self.groupDelay = -scipy.diff(self.fftDeg) self.phaseDelay = -self.fftDeg[1:]/self.freq[1:] def update_time_curves(self): ntaps = len(self.taps) if(ntaps > 0): if(type(self.taps[0]) == scipy.complex128): self.rcurve.setData(scipy.arange(ntaps), self.taps.real) self.icurve.setData(scipy.arange(ntaps), self.taps.imag) ymax = 1.5 * max(max(self.taps.real),max(self.taps.imag)) ymin = 1.5 * min(min(self.taps.real),min(self.taps.imag)) else: self.rcurve.setData(scipy.arange(ntaps), self.taps) self.icurve.setData([],[]); ymax = 1.5 * max(self.taps) ymin = 1.5 * min(self.taps) # Reset the x-axis to the new time scale self.gui.timePlot.setAxisScale(self.gui.timePlot.xBottom, 0, ntaps) self.gui.timePlot.setAxisScale(self.gui.timePlot.yLeft, ymin, ymax) if self.mtoverlay: self.gui.mtimePlot.setAxisScale(self.rcurve.yAxis(), ymin, ymax) self.mtimeZoomer2.setEnabled(True) self.mtimeZoomer2.setZoomBase() else: self.mtimeZoomer2.setEnabled(False) self.gui.mtimePlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mtimePlot.setAxisScale(self.gui.mtimePlot.yLeft, ymin, ymax) # Set the zoomer base to unzoom to the new axis self.timeZoomer.setZoomBase() self.mtimeZoomer.setZoomBase() self.gui.timePlot.replot() self.gui.mtimePlot.replot() def update_step_curves(self): ntaps = len(self.taps) if(ntaps > 0 or self.iir): if self.iir: stepres=self.step_response(self.b,self.a) ntaps=50 else: stepres=self.step_response(self.taps) if(type(stepres[0]) == scipy.complex128): self.steprescurve.setData(scipy.arange(ntaps), stepres.real) self.steprescurve_i.setData(scipy.arange(ntaps), stepres.imag) symax = 1.5 * max(max(stepres.real),max(stepres.imag)) symin = 1.5 * min(min(stepres.real),min(stepres.imag)) else: self.steprescurve.setData(scipy.arange(ntaps), stepres) self.steprescurve_i.setData([],[]) symax = 1.5 * max(stepres) symin = 1.5 * min(stepres) # Reset the x-axis to the new time scale self.gui.stepresPlot.setAxisScale(self.gui.stepresPlot.xBottom, 0, ntaps) self.gui.stepresPlot.setAxisScale(self.gui.stepresPlot.yLeft, symin, symax) if self.mtoverlay: self.gui.mtimePlot.setAxisScale(self.steprescurve.yAxis(), symin, symax) self.mtimeZoomer2.setEnabled(True) self.mtimeZoomer2.setZoomBase() else: self.mtimeZoomer2.setEnabled(False) self.gui.mtimePlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mtimePlot.setAxisScale(self.gui.mtimePlot.yLeft, symin, symax) # Set the zoomer base to unzoom to the new axis self.mtimeZoomer.setZoomBase() self.stepresZoomer.setZoomBase() self.gui.mtimePlot.replot() self.gui.stepresPlot.replot() def update_imp_curves(self): ntaps = len(self.taps) if(ntaps > 0 or self.iir): if self.iir: impres=self.impulse_response(self.b, self.a) ntaps=50 else: impres=self.impulse_response(self.taps) if(type(impres[0]) == scipy.complex128): self.imprescurve.setData(scipy.arange(ntaps), impres.real) self.imprescurve_i.setData(scipy.arange(ntaps), impres.imag) iymax = 1.5 * max(max(impres.real),max(impres.imag)) iymin = 1.5 * min(min(impres.real),min(impres.imag)) else: self.imprescurve.setData(scipy.arange(ntaps), impres) self.imprescurve_i.setData([],[]) iymax = 1.5 * max(impres) iymin = 1.5 * min(impres) # Reset the x-axis to the new time scale self.gui.impresPlot.setAxisScale(self.gui.impresPlot.xBottom, 0, ntaps) self.gui.impresPlot.setAxisScale(self.gui.impresPlot.yLeft, iymin, iymax) if self.mtoverlay: self.gui.mtimePlot.setAxisScale(self.imprescurve.yAxis(), iymin, iymax) self.mtimeZoomer2.setEnabled(True) self.mtimeZoomer2.setZoomBase() else: self.mtimeZoomer2.setEnabled(False) self.gui.mtimePlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mtimePlot.setAxisScale(self.gui.mtimePlot.yLeft, iymin, iymax) # Set the zoomer base to unzoom to the new axis self.mtimeZoomer.setZoomBase() self.impresZoomer.setZoomBase() self.gui.mtimePlot.replot() self.gui.impresPlot.replot() def update_freq_curves(self): npts = len(self.fftdB) fxtitle=Qwt.QwtText("Frequency (Hz)") fxtitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) fytitle=Qwt.QwtText("Magnitude (dB)") fytitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) if(npts > 0): self.freqcurve.setData(self.freq, self.fftdB) # Reset the x-axis to the new time scale if self.iir: xmax = self.freq[npts-1] ymax = self.fftdB.max() if(ymax < 0): ymax = 0.8 * self.fftdB.max() ymin = 1.1 * self.fftdB.min() else: xmax = self.freq[npts/2] ymax = 1.5 * max(self.fftdB[0:npts/2]) ymin = 1.1 * min(self.fftdB[0:npts/2]) xmin = self.freq[0] self.gui.freqPlot.setAxisScale(self.gui.freqPlot.xBottom, xmin, xmax) self.gui.freqPlot.setAxisScale(self.gui.freqPlot.yLeft, ymin, ymax) if self.mfoverlay: self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.freqcurve.yAxis(), ymin, ymax) self.mfreqZoomer2.setEnabled(True) self.mfreqZoomer2.setZoomBase() else: self.mfreqZoomer2.setEnabled(False) self.gui.mfreqPlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.yLeft, ymin, ymax) #Set Axis title self.gui.mfreqPlot.setAxisTitle(self.freqcurve.yAxis(), fytitle) self.gui.mfreqPlot.setAxisTitle(self.freqcurve.xAxis(), fxtitle) # Set the zoomer base to unzoom to the new axis self.freqZoomer.setZoomBase() self.mfreqZoomer.setZoomBase() self.gui.freqPlot.replot() self.gui.mfreqPlot.replot() def update_phase_curves(self): pytitle=Qwt.QwtText("Phase (Radians)") pytitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) npts = len(self.fftDeg) if(npts > 0): self.phasecurve.setData(self.freq, self.fftDeg) # Reset the x-axis to the new time scale if self.iir: xmax = self.freq[npts-1] ymax = self.fftDeg.max() if(ymax < 0): ymax = 0.8 * self.fftDeg.max() ymin = 1.1 * self.fftDeg.min() else: ymax = 1.5 * max(self.fftDeg[0:npts/2]) ymin = 1.1 * min(self.fftDeg[0:npts/2]) xmax = self.freq[npts/2] xmin = self.freq[0] self.gui.phasePlot.setAxisScale(self.gui.phasePlot.xBottom, xmin, xmax) self.gui.phasePlot.setAxisScale(self.gui.phasePlot.yLeft, ymin, ymax) if self.mfoverlay: self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.phasecurve.yAxis(), ymin, ymax) self.mfreqZoomer2.setEnabled(True) self.mfreqZoomer2.setZoomBase() else: self.mfreqZoomer2.setEnabled(False) self.gui.mfreqPlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.yLeft, ymin, ymax) #Set Axis title self.gui.mfreqPlot.setAxisTitle(self.phasecurve.yAxis(), pytitle) # Set the zoomer base to unzoom to the new axis self.phaseZoomer.setZoomBase() self.mfreqZoomer.setZoomBase() self.gui.phasePlot.replot() self.gui.mfreqPlot.replot() def update_group_curves(self): gytitle=Qwt.QwtText("Delay (sec)") gytitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) npts = len(self.groupDelay) if(npts > 0): self.groupcurve.setData(self.freq, self.groupDelay) # Reset the x-axis to the new time scale if self.iir: xmax = self.freq[npts-1] ymax = self.groupDelay.max() if(ymax < 0): ymax = 0.8 * self.groupDelay.max() ymin = 1.1 * self.groupDelay.min() else: ymax = 1.5 * max(self.groupDelay[0:npts/2]) ymin = 1.1 * min(self.groupDelay[0:npts/2]) xmax = self.freq[npts/2] xmin = self.freq[0] self.gui.groupPlot.setAxisScale(self.gui.groupPlot.xBottom, xmin, xmax) self.gui.groupPlot.setAxisScale(self.gui.groupPlot.yLeft, ymin, ymax) if self.mfoverlay: self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.groupcurve.yAxis(), ymin, ymax) self.mfreqZoomer2.setEnabled(True) self.mfreqZoomer2.setZoomBase() else: self.mfreqZoomer2.setEnabled(False) self.gui.mfreqPlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.yLeft, ymin, ymax) #Set Axis title self.gui.mfreqPlot.setAxisTitle(self.groupcurve.yAxis(), gytitle) # Set the zoomer base to unzoom to the new axis self.groupZoomer.setZoomBase() self.mfreqZoomer.setZoomBase() self.gui.groupPlot.replot() self.gui.mfreqPlot.replot() def update_pdelay_curves(self): phytitle=Qwt.QwtText("Phase Delay") phytitle.setFont(Qt.QFont("Helvetica", 9, Qt.QFont.Bold)) npts = len(self.phaseDelay) if(npts > 0): self.pdelaycurve.setData(self.freq, self.phaseDelay) # Reset the x-axis to the new time scale if self.iir: xmax = self.freq[npts-1] ymax = self.phaseDelay.max() if(ymax < 0): ymax = 0.8 * self.phaseDelay.max() ymin = 1.1 * self.phaseDelay.min() else: ymax = 1.3 * max(self.phaseDelay[0:npts]) ymin = 0.8 * min(self.phaseDelay[0:npts]) xmax = self.freq[npts/2] xmin = self.freq[0] self.gui.pdelayPlot.setAxisScale(self.gui.pdelayPlot.xBottom, xmin, xmax) self.gui.pdelayPlot.setAxisScale(self.gui.pdelayPlot.yLeft, ymin, ymax) if self.mfoverlay: self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.pdelaycurve.yAxis(), ymin, ymax) self.mfreqZoomer2.setEnabled(True) self.mfreqZoomer2.setZoomBase() else: self.mfreqZoomer2.setEnabled(False) self.gui.mfreqPlot.enableAxis(Qwt.QwtPlot.yRight,False) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.xBottom, xmin, xmax) self.gui.mfreqPlot.setAxisScale(self.gui.mfreqPlot.yLeft, ymin, ymax) #Set Axis title self.gui.mfreqPlot.setAxisTitle(self.pdelaycurve.yAxis(), phytitle) # Set the zoomer base to unzoom to the new axis self.pdelayZoomer.setZoomBase() self.mfreqZoomer.setZoomBase() self.gui.pdelayPlot.replot() self.gui.mfreqPlot.replot() def action_quick_access(self): #Hides quick access widget if unselected if (self.gui.quickFrame.isHidden()): self.gui.quickFrame.show() else: self.gui.quickFrame.hide() def action_spec_widget(self): #Hides spec widget if unselected if (self.gui.filterspecView.isHidden()): self.gui.filterspecView.show() else: self.gui.filterspecView.hide() def action_response_widget(self): if (self.gui.tabGroup.isHidden()): self.gui.tabGroup.show() else: self.gui.tabGroup.hide() def action_design_widget(self): #Hides design widget if unselected if (self.gui.filterFrame.isHidden()): self.gui.filterFrame.show() else: self.gui.filterFrame.hide() #Saves and attach the plots for comparison def set_bufferplots(self): if (self.gui.checkKeepcur.checkState() == 0 ): #Detach and delete all plots if unchecked for c in self.bufferplots: c.detach() self.replot_all() self.bufferplots = [] else: self.bufferplots = [] #Iterate through tabgroup children and copy curves for i in range(self.gui.tabGroup.count()): page = self.gui.tabGroup.widget(i) for item in page.children(): if isinstance(item, Qwt.QwtPlot): #Change colours as both plots overlay colours = [QtCore.Qt.darkYellow,QtCore.Qt.black] for c in item.itemList(): if isinstance(c, Qwt.QwtPlotCurve): dup = Qwt.QwtPlotCurve() dpen = c.pen() dsym = c.symbol() dsym.setPen(Qt.QPen(colours[0])) dsym.setSize(Qt.QSize(6, 6)) dpen.setColor(colours[0]) del colours[0] dup.setPen(dpen) dup.setSymbol(dsym) dup.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) dup.setData([c.x(i) for i in range(c.dataSize())], [c.y(i) for i in range(c.dataSize())]) self.bufferplots.append(dup) self.bufferplots[-1].attach(item) def set_grid(self): if (self.gui.checkGrid.checkState() == 0 ): self.gridenable=False self.detach_allgrid() self.replot_all() else: self.gridenable=True if self.gridview: self.freqgrid.attach(self.gui.mfreqPlot) self.ftapsgrid.attach(self.gui.mtimePlot) self.gui.mfreqPlot.replot() self.gui.mtimePlot.replot() else: self.freqgrid.attach(self.gui.freqPlot) self.phasegrid.attach(self.gui.phasePlot) self.groupgrid.attach(self.gui.groupPlot) self.impresgrid.attach(self.gui.impresPlot) self.stepresgrid.attach(self.gui.stepresPlot) self.pdelaygrid.attach(self.gui.pdelayPlot) self.ftapsgrid.attach(self.gui.timePlot) self.replot_all() def set_actgrid(self): if (self.gui.actionGrid_2.isChecked() == 0 ): self.gridenable=False self.detach_allgrid() self.replot_all() else: self.gridenable=True if self.gridview: self.freqgrid.attach(self.gui.mfreqPlot) self.ftapsgrid.attach(self.gui.mtimePlot) self.gui.mfreqPlot.replot() self.gui.mtimePlot.replot() else: self.freqgrid.attach(self.gui.freqPlot) self.phasegrid.attach(self.gui.phasePlot) self.groupgrid.attach(self.gui.groupPlot) self.impresgrid.attach(self.gui.impresPlot) self.stepresgrid.attach(self.gui.stepresPlot) self.pdelaygrid.attach(self.gui.pdelayPlot) self.ftapsgrid.attach(self.gui.timePlot) self.replot_all() def set_magresponse(self): if (self.gui.checkMagres.checkState() == 0 ): self.magres=False self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.freqTab)) else: self.magres=True self.gui.tabGroup.addTab(self.gui.freqTab, _fromUtf8("Magnitude Response")) self.update_freq_curves() def set_actmagresponse(self): if (self.gui.actionMagnitude_Response.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.freqTab)) else: self.gui.tabGroup.addTab(self.gui.freqTab, _fromUtf8("Magnitude Response")) self.update_freq_curves() def set_switchview(self): if (self.gui.actionGridview.isChecked() == 0 ): self.gridview=0 self.set_defaultpen() self.set_actgrid() self.gui.stackedWindows.setCurrentIndex(0) self.freqcurve.attach(self.gui.freqPlot) self.phasecurve.attach(self.gui.phasePlot) self.pdelaycurve.attach(self.gui.pdelayPlot) self.groupcurve.attach(self.gui.groupPlot) self.rcurve.attach(self.gui.timePlot) self.icurve.attach(self.gui.timePlot) self.imprescurve.attach(self.gui.impresPlot) self.imprescurve_i.attach(self.gui.impresPlot) self.steprescurve.attach(self.gui.stepresPlot) self.steprescurve_i.attach(self.gui.stepresPlot) if self.iir: self.iir_plot_all(self.z,self.p,self.k) else: self.draw_plots(self.taps,self.params) else: self.gridview=1 self.set_actgrid() self.gui.stackedWindows.setCurrentIndex(1) self.freqcurve.attach(self.gui.mfreqPlot) self.rcurve.attach(self.gui.mtimePlot) self.icurve.attach(self.gui.mtimePlot) self.update_freq_curves() self.update_time_curves() self.set_drawideal() def set_plotselect(self): if (self.gui.actionPlot_select.isChecked() == 0 ): self.gui.mfgroupBox.hide() self.gui.mtgroupBox.hide() self.gui.pzgroupBox.hide() self.gui.mpzgroupBox.hide() else: self.gui.mfgroupBox.show() self.gui.mtgroupBox.show() self.gui.pzgroupBox.show() self.gui.mpzgroupBox.show() def replot_all(self): self.gui.timePlot.replot() self.gui.mtimePlot.replot() self.gui.freqPlot.replot() self.gui.mfreqPlot.replot() self.gui.phasePlot.replot() self.gui.groupPlot.replot() self.gui.impresPlot.replot() self.gui.stepresPlot.replot() self.gui.pdelayPlot.replot() def detach_allgrid(self): self.freqgrid.detach() self.phasegrid.detach() self.groupgrid.detach() self.pdelaygrid.detach() self.impresgrid.detach() self.stepresgrid.detach() self.ftapsgrid.detach() def set_mfmagresponse(self): if self.mfoverlay: if not(self.ifinlist(self.freqcurve,self.gui.mfreqPlot.itemList())): self.detach_allgrid() self.freqcurve.attach(self.gui.mfreqPlot) self.detach_firstattached(self.gui.mfreqPlot) self.update_freq_curves() self.idbanditems.detach_allidealcurves(self.gui.mfreqPlot) else: self.gui.mfreqPlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.freqcurve.setPen(QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.SolidLine)) self.freqcurve.setYAxis(Qwt.QwtPlot.yLeft) self.freqcurve.attach(self.gui.mfreqPlot) self.update_freq_curves() self.set_drawideal() def set_mfphaseresponse(self): if self.mfoverlay: if not(self.ifinlist(self.phasecurve,self.gui.mfreqPlot.itemList())): self.detach_allgrid() self.phasecurve.attach(self.gui.mfreqPlot) self.detach_firstattached(self.gui.mfreqPlot) self.update_phase_curves() self.idbanditems.detach_allidealcurves(self.gui.mfreqPlot) else: self.gui.mfreqPlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.phasecurve.setPen(QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.SolidLine)) self.phasecurve.setYAxis(Qwt.QwtPlot.yLeft) self.phasecurve.attach(self.gui.mfreqPlot) self.update_phase_curves() def set_mfgroupdelay(self): if self.mfoverlay: if not(self.ifinlist(self.groupcurve,self.gui.mfreqPlot.itemList())): self.detach_allgrid() self.groupcurve.attach(self.gui.mfreqPlot) self.detach_firstattached(self.gui.mfreqPlot) self.update_group_curves() self.idbanditems.detach_allidealcurves(self.gui.mfreqPlot) else: self.gui.mfreqPlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.groupcurve.setPen(QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.SolidLine)) self.groupcurve.setYAxis(Qwt.QwtPlot.yLeft) self.groupcurve.attach(self.gui.mfreqPlot) self.update_group_curves() def set_mfphasedelay(self): if self.mfoverlay: if not(self.ifinlist(self.pdelaycurve,self.gui.mfreqPlot.itemList())): self.detach_allgrid() self.pdelaycurve.attach(self.gui.mfreqPlot) self.detach_firstattached(self.gui.mfreqPlot) self.update_pdelay_curves() self.idbanditems.detach_allidealcurves(self.gui.mfreqPlot) else: self.gui.mfreqPlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.pdelaycurve.setPen(QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.SolidLine)) self.pdelaycurve.setYAxis(Qwt.QwtPlot.yLeft) self.pdelaycurve.attach(self.gui.mfreqPlot) self.update_pdelay_curves() def ifinlist(self,a,dlist): for d in dlist: if self.compare_instances(a,d): return True return False def compare_instances(self,a,b): if a is b: return True else: return False def detach_firstattached(self, plot): items=plot.itemList() plot.enableAxis(Qwt.QwtPlot.yRight) if len(items) > 2: yaxis=items[0].yAxis() items[2].setPen(items[0].pen()) items[2].setYAxis(yaxis) items[0].detach() else: items[1].setYAxis(Qwt.QwtPlot.yRight) if plot is self.gui.mfreqPlot: items[1].setPen(QtGui.QPen(QtCore.Qt.red, 1, QtCore.Qt.SolidLine)) self.set_actgrid() def update_fft(self, taps, params): self.params = params self.taps = scipy.array(taps) self.get_fft(self.params["fs"], self.taps, self.nfftpts) def set_mfoverlay(self): self.mfoverlay = not(self.mfoverlay) def set_conj(self): self.cpicker.set_conjugate() def set_mconj(self): self.cpicker2.set_conjugate() def set_zeroadd(self): self.cpicker.add_zero() def set_mzeroadd(self): self.cpicker2.add_zero() def set_poleadd(self): self.cpicker.add_pole() def set_mpoleadd(self): self.cpicker2.add_pole() def set_delpz(self): self.cpicker.delete_pz() def set_mdelpz(self): self.cpicker2.delete_pz() def set_mttaps(self): if self.mtoverlay: if not(self.ifinlist(self.rcurve,self.gui.mtimePlot.itemList())): self.rcurve.attach(self.gui.mtimePlot) self.icurve.attach(self.gui.mtimePlot) self.detach_firstattached(self.gui.mtimePlot) self.update_time_curves() else: self.gui.mtimePlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.rcurve.setYAxis(Qwt.QwtPlot.yLeft) self.icurve.setYAxis(Qwt.QwtPlot.yLeft) self.rcurve.attach(self.gui.mtimePlot) self.icurve.attach(self.gui.mtimePlot) self.update_time_curves() def set_mtstep(self): if self.mtoverlay: if not(self.ifinlist(self.steprescurve,self.gui.mtimePlot.itemList())): self.steprescurve.attach(self.gui.mtimePlot) self.steprescurve_i.attach(self.gui.mtimePlot) self.detach_firstattached(self.gui.mtimePlot) self.update_step_curves() else: self.gui.mtimePlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.steprescurve.setYAxis(Qwt.QwtPlot.yLeft) self.steprescurve.attach(self.gui.mtimePlot) self.steprescurve_i.attach(self.gui.mtimePlot) self.update_step_curves() def set_mtimpulse(self): if self.mtoverlay: if not(self.ifinlist(self.imprescurve,self.gui.mtimePlot.itemList())): self.imprescurve.attach(self.gui.mtimePlot) self.imprescurve_i.attach(self.gui.mtimePlot) self.detach_firstattached(self.gui.mtimePlot) self.update_imp_curves() else: self.gui.mtimePlot.detachItems(Qwt.QwtPlotItem.Rtti_PlotItem, False) self.set_actgrid() self.imprescurve.setYAxis(Qwt.QwtPlot.yLeft) self.imprescurve.attach(self.gui.mtimePlot) self.imprescurve_i.attach(self.gui.mtimePlot) self.update_imp_curves() def set_gdelay(self): if (self.gui.checkGdelay.checkState() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.groupTab)) else: self.gui.tabGroup.addTab(self.gui.groupTab, _fromUtf8("Group Delay")) self.update_freq_curves() def set_actgdelay(self): if (self.gui.actionGroup_Delay.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.groupTab)) else: self.gui.tabGroup.addTab(self.gui.groupTab, _fromUtf8("Group Delay")) self.update_freq_curves() def set_phase(self): if (self.gui.checkPhase.checkState() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.phaseTab)) else: self.gui.tabGroup.addTab(self.gui.phaseTab, _fromUtf8("Phase Response")) self.update_freq_curves() def set_actphase(self): if (self.gui.actionPhase_Respone.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.phaseTab)) else: self.gui.tabGroup.addTab(self.gui.phaseTab, _fromUtf8("Phase Response")) self.update_freq_curves() def set_fcoeff(self): if (self.gui.checkFcoeff.checkState() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.fcTab)) else: self.gui.tabGroup.addTab(self.gui.fcTab, _fromUtf8("Filter Coefficients")) self.update_fcoeff() def set_actfcoeff(self): if (self.gui.actionFilter_Coefficients.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.fcTab)) else: self.gui.tabGroup.addTab(self.gui.fcTab, _fromUtf8("Filter Coefficients")) self.update_fcoeff() def set_band(self): if (self.gui.checkBand.checkState() == 0 ): self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.bandDiagram)) else: self.gui.filterspecView.addTab(self.gui.bandDiagram, _fromUtf8("Band Diagram")) def set_actband(self): if (self.gui.actionBand_Diagram.isChecked() == 0 ): self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.bandDiagram)) else: self.gui.filterspecView.addTab(self.gui.bandDiagram, _fromUtf8("Band Diagram")) def set_drawideal(self): fsel = str(self.gui.fselectComboBox.currentText().toAscii()) if self.gridview and not(self.mfoverlay): plot = self.gui.mfreqPlot else: plot = self.gui.freqPlot if (self.gui.actionIdeal_Band.isChecked() == 0 or fsel == "IIR(scipy)"): self.idbanditems.detach_allidealcurves(plot) elif(self.params): ftype = str(self.gui.filterTypeComboBox.currentText().toAscii()) self.idbanditems.attach_allidealcurves(plot) self.idbanditems.plotIdealCurves(ftype, self.params, plot) plot.replot() def set_pzplot(self): if (self.gui.checkPzplot.checkState() == 0 ): self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.poleZero)) else: self.gui.filterspecView.addTab(self.gui.poleZero, _fromUtf8("Pole-Zero Plot")) def set_actpzplot(self): if (self.gui.actionPole_Zero_Plot_2.isChecked() == 0 ): self.gui.filterspecView.removeTab(self.gui.filterspecView.indexOf(self.gui.poleZero)) else: self.gui.filterspecView.addTab(self.gui.poleZero, _fromUtf8("Pole-Zero Plot")) def set_pdelay(self): if (self.gui.checkPzplot.checkState() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.pdelayTab)) else: self.gui.tabGroup.addTab(self.gui.pdelayTab, _fromUtf8("Phase Delay")) def set_actpdelay(self): if (self.gui.actionPhase_Delay.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.pdelayTab)) else: self.gui.tabGroup.addTab(self.gui.pdelayTab, _fromUtf8("Phase Delay")) def set_impres(self): if (self.gui.checkImpulse.checkState() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.impresTab)) else: self.gui.tabGroup.addTab(self.gui.impresTab, _fromUtf8("Impulse Response")) def set_actimpres(self): if (self.gui.actionImpulse_Response.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.impresTab)) else: self.gui.tabGroup.addTab(self.gui.impresTab, _fromUtf8("Impulse Response")) def set_stepres(self): if (self.gui.checkStep.checkState() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.stepresTab)) else: self.gui.tabGroup.addTab(self.gui.stepresTab, _fromUtf8("Step Response")) def set_actstepres(self): if (self.gui.actionStep_Response.isChecked() == 0 ): self.gui.tabGroup.removeTab(self.gui.tabGroup.indexOf(self.gui.stepresTab)) else: self.gui.tabGroup.addTab(self.gui.stepresTab, _fromUtf8("Step Response")) def populate_bandview(self,fitems): for item in fitems: if (item.isWidgetType()): self.scene.addWidget(item) else: self.scene.addItem(item) def remove_bandview(self): for item in self.scene.items(): self.scene.removeItem(item) def set_fatten(self,atten): ftype = str(self.gui.filterTypeComboBox.currentText().toAscii()) if (ftype == "Low Pass"): boxatten,r = self.gui.lpfStopBandAttenEdit.text().toDouble() self.gui.lpfStopBandAttenEdit.setText(Qt.QString(str(atten+boxatten))) if ftype == "High Pass": boxatten,r = self.gui.hpfStopBandAttenEdit.text().toDouble() self.gui.hpfStopBandAttenEdit.setText(Qt.QString(str(atten+boxatten))) if ftype == "Band Pass": boxatten,r = self.gui.bpfStopBandAttenEdit.text().toDouble() self.gui.bpfStopBandAttenEdit.setText(Qt.QString(str(atten+boxatten))) if ftype == "Band Notch": boxatten,r = self.gui.bnfStopBandAttenEdit.text().toDouble() self.gui.bnfStopBandAttenEdit.setText(Qt.QString(str(atten+boxatten))) if ftype == "Complex Band Pass": boxatten,r = self.gui.bpfStopBandAttenEdit.text().toDouble() self.gui.bpfStopBandAttenEdit.setText(Qt.QString(str(atten+boxatten))) #self.design() def set_curvetaps(self,(zr,pl)): if self.iir: self.z=zr self.p=pl self.iir_plot_all(self.z,self.p,self.k) self.gui.mpzPlot.insertZeros(zr) self.gui.mpzPlot.insertPoles(pl) self.update_fcoeff() if self.callback: retobj = ApiObject() retobj.update_all("iir", self.params, (self.b, self.a), 1) self.callback(retobj) else: hz = poly1d(zr,r=1) #print hz.c self.taps=hz.c*self.taps[0] self.draw_plots(self.taps,self.params) self.update_fcoeff() #update the pzplot in other view zeros=self.get_zeros() poles=self.get_poles() self.gui.mpzPlot.insertZeros(zeros) self.gui.mpzPlot.insertPoles(poles) self.gui.nTapsEdit.setText(Qt.QString("%1").arg(self.taps.size)) if self.callback: retobj = ApiObject() retobj.update_all("fir", self.params, self.taps, 1) self.callback(retobj) def set_mcurvetaps(self,(zr,pl)): if self.iir: self.z=zr self.p=pl self.iir_plot_all(self.z,self.p,self.k) self.gui.pzPlot.insertZeros(zr) self.gui.pzPlot.insertPoles(pl) self.update_fcoeff() if self.callback: retobj = ApiObject() retobj.update_all("iir", self.params, (self.b, self.a), 1) self.callback(retobj) else: hz = poly1d(zr,r=1) #print hz.c self.taps=hz.c*self.taps[0] if self.gridview: self.update_fft(self.taps, self.params) self.set_mfmagresponse() self.set_mttaps() else: self.draw_plots(self.taps,self.params) self.update_fcoeff() #update the pzplot in other view zeros=self.get_zeros() poles=self.get_poles() self.gui.pzPlot.insertZeros(zeros) self.gui.pzPlot.insertPoles(poles) self.gui.nTapsEdit.setText(Qt.QString("%1").arg(self.taps.size)) if self.callback: retobj = ApiObject() retobj.update_all("fir", self.params, self.taps, 1) self.callback(retobj) def set_statusbar(self,(x,y)): if x == None: self.gui.pzstatusBar.showMessage("") else: self.gui.pzstatusBar.showMessage("X: "+str(x)+" Y: "+str(y)) def set_mstatusbar(self,(x,y)): if x == None: self.gui.mpzstatusBar.showMessage("") else: self.gui.mpzstatusBar.showMessage("X: "+str(x)+" Y: "+str(y)) def get_zeros(self): hz = poly1d(self.taps,r=0) return hz.r def get_poles(self): if len(self.taps): hp = zeros(len(self.taps)-1,complex) return hp else: return [] def impulse_response(self,b,a=1): l = len(b) if self.iir: l = 50 impulse = scipy.repeat(0.,l) impulse[0] =1. x = scipy.arange(0,l) response = signal.lfilter(b,a,impulse) return response def step_response(self,b,a=1): l = len(b) if self.iir: l = 50 impulse = scipy.repeat(0.,l) impulse[0] =1. x = scipy.arange(0,l) response = signal.lfilter(b,a,impulse) step = scipy.cumsum(response) return step def update_fcoeff(self): fcoeff="" if self.iir: fcoeff="b = "+str(self.b.tolist())+"\na = "+str(self.a.tolist()) else: fcoeff="taps = "+str(self.taps.tolist()) self.gui.filterCoeff.setText(Qt.QString(fcoeff)) self.gui.mfilterCoeff.setText(Qt.QString(fcoeff)) def action_save_dialog(self): filename = QtGui.QFileDialog.getSaveFileName(self, "Save CSV Filter File", ".", "") try: handle = open(filename, "wb") except IOError: reply = QtGui.QMessageBox.information(self, 'File Name', ("Could not save to file: %s" % filename), "&Ok") return csvhandle = csv.writer(handle, delimiter=",") #indicate fir/iir for easy reading if self.iir: csvhandle.writerow(["restype","iir"]) else: csvhandle.writerow(["restype","fir"]) for k in self.params.keys(): csvhandle.writerow([k, self.params[k]]) if self.iir: csvhandle.writerow(["b",] + self.b.tolist()) csvhandle.writerow(["a",] + self.a.tolist()) else: csvhandle.writerow(["taps",] + self.taps.tolist()) handle.close() def action_open_dialog(self): filename = QtGui.QFileDialog.getOpenFileName(self, "Open CSV Filter File", ".", "") if(len(filename) == 0): return try: handle = open(filename, "rb") except IOError: reply = QtGui.QMessageBox.information(self, 'File Name', ("Could not open file: %s" % filename), "&Ok") return csvhandle = csv.reader(handle, delimiter=",") b_a={} taps = [] params = {} for row in csvhandle: if (row[0] == "restype"): restype = row[1] elif(row[0] == "taps"): testcpx = re.findall("[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) if(len(testcpx) > 0): # it's a complex taps = [complex(r) for r in row[1:]] else: taps = [float(r) for r in row[1:]] elif(row[0] == "b" or row[0] == "a"): testcpx = re.findall("[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) if(len(testcpx) > 0): # it's a complex b_a[row[0]] = [complex(r) for r in row[1:]] else: b_a[row[0]]= [float(r) for r in row[1:]] else: testcpx = re.findall("[+-]?\d+\.*\d*[Ee]?[-+]?\d+j", row[1]) if(len(testcpx) > 0): # it's a complex params[row[0]] = complex(row[1]) else: # assume it's a float try: # if it's not a float, its a string params[row[0]] = float(row[1]) except ValueError: params[row[0]] = row[1] handle.close() if restype == "fir": self.iir = False self.gui.fselectComboBox.setCurrentIndex(0) self.draw_plots(taps, params) zeros=self.get_zeros() poles=self.get_poles() self.gui.pzPlot.insertZeros(zeros) self.gui.pzPlot.insertPoles(poles) self.gui.mpzPlot.insertZeros(zeros) self.gui.mpzPlot.insertPoles(poles) self.gui.sampleRateEdit.setText(Qt.QString("%1").arg(params["fs"])) self.gui.filterGainEdit.setText(Qt.QString("%1").arg(params["gain"])) # Set up GUI parameters for each filter type if(params["filttype"] == "lpf"): self.gui.filterTypeComboBox.setCurrentIndex(0) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.endofLpfPassBandEdit.setText(Qt.QString("%1").arg(params["pbend"])) self.gui.startofLpfStopBandEdit.setText(Qt.QString("%1").arg(params["sbstart"])) self.gui.lpfStopBandAttenEdit.setText(Qt.QString("%1").arg(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): self.gui.lpfPassBandRippleEdit.setText(Qt.QString("%1").arg(params["ripple"])) elif(params["filttype"] == "bpf"): self.gui.filterTypeComboBox.setCurrentIndex(1) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.startofBpfPassBandEdit.setText(Qt.QString("%1").arg(params["pbstart"])) self.gui.endofBpfPassBandEdit.setText(Qt.QString("%1").arg(params["pbend"])) self.gui.bpfTransitionEdit.setText(Qt.QString("%1").arg(params["tb"])) self.gui.bpfStopBandAttenEdit.setText(Qt.QString("%1").arg(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): self.gui.bpfPassBandRippleEdit.setText(Qt.QString("%1").arg(params["ripple"])) elif(params["filttype"] == "cbpf"): self.gui.filterTypeComboBox.setCurrentIndex(2) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.startofBpfPassBandEdit.setText(Qt.QString("%1").arg(params["pbstart"])) self.gui.endofBpfPassBandEdit.setText(Qt.QString("%1").arg(params["pbend"])) self.gui.bpfTransitionEdit.setText(Qt.QString("%1").arg(params["tb"])) self.gui.bpfStopBandAttenEdit.setText(Qt.QString("%1").arg(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): self.gui.bpfPassBandRippleEdit.setText(Qt.QString("%1").arg(params["ripple"])) elif(params["filttype"] == "bnf"): self.gui.filterTypeComboBox.setCurrentIndex(3) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.startofBnfStopBandEdit.setText(Qt.QString("%1").arg(params["sbstart"])) self.gui.endofBnfStopBandEdit.setText(Qt.QString("%1").arg(params["sbend"])) self.gui.bnfTransitionEdit.setText(Qt.QString("%1").arg(params["tb"])) self.gui.bnfStopBandAttenEdit.setText(Qt.QString("%1").arg(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): self.gui.bnfPassBandRippleEdit.setText(Qt.QString("%1").arg(params["ripple"])) elif(params["filttype"] == "hpf"): self.gui.filterTypeComboBox.setCurrentIndex(4) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.endofHpfStopBandEdit.setText(Qt.QString("%1").arg(params["sbend"])) self.gui.startofHpfPassBandEdit.setText(Qt.QString("%1").arg(params["pbstart"])) self.gui.hpfStopBandAttenEdit.setText(Qt.QString("%1").arg(params["atten"])) if(params["wintype"] == self.EQUIRIPPLE_FILT): self.gui.hpfPassBandRippleEdit.setText(Qt.QString("%1").arg(params["ripple"])) elif(params["filttype"] == "rrc"): self.gui.filterTypeComboBox.setCurrentIndex(5) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.rrcSymbolRateEdit.setText(Qt.QString("%1").arg(params["srate"])) self.gui.rrcAlphaEdit.setText(Qt.QString("%1").arg(params["alpha"])) self.gui.rrcNumTapsEdit.setText(Qt.QString("%1").arg(params["ntaps"])) elif(params["filttype"] == "gaus"): self.gui.filterTypeComboBox.setCurrentIndex(6) self.gui.filterDesignTypeComboBox.setCurrentIndex(int(params["wintype"])) self.gui.gausSymbolRateEdit.setText(Qt.QString("%1").arg(params["srate"])) self.gui.gausBTEdit.setText(Qt.QString("%1").arg(params["bt"])) self.gui.gausNumTapsEdit.setText(Qt.QString("%1").arg(params["ntaps"])) else: self.iir = True self.b, self.a = b_a["b"],b_a["a"] (self.z,self.p,self.k) = signal.tf2zpk(self.b, self.a) self.gui.pzPlot.insertZeros(self.z) self.gui.pzPlot.insertPoles(self.p) self.gui.mpzPlot.insertZeros(self.z) self.gui.mpzPlot.insertPoles(self.p) self.iir_plot_all(self.z,self.p,self.k) self.update_fcoeff() self.gui.nTapsEdit.setText("-") self.params = params #Set GUI for IIR type iirft = { "ellip" : 0, "butter" : 1, "cheby1" : 2, "cheby2" : 3, "bessel" : 4 } paramtype = { "analog" : 1, "digital" : 0 } bandpos = { "lpf" : 0, "bpf" : 1, "bnf" : 2, "hpf" : 3} iirboxes = {"lpf" : [self.gui.iirendofLpfPassBandEdit, self.gui.iirstartofLpfStopBandEdit, self.gui.iirLpfPassBandAttenEdit, self.gui.iirLpfStopBandRippleEdit], "hpf" : [self.gui.iirstartofHpfPassBandEdit, self.gui.iirendofHpfStopBandEdit, self.gui.iirHpfPassBandAttenEdit, self.gui.iirHpfStopBandRippleEdit], "bpf" : [self.gui.iirstartofBpfPassBandEdit, self.gui.iirendofBpfPassBandEdit, self.gui.iirendofBpfStopBandEdit1, self.gui.iirstartofBpfStopBandEdit2, self.gui.iirBpfPassBandAttenEdit, self.gui.iirBpfStopBandRippleEdit], "bnf" : [self.gui.iirendofBsfPassBandEdit1, self.gui.iirstartofBsfPassBandEdit2, self.gui.iirstartofBsfStopBandEdit, self.gui.iirendofBsfStopBandEdit, self.gui.iirBsfPassBandAttenEdit, self.gui.iirBsfStopBandRippleEdit] } self.gui.fselectComboBox.setCurrentIndex(1) self.gui.iirfilterTypeComboBox.setCurrentIndex(iirft[params["filttype"]]) self.gui.iirfilterBandComboBox.setCurrentIndex(bandpos[params["bandtype"]]) if params["filttype"] == "bessel": critfreq = map(float, params["critfreq"][1:-1].split(',')) self.gui.besselordEdit.setText(Qt.QString("%1").arg(params["filtord"])) self.gui.iirbesselcritEdit1.setText(Qt.QString("%1").arg(critfreq[0])) self.gui.iirbesselcritEdit2.setText(Qt.QString("%1").arg(critfreq[1])) else: self.gui.adComboBox.setCurrentIndex(paramtype[params["paramtype"]]) if len(iirboxes[params["bandtype"]]) == 4: sdata = [params["pbedge"], params["sbedge"], params["gpass"], params["gstop"]] else: pbedge = map(float, params["pbedge"][1:-1].split(',')) sbedge = map(float, params["sbedge"][1:-1].split(',')) sdata = [pbedge[0], pbedge[1], sbedge[0], sbedge[1], params["gpass"], params["gstop"]] cboxes = iirboxes[params["bandtype"]] for i in range(len(cboxes)): cboxes[i].setText(Qt.QString("%1").arg(sdata[i])) def draw_plots(self, taps, params): self.params = params self.taps = scipy.array(taps) if self.params: self.get_fft(self.params["fs"], self.taps, self.nfftpts) self.update_time_curves() self.update_freq_curves() self.update_phase_curves() self.update_group_curves() self.update_pdelay_curves() self.update_step_curves() self.update_imp_curves() self.gui.nTapsEdit.setText(Qt.QString("%1").arg(self.taps.size)) def setup_options(): usage="%prog: [options] (input_filename)" description = "" parser = OptionParser(conflict_handler="resolve", usage=usage, description=description) return parser def launch(args, callback=None, restype=""): parser = setup_options() (options, args) = parser.parse_args () if callback == None: app = Qt.QApplication(args) gplt = gr_plot_filter(options, callback, restype) app.exec_() if gplt.iir: retobj = ApiObject() retobj.update_all("iir", gplt.params, (gplt.b, gplt.a), 1) return retobj else: retobj = ApiObject() retobj.update_all("fir", gplt.params, gplt.taps, 1) return retobj else: gplt = gr_plot_filter(options, callback, restype) return gplt def main(args): parser = setup_options() (options, args) = parser.parse_args () app = Qt.QApplication(args) gplt = gr_plot_filter(options) app.exec_() if __name__ == '__main__': main(sys.argv) gnuradio-3.7.2.1/gr-filter/python/filter/design/fir_design.py0000664000175000017500000003702012207440367023770 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import scipy from gnuradio import filter from PyQt4 import QtGui # Filter design functions using a window def design_win_lpf(fs, gain, wintype, mainwin): ret = True pb,r = mainwin.gui.endofLpfPassBandEdit.text().toDouble() ret = r and ret sb,r = mainwin.gui.startofLpfStopBandEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.lpfStopBandAttenEdit.text().toDouble() ret = r and ret if(ret): tb = sb - pb try: taps = filter.firdes.low_pass_2(gain, fs, pb, tb, atten, wintype) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") return ([], [], ret) else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "lpf", "pbend": pb, "sbstart": sb, "atten": atten, "ntaps": len(taps)} return (taps, params, ret) else: return ([], [], ret) def design_win_bpf(fs, gain, wintype, mainwin): ret = True pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble() ret = r and ret pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble() ret = r and ret tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble() ret = r and ret if(ret): try: taps = filter.firdes.band_pass_2(gain, fs, pb1, pb2, tb, atten, wintype) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") return ([], [], ret) else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "bpf", "pbstart": pb1, "pbend": pb2, "tb": tb, "atten": atten, "ntaps": len(taps)} return (taps,params,r) else: return ([],[],ret) def design_win_cbpf(fs, gain, wintype, mainwin): ret = True pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble() ret = r and ret pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble() ret = r and ret tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble() ret = r and ret if(ret): try: taps = filter.firdes.complex_band_pass_2(gain, fs, pb1, pb2, tb, atten, wintype) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") return ([], [], ret) else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "cbpf", "pbstart": pb1, "pbend": pb2, "tb": tb, "atten": atten, "ntaps": len(taps)} return (taps,params,r) else: return ([],[],ret) def design_win_bnf(fs, gain, wintype, mainwin): ret = True pb1,r = mainwin.gui.startofBnfStopBandEdit.text().toDouble() ret = r and ret pb2,r = mainwin.gui.endofBnfStopBandEdit.text().toDouble() ret = r and ret tb,r = mainwin.gui.bnfTransitionEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.bnfStopBandAttenEdit.text().toDouble() ret = r and ret if(ret): try: taps = filter.firdes.band_reject_2(gain, fs, pb1, pb2, tb, atten, wintype) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") return ([], [], ret) else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "bnf", "sbstart": pb1, "sbend": pb2, "tb": tb, "atten": atten, "ntaps": len(taps)} return (taps,params,r) else: return ([],[],ret) def design_win_hpf(fs, gain, wintype, mainwin): ret = True sb,r = mainwin.gui.endofHpfStopBandEdit.text().toDouble() ret = r and ret pb,r = mainwin.gui.startofHpfPassBandEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.hpfStopBandAttenEdit.text().toDouble() ret = r and ret if(ret): tb = pb - sb try: taps = filter.firdes.high_pass_2(gain, fs, pb, tb, atten, wintype) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "hpf", "sbend": sb, "pbstart": pb, "atten": atten, "ntaps": len(taps)} return (taps,params,ret) else: return ([],[],ret) def design_win_hb(fs, gain, wintype, mainwin): ret = True filtord,r = mainwin.gui.firhbordEdit.text().toDouble() ret = r and ret trwidth,r = mainwin.gui.firhbtrEdit.text().toDouble() ret = r and ret filtwin = { filter.firdes.WIN_HAMMING : 'hamming', filter.firdes.WIN_HANN : 'hanning', filter.firdes.WIN_BLACKMAN : 'blackman', filter.firdes.WIN_RECTANGULAR: 'boxcar', filter.firdes.WIN_KAISER: ('kaiser', 4.0), filter.firdes.WIN_BLACKMAN_hARRIS: 'blackmanharris'} if int(filtord) & 1: reply = QtGui.QMessageBox.information(mainwin, "Filter order should be even", "Filter order should be even","&Ok") return ([],[],False) if(ret): taps = scipy.signal.firwin(int(filtord)+1, 0.5, window = filtwin[wintype]) taps[abs(taps) <= 1e-6] = 0. params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "hb","ntaps": len(taps)} return (taps,params,ret) else: return ([],[],ret) def design_win_rrc(fs, gain, wintype, mainwin): ret = True sr,r = mainwin.gui.rrcSymbolRateEdit.text().toDouble() ret = r and ret alpha,r = mainwin.gui.rrcAlphaEdit.text().toDouble() ret = r and ret ntaps,r = mainwin.gui.rrcNumTapsEdit.text().toInt() ret = r and ret if(ret): try: taps = filter.firdes.root_raised_cosine(gain, fs, sr, alpha, ntaps) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "rrc", "srate": sr, "alpha": alpha, "ntaps": ntaps} return (taps,params,ret) else: return ([],[],ret) def design_win_gaus(fs, gain, wintype, mainwin): ret = True sr,r = mainwin.gui.gausSymbolRateEdit.text().toDouble() ret = r and ret bt,r = mainwin.gui.gausBTEdit.text().toDouble() ret = r and ret ntaps,r = mainwin.gui.gausNumTapsEdit.text().toInt() ret = r and ret if(ret): spb = fs / sr try: taps = filter.firdes.gaussian(gain, spb, bt, ntaps) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Runtime Error", e.args[0], "&Ok") else: params = {"fs": fs, "gain": gain, "wintype": wintype, "filttype": "gaus", "srate": sr, "bt": bt, "ntaps": ntaps} return (taps,params,ret) else: return ([],[],ret) # Design Functions for Equiripple Filters def design_opt_lpf(fs, gain, mainwin): ret = True pb,r = mainwin.gui.endofLpfPassBandEdit.text().toDouble() ret = r and ret sb,r = mainwin.gui.startofLpfStopBandEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.lpfStopBandAttenEdit.text().toDouble() ret = r and ret ripple,r = mainwin.gui.lpfPassBandRippleEdit.text().toDouble() ret = r and ret if(ret): try: taps = filter.optfir.low_pass(gain, fs, pb, sb, ripple, atten) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge", e.args[0], "&Ok") return ([],[],False) else: params = {"fs": fs, "gain": gain, "wintype": mainwin.EQUIRIPPLE_FILT, "filttype": "lpf", "pbend": pb, "sbstart": sb, "atten": atten, "ripple": ripple, "ntaps": len(taps)} return (taps, params, ret) else: return ([], [], ret) def design_opt_bpf(fs, gain, mainwin): ret = True pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble() ret = r and ret pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble() ret = r and ret tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble() ret = r and ret ripple,r = mainwin.gui.bpfPassBandRippleEdit.text().toDouble() ret = r and ret if(r): sb1 = pb1 - tb sb2 = pb2 + tb try: taps = filter.optfir.band_pass(gain, fs, sb1, pb1, pb2, sb2, ripple, atten) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge", e.args[0], "&Ok") return ([],[],False) else: params = {"fs": fs, "gain": gain, "wintype": mainwin.EQUIRIPPLE_FILT, "filttype": "bpf", "pbstart": pb1, "pbend": pb2, "tb": tb, "atten": atten, "ripple": ripple, "ntaps": len(taps)} return (taps,params,r) else: return ([],[],r) def design_opt_cbpf(fs, gain, mainwin): ret = True pb1,r = mainwin.gui.startofBpfPassBandEdit.text().toDouble() ret = r and ret pb2,r = mainwin.gui.endofBpfPassBandEdit.text().toDouble() ret = r and ret tb,r = mainwin.gui.bpfTransitionEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.bpfStopBandAttenEdit.text().toDouble() ret = r and ret ripple,r = mainwin.gui.bpfPassBandRippleEdit.text().toDouble() ret = r and ret if(r): sb1 = pb1 - tb sb2 = pb2 + tb try: taps = filter.optfir.complex_band_pass(gain, fs, sb1, pb1, pb2, sb2, ripple, atten) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge", e.args[0], "&Ok") return ([],[],False) else: params = {"fs": fs, "gain": gain, "wintype": self.EQUIRIPPLE_FILT, "filttype": "cbpf", "pbstart": pb1, "pbend": pb2, "tb": tb, "atten": atten, "ripple": ripple, "ntaps": len(taps)} return (taps,params,r) else: return ([],[],r) def design_opt_bnf(fs, gain, mainwin): ret = True sb1,r = mainwin.gui.startofBnfStopBandEdit.text().toDouble() ret = r and ret sb2,r = mainwin.gui.endofBnfStopBandEdit.text().toDouble() ret = r and ret tb,r = mainwin.gui.bnfTransitionEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.bnfStopBandAttenEdit.text().toDouble() ret = r and ret ripple,r = mainwin.gui.bnfPassBandRippleEdit.text().toDouble() ret = r and ret if(ret): pb1 = sb1 - tb pb2 = sb2 + tb try: taps = filter.optfir.band_reject(gain, fs, pb1, sb1, sb2, pb2, ripple, atten) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge", e.args[0], "&Ok") return ([],[],False) else: params = {"fs": fs, "gain": gain, "wintype": mainwin.EQUIRIPPLE_FILT, "filttype": "bnf", "sbstart": pb1, "sbend": pb2, "tb": tb, "atten": atten, "ripple": ripple, "ntaps": len(taps)} return (taps,params,ret) else: return ([],[],ret) def design_opt_hb(fs, gain, mainwin): ret = True filtord,r = mainwin.gui.firhbordEdit.text().toDouble() ret = r and ret trwidth,r = mainwin.gui.firhbtrEdit.text().toDouble() ret = r and ret if int(filtord) & 1: reply = QtGui.QMessageBox.information(mainwin, "Filter order should be even", "Filter order should be even","&Ok") return ([],[],False) if(ret): try: bands = [0,.25 - (trwidth/fs), .25 + (trwidth/fs), 0.5] taps = scipy.signal.remez(int(filtord)+1, bands, [1,0], [1,1]) taps[abs(taps) <= 1e-6] = 0. except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Filter Design Error", e.args[0], "&Ok") return ([],[],False) else: params = {"fs": fs, "gain": gain, "wintype": self.EQUIRIPPLE_FILT, "filttype": "hb", "ntaps": len(taps)} return (taps,params,ret) else: return ([],[],ret) def design_opt_hpf(fs, gain, mainwin): ret = True sb,r = mainwin.gui.endofHpfStopBandEdit.text().toDouble() ret = r and ret pb,r = mainwin.gui.startofHpfPassBandEdit.text().toDouble() ret = r and ret atten,r = mainwin.gui.hpfStopBandAttenEdit.text().toDouble() ret = r and ret ripple,r = mainwin.gui.hpfPassBandRippleEdit.text().toDouble() ret = r and ret if(ret): try: taps = filter.optfir.high_pass(gain, fs, sb, pb, atten, ripple) except RuntimeError, e: reply = QtGui.QMessageBox.information(mainwin, "Filter did not converge", e.args[0], "&Ok") return ([],[],False) else: params = {"fs": fs, "gain": gain, "wintype": self.EQUIRIPPLE_FILT, "filttype": "hpf", "sbend": sb, "pbstart": pb, "atten": atten, "ripple": ripple, "ntaps": len(taps)} return (taps,params,ret) else: return ([],[],ret) gnuradio-3.7.2.1/gr-filter/python/filter/gui/0000775000175000017500000000000012207440367020616 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/python/filter/gui/icons.qrc0000664000175000017500000000116112207440367022437 0ustar jcorganjcorgan icons/add_pole.svg icons/add_zero.svg icons/conjugate.svg icons/filtr_taps.svg icons/group_delay.svg icons/impulse_response.svg icons/impulse.svg icons/mag_response.svg icons/overlay.svg icons/phase_delay.svg icons/phase_response.svg icons/remove_red.svg icons/step_response.svg icons/add_zero.svg icons/add_pole.svg gnuradio-3.7.2.1/gr-filter/python/filter/gui/banditems.py0000664000175000017500000001753412207440367023150 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # try: from PyQt4 import Qt, QtCore, QtGui except ImportError: print "Please install PyQt4 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)" raise SystemExit, 1 #Movable solid line for filter ideal-band diagram #Enable split to cut the line into two (for bpf) class filtermovlineItem(QtGui.QGraphicsObject): attenChanged = QtCore.pyqtSignal(float) def __init__(self,x1,y1,x2,y2,lower,upper,split=False,sx1=0,sy1=0,sx2=0,sy2=0): QtGui.QGraphicsObject.__init__(self) self.lower=lower self.upper=upper self.x1,self.y1=x1,y1 self.x2,self.y2=x2,y2 self.sx1,self.sy1=sx1,sy1 self.sx2,self.sy2=sx2,sy2 self.split=split def paint(self, painter, option, widget): painter.setPen(QtGui.QPen(QtCore.Qt.black,2 , QtCore.Qt.SolidLine)) painter.drawLine(self.x1,self.y1,self.x2,self.y2) painter.drawLine(self.x1,self.y1,self.x1,self.y1-5) painter.drawLine(self.x2,self.y2,self.x2,self.y2-5) if self.split: painter.drawLine(self.sx1,self.sy1,self.sx2,self.sy2) painter.drawLine(self.sx1,self.sy1,self.sx1,self.sy1-5) painter.drawLine(self.sx2,self.sy2,self.sx2,self.sy2-5) def boundingRect(self): return QtCore.QRectF(0,0,400,400) #allow only vertical movement and emit signals def itemChange(self, change, value): if (change == QtGui.QGraphicsItem.ItemPositionChange): newpos=value.toPointF() div=0 if newpos.y() < self.pos().y(): div=1 if newpos.y() > self.pos().y(): div=-1 hit=0 rect=self.scene().sceneRect() if (newpos.y() >= self.lower): newpos.setY(self.lower) hit=1 if (newpos.y() <= self.upper): newpos.setY(self.upper) hit=1 if not(hit): self.attenChanged.emit(div) return QtCore.QPointF(self.pos().x(), newpos.y()) return QtGui.QGraphicsItem.itemChange(self, change, value) #Static lines in lpf band diagram class lpfsLines(QtGui.QGraphicsObject): def __init__(self): QtGui.QGraphicsObject.__init__(self) def paint(self, painter, option, widget): painter.setPen(QtGui.QPen(QtCore.Qt.darkGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(5,20,5,200) painter.drawLine(5,200,400,200) painter.setPen(QtGui.QPen(QtCore.Qt.lightGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(6,105,150,105) painter.drawLine(150,105,150,199) painter.drawLine(200,180,400,180) painter.drawLine(200,180,200,199) painter.setPen(QtGui.QPen(QtCore.Qt.black)) painter.save() painter.rotate(270) painter.drawText(-150,-10,"Magnitude (dB)") painter.restore() painter.drawText(350,220,"Frequency (Hz)") painter.drawText(130,220,"Fpass") painter.drawText(180,220,"Fstop") def boundingRect(self): return QtCore.QRectF(0,0,300,300) #Static lines in hpf band diagram class hpfsLines(QtGui.QGraphicsObject): def __init__(self): QtGui.QGraphicsObject.__init__(self) def paint(self, painter, option, widget): painter.setPen(QtGui.QPen(QtCore.Qt.darkGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(5,20,5,200) painter.drawLine(5,200,400,200) painter.setPen(QtGui.QPen(QtCore.Qt.lightGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(200,105,400,105) painter.drawLine(200,105,200,199) painter.drawLine(6,180,150,180) painter.drawLine(150,180,150,199) painter.setPen(QtGui.QPen(QtCore.Qt.black)) painter.drawText(350,220,"Frequency (Hz)") painter.drawText(130,220,"Fstop") painter.drawText(180,220,"Fpass") def boundingRect(self): return QtCore.QRectF(0,0,300,300) #Static lines in bpf band diagram class bpfsLines(QtGui.QGraphicsObject): def __init__(self): QtGui.QGraphicsObject.__init__(self) def paint(self, painter, option, widget): painter.setPen(QtGui.QPen(QtCore.Qt.darkGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(5,20,5,200) painter.drawLine(5,200,400,200) painter.setPen(QtGui.QPen(QtCore.Qt.lightGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(6,180,110,180) painter.drawLine(110,180,110,199) painter.drawLine(155,105,255,105) painter.drawLine(255,105,255,199) painter.drawLine(155,105,155,199) painter.drawLine(300,180,400,180) painter.drawLine(300,180,300,199) painter.setPen(QtGui.QPen(QtCore.Qt.black)) painter.drawText(350,220,"Frequency (Hz)") painter.drawText(80,220,"Fstop1") painter.drawText(140,220,"Fpass1") painter.drawText(220,220,"Fpass2") painter.drawText(290,220,"Fstop2") def boundingRect(self): return QtCore.QRectF(0,0,300,300) #Static lines in bnf band diagram class bnfsLines(QtGui.QGraphicsObject): def __init__(self): QtGui.QGraphicsObject.__init__(self) def paint(self, painter, option, widget): painter.setPen(QtGui.QPen(QtCore.Qt.darkGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(5,20,5,200) painter.drawLine(5,200,400,200) painter.setPen(QtGui.QPen(QtCore.Qt.lightGray, 2, QtCore.Qt.SolidLine)) painter.drawLine(6,105,110,105) painter.drawLine(110,105,110,199) painter.drawLine(155,180,255,180) painter.drawLine(255,180,255,199) painter.drawLine(155,180,155,199) painter.drawLine(300,105,400,105) painter.drawLine(300,105,300,199) painter.setPen(QtGui.QPen(QtCore.Qt.black)) painter.drawText(350,220,"Frequency (Hz)") painter.drawText(80,220,"Fpass1") painter.drawText(140,220,"Fstop1") painter.drawText(220,220,"Fstop2") painter.drawText(290,220,"Fpass2") def boundingRect(self): return QtCore.QRectF(0,0,300,300) lpfItems=[] hpfItems=[] bpfItems=[] bnfItems=[] #lpfitems list lpfItems.append(filtermovlineItem(200,175,400,175,0,-60)) #lpfItems.append(filtermovlineItem(200,145,400,145,30,-30)) lpfItems[0].setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable| QtGui.QGraphicsItem.ItemSendsGeometryChanges) lpfItems.append(lpfsLines()) #hpfitems list hpfItems.append(filtermovlineItem(6,175,150,175,0,-60)) hpfItems[0].setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable| QtGui.QGraphicsItem.ItemSendsGeometryChanges) hpfItems.append(hpfsLines()) #bpfitems list bpfItems.append(filtermovlineItem(6,175,110,175,0,-60,True,300,175,400,175)) bpfItems[0].setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable| QtGui.QGraphicsItem.ItemSendsGeometryChanges) bpfItems.append(bpfsLines()) #bnfitems list bnfItems.append(filtermovlineItem(155,175,255,175,0,-60)) bnfItems[0].setFlags(QtGui.QGraphicsItem.ItemIsSelectable | QtGui.QGraphicsItem.ItemIsMovable| QtGui.QGraphicsItem.ItemSendsGeometryChanges) bnfItems.append(bnfsLines()) gnuradio-3.7.2.1/gr-filter/python/filter/gui/CMakeLists.txt0000664000175000017500000000210312207440367023352 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES bandgraphicsview.py banditems.py icons_rc.py idealbanditems.py polezero_plot.py pyqt_filter_stacked.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/filter COMPONENT "filter_python" ) gnuradio-3.7.2.1/gr-filter/python/filter/gui/pyqt_filter_stacked.ui0000664000175000017500000025131312207440367025222 0ustar jcorganjcorgan MainWindow 0 0 1128 649 GNU Radio Filter Design Tool 0 0 0 0 0 0 1 600 0 Qt::Vertical true 0 1 0 false false Magnitude Response Filter Taps Phase Response Group Delay Filter Coefficients Impulse Response 0 0 Step Response Phase Delay 0 0 0 100 0 100 1 false false 0 0 Band Diagram 0 1 525 249 false Pole-Zero Plot 0 0 ArrowCursor false false Add zero ... :/icons/add_zero.svg:/icons/add_zero.svg 16 16 true Add pole ... :/icons/add_pole.svg:/icons/add_pole.svg true Delete pole/zero ... :/icons/remove_red.svg:/icons/remove_red.svg true Conjugate ... :/icons/conjugate.svg:/icons/conjugate.svg 16 16 true 180 200 QFrame::StyledPanel QFrame::Raised 10 10 161 251 Filter Responses 10 40 151 19 Magnitude Response true 10 60 151 19 Phase Response true 10 80 111 19 Group Delay true 10 100 111 19 Phase Delay true 10 120 141 19 Impulse Response true 10 140 131 19 Step Response true 10 160 85 19 Grid 10 180 131 19 Filter Coefficients true 10 200 141 19 Buffer current plots 10 280 161 91 Filter Specs 10 20 111 19 Band Diagram true 10 40 131 19 Pole-Zero Plot true 10 390 161 91 Plot Parameter QFormLayout::AllNonFixedFieldsGrow 150 0 Num FFT points groupSpecs responseBox sysParamsBox 0 0 0 0 Qt::Vertical Qt::Horizontal 0 false 0 0 Frequency Response 0 0 ArrowCursor false false Magnitude Response ... :/icons/mag_response.svg:/icons/mag_response.svg 16 16 false Phase Response ... :/icons/phase_response.svg:/icons/phase_response.svg 16 16 false Group Delay ... :/icons/group_delay.svg:/icons/group_delay.svg 16 16 false Phase Delay ... :/icons/phase_delay.svg:/icons/phase_delay.svg 16 16 false Overlay ... :/icons/overlay.svg:/icons/overlay.svg 16 16 true 0 0 Time responses 0 0 ArrowCursor false false Filter Taps ... :/icons/filtr_taps.svg:/icons/filtr_taps.svg 16 16 false Step Response ... :/icons/step_response.svg:/icons/step_response.svg 16 16 false Impulse Response ... :/icons/impulse.svg:/icons/impulse.svg 16 16 false 0 0 0 100 0 100 1 false false 0 0 Ideal Band 0 1 525 249 false Pole-Zero Plot 0 0 ArrowCursor false false Add zero ... :/icons/add_zero.svg:/icons/add_zero.svg true Add pole ... :/icons/add_pole.svg:/icons/add_pole.svg true Delete pole/zero ... :/icons/remove_red.svg:/icons/remove_red.svg true Conjugate ... :/icons/conjugate.svg:/icons/conjugate.svg 16 16 true Filter Coefficients 300 0 300 16777215 QFrame::StyledPanel QFrame::Raised true FIR IIR(scipy) Low Pass High Pass Band Pass Complex Band Pass Band Notch Root Raised Cosine Gaussian Half Band Low Pass Band Pass Band Stop High Pass Digital (normalized 0-1) Analog (rad/second) Hamming Window Hann Window Blackman Window Rectangular Window Kaiser Window Blackman-harris Window Equiripple Elliptic Butterworth Chebyshev-1 Chebyshev-2 Bessel QFormLayout::AllNonFixedFieldsGrow 16777215 30 Sample Rate (sps) 16777215 30 320000 Filter Gain 2 11 QFormLayout::AllNonFixedFieldsGrow End of Pass Band (Hz) 50000 Start of Stop Band (Hz) 60000 Stop Band Attenuation (dB) 40 Pass Band Ripple (dB) 1 Start of Pass Band (Hz) 50000 End of Pass Band (Hz) 80000 40 Stop Band Attenuation (dB) Transition Width (Hz) 10000 1 Pass Band Ripple (dB) QFormLayout::AllNonFixedFieldsGrow Start of Stop Band (Hz) 50000 End of Stop Band (Hz) 80000 Transition Width (Hz) 10000 Stop Band Attenuation (dB) 48 Pass Band Ripple (dB) 1 QFormLayout::AllNonFixedFieldsGrow End of Stop Band (Hz) 50000 Start of Pass Band (Hz) 55000 Stop Band Attenuation (dB) 48 Pass Band Ripple (dB) 1 Symbol Rate (sps) Roll-off Factor Number of Taps 3200 15 50 Symbol Rate (sps) 5000 Roll-off Factor 0.5 Number of Taps 30 End of Pass Band 0.3 Start of Stop Band 0.5 Max loss in Pass Band (dB) 1 Min atten in Stop Band (dB) 60 End of Stop Band 0.3 Start of Pass Band 0.5 Max loss in Pass Band (dB) 1 Min atten in Stop Band (dB) 60 End of Stop Band-1 0.2 Start of Pass Band 0.3 End of Pass Band 0.5 Start of Stop Band-2 0.6 Max loss in Pass Band (dB) 1 Min atten in Stop Band (dB) 60 End of Pass Band-1 0.2 Start of Stop Band 0.3 End of Stop Band 0.6 Start of Pass Band-2 0.7 Max loss in Pass Band (dB) 1 Min atten in Stop Band (dB) 60 QFormLayout::AllNonFixedFieldsGrow Filter Order 10 Critical point-1 0.2 0.5 Critical point-2 QFormLayout::AllNonFixedFieldsGrow Filter Order 34 Transition width (from fs/4) 10000 Filter Properties QFormLayout::AllNonFixedFieldsGrow 150 0 Number of Taps: 100 16777215 QFrame::Box QFrame::Raised 0 0 200 16777215 Design true true 0 0 1128 19 &File Analysis 408 108 129 86 View E&xit &Save Ctrl+S &Open Ctrl+O true true Magnitude Response true true Phase Respone true true Group Delay true true Phase Delay true true Impulse Response true true Step Response Pole-Zero Plot Grid true true Pole Zero Plot true false Ideal Band true false Grid Grid true Tabbed true Overlay true true Response widget true true Spec widget true true Quick access true true Filter Coefficients true true Design widget Overlay true Gridview true Design widget Quick access Spec widget Response widget true true Design Widget true true Quick Access true true Spec Widget true true Response Widget true true Tabview true true Plot select true true Band Diagram check Plot FFT points QwtPlot QFrame
qwt_plot.h
1
BandGraphicsView QGraphicsView
bandgraphicsview
PzPlot QListView
polezero_plot
filterTypeComboBox filterDesignTypeComboBox endofLpfPassBandEdit startofLpfStopBandEdit lpfStopBandAttenEdit lpfPassBandRippleEdit startofBpfPassBandEdit endofBpfPassBandEdit bpfTransitionEdit bpfStopBandAttenEdit bpfPassBandRippleEdit startofBnfStopBandEdit endofBnfStopBandEdit bnfTransitionEdit bnfStopBandAttenEdit bnfPassBandRippleEdit endofHpfStopBandEdit startofHpfPassBandEdit hpfStopBandAttenEdit hpfPassBandRippleEdit rrcSymbolRateEdit rrcAlphaEdit rrcNumTapsEdit gausSymbolRateEdit gausBTEdit gausNumTapsEdit designButton action_exit activated() MainWindow close() -1 -1 399 347
gnuradio-3.7.2.1/gr-filter/python/filter/gui/pyqt_filter_stacked.py0000664000175000017500000033131612207440367025237 0ustar jcorganjcorgan# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyqt_filter_stacked.ui' # # Created: Wed Aug 8 11:42:47 2012 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1128, 649) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout = QtGui.QGridLayout(self.centralwidget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.stackedWindows = QtGui.QStackedWidget(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWindows.sizePolicy().hasHeightForWidth()) self.stackedWindows.setSizePolicy(sizePolicy) self.stackedWindows.setObjectName(_fromUtf8("stackedWindows")) self.classic = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.classic.sizePolicy().hasHeightForWidth()) self.classic.setSizePolicy(sizePolicy) self.classic.setObjectName(_fromUtf8("classic")) self.horizontalLayout = QtGui.QHBoxLayout(self.classic) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.splitter = QtGui.QSplitter(self.classic) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth()) self.splitter.setSizePolicy(sizePolicy) self.splitter.setMinimumSize(QtCore.QSize(600, 0)) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(_fromUtf8("splitter")) self.tabGroup = QtGui.QTabWidget(self.splitter) self.tabGroup.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.tabGroup.sizePolicy().hasHeightForWidth()) self.tabGroup.setSizePolicy(sizePolicy) self.tabGroup.setTabsClosable(False) self.tabGroup.setMovable(False) self.tabGroup.setObjectName(_fromUtf8("tabGroup")) self.freqTab = QtGui.QWidget() self.freqTab.setObjectName(_fromUtf8("freqTab")) self.horizontalLayout_9 = QtGui.QHBoxLayout(self.freqTab) self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9")) self.freqPlot = Qwt5.QwtPlot(self.freqTab) self.freqPlot.setObjectName(_fromUtf8("freqPlot")) self.horizontalLayout_9.addWidget(self.freqPlot) self.tabGroup.addTab(self.freqTab, _fromUtf8("")) self.timeTab = QtGui.QWidget() self.timeTab.setObjectName(_fromUtf8("timeTab")) self.horizontalLayout_10 = QtGui.QHBoxLayout(self.timeTab) self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10")) self.timePlot = Qwt5.QwtPlot(self.timeTab) self.timePlot.setObjectName(_fromUtf8("timePlot")) self.horizontalLayout_10.addWidget(self.timePlot) self.tabGroup.addTab(self.timeTab, _fromUtf8("")) self.phaseTab = QtGui.QWidget() self.phaseTab.setObjectName(_fromUtf8("phaseTab")) self.horizontalLayout_11 = QtGui.QHBoxLayout(self.phaseTab) self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11")) self.phasePlot = Qwt5.QwtPlot(self.phaseTab) self.phasePlot.setObjectName(_fromUtf8("phasePlot")) self.horizontalLayout_11.addWidget(self.phasePlot) self.tabGroup.addTab(self.phaseTab, _fromUtf8("")) self.groupTab = QtGui.QWidget() self.groupTab.setObjectName(_fromUtf8("groupTab")) self.horizontalLayout_12 = QtGui.QHBoxLayout(self.groupTab) self.horizontalLayout_12.setObjectName(_fromUtf8("horizontalLayout_12")) self.groupPlot = Qwt5.QwtPlot(self.groupTab) self.groupPlot.setObjectName(_fromUtf8("groupPlot")) self.horizontalLayout_12.addWidget(self.groupPlot) self.tabGroup.addTab(self.groupTab, _fromUtf8("")) self.fcTab = QtGui.QWidget() self.fcTab.setObjectName(_fromUtf8("fcTab")) self.horizontalLayout_7 = QtGui.QHBoxLayout(self.fcTab) self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.filterCoeff = QtGui.QTextBrowser(self.fcTab) self.filterCoeff.setObjectName(_fromUtf8("filterCoeff")) self.horizontalLayout_7.addWidget(self.filterCoeff) self.tabGroup.addTab(self.fcTab, _fromUtf8("")) self.impresTab = QtGui.QWidget() self.impresTab.setObjectName(_fromUtf8("impresTab")) self.horizontalLayout_6 = QtGui.QHBoxLayout(self.impresTab) self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) self.impresPlot = Qwt5.QwtPlot(self.impresTab) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.impresPlot.sizePolicy().hasHeightForWidth()) self.impresPlot.setSizePolicy(sizePolicy) self.impresPlot.setObjectName(_fromUtf8("impresPlot")) self.horizontalLayout_6.addWidget(self.impresPlot) self.tabGroup.addTab(self.impresTab, _fromUtf8("")) self.stepresTab = QtGui.QWidget() self.stepresTab.setObjectName(_fromUtf8("stepresTab")) self.horizontalLayout_8 = QtGui.QHBoxLayout(self.stepresTab) self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8")) self.stepresPlot = Qwt5.QwtPlot(self.stepresTab) self.stepresPlot.setObjectName(_fromUtf8("stepresPlot")) self.horizontalLayout_8.addWidget(self.stepresPlot) self.tabGroup.addTab(self.stepresTab, _fromUtf8("")) self.pdelayTab = QtGui.QWidget() self.pdelayTab.setObjectName(_fromUtf8("pdelayTab")) self.horizontalLayout_17 = QtGui.QHBoxLayout(self.pdelayTab) self.horizontalLayout_17.setObjectName(_fromUtf8("horizontalLayout_17")) self.pdelayPlot = Qwt5.QwtPlot(self.pdelayTab) self.pdelayPlot.setObjectName(_fromUtf8("pdelayPlot")) self.horizontalLayout_17.addWidget(self.pdelayPlot) self.tabGroup.addTab(self.pdelayTab, _fromUtf8("")) self.filterspecView = QtGui.QTabWidget(self.splitter) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.filterspecView.sizePolicy().hasHeightForWidth()) self.filterspecView.setSizePolicy(sizePolicy) self.filterspecView.setMinimumSize(QtCore.QSize(0, 100)) self.filterspecView.setBaseSize(QtCore.QSize(0, 100)) self.filterspecView.setDocumentMode(False) self.filterspecView.setTabsClosable(False) self.filterspecView.setObjectName(_fromUtf8("filterspecView")) self.bandDiagram = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.bandDiagram.sizePolicy().hasHeightForWidth()) self.bandDiagram.setSizePolicy(sizePolicy) self.bandDiagram.setObjectName(_fromUtf8("bandDiagram")) self.horizontalLayout_13 = QtGui.QHBoxLayout(self.bandDiagram) self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13")) self.bandView = BandGraphicsView(self.bandDiagram) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.bandView.sizePolicy().hasHeightForWidth()) self.bandView.setSizePolicy(sizePolicy) self.bandView.setMinimumSize(QtCore.QSize(525, 249)) self.bandView.setObjectName(_fromUtf8("bandView")) self.horizontalLayout_13.addWidget(self.bandView) self.filterspecView.addTab(self.bandDiagram, _fromUtf8("")) self.poleZero = QtGui.QWidget() self.poleZero.setAutoFillBackground(False) self.poleZero.setObjectName(_fromUtf8("poleZero")) self.gridLayout_2 = QtGui.QGridLayout(self.poleZero) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.pzPlot = PzPlot(self.poleZero) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pzPlot.sizePolicy().hasHeightForWidth()) self.pzPlot.setSizePolicy(sizePolicy) self.pzPlot.setObjectName(_fromUtf8("pzPlot")) self.gridLayout_2.addWidget(self.pzPlot, 0, 0, 1, 1) self.pzgroupBox = QtGui.QGroupBox(self.poleZero) self.pzgroupBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.pzgroupBox.setTitle(_fromUtf8("")) self.pzgroupBox.setFlat(False) self.pzgroupBox.setCheckable(False) self.pzgroupBox.setObjectName(_fromUtf8("pzgroupBox")) self.verticalLayout_3 = QtGui.QVBoxLayout(self.pzgroupBox) self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.addzeroPush = QtGui.QToolButton(self.pzgroupBox) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/add_zero.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.addzeroPush.setIcon(icon) self.addzeroPush.setIconSize(QtCore.QSize(16, 16)) self.addzeroPush.setCheckable(True) self.addzeroPush.setObjectName(_fromUtf8("addzeroPush")) self.verticalLayout_3.addWidget(self.addzeroPush) self.addpolePush = QtGui.QToolButton(self.pzgroupBox) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/add_pole.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.addpolePush.setIcon(icon1) self.addpolePush.setCheckable(True) self.addpolePush.setObjectName(_fromUtf8("addpolePush")) self.verticalLayout_3.addWidget(self.addpolePush) self.delPush = QtGui.QToolButton(self.pzgroupBox) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/remove_red.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.delPush.setIcon(icon2) self.delPush.setCheckable(True) self.delPush.setObjectName(_fromUtf8("delPush")) self.verticalLayout_3.addWidget(self.delPush) self.conjPush = QtGui.QToolButton(self.pzgroupBox) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/conjugate.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.conjPush.setIcon(icon3) self.conjPush.setIconSize(QtCore.QSize(16, 16)) self.conjPush.setCheckable(True) self.conjPush.setObjectName(_fromUtf8("conjPush")) self.verticalLayout_3.addWidget(self.conjPush) self.gridLayout_2.addWidget(self.pzgroupBox, 0, 1, 1, 1) self.pzstatusBar = QtGui.QStatusBar(self.poleZero) self.pzstatusBar.setObjectName(_fromUtf8("pzstatusBar")) self.gridLayout_2.addWidget(self.pzstatusBar, 1, 0, 1, 2) self.filterspecView.addTab(self.poleZero, _fromUtf8("")) self.horizontalLayout.addWidget(self.splitter) self.quickFrame = QtGui.QFrame(self.classic) self.quickFrame.setMinimumSize(QtCore.QSize(180, 200)) self.quickFrame.setFrameShape(QtGui.QFrame.StyledPanel) self.quickFrame.setFrameShadow(QtGui.QFrame.Raised) self.quickFrame.setObjectName(_fromUtf8("quickFrame")) self.responseBox = QtGui.QGroupBox(self.quickFrame) self.responseBox.setGeometry(QtCore.QRect(10, 10, 161, 251)) self.responseBox.setObjectName(_fromUtf8("responseBox")) self.checkMagres = QtGui.QCheckBox(self.responseBox) self.checkMagres.setGeometry(QtCore.QRect(10, 40, 151, 19)) self.checkMagres.setChecked(True) self.checkMagres.setObjectName(_fromUtf8("checkMagres")) self.checkPhase = QtGui.QCheckBox(self.responseBox) self.checkPhase.setGeometry(QtCore.QRect(10, 60, 151, 19)) self.checkPhase.setChecked(True) self.checkPhase.setObjectName(_fromUtf8("checkPhase")) self.checkGdelay = QtGui.QCheckBox(self.responseBox) self.checkGdelay.setGeometry(QtCore.QRect(10, 80, 111, 19)) self.checkGdelay.setChecked(True) self.checkGdelay.setObjectName(_fromUtf8("checkGdelay")) self.checkPdelay = QtGui.QCheckBox(self.responseBox) self.checkPdelay.setGeometry(QtCore.QRect(10, 100, 111, 19)) self.checkPdelay.setChecked(True) self.checkPdelay.setObjectName(_fromUtf8("checkPdelay")) self.checkImpulse = QtGui.QCheckBox(self.responseBox) self.checkImpulse.setGeometry(QtCore.QRect(10, 120, 141, 19)) self.checkImpulse.setChecked(True) self.checkImpulse.setObjectName(_fromUtf8("checkImpulse")) self.checkStep = QtGui.QCheckBox(self.responseBox) self.checkStep.setGeometry(QtCore.QRect(10, 140, 131, 19)) self.checkStep.setChecked(True) self.checkStep.setObjectName(_fromUtf8("checkStep")) self.checkGrid = QtGui.QCheckBox(self.responseBox) self.checkGrid.setGeometry(QtCore.QRect(10, 160, 85, 19)) self.checkGrid.setObjectName(_fromUtf8("checkGrid")) self.checkFcoeff = QtGui.QCheckBox(self.responseBox) self.checkFcoeff.setGeometry(QtCore.QRect(10, 180, 131, 19)) self.checkFcoeff.setChecked(True) self.checkFcoeff.setObjectName(_fromUtf8("checkFcoeff")) self.checkKeepcur = QtGui.QCheckBox(self.responseBox) self.checkKeepcur.setGeometry(QtCore.QRect(10, 200, 141, 19)) self.checkKeepcur.setObjectName(_fromUtf8("checkKeepcur")) self.groupSpecs = QtGui.QGroupBox(self.quickFrame) self.groupSpecs.setGeometry(QtCore.QRect(10, 280, 161, 91)) self.groupSpecs.setObjectName(_fromUtf8("groupSpecs")) self.checkBand = QtGui.QCheckBox(self.groupSpecs) self.checkBand.setGeometry(QtCore.QRect(10, 20, 111, 19)) self.checkBand.setChecked(True) self.checkBand.setObjectName(_fromUtf8("checkBand")) self.checkPzplot = QtGui.QCheckBox(self.groupSpecs) self.checkPzplot.setGeometry(QtCore.QRect(10, 40, 131, 19)) self.checkPzplot.setChecked(True) self.checkPzplot.setObjectName(_fromUtf8("checkPzplot")) self.sysParamsBox = QtGui.QGroupBox(self.quickFrame) self.sysParamsBox.setGeometry(QtCore.QRect(10, 390, 161, 91)) self.sysParamsBox.setObjectName(_fromUtf8("sysParamsBox")) self.formLayout_4 = QtGui.QFormLayout(self.sysParamsBox) self.formLayout_4.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_4.setObjectName(_fromUtf8("formLayout_4")) self.nfftLabel = QtGui.QLabel(self.sysParamsBox) self.nfftLabel.setMinimumSize(QtCore.QSize(150, 0)) self.nfftLabel.setObjectName(_fromUtf8("nfftLabel")) self.formLayout_4.setWidget(1, QtGui.QFormLayout.LabelRole, self.nfftLabel) self.nfftEdit = QtGui.QLineEdit(self.sysParamsBox) self.nfftEdit.setObjectName(_fromUtf8("nfftEdit")) self.formLayout_4.setWidget(2, QtGui.QFormLayout.LabelRole, self.nfftEdit) self.horizontalLayout.addWidget(self.quickFrame) self.stackedWindows.addWidget(self.classic) self.modern = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.modern.sizePolicy().hasHeightForWidth()) self.modern.setSizePolicy(sizePolicy) self.modern.setObjectName(_fromUtf8("modern")) self.horizontalLayout_5 = QtGui.QHBoxLayout(self.modern) self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) self.splitter_3 = QtGui.QSplitter(self.modern) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.splitter_3.sizePolicy().hasHeightForWidth()) self.splitter_3.setSizePolicy(sizePolicy) self.splitter_3.setOrientation(QtCore.Qt.Vertical) self.splitter_3.setObjectName(_fromUtf8("splitter_3")) self.splitter_2 = QtGui.QSplitter(self.splitter_3) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(_fromUtf8("splitter_2")) self.mfreqTabgroup = QtGui.QTabWidget(self.splitter_2) self.mfreqTabgroup.setTabsClosable(False) self.mfreqTabgroup.setObjectName(_fromUtf8("mfreqTabgroup")) self.mfreqTab = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mfreqTab.sizePolicy().hasHeightForWidth()) self.mfreqTab.setSizePolicy(sizePolicy) self.mfreqTab.setObjectName(_fromUtf8("mfreqTab")) self.horizontalLayout_2 = QtGui.QHBoxLayout(self.mfreqTab) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.mfreqPlot = Qwt5.QwtPlot(self.mfreqTab) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mfreqPlot.sizePolicy().hasHeightForWidth()) self.mfreqPlot.setSizePolicy(sizePolicy) self.mfreqPlot.setObjectName(_fromUtf8("mfreqPlot")) self.horizontalLayout_2.addWidget(self.mfreqPlot) self.mfgroupBox = QtGui.QGroupBox(self.mfreqTab) self.mfgroupBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.mfgroupBox.setTitle(_fromUtf8("")) self.mfgroupBox.setFlat(False) self.mfgroupBox.setCheckable(False) self.mfgroupBox.setObjectName(_fromUtf8("mfgroupBox")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.mfgroupBox) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.mfmagPush = QtGui.QToolButton(self.mfgroupBox) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/mag_response.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfmagPush.setIcon(icon4) self.mfmagPush.setIconSize(QtCore.QSize(16, 16)) self.mfmagPush.setCheckable(False) self.mfmagPush.setObjectName(_fromUtf8("mfmagPush")) self.verticalLayout_2.addWidget(self.mfmagPush) self.mfphasePush = QtGui.QToolButton(self.mfgroupBox) icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/phase_response.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfphasePush.setIcon(icon5) self.mfphasePush.setIconSize(QtCore.QSize(16, 16)) self.mfphasePush.setCheckable(False) self.mfphasePush.setObjectName(_fromUtf8("mfphasePush")) self.verticalLayout_2.addWidget(self.mfphasePush) self.mfgpdlyPush = QtGui.QToolButton(self.mfgroupBox) icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/group_delay.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfgpdlyPush.setIcon(icon6) self.mfgpdlyPush.setIconSize(QtCore.QSize(16, 16)) self.mfgpdlyPush.setCheckable(False) self.mfgpdlyPush.setObjectName(_fromUtf8("mfgpdlyPush")) self.verticalLayout_2.addWidget(self.mfgpdlyPush) self.mfphdlyPush = QtGui.QToolButton(self.mfgroupBox) icon7 = QtGui.QIcon() icon7.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/phase_delay.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfphdlyPush.setIcon(icon7) self.mfphdlyPush.setIconSize(QtCore.QSize(16, 16)) self.mfphdlyPush.setCheckable(False) self.mfphdlyPush.setObjectName(_fromUtf8("mfphdlyPush")) self.verticalLayout_2.addWidget(self.mfphdlyPush) self.mfoverlayPush = QtGui.QToolButton(self.mfgroupBox) icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/overlay.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mfoverlayPush.setIcon(icon8) self.mfoverlayPush.setIconSize(QtCore.QSize(16, 16)) self.mfoverlayPush.setCheckable(True) self.mfoverlayPush.setObjectName(_fromUtf8("mfoverlayPush")) self.verticalLayout_2.addWidget(self.mfoverlayPush) self.horizontalLayout_2.addWidget(self.mfgroupBox) self.mfreqTabgroup.addTab(self.mfreqTab, _fromUtf8("")) self.mtimeTabgroup = QtGui.QTabWidget(self.splitter_2) self.mtimeTabgroup.setObjectName(_fromUtf8("mtimeTabgroup")) self.mtimeTab = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mtimeTab.sizePolicy().hasHeightForWidth()) self.mtimeTab.setSizePolicy(sizePolicy) self.mtimeTab.setObjectName(_fromUtf8("mtimeTab")) self.horizontalLayout_3 = QtGui.QHBoxLayout(self.mtimeTab) self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.mtimePlot = Qwt5.QwtPlot(self.mtimeTab) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mtimePlot.sizePolicy().hasHeightForWidth()) self.mtimePlot.setSizePolicy(sizePolicy) self.mtimePlot.setObjectName(_fromUtf8("mtimePlot")) self.horizontalLayout_3.addWidget(self.mtimePlot) self.mtgroupBox = QtGui.QGroupBox(self.mtimeTab) self.mtgroupBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.mtgroupBox.setTitle(_fromUtf8("")) self.mtgroupBox.setFlat(False) self.mtgroupBox.setCheckable(False) self.mtgroupBox.setObjectName(_fromUtf8("mtgroupBox")) self.verticalLayout_5 = QtGui.QVBoxLayout(self.mtgroupBox) self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) self.mttapsPush = QtGui.QToolButton(self.mtgroupBox) icon9 = QtGui.QIcon() icon9.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/filtr_taps.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mttapsPush.setIcon(icon9) self.mttapsPush.setIconSize(QtCore.QSize(16, 16)) self.mttapsPush.setCheckable(False) self.mttapsPush.setObjectName(_fromUtf8("mttapsPush")) self.verticalLayout_5.addWidget(self.mttapsPush) self.mtstepPush = QtGui.QToolButton(self.mtgroupBox) icon10 = QtGui.QIcon() icon10.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/step_response.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mtstepPush.setIcon(icon10) self.mtstepPush.setIconSize(QtCore.QSize(16, 16)) self.mtstepPush.setCheckable(False) self.mtstepPush.setObjectName(_fromUtf8("mtstepPush")) self.verticalLayout_5.addWidget(self.mtstepPush) self.mtimpPush = QtGui.QToolButton(self.mtgroupBox) icon11 = QtGui.QIcon() icon11.addPixmap(QtGui.QPixmap(_fromUtf8(":/icons/impulse.svg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.mtimpPush.setIcon(icon11) self.mtimpPush.setIconSize(QtCore.QSize(16, 16)) self.mtimpPush.setCheckable(False) self.mtimpPush.setObjectName(_fromUtf8("mtimpPush")) self.verticalLayout_5.addWidget(self.mtimpPush) self.horizontalLayout_3.addWidget(self.mtgroupBox) self.mtimeTabgroup.addTab(self.mtimeTab, _fromUtf8("")) self.mfilterspecView = QtGui.QTabWidget(self.splitter_3) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mfilterspecView.sizePolicy().hasHeightForWidth()) self.mfilterspecView.setSizePolicy(sizePolicy) self.mfilterspecView.setMinimumSize(QtCore.QSize(0, 100)) self.mfilterspecView.setBaseSize(QtCore.QSize(0, 100)) self.mfilterspecView.setDocumentMode(False) self.mfilterspecView.setTabsClosable(False) self.mfilterspecView.setObjectName(_fromUtf8("mfilterspecView")) self.mbandDiagram = QtGui.QWidget() sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mbandDiagram.sizePolicy().hasHeightForWidth()) self.mbandDiagram.setSizePolicy(sizePolicy) self.mbandDiagram.setObjectName(_fromUtf8("mbandDiagram")) self.horizontalLayout_15 = QtGui.QHBoxLayout(self.mbandDiagram) self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15")) self.mbandView = BandGraphicsView(self.mbandDiagram) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.mbandView.sizePolicy().hasHeightForWidth()) self.mbandView.setSizePolicy(sizePolicy) self.mbandView.setMinimumSize(QtCore.QSize(525, 249)) self.mbandView.setObjectName(_fromUtf8("mbandView")) self.horizontalLayout_15.addWidget(self.mbandView) self.mfilterspecView.addTab(self.mbandDiagram, _fromUtf8("")) self.mpoleZero = QtGui.QWidget() self.mpoleZero.setAutoFillBackground(False) self.mpoleZero.setObjectName(_fromUtf8("mpoleZero")) self.gridLayout_3 = QtGui.QGridLayout(self.mpoleZero) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.mpzPlot = PzPlot(self.mpoleZero) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mpzPlot.sizePolicy().hasHeightForWidth()) self.mpzPlot.setSizePolicy(sizePolicy) self.mpzPlot.setObjectName(_fromUtf8("mpzPlot")) self.gridLayout_3.addWidget(self.mpzPlot, 0, 0, 1, 1) self.mpzgroupBox = QtGui.QGroupBox(self.mpoleZero) self.mpzgroupBox.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.mpzgroupBox.setTitle(_fromUtf8("")) self.mpzgroupBox.setFlat(False) self.mpzgroupBox.setCheckable(False) self.mpzgroupBox.setObjectName(_fromUtf8("mpzgroupBox")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.mpzgroupBox) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.maddzeroPush = QtGui.QToolButton(self.mpzgroupBox) self.maddzeroPush.setIcon(icon) self.maddzeroPush.setCheckable(True) self.maddzeroPush.setObjectName(_fromUtf8("maddzeroPush")) self.verticalLayout_4.addWidget(self.maddzeroPush) self.maddpolePush = QtGui.QToolButton(self.mpzgroupBox) self.maddpolePush.setIcon(icon1) self.maddpolePush.setCheckable(True) self.maddpolePush.setObjectName(_fromUtf8("maddpolePush")) self.verticalLayout_4.addWidget(self.maddpolePush) self.mdelPush = QtGui.QToolButton(self.mpzgroupBox) self.mdelPush.setIcon(icon2) self.mdelPush.setCheckable(True) self.mdelPush.setObjectName(_fromUtf8("mdelPush")) self.verticalLayout_4.addWidget(self.mdelPush) self.mconjPush = QtGui.QToolButton(self.mpzgroupBox) self.mconjPush.setIcon(icon3) self.mconjPush.setIconSize(QtCore.QSize(16, 16)) self.mconjPush.setCheckable(True) self.mconjPush.setObjectName(_fromUtf8("mconjPush")) self.verticalLayout_4.addWidget(self.mconjPush) self.gridLayout_3.addWidget(self.mpzgroupBox, 0, 1, 1, 1) self.mpzstatusBar = QtGui.QStatusBar(self.mpoleZero) self.mpzstatusBar.setObjectName(_fromUtf8("mpzstatusBar")) self.gridLayout_3.addWidget(self.mpzstatusBar, 1, 0, 1, 2) self.mfilterspecView.addTab(self.mpoleZero, _fromUtf8("")) self.mfcTab = QtGui.QWidget() self.mfcTab.setObjectName(_fromUtf8("mfcTab")) self.horizontalLayout_4 = QtGui.QHBoxLayout(self.mfcTab) self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.mfilterCoeff = QtGui.QTextBrowser(self.mfcTab) self.mfilterCoeff.setObjectName(_fromUtf8("mfilterCoeff")) self.horizontalLayout_4.addWidget(self.mfilterCoeff) self.mfilterspecView.addTab(self.mfcTab, _fromUtf8("")) self.horizontalLayout_5.addWidget(self.splitter_3) self.stackedWindows.addWidget(self.modern) self.gridLayout.addWidget(self.stackedWindows, 0, 1, 1, 1) self.filterFrame = QtGui.QFrame(self.centralwidget) self.filterFrame.setMinimumSize(QtCore.QSize(300, 0)) self.filterFrame.setMaximumSize(QtCore.QSize(300, 16777215)) self.filterFrame.setFrameShape(QtGui.QFrame.StyledPanel) self.filterFrame.setFrameShadow(QtGui.QFrame.Raised) self.filterFrame.setObjectName(_fromUtf8("filterFrame")) self.verticalLayout = QtGui.QVBoxLayout(self.filterFrame) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.fselectComboBox = QtGui.QComboBox(self.filterFrame) self.fselectComboBox.setEnabled(True) self.fselectComboBox.setObjectName(_fromUtf8("fselectComboBox")) self.fselectComboBox.addItem(_fromUtf8("")) self.fselectComboBox.addItem(_fromUtf8("")) self.verticalLayout.addWidget(self.fselectComboBox) self.filterTypeComboBox = QtGui.QComboBox(self.filterFrame) self.filterTypeComboBox.setObjectName(_fromUtf8("filterTypeComboBox")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.filterTypeComboBox.addItem(_fromUtf8("")) self.verticalLayout.addWidget(self.filterTypeComboBox) self.iirfilterBandComboBox = QtGui.QComboBox(self.filterFrame) self.iirfilterBandComboBox.setObjectName(_fromUtf8("iirfilterBandComboBox")) self.iirfilterBandComboBox.addItem(_fromUtf8("")) self.iirfilterBandComboBox.addItem(_fromUtf8("")) self.iirfilterBandComboBox.addItem(_fromUtf8("")) self.iirfilterBandComboBox.addItem(_fromUtf8("")) self.verticalLayout.addWidget(self.iirfilterBandComboBox) self.adComboBox = QtGui.QComboBox(self.filterFrame) self.adComboBox.setObjectName(_fromUtf8("adComboBox")) self.adComboBox.addItem(_fromUtf8("")) self.adComboBox.addItem(_fromUtf8("")) self.verticalLayout.addWidget(self.adComboBox) self.filterDesignTypeComboBox = QtGui.QComboBox(self.filterFrame) self.filterDesignTypeComboBox.setObjectName(_fromUtf8("filterDesignTypeComboBox")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.filterDesignTypeComboBox.addItem(_fromUtf8("")) self.verticalLayout.addWidget(self.filterDesignTypeComboBox) self.iirfilterTypeComboBox = QtGui.QComboBox(self.filterFrame) self.iirfilterTypeComboBox.setObjectName(_fromUtf8("iirfilterTypeComboBox")) self.iirfilterTypeComboBox.addItem(_fromUtf8("")) self.iirfilterTypeComboBox.addItem(_fromUtf8("")) self.iirfilterTypeComboBox.addItem(_fromUtf8("")) self.iirfilterTypeComboBox.addItem(_fromUtf8("")) self.iirfilterTypeComboBox.addItem(_fromUtf8("")) self.verticalLayout.addWidget(self.iirfilterTypeComboBox) self.globalParamsBox = QtGui.QGroupBox(self.filterFrame) self.globalParamsBox.setTitle(_fromUtf8("")) self.globalParamsBox.setObjectName(_fromUtf8("globalParamsBox")) self.formLayout_12 = QtGui.QFormLayout(self.globalParamsBox) self.formLayout_12.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_12.setObjectName(_fromUtf8("formLayout_12")) self.sampleRateLabel = QtGui.QLabel(self.globalParamsBox) self.sampleRateLabel.setMaximumSize(QtCore.QSize(16777215, 30)) self.sampleRateLabel.setObjectName(_fromUtf8("sampleRateLabel")) self.formLayout_12.setWidget(0, QtGui.QFormLayout.LabelRole, self.sampleRateLabel) self.sampleRateEdit = QtGui.QLineEdit(self.globalParamsBox) self.sampleRateEdit.setMaximumSize(QtCore.QSize(16777215, 30)) self.sampleRateEdit.setObjectName(_fromUtf8("sampleRateEdit")) self.formLayout_12.setWidget(0, QtGui.QFormLayout.FieldRole, self.sampleRateEdit) self.filterGainLabel = QtGui.QLabel(self.globalParamsBox) self.filterGainLabel.setObjectName(_fromUtf8("filterGainLabel")) self.formLayout_12.setWidget(1, QtGui.QFormLayout.LabelRole, self.filterGainLabel) self.filterGainEdit = QtGui.QLineEdit(self.globalParamsBox) self.filterGainEdit.setObjectName(_fromUtf8("filterGainEdit")) self.formLayout_12.setWidget(1, QtGui.QFormLayout.FieldRole, self.filterGainEdit) self.verticalLayout.addWidget(self.globalParamsBox) self.filterTypeWidget = QtGui.QStackedWidget(self.filterFrame) self.filterTypeWidget.setObjectName(_fromUtf8("filterTypeWidget")) self.firlpfPage = QtGui.QWidget() self.firlpfPage.setObjectName(_fromUtf8("firlpfPage")) self.formLayout = QtGui.QFormLayout(self.firlpfPage) self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout.setObjectName(_fromUtf8("formLayout")) self.endofLpfPassBandLabel = QtGui.QLabel(self.firlpfPage) self.endofLpfPassBandLabel.setObjectName(_fromUtf8("endofLpfPassBandLabel")) self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.endofLpfPassBandLabel) self.endofLpfPassBandEdit = QtGui.QLineEdit(self.firlpfPage) self.endofLpfPassBandEdit.setObjectName(_fromUtf8("endofLpfPassBandEdit")) self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.endofLpfPassBandEdit) self.startofLpfStopBandLabel = QtGui.QLabel(self.firlpfPage) self.startofLpfStopBandLabel.setObjectName(_fromUtf8("startofLpfStopBandLabel")) self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.startofLpfStopBandLabel) self.startofLpfStopBandEdit = QtGui.QLineEdit(self.firlpfPage) self.startofLpfStopBandEdit.setObjectName(_fromUtf8("startofLpfStopBandEdit")) self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.startofLpfStopBandEdit) self.lpfStopBandAttenLabel = QtGui.QLabel(self.firlpfPage) self.lpfStopBandAttenLabel.setObjectName(_fromUtf8("lpfStopBandAttenLabel")) self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.lpfStopBandAttenLabel) self.lpfStopBandAttenEdit = QtGui.QLineEdit(self.firlpfPage) self.lpfStopBandAttenEdit.setObjectName(_fromUtf8("lpfStopBandAttenEdit")) self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.lpfStopBandAttenEdit) self.lpfPassBandRippleLabel = QtGui.QLabel(self.firlpfPage) self.lpfPassBandRippleLabel.setObjectName(_fromUtf8("lpfPassBandRippleLabel")) self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.lpfPassBandRippleLabel) self.lpfPassBandRippleEdit = QtGui.QLineEdit(self.firlpfPage) self.lpfPassBandRippleEdit.setObjectName(_fromUtf8("lpfPassBandRippleEdit")) self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.lpfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firlpfPage) self.firbpfPage = QtGui.QWidget() self.firbpfPage.setObjectName(_fromUtf8("firbpfPage")) self.formLayout_2 = QtGui.QFormLayout(self.firbpfPage) self.formLayout_2.setObjectName(_fromUtf8("formLayout_2")) self.startofBpfPassBandLabel = QtGui.QLabel(self.firbpfPage) self.startofBpfPassBandLabel.setObjectName(_fromUtf8("startofBpfPassBandLabel")) self.formLayout_2.setWidget(0, QtGui.QFormLayout.LabelRole, self.startofBpfPassBandLabel) self.startofBpfPassBandEdit = QtGui.QLineEdit(self.firbpfPage) self.startofBpfPassBandEdit.setObjectName(_fromUtf8("startofBpfPassBandEdit")) self.formLayout_2.setWidget(0, QtGui.QFormLayout.FieldRole, self.startofBpfPassBandEdit) self.endofBpfPassBandLabel = QtGui.QLabel(self.firbpfPage) self.endofBpfPassBandLabel.setObjectName(_fromUtf8("endofBpfPassBandLabel")) self.formLayout_2.setWidget(1, QtGui.QFormLayout.LabelRole, self.endofBpfPassBandLabel) self.endofBpfPassBandEdit = QtGui.QLineEdit(self.firbpfPage) self.endofBpfPassBandEdit.setObjectName(_fromUtf8("endofBpfPassBandEdit")) self.formLayout_2.setWidget(1, QtGui.QFormLayout.FieldRole, self.endofBpfPassBandEdit) self.bpfStopBandAttenEdit = QtGui.QLineEdit(self.firbpfPage) self.bpfStopBandAttenEdit.setObjectName(_fromUtf8("bpfStopBandAttenEdit")) self.formLayout_2.setWidget(3, QtGui.QFormLayout.FieldRole, self.bpfStopBandAttenEdit) self.bpfStopBandAttenLabel = QtGui.QLabel(self.firbpfPage) self.bpfStopBandAttenLabel.setObjectName(_fromUtf8("bpfStopBandAttenLabel")) self.formLayout_2.setWidget(3, QtGui.QFormLayout.LabelRole, self.bpfStopBandAttenLabel) self.bpfTransitionLabel = QtGui.QLabel(self.firbpfPage) self.bpfTransitionLabel.setObjectName(_fromUtf8("bpfTransitionLabel")) self.formLayout_2.setWidget(2, QtGui.QFormLayout.LabelRole, self.bpfTransitionLabel) self.bpfTransitionEdit = QtGui.QLineEdit(self.firbpfPage) self.bpfTransitionEdit.setObjectName(_fromUtf8("bpfTransitionEdit")) self.formLayout_2.setWidget(2, QtGui.QFormLayout.FieldRole, self.bpfTransitionEdit) self.bpfPassBandRippleEdit = QtGui.QLineEdit(self.firbpfPage) self.bpfPassBandRippleEdit.setObjectName(_fromUtf8("bpfPassBandRippleEdit")) self.formLayout_2.setWidget(4, QtGui.QFormLayout.FieldRole, self.bpfPassBandRippleEdit) self.bpfPassBandRippleLabel = QtGui.QLabel(self.firbpfPage) self.bpfPassBandRippleLabel.setObjectName(_fromUtf8("bpfPassBandRippleLabel")) self.formLayout_2.setWidget(4, QtGui.QFormLayout.LabelRole, self.bpfPassBandRippleLabel) self.filterTypeWidget.addWidget(self.firbpfPage) self.firbnfPage = QtGui.QWidget() self.firbnfPage.setObjectName(_fromUtf8("firbnfPage")) self.formLayout_5 = QtGui.QFormLayout(self.firbnfPage) self.formLayout_5.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_5.setObjectName(_fromUtf8("formLayout_5")) self.startofBnfStopBandLabel = QtGui.QLabel(self.firbnfPage) self.startofBnfStopBandLabel.setObjectName(_fromUtf8("startofBnfStopBandLabel")) self.formLayout_5.setWidget(0, QtGui.QFormLayout.LabelRole, self.startofBnfStopBandLabel) self.startofBnfStopBandEdit = QtGui.QLineEdit(self.firbnfPage) self.startofBnfStopBandEdit.setObjectName(_fromUtf8("startofBnfStopBandEdit")) self.formLayout_5.setWidget(0, QtGui.QFormLayout.FieldRole, self.startofBnfStopBandEdit) self.endofBnfStopBandLabel = QtGui.QLabel(self.firbnfPage) self.endofBnfStopBandLabel.setObjectName(_fromUtf8("endofBnfStopBandLabel")) self.formLayout_5.setWidget(1, QtGui.QFormLayout.LabelRole, self.endofBnfStopBandLabel) self.endofBnfStopBandEdit = QtGui.QLineEdit(self.firbnfPage) self.endofBnfStopBandEdit.setObjectName(_fromUtf8("endofBnfStopBandEdit")) self.formLayout_5.setWidget(1, QtGui.QFormLayout.FieldRole, self.endofBnfStopBandEdit) self.bnfTransitionLabel = QtGui.QLabel(self.firbnfPage) self.bnfTransitionLabel.setObjectName(_fromUtf8("bnfTransitionLabel")) self.formLayout_5.setWidget(2, QtGui.QFormLayout.LabelRole, self.bnfTransitionLabel) self.bnfTransitionEdit = QtGui.QLineEdit(self.firbnfPage) self.bnfTransitionEdit.setObjectName(_fromUtf8("bnfTransitionEdit")) self.formLayout_5.setWidget(2, QtGui.QFormLayout.FieldRole, self.bnfTransitionEdit) self.bnfStopBandAttenLabel = QtGui.QLabel(self.firbnfPage) self.bnfStopBandAttenLabel.setObjectName(_fromUtf8("bnfStopBandAttenLabel")) self.formLayout_5.setWidget(3, QtGui.QFormLayout.LabelRole, self.bnfStopBandAttenLabel) self.bnfStopBandAttenEdit = QtGui.QLineEdit(self.firbnfPage) self.bnfStopBandAttenEdit.setObjectName(_fromUtf8("bnfStopBandAttenEdit")) self.formLayout_5.setWidget(3, QtGui.QFormLayout.FieldRole, self.bnfStopBandAttenEdit) self.bnfPassBandRippleLabel = QtGui.QLabel(self.firbnfPage) self.bnfPassBandRippleLabel.setObjectName(_fromUtf8("bnfPassBandRippleLabel")) self.formLayout_5.setWidget(4, QtGui.QFormLayout.LabelRole, self.bnfPassBandRippleLabel) self.bnfPassBandRippleEdit = QtGui.QLineEdit(self.firbnfPage) self.bnfPassBandRippleEdit.setObjectName(_fromUtf8("bnfPassBandRippleEdit")) self.formLayout_5.setWidget(4, QtGui.QFormLayout.FieldRole, self.bnfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firbnfPage) self.firhpfPage = QtGui.QWidget() self.firhpfPage.setObjectName(_fromUtf8("firhpfPage")) self.formLayout_3 = QtGui.QFormLayout(self.firhpfPage) self.formLayout_3.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_3.setObjectName(_fromUtf8("formLayout_3")) self.endofHpfStopBandLabel = QtGui.QLabel(self.firhpfPage) self.endofHpfStopBandLabel.setObjectName(_fromUtf8("endofHpfStopBandLabel")) self.formLayout_3.setWidget(0, QtGui.QFormLayout.LabelRole, self.endofHpfStopBandLabel) self.endofHpfStopBandEdit = QtGui.QLineEdit(self.firhpfPage) self.endofHpfStopBandEdit.setObjectName(_fromUtf8("endofHpfStopBandEdit")) self.formLayout_3.setWidget(0, QtGui.QFormLayout.FieldRole, self.endofHpfStopBandEdit) self.startofHpfPassBandLabel = QtGui.QLabel(self.firhpfPage) self.startofHpfPassBandLabel.setObjectName(_fromUtf8("startofHpfPassBandLabel")) self.formLayout_3.setWidget(1, QtGui.QFormLayout.LabelRole, self.startofHpfPassBandLabel) self.startofHpfPassBandEdit = QtGui.QLineEdit(self.firhpfPage) self.startofHpfPassBandEdit.setObjectName(_fromUtf8("startofHpfPassBandEdit")) self.formLayout_3.setWidget(1, QtGui.QFormLayout.FieldRole, self.startofHpfPassBandEdit) self.hpfStopBandAttenLabel = QtGui.QLabel(self.firhpfPage) self.hpfStopBandAttenLabel.setObjectName(_fromUtf8("hpfStopBandAttenLabel")) self.formLayout_3.setWidget(2, QtGui.QFormLayout.LabelRole, self.hpfStopBandAttenLabel) self.hpfStopBandAttenEdit = QtGui.QLineEdit(self.firhpfPage) self.hpfStopBandAttenEdit.setObjectName(_fromUtf8("hpfStopBandAttenEdit")) self.formLayout_3.setWidget(2, QtGui.QFormLayout.FieldRole, self.hpfStopBandAttenEdit) self.hpfPassBandRippleLabel = QtGui.QLabel(self.firhpfPage) self.hpfPassBandRippleLabel.setObjectName(_fromUtf8("hpfPassBandRippleLabel")) self.formLayout_3.setWidget(3, QtGui.QFormLayout.LabelRole, self.hpfPassBandRippleLabel) self.hpfPassBandRippleEdit = QtGui.QLineEdit(self.firhpfPage) self.hpfPassBandRippleEdit.setObjectName(_fromUtf8("hpfPassBandRippleEdit")) self.formLayout_3.setWidget(3, QtGui.QFormLayout.FieldRole, self.hpfPassBandRippleEdit) self.filterTypeWidget.addWidget(self.firhpfPage) self.rrcPage = QtGui.QWidget() self.rrcPage.setObjectName(_fromUtf8("rrcPage")) self.formLayout_6 = QtGui.QFormLayout(self.rrcPage) self.formLayout_6.setObjectName(_fromUtf8("formLayout_6")) self.rrcSymbolRateLabel = QtGui.QLabel(self.rrcPage) self.rrcSymbolRateLabel.setObjectName(_fromUtf8("rrcSymbolRateLabel")) self.formLayout_6.setWidget(0, QtGui.QFormLayout.LabelRole, self.rrcSymbolRateLabel) self.rrcAlphaLabel = QtGui.QLabel(self.rrcPage) self.rrcAlphaLabel.setObjectName(_fromUtf8("rrcAlphaLabel")) self.formLayout_6.setWidget(1, QtGui.QFormLayout.LabelRole, self.rrcAlphaLabel) self.rrcNumTapsLabel = QtGui.QLabel(self.rrcPage) self.rrcNumTapsLabel.setObjectName(_fromUtf8("rrcNumTapsLabel")) self.formLayout_6.setWidget(2, QtGui.QFormLayout.LabelRole, self.rrcNumTapsLabel) self.rrcSymbolRateEdit = QtGui.QLineEdit(self.rrcPage) self.rrcSymbolRateEdit.setObjectName(_fromUtf8("rrcSymbolRateEdit")) self.formLayout_6.setWidget(0, QtGui.QFormLayout.FieldRole, self.rrcSymbolRateEdit) self.rrcAlphaEdit = QtGui.QLineEdit(self.rrcPage) self.rrcAlphaEdit.setObjectName(_fromUtf8("rrcAlphaEdit")) self.formLayout_6.setWidget(1, QtGui.QFormLayout.FieldRole, self.rrcAlphaEdit) self.rrcNumTapsEdit = QtGui.QLineEdit(self.rrcPage) self.rrcNumTapsEdit.setObjectName(_fromUtf8("rrcNumTapsEdit")) self.formLayout_6.setWidget(2, QtGui.QFormLayout.FieldRole, self.rrcNumTapsEdit) self.filterTypeWidget.addWidget(self.rrcPage) self.gausPage = QtGui.QWidget() self.gausPage.setObjectName(_fromUtf8("gausPage")) self.formLayout_7 = QtGui.QFormLayout(self.gausPage) self.formLayout_7.setObjectName(_fromUtf8("formLayout_7")) self.gausSymbolRateLabel = QtGui.QLabel(self.gausPage) self.gausSymbolRateLabel.setObjectName(_fromUtf8("gausSymbolRateLabel")) self.formLayout_7.setWidget(0, QtGui.QFormLayout.LabelRole, self.gausSymbolRateLabel) self.gausSymbolRateEdit = QtGui.QLineEdit(self.gausPage) self.gausSymbolRateEdit.setObjectName(_fromUtf8("gausSymbolRateEdit")) self.formLayout_7.setWidget(0, QtGui.QFormLayout.FieldRole, self.gausSymbolRateEdit) self.gausBTLabel = QtGui.QLabel(self.gausPage) self.gausBTLabel.setObjectName(_fromUtf8("gausBTLabel")) self.formLayout_7.setWidget(1, QtGui.QFormLayout.LabelRole, self.gausBTLabel) self.gausBTEdit = QtGui.QLineEdit(self.gausPage) self.gausBTEdit.setObjectName(_fromUtf8("gausBTEdit")) self.formLayout_7.setWidget(1, QtGui.QFormLayout.FieldRole, self.gausBTEdit) self.gausNumTapsLabel = QtGui.QLabel(self.gausPage) self.gausNumTapsLabel.setObjectName(_fromUtf8("gausNumTapsLabel")) self.formLayout_7.setWidget(2, QtGui.QFormLayout.LabelRole, self.gausNumTapsLabel) self.gausNumTapsEdit = QtGui.QLineEdit(self.gausPage) self.gausNumTapsEdit.setObjectName(_fromUtf8("gausNumTapsEdit")) self.formLayout_7.setWidget(2, QtGui.QFormLayout.FieldRole, self.gausNumTapsEdit) self.filterTypeWidget.addWidget(self.gausPage) self.iirlpfPage = QtGui.QWidget() self.iirlpfPage.setObjectName(_fromUtf8("iirlpfPage")) self.formLayout_15 = QtGui.QFormLayout(self.iirlpfPage) self.formLayout_15.setObjectName(_fromUtf8("formLayout_15")) self.iirendofLpfPassBandLabel = QtGui.QLabel(self.iirlpfPage) self.iirendofLpfPassBandLabel.setObjectName(_fromUtf8("iirendofLpfPassBandLabel")) self.formLayout_15.setWidget(0, QtGui.QFormLayout.LabelRole, self.iirendofLpfPassBandLabel) self.iirendofLpfPassBandEdit = QtGui.QLineEdit(self.iirlpfPage) self.iirendofLpfPassBandEdit.setObjectName(_fromUtf8("iirendofLpfPassBandEdit")) self.formLayout_15.setWidget(0, QtGui.QFormLayout.FieldRole, self.iirendofLpfPassBandEdit) self.iirstartofLpfStopBandLabel = QtGui.QLabel(self.iirlpfPage) self.iirstartofLpfStopBandLabel.setObjectName(_fromUtf8("iirstartofLpfStopBandLabel")) self.formLayout_15.setWidget(1, QtGui.QFormLayout.LabelRole, self.iirstartofLpfStopBandLabel) self.iirstartofLpfStopBandEdit = QtGui.QLineEdit(self.iirlpfPage) self.iirstartofLpfStopBandEdit.setObjectName(_fromUtf8("iirstartofLpfStopBandEdit")) self.formLayout_15.setWidget(1, QtGui.QFormLayout.FieldRole, self.iirstartofLpfStopBandEdit) self.iirLpfPassBandAttenLabel = QtGui.QLabel(self.iirlpfPage) self.iirLpfPassBandAttenLabel.setObjectName(_fromUtf8("iirLpfPassBandAttenLabel")) self.formLayout_15.setWidget(2, QtGui.QFormLayout.LabelRole, self.iirLpfPassBandAttenLabel) self.iirLpfPassBandAttenEdit = QtGui.QLineEdit(self.iirlpfPage) self.iirLpfPassBandAttenEdit.setObjectName(_fromUtf8("iirLpfPassBandAttenEdit")) self.formLayout_15.setWidget(2, QtGui.QFormLayout.FieldRole, self.iirLpfPassBandAttenEdit) self.iirLpfStopBandRippleLabel = QtGui.QLabel(self.iirlpfPage) self.iirLpfStopBandRippleLabel.setObjectName(_fromUtf8("iirLpfStopBandRippleLabel")) self.formLayout_15.setWidget(3, QtGui.QFormLayout.LabelRole, self.iirLpfStopBandRippleLabel) self.iirLpfStopBandRippleEdit = QtGui.QLineEdit(self.iirlpfPage) self.iirLpfStopBandRippleEdit.setObjectName(_fromUtf8("iirLpfStopBandRippleEdit")) self.formLayout_15.setWidget(3, QtGui.QFormLayout.FieldRole, self.iirLpfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirlpfPage) self.iirhpfPage = QtGui.QWidget() self.iirhpfPage.setObjectName(_fromUtf8("iirhpfPage")) self.formLayout_9 = QtGui.QFormLayout(self.iirhpfPage) self.formLayout_9.setObjectName(_fromUtf8("formLayout_9")) self.iirendofHpfStopBandLabel = QtGui.QLabel(self.iirhpfPage) self.iirendofHpfStopBandLabel.setObjectName(_fromUtf8("iirendofHpfStopBandLabel")) self.formLayout_9.setWidget(0, QtGui.QFormLayout.LabelRole, self.iirendofHpfStopBandLabel) self.iirendofHpfStopBandEdit = QtGui.QLineEdit(self.iirhpfPage) self.iirendofHpfStopBandEdit.setObjectName(_fromUtf8("iirendofHpfStopBandEdit")) self.formLayout_9.setWidget(0, QtGui.QFormLayout.FieldRole, self.iirendofHpfStopBandEdit) self.iirstartofHpfPassBandLabel = QtGui.QLabel(self.iirhpfPage) self.iirstartofHpfPassBandLabel.setObjectName(_fromUtf8("iirstartofHpfPassBandLabel")) self.formLayout_9.setWidget(1, QtGui.QFormLayout.LabelRole, self.iirstartofHpfPassBandLabel) self.iirstartofHpfPassBandEdit = QtGui.QLineEdit(self.iirhpfPage) self.iirstartofHpfPassBandEdit.setObjectName(_fromUtf8("iirstartofHpfPassBandEdit")) self.formLayout_9.setWidget(1, QtGui.QFormLayout.FieldRole, self.iirstartofHpfPassBandEdit) self.iirHpfPassBandAttenLabel = QtGui.QLabel(self.iirhpfPage) self.iirHpfPassBandAttenLabel.setObjectName(_fromUtf8("iirHpfPassBandAttenLabel")) self.formLayout_9.setWidget(2, QtGui.QFormLayout.LabelRole, self.iirHpfPassBandAttenLabel) self.iirHpfPassBandAttenEdit = QtGui.QLineEdit(self.iirhpfPage) self.iirHpfPassBandAttenEdit.setObjectName(_fromUtf8("iirHpfPassBandAttenEdit")) self.formLayout_9.setWidget(2, QtGui.QFormLayout.FieldRole, self.iirHpfPassBandAttenEdit) self.iirHpfStopBandRippleLabel = QtGui.QLabel(self.iirhpfPage) self.iirHpfStopBandRippleLabel.setObjectName(_fromUtf8("iirHpfStopBandRippleLabel")) self.formLayout_9.setWidget(3, QtGui.QFormLayout.LabelRole, self.iirHpfStopBandRippleLabel) self.iirHpfStopBandRippleEdit = QtGui.QLineEdit(self.iirhpfPage) self.iirHpfStopBandRippleEdit.setObjectName(_fromUtf8("iirHpfStopBandRippleEdit")) self.formLayout_9.setWidget(3, QtGui.QFormLayout.FieldRole, self.iirHpfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirhpfPage) self.iirbpfPage = QtGui.QWidget() self.iirbpfPage.setObjectName(_fromUtf8("iirbpfPage")) self.formLayout_10 = QtGui.QFormLayout(self.iirbpfPage) self.formLayout_10.setObjectName(_fromUtf8("formLayout_10")) self.iirendofBpfStopBandLabel1 = QtGui.QLabel(self.iirbpfPage) self.iirendofBpfStopBandLabel1.setObjectName(_fromUtf8("iirendofBpfStopBandLabel1")) self.formLayout_10.setWidget(0, QtGui.QFormLayout.LabelRole, self.iirendofBpfStopBandLabel1) self.iirendofBpfStopBandEdit1 = QtGui.QLineEdit(self.iirbpfPage) self.iirendofBpfStopBandEdit1.setObjectName(_fromUtf8("iirendofBpfStopBandEdit1")) self.formLayout_10.setWidget(0, QtGui.QFormLayout.FieldRole, self.iirendofBpfStopBandEdit1) self.iirstartofBpfPassBandLabel = QtGui.QLabel(self.iirbpfPage) self.iirstartofBpfPassBandLabel.setObjectName(_fromUtf8("iirstartofBpfPassBandLabel")) self.formLayout_10.setWidget(1, QtGui.QFormLayout.LabelRole, self.iirstartofBpfPassBandLabel) self.iirstartofBpfPassBandEdit = QtGui.QLineEdit(self.iirbpfPage) self.iirstartofBpfPassBandEdit.setObjectName(_fromUtf8("iirstartofBpfPassBandEdit")) self.formLayout_10.setWidget(1, QtGui.QFormLayout.FieldRole, self.iirstartofBpfPassBandEdit) self.iirendofBpfPassBandLabel = QtGui.QLabel(self.iirbpfPage) self.iirendofBpfPassBandLabel.setObjectName(_fromUtf8("iirendofBpfPassBandLabel")) self.formLayout_10.setWidget(2, QtGui.QFormLayout.LabelRole, self.iirendofBpfPassBandLabel) self.iirendofBpfPassBandEdit = QtGui.QLineEdit(self.iirbpfPage) self.iirendofBpfPassBandEdit.setObjectName(_fromUtf8("iirendofBpfPassBandEdit")) self.formLayout_10.setWidget(2, QtGui.QFormLayout.FieldRole, self.iirendofBpfPassBandEdit) self.iirstartofBpfStopBandLabel2 = QtGui.QLabel(self.iirbpfPage) self.iirstartofBpfStopBandLabel2.setObjectName(_fromUtf8("iirstartofBpfStopBandLabel2")) self.formLayout_10.setWidget(3, QtGui.QFormLayout.LabelRole, self.iirstartofBpfStopBandLabel2) self.iirstartofBpfStopBandEdit2 = QtGui.QLineEdit(self.iirbpfPage) self.iirstartofBpfStopBandEdit2.setObjectName(_fromUtf8("iirstartofBpfStopBandEdit2")) self.formLayout_10.setWidget(3, QtGui.QFormLayout.FieldRole, self.iirstartofBpfStopBandEdit2) self.iirBpfPassBandAttenLabel = QtGui.QLabel(self.iirbpfPage) self.iirBpfPassBandAttenLabel.setObjectName(_fromUtf8("iirBpfPassBandAttenLabel")) self.formLayout_10.setWidget(4, QtGui.QFormLayout.LabelRole, self.iirBpfPassBandAttenLabel) self.iirBpfPassBandAttenEdit = QtGui.QLineEdit(self.iirbpfPage) self.iirBpfPassBandAttenEdit.setObjectName(_fromUtf8("iirBpfPassBandAttenEdit")) self.formLayout_10.setWidget(4, QtGui.QFormLayout.FieldRole, self.iirBpfPassBandAttenEdit) self.iirBpfStopBandRippleLabel = QtGui.QLabel(self.iirbpfPage) self.iirBpfStopBandRippleLabel.setObjectName(_fromUtf8("iirBpfStopBandRippleLabel")) self.formLayout_10.setWidget(5, QtGui.QFormLayout.LabelRole, self.iirBpfStopBandRippleLabel) self.iirBpfStopBandRippleEdit = QtGui.QLineEdit(self.iirbpfPage) self.iirBpfStopBandRippleEdit.setObjectName(_fromUtf8("iirBpfStopBandRippleEdit")) self.formLayout_10.setWidget(5, QtGui.QFormLayout.FieldRole, self.iirBpfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirbpfPage) self.iirbsfPage = QtGui.QWidget() self.iirbsfPage.setObjectName(_fromUtf8("iirbsfPage")) self.formLayout_11 = QtGui.QFormLayout(self.iirbsfPage) self.formLayout_11.setObjectName(_fromUtf8("formLayout_11")) self.iirendofBsfPassBandLabel1 = QtGui.QLabel(self.iirbsfPage) self.iirendofBsfPassBandLabel1.setObjectName(_fromUtf8("iirendofBsfPassBandLabel1")) self.formLayout_11.setWidget(0, QtGui.QFormLayout.LabelRole, self.iirendofBsfPassBandLabel1) self.iirendofBsfPassBandEdit1 = QtGui.QLineEdit(self.iirbsfPage) self.iirendofBsfPassBandEdit1.setObjectName(_fromUtf8("iirendofBsfPassBandEdit1")) self.formLayout_11.setWidget(0, QtGui.QFormLayout.FieldRole, self.iirendofBsfPassBandEdit1) self.iirstartofBsfStopBandLabel = QtGui.QLabel(self.iirbsfPage) self.iirstartofBsfStopBandLabel.setObjectName(_fromUtf8("iirstartofBsfStopBandLabel")) self.formLayout_11.setWidget(1, QtGui.QFormLayout.LabelRole, self.iirstartofBsfStopBandLabel) self.iirstartofBsfStopBandEdit = QtGui.QLineEdit(self.iirbsfPage) self.iirstartofBsfStopBandEdit.setObjectName(_fromUtf8("iirstartofBsfStopBandEdit")) self.formLayout_11.setWidget(1, QtGui.QFormLayout.FieldRole, self.iirstartofBsfStopBandEdit) self.iirendofBsfStopBandLabel = QtGui.QLabel(self.iirbsfPage) self.iirendofBsfStopBandLabel.setObjectName(_fromUtf8("iirendofBsfStopBandLabel")) self.formLayout_11.setWidget(2, QtGui.QFormLayout.LabelRole, self.iirendofBsfStopBandLabel) self.iirendofBsfStopBandEdit = QtGui.QLineEdit(self.iirbsfPage) self.iirendofBsfStopBandEdit.setObjectName(_fromUtf8("iirendofBsfStopBandEdit")) self.formLayout_11.setWidget(2, QtGui.QFormLayout.FieldRole, self.iirendofBsfStopBandEdit) self.iirstartofBsfPassBandLabel2 = QtGui.QLabel(self.iirbsfPage) self.iirstartofBsfPassBandLabel2.setObjectName(_fromUtf8("iirstartofBsfPassBandLabel2")) self.formLayout_11.setWidget(3, QtGui.QFormLayout.LabelRole, self.iirstartofBsfPassBandLabel2) self.iirstartofBsfPassBandEdit2 = QtGui.QLineEdit(self.iirbsfPage) self.iirstartofBsfPassBandEdit2.setObjectName(_fromUtf8("iirstartofBsfPassBandEdit2")) self.formLayout_11.setWidget(3, QtGui.QFormLayout.FieldRole, self.iirstartofBsfPassBandEdit2) self.iirBsfPassBandAttenLabel = QtGui.QLabel(self.iirbsfPage) self.iirBsfPassBandAttenLabel.setObjectName(_fromUtf8("iirBsfPassBandAttenLabel")) self.formLayout_11.setWidget(4, QtGui.QFormLayout.LabelRole, self.iirBsfPassBandAttenLabel) self.iirBsfPassBandAttenEdit = QtGui.QLineEdit(self.iirbsfPage) self.iirBsfPassBandAttenEdit.setObjectName(_fromUtf8("iirBsfPassBandAttenEdit")) self.formLayout_11.setWidget(4, QtGui.QFormLayout.FieldRole, self.iirBsfPassBandAttenEdit) self.iirBsfStopBandRippleLabel = QtGui.QLabel(self.iirbsfPage) self.iirBsfStopBandRippleLabel.setObjectName(_fromUtf8("iirBsfStopBandRippleLabel")) self.formLayout_11.setWidget(5, QtGui.QFormLayout.LabelRole, self.iirBsfStopBandRippleLabel) self.iirBsfStopBandRippleEdit = QtGui.QLineEdit(self.iirbsfPage) self.iirBsfStopBandRippleEdit.setObjectName(_fromUtf8("iirBsfStopBandRippleEdit")) self.formLayout_11.setWidget(5, QtGui.QFormLayout.FieldRole, self.iirBsfStopBandRippleEdit) self.filterTypeWidget.addWidget(self.iirbsfPage) self.iirbesselPage = QtGui.QWidget() self.iirbesselPage.setObjectName(_fromUtf8("iirbesselPage")) self.formLayout_13 = QtGui.QFormLayout(self.iirbesselPage) self.formLayout_13.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_13.setObjectName(_fromUtf8("formLayout_13")) self.besselordLabel = QtGui.QLabel(self.iirbesselPage) self.besselordLabel.setObjectName(_fromUtf8("besselordLabel")) self.formLayout_13.setWidget(0, QtGui.QFormLayout.LabelRole, self.besselordLabel) self.besselordEdit = QtGui.QLineEdit(self.iirbesselPage) self.besselordEdit.setObjectName(_fromUtf8("besselordEdit")) self.formLayout_13.setWidget(0, QtGui.QFormLayout.FieldRole, self.besselordEdit) self.iirbesselcritLabel1 = QtGui.QLabel(self.iirbesselPage) self.iirbesselcritLabel1.setObjectName(_fromUtf8("iirbesselcritLabel1")) self.formLayout_13.setWidget(1, QtGui.QFormLayout.LabelRole, self.iirbesselcritLabel1) self.iirbesselcritEdit1 = QtGui.QLineEdit(self.iirbesselPage) self.iirbesselcritEdit1.setObjectName(_fromUtf8("iirbesselcritEdit1")) self.formLayout_13.setWidget(1, QtGui.QFormLayout.FieldRole, self.iirbesselcritEdit1) self.iirbesselcritEdit2 = QtGui.QLineEdit(self.iirbesselPage) self.iirbesselcritEdit2.setObjectName(_fromUtf8("iirbesselcritEdit2")) self.formLayout_13.setWidget(2, QtGui.QFormLayout.FieldRole, self.iirbesselcritEdit2) self.iirbesselcritLabel2 = QtGui.QLabel(self.iirbesselPage) self.iirbesselcritLabel2.setObjectName(_fromUtf8("iirbesselcritLabel2")) self.formLayout_13.setWidget(2, QtGui.QFormLayout.LabelRole, self.iirbesselcritLabel2) self.filterTypeWidget.addWidget(self.iirbesselPage) self.firhbPage = QtGui.QWidget() self.firhbPage.setObjectName(_fromUtf8("firhbPage")) self.formLayout_14 = QtGui.QFormLayout(self.firhbPage) self.formLayout_14.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_14.setObjectName(_fromUtf8("formLayout_14")) self.firhbordLabel = QtGui.QLabel(self.firhbPage) self.firhbordLabel.setObjectName(_fromUtf8("firhbordLabel")) self.formLayout_14.setWidget(0, QtGui.QFormLayout.LabelRole, self.firhbordLabel) self.firhbordEdit = QtGui.QLineEdit(self.firhbPage) self.firhbordEdit.setObjectName(_fromUtf8("firhbordEdit")) self.formLayout_14.setWidget(0, QtGui.QFormLayout.FieldRole, self.firhbordEdit) self.firhbtrEditLabel2 = QtGui.QLabel(self.firhbPage) self.firhbtrEditLabel2.setObjectName(_fromUtf8("firhbtrEditLabel2")) self.formLayout_14.setWidget(2, QtGui.QFormLayout.LabelRole, self.firhbtrEditLabel2) self.firhbtrEdit = QtGui.QLineEdit(self.firhbPage) self.firhbtrEdit.setObjectName(_fromUtf8("firhbtrEdit")) self.formLayout_14.setWidget(2, QtGui.QFormLayout.FieldRole, self.firhbtrEdit) self.filterTypeWidget.addWidget(self.firhbPage) self.verticalLayout.addWidget(self.filterTypeWidget) self.filterPropsBox = QtGui.QGroupBox(self.filterFrame) self.filterPropsBox.setObjectName(_fromUtf8("filterPropsBox")) self.formLayout_8 = QtGui.QFormLayout(self.filterPropsBox) self.formLayout_8.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow) self.formLayout_8.setObjectName(_fromUtf8("formLayout_8")) self.nTapsLabel = QtGui.QLabel(self.filterPropsBox) self.nTapsLabel.setMinimumSize(QtCore.QSize(150, 0)) self.nTapsLabel.setObjectName(_fromUtf8("nTapsLabel")) self.formLayout_8.setWidget(1, QtGui.QFormLayout.LabelRole, self.nTapsLabel) self.nTapsEdit = QtGui.QLabel(self.filterPropsBox) self.nTapsEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.nTapsEdit.setFrameShape(QtGui.QFrame.Box) self.nTapsEdit.setFrameShadow(QtGui.QFrame.Raised) self.nTapsEdit.setText(_fromUtf8("")) self.nTapsEdit.setObjectName(_fromUtf8("nTapsEdit")) self.formLayout_8.setWidget(1, QtGui.QFormLayout.FieldRole, self.nTapsEdit) self.verticalLayout.addWidget(self.filterPropsBox) self.designButton = QtGui.QPushButton(self.filterFrame) self.designButton.setMinimumSize(QtCore.QSize(0, 0)) self.designButton.setMaximumSize(QtCore.QSize(200, 16777215)) self.designButton.setAutoDefault(True) self.designButton.setDefault(True) self.designButton.setObjectName(_fromUtf8("designButton")) self.verticalLayout.addWidget(self.designButton) self.gridLayout.addWidget(self.filterFrame, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1128, 19)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menu_File = QtGui.QMenu(self.menubar) self.menu_File.setObjectName(_fromUtf8("menu_File")) self.menu_Analysis = QtGui.QMenu(self.menubar) self.menu_Analysis.setObjectName(_fromUtf8("menu_Analysis")) self.menuWidgets = QtGui.QMenu(self.menubar) self.menuWidgets.setGeometry(QtCore.QRect(408, 108, 129, 86)) self.menuWidgets.setObjectName(_fromUtf8("menuWidgets")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.action_exit = QtGui.QAction(MainWindow) self.action_exit.setObjectName(_fromUtf8("action_exit")) self.action_save = QtGui.QAction(MainWindow) self.action_save.setObjectName(_fromUtf8("action_save")) self.action_open = QtGui.QAction(MainWindow) self.action_open.setObjectName(_fromUtf8("action_open")) self.actionMagnitude_Response = QtGui.QAction(MainWindow) self.actionMagnitude_Response.setCheckable(True) self.actionMagnitude_Response.setChecked(True) self.actionMagnitude_Response.setObjectName(_fromUtf8("actionMagnitude_Response")) self.actionPhase_Respone = QtGui.QAction(MainWindow) self.actionPhase_Respone.setCheckable(True) self.actionPhase_Respone.setChecked(True) self.actionPhase_Respone.setObjectName(_fromUtf8("actionPhase_Respone")) self.actionGroup_Delay = QtGui.QAction(MainWindow) self.actionGroup_Delay.setCheckable(True) self.actionGroup_Delay.setChecked(True) self.actionGroup_Delay.setObjectName(_fromUtf8("actionGroup_Delay")) self.actionPhase_Delay = QtGui.QAction(MainWindow) self.actionPhase_Delay.setCheckable(True) self.actionPhase_Delay.setChecked(True) self.actionPhase_Delay.setObjectName(_fromUtf8("actionPhase_Delay")) self.actionImpulse_Response = QtGui.QAction(MainWindow) self.actionImpulse_Response.setCheckable(True) self.actionImpulse_Response.setChecked(True) self.actionImpulse_Response.setObjectName(_fromUtf8("actionImpulse_Response")) self.actionStep_Response = QtGui.QAction(MainWindow) self.actionStep_Response.setCheckable(True) self.actionStep_Response.setChecked(True) self.actionStep_Response.setObjectName(_fromUtf8("actionStep_Response")) self.actionPole_Zero_Plot = QtGui.QAction(MainWindow) self.actionPole_Zero_Plot.setObjectName(_fromUtf8("actionPole_Zero_Plot")) self.actionGrid = QtGui.QAction(MainWindow) self.actionGrid.setObjectName(_fromUtf8("actionGrid")) self.actionPole_Zero_Plot_2 = QtGui.QAction(MainWindow) self.actionPole_Zero_Plot_2.setCheckable(True) self.actionPole_Zero_Plot_2.setChecked(True) self.actionPole_Zero_Plot_2.setObjectName(_fromUtf8("actionPole_Zero_Plot_2")) self.actionIdeal_Band = QtGui.QAction(MainWindow) self.actionIdeal_Band.setCheckable(True) self.actionIdeal_Band.setChecked(False) self.actionIdeal_Band.setObjectName(_fromUtf8("actionIdeal_Band")) self.actionGrid_2 = QtGui.QAction(MainWindow) self.actionGrid_2.setCheckable(True) self.actionGrid_2.setChecked(False) self.actionGrid_2.setObjectName(_fromUtf8("actionGrid_2")) self.actionGrid_3 = QtGui.QAction(MainWindow) self.actionGrid_3.setObjectName(_fromUtf8("actionGrid_3")) self.actionTabbed = QtGui.QAction(MainWindow) self.actionTabbed.setCheckable(True) self.actionTabbed.setObjectName(_fromUtf8("actionTabbed")) self.actionOverlay = QtGui.QAction(MainWindow) self.actionOverlay.setCheckable(True) self.actionOverlay.setObjectName(_fromUtf8("actionOverlay")) self.actionResponse_widget = QtGui.QAction(MainWindow) self.actionResponse_widget.setCheckable(True) self.actionResponse_widget.setChecked(True) self.actionResponse_widget.setObjectName(_fromUtf8("actionResponse_widget")) self.actionSpec_widget = QtGui.QAction(MainWindow) self.actionSpec_widget.setCheckable(True) self.actionSpec_widget.setChecked(True) self.actionSpec_widget.setObjectName(_fromUtf8("actionSpec_widget")) self.actionQuick_access = QtGui.QAction(MainWindow) self.actionQuick_access.setCheckable(True) self.actionQuick_access.setChecked(True) self.actionQuick_access.setObjectName(_fromUtf8("actionQuick_access")) self.actionFilter_Coefficients = QtGui.QAction(MainWindow) self.actionFilter_Coefficients.setCheckable(True) self.actionFilter_Coefficients.setChecked(True) self.actionFilter_Coefficients.setObjectName(_fromUtf8("actionFilter_Coefficients")) self.actionDesign_widget = QtGui.QAction(MainWindow) self.actionDesign_widget.setCheckable(True) self.actionDesign_widget.setChecked(True) self.actionDesign_widget.setObjectName(_fromUtf8("actionDesign_widget")) self.actionOverlay_2 = QtGui.QAction(MainWindow) self.actionOverlay_2.setObjectName(_fromUtf8("actionOverlay_2")) self.actionGridview = QtGui.QAction(MainWindow) self.actionGridview.setCheckable(True) self.actionGridview.setObjectName(_fromUtf8("actionGridview")) self.actionDesign_widget_2 = QtGui.QAction(MainWindow) self.actionDesign_widget_2.setCheckable(True) self.actionDesign_widget_2.setObjectName(_fromUtf8("actionDesign_widget_2")) self.actionQuick_access_2 = QtGui.QAction(MainWindow) self.actionQuick_access_2.setObjectName(_fromUtf8("actionQuick_access_2")) self.actionSpec_widget_2 = QtGui.QAction(MainWindow) self.actionSpec_widget_2.setObjectName(_fromUtf8("actionSpec_widget_2")) self.actionResponse_widget_2 = QtGui.QAction(MainWindow) self.actionResponse_widget_2.setObjectName(_fromUtf8("actionResponse_widget_2")) self.actionDesign_Widget = QtGui.QAction(MainWindow) self.actionDesign_Widget.setCheckable(True) self.actionDesign_Widget.setChecked(True) self.actionDesign_Widget.setObjectName(_fromUtf8("actionDesign_Widget")) self.actionQuick_Access = QtGui.QAction(MainWindow) self.actionQuick_Access.setCheckable(True) self.actionQuick_Access.setChecked(True) self.actionQuick_Access.setObjectName(_fromUtf8("actionQuick_Access")) self.actionSpec_Widget = QtGui.QAction(MainWindow) self.actionSpec_Widget.setCheckable(True) self.actionSpec_Widget.setChecked(True) self.actionSpec_Widget.setObjectName(_fromUtf8("actionSpec_Widget")) self.actionResponse_Widget = QtGui.QAction(MainWindow) self.actionResponse_Widget.setCheckable(True) self.actionResponse_Widget.setChecked(True) self.actionResponse_Widget.setObjectName(_fromUtf8("actionResponse_Widget")) self.actionTabview_2 = QtGui.QAction(MainWindow) self.actionTabview_2.setCheckable(True) self.actionTabview_2.setChecked(True) self.actionTabview_2.setObjectName(_fromUtf8("actionTabview_2")) self.actionPlot_select = QtGui.QAction(MainWindow) self.actionPlot_select.setCheckable(True) self.actionPlot_select.setChecked(True) self.actionPlot_select.setObjectName(_fromUtf8("actionPlot_select")) self.actionBand_Diagram = QtGui.QAction(MainWindow) self.actionBand_Diagram.setCheckable(True) self.actionBand_Diagram.setChecked(True) self.actionBand_Diagram.setObjectName(_fromUtf8("actionBand_Diagram")) self.actionCheck = QtGui.QAction(MainWindow) self.actionCheck.setObjectName(_fromUtf8("actionCheck")) self.actionPlot_FFT_points = QtGui.QAction(MainWindow) self.actionPlot_FFT_points.setObjectName(_fromUtf8("actionPlot_FFT_points")) self.menu_File.addAction(self.action_open) self.menu_File.addAction(self.action_save) self.menu_File.addAction(self.action_exit) self.menu_Analysis.addSeparator() self.menu_Analysis.addAction(self.actionMagnitude_Response) self.menu_Analysis.addAction(self.actionPhase_Respone) self.menu_Analysis.addAction(self.actionGroup_Delay) self.menu_Analysis.addAction(self.actionPhase_Delay) self.menu_Analysis.addAction(self.actionImpulse_Response) self.menu_Analysis.addAction(self.actionStep_Response) self.menu_Analysis.addAction(self.actionGrid_2) self.menu_Analysis.addAction(self.actionFilter_Coefficients) self.menu_Analysis.addAction(self.actionIdeal_Band) self.menu_Analysis.addSeparator() self.menu_Analysis.addAction(self.actionPole_Zero_Plot_2) self.menu_Analysis.addAction(self.actionBand_Diagram) self.menu_Analysis.addSeparator() self.menu_Analysis.addAction(self.actionDesign_Widget) self.menu_Analysis.addAction(self.actionQuick_Access) self.menu_Analysis.addAction(self.actionSpec_Widget) self.menu_Analysis.addAction(self.actionResponse_Widget) self.menuWidgets.addAction(self.actionGridview) self.menuWidgets.addAction(self.actionPlot_select) self.menubar.addAction(self.menu_File.menuAction()) self.menubar.addAction(self.menu_Analysis.menuAction()) self.menubar.addAction(self.menuWidgets.menuAction()) self.retranslateUi(MainWindow) self.stackedWindows.setCurrentIndex(0) self.tabGroup.setCurrentIndex(0) self.filterspecView.setCurrentIndex(1) self.mfreqTabgroup.setCurrentIndex(0) self.mfilterspecView.setCurrentIndex(1) self.filterTypeWidget.setCurrentIndex(11) QtCore.QObject.connect(self.action_exit, QtCore.SIGNAL(_fromUtf8("activated()")), MainWindow.close) QtCore.QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.filterTypeComboBox, self.filterDesignTypeComboBox) MainWindow.setTabOrder(self.filterDesignTypeComboBox, self.endofLpfPassBandEdit) MainWindow.setTabOrder(self.endofLpfPassBandEdit, self.startofLpfStopBandEdit) MainWindow.setTabOrder(self.startofLpfStopBandEdit, self.lpfStopBandAttenEdit) MainWindow.setTabOrder(self.lpfStopBandAttenEdit, self.lpfPassBandRippleEdit) MainWindow.setTabOrder(self.lpfPassBandRippleEdit, self.startofBpfPassBandEdit) MainWindow.setTabOrder(self.startofBpfPassBandEdit, self.endofBpfPassBandEdit) MainWindow.setTabOrder(self.endofBpfPassBandEdit, self.bpfTransitionEdit) MainWindow.setTabOrder(self.bpfTransitionEdit, self.bpfStopBandAttenEdit) MainWindow.setTabOrder(self.bpfStopBandAttenEdit, self.bpfPassBandRippleEdit) MainWindow.setTabOrder(self.bpfPassBandRippleEdit, self.startofBnfStopBandEdit) MainWindow.setTabOrder(self.startofBnfStopBandEdit, self.endofBnfStopBandEdit) MainWindow.setTabOrder(self.endofBnfStopBandEdit, self.bnfTransitionEdit) MainWindow.setTabOrder(self.bnfTransitionEdit, self.bnfStopBandAttenEdit) MainWindow.setTabOrder(self.bnfStopBandAttenEdit, self.bnfPassBandRippleEdit) MainWindow.setTabOrder(self.bnfPassBandRippleEdit, self.endofHpfStopBandEdit) MainWindow.setTabOrder(self.endofHpfStopBandEdit, self.startofHpfPassBandEdit) MainWindow.setTabOrder(self.startofHpfPassBandEdit, self.hpfStopBandAttenEdit) MainWindow.setTabOrder(self.hpfStopBandAttenEdit, self.hpfPassBandRippleEdit) MainWindow.setTabOrder(self.hpfPassBandRippleEdit, self.rrcSymbolRateEdit) MainWindow.setTabOrder(self.rrcSymbolRateEdit, self.rrcAlphaEdit) MainWindow.setTabOrder(self.rrcAlphaEdit, self.rrcNumTapsEdit) MainWindow.setTabOrder(self.rrcNumTapsEdit, self.gausSymbolRateEdit) MainWindow.setTabOrder(self.gausSymbolRateEdit, self.gausBTEdit) MainWindow.setTabOrder(self.gausBTEdit, self.gausNumTapsEdit) MainWindow.setTabOrder(self.gausNumTapsEdit, self.designButton) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "GNU Radio Filter Design Tool", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.freqTab), QtGui.QApplication.translate("MainWindow", "Magnitude Response", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.timeTab), QtGui.QApplication.translate("MainWindow", "Filter Taps", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.phaseTab), QtGui.QApplication.translate("MainWindow", "Phase Response", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.groupTab), QtGui.QApplication.translate("MainWindow", "Group Delay", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.fcTab), QtGui.QApplication.translate("MainWindow", "Filter Coefficients", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.impresTab), QtGui.QApplication.translate("MainWindow", "Impulse Response", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.stepresTab), QtGui.QApplication.translate("MainWindow", "Step Response", None, QtGui.QApplication.UnicodeUTF8)) self.tabGroup.setTabText(self.tabGroup.indexOf(self.pdelayTab), QtGui.QApplication.translate("MainWindow", "Phase Delay", None, QtGui.QApplication.UnicodeUTF8)) self.filterspecView.setTabText(self.filterspecView.indexOf(self.bandDiagram), QtGui.QApplication.translate("MainWindow", "Band Diagram", None, QtGui.QApplication.UnicodeUTF8)) self.addzeroPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Add zero", None, QtGui.QApplication.UnicodeUTF8)) self.addzeroPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.addpolePush.setToolTip(QtGui.QApplication.translate("MainWindow", "Add pole", None, QtGui.QApplication.UnicodeUTF8)) self.addpolePush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.delPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Delete pole/zero", None, QtGui.QApplication.UnicodeUTF8)) self.delPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.conjPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Conjugate", None, QtGui.QApplication.UnicodeUTF8)) self.conjPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.filterspecView.setTabText(self.filterspecView.indexOf(self.poleZero), QtGui.QApplication.translate("MainWindow", "Pole-Zero Plot", None, QtGui.QApplication.UnicodeUTF8)) self.responseBox.setTitle(QtGui.QApplication.translate("MainWindow", "Filter Responses", None, QtGui.QApplication.UnicodeUTF8)) self.checkMagres.setText(QtGui.QApplication.translate("MainWindow", "Magnitude Response", None, QtGui.QApplication.UnicodeUTF8)) self.checkPhase.setText(QtGui.QApplication.translate("MainWindow", "Phase Response", None, QtGui.QApplication.UnicodeUTF8)) self.checkGdelay.setText(QtGui.QApplication.translate("MainWindow", "Group Delay", None, QtGui.QApplication.UnicodeUTF8)) self.checkPdelay.setText(QtGui.QApplication.translate("MainWindow", "Phase Delay", None, QtGui.QApplication.UnicodeUTF8)) self.checkImpulse.setText(QtGui.QApplication.translate("MainWindow", "Impulse Response", None, QtGui.QApplication.UnicodeUTF8)) self.checkStep.setText(QtGui.QApplication.translate("MainWindow", "Step Response", None, QtGui.QApplication.UnicodeUTF8)) self.checkGrid.setText(QtGui.QApplication.translate("MainWindow", "Grid", None, QtGui.QApplication.UnicodeUTF8)) self.checkFcoeff.setText(QtGui.QApplication.translate("MainWindow", "Filter Coefficients", None, QtGui.QApplication.UnicodeUTF8)) self.checkKeepcur.setText(QtGui.QApplication.translate("MainWindow", "Buffer current plots", None, QtGui.QApplication.UnicodeUTF8)) self.groupSpecs.setTitle(QtGui.QApplication.translate("MainWindow", "Filter Specs", None, QtGui.QApplication.UnicodeUTF8)) self.checkBand.setText(QtGui.QApplication.translate("MainWindow", "Band Diagram", None, QtGui.QApplication.UnicodeUTF8)) self.checkPzplot.setText(QtGui.QApplication.translate("MainWindow", "Pole-Zero Plot", None, QtGui.QApplication.UnicodeUTF8)) self.sysParamsBox.setTitle(QtGui.QApplication.translate("MainWindow", "Plot Parameter", None, QtGui.QApplication.UnicodeUTF8)) self.nfftLabel.setText(QtGui.QApplication.translate("MainWindow", "Num FFT points", None, QtGui.QApplication.UnicodeUTF8)) self.mfmagPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Magnitude Response", None, QtGui.QApplication.UnicodeUTF8)) self.mfmagPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mfphasePush.setToolTip(QtGui.QApplication.translate("MainWindow", "Phase Response", None, QtGui.QApplication.UnicodeUTF8)) self.mfphasePush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mfgpdlyPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Group Delay", None, QtGui.QApplication.UnicodeUTF8)) self.mfgpdlyPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mfphdlyPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Phase Delay", None, QtGui.QApplication.UnicodeUTF8)) self.mfphdlyPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mfoverlayPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Overlay", None, QtGui.QApplication.UnicodeUTF8)) self.mfoverlayPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mfreqTabgroup.setTabText(self.mfreqTabgroup.indexOf(self.mfreqTab), QtGui.QApplication.translate("MainWindow", "Frequency Response", None, QtGui.QApplication.UnicodeUTF8)) self.mttapsPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Filter Taps", None, QtGui.QApplication.UnicodeUTF8)) self.mttapsPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mtstepPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Step Response", None, QtGui.QApplication.UnicodeUTF8)) self.mtstepPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mtimpPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Impulse Response", None, QtGui.QApplication.UnicodeUTF8)) self.mtimpPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mtimeTabgroup.setTabText(self.mtimeTabgroup.indexOf(self.mtimeTab), QtGui.QApplication.translate("MainWindow", "Time responses", None, QtGui.QApplication.UnicodeUTF8)) self.mfilterspecView.setTabText(self.mfilterspecView.indexOf(self.mbandDiagram), QtGui.QApplication.translate("MainWindow", "Ideal Band", None, QtGui.QApplication.UnicodeUTF8)) self.maddzeroPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Add zero", None, QtGui.QApplication.UnicodeUTF8)) self.maddzeroPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.maddpolePush.setToolTip(QtGui.QApplication.translate("MainWindow", "Add pole", None, QtGui.QApplication.UnicodeUTF8)) self.maddpolePush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mdelPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Delete pole/zero", None, QtGui.QApplication.UnicodeUTF8)) self.mdelPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mconjPush.setToolTip(QtGui.QApplication.translate("MainWindow", "Conjugate", None, QtGui.QApplication.UnicodeUTF8)) self.mconjPush.setText(QtGui.QApplication.translate("MainWindow", "...", None, QtGui.QApplication.UnicodeUTF8)) self.mfilterspecView.setTabText(self.mfilterspecView.indexOf(self.mpoleZero), QtGui.QApplication.translate("MainWindow", "Pole-Zero Plot", None, QtGui.QApplication.UnicodeUTF8)) self.mfilterspecView.setTabText(self.mfilterspecView.indexOf(self.mfcTab), QtGui.QApplication.translate("MainWindow", "Filter Coefficients", None, QtGui.QApplication.UnicodeUTF8)) self.fselectComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "FIR", None, QtGui.QApplication.UnicodeUTF8)) self.fselectComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "IIR(scipy)", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Low Pass", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "High Pass", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Band Pass", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(3, QtGui.QApplication.translate("MainWindow", "Complex Band Pass", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(4, QtGui.QApplication.translate("MainWindow", "Band Notch", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(5, QtGui.QApplication.translate("MainWindow", "Root Raised Cosine", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(6, QtGui.QApplication.translate("MainWindow", "Gaussian", None, QtGui.QApplication.UnicodeUTF8)) self.filterTypeComboBox.setItemText(7, QtGui.QApplication.translate("MainWindow", "Half Band", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterBandComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Low Pass", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterBandComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Band Pass", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterBandComboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Band Stop", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterBandComboBox.setItemText(3, QtGui.QApplication.translate("MainWindow", "High Pass", None, QtGui.QApplication.UnicodeUTF8)) self.adComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Digital (normalized 0-1)", None, QtGui.QApplication.UnicodeUTF8)) self.adComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Analog (rad/second)", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Hamming Window", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Hann Window", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Blackman Window", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(3, QtGui.QApplication.translate("MainWindow", "Rectangular Window", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(4, QtGui.QApplication.translate("MainWindow", "Kaiser Window", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(5, QtGui.QApplication.translate("MainWindow", "Blackman-harris Window", None, QtGui.QApplication.UnicodeUTF8)) self.filterDesignTypeComboBox.setItemText(6, QtGui.QApplication.translate("MainWindow", "Equiripple", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterTypeComboBox.setItemText(0, QtGui.QApplication.translate("MainWindow", "Elliptic", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterTypeComboBox.setItemText(1, QtGui.QApplication.translate("MainWindow", "Butterworth", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterTypeComboBox.setItemText(2, QtGui.QApplication.translate("MainWindow", "Chebyshev-1", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterTypeComboBox.setItemText(3, QtGui.QApplication.translate("MainWindow", "Chebyshev-2", None, QtGui.QApplication.UnicodeUTF8)) self.iirfilterTypeComboBox.setItemText(4, QtGui.QApplication.translate("MainWindow", "Bessel", None, QtGui.QApplication.UnicodeUTF8)) self.sampleRateLabel.setText(QtGui.QApplication.translate("MainWindow", "Sample Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) self.sampleRateEdit.setText(QtGui.QApplication.translate("MainWindow", "320000", None, QtGui.QApplication.UnicodeUTF8)) self.filterGainLabel.setText(QtGui.QApplication.translate("MainWindow", "Filter Gain", None, QtGui.QApplication.UnicodeUTF8)) self.filterGainEdit.setText(QtGui.QApplication.translate("MainWindow", "2", None, QtGui.QApplication.UnicodeUTF8)) self.endofLpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.endofLpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "50000", None, QtGui.QApplication.UnicodeUTF8)) self.startofLpfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.startofLpfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "60000", None, QtGui.QApplication.UnicodeUTF8)) self.lpfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.lpfStopBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "40", None, QtGui.QApplication.UnicodeUTF8)) self.lpfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.lpfPassBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.startofBpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.startofBpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "50000", None, QtGui.QApplication.UnicodeUTF8)) self.endofBpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.endofBpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "80000", None, QtGui.QApplication.UnicodeUTF8)) self.bpfStopBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "40", None, QtGui.QApplication.UnicodeUTF8)) self.bpfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.bpfTransitionLabel.setText(QtGui.QApplication.translate("MainWindow", "Transition Width (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.bpfTransitionEdit.setText(QtGui.QApplication.translate("MainWindow", "10000", None, QtGui.QApplication.UnicodeUTF8)) self.bpfPassBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.bpfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.startofBnfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.startofBnfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "50000", None, QtGui.QApplication.UnicodeUTF8)) self.endofBnfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.endofBnfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "80000", None, QtGui.QApplication.UnicodeUTF8)) self.bnfTransitionLabel.setText(QtGui.QApplication.translate("MainWindow", "Transition Width (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.bnfTransitionEdit.setText(QtGui.QApplication.translate("MainWindow", "10000", None, QtGui.QApplication.UnicodeUTF8)) self.bnfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.bnfStopBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "48", None, QtGui.QApplication.UnicodeUTF8)) self.bnfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.bnfPassBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.endofHpfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.endofHpfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "50000", None, QtGui.QApplication.UnicodeUTF8)) self.startofHpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.startofHpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "55000", None, QtGui.QApplication.UnicodeUTF8)) self.hpfStopBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Stop Band Attenuation (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.hpfStopBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "48", None, QtGui.QApplication.UnicodeUTF8)) self.hpfPassBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Pass Band Ripple (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.hpfPassBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.rrcSymbolRateLabel.setText(QtGui.QApplication.translate("MainWindow", "Symbol Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) self.rrcAlphaLabel.setText(QtGui.QApplication.translate("MainWindow", "Roll-off Factor", None, QtGui.QApplication.UnicodeUTF8)) self.rrcNumTapsLabel.setText(QtGui.QApplication.translate("MainWindow", "Number of Taps", None, QtGui.QApplication.UnicodeUTF8)) self.rrcSymbolRateEdit.setText(QtGui.QApplication.translate("MainWindow", "3200", None, QtGui.QApplication.UnicodeUTF8)) self.rrcAlphaEdit.setText(QtGui.QApplication.translate("MainWindow", "15", None, QtGui.QApplication.UnicodeUTF8)) self.rrcNumTapsEdit.setText(QtGui.QApplication.translate("MainWindow", "50", None, QtGui.QApplication.UnicodeUTF8)) self.gausSymbolRateLabel.setText(QtGui.QApplication.translate("MainWindow", "Symbol Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) self.gausSymbolRateEdit.setText(QtGui.QApplication.translate("MainWindow", "5000", None, QtGui.QApplication.UnicodeUTF8)) self.gausBTLabel.setText(QtGui.QApplication.translate("MainWindow", "Roll-off Factor", None, QtGui.QApplication.UnicodeUTF8)) self.gausBTEdit.setText(QtGui.QApplication.translate("MainWindow", "0.5", None, QtGui.QApplication.UnicodeUTF8)) self.gausNumTapsLabel.setText(QtGui.QApplication.translate("MainWindow", "Number of Taps", None, QtGui.QApplication.UnicodeUTF8)) self.gausNumTapsEdit.setText(QtGui.QApplication.translate("MainWindow", "30", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofLpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofLpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.3", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofLpfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band ", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofLpfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.5", None, QtGui.QApplication.UnicodeUTF8)) self.iirLpfPassBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Max loss in Pass Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirLpfPassBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.iirLpfStopBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Min atten in Stop Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirLpfStopBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "60", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofHpfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofHpfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.3", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofHpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band ", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofHpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.5", None, QtGui.QApplication.UnicodeUTF8)) self.iirHpfPassBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Max loss in Pass Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirHpfPassBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.iirHpfStopBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Min atten in Stop Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirHpfStopBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "60", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBpfStopBandLabel1.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band-1", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBpfStopBandEdit1.setText(QtGui.QApplication.translate("MainWindow", "0.2", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band ", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.3", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBpfPassBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band ", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBpfPassBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.5", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBpfStopBandLabel2.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band-2", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBpfStopBandEdit2.setText(QtGui.QApplication.translate("MainWindow", "0.6", None, QtGui.QApplication.UnicodeUTF8)) self.iirBpfPassBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Max loss in Pass Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirBpfPassBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.iirBpfStopBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Min atten in Stop Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirBpfStopBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "60", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBsfPassBandLabel1.setText(QtGui.QApplication.translate("MainWindow", "End of Pass Band-1", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBsfPassBandEdit1.setText(QtGui.QApplication.translate("MainWindow", "0.2", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBsfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "Start of Stop Band ", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBsfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.3", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBsfStopBandLabel.setText(QtGui.QApplication.translate("MainWindow", "End of Stop Band ", None, QtGui.QApplication.UnicodeUTF8)) self.iirendofBsfStopBandEdit.setText(QtGui.QApplication.translate("MainWindow", "0.6", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBsfPassBandLabel2.setText(QtGui.QApplication.translate("MainWindow", "Start of Pass Band-2", None, QtGui.QApplication.UnicodeUTF8)) self.iirstartofBsfPassBandEdit2.setText(QtGui.QApplication.translate("MainWindow", "0.7", None, QtGui.QApplication.UnicodeUTF8)) self.iirBsfPassBandAttenLabel.setText(QtGui.QApplication.translate("MainWindow", "Max loss in Pass Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirBsfPassBandAttenEdit.setText(QtGui.QApplication.translate("MainWindow", "1", None, QtGui.QApplication.UnicodeUTF8)) self.iirBsfStopBandRippleLabel.setText(QtGui.QApplication.translate("MainWindow", "Min atten in Stop Band (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.iirBsfStopBandRippleEdit.setText(QtGui.QApplication.translate("MainWindow", "60", None, QtGui.QApplication.UnicodeUTF8)) self.besselordLabel.setText(QtGui.QApplication.translate("MainWindow", "Filter Order", None, QtGui.QApplication.UnicodeUTF8)) self.besselordEdit.setText(QtGui.QApplication.translate("MainWindow", "10", None, QtGui.QApplication.UnicodeUTF8)) self.iirbesselcritLabel1.setText(QtGui.QApplication.translate("MainWindow", "Critical point-1", None, QtGui.QApplication.UnicodeUTF8)) self.iirbesselcritEdit1.setText(QtGui.QApplication.translate("MainWindow", "0.2", None, QtGui.QApplication.UnicodeUTF8)) self.iirbesselcritEdit2.setText(QtGui.QApplication.translate("MainWindow", "0.5", None, QtGui.QApplication.UnicodeUTF8)) self.iirbesselcritLabel2.setText(QtGui.QApplication.translate("MainWindow", "Critical point-2", None, QtGui.QApplication.UnicodeUTF8)) self.firhbordLabel.setText(QtGui.QApplication.translate("MainWindow", "Filter Order", None, QtGui.QApplication.UnicodeUTF8)) self.firhbordEdit.setText(QtGui.QApplication.translate("MainWindow", "34", None, QtGui.QApplication.UnicodeUTF8)) self.firhbtrEditLabel2.setText(QtGui.QApplication.translate("MainWindow", "Transition width \n" " (from fs/4)", None, QtGui.QApplication.UnicodeUTF8)) self.firhbtrEdit.setText(QtGui.QApplication.translate("MainWindow", "10000", None, QtGui.QApplication.UnicodeUTF8)) self.filterPropsBox.setTitle(QtGui.QApplication.translate("MainWindow", "Filter Properties", None, QtGui.QApplication.UnicodeUTF8)) self.nTapsLabel.setText(QtGui.QApplication.translate("MainWindow", "Number of Taps:", None, QtGui.QApplication.UnicodeUTF8)) self.designButton.setText(QtGui.QApplication.translate("MainWindow", "Design", None, QtGui.QApplication.UnicodeUTF8)) self.menu_File.setTitle(QtGui.QApplication.translate("MainWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) self.menu_Analysis.setTitle(QtGui.QApplication.translate("MainWindow", "Analysis", None, QtGui.QApplication.UnicodeUTF8)) self.menuWidgets.setTitle(QtGui.QApplication.translate("MainWindow", "View", None, QtGui.QApplication.UnicodeUTF8)) self.action_exit.setText(QtGui.QApplication.translate("MainWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) self.action_save.setText(QtGui.QApplication.translate("MainWindow", "&Save", None, QtGui.QApplication.UnicodeUTF8)) self.action_save.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+S", None, QtGui.QApplication.UnicodeUTF8)) self.action_open.setText(QtGui.QApplication.translate("MainWindow", "&Open", None, QtGui.QApplication.UnicodeUTF8)) self.action_open.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+O", None, QtGui.QApplication.UnicodeUTF8)) self.actionMagnitude_Response.setText(QtGui.QApplication.translate("MainWindow", "Magnitude Response", None, QtGui.QApplication.UnicodeUTF8)) self.actionPhase_Respone.setText(QtGui.QApplication.translate("MainWindow", "Phase Respone", None, QtGui.QApplication.UnicodeUTF8)) self.actionGroup_Delay.setText(QtGui.QApplication.translate("MainWindow", "Group Delay", None, QtGui.QApplication.UnicodeUTF8)) self.actionPhase_Delay.setText(QtGui.QApplication.translate("MainWindow", "Phase Delay", None, QtGui.QApplication.UnicodeUTF8)) self.actionImpulse_Response.setText(QtGui.QApplication.translate("MainWindow", "Impulse Response", None, QtGui.QApplication.UnicodeUTF8)) self.actionStep_Response.setText(QtGui.QApplication.translate("MainWindow", "Step Response", None, QtGui.QApplication.UnicodeUTF8)) self.actionPole_Zero_Plot.setText(QtGui.QApplication.translate("MainWindow", "Pole-Zero Plot", None, QtGui.QApplication.UnicodeUTF8)) self.actionGrid.setText(QtGui.QApplication.translate("MainWindow", "Grid", None, QtGui.QApplication.UnicodeUTF8)) self.actionPole_Zero_Plot_2.setText(QtGui.QApplication.translate("MainWindow", "Pole Zero Plot", None, QtGui.QApplication.UnicodeUTF8)) self.actionIdeal_Band.setText(QtGui.QApplication.translate("MainWindow", "Ideal Band", None, QtGui.QApplication.UnicodeUTF8)) self.actionGrid_2.setText(QtGui.QApplication.translate("MainWindow", "Grid", None, QtGui.QApplication.UnicodeUTF8)) self.actionGrid_3.setText(QtGui.QApplication.translate("MainWindow", "Grid", None, QtGui.QApplication.UnicodeUTF8)) self.actionTabbed.setText(QtGui.QApplication.translate("MainWindow", "Tabbed", None, QtGui.QApplication.UnicodeUTF8)) self.actionOverlay.setText(QtGui.QApplication.translate("MainWindow", "Overlay", None, QtGui.QApplication.UnicodeUTF8)) self.actionResponse_widget.setText(QtGui.QApplication.translate("MainWindow", "Response widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionSpec_widget.setText(QtGui.QApplication.translate("MainWindow", "Spec widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionQuick_access.setText(QtGui.QApplication.translate("MainWindow", "Quick access", None, QtGui.QApplication.UnicodeUTF8)) self.actionFilter_Coefficients.setText(QtGui.QApplication.translate("MainWindow", "Filter Coefficients", None, QtGui.QApplication.UnicodeUTF8)) self.actionDesign_widget.setText(QtGui.QApplication.translate("MainWindow", "Design widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionOverlay_2.setText(QtGui.QApplication.translate("MainWindow", "Overlay", None, QtGui.QApplication.UnicodeUTF8)) self.actionGridview.setText(QtGui.QApplication.translate("MainWindow", "Gridview", None, QtGui.QApplication.UnicodeUTF8)) self.actionDesign_widget_2.setText(QtGui.QApplication.translate("MainWindow", "Design widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionQuick_access_2.setText(QtGui.QApplication.translate("MainWindow", "Quick access", None, QtGui.QApplication.UnicodeUTF8)) self.actionSpec_widget_2.setText(QtGui.QApplication.translate("MainWindow", "Spec widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionResponse_widget_2.setText(QtGui.QApplication.translate("MainWindow", "Response widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionDesign_Widget.setText(QtGui.QApplication.translate("MainWindow", "Design Widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionQuick_Access.setText(QtGui.QApplication.translate("MainWindow", "Quick Access", None, QtGui.QApplication.UnicodeUTF8)) self.actionSpec_Widget.setText(QtGui.QApplication.translate("MainWindow", "Spec Widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionResponse_Widget.setText(QtGui.QApplication.translate("MainWindow", "Response Widget", None, QtGui.QApplication.UnicodeUTF8)) self.actionTabview_2.setText(QtGui.QApplication.translate("MainWindow", "Tabview", None, QtGui.QApplication.UnicodeUTF8)) self.actionPlot_select.setText(QtGui.QApplication.translate("MainWindow", "Plot select", None, QtGui.QApplication.UnicodeUTF8)) self.actionBand_Diagram.setText(QtGui.QApplication.translate("MainWindow", "Band Diagram", None, QtGui.QApplication.UnicodeUTF8)) self.actionCheck.setText(QtGui.QApplication.translate("MainWindow", "check", None, QtGui.QApplication.UnicodeUTF8)) self.actionPlot_FFT_points.setText(QtGui.QApplication.translate("MainWindow", "Plot FFT points", None, QtGui.QApplication.UnicodeUTF8)) from PyQt4 import Qwt5 from bandgraphicsview import BandGraphicsView from polezero_plot import PzPlot import icons_rc gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/0000775000175000017500000000000012207440367021731 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/remove_red.svg0000664000175000017500000000713012207440367024602 0ustar jcorganjcorgan image/svg+xml r x 0 gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/impulse_response.svg0000664000175000017500000000411212207440367026044 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/overlay.svg0000664000175000017500000000472212207440367024140 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/conjugate.svg0000664000175000017500000001146112207440367024434 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/step_response.svg0000664000175000017500000000355412207440367025352 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/filtr_taps.svg0000664000175000017500000000544212207440367024626 0ustar jcorganjcorgan image/svg+xml a ,b gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/phase_delay.svg0000664000175000017500000000470212207440367024733 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/add_pole.svg0000664000175000017500000000553012207440367024224 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/group_delay.svg0000664000175000017500000000520512207440367024766 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/impulse.svg0000664000175000017500000000620712207440367024135 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/mag_response.svg0000664000175000017500000000376112207440367025143 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/phase_response.svg0000664000175000017500000000442712207440367025477 0ustar jcorganjcorgan image/svg+xml gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons/add_zero.svg0000664000175000017500000000437512207440367024252 0ustar jcorganjcorgan image/svg+xml o gnuradio-3.7.2.1/gr-filter/python/filter/gui/icons_rc.py0000664000175000017500000052276612207440367023011 0ustar jcorganjcorgan# -*- coding: utf-8 -*- # Resource object code # # Created: Fri Aug 3 00:15:09 2012 # by: The Resource Compiler for PyQt (Qt v4.8.0) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x08\x4a\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x34\x33\x36\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x69\x6d\x70\x75\x6c\x73\ \x65\x5f\x72\x65\x73\x70\x6f\x6e\x73\x65\x2e\x69\x63\x6f\x22\x3e\ \x0a\x20\x20\x3c\x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x33\x34\ \x34\x32\x22\x3e\x0a\x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\ \x6b\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\ \x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\ \x20\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\ \x65\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\ \x72\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\ \x63\x3a\x74\x79\x70\x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\ \x20\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ \x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ \x6c\x49\x6d\x61\x67\x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\ \x20\x20\x20\x3c\x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\ \x63\x3a\x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ \x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\ \x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\ \x61\x64\x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\ \x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\x33\x34\x34\x30\ \x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\ \x70\x61\x67\x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\ \x66\x66\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\ \x6f\x6c\x6f\x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\ \x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\ \x79\x3d\x22\x31\x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\ \x74\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\ \x20\x20\x20\x20\x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\ \x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\ \x64\x65\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\ \x61\x67\x65\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\ \x65\x73\x68\x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\ \x6f\x77\x2d\x68\x65\x69\x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\ \x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\ \x65\x77\x33\x34\x33\x38\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\ \x77\x67\x72\x69\x64\x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\ \x3d\x22\x37\x2e\x33\x37\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x63\x78\x3d\x22\x31\x36\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\ \x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ \x6e\x64\x6f\x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\ \x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x33\ \x34\x33\x36\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\ \x0a\x20\x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\ \x0a\x20\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\ \x22\x0a\x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\ \x66\x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\ \x67\x3b\x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\ \x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\ \x41\x41\x43\x41\x41\x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\ \x7a\x65\x6e\x72\x30\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\ \x49\x43\x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x41\x50\x31\ \x4a\x52\x45\x46\x55\x0a\x57\x49\x58\x74\x6c\x7a\x46\x75\x51\x6a\ \x45\x4d\x68\x6a\x38\x6e\x36\x63\x41\x4e\x75\x72\x43\x39\x37\x70\ \x31\x36\x68\x49\x36\x49\x4c\x68\x45\x58\x51\x4f\x49\x4b\x6e\x49\ \x41\x72\x49\x4c\x46\x58\x54\x32\x2f\x71\x33\x68\x74\x30\x34\x67\ \x42\x73\x4c\x4e\x79\x41\x67\x62\x7a\x6e\x44\x71\x38\x67\x70\x45\ \x70\x56\x0a\x38\x32\x69\x56\x78\x52\x34\x64\x2b\x2f\x65\x6e\x4f\ \x4c\x46\x6b\x41\x5a\x54\x43\x56\x68\x4a\x41\x58\x63\x48\x69\x41\ \x49\x54\x42\x6d\x58\x66\x4e\x49\x39\x6f\x39\x67\x79\x72\x69\x33\ \x7a\x6e\x46\x37\x52\x41\x5a\x6f\x57\x2b\x42\x35\x4b\x55\x31\x39\ \x34\x54\x75\x41\x78\x68\x2f\x4f\x66\x59\x6b\x39\x77\x54\x78\x0a\ \x6b\x46\x6c\x2f\x53\x41\x75\x61\x45\x62\x35\x37\x41\x31\x31\x66\ \x36\x61\x78\x37\x58\x7a\x50\x4b\x56\x63\x73\x45\x55\x43\x47\x30\ \x47\x30\x52\x33\x70\x4e\x6e\x71\x34\x6b\x36\x7a\x46\x61\x49\x37\ \x51\x72\x73\x42\x7a\x62\x72\x4e\x50\x49\x42\x51\x4c\x31\x47\x70\ \x53\x48\x34\x4f\x63\x76\x56\x37\x52\x45\x6c\x2b\x0a\x6a\x6b\x70\ \x46\x71\x4a\x66\x2f\x41\x2b\x42\x66\x58\x30\x41\x57\x74\x47\x34\ \x4b\x38\x66\x67\x39\x49\x42\x37\x37\x4d\x31\x6e\x30\x73\x58\x38\ \x4e\x49\x46\x49\x68\x62\x76\x4c\x7a\x51\x34\x73\x48\x78\x45\x30\ \x51\x39\x2f\x42\x72\x58\x57\x34\x5a\x52\x4b\x46\x57\x51\x6e\x33\ \x4c\x49\x43\x73\x2f\x69\x41\x7a\x41\x0a\x41\x41\x7a\x41\x41\x41\ \x7a\x41\x41\x41\x7a\x41\x41\x41\x77\x41\x43\x69\x2b\x6e\x35\x39\ \x57\x73\x6d\x48\x30\x43\x6a\x73\x52\x45\x35\x37\x4b\x79\x74\x38\ \x41\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\x43\x59\x49\ \x49\x3d\x0a\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\ \x61\x67\x65\x33\x34\x34\x34\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\ \x22\x30\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\ \x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x0e\x58\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x72\x65\x6d\x6f\x76\x65\ \x5f\x72\x65\x64\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\ \x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x6d\x65\x74\x61\x64\x61\x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\ \x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\ \x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\ \x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\ \x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\ \x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\ \x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\ \x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\ \x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\ \x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\ \x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\ \x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x64\x65\x66\x73\x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\ \x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\ \x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\ \x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\ \x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\ \x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\ \x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\ \x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\ \x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\ \x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\ \x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\ \x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\ \x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\ \x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\ \x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\ \x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\ \x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\ \x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x63\x78\x3d\x22\x32\x36\x2e\x32\x31\x34\x39\x33\x36\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\ \x3d\x22\x31\x39\x2e\x37\x32\x38\x38\x31\x34\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\ \x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ \x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\ \x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\ \x65\x72\x3d\x22\x73\x76\x67\x34\x35\x35\x37\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\ \x67\x6c\x6f\x62\x61\x6c\x3d\x22\x66\x61\x6c\x73\x65\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\ \x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\ \x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\ \x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\ \x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\ \x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\x41\ \x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\x41\ \x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\ \x41\x68\x6b\x69\x41\x41\x41\x41\x44\x56\x4a\x52\x45\x46\x55\x0a\ \x57\x49\x58\x74\x31\x7a\x45\x42\x41\x44\x41\x4d\x77\x7a\x42\x33\ \x2f\x44\x6c\x33\x4d\x50\x6f\x6f\x42\x4b\x77\x33\x55\x32\x33\x48\ \x75\x77\x54\x73\x4f\x34\x78\x58\x42\x51\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x77\x48\x64\x2f\x7a\ \x44\x78\x72\x74\x42\x44\x6b\x45\x71\x4e\x62\x67\x0a\x41\x41\x41\ \x41\x41\x45\x6c\x46\x54\x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\ \x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x34\x35\ \x36\x35\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\ \x74\x65\x78\x74\x0a\x20\x20\x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\ \x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\x22\x0a\x20\ \x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\ \x73\x69\x7a\x65\x3a\x34\x30\x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\ \x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\ \x2d\x77\x65\x69\x67\x68\x74\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\ \x69\x6e\x65\x2d\x68\x65\x69\x67\x68\x74\x3a\x31\x32\x35\x25\x3b\ \x6c\x65\x74\x74\x65\x72\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\ \x70\x78\x3b\x77\x6f\x72\x64\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\ \x30\x70\x78\x3b\x66\x69\x6c\x6c\x3a\x23\x30\x30\x30\x30\x30\x30\ \x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x3b\ \x73\x74\x72\x6f\x6b\x65\x3a\x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\ \x2d\x66\x61\x6d\x69\x6c\x79\x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\ \x20\x20\x20\x78\x3d\x22\x31\x31\x2e\x36\x36\x31\x30\x31\x37\x22\ \x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x39\x2e\x33\x35\x35\x39\x33\ \x32\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\x65\x78\ \x74\x35\x34\x31\x38\x22\x0a\x20\x20\x20\x20\x20\x73\x6f\x64\x69\ \x70\x6f\x64\x69\x3a\x6c\x69\x6e\x65\x73\x70\x61\x63\x69\x6e\x67\ \x3d\x22\x31\x32\x35\x25\x22\x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\ \x20\x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\ \x6f\x6c\x65\x3d\x22\x6c\x69\x6e\x65\x22\x0a\x20\x20\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x74\x73\x70\x61\x6e\x35\x34\x32\x30\x22\ \x0a\x20\x20\x20\x20\x20\x20\x20\x78\x3d\x22\x31\x31\x2e\x36\x36\ \x31\x30\x31\x37\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x79\x3d\x22\ \x39\x2e\x33\x35\x35\x39\x33\x32\x32\x22\x20\x2f\x3e\x3c\x2f\x74\ \x65\x78\x74\x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\x20\x20\ \x20\x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\ \x73\x65\x72\x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\x79\x6c\ \x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x34\x30\x70\ \x78\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\x72\ \x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\x3a\ \x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\x67\ \x68\x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\x2d\x73\ \x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\x64\x2d\ \x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\x6c\x6c\ \x3a\x23\x66\x66\x30\x30\x30\x30\x3b\x66\x69\x6c\x6c\x2d\x6f\x70\ \x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x6e\ \x6f\x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\ \x53\x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x35\x2e\ \x39\x36\x36\x31\x30\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\ \x22\x32\x37\x2e\x31\x31\x38\x36\x34\x35\x22\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x74\x65\x78\x74\x36\x34\x38\x34\x22\x0a\x20\ \x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\x69\x6e\ \x65\x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\x22\x3e\ \x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\x73\x6f\ \x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\x69\x6e\ \x65\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\x73\ \x70\x61\x6e\x36\x34\x38\x36\x22\x0a\x20\x20\x20\x20\x20\x20\x20\ \x78\x3d\x22\x35\x2e\x39\x36\x36\x31\x30\x31\x36\x22\x0a\x20\x20\ \x20\x20\x20\x20\x20\x79\x3d\x22\x32\x37\x2e\x31\x31\x38\x36\x34\ \x35\x22\x3e\x72\x3c\x2f\x74\x73\x70\x61\x6e\x3e\x3c\x2f\x74\x65\ \x78\x74\x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\x20\x20\x20\ \x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\ \x65\x72\x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\ \x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x31\x32\x2e\x35\ \x39\x33\x33\x34\x39\x34\x36\x30\x30\x30\x30\x30\x30\x30\x36\x36\ \x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\ \x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\ \x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\ \x67\x68\x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\x2d\ \x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\x64\ \x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\x6c\ \x6c\x3a\x23\x30\x30\x30\x30\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x6f\ \x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\x3a\ \x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\ \x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x31\ \x32\x2e\x37\x31\x33\x34\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x79\ \x3d\x22\x31\x39\x2e\x38\x38\x36\x35\x37\x32\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x74\x65\x78\x74\x36\x34\x38\x38\x22\x0a\ \x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\x69\ \x6e\x65\x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\x22\ \x0a\x20\x20\x20\x20\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\ \x22\x73\x63\x61\x6c\x65\x28\x31\x2e\x31\x34\x35\x38\x30\x38\x34\ \x2c\x30\x2e\x38\x37\x32\x37\x34\x36\x32\x37\x29\x22\x3e\x3c\x74\ \x73\x70\x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\x73\x6f\x64\x69\ \x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\x69\x6e\x65\x22\ \x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\x73\x70\x61\ \x6e\x36\x34\x39\x30\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x78\x3d\ \x22\x31\x32\x2e\x37\x31\x33\x34\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x20\x20\x79\x3d\x22\x31\x39\x2e\x38\x38\x36\x35\x37\x32\x22\ \x3e\x78\x3c\x2f\x74\x73\x70\x61\x6e\x3e\x3c\x2f\x74\x65\x78\x74\ \x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\x20\x20\x20\x20\x78\ \x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\ \x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\ \x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x31\x32\x2e\x32\x39\x30\ \x36\x30\x37\x34\x34\x39\x39\x39\x39\x39\x39\x39\x35\x35\x70\x78\ \x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\ \x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\x3a\x6e\ \x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\x67\x68\ \x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\x2d\x73\x70\ \x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\x64\x2d\x73\ \x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\x6c\x6c\x3a\ \x23\x30\x30\x30\x30\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\ \x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x6e\x6f\ \x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\x53\ \x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x31\x34\x2e\ \x32\x35\x30\x32\x38\x32\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\ \x32\x37\x2e\x35\x34\x39\x30\x31\x37\x22\x0a\x20\x20\x20\x20\x20\ \x69\x64\x3d\x22\x74\x65\x78\x74\x36\x34\x39\x32\x22\x0a\x20\x20\ \x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\x69\x6e\x65\ \x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\x22\x0a\x20\ \x20\x20\x20\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x73\ \x63\x61\x6c\x65\x28\x31\x2e\x30\x32\x31\x33\x38\x32\x33\x2c\x30\ \x2e\x39\x37\x39\x30\x36\x35\x33\x33\x29\x22\x3e\x3c\x74\x73\x70\ \x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\ \x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\x69\x6e\x65\x22\x0a\x20\ \x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\x73\x70\x61\x6e\x36\ \x34\x39\x34\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x78\x3d\x22\x31\ \x34\x2e\x32\x35\x30\x32\x38\x32\x22\x0a\x20\x20\x20\x20\x20\x20\ \x20\x79\x3d\x22\x32\x37\x2e\x35\x34\x39\x30\x31\x37\x22\x3e\x30\ \x3c\x2f\x74\x73\x70\x61\x6e\x3e\x3c\x2f\x74\x65\x78\x74\x3e\x0a\ \x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x09\xc2\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x36\x39\x35\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x70\x68\x61\x73\x65\x5f\ \x64\x65\x6c\x61\x79\x2e\x69\x63\x6f\x22\x3e\x0a\x20\x20\x3c\x6d\ \x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\ \x22\x6d\x65\x74\x61\x64\x61\x74\x61\x33\x37\x30\x31\x22\x3e\x0a\ \x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\ \x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\ \x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\ \x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\ \x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\ \x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ \x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\ \x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\ \x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\ \x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\ \x63\x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\ \x6c\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\ \x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\ \x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ \x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x64\x65\x66\x73\x33\x36\x39\x39\x22\x20\x2f\x3e\x0a\ \x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\ \x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\ \x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\ \x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\ \x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\ \x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\ \x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\ \x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\ \x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\ \x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\ \x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\ \x68\x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\ \x69\x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x33\x36\x39\ \x37\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\ \x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\ \x37\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ \x65\x3a\x63\x78\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x36\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ \x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\ \x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\ \x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\ \x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x33\x36\x39\x35\x22\x20\ \x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\ \x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\ \x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\ \x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\ \x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\ \x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\ \x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\ \x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\ \x66\x41\x68\x6b\x69\x41\x41\x41\x41\x68\x68\x4a\x52\x45\x46\x55\ \x0a\x57\x49\x58\x74\x6c\x55\x39\x49\x56\x45\x45\x63\x78\x7a\x2f\ \x7a\x5a\x74\x72\x53\x4e\x6e\x64\x72\x55\x31\x6a\x37\x44\x39\x45\ \x68\x75\x6e\x52\x4d\x49\x76\x45\x53\x55\x53\x65\x68\x77\x45\x4f\ \x48\x4a\x4b\x78\x54\x70\x34\x49\x36\x47\x47\x4c\x64\x75\x6e\x6a\ \x74\x55\x6c\x32\x57\x6b\x6b\x54\x70\x55\x42\x30\x36\x0a\x43\x46\ \x4b\x75\x46\x37\x55\x4d\x53\x32\x6b\x58\x44\x52\x64\x69\x43\x5a\ \x58\x43\x72\x57\x7a\x66\x65\x7a\x73\x64\x4e\x6b\x72\x64\x43\x47\ \x62\x65\x32\x68\x4c\x73\x35\x2f\x53\x59\x65\x62\x38\x76\x48\x32\ \x62\x65\x37\x2f\x63\x6b\x51\x5a\x43\x7a\x4c\x59\x6a\x6c\x49\x2b\ \x69\x78\x53\x64\x73\x49\x4a\x35\x43\x41\x0a\x38\x43\x37\x67\x63\ \x43\x74\x49\x52\x44\x43\x42\x4d\x6c\x42\x78\x41\x57\x46\x65\x6f\ \x69\x56\x71\x70\x42\x4f\x64\x50\x6f\x6d\x49\x37\x49\x59\x50\x55\ \x66\x54\x32\x4d\x5a\x68\x37\x6a\x64\x39\x2f\x46\x5a\x4a\x4c\x35\ \x64\x64\x63\x69\x5a\x70\x34\x6a\x4c\x77\x79\x42\x51\x64\x44\x71\ \x4e\x51\x44\x31\x4d\x55\x4d\x0a\x61\x49\x47\x63\x76\x34\x32\x36\ \x6b\x59\x46\x6d\x5a\x52\x4a\x6e\x65\x41\x58\x44\x44\x54\x42\x31\ \x43\x6a\x46\x78\x44\x74\x37\x6d\x66\x36\x38\x4c\x6a\x66\x2f\x38\ \x47\x68\x7a\x59\x69\x64\x78\x77\x66\x50\x30\x45\x35\x4a\x66\x44\ \x41\x48\x6a\x68\x32\x64\x4c\x4e\x31\x6b\x38\x67\x50\x49\x52\x37\ \x33\x69\x54\x79\x0a\x37\x38\x65\x6c\x65\x76\x57\x76\x5a\x36\x39\ \x4e\x77\x4a\x73\x61\x69\x41\x4e\x75\x34\x63\x38\x46\x6f\x67\x42\ \x36\x63\x2f\x6b\x45\x76\x4c\x62\x56\x48\x36\x6d\x4b\x76\x73\x49\ \x48\x51\x6d\x36\x4d\x50\x50\x4f\x72\x58\x78\x36\x74\x68\x58\x51\ \x49\x49\x66\x74\x4e\x42\x4d\x79\x75\x34\x48\x76\x37\x65\x33\x52\ \x6b\x0a\x68\x6b\x4b\x38\x70\x32\x52\x50\x6e\x65\x36\x41\x68\x57\ \x2b\x34\x36\x72\x35\x4a\x70\x45\x30\x62\x62\x6b\x4d\x4e\x4a\x74\ \x44\x70\x4b\x4f\x79\x4e\x49\x53\x59\x62\x34\x64\x41\x51\x4f\x68\ \x58\x48\x47\x65\x6a\x41\x48\x52\x77\x33\x7a\x37\x51\x69\x74\x67\ \x58\x31\x38\x69\x6e\x71\x63\x68\x62\x4f\x4e\x74\x69\x6d\x0a\x42\ \x4a\x69\x45\x43\x30\x73\x51\x2f\x67\x77\x35\x46\x78\x49\x66\x4b\ \x79\x42\x51\x48\x6f\x79\x6d\x56\x67\x6c\x65\x37\x53\x58\x77\x4e\ \x77\x57\x4a\x57\x4e\x4e\x6d\x4b\x2f\x70\x2b\x76\x56\x6e\x62\x34\ \x6c\x58\x2b\x49\x33\x79\x4a\x54\x4e\x35\x46\x39\x65\x55\x41\x55\ \x50\x64\x79\x79\x4f\x74\x33\x6f\x4d\x75\x71\x0a\x6f\x38\x79\x4c\ \x70\x4f\x78\x47\x39\x49\x37\x6a\x50\x61\x77\x48\x77\x47\x73\x50\ \x51\x2f\x59\x4a\x38\x6b\x57\x58\x6a\x59\x41\x35\x61\x6d\x41\x52\ \x7a\x74\x51\x55\x5a\x58\x70\x6d\x69\x6f\x76\x54\x64\x61\x69\x62\ \x69\x7a\x5a\x78\x46\x73\x65\x57\x6a\x30\x44\x66\x4d\x67\x42\x69\ \x36\x34\x37\x69\x57\x69\x49\x48\x0a\x2b\x79\x4c\x2f\x53\x45\x43\ \x34\x63\x43\x49\x45\x67\x42\x37\x35\x2b\x65\x50\x70\x56\x76\x44\ \x56\x74\x52\x45\x77\x6e\x34\x53\x36\x66\x68\x71\x6e\x72\x70\x56\ \x43\x55\x78\x4b\x61\x38\x35\x44\x64\x68\x58\x4f\x30\x43\x62\x30\ \x2f\x5a\x53\x4e\x67\x4d\x59\x31\x47\x47\x35\x48\x5a\x49\x58\x6a\ \x6e\x34\x32\x38\x38\x0a\x68\x74\x77\x7a\x44\x48\x4d\x43\x2f\x31\ \x45\x4c\x50\x4d\x76\x59\x53\x46\x53\x70\x55\x6c\x46\x2b\x41\x47\ \x50\x45\x6c\x34\x58\x43\x30\x65\x30\x57\x41\x41\x41\x41\x41\x45\ \x6c\x46\x54\x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x33\x37\x30\x33\x22\ \x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\ \x0a\ \x00\x00\x13\x31\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x63\x6f\x6e\x6a\x75\x67\ \x61\x74\x65\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\x74\ \x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6d\ \x65\x74\x61\x64\x61\x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\x20\ \x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\ \x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\ \x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\ \x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\ \x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x72\ \x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\ \x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\ \x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\ \x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\ \x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\x65\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\x72\ \x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\x46\ \x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\x0a\ \x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\ \x22\x64\x65\x66\x73\x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\x20\ \x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\x76\ \x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\x6c\ \x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\x20\ \x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\x23\ \x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\ \x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\x20\ \x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\x61\ \x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x72\ \x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\ \x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\x72\ \x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\x63\ \x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\x77\ \x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\x3d\ \x22\x36\x38\x31\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\x68\ \x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\ \x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\x22\x0a\ \x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\x66\ \x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\x35\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\ \x78\x3d\x22\x31\x30\x2e\x32\x37\x31\x30\x30\x35\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\ \x31\x33\x2e\x32\x32\x32\x38\x37\x38\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\ \x78\x3d\x22\x36\x38\x33\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\ \x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ \x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\ \x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\ \x65\x72\x3d\x22\x73\x76\x67\x34\x35\x35\x37\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\ \x67\x6c\x6f\x62\x61\x6c\x3d\x22\x66\x61\x6c\x73\x65\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\ \x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\ \x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\ \x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\ \x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\ \x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\x41\ \x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\x41\ \x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\ \x41\x68\x6b\x69\x41\x41\x41\x41\x44\x56\x4a\x52\x45\x46\x55\x0a\ \x57\x49\x58\x74\x31\x7a\x45\x42\x41\x44\x41\x4d\x77\x7a\x42\x33\ \x2f\x44\x6c\x33\x4d\x50\x6f\x6f\x42\x4b\x77\x33\x55\x32\x33\x48\ \x75\x77\x54\x73\x4f\x34\x78\x58\x42\x51\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x77\x48\x64\x2f\x7a\ \x44\x78\x72\x74\x42\x44\x6b\x45\x71\x4e\x62\x67\x0a\x41\x41\x41\ \x41\x41\x45\x6c\x46\x54\x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\ \x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x34\x35\ \x36\x35\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\ \x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x31\x2e\ \x32\x35\x34\x32\x33\x37\x37\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\ \x22\x30\x2e\x33\x33\x38\x39\x38\x32\x38\x32\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x35\x33\x32\x39\x22\ \x0a\x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\ \x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\ \x3b\x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\ \x47\x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\ \x41\x48\x67\x41\x41\x41\x43\x55\x43\x41\x59\x41\x41\x41\x42\x59\ \x34\x75\x30\x72\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\ \x43\x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x41\x35\x35\x4a\ \x52\x45\x46\x55\x0a\x65\x4a\x7a\x74\x33\x64\x74\x79\x32\x7a\x41\ \x4d\x52\x56\x47\x34\x30\x2f\x2f\x2f\x5a\x66\x66\x4a\x4d\x33\x5a\ \x39\x45\x57\x38\x67\x44\x73\x43\x39\x6e\x74\x4f\x45\x31\x69\x5a\ \x56\x53\x57\x59\x63\x4d\x77\x41\x41\x41\x41\x41\x41\x41\x41\x41\ \x49\x64\x34\x73\x65\x51\x41\x33\x33\x65\x39\x76\x58\x33\x62\x59\ \x66\x0a\x62\x77\x4a\x50\x61\x51\x33\x37\x79\x5a\x37\x59\x42\x42\ \x34\x32\x45\x2f\x66\x42\x50\x7a\x4b\x42\x75\x36\x30\x49\x2b\x38\ \x77\x33\x38\x68\x2f\x50\x62\x34\x34\x57\x71\x79\x66\x4d\x4b\x31\ \x5a\x77\x46\x38\x38\x59\x50\x69\x75\x5a\x46\x64\x7a\x4d\x64\x36\ \x56\x35\x49\x62\x41\x4d\x6e\x77\x6c\x45\x34\x43\x59\x35\x0a\x56\ \x36\x38\x5a\x67\x63\x57\x73\x6e\x30\x67\x45\x4c\x6f\x37\x41\x6c\ \x2f\x4b\x65\x6e\x73\x30\x49\x58\x42\x36\x42\x69\x79\x4e\x77\x63\ \x51\x51\x75\x6a\x73\x43\x58\x39\x72\x2b\x48\x75\x78\x4b\x42\x69\ \x79\x4f\x77\x6c\x50\x56\x6e\x43\x77\x49\x33\x79\x58\x75\x61\x4a\ \x6e\x42\x78\x61\x57\x64\x6d\x44\x4e\x34\x50\x0a\x78\x68\x43\x2f\ \x2f\x77\x4a\x59\x77\x57\x38\x2b\x72\x64\x4c\x6e\x41\x4c\x6e\x32\ \x5a\x42\x48\x59\x7a\x50\x72\x33\x4e\x61\x2b\x4b\x7a\x4b\x35\x4b\ \x5a\x36\x4f\x68\x56\x6f\x52\x6d\x58\x37\x51\x54\x6a\x39\x58\x58\ \x38\x7a\x33\x33\x33\x6e\x49\x64\x46\x4e\x6a\x6a\x43\x76\x68\x62\ \x72\x4d\x66\x50\x69\x72\x39\x2f\x0a\x44\x68\x2b\x41\x72\x78\x31\ \x76\x31\x73\x64\x48\x2f\x45\x56\x36\x63\x4f\x4e\x32\x37\x38\x4c\ \x51\x6a\x53\x77\x37\x73\x48\x37\x52\x57\x32\x73\x30\x49\x2f\x2b\ \x4e\x48\x73\x43\x38\x36\x4c\x44\x61\x4a\x47\x66\x64\x4e\x64\x57\ \x6f\x65\x71\x73\x34\x32\x51\x70\x57\x44\x61\x74\x4c\x62\x73\x61\ \x39\x79\x78\x5a\x56\x0a\x61\x78\x56\x4c\x44\x65\x5a\x56\x74\x72\ \x44\x50\x64\x43\x4b\x4c\x6e\x61\x49\x7a\x52\x39\x55\x6b\x4d\x74\ \x4d\x71\x68\x74\x56\x59\x78\x63\x45\x72\x75\x47\x4a\x59\x4c\x59\ \x47\x7a\x37\x49\x53\x34\x38\x61\x75\x59\x48\x52\x33\x46\x42\x63\ \x32\x77\x45\x31\x62\x76\x51\x2b\x77\x71\x4c\x72\x61\x43\x62\x37\ \x66\x6f\x0a\x41\x2f\x6f\x75\x64\x6a\x4b\x4c\x33\x53\x61\x4e\x38\ \x74\x77\x7a\x6c\x56\x76\x69\x69\x36\x79\x72\x4e\x39\x76\x56\x78\ \x4a\x78\x5a\x6b\x71\x31\x67\x74\x64\x4f\x76\x76\x75\x41\x44\x35\ \x76\x45\x70\x72\x61\x6f\x72\x32\x4f\x7a\x51\x54\x35\x76\x39\x46\ \x6d\x54\x30\x59\x43\x67\x48\x4e\x6d\x50\x54\x33\x52\x54\x31\x0a\ \x75\x47\x61\x37\x41\x78\x65\x37\x54\x63\x70\x67\x37\x79\x51\x6b\ \x63\x48\x45\x45\x44\x72\x46\x76\x46\x52\x4e\x34\x69\x75\x4b\x54\ \x73\x31\x63\x45\x44\x72\x4e\x6e\x46\x55\x76\x50\x76\x6a\x37\x52\ \x6d\x39\x31\x6e\x66\x35\x48\x4e\x42\x79\x74\x34\x79\x4b\x63\x6f\ \x6d\x71\x64\x71\x41\x6e\x64\x62\x48\x64\x4c\x33\x0a\x7a\x46\x4d\ \x6b\x73\x4d\x6f\x44\x44\x72\x31\x56\x58\x43\x44\x77\x7a\x72\x68\ \x65\x41\x66\x31\x65\x67\x39\x79\x4d\x36\x36\x4d\x61\x56\x2b\x65\ \x43\x4b\x2f\x45\x4b\x56\x6f\x30\x37\x38\x76\x56\x2b\x6b\x67\x5a\ \x57\x6a\x6a\x75\x44\x76\x39\x6c\x67\x4f\x68\x64\x55\x56\x7a\x52\ \x57\x63\x62\x4c\x41\x30\x51\x38\x7a\x0a\x64\x76\x2f\x37\x65\x63\ \x6b\x43\x6f\x31\x65\x69\x77\x46\x6c\x4f\x7a\x66\x39\x6a\x58\x33\ \x53\x44\x72\x48\x45\x66\x34\x69\x4a\x50\x2f\x75\x43\x72\x7a\x33\ \x56\x63\x49\x54\x72\x75\x71\x74\x66\x54\x38\x6a\x72\x57\x54\x77\ \x54\x48\x6a\x57\x30\x72\x42\x68\x73\x64\x31\x32\x7a\x74\x51\x66\ \x2f\x31\x65\x6e\x78\x57\x0a\x2b\x63\x41\x33\x37\x54\x33\x6f\x4d\ \x77\x4f\x76\x46\x76\x6a\x68\x2b\x58\x58\x4a\x66\x64\x72\x73\x7a\ \x73\x64\x77\x43\x6f\x48\x4e\x6f\x69\x2b\x55\x5a\x6e\x52\x65\x5a\ \x4d\x30\x63\x38\x50\x74\x64\x4a\x39\x67\x35\x41\x71\x36\x69\x43\ \x62\x31\x54\x34\x47\x31\x53\x70\x74\x42\x5a\x78\x76\x6c\x4f\x34\ \x44\x37\x34\x0a\x57\x2b\x69\x38\x42\x31\x57\x4a\x51\x4f\x43\x48\ \x35\x36\x44\x45\x58\x53\x58\x78\x6c\x65\x31\x75\x4f\x61\x2b\x6b\ \x68\x56\x59\x77\x50\x41\x77\x45\x7a\x6a\x53\x54\x4d\x34\x33\x56\ \x78\x2b\x41\x4b\x31\x76\x2b\x56\x44\x66\x33\x78\x37\x54\x46\x35\ \x69\x6c\x59\x4e\x72\x54\x69\x6d\x47\x45\x58\x65\x2b\x62\x6b\x4b\ \x0a\x75\x6d\x4a\x63\x4f\x53\x64\x4e\x75\x6e\x32\x2b\x37\x31\x6f\ \x50\x2f\x4a\x6d\x52\x6e\x51\x66\x73\x48\x62\x72\x33\x67\x48\x74\ \x39\x64\x4a\x4f\x75\x44\x51\x50\x32\x69\x68\x7a\x78\x4e\x69\x53\ \x42\x66\x31\x67\x5a\x4f\x6d\x6f\x7a\x51\x62\x37\x41\x47\x78\x39\ \x30\x72\x4c\x72\x69\x7a\x6e\x65\x51\x49\x77\x55\x38\x0a\x79\x5a\ \x6f\x4a\x54\x64\x78\x65\x67\x59\x38\x71\x65\x30\x4d\x54\x64\x34\ \x54\x41\x73\x2b\x69\x57\x30\x4d\x51\x64\x4a\x66\x52\x68\x70\x45\ \x54\x30\x49\x4c\x43\x43\x34\x59\x6e\x41\x78\x52\x47\x34\x57\x63\ \x37\x2f\x51\x67\x68\x63\x48\x49\x47\x4c\x4f\x7a\x54\x77\x4f\x66\ \x76\x4b\x44\x67\x31\x38\x44\x67\x49\x58\x0a\x52\x2b\x44\x69\x43\ \x46\x77\x63\x67\x59\x73\x6a\x63\x48\x45\x45\x4c\x6f\x37\x41\x54\ \x58\x49\x2b\x70\x6a\x51\x6a\x63\x48\x6b\x45\x4c\x75\x37\x41\x77\ \x4f\x63\x38\x70\x6a\x51\x37\x4d\x76\x42\x5a\x43\x46\x77\x63\x67\ \x59\x73\x6a\x63\x48\x45\x45\x4c\x6f\x37\x41\x78\x52\x47\x34\x4f\ \x41\x49\x58\x52\x2b\x42\x4c\x0a\x65\x5a\x39\x44\x6d\x78\x47\x34\ \x76\x4d\x4d\x43\x6e\x2f\x57\x59\x30\x75\x79\x34\x77\x4f\x63\x68\ \x63\x48\x45\x45\x4c\x6f\x37\x41\x78\x52\x47\x34\x4f\x41\x49\x58\ \x6c\x2f\x6f\x6d\x66\x6b\x7a\x50\x72\x56\x4c\x75\x68\x78\x78\x6d\ \x52\x77\x59\x32\x69\x2f\x6f\x7a\x63\x78\x46\x4b\x76\x49\x67\x78\ \x2b\x2f\x2f\x4d\x0a\x48\x41\x41\x41\x41\x41\x41\x41\x41\x43\x62\ \x38\x41\x78\x4d\x4b\x7a\x76\x4c\x75\x31\x71\x62\x6b\x41\x41\x41\ \x41\x41\x45\x6c\x46\x54\x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\ \x20\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x32\x39\x2e\ \x37\x36\x32\x37\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x77\x69\x64\ \x74\x68\x3d\x22\x32\x31\x2e\x39\x36\x36\x31\x30\x33\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\ \x79\x3d\x22\x30\x2e\x39\x38\x33\x30\x34\x38\x36\x32\x22\x0a\x20\ \x20\x20\x20\x20\x78\x3d\x22\x31\x31\x2e\x35\x32\x35\x34\x32\x34\ \x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\ \x35\x33\x32\x39\x2d\x38\x22\x0a\x20\x20\x20\x20\x20\x78\x6c\x69\ \x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\ \x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\x36\x34\x2c\x69\ \x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\x53\ \x55\x68\x45\x55\x67\x41\x41\x41\x48\x67\x41\x41\x41\x43\x55\x43\ \x41\x59\x41\x41\x41\x42\x59\x34\x75\x30\x72\x41\x41\x41\x41\x42\ \x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\x41\x68\x6b\x69\ \x41\x41\x41\x41\x35\x35\x4a\x52\x45\x46\x55\x20\x65\x4a\x7a\x74\ \x33\x64\x74\x79\x32\x7a\x41\x4d\x52\x56\x47\x34\x30\x2f\x2f\x2f\ \x5a\x66\x66\x4a\x4d\x33\x5a\x39\x45\x57\x38\x67\x44\x73\x43\x39\ \x6e\x74\x4f\x45\x31\x69\x5a\x56\x53\x57\x59\x63\x4d\x77\x41\x41\ \x41\x41\x41\x41\x41\x41\x41\x49\x64\x34\x73\x65\x51\x41\x33\x33\ \x65\x39\x76\x58\x33\x62\x59\x66\x20\x62\x77\x4a\x50\x61\x51\x33\ \x37\x79\x5a\x37\x59\x42\x42\x34\x32\x45\x2f\x66\x42\x50\x7a\x4b\ \x42\x75\x36\x30\x49\x2b\x38\x77\x33\x38\x68\x2f\x50\x62\x34\x34\ \x57\x71\x79\x66\x4d\x4b\x31\x5a\x77\x46\x38\x38\x59\x50\x69\x75\ \x5a\x46\x64\x7a\x4d\x64\x36\x56\x35\x49\x62\x41\x4d\x6e\x77\x6c\ \x45\x34\x43\x59\x35\x20\x56\x36\x38\x5a\x67\x63\x57\x73\x6e\x30\ \x67\x45\x4c\x6f\x37\x41\x6c\x2f\x4b\x65\x6e\x73\x30\x49\x58\x42\ \x36\x42\x69\x79\x4e\x77\x63\x51\x51\x75\x6a\x73\x43\x58\x39\x72\ \x2b\x48\x75\x78\x4b\x42\x69\x79\x4f\x77\x6c\x50\x56\x6e\x43\x77\ \x49\x33\x79\x58\x75\x61\x4a\x6e\x42\x78\x61\x57\x64\x6d\x44\x4e\ \x34\x50\x20\x78\x68\x43\x2f\x2f\x77\x4a\x59\x77\x57\x38\x2b\x72\ \x64\x4c\x6e\x41\x4c\x6e\x32\x5a\x42\x48\x59\x7a\x50\x72\x33\x4e\ \x61\x2b\x4b\x7a\x4b\x35\x4b\x5a\x36\x4f\x68\x56\x6f\x52\x6d\x58\ \x37\x51\x54\x6a\x39\x58\x58\x38\x7a\x33\x33\x33\x6e\x49\x64\x46\ \x4e\x6a\x6a\x43\x76\x68\x62\x72\x4d\x66\x50\x69\x72\x39\x2f\x20\ \x44\x68\x2b\x41\x72\x78\x31\x76\x31\x73\x64\x48\x2f\x45\x56\x36\ \x63\x4f\x4e\x32\x37\x38\x4c\x51\x6a\x53\x77\x37\x73\x48\x37\x52\ \x57\x32\x73\x30\x49\x2f\x2b\x4e\x48\x73\x43\x38\x36\x4c\x44\x61\ \x4a\x47\x66\x64\x4e\x64\x57\x6f\x65\x71\x73\x34\x32\x51\x70\x57\ \x44\x61\x74\x4c\x62\x73\x61\x39\x79\x78\x5a\x56\x20\x61\x78\x56\ \x4c\x44\x65\x5a\x56\x74\x72\x44\x50\x64\x43\x4b\x4c\x6e\x61\x49\ \x7a\x52\x39\x55\x6b\x4d\x74\x4d\x71\x68\x74\x56\x59\x78\x63\x45\ \x72\x75\x47\x4a\x59\x4c\x59\x47\x7a\x37\x49\x53\x34\x38\x61\x75\ \x59\x48\x52\x33\x46\x42\x63\x32\x77\x45\x31\x62\x76\x51\x2b\x77\ \x71\x4c\x72\x61\x43\x62\x37\x66\x6f\x20\x41\x2f\x6f\x75\x64\x6a\ \x4b\x4c\x33\x53\x61\x4e\x38\x74\x77\x7a\x6c\x56\x76\x69\x69\x36\ \x79\x72\x4e\x39\x76\x56\x78\x4a\x78\x5a\x6b\x71\x31\x67\x74\x64\ \x4f\x76\x76\x75\x41\x44\x35\x76\x45\x70\x72\x61\x6f\x72\x32\x4f\ \x7a\x51\x54\x35\x76\x39\x46\x6d\x54\x30\x59\x43\x67\x48\x4e\x6d\ \x50\x54\x33\x52\x54\x31\x20\x75\x47\x61\x37\x41\x78\x65\x37\x54\ \x63\x70\x67\x37\x79\x51\x6b\x63\x48\x45\x45\x44\x72\x46\x76\x46\ \x52\x4e\x34\x69\x75\x4b\x54\x73\x31\x63\x45\x44\x72\x4e\x6e\x46\ \x55\x76\x50\x76\x6a\x37\x52\x6d\x39\x31\x6e\x66\x35\x48\x4e\x42\ \x79\x74\x34\x79\x4b\x63\x6f\x6d\x71\x64\x71\x41\x6e\x64\x62\x48\ \x64\x4c\x33\x20\x7a\x46\x4d\x6b\x73\x4d\x6f\x44\x44\x72\x31\x56\ \x58\x43\x44\x77\x7a\x72\x68\x65\x41\x66\x31\x65\x67\x39\x79\x4d\ \x36\x36\x4d\x61\x56\x2b\x65\x43\x4b\x2f\x45\x4b\x56\x6f\x30\x37\ \x38\x76\x56\x2b\x6b\x67\x5a\x57\x6a\x6a\x75\x44\x76\x39\x6c\x67\ \x4f\x68\x64\x55\x56\x7a\x52\x57\x63\x62\x4c\x41\x30\x51\x38\x7a\ \x20\x64\x76\x2f\x37\x65\x63\x6b\x43\x6f\x31\x65\x69\x77\x46\x6c\ \x4f\x7a\x66\x39\x6a\x58\x33\x53\x44\x72\x48\x45\x66\x34\x69\x4a\ \x50\x2f\x75\x43\x72\x7a\x33\x56\x63\x49\x54\x72\x75\x71\x74\x66\ \x54\x38\x6a\x72\x57\x54\x77\x54\x48\x6a\x57\x30\x72\x42\x68\x73\ \x64\x31\x32\x7a\x74\x51\x66\x2f\x31\x65\x6e\x78\x57\x20\x2b\x63\ \x41\x33\x37\x54\x33\x6f\x4d\x77\x4f\x76\x46\x76\x6a\x68\x2b\x58\ \x58\x4a\x66\x64\x72\x73\x7a\x73\x64\x77\x43\x6f\x48\x4e\x6f\x69\ \x2b\x55\x5a\x6e\x52\x65\x5a\x4d\x30\x63\x38\x50\x74\x64\x4a\x39\ \x67\x35\x41\x71\x36\x69\x43\x62\x31\x54\x34\x47\x31\x53\x70\x74\ \x42\x5a\x78\x76\x6c\x4f\x34\x44\x37\x34\x20\x57\x2b\x69\x38\x42\ \x31\x57\x4a\x51\x4f\x43\x48\x35\x36\x44\x45\x58\x53\x58\x78\x6c\ \x65\x31\x75\x4f\x61\x2b\x6b\x68\x56\x59\x77\x50\x41\x77\x45\x7a\ \x6a\x53\x54\x4d\x34\x33\x56\x78\x2b\x41\x4b\x31\x76\x2b\x56\x44\ \x66\x33\x78\x37\x54\x46\x35\x69\x6c\x59\x4e\x72\x54\x69\x6d\x47\ \x45\x58\x65\x2b\x62\x6b\x4b\x20\x75\x6d\x4a\x63\x4f\x53\x64\x4e\ \x75\x6e\x32\x2b\x37\x31\x6f\x50\x2f\x4a\x6d\x52\x6e\x51\x66\x73\ \x48\x62\x72\x33\x67\x48\x74\x39\x64\x4a\x4f\x75\x44\x51\x50\x32\ \x69\x68\x7a\x78\x4e\x69\x53\x42\x66\x31\x67\x5a\x4f\x6d\x6f\x7a\ \x51\x62\x37\x41\x47\x78\x39\x30\x72\x4c\x72\x69\x7a\x6e\x65\x51\ \x49\x77\x55\x38\x20\x79\x5a\x6f\x4a\x54\x64\x78\x65\x67\x59\x38\ \x71\x65\x30\x4d\x54\x64\x34\x54\x41\x73\x2b\x69\x57\x30\x4d\x51\ \x64\x4a\x66\x52\x68\x70\x45\x54\x30\x49\x4c\x43\x43\x34\x59\x6e\ \x41\x78\x52\x47\x34\x57\x63\x37\x2f\x51\x67\x68\x63\x48\x49\x47\ \x4c\x4f\x7a\x54\x77\x4f\x66\x76\x4b\x44\x67\x31\x38\x44\x67\x49\ \x58\x20\x52\x2b\x44\x69\x43\x46\x77\x63\x67\x59\x73\x6a\x63\x48\ \x45\x45\x4c\x6f\x37\x41\x54\x58\x49\x2b\x70\x6a\x51\x6a\x63\x48\ \x6b\x45\x4c\x75\x37\x41\x77\x4f\x63\x38\x70\x6a\x51\x37\x4d\x76\ \x42\x5a\x43\x46\x77\x63\x67\x59\x73\x6a\x63\x48\x45\x45\x4c\x6f\ \x37\x41\x78\x52\x47\x34\x4f\x41\x49\x58\x52\x2b\x42\x4c\x20\x65\ \x5a\x39\x44\x6d\x78\x47\x34\x76\x4d\x4d\x43\x6e\x2f\x57\x59\x30\ \x75\x79\x34\x77\x4f\x63\x68\x63\x48\x45\x45\x4c\x6f\x37\x41\x78\ \x52\x47\x34\x4f\x41\x49\x58\x6c\x2f\x6f\x6d\x66\x6b\x7a\x50\x72\ \x56\x4c\x75\x68\x78\x78\x6d\x52\x77\x59\x32\x69\x2f\x6f\x7a\x63\ \x78\x46\x4b\x76\x49\x67\x78\x2b\x2f\x2f\x4d\x20\x48\x41\x41\x41\ \x41\x41\x41\x41\x41\x43\x62\x38\x41\x78\x4d\x4b\x7a\x76\x4c\x75\ \x31\x71\x62\x6b\x41\x41\x41\x41\x41\x45\x6c\x46\x54\x6b\x53\x75\ \x51\x6d\x43\x43\x20\x22\x0a\x20\x20\x20\x20\x20\x68\x65\x69\x67\ \x68\x74\x3d\x22\x32\x39\x2e\x37\x36\x32\x37\x31\x36\x22\x0a\x20\ \x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x31\x2e\x39\x36\ \x36\x31\x30\x33\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \ \x00\x00\x07\x6c\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x38\x37\x39\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x73\x74\x65\x70\x5f\x72\ \x65\x73\x70\x6f\x6e\x73\x65\x2e\x69\x63\x6f\x22\x3e\x0a\x20\x20\ \x3c\x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x33\x38\x38\x35\x22\ \x3e\x0a\x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\ \x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\ \x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\ \x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\ \x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\ \x74\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\ \x79\x70\x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\ \x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\ \x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\ \x61\x67\x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\ \x3c\x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\ \x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\ \x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\ \x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\ \x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x64\x65\x66\x73\x33\x38\x38\x33\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\ \x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\ \x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\ \x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\ \x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\ \x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\ \x31\x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\ \x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\ \x20\x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\ \x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\ \x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\ \x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\ \x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\ \x64\x74\x68\x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\ \x68\x65\x69\x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x33\ \x38\x38\x31\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\ \x69\x64\x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\ \x2e\x33\x37\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x63\x78\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x36\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\ \x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\ \x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x33\x38\x37\x39\ \x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\ \x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\ \x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\ \x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\ \x64\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\ \x61\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\ \x6f\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\ \x41\x41\x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\ \x72\x30\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\ \x67\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x41\x46\x70\x4a\x52\x45\ \x46\x55\x0a\x57\x49\x58\x74\x31\x7a\x45\x4b\x77\x44\x41\x4d\x42\ \x4d\x46\x56\x79\x43\x50\x39\x78\x44\x7a\x53\x34\x44\x52\x4a\x37\ \x55\x6f\x63\x49\x58\x75\x31\x51\x59\x4f\x4b\x4d\x79\x70\x67\x45\ \x55\x34\x53\x73\x49\x37\x67\x63\x41\x41\x45\x43\x42\x41\x67\x49\ \x41\x34\x34\x39\x79\x2b\x75\x76\x71\x71\x65\x34\x77\x73\x62\x0a\ \x65\x44\x4e\x48\x4e\x63\x7a\x33\x4d\x78\x49\x67\x51\x4d\x42\x54\ \x52\x4a\x31\x31\x75\x30\x6c\x38\x41\x2b\x42\x64\x49\x4f\x44\x76\ \x67\x43\x4a\x38\x6e\x74\x38\x44\x53\x67\x30\x35\x51\x36\x2b\x69\ \x72\x67\x41\x41\x41\x41\x42\x4a\x52\x55\x35\x45\x72\x6b\x4a\x67\ \x67\x67\x3d\x3d\x0a\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x69\x6d\x61\x67\x65\x33\x38\x38\x37\x22\x0a\x20\x20\x20\x20\x20\ \x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x30\x22\ \x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x0a\x85\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x33\x35\x36\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x67\x72\x6f\x75\x70\x5f\ \x64\x65\x6c\x61\x79\x2e\x69\x63\x6f\x22\x3e\x0a\x20\x20\x3c\x6d\ \x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\ \x22\x6d\x65\x74\x61\x64\x61\x74\x61\x33\x33\x36\x32\x22\x3e\x0a\ \x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\ \x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\ \x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\ \x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\ \x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\ \x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ \x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\ \x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\ \x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\ \x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\ \x63\x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\ \x6c\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\ \x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\ \x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ \x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x64\x65\x66\x73\x33\x33\x36\x30\x22\x20\x2f\x3e\x0a\ \x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\ \x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\ \x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\ \x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\ \x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\ \x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\ \x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\ \x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\ \x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\ \x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\ \x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\ \x68\x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\ \x69\x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x33\x33\x35\ \x38\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\ \x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\ \x37\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ \x65\x3a\x63\x78\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x36\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ \x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\ \x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\ \x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\ \x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x33\x33\x35\x36\x22\x20\ \x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\ \x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\ \x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\ \x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\ \x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\ \x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\ \x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\ \x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\ \x66\x41\x68\x6b\x69\x41\x41\x41\x41\x71\x5a\x4a\x52\x45\x46\x55\ \x0a\x57\x49\x58\x74\x6c\x6b\x74\x49\x56\x47\x45\x59\x68\x70\x2f\ \x6a\x39\x7a\x75\x57\x56\x37\x4b\x63\x30\x44\x52\x6f\x49\x39\x47\ \x71\x57\x75\x62\x43\x63\x69\x47\x47\x61\x46\x67\x49\x45\x53\x30\ \x73\x6b\x56\x61\x74\x4b\x6d\x67\x54\x64\x74\x75\x71\x42\x43\x47\ \x31\x4b\x4f\x30\x2b\x4a\x42\x57\x45\x53\x53\x34\x4b\x0a\x51\x6a\ \x45\x4b\x4e\x46\x33\x6b\x6e\x61\x6c\x77\x55\x32\x47\x53\x61\x4e\ \x62\x4d\x6e\x4a\x6e\x54\x34\x6b\x79\x4f\x34\x2b\x58\x4d\x4f\x54\ \x72\x6d\x78\x67\x63\x4f\x35\x37\x39\x38\x33\x2f\x6c\x66\x2f\x74\ \x74\x35\x77\x53\x34\x79\x65\x52\x42\x35\x4f\x62\x70\x6f\x6e\x78\ \x70\x35\x68\x44\x6f\x31\x5a\x76\x74\x62\x0a\x63\x31\x4e\x74\x52\ \x32\x71\x76\x6d\x38\x43\x33\x64\x54\x6d\x44\x57\x4a\x46\x67\x4f\ \x31\x49\x76\x7a\x34\x33\x33\x34\x4d\x34\x45\x49\x48\x70\x30\x50\ \x53\x69\x6f\x72\x6c\x72\x6b\x37\x6a\x76\x6f\x33\x77\x2b\x37\x74\ \x79\x41\x74\x6e\x55\x68\x64\x49\x2b\x78\x4c\x69\x34\x38\x38\x79\ \x53\x35\x44\x65\x58\x54\x55\x0a\x50\x5a\x33\x45\x6f\x69\x71\x55\ \x78\x35\x6a\x74\x55\x33\x32\x74\x79\x4e\x6b\x42\x32\x4f\x57\x4b\ \x37\x49\x47\x67\x68\x6f\x7a\x66\x51\x46\x30\x65\x67\x30\x4a\x62\ \x79\x32\x73\x39\x41\x31\x72\x44\x4d\x34\x79\x6d\x77\x2b\x68\x44\ \x4c\x6f\x77\x37\x53\x5a\x47\x4f\x44\x6a\x63\x4d\x6c\x4b\x4c\x31\ \x56\x55\x47\x2f\x0a\x66\x34\x35\x69\x67\x2b\x43\x62\x38\x35\x43\ \x66\x69\x79\x51\x57\x72\x31\x77\x41\x43\x4d\x48\x32\x35\x33\x41\ \x31\x68\x50\x36\x72\x4f\x64\x49\x36\x73\x77\x63\x41\x50\x66\x58\ \x54\x77\x70\x51\x6a\x50\x30\x48\x54\x30\x51\x4c\x56\x7a\x67\x51\ \x6f\x6a\x7a\x48\x37\x4c\x4d\x70\x4f\x58\x36\x54\x38\x63\x61\x50\ \x35\x0a\x44\x6f\x51\x57\x6a\x39\x56\x43\x59\x4b\x54\x59\x45\x52\ \x42\x5a\x4a\x2f\x32\x6f\x5a\x68\x33\x61\x6b\x77\x4c\x44\x51\x4b\ \x46\x43\x5a\x66\x51\x53\x42\x46\x79\x42\x7a\x66\x67\x5a\x6a\x34\ \x35\x37\x6e\x77\x78\x65\x46\x35\x6f\x38\x73\x53\x4d\x67\x31\x68\ \x49\x45\x6b\x5a\x49\x79\x30\x45\x44\x6b\x6e\x43\x6d\x35\x0a\x2b\ \x67\x75\x2b\x6d\x73\x38\x59\x47\x56\x35\x43\x32\x51\x30\x4c\x4d\ \x6c\x52\x6c\x44\x66\x7a\x34\x54\x55\x41\x39\x74\x43\x50\x41\x47\ \x73\x6b\x71\x4e\x30\x39\x42\x38\x77\x77\x4a\x42\x34\x34\x68\x31\ \x37\x7a\x49\x79\x56\x4b\x7a\x4d\x35\x53\x4a\x65\x74\x57\x47\x33\ \x4f\x78\x43\x32\x6f\x64\x51\x64\x56\x4f\x6f\x0a\x39\x6c\x62\x6b\ \x65\x6a\x65\x4a\x52\x58\x74\x58\x50\x72\x68\x74\x4d\x74\x4e\x51\ \x48\x39\x70\x51\x5a\x37\x37\x43\x63\x62\x66\x54\x62\x41\x63\x58\ \x30\x56\x4a\x4d\x54\x45\x48\x71\x4a\x45\x77\x48\x34\x50\x37\x33\ \x4e\x52\x43\x77\x4d\x75\x7a\x2f\x6a\x4b\x7a\x51\x6b\x30\x39\x44\ \x63\x4d\x4e\x79\x55\x73\x32\x6a\x0a\x74\x2b\x54\x5a\x58\x30\x56\ \x69\x48\x76\x74\x31\x35\x6d\x50\x6c\x69\x46\x62\x41\x6d\x6a\x73\ \x69\x42\x78\x68\x71\x4e\x54\x61\x72\x67\x33\x74\x41\x30\x32\x50\ \x48\x78\x46\x75\x41\x35\x45\x51\x37\x6f\x69\x67\x4d\x51\x62\x70\ \x75\x6f\x31\x71\x6d\x41\x56\x42\x4e\x30\x38\x69\x46\x57\x31\x44\ \x72\x36\x48\x4b\x4c\x0a\x34\x59\x6a\x71\x77\x34\x35\x6f\x64\x4a\ \x34\x6a\x41\x6b\x53\x37\x68\x4f\x62\x70\x51\x58\x2b\x63\x42\x59\ \x42\x2b\x49\x68\x57\x2b\x76\x55\x41\x36\x61\x35\x30\x49\x73\x43\ \x5a\x71\x7a\x59\x65\x54\x6f\x6a\x33\x68\x30\x77\x6d\x6f\x4e\x49\ \x32\x4a\x4e\x48\x6a\x44\x4d\x65\x6d\x6f\x4b\x78\x4e\x4f\x68\x6e\ \x41\x77\x0a\x58\x66\x6d\x2b\x36\x4c\x6f\x2f\x41\x31\x72\x2b\x41\ \x4b\x42\x74\x32\x6d\x61\x32\x50\x5a\x69\x47\x48\x52\x6d\x72\x4a\ \x4b\x41\x33\x62\x4c\x48\x2b\x75\x56\x30\x74\x41\x43\x55\x75\x41\ \x49\x79\x33\x50\x57\x62\x62\x52\x51\x55\x7a\x67\x58\x67\x4b\x43\ \x44\x73\x69\x51\x4c\x53\x49\x49\x77\x49\x77\x73\x67\x5a\x4a\x0a\ \x53\x4b\x2b\x41\x67\x75\x31\x51\x36\x49\x64\x44\x65\x53\x51\x55\ \x56\x47\x42\x30\x6a\x44\x67\x52\x59\x49\x32\x34\x4c\x52\x78\x52\ \x64\x77\x37\x53\x4f\x6f\x4c\x55\x44\x30\x4b\x6a\x32\x79\x77\x33\ \x6a\x6b\x4a\x78\x58\x76\x77\x45\x72\x50\x4d\x66\x2b\x41\x75\x6f\ \x6e\x4e\x58\x7a\x6c\x59\x54\x52\x77\x51\x41\x41\x0a\x41\x41\x42\ \x4a\x52\x55\x35\x45\x72\x6b\x4a\x67\x67\x67\x3d\x3d\x0a\x22\x0a\ \x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x33\x33\ \x36\x34\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\ \x76\x67\x3e\x0a\ \x00\x00\x09\xd2\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x35\x39\x36\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x6f\x76\x65\x72\x6c\x61\ \x79\x2e\x69\x63\x6f\x22\x3e\x0a\x20\x20\x3c\x6d\x65\x74\x61\x64\ \x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6d\x65\x74\ \x61\x64\x61\x74\x61\x33\x36\x30\x32\x22\x3e\x0a\x20\x20\x20\x20\ \x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\x20\x20\ \x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\x20\x20\ \x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\x72\x6d\ \x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\x6d\x6c\ \x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\x20\x20\ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x72\x65\x73\ \x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\ \x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\ \x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\x20\x2f\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x69\ \x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\ \x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\ \x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\x0a\x20\x20\ \x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x64\ \x65\x66\x73\x33\x36\x30\x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\ \x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\ \x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\x6c\x6f\x72\ \x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\x20\x20\x20\ \x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x36\x36\ \x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\ \x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\x20\x20\x20\ \x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\x61\x6e\x63\ \x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x72\x69\x64\ \x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\ \x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\x72\x61\x6e\ \x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\x63\x69\x74\ \x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\x77\x3d\x22\ \x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\ \x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\x68\x74\ \x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x33\x35\x39\x38\x22\x0a\x20\ \x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\x66\x61\ \x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\x35\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x78\ \x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x31\ \x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\ \x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\ \x72\x3d\x22\x73\x76\x67\x33\x35\x39\x36\x22\x20\x2f\x3e\x0a\x20\ \x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\x77\x69\x64\ \x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x68\x65\x69\ \x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x78\x6c\ \x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\x61\x3a\x69\ \x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\x36\x34\x2c\ \x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\ \x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\x41\x41\x41\x67\ \x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\x41\x41\x41\x41\ \x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\x41\x68\x6b\ \x69\x41\x41\x41\x41\x69\x5a\x4a\x52\x45\x46\x55\x0a\x57\x49\x58\ \x74\x6c\x6b\x39\x49\x46\x46\x45\x63\x78\x7a\x38\x7a\x4c\x69\x4b\ \x37\x42\x4c\x6d\x73\x62\x46\x34\x32\x4c\x44\x31\x49\x55\x46\x4a\ \x55\x56\x48\x53\x51\x79\x6f\x67\x79\x42\x4b\x75\x54\x53\x59\x64\ \x51\x45\x49\x52\x4d\x64\x6c\x65\x4a\x56\x70\x4d\x4f\x32\x79\x35\ \x49\x73\x4f\x55\x68\x35\x74\x44\x66\x0a\x69\x33\x51\x49\x4f\x37\ \x6b\x52\x52\x6f\x6b\x46\x49\x74\x52\x42\x59\x30\x57\x43\x50\x4c\ \x51\x75\x6d\x70\x37\x63\x51\x2b\x6d\x2b\x44\x6c\x4d\x62\x30\x37\ \x62\x72\x76\x70\x6d\x46\x76\x65\x79\x44\x59\x59\x59\x33\x37\x2f\ \x74\x2b\x6e\x2f\x6e\x78\x66\x62\x2f\x66\x4b\x49\x43\x67\x79\x4b\ \x4f\x59\x41\x45\x49\x74\x0a\x59\x6e\x41\x41\x53\x67\x41\x6c\x67\ \x42\x4a\x41\x43\x61\x44\x6f\x41\x44\x62\x39\x46\x6a\x4a\x54\x6a\ \x71\x76\x42\x74\x32\x51\x56\x51\x41\x47\x45\x53\x46\x54\x49\x69\ \x64\x79\x33\x68\x76\x55\x6e\x66\x36\x2f\x46\x2b\x47\x5a\x37\x67\ \x52\x49\x47\x63\x51\x56\x43\x4f\x79\x77\x43\x6d\x50\x4f\x41\x53\ \x41\x54\x69\x0a\x6f\x44\x77\x45\x34\x62\x55\x4b\x6f\x41\x41\x69\ \x46\x44\x68\x4a\x36\x37\x6c\x5a\x64\x75\x31\x63\x79\x31\x2f\x6f\ \x48\x71\x71\x47\x31\x43\x79\x6f\x65\x33\x51\x76\x42\x4f\x74\x42\ \x6e\x54\x4d\x46\x45\x42\x34\x34\x51\x66\x52\x4e\x4c\x64\x48\x52\ \x52\x33\x4c\x69\x74\x42\x65\x53\x4e\x38\x44\x78\x41\x63\x51\x39\ \x0a\x38\x47\x73\x53\x57\x2b\x67\x65\x75\x4e\x62\x78\x6e\x70\x56\ \x56\x4f\x34\x39\x48\x47\x36\x51\x41\x2f\x6e\x72\x42\x63\x52\x39\ \x45\x54\x44\x49\x34\x38\x4e\x73\x44\x4e\x6c\x73\x4b\x62\x66\x67\ \x46\x76\x71\x45\x6d\x56\x6c\x62\x74\x65\x59\x74\x31\x4c\x36\x68\ \x76\x67\x56\x59\x6f\x37\x35\x51\x4e\x6e\x67\x59\x41\x0a\x32\x4c\ \x38\x33\x7a\x75\x57\x4c\x6e\x2b\x69\x35\x65\x53\x5a\x76\x38\x62\ \x65\x6c\x62\x51\x44\x48\x49\x4b\x58\x41\x54\x37\x6d\x7a\x2f\x43\ \x38\x41\x77\x4b\x42\x33\x67\x71\x6c\x70\x44\x2b\x4d\x54\x74\x56\ \x73\x4b\x4e\x7a\x64\x56\x32\x72\x6f\x75\x63\x4c\x76\x2f\x64\x52\ \x55\x6f\x6d\x74\x6b\x54\x59\x51\x42\x77\x0a\x32\x48\x38\x77\x63\ \x75\x63\x6c\x58\x66\x35\x6d\x31\x70\x50\x6c\x4f\x59\x58\x42\x79\ \x48\x45\x41\x2b\x72\x72\x66\x59\x61\x55\x75\x5a\x4e\x53\x42\x30\ \x34\x30\x4c\x48\x44\x32\x34\x79\x47\x43\x34\x4d\x61\x74\x6f\x61\ \x74\x70\x44\x52\x44\x76\x4d\x30\x35\x48\x6e\x6c\x4a\x57\x6c\x4c\ \x4e\x63\x46\x49\x52\x49\x56\x0a\x68\x6d\x76\x35\x73\x31\x4f\x34\ \x71\x77\x4a\x69\x35\x6c\x56\x4e\x78\x72\x75\x31\x2b\x65\x32\x69\ \x78\x74\x4d\x76\x78\x70\x37\x73\x4d\x38\x7a\x72\x58\x78\x2f\x38\ \x4c\x70\x6d\x46\x2f\x35\x64\x69\x6c\x7a\x4e\x4a\x4b\x42\x44\x6c\ \x36\x76\x55\x57\x4e\x6a\x61\x4d\x53\x7a\x71\x39\x35\x7a\x6c\x37\ \x61\x70\x37\x6d\x0a\x70\x70\x68\x78\x4a\x35\x4e\x5a\x79\x46\x71\ \x4b\x32\x79\x39\x39\x78\x4f\x56\x4d\x63\x76\x66\x42\x6b\x66\x53\ \x63\x39\x75\x77\x41\x73\x51\x55\x58\x34\x59\x48\x78\x4c\x43\x70\ \x35\x4c\x2b\x54\x73\x68\x6c\x2b\x2b\x56\x72\x4c\x37\x55\x49\x39\ \x68\x62\x6d\x34\x79\x51\x6e\x33\x64\x63\x76\x59\x4e\x35\x54\x71\ \x6c\x0a\x4d\x4e\x57\x4f\x63\x34\x33\x4d\x48\x70\x45\x62\x6f\x4f\ \x42\x2f\x52\x4c\x4a\x65\x4b\x48\x67\x47\x34\x45\x38\x57\x69\x47\ \x2b\x39\x30\x71\x63\x44\x46\x44\x53\x36\x35\x50\x67\x46\x53\x65\ \x48\x64\x62\x59\x4e\x50\x58\x30\x55\x41\x41\x41\x41\x41\x53\x55\ \x56\x4f\x52\x4b\x35\x43\x59\x49\x49\x3d\x0a\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x33\x36\x30\x34\x22\ \x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\ \x0a\ \x00\x00\x09\x17\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x37\x39\x39\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x70\x68\x61\x73\x65\x5f\ \x72\x65\x73\x70\x6f\x6e\x73\x65\x2e\x69\x63\x6f\x22\x3e\x0a\x20\ \x20\x3c\x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\ \x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x33\x38\x30\x35\ \x22\x3e\x0a\x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\ \x0a\x20\x20\x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\ \x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\ \x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\ \x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\ \x61\x74\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\ \x74\x79\x70\x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\ \x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\ \x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\ \x6d\x61\x67\x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\ \x20\x3c\x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\ \x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\ \x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\ \x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\ \x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\x33\x38\x30\x33\x22\x20\ \x2f\x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\ \x61\x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\ \x67\x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\ \x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\ \x6f\x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\ \x20\x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\ \x22\x31\x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\ \x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\ \x20\x20\x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\ \x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\ \x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\ \x65\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\ \x68\x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\ \x69\x64\x74\x68\x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x68\x65\x69\x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\ \x20\x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\ \x33\x38\x30\x31\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\ \x72\x69\x64\x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\ \x37\x2e\x33\x37\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x63\x78\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\ \x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\ \x6f\x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\ \x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\ \x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x33\x37\x39\ \x39\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\ \x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\ \x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\ \x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\ \x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\ \x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\ \x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\ \x43\x41\x41\x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\ \x6e\x72\x30\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\ \x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x41\x5a\x56\x4a\x52\ \x45\x46\x55\x0a\x57\x49\x58\x74\x31\x37\x46\x72\x46\x45\x45\x55\ \x78\x2f\x48\x50\x6e\x49\x64\x4b\x62\x4d\x54\x61\x4a\x70\x42\x57\ \x4f\x31\x45\x51\x77\x63\x72\x69\x69\x43\x6b\x46\x4c\x57\x30\x30\ \x49\x46\x6f\x63\x75\x78\x64\x74\x51\x6b\x44\x69\x33\x52\x34\x57\ \x69\x68\x42\x74\x4c\x41\x32\x6d\x31\x48\x42\x46\x47\x67\x73\x52\ \x0a\x42\x43\x75\x31\x46\x66\x49\x66\x42\x42\x75\x44\x53\x72\x79\ \x78\x57\x4d\x35\x4b\x6b\x31\x6b\x76\x63\x49\x4c\x37\x71\x6d\x48\ \x67\x39\x2b\x62\x4c\x6d\x2f\x6d\x39\x6d\x51\x6d\x49\x4a\x68\x79\ \x54\x42\x49\x69\x4e\x43\x53\x34\x4f\x61\x6f\x41\x61\x6f\x41\x62\ \x34\x56\x77\x42\x36\x47\x66\x33\x54\x31\x61\x52\x46\x0a\x70\x44\ \x65\x37\x54\x77\x44\x68\x50\x66\x45\x6c\x33\x52\x4d\x56\x39\x59\ \x38\x70\x35\x76\x63\x42\x49\x4e\x38\x67\x33\x4b\x41\x78\x59\x48\ \x6d\x6d\x67\x76\x77\x63\x38\x53\x61\x39\x48\x6a\x47\x4d\x41\x51\ \x44\x5a\x47\x75\x37\x53\x48\x4e\x41\x39\x6e\x69\x62\x50\x4e\x6d\ \x6d\x65\x78\x52\x6e\x36\x71\x7a\x77\x34\x0a\x4e\x41\x59\x41\x35\ \x45\x2f\x77\x74\x4b\x7a\x45\x2f\x57\x4e\x70\x4b\x64\x70\x62\x48\ \x4c\x35\x51\x6a\x72\x39\x75\x70\x4f\x74\x2b\x43\x77\x42\x35\x46\ \x77\x4e\x32\x42\x69\x78\x4f\x70\x61\x57\x35\x39\x59\x33\x73\x4d\ \x74\x36\x79\x38\x34\x62\x2b\x39\x42\x67\x41\x6b\x4e\x33\x47\x42\ \x34\x36\x38\x59\x50\x46\x67\x0a\x57\x71\x6f\x51\x36\x58\x51\x49\ \x44\x78\x6d\x2b\x70\x6e\x39\x71\x44\x49\x41\x51\x6d\x5a\x34\x6e\ \x66\x6d\x62\x71\x47\x57\x73\x48\x30\x69\x41\x67\x58\x38\x46\x31\ \x68\x75\x73\x70\x4e\x74\x32\x6c\x45\x56\x33\x36\x77\x66\x59\x56\ \x77\x6c\x45\x32\x56\x36\x71\x64\x38\x73\x34\x36\x6a\x56\x6b\x4a\ \x4e\x74\x32\x6a\x0a\x45\x79\x35\x39\x35\x38\x73\x63\x54\x74\x4b\ \x2f\x6c\x77\x34\x41\x32\x62\x73\x55\x6d\x79\x61\x30\x34\x71\x56\ \x74\x6d\x69\x32\x30\x4b\x42\x59\x71\x51\x75\x78\x70\x30\x38\x53\ \x37\x6f\x4c\x33\x46\x73\x49\x57\x72\x46\x4e\x65\x71\x51\x65\x78\ \x75\x30\x36\x42\x38\x6c\x43\x62\x75\x37\x2f\x49\x4d\x7a\x56\x65\ \x45\x0a\x4e\x76\x45\x35\x65\x59\x56\x7a\x45\x51\x4e\x46\x46\x33\ \x4d\x30\x57\x6d\x56\x31\x4b\x6a\x39\x4b\x37\x33\x77\x71\x4b\x78\ \x45\x66\x56\x64\x50\x78\x4a\x35\x76\x2b\x78\x58\x57\x38\x38\x4a\ \x46\x77\x73\x62\x70\x75\x46\x4c\x39\x73\x65\x6e\x34\x30\x55\x2f\ \x38\x4c\x61\x6f\x44\x2f\x47\x32\x44\x55\x69\x43\x59\x57\x0a\x50\ \x77\x48\x43\x37\x48\x54\x6e\x46\x42\x69\x6f\x6f\x67\x41\x41\x41\ \x41\x42\x4a\x52\x55\x35\x45\x72\x6b\x4a\x67\x67\x67\x3d\x3d\x0a\ \x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\ \x33\x38\x30\x37\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\ \x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x3c\ \x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x0b\x58\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x73\x74\x65\x70\x2e\x73\ \x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\x74\x61\x64\x61\x74\x61\ \x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ \x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\x20\x20\x20\x3c\x72\x64\ \x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x63\x63\ \x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\ \x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\ \x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\ \x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x20\x20\ \x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\x20\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\ \x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\ \x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\ \x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\x20\x2f\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x69\x74\x6c\x65\ \x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\ \x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\ \x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\ \x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\ \x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\ \x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x0a\x20\ \x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\ \x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\ \x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x36\x36\x36\x36\x36\ \x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x6f\x70\ \x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\x20\x20\x20\x20\x20\x6f\ \x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\ \x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x72\x69\x64\x74\x6f\x6c\ \x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\ \x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\ \x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\ \x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ \x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x33\x36\x34\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\x68\x74\x3d\x22\x37\ \x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\ \x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\x22\x0a\x20\x20\x20\x20\ \x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\x66\x61\x6c\x73\x65\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\x35\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x78\x3d\x22\x32\ \x36\x2e\x32\x31\x34\x39\x33\x36\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x39\x2e\x37\ \x32\x38\x38\x31\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\ \x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\ \x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\ \x67\x34\x35\x35\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\x67\x6c\x6f\x62\x61\x6c\ \x3d\x22\x66\x61\x6c\x73\x65\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\ \x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\ \x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\ \x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\ \x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\ \x45\x55\x67\x41\x41\x41\x43\x41\x41\x41\x41\x41\x67\x43\x41\x59\ \x41\x41\x41\x42\x7a\x65\x6e\x72\x30\x41\x41\x41\x41\x42\x48\x4e\ \x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\ \x41\x41\x44\x56\x4a\x52\x45\x46\x55\x0a\x57\x49\x58\x74\x31\x7a\ \x45\x42\x41\x44\x41\x4d\x77\x7a\x42\x33\x2f\x44\x6c\x33\x4d\x50\ \x6f\x6f\x42\x4b\x77\x33\x55\x32\x33\x48\x75\x77\x54\x73\x4f\x34\ \x78\x58\x42\x51\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x41\x77\x48\x64\x2f\x7a\x44\x78\x72\x74\x42\x44\ \x6b\x45\x71\x4e\x62\x67\x0a\x41\x41\x41\x41\x41\x45\x6c\x46\x54\ \x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x69\x6d\x61\x67\x65\x34\x35\x36\x35\x22\x0a\x20\x20\ \x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\ \x22\x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\ \x20\x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\ \x72\x65\x73\x65\x72\x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\ \x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x34\ \x30\x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\ \x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\ \x74\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\ \x69\x67\x68\x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\ \x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\ \x64\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\ \x6c\x6c\x3a\x23\x30\x30\x30\x30\x30\x30\x3b\x66\x69\x6c\x6c\x2d\ \x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\ \x3a\x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\ \x79\x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\ \x31\x31\x2e\x36\x36\x31\x30\x31\x37\x22\x0a\x20\x20\x20\x20\x20\ \x79\x3d\x22\x39\x2e\x33\x35\x35\x39\x33\x32\x32\x22\x0a\x20\x20\ \x20\x20\x20\x69\x64\x3d\x22\x74\x65\x78\x74\x35\x34\x31\x38\x22\ \x0a\x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\ \x69\x6e\x65\x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\ \x22\x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\ \x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\ \x69\x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x74\x73\x70\x61\x6e\x35\x34\x32\x30\x22\x0a\x20\x20\x20\x20\x20\ \x20\x20\x78\x3d\x22\x31\x31\x2e\x36\x36\x31\x30\x31\x37\x22\x0a\ \x20\x20\x20\x20\x20\x20\x20\x79\x3d\x22\x39\x2e\x33\x35\x35\x39\ \x33\x32\x32\x22\x20\x2f\x3e\x3c\x2f\x74\x65\x78\x74\x3e\x0a\x20\ \x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\x65\x63\x74\x6f\x72\x2d\x63\ \x75\x72\x76\x61\x74\x75\x72\x65\x3d\x22\x30\x22\x0a\x20\x20\x20\ \x20\x20\x64\x3d\x22\x4d\x20\x32\x35\x2e\x31\x39\x39\x39\x37\x33\ \x2c\x36\x2e\x32\x32\x37\x36\x34\x34\x34\x20\x43\x20\x32\x33\x2e\ \x39\x30\x32\x32\x30\x39\x2c\x36\x2e\x33\x36\x30\x34\x31\x30\x39\ \x20\x32\x30\x2e\x37\x35\x30\x37\x38\x36\x2c\x38\x2e\x34\x39\x31\ \x34\x35\x35\x37\x20\x31\x36\x2e\x32\x38\x30\x30\x36\x32\x2c\x31\ \x32\x2e\x35\x31\x31\x39\x32\x32\x20\x35\x2e\x33\x38\x32\x31\x39\ \x33\x38\x2c\x32\x2e\x37\x36\x36\x38\x39\x32\x36\x20\x32\x2e\x37\ \x35\x36\x39\x34\x35\x39\x2c\x35\x2e\x33\x35\x34\x33\x34\x36\x36\ \x20\x31\x32\x2e\x38\x31\x32\x32\x38\x2c\x31\x35\x2e\x38\x31\x35\ \x34\x38\x39\x20\x63\x20\x2d\x39\x2e\x39\x36\x39\x37\x38\x33\x38\ \x2c\x31\x30\x2e\x38\x39\x32\x37\x39\x33\x20\x2d\x37\x2e\x32\x35\ \x34\x30\x39\x31\x39\x2c\x31\x33\x2e\x34\x34\x33\x35\x38\x38\x20\ \x33\x2e\x34\x35\x36\x35\x34\x2c\x33\x2e\x33\x31\x35\x38\x37\x36\ \x20\x31\x30\x2e\x39\x34\x38\x30\x33\x39\x2c\x39\x2e\x38\x34\x32\ \x37\x33\x32\x20\x31\x33\x2e\x31\x37\x37\x39\x32\x36\x2c\x37\x2e\ \x34\x35\x36\x35\x31\x35\x20\x33\x2e\x32\x33\x30\x34\x33\x2c\x2d\ \x33\x2e\x33\x31\x37\x38\x37\x36\x20\x35\x2e\x37\x34\x37\x32\x31\ \x31\x2c\x2d\x36\x2e\x32\x36\x34\x38\x31\x35\x20\x37\x2e\x35\x31\ \x34\x32\x33\x2c\x2d\x39\x2e\x37\x37\x31\x33\x37\x33\x31\x20\x35\ \x2e\x37\x30\x30\x37\x32\x33\x2c\x2d\x39\x2e\x35\x38\x35\x38\x34\ \x34\x36\x20\x7a\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x70\ \x61\x74\x68\x31\x31\x33\x30\x22\x0a\x20\x20\x20\x20\x20\x73\x6f\ \x64\x69\x70\x6f\x64\x69\x3a\x73\x74\x72\x6f\x6b\x65\x2d\x63\x6d\ \x79\x6b\x3d\x22\x28\x30\x20\x30\x20\x30\x20\x30\x2e\x38\x29\x22\ \x0a\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\ \x74\x2d\x73\x69\x7a\x65\x3a\x31\x32\x70\x78\x3b\x66\x69\x6c\x6c\ \x3a\x23\x30\x30\x30\x30\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x72\x75\ \x6c\x65\x3a\x65\x76\x65\x6e\x6f\x64\x64\x3b\x73\x74\x72\x6f\x6b\ \x65\x3a\x23\x33\x33\x33\x33\x33\x33\x3b\x73\x74\x72\x6f\x6b\x65\ \x2d\x77\x69\x64\x74\x68\x3a\x32\x2e\x35\x30\x30\x30\x30\x30\x30\ \x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x3b\x73\x74\x72\x6f\x6b\ \x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3a\x72\x6f\x75\x6e\x64\x3b\ \x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3a\ \x72\x6f\x75\x6e\x64\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x64\x61\x73\ \x68\x61\x72\x72\x61\x79\x3a\x6e\x6f\x6e\x65\x22\x20\x2f\x3e\x0a\ \x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x0b\x58\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x73\x74\x65\x70\x2e\x73\ \x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\x74\x61\x64\x61\x74\x61\ \x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ \x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\x20\x20\x20\x3c\x72\x64\ \x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x63\x63\ \x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\ \x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\ \x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\ \x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x20\x20\ \x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\x20\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\ \x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\ \x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\ \x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\x20\x2f\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x69\x74\x6c\x65\ \x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\ \x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\ \x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\ \x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\ \x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\ \x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x0a\x20\ \x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\ \x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\ \x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x36\x36\x36\x36\x36\ \x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x6f\x70\ \x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\x20\x20\x20\x20\x20\x6f\ \x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\ \x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x72\x69\x64\x74\x6f\x6c\ \x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\ \x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\ \x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\ \x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ \x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x33\x36\x34\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\x68\x74\x3d\x22\x37\ \x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\ \x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\x22\x0a\x20\x20\x20\x20\ \x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\x66\x61\x6c\x73\x65\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\x35\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x78\x3d\x22\x32\ \x36\x2e\x32\x31\x34\x39\x33\x36\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x39\x2e\x37\ \x32\x38\x38\x31\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\ \x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\ \x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\ \x67\x34\x35\x35\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\x67\x6c\x6f\x62\x61\x6c\ \x3d\x22\x66\x61\x6c\x73\x65\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\ \x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\ \x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\ \x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\ \x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\ \x45\x55\x67\x41\x41\x41\x43\x41\x41\x41\x41\x41\x67\x43\x41\x59\ \x41\x41\x41\x42\x7a\x65\x6e\x72\x30\x41\x41\x41\x41\x42\x48\x4e\ \x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\ \x41\x41\x44\x56\x4a\x52\x45\x46\x55\x0a\x57\x49\x58\x74\x31\x7a\ \x45\x42\x41\x44\x41\x4d\x77\x7a\x42\x33\x2f\x44\x6c\x33\x4d\x50\ \x6f\x6f\x42\x4b\x77\x33\x55\x32\x33\x48\x75\x77\x54\x73\x4f\x34\ \x78\x58\x42\x51\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x41\x77\x48\x64\x2f\x7a\x44\x78\x72\x74\x42\x44\ \x6b\x45\x71\x4e\x62\x67\x0a\x41\x41\x41\x41\x41\x45\x6c\x46\x54\ \x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x69\x6d\x61\x67\x65\x34\x35\x36\x35\x22\x0a\x20\x20\ \x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\ \x22\x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\ \x20\x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\ \x72\x65\x73\x65\x72\x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\ \x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x34\ \x30\x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\ \x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\ \x74\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\ \x69\x67\x68\x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\ \x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\ \x64\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\ \x6c\x6c\x3a\x23\x30\x30\x30\x30\x30\x30\x3b\x66\x69\x6c\x6c\x2d\ \x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\ \x3a\x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\ \x79\x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\ \x31\x31\x2e\x36\x36\x31\x30\x31\x37\x22\x0a\x20\x20\x20\x20\x20\ \x79\x3d\x22\x39\x2e\x33\x35\x35\x39\x33\x32\x32\x22\x0a\x20\x20\ \x20\x20\x20\x69\x64\x3d\x22\x74\x65\x78\x74\x35\x34\x31\x38\x22\ \x0a\x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\ \x69\x6e\x65\x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\ \x22\x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\ \x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\ \x69\x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x74\x73\x70\x61\x6e\x35\x34\x32\x30\x22\x0a\x20\x20\x20\x20\x20\ \x20\x20\x78\x3d\x22\x31\x31\x2e\x36\x36\x31\x30\x31\x37\x22\x0a\ \x20\x20\x20\x20\x20\x20\x20\x79\x3d\x22\x39\x2e\x33\x35\x35\x39\ \x33\x32\x32\x22\x20\x2f\x3e\x3c\x2f\x74\x65\x78\x74\x3e\x0a\x20\ \x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\x65\x63\x74\x6f\x72\x2d\x63\ \x75\x72\x76\x61\x74\x75\x72\x65\x3d\x22\x30\x22\x0a\x20\x20\x20\ \x20\x20\x64\x3d\x22\x4d\x20\x32\x35\x2e\x31\x39\x39\x39\x37\x33\ \x2c\x36\x2e\x32\x32\x37\x36\x34\x34\x34\x20\x43\x20\x32\x33\x2e\ \x39\x30\x32\x32\x30\x39\x2c\x36\x2e\x33\x36\x30\x34\x31\x30\x39\ \x20\x32\x30\x2e\x37\x35\x30\x37\x38\x36\x2c\x38\x2e\x34\x39\x31\ \x34\x35\x35\x37\x20\x31\x36\x2e\x32\x38\x30\x30\x36\x32\x2c\x31\ \x32\x2e\x35\x31\x31\x39\x32\x32\x20\x35\x2e\x33\x38\x32\x31\x39\ \x33\x38\x2c\x32\x2e\x37\x36\x36\x38\x39\x32\x36\x20\x32\x2e\x37\ \x35\x36\x39\x34\x35\x39\x2c\x35\x2e\x33\x35\x34\x33\x34\x36\x36\ \x20\x31\x32\x2e\x38\x31\x32\x32\x38\x2c\x31\x35\x2e\x38\x31\x35\ \x34\x38\x39\x20\x63\x20\x2d\x39\x2e\x39\x36\x39\x37\x38\x33\x38\ \x2c\x31\x30\x2e\x38\x39\x32\x37\x39\x33\x20\x2d\x37\x2e\x32\x35\ \x34\x30\x39\x31\x39\x2c\x31\x33\x2e\x34\x34\x33\x35\x38\x38\x20\ \x33\x2e\x34\x35\x36\x35\x34\x2c\x33\x2e\x33\x31\x35\x38\x37\x36\ \x20\x31\x30\x2e\x39\x34\x38\x30\x33\x39\x2c\x39\x2e\x38\x34\x32\ \x37\x33\x32\x20\x31\x33\x2e\x31\x37\x37\x39\x32\x36\x2c\x37\x2e\ \x34\x35\x36\x35\x31\x35\x20\x33\x2e\x32\x33\x30\x34\x33\x2c\x2d\ \x33\x2e\x33\x31\x37\x38\x37\x36\x20\x35\x2e\x37\x34\x37\x32\x31\ \x31\x2c\x2d\x36\x2e\x32\x36\x34\x38\x31\x35\x20\x37\x2e\x35\x31\ \x34\x32\x33\x2c\x2d\x39\x2e\x37\x37\x31\x33\x37\x33\x31\x20\x35\ \x2e\x37\x30\x30\x37\x32\x33\x2c\x2d\x39\x2e\x35\x38\x35\x38\x34\ \x34\x36\x20\x7a\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x70\ \x61\x74\x68\x31\x31\x33\x30\x22\x0a\x20\x20\x20\x20\x20\x73\x6f\ \x64\x69\x70\x6f\x64\x69\x3a\x73\x74\x72\x6f\x6b\x65\x2d\x63\x6d\ \x79\x6b\x3d\x22\x28\x30\x20\x30\x20\x30\x20\x30\x2e\x38\x29\x22\ \x0a\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\ \x74\x2d\x73\x69\x7a\x65\x3a\x31\x32\x70\x78\x3b\x66\x69\x6c\x6c\ \x3a\x23\x30\x30\x30\x30\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x72\x75\ \x6c\x65\x3a\x65\x76\x65\x6e\x6f\x64\x64\x3b\x73\x74\x72\x6f\x6b\ \x65\x3a\x23\x33\x33\x33\x33\x33\x33\x3b\x73\x74\x72\x6f\x6b\x65\ \x2d\x77\x69\x64\x74\x68\x3a\x32\x2e\x35\x30\x30\x30\x30\x30\x30\ \x30\x30\x30\x30\x30\x30\x30\x30\x30\x30\x3b\x73\x74\x72\x6f\x6b\ \x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3a\x72\x6f\x75\x6e\x64\x3b\ \x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3a\ \x72\x6f\x75\x6e\x64\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x64\x61\x73\ \x68\x61\x72\x72\x61\x79\x3a\x6e\x6f\x6e\x65\x22\x20\x2f\x3e\x0a\ \x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x07\xf1\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x33\x35\x31\x36\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x6d\x61\x67\x5f\x72\x65\ \x73\x70\x6f\x6e\x73\x65\x2e\x69\x63\x6f\x22\x3e\x0a\x20\x20\x3c\ \x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x33\x35\x32\x32\x22\x3e\ \x0a\x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\ \x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\ \x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\ \x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\ \x70\x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\ \x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\ \x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\ \x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\ \x67\x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\ \x64\x63\x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\ \x74\x6c\x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\ \x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\ \x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\ \x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\ \x69\x64\x3d\x22\x64\x65\x66\x73\x33\x35\x32\x30\x22\x20\x2f\x3e\ \x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\ \x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\ \x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\ \x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\ \x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\ \x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\ \x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\ \x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\ \x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\ \x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\ \x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\ \x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\ \x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\ \x74\x68\x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\ \x65\x69\x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x33\x35\ \x31\x38\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\ \x64\x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\ \x33\x37\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x63\x78\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x31\x36\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\ \x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\ \x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\ \x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x33\x35\x31\x36\x22\ \x20\x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\ \x20\x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\ \x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\ \x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ \x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ \x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ \x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\ \x41\x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\ \x30\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ \x49\x66\x41\x68\x6b\x69\x41\x41\x41\x41\x4c\x35\x4a\x52\x45\x46\ \x55\x0a\x57\x49\x58\x74\x6c\x6a\x45\x4f\x77\x6a\x41\x4d\x52\x56\ \x38\x51\x41\x7a\x63\x6f\x76\x52\x31\x33\x51\x4a\x51\x4e\x43\x63\ \x59\x69\x63\x51\x5a\x75\x56\x33\x6f\x4b\x4d\x2b\x51\x41\x56\x65\ \x78\x66\x65\x59\x6d\x58\x5a\x45\x6a\x69\x70\x36\x66\x45\x54\x67\ \x47\x4d\x35\x4d\x67\x45\x73\x45\x4e\x69\x63\x67\x41\x36\x0a\x51\ \x41\x66\x6f\x41\x42\x30\x67\x48\x65\x42\x59\x68\x39\x6c\x54\x6a\ \x6b\x65\x59\x66\x6c\x47\x41\x41\x70\x69\x74\x70\x37\x5a\x4e\x77\ \x2f\x4e\x54\x5a\x2f\x64\x72\x4d\x4c\x2b\x33\x46\x35\x51\x33\x63\ \x49\x48\x35\x48\x41\x54\x77\x33\x51\x46\x62\x48\x77\x76\x77\x42\ \x62\x75\x6c\x41\x4e\x54\x51\x57\x48\x41\x44\x0a\x71\x43\x77\x45\ \x6e\x32\x48\x63\x51\x67\x68\x41\x59\x55\x46\x51\x69\x47\x49\x57\ \x77\x67\x42\x52\x43\x36\x4a\x53\x37\x4c\x63\x67\x41\x59\x68\x59\ \x45\x44\x59\x6a\x6e\x77\x55\x5a\x67\x4e\x65\x43\x75\x42\x32\x33\ \x57\x35\x41\x43\x65\x43\x7a\x73\x38\x43\x46\x70\x73\x79\x41\x48\ \x61\x4c\x58\x67\x2b\x70\x42\x73\x0a\x48\x6a\x71\x38\x52\x6d\x44\ \x5a\x58\x6a\x6c\x56\x41\x47\x6e\x32\x78\x76\x67\x44\x79\x74\x74\ \x4a\x72\x38\x33\x33\x55\x79\x59\x41\x41\x41\x41\x41\x53\x55\x56\ \x4f\x52\x4b\x35\x43\x59\x49\x49\x3d\x0a\x22\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x33\x35\x32\x34\x22\x0a\ \x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\ \x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \ \x00\x00\x08\xfd\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x61\x64\x64\x5f\x70\x6f\ \x6c\x65\x5f\x31\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\ \x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x6d\x65\x74\x61\x64\x61\x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\ \x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\ \x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\ \x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\ \x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\ \x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\ \x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\ \x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\ \x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\ \x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\ \x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\ \x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x64\x65\x66\x73\x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\ \x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\ \x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\ \x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\ \x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\ \x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\ \x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\ \x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\ \x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\ \x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\ \x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\ \x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\ \x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\ \x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\ \x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\ \x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\ \x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\ \x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x63\x78\x3d\x22\x32\x34\x2e\x30\x39\x35\x33\x33\x38\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\ \x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\ \x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\ \x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\ \x34\x35\x35\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\x67\x6c\x6f\x62\x61\x6c\x3d\ \x22\x66\x61\x6c\x73\x65\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\x6d\ \x61\x67\x65\x0a\x20\x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\ \x33\x32\x22\x0a\x20\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\ \x68\x72\x65\x66\x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\ \x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\ \x52\x77\x30\x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\x45\ \x55\x67\x41\x41\x41\x43\x41\x41\x41\x41\x41\x67\x43\x41\x59\x41\ \x41\x41\x42\x7a\x65\x6e\x72\x30\x41\x41\x41\x41\x42\x48\x4e\x43\ \x53\x56\x51\x49\x43\x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\x41\ \x41\x44\x56\x4a\x52\x45\x46\x55\x0a\x57\x49\x58\x74\x31\x7a\x45\ \x42\x41\x44\x41\x4d\x77\x7a\x42\x33\x2f\x44\x6c\x33\x4d\x50\x6f\ \x6f\x42\x4b\x77\x33\x55\x32\x33\x48\x75\x77\x54\x73\x4f\x34\x78\ \x58\x42\x51\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x77\x48\x64\x2f\x7a\x44\x78\x72\x74\x42\x44\x6b\ \x45\x71\x4e\x62\x67\x0a\x41\x41\x41\x41\x41\x45\x6c\x46\x54\x6b\ \x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x69\x6d\x61\x67\x65\x34\x35\x36\x35\x22\x0a\x20\x20\x20\ \x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\ \x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\x20\ \x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\ \x65\x73\x65\x72\x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\x79\ \x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x34\x30\ \x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\ \x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\ \x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\ \x67\x68\x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\x2d\ \x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\x64\ \x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\x6c\ \x6c\x3a\x23\x30\x30\x30\x30\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x6f\ \x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\x3a\ \x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\ \x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x33\ \x2e\x39\x36\x36\x31\x30\x31\x39\x22\x0a\x20\x20\x20\x20\x20\x79\ \x3d\x22\x32\x37\x2e\x30\x35\x30\x38\x34\x36\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x74\x65\x78\x74\x34\x37\x36\x38\x22\x0a\ \x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\x69\ \x6e\x65\x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\x22\ \x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\x73\ \x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\x69\ \x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\ \x73\x70\x61\x6e\x34\x37\x37\x30\x22\x0a\x20\x20\x20\x20\x20\x20\ \x20\x78\x3d\x22\x33\x2e\x39\x36\x36\x31\x30\x31\x39\x22\x0a\x20\ \x20\x20\x20\x20\x20\x20\x79\x3d\x22\x32\x37\x2e\x30\x35\x30\x38\ \x34\x36\x22\x3e\x6f\x3c\x2f\x74\x73\x70\x61\x6e\x3e\x3c\x2f\x74\ \x65\x78\x74\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x08\xfd\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x61\x64\x64\x5f\x70\x6f\ \x6c\x65\x5f\x31\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\ \x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x6d\x65\x74\x61\x64\x61\x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\ \x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\ \x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\ \x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\ \x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\ \x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\ \x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\ \x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\ \x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\ \x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\ \x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\ \x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x64\x65\x66\x73\x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\ \x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\ \x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\ \x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\ \x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\ \x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\ \x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\ \x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\ \x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\ \x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\ \x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\ \x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\ \x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\ \x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\ \x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\ \x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\ \x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\ \x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x63\x78\x3d\x22\x32\x34\x2e\x30\x39\x35\x33\x33\x38\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\ \x3d\x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x30\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\ \x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x31\x36\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\ \x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\ \x34\x35\x35\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\x67\x6c\x6f\x62\x61\x6c\x3d\ \x22\x66\x61\x6c\x73\x65\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x69\x6d\ \x61\x67\x65\x0a\x20\x20\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\ \x33\x32\x22\x0a\x20\x20\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\x78\x6c\x69\x6e\x6b\x3a\ \x68\x72\x65\x66\x3d\x22\x64\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\ \x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\ \x52\x77\x30\x4b\x47\x67\x6f\x41\x41\x41\x41\x4e\x53\x55\x68\x45\ \x55\x67\x41\x41\x41\x43\x41\x41\x41\x41\x41\x67\x43\x41\x59\x41\ \x41\x41\x42\x7a\x65\x6e\x72\x30\x41\x41\x41\x41\x42\x48\x4e\x43\ \x53\x56\x51\x49\x43\x41\x67\x49\x66\x41\x68\x6b\x69\x41\x41\x41\ \x41\x44\x56\x4a\x52\x45\x46\x55\x0a\x57\x49\x58\x74\x31\x7a\x45\ \x42\x41\x44\x41\x4d\x77\x7a\x42\x33\x2f\x44\x6c\x33\x4d\x50\x6f\ \x6f\x42\x4b\x77\x33\x55\x32\x33\x48\x75\x77\x54\x73\x4f\x34\x78\ \x58\x42\x51\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x77\x48\x64\x2f\x7a\x44\x78\x72\x74\x42\x44\x6b\ \x45\x71\x4e\x62\x67\x0a\x41\x41\x41\x41\x41\x45\x6c\x46\x54\x6b\ \x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x69\x6d\x61\x67\x65\x34\x35\x36\x35\x22\x0a\x20\x20\x20\ \x20\x20\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\ \x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x74\x65\x78\x74\x0a\x20\x20\ \x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\x65\x3d\x22\x70\x72\ \x65\x73\x65\x72\x76\x65\x22\x0a\x20\x20\x20\x20\x20\x73\x74\x79\ \x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x34\x30\ \x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\ \x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\ \x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\ \x67\x68\x74\x3a\x31\x32\x35\x25\x3b\x6c\x65\x74\x74\x65\x72\x2d\ \x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\x72\x64\ \x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\x69\x6c\ \x6c\x3a\x23\x30\x30\x30\x30\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x6f\ \x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\x65\x3a\ \x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\ \x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x33\ \x2e\x39\x36\x36\x31\x30\x31\x39\x22\x0a\x20\x20\x20\x20\x20\x79\ \x3d\x22\x32\x37\x2e\x30\x35\x30\x38\x34\x36\x22\x0a\x20\x20\x20\ \x20\x20\x69\x64\x3d\x22\x74\x65\x78\x74\x34\x37\x36\x38\x22\x0a\ \x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6c\x69\ \x6e\x65\x73\x70\x61\x63\x69\x6e\x67\x3d\x22\x31\x32\x35\x25\x22\ \x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\x20\x20\x20\x20\x20\x73\ \x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\x3d\x22\x6c\x69\ \x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\ \x73\x70\x61\x6e\x34\x37\x37\x30\x22\x0a\x20\x20\x20\x20\x20\x20\ \x20\x78\x3d\x22\x33\x2e\x39\x36\x36\x31\x30\x31\x39\x22\x0a\x20\ \x20\x20\x20\x20\x20\x20\x79\x3d\x22\x32\x37\x2e\x30\x35\x30\x38\ \x34\x36\x22\x3e\x6f\x3c\x2f\x74\x73\x70\x61\x6e\x3e\x3c\x2f\x74\ \x65\x78\x74\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x0b\x22\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x63\x6f\x6e\x6a\x75\x67\ \x61\x74\x65\x31\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\ \x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x6d\x65\x74\x61\x64\x61\x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\ \x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\ \x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\ \x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\ \x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\ \x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\ \x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\ \x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\ \x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\ \x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\ \x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\ \x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x64\x65\x66\x73\x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\ \x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\ \x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\ \x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\ \x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\ \x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\ \x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\ \x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\ \x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\ \x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\ \x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\ \x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\ \x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\ \x3d\x22\x31\x33\x36\x34\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\ \x67\x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\ \x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\ \x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\ \x35\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x63\x78\x3d\x22\x32\x36\x2e\x32\x31\x34\x39\x33\x36\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\ \x3d\x22\x31\x37\x2e\x32\x39\x30\x36\x37\x35\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x78\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\ \x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ \x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\ \x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\ \x65\x72\x3d\x22\x73\x76\x67\x34\x35\x35\x37\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x73\x6e\x61\x70\x2d\ \x67\x6c\x6f\x62\x61\x6c\x3d\x22\x66\x61\x6c\x73\x65\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\x20\ \x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\x20\ \x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\x74\ \x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\x65\ \x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\x41\ \x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\x41\ \x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\x41\ \x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\x66\ \x41\x68\x6b\x69\x41\x41\x41\x41\x44\x56\x4a\x52\x45\x46\x55\x0a\ \x57\x49\x58\x74\x31\x7a\x45\x42\x41\x44\x41\x4d\x77\x7a\x42\x33\ \x2f\x44\x6c\x33\x4d\x50\x6f\x6f\x42\x4b\x77\x33\x55\x32\x33\x48\ \x75\x77\x54\x73\x4f\x34\x78\x58\x42\x51\x41\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x77\x48\x64\x2f\x7a\ \x44\x78\x72\x74\x42\x44\x6b\x45\x71\x4e\x62\x67\x0a\x41\x41\x41\ \x41\x41\x45\x6c\x46\x54\x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\x0a\ \x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x34\x35\ \x36\x35\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x20\x20\x3c\ \x74\x65\x78\x74\x0a\x20\x20\x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\ \x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\x22\x0a\x20\ \x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\ \x73\x69\x7a\x65\x3a\x31\x36\x2e\x39\x36\x38\x36\x33\x37\x34\x37\ \x30\x30\x30\x30\x30\x30\x30\x38\x39\x70\x78\x3b\x66\x6f\x6e\x74\ \x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\ \x6e\x74\x2d\x77\x65\x69\x67\x68\x74\x3a\x6e\x6f\x72\x6d\x61\x6c\ \x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\x67\x68\x74\x3a\x31\x32\x35\ \x25\x3b\x6c\x65\x74\x74\x65\x72\x2d\x73\x70\x61\x63\x69\x6e\x67\ \x3a\x30\x70\x78\x3b\x77\x6f\x72\x64\x2d\x73\x70\x61\x63\x69\x6e\ \x67\x3a\x30\x70\x78\x3b\x66\x69\x6c\x6c\x3a\x23\x30\x30\x30\x30\ \x66\x66\x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\ \x31\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x6e\x6f\x6e\x65\x3b\x66\x6f\ \x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\x53\x61\x6e\x73\x22\x0a\ \x20\x20\x20\x20\x20\x78\x3d\x22\x32\x2e\x30\x34\x33\x39\x35\x32\ \x35\x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x32\x32\x2e\x30\x37\ \x35\x31\x33\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\ \x65\x78\x74\x35\x33\x39\x31\x22\x0a\x20\x20\x20\x20\x20\x73\x6f\ \x64\x69\x70\x6f\x64\x69\x3a\x6c\x69\x6e\x65\x73\x70\x61\x63\x69\ \x6e\x67\x3d\x22\x31\x32\x35\x25\x22\x0a\x20\x20\x20\x20\x20\x74\ \x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x73\x63\x61\x6c\x65\x28\ \x31\x2e\x30\x34\x39\x38\x39\x36\x35\x2c\x30\x2e\x39\x35\x32\x34\ \x37\x34\x38\x32\x29\x22\x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\ \x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\ \x6c\x65\x3d\x22\x6c\x69\x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x74\x73\x70\x61\x6e\x35\x33\x39\x33\x22\x0a\ \x20\x20\x20\x20\x20\x20\x20\x78\x3d\x22\x32\x2e\x30\x34\x33\x39\ \x35\x32\x35\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x79\x3d\x22\x32\ \x32\x2e\x30\x37\x35\x31\x33\x36\x22\x3e\x61\x3c\x2f\x74\x73\x70\ \x61\x6e\x3e\x3c\x2f\x74\x65\x78\x74\x3e\x0a\x20\x20\x3c\x74\x65\ \x78\x74\x0a\x20\x20\x20\x20\x20\x78\x6d\x6c\x3a\x73\x70\x61\x63\ \x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\x22\x0a\x20\x20\x20\ \x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x69\ \x7a\x65\x3a\x31\x36\x2e\x39\x36\x38\x36\x33\x37\x34\x37\x30\x30\ \x30\x30\x30\x30\x30\x38\x39\x70\x78\x3b\x66\x6f\x6e\x74\x2d\x73\ \x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\ \x2d\x77\x65\x69\x67\x68\x74\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x6c\ \x69\x6e\x65\x2d\x68\x65\x69\x67\x68\x74\x3a\x31\x32\x35\x25\x3b\ \x6c\x65\x74\x74\x65\x72\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\ \x70\x78\x3b\x77\x6f\x72\x64\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\ \x30\x70\x78\x3b\x66\x69\x6c\x6c\x3a\x23\x30\x30\x30\x30\x66\x66\ \x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x3b\ \x73\x74\x72\x6f\x6b\x65\x3a\x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\x74\ \x2d\x66\x61\x6d\x69\x6c\x79\x3a\x53\x61\x6e\x73\x22\x0a\x20\x20\ \x20\x20\x20\x78\x3d\x22\x31\x32\x2e\x33\x39\x37\x36\x39\x37\x22\ \x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x32\x31\x2e\x35\x35\x37\x34\ \x34\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\x65\x78\ \x74\x35\x33\x39\x35\x22\x0a\x20\x20\x20\x20\x20\x73\x6f\x64\x69\ \x70\x6f\x64\x69\x3a\x6c\x69\x6e\x65\x73\x70\x61\x63\x69\x6e\x67\ \x3d\x22\x31\x32\x35\x25\x22\x0a\x20\x20\x20\x20\x20\x74\x72\x61\ \x6e\x73\x66\x6f\x72\x6d\x3d\x22\x73\x63\x61\x6c\x65\x28\x31\x2e\ \x30\x34\x39\x38\x39\x36\x35\x2c\x30\x2e\x39\x35\x32\x34\x37\x34\ \x38\x32\x29\x22\x3e\x3c\x74\x73\x70\x61\x6e\x0a\x20\x20\x20\x20\ \x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x72\x6f\x6c\x65\ \x3d\x22\x6c\x69\x6e\x65\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x74\x73\x70\x61\x6e\x35\x33\x39\x37\x22\x0a\x20\x20\ \x20\x20\x20\x20\x20\x78\x3d\x22\x31\x32\x2e\x33\x39\x37\x36\x39\ \x37\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x79\x3d\x22\x32\x31\x2e\ \x35\x35\x37\x34\x34\x37\x22\x3e\x2c\x62\x3c\x2f\x74\x73\x70\x61\ \x6e\x3e\x3c\x2f\x74\x65\x78\x74\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\ \x0a\ \x00\x00\x0c\x87\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\x74\ \x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\ \x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\x68\x74\ \x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\x73\x6f\ \x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\x44\x54\ \x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\x74\x64\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\x61\x6d\ \x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x34\x35\x35\x37\ \x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\ \x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x34\x38\x2e\x33\x2e\x31\ \x20\x72\x39\x38\x38\x36\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\ \x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\ \x22\x33\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x66\x69\x6c\x74\x72\x5f\ \x74\x61\x70\x73\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x6d\x65\ \x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x6d\x65\x74\x61\x64\x61\x74\x61\x34\x35\x36\x33\x22\x3e\x0a\x20\ \x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\ \x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\ \x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\ \x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\ \x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\ \x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\ \x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\ \x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\ \x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\ \x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\ \x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x64\x65\x66\x73\x34\x35\x36\x31\x22\x20\x2f\x3e\x0a\x20\ \x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\ \x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\ \x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\ \x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\ \x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\ \x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\ \x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\ \x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\ \x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\ \x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\ \x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\ \x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\ \x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\ \x3d\x22\x37\x32\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\ \x68\x74\x3d\x22\x37\x35\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x35\x35\x39\x22\ \x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\ \x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x37\x2e\x33\x37\x35\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x63\x78\x3d\x22\x32\x36\x2e\x32\x31\x34\x39\x33\x36\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\ \x22\x31\x39\x2e\x37\x32\x38\x38\x31\x34\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x78\x3d\x22\x36\x38\x33\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\ \x22\x31\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\ \x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\ \x79\x65\x72\x3d\x22\x73\x76\x67\x34\x35\x35\x37\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x73\x6e\x61\x70\ \x2d\x67\x6c\x6f\x62\x61\x6c\x3d\x22\x66\x61\x6c\x73\x65\x22\x20\ \x2f\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x0a\x20\x20\x20\x20\ \x20\x77\x69\x64\x74\x68\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\x20\ \x20\x68\x65\x69\x67\x68\x74\x3d\x22\x33\x32\x22\x0a\x20\x20\x20\ \x20\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\x61\ \x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\x73\ \x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\x41\ \x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x43\x41\x41\ \x41\x41\x41\x67\x43\x41\x59\x41\x41\x41\x42\x7a\x65\x6e\x72\x30\ \x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\x49\ \x66\x41\x68\x6b\x69\x41\x41\x41\x41\x44\x56\x4a\x52\x45\x46\x55\ \x0a\x57\x49\x58\x74\x31\x7a\x45\x42\x41\x44\x41\x4d\x77\x7a\x42\ \x33\x2f\x44\x6c\x33\x4d\x50\x6f\x6f\x42\x4b\x77\x33\x55\x32\x33\ \x48\x75\x77\x54\x73\x4f\x34\x78\x58\x42\x51\x41\x41\x41\x41\x41\ \x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x77\x48\x64\x2f\ \x7a\x44\x78\x72\x74\x42\x44\x6b\x45\x71\x4e\x62\x67\x0a\x41\x41\ \x41\x41\x41\x45\x6c\x46\x54\x6b\x53\x75\x51\x6d\x43\x43\x0a\x22\ \x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x69\x6d\x61\x67\x65\x34\ \x35\x36\x35\x22\x0a\x20\x20\x20\x20\x20\x78\x3d\x22\x30\x22\x0a\ \x20\x20\x20\x20\x20\x79\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x20\x20\ \x3c\x74\x65\x78\x74\x0a\x20\x20\x20\x20\x20\x78\x6d\x6c\x3a\x73\ \x70\x61\x63\x65\x3d\x22\x70\x72\x65\x73\x65\x72\x76\x65\x22\x0a\ \x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\ \x2d\x73\x69\x7a\x65\x3a\x34\x30\x70\x78\x3b\x66\x6f\x6e\x74\x2d\ \x73\x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\ \x74\x2d\x77\x65\x69\x67\x68\x74\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\ \x6c\x69\x6e\x65\x2d\x68\x65\x69\x67\x68\x74\x3a\x31\x32\x35\x25\ \x3b\x6c\x65\x74\x74\x65\x72\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\ \x30\x70\x78\x3b\x77\x6f\x72\x64\x2d\x73\x70\x61\x63\x69\x6e\x67\ \x3a\x30\x70\x78\x3b\x66\x69\x6c\x6c\x3a\x23\x30\x30\x30\x30\x30\ \x30\x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\ \x3b\x73\x74\x72\x6f\x6b\x65\x3a\x6e\x6f\x6e\x65\x3b\x66\x6f\x6e\ \x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\x53\x61\x6e\x73\x22\x0a\x20\ \x20\x20\x20\x20\x78\x3d\x22\x31\x31\x2e\x36\x36\x31\x30\x31\x37\ \x22\x0a\x20\x20\x20\x20\x20\x79\x3d\x22\x39\x2e\x33\x35\x35\x39\ \x33\x32\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\x65\ \x78\x74\x35\x34\x31\x38\x22\x0a\x20\x20\x20\x20\x20\x73\x6f\x64\ \x69\x70\x6f\x64\x69\x3a\x6c\x69\x6e\x65\x73\x70\x61\x63\x69\x6e\ \x67\x3d\x22\x31\x32\x35\x25\x22\x3e\x3c\x74\x73\x70\x61\x6e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\ \x72\x6f\x6c\x65\x3d\x22\x6c\x69\x6e\x65\x22\x0a\x20\x20\x20\x20\ \x20\x20\x20\x69\x64\x3d\x22\x74\x73\x70\x61\x6e\x35\x34\x32\x30\ \x22\x0a\x20\x20\x20\x20\x20\x20\x20\x78\x3d\x22\x31\x31\x2e\x36\ \x36\x31\x30\x31\x37\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x79\x3d\ \x22\x39\x2e\x33\x35\x35\x39\x33\x32\x32\x22\x20\x2f\x3e\x3c\x2f\ \x74\x65\x78\x74\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\ \x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x6e\ \x6f\x6e\x65\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x23\x30\x30\x30\x30\ \x66\x66\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3a\ \x31\x70\x78\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ \x61\x70\x3a\x62\x75\x74\x74\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ \x69\x6e\x65\x6a\x6f\x69\x6e\x3a\x6d\x69\x74\x65\x72\x3b\x73\x74\ \x72\x6f\x6b\x65\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x22\x0a\ \x20\x20\x20\x20\x20\x64\x3d\x22\x6d\x20\x31\x36\x2e\x37\x37\x39\ \x36\x36\x31\x2c\x34\x2e\x34\x37\x34\x35\x37\x36\x33\x20\x63\x20\ \x30\x2c\x37\x2e\x39\x35\x34\x38\x30\x32\x37\x20\x30\x2c\x31\x35\ \x2e\x39\x30\x39\x36\x30\x34\x37\x20\x30\x2c\x32\x33\x2e\x38\x36\ \x34\x34\x30\x36\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x70\x61\x74\x68\x35\x34\x32\x34\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\x65\x63\x74\x6f\ \x72\x2d\x63\x75\x72\x76\x61\x74\x75\x72\x65\x3d\x22\x30\x22\x20\ \x2f\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\ \x73\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x23\x30\x30\x30\ \x30\x66\x66\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x23\x30\x30\x30\x30\ \x66\x66\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3a\ \x31\x70\x78\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ \x61\x70\x3a\x62\x75\x74\x74\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ \x69\x6e\x65\x6a\x6f\x69\x6e\x3a\x6d\x69\x74\x65\x72\x3b\x73\x74\ \x72\x6f\x6b\x65\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x22\x0a\ \x20\x20\x20\x20\x20\x64\x3d\x22\x6d\x20\x31\x36\x2e\x39\x35\x30\ \x35\x31\x31\x2c\x34\x2e\x39\x34\x31\x31\x36\x31\x35\x20\x63\x20\ \x32\x2e\x30\x31\x30\x33\x39\x33\x2c\x32\x2e\x34\x30\x30\x38\x30\ \x38\x32\x20\x34\x2e\x30\x32\x30\x37\x38\x36\x2c\x34\x2e\x38\x30\ \x31\x36\x31\x37\x33\x20\x36\x2e\x30\x33\x31\x31\x37\x38\x2c\x37\ \x2e\x32\x30\x32\x34\x32\x34\x35\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x70\x61\x74\x68\x35\x34\x32\x36\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\x65\ \x63\x74\x6f\x72\x2d\x63\x75\x72\x76\x61\x74\x75\x72\x65\x3d\x22\ \x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x2d\x63\x65\x6e\x74\x65\ \x72\x2d\x78\x3d\x22\x2d\x32\x2e\x33\x30\x35\x30\x38\x34\x37\x22\ \x20\x2f\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\ \x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x6e\x6f\x6e\ \x65\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x23\x30\x30\x30\x30\x66\x66\ \x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3a\x31\x70\ \x78\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ \x3a\x62\x75\x74\x74\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ \x65\x6a\x6f\x69\x6e\x3a\x6d\x69\x74\x65\x72\x3b\x73\x74\x72\x6f\ \x6b\x65\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x30\x2e\x39\x34\x31\ \x31\x37\x36\x34\x37\x22\x0a\x20\x20\x20\x20\x20\x64\x3d\x22\x4d\ \x20\x31\x36\x2e\x38\x31\x32\x31\x39\x39\x2c\x34\x2e\x38\x30\x35\ \x35\x36\x37\x32\x20\x43\x20\x31\x34\x2e\x38\x30\x31\x38\x30\x36\ \x2c\x37\x2e\x32\x30\x36\x33\x37\x35\x34\x20\x31\x32\x2e\x37\x39\ \x31\x34\x31\x33\x2c\x39\x2e\x36\x30\x37\x31\x38\x34\x38\x20\x31\ \x30\x2e\x37\x38\x31\x30\x32\x31\x2c\x31\x32\x2e\x30\x30\x37\x39\ \x39\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x70\x61\x74\ \x68\x35\x34\x32\x36\x2d\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\x65\x63\x74\x6f\x72\ \x2d\x63\x75\x72\x76\x61\x74\x75\x72\x65\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x74\x72\x61\ \x6e\x73\x66\x6f\x72\x6d\x2d\x63\x65\x6e\x74\x65\x72\x2d\x78\x3d\ \x22\x32\x2e\x33\x30\x35\x30\x38\x34\x37\x22\x20\x2f\x3e\x0a\x3c\ \x2f\x73\x76\x67\x3e\x0a\ " qt_resource_name = "\ \x00\x05\ \x00\x6f\xa6\x53\ \x00\x69\ \x00\x63\x00\x6f\x00\x6e\x00\x73\ \x00\x14\ \x09\x81\xca\x67\ \x00\x69\ \x00\x6d\x00\x70\x00\x75\x00\x6c\x00\x73\x00\x65\x00\x5f\x00\x72\x00\x65\x00\x73\x00\x70\x00\x6f\x00\x6e\x00\x73\x00\x65\x00\x2e\ \x00\x73\x00\x76\x00\x67\ \x00\x0e\ \x00\x3a\xd2\x27\ \x00\x72\ \x00\x65\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x72\x00\x65\x00\x64\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x0f\ \x03\xbf\x35\xe7\ \x00\x70\ \x00\x68\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x65\x00\x6c\x00\x61\x00\x79\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x0d\ \x0c\x6e\x6c\xc7\ \x00\x63\ \x00\x6f\x00\x6e\x00\x6a\x00\x75\x00\x67\x00\x61\x00\x74\x00\x65\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x11\ \x09\x67\xa5\x87\ \x00\x73\ \x00\x74\x00\x65\x00\x70\x00\x5f\x00\x72\x00\x65\x00\x73\x00\x70\x00\x6f\x00\x6e\x00\x73\x00\x65\x00\x2e\x00\x73\x00\x76\x00\x67\ \ \x00\x0f\ \x0f\x09\x55\x87\ \x00\x67\ \x00\x72\x00\x6f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x65\x00\x6c\x00\x61\x00\x79\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x0b\ \x02\x69\xc3\xe7\ \x00\x6f\ \x00\x76\x00\x65\x00\x72\x00\x6c\x00\x61\x00\x79\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x12\ \x05\x37\x32\x67\ \x00\x70\ \x00\x68\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x72\x00\x65\x00\x73\x00\x70\x00\x6f\x00\x6e\x00\x73\x00\x65\x00\x2e\x00\x73\x00\x76\ \x00\x67\ \x00\x0c\ \x0a\xd5\x16\x27\ \x00\x61\ \x00\x64\x00\x64\x00\x5f\x00\x70\x00\x6f\x00\x6c\x00\x65\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x10\ \x08\x95\xc8\xc7\ \x00\x6d\ \x00\x61\x00\x67\x00\x5f\x00\x72\x00\x65\x00\x73\x00\x70\x00\x6f\x00\x6e\x00\x73\x00\x65\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x0c\ \x00\x67\x14\xc7\ \x00\x61\ \x00\x64\x00\x64\x00\x5f\x00\x7a\x00\x65\x00\x72\x00\x6f\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x0e\ \x08\x05\x4c\xc7\ \x00\x66\ \x00\x69\x00\x6c\x00\x74\x00\x72\x00\x5f\x00\x74\x00\x61\x00\x70\x00\x73\x00\x2e\x00\x73\x00\x76\x00\x67\ \x00\x0b\ \x03\x78\xd5\x47\ \x00\x69\ \x00\x6d\x00\x70\x00\x75\x00\x6c\x00\x73\x00\x65\x00\x2e\x00\x73\x00\x76\x00\x67\ " qt_resource_struct = "\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x0f\x00\x00\x00\x02\ \x00\x00\x00\x3e\x00\x00\x00\x00\x00\x01\x00\x00\x08\x4e\ \x00\x00\x01\x7a\x00\x00\x00\x00\x00\x01\x00\x00\x80\x3d\ \x00\x00\x01\x7a\x00\x00\x00\x00\x00\x01\x00\x00\x77\x3c\ \x00\x00\x00\xf0\x00\x00\x00\x00\x00\x01\x00\x00\x45\x9e\ \x00\x00\x01\xba\x00\x00\x00\x00\x00\x01\x00\x00\x94\x64\ \x00\x00\x00\x60\x00\x00\x00\x00\x00\x01\x00\x00\x16\xaa\ \x00\x00\x01\x0c\x00\x00\x00\x00\x00\x01\x00\x00\x4f\x74\ \x00\x00\x01\x98\x00\x00\x00\x00\x00\x01\x00\x00\x89\x3e\ \x00\x00\x01\x54\x00\x00\x00\x00\x00\x01\x00\x00\x6f\x47\ \x00\x00\x00\xa4\x00\x00\x00\x00\x00\x01\x00\x00\x33\xa5\ \x00\x00\x00\x10\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ \x00\x00\x01\x36\x00\x00\x00\x00\x00\x01\x00\x00\x58\x8f\ \x00\x00\x01\x36\x00\x00\x00\x00\x00\x01\x00\x00\x63\xeb\ \x00\x00\x00\x84\x00\x00\x00\x00\x00\x01\x00\x00\x20\x70\ \x00\x00\x00\xcc\x00\x00\x00\x00\x00\x01\x00\x00\x3b\x15\ " def qInitResources(): QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources() gnuradio-3.7.2.1/gr-filter/python/filter/gui/bandgraphicsview.py0000664000175000017500000000211312207440367024505 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from PyQt4 import QtGui, QtCore, Qt class BandGraphicsView(QtGui.QGraphicsView): def resizeEvent(self, event): self.setAlignment(Qt.Qt.AlignCenter) self.fitInView(self.scene().itemsBoundingRect(), QtCore.Qt.KeepAspectRatio) self.scale(1.3,1.3) self.setViewportMargins(10,10,10,10) gnuradio-3.7.2.1/gr-filter/python/filter/gui/idealbanditems.py0000664000175000017500000002076212207440367024144 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from PyQt4 import QtGui, QtCore, Qt import PyQt4.Qwt5 as Qwt import scipy class IdealBandItems(): def __init__(self): self.idealbandhcurves= [ Qwt.QwtPlotCurve() for i in range(4) ] self.idealbandvcurves= [ Qwt.QwtPlotCurve() for i in range(4) ] self.params="" def setLinetype(self): for c in self.idealbandhcurves: c.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) c.setPen(Qt.QPen(Qt.Qt.red, 2, Qt.Qt.DotLine)) for c in self.idealbandvcurves: c.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) c.setPen(Qt.QPen(Qt.Qt.red, 2, Qt.Qt.DotLine)) def plotIdealCurves(self, ftype, params, plot): self.params=params try: if (ftype == "Low Pass"): self.detach_unwantedcurves(plot) x=[0, self.params["pbend"]] y=[20.0*scipy.log10(self.params["gain"])]*2 self.idealbandhcurves[0].setData(x, y) x=[self.params["pbend"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) x=[self.params["sbstart"], self.params["fs"]/2.0] y=[-self.params["atten"]]*2 self.idealbandhcurves[1].setData(x, y) x=[self.params["sbstart"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) elif ftype == "High Pass": self.detach_unwantedcurves(plot) x=[self.params["pbstart"],self.params["fs"]/2.0] y=[20.0*scipy.log10(self.params["gain"])]*2 self.idealbandhcurves[0].setData(x, y) x=[self.params["pbstart"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) x=[0,self.params["sbend"]] y=[-self.params["atten"]]*2 self.idealbandhcurves[1].setData(x, y) x=[self.params["sbend"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) elif ftype == "Band Notch": x=[self.params["sbstart"],self.params["sbend"]] y=[-self.params["atten"]]*2 self.idealbandhcurves[0].setData(x, y) x=[self.params["sbstart"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) x=[self.params["sbend"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) x=[0,self.params["sbstart"]-self.params["tb"]] y=[20.0*scipy.log10(self.params["gain"])]*2 self.idealbandhcurves[1].setData(x, y) x=[self.params["sbstart"]-self.params["tb"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[2].setData(x, y) x=[self.params["sbend"]+self.params["tb"],self.params["fs"]/2.0] y=[20.0*scipy.log10(self.params["gain"])]*2 self.idealbandhcurves[2].setData(x, y) x=[self.params["sbend"]+self.params["tb"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[3].setData(x, y) elif ftype == "Band Pass": x=[self.params["pbstart"],self.params["pbend"]] y=[20.0*scipy.log10(self.params["gain"])]*2 self.idealbandhcurves[0].setData(x, y) x=[self.params["pbstart"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) x=[self.params["pbend"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) x=[0,self.params["pbstart"]-self.params["tb"]] y=[-self.params["atten"]]*2 self.idealbandhcurves[1].setData(x, y) x=[self.params["pbstart"]-self.params["tb"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[2].setData(x, y) x=[self.params["pbend"]+self.params["tb"],self.params["fs"]/2.0] y=[-self.params["atten"]]*2 self.idealbandhcurves[2].setData(x, y) x=[self.params["pbend"]+self.params["tb"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[3].setData(x, y) elif ftype == "Complex Band Pass": x=[self.params["pbstart"],self.params["pbend"]] y=[20.0*scipy.log10(self.params["gain"])]*2 self.idealbandhcurves[0].setData(x, y) x=[self.params["pbstart"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[0].setData(x, y) x=[self.params["pbend"]]*2 y=[20.0*scipy.log10(self.params["gain"]), plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[1].setData(x, y) x=[0,self.params["pbstart"]-self.params["tb"]] y=[-self.params["atten"]]*2 self.idealbandhcurves[1].setData(x, y) x=[self.params["pbstart"]-self.params["tb"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[2].setData(x, y) x=[self.params["pbend"]+self.params["tb"],self.params["fs"]/2.0] y=[-self.params["atten"]]*2 self.idealbandhcurves[2].setData(x, y) x=[self.params["pbend"]+self.params["tb"]]*2 y=[-self.params["atten"], plot.axisScaleDiv(Qwt.QwtPlot.yLeft).lowerBound()] self.idealbandvcurves[3].setData(x, y) else: self.detach_allidealcurves(plot) except KeyError: print "All parameters not set for ideal band diagram" self.detach_allidealcurves(plot) def detach_allidealcurves(self, plot): for c in self.idealbandhcurves: c.detach() for c in self.idealbandvcurves: c.detach() plot.replot() def detach_unwantedcurves(self, plot): for i in range(2,4): self.idealbandvcurves[i].detach() self.idealbandhcurves[i].detach() plot.replot() def attach_allidealcurves(self, plot): for c in self.idealbandhcurves: c.attach(plot) for c in self.idealbandvcurves: c.attach(plot) plot.replot() gnuradio-3.7.2.1/gr-filter/python/filter/gui/polezero_plot.py0000664000175000017500000004305512207440367024074 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from PyQt4 import Qt, QtCore from math import sin, cos, pi import PyQt4.Qwt5 as Qwt from PyQt4.Qwt5.anynumpy import * class PzPlot(Qwt.QwtPlot): def __init__(self, *args): Qwt.QwtPlot.__init__(self, *args) self.ymax=0 self.xmax=0 self.ymin=0 self.xmin=0 self.setCanvasColor(Qt.Qt.darkCyan) grid = Qwt.QwtPlotGrid() grid.attach(self) grid.setMajPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.DotLine)) self.setAxisScale(Qwt.QwtPlot.xBottom, -3, 3) self.setAxisScale(Qwt.QwtPlot.yLeft, -2, 2) self.drawUnitcircle() def setCanvasColor(self, color): self.setCanvasBackground(color) self.replot() def drawUnitcircle(self): radius = 1.0 steps = 1024 angleStep = 2 * pi / steps x=[sin(a * angleStep) * radius for a in range(0, steps)] y=[cos(a * angleStep) * radius for a in range(0, steps)] curve = Qwt.QwtPlotCurve() curve.attach(self) curve.setPen(Qt.QPen(Qt.Qt.gray, 1, Qt.Qt.DotLine)) curve.setData(x, y) def insertZeros(self, roots): self.removeallCurves() if len(roots): self.__insertZero(Qt.Qt.blue, roots.real,roots.imag) self.ymax = max(roots.imag) self.ymin = min(roots.imag) self.xmax = max(roots.real) self.xmin = min(roots.real) #To make the plot look good if self.xmax <= 1.3: self.xmax = 2 if self.xmin >= -1.3: self.xmin = -2 if self.ymax <= 1: self.ymax = 1.5 if self.ymin >= -1: self.ymin = -1.5 self.setAxisScale(Qwt.QwtPlot.xBottom, self.xmin, self.xmax) self.setAxisScale(Qwt.QwtPlot.yLeft, self.ymin, self.ymax) def insertPoles(self, roots): if len(roots): self.__insertPole(Qt.Qt.black, roots.real,roots.imag) ymax = max(roots.imag) ymax = max(ymax,self.ymax) ymin = min(roots.imag) ymin = min(ymin,self.ymin) xmax = max(roots.real) xmax = max(xmax,self.xmax) xmin = min(roots.real) xmin = min(xmin,self.xmin) #To make the plot look good if xmax <= 1.3: xmax = 2 else: xmax = 1.2 * xmax if xmin >= -1.3: xmin = -2 else: xmin = 1.2 * xmin if ymax <= 1: ymax = 1.5 else: ymax = 1.2 * ymax if ymin >= -1: ymin = -1.5 else: ymin = 1.2 * ymin self.setAxisScale(Qwt.QwtPlot.xBottom, xmin, xmax) self.setAxisScale(Qwt.QwtPlot.yLeft, ymin, ymax) self.drawUnitcircle() self.replot() def __insertZero(self, color, px, py): curve = Qwt.QwtPlotCurve() curve.attach(self) curve.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) curve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, Qt.QBrush(Qt.Qt.gray), Qt.QPen(color), Qt.QSize(10, 10))) curve.setData(px, py) def __insertPole(self, color, px, py): curve = Qwt.QwtPlotCurve() curve.attach(self) curve.setPen(Qt.QPen(Qt.Qt.white, 0, Qt.Qt.NoPen)) curve.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.XCross, Qt.QBrush(Qt.Qt.gray), Qt.QPen(color), Qt.QSize(7, 7))) curve.setData(px, py) def removeallCurves(self): for curve in self.itemList(): if isinstance(curve, Qwt.QwtPlotCurve): curve.detach() self.replot() class CanvasPicker(Qt.QObject): curveChanged = QtCore.pyqtSignal(tuple) mouseposChanged = QtCore.pyqtSignal(tuple) def __init__(self, plot): Qt.QObject.__init__(self, plot) self.__selectedCurve = None self.__selectedPoint = -1 self.__selectedcPoint = -1 self.__addedZero = -1 self.__addedcZero = -1 self.changeConjugate = False self.enableZeroadd= False self.enablePoleadd= False self.enablepzDelete= False self.iir = False self.__plot = plot canvas = plot.canvas() canvas.installEventFilter(self) # We want the focus, but no focus rect. # The selected point will be highlighted instead. canvas.setFocusPolicy(Qt.Qt.StrongFocus) canvas.setCursor(Qt.Qt.PointingHandCursor) canvas.setFocusIndicator(Qwt.QwtPlotCanvas.ItemFocusIndicator) canvas.setFocus() canvas.setWhatsThis( 'All points can be moved using the left mouse button ' 'or with these keys:\n\n' '- Up: Select next curve\n' '- Down: Select previous curve\n' '- Left, "-": Select next point\n' '- Right, "+": Select previous point\n' '- 7, 8, 9, 4, 6, 1, 2, 3: Move selected point' ) self.__shiftCurveCursor(True) def event(self, event): if event.type() == Qt.QEvent.User: self.__showCursor(True) return True try: return Qt.QObject.event(event) except TypeError: return False def set_conjugate(self): self.changeConjugate = not(self.changeConjugate) def set_iir(self,val=True): self.iir = val def add_zero(self): self.enableZeroadd = not(self.enableZeroadd) def add_pole(self): #Adding pole support only for iir if self.iir: self.enablePoleadd = not(self.enablePoleadd) def delete_pz(self): self.enablepzDelete = not(self.enablepzDelete) def eventFilter(self, object, event): if event.type() == Qt.QEvent.FocusIn: self.__showCursor(True) if event.type() == Qt.QEvent.FocusOut: self.__showCursor(False) if event.type() == Qt.QEvent.Paint: Qt.QApplication.postEvent( self, Qt.QEvent(Qt.QEvent.User)) elif event.type() == Qt.QEvent.MouseButtonPress: if self.enableZeroadd or self.enablePoleadd: self.__drawAddedzero_pole(True, event.pos()) else: self.__select(event.pos()) return True elif event.type() == Qt.QEvent.MouseMove: curve = self.__selectedCurve if curve: tp=(self.__plot.invTransform(curve.xAxis(), event.pos().x()), self.__plot.invTransform(curve.xAxis(), event.pos().y())) self.mouseposChanged.emit(tp) self.__move(event.pos()) return True if event.type() == Qt.QEvent.KeyPress: delta = 5 key = event.key() if key == Qt.Qt.Key_Up: self.__shiftCurveCursor(True) return True elif key == Qt.Qt.Key_Down: self.__shiftCurveCursor(False) return True elif key == Qt.Qt.Key_Right or key == Qt.Qt.Key_Plus: if self.__selectedCurve: self.__shiftPointCursor(True) else: self.__shiftCurveCursor(True) return True elif key == Qt.Qt.Key_Left or key == Qt.Qt.Key_Minus: if self.__selectedCurve: self.__shiftPointCursor(False) else: self.__shiftCurveCursor(True) return True if key == Qt.Qt.Key_1: self.__moveBy(-delta, delta) elif key == Qt.Qt.Key_2: self.__moveBy(0, delta) elif key == Qt.Qt.Key_3: self.__moveBy(delta, delta) elif key == Qt.Qt.Key_4: self.__moveBy(-delta, 0) elif key == Qt.Qt.Key_6: self.__moveBy(delta, 0) elif key == Qt.Qt.Key_7: self.__moveBy(-delta, -delta) elif key == Qt.Qt.Key_8: self.__moveBy(0, -delta) elif key == Qt.Qt.Key_9: self.__moveBy(delta, -delta) return Qwt.QwtPlot.eventFilter(self, object, event) def __select(self, pos): found, distance, point = None, 1e100, -1 for curve in self.__plot.itemList(): if isinstance(curve, Qwt.QwtPlotCurve): if curve.symbol().style() != Qwt.QwtSymbol.NoSymbol: i, d = curve.closestPoint(pos) if d < distance: found = curve point = i distance = d self.__showCursor(False) self.__selectedCurve = None self.__selectedPoint = -1 self.__selectedcPoint = -1 if found and distance < 10: self.__selectedCurve = found self.__selectedPoint = point #search for conjugate point if enabled if self.changeConjugate: j=self.__searchConjugate(found.x(point),found.y(point)) self.__selectedcPoint = j #delete zero/pole if enabled if self.enablepzDelete: self.__deleteZero() self.__showCursor(True) else: self.mouseposChanged.emit((None,None)) def __deleteZero(self): curve = self.__selectedCurve xData = zeros(curve.dataSize(), Float) yData = zeros(curve.dataSize(), Float) for i in range(curve.dataSize()): xData[i] = curve.x(i) yData[i] = curve.y(i) if(self.__selectedPoint != -1): xData=delete(xData, self.__selectedPoint) yData=delete(yData, self.__selectedPoint) #one less to accomodate previous delete if(self.__selectedcPoint != -1): xData=delete(xData, self.__selectedcPoint-1) yData=delete(yData, self.__selectedcPoint-1) curve.setData(xData, yData) self.__plot.replot() px=[] py=[] for c in self.__plot.itemList(): if isinstance(c, Qwt.QwtPlotCurve): px.append([c.x(i) for i in range(c.dataSize())]) py.append([c.y(i) for i in range(c.dataSize())]) tp=(vectorize(complex)(px[0],py[0]),vectorize(complex)(px[1],py[1])) self.curveChanged.emit(tp) def __moveBy(self, dx, dy): if dx == 0 and dy == 0: return curve = self.__selectedCurve if not curve: return x = self.__plot.transform( curve.xAxis(), curve.x(self.__selectedPoint)) + dx y = self.__plot.transform( curve.yAxis(), curve.y(self.__selectedPoint)) + dy self.__move(Qt.QPoint(x, y)) def __move(self, pos): curve = self.__selectedCurve if not curve: return xData = zeros(curve.dataSize(), Float) yData = zeros(curve.dataSize(), Float) #poles made unmovable when FIR design is active move_enable=True if not self.iir: if self.__selectedCurve.symbol().style() == Qwt.QwtSymbol.XCross: move_enable=False if move_enable: for i in range(curve.dataSize()): if i == self.__selectedPoint: xData[i] = self.__plot.invTransform(curve.xAxis(), pos.x()) yData[i] = self.__plot.invTransform(curve.yAxis(), pos.y()) if(self.__selectedcPoint != -1): xData[self.__selectedcPoint] = xData[i] yData[self.__selectedcPoint] = -yData[i] elif i != self.__selectedcPoint: xData[i] = curve.x(i) yData[i] = curve.y(i) curve.setData(xData, yData) self.__plot.replot() px=[] py=[] for c in self.__plot.itemList(): if isinstance(c, Qwt.QwtPlotCurve): px.append([c.x(i) for i in range(c.dataSize())]) py.append([c.y(i) for i in range(c.dataSize())]) tp=(vectorize(complex)(px[0],py[0]),vectorize(complex)(px[1],py[1])) self.curveChanged.emit(tp) self.__showCursor(True) def __searchConjugate(self, x, y): curve = self.__selectedCurve for i in range(curve.dataSize()): if (round(curve.x(i),8) == round(x,8) and round(curve.y(i),8) == -round(y,8)): if (y !=0): return i return -1 def __drawAddedzero_pole(self, showIt, pos): editcurve='' for curve in self.__plot.itemList(): if isinstance(curve, Qwt.QwtPlotCurve): if self.enableZeroadd: if curve.symbol().style() == Qwt.QwtSymbol.Ellipse: editcurve=curve if self.enablePoleadd: if curve.symbol().style() == Qwt.QwtSymbol.XCross: editcurve=curve if not editcurve: return if self.changeConjugate: extrapoints=2 else: extrapoints=1 xData = zeros(editcurve.dataSize()+extrapoints, Float) yData = zeros(editcurve.dataSize()+extrapoints, Float) for i in range(editcurve.dataSize()): xData[i] = editcurve.x(i) yData[i] = editcurve.y(i) xData[i+1] = self.__plot.invTransform(editcurve.xAxis(), pos.x()) yData[i+1] = self.__plot.invTransform(editcurve.yAxis(), pos.y()) if self.changeConjugate: xData[i+2] = xData[i+1] yData[i+2] = -yData[i+1] self.__addedcZero=i+2 editcurve.setData(xData, yData) self.__addedZero=i+1 symbol = Qwt.QwtSymbol(editcurve.symbol()) newSymbol = Qwt.QwtSymbol(symbol) newSymbol.setPen(Qt.QPen(Qt.Qt.red)) doReplot = self.__plot.autoReplot() self.__plot.setAutoReplot(False) editcurve.setSymbol(newSymbol) editcurve.draw(self.__addedZero, self.__addedZero) if self.changeConjugate: editcurve.draw(self.__addedcZero, self.__addedcZero) editcurve.setSymbol(symbol) self.__plot.setAutoReplot(doReplot) px=[] py=[] for c in self.__plot.itemList(): if isinstance(c, Qwt.QwtPlotCurve): px.append([c.x(i) for i in range(c.dataSize())]) py.append([c.y(i) for i in range(c.dataSize())]) tp=(vectorize(complex)(px[0],py[0]),vectorize(complex)(px[1],py[1])) self.curveChanged.emit(tp) self.__showCursor(True) def __showCursor(self, showIt): curve = self.__selectedCurve if not curve: return # Use copy constructors to defeat the reference semantics. symbol = Qwt.QwtSymbol(curve.symbol()) newSymbol = Qwt.QwtSymbol(symbol) if showIt: newSymbol.setBrush(symbol.brush().color().dark(150)) doReplot = self.__plot.autoReplot() self.__plot.setAutoReplot(False) curve.setSymbol(newSymbol) curve.draw(self.__selectedPoint, self.__selectedPoint) if (self.__selectedcPoint != -1): curve.draw(self.__selectedcPoint, self.__selectedcPoint) curve.setSymbol(symbol) self.__plot.setAutoReplot(doReplot) def __shiftCurveCursor(self, up): curves = [curve for curve in self.__plot.itemList() if isinstance(curve, Qwt.QwtPlotCurve)] if not curves: return if self.__selectedCurve in curves: index = curves.index(self.__selectedCurve) if up: index += 1 else: index -= 1 # keep index within [0, len(curves)) index += len(curves) index %= len(curves) else: index = 0 self.__showCursor(False) self.__selectedPoint = 0 self.__selectedCurve = curves[index] self.__showCursor(True) def __shiftPointCursor(self, up): curve = self.__selectedCurve if not curve: return if up: index = self.__selectedPoint + 1 else: index = self.__selectedPoint - 1 # keep index within [0, curve.dataSize()) index += curve.dataSize() index %= curve.dataSize() if index != self.__selectedPoint: self.__showCursor(False) self.__selectedPoint = index self.__showCursor(True) gnuradio-3.7.2.1/gr-filter/lib/0000755000175000017500000000000012245466767016006 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/lib/adaptive_fir_ccf_impl.cc0000664000175000017500000000542712245466767022620 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "adaptive_fir_ccf_impl.h" #include namespace gr { namespace filter { adaptive_fir_ccf::sptr adaptive_fir_ccf::make(const char *name, int decimation, const std::vector &taps) { return gnuradio::get_initial_sptr(new adaptive_fir_ccf_impl (name, decimation, taps)); } adaptive_fir_ccf_impl::adaptive_fir_ccf_impl(const char *name, int decimation, const std::vector &taps) : sync_decimator(name, io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), decimation), kernel::adaptive_fir_ccf(decimation, taps), d_updated(false) { set_history(d_ntaps); } void adaptive_fir_ccf_impl::set_taps(const std::vector &taps) { d_new_taps = taps; d_updated = true; } std::vector adaptive_fir_ccf_impl::taps() { return kernel::fir_filter_ccf::taps(); } float adaptive_fir_ccf_impl::error(const gr_complex &out) { return 0; } void adaptive_fir_ccf_impl::update_tap(float &tap, const gr_complex &in) { tap = tap; } int adaptive_fir_ccf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; if (d_updated) { kernel::fir_filter_ccf::set_taps(d_new_taps); set_history(d_ntaps); d_updated = false; return 0; // history requirements may have changed. } // Call base class filtering function that uses // overloaded error and update_tap functions. if (decimation() == 1) { filterN(out, in, noutput_items); } else { filterNdec(out, in, noutput_items, decimation()); } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/CMakeLists.txt0000664000175000017500000001522612245466767020556 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_impl_dict2(name, sig, 'filter') build_utils.expand_template(d, inp) ") macro(expand_cc root) #make a list of all the generated files unset(expanded_files_cc) unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_cc ${CMAKE_CURRENT_BINARY_DIR}/${name}.cc) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the source files add_custom_command( OUTPUT ${expanded_files_cc} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.cc.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.cc.t ${ARGN} ) #create a command to generate the header file add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #make source files depends on headers to force generation set_source_files_properties(${expanded_files_cc} PROPERTIES OBJECT_DEPENDS "${expanded_files_h}" ) #install rules for the generated cc files list(APPEND generated_sources ${expanded_files_cc}) list(APPEND generated_headers ${expanded_files_h}) endmacro(expand_cc) ######################################################################## # Invoke macro to generate various sources ######################################################################## expand_cc(fir_filter_XXX_impl ccc ccf fcc fff fsf scc) expand_cc(freq_xlating_fir_filter_XXX_impl ccc ccf fcc fcf scf scc) expand_cc(interp_fir_filter_XXX_impl ccc ccf fcc fff fsf scc) expand_cc(rational_resampler_base_XXX_impl ccc ccf fcc fff fsf scc) ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${GR_FILTER_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${LOG4CPP_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories( ${Boost_LIBRARY_DIRS} ${LOG4CPP_LIBRARIES} ) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND filter_sources adaptive_fir.cc fir_filter.cc fir_filter_with_buffer.cc fft_filter.cc firdes.cc mmse_fir_interpolator_cc.cc mmse_fir_interpolator_ff.cc pm_remez.cc polyphase_filterbank.cc ${generated_sources} adaptive_fir_ccc_impl.cc adaptive_fir_ccf_impl.cc dc_blocker_cc_impl.cc dc_blocker_ff_impl.cc filter_delay_fc_impl.cc fft_filter_ccc_impl.cc fft_filter_fff_impl.cc fractional_interpolator_cc_impl.cc fractional_interpolator_ff_impl.cc fractional_resampler_cc_impl.cc fractional_resampler_ff_impl.cc hilbert_fc_impl.cc iir_filter_ffd_impl.cc pfb_arb_resampler.cc pfb_arb_resampler_ccf_impl.cc pfb_arb_resampler_fff_impl.cc pfb_channelizer_ccf_impl.cc pfb_decimator_ccf_impl.cc pfb_interpolator_ccf_impl.cc pfb_synthesizer_ccf_impl.cc single_pole_iir_filter_cc_impl.cc single_pole_iir_filter_ff_impl.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-filter.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-filter.rc @ONLY) list(APPEND filter_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-filter.rc ) endif(MSVC) list(APPEND filter_libs gnuradio-runtime gnuradio-fft gnuradio-blocks volk ${Boost_LIBRARIES} ) add_library(gnuradio-filter SHARED ${filter_sources}) target_link_libraries(gnuradio-filter ${filter_libs}) GR_LIBRARY_FOO(gnuradio-filter RUNTIME_COMPONENT "filter_runtime" DEVEL_COMPONENT "filter_devel") add_dependencies(gnuradio-filter filter_generated_includes filter_generated_swigs gnuradio-runtime gnuradio-fft) ######################################################################## # QA C++ Code for gr-filter ######################################################################## if(ENABLE_TESTING) include(GrTest) include_directories(${CPPUNIT_INCLUDE_DIRS}) link_directories(${CPPUNIT_LIBRARY_DIRS}) list(APPEND test_gr_filter_sources ${CMAKE_CURRENT_SOURCE_DIR}/test_gr_filter.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_filter.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_firdes.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_fir_filter_with_buffer.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_mmse_fir_interpolator_cc.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_mmse_fir_interpolator_ff.cc ) add_executable(test-gr-filter ${test_gr_filter_sources}) list(APPEND GR_TEST_TARGET_DEPS test-gr-filter gnuradio-filter gnuradio-fft) target_link_libraries( test-gr-filter gnuradio-runtime gnuradio-filter ${Boost_LIBRARIES} ${CPPUNIT_LIBRARIES} ) GR_ADD_TEST(test_gr_filter test-gr-filter) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-filter/lib/adaptive_fir.cc0000664000175000017500000000306412245466767020757 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { namespace filter { namespace kernel { adaptive_fir_ccc::adaptive_fir_ccc(int decimation, const std::vector &taps) : fir_filter_ccc(decimation, taps) { } adaptive_fir_ccc::~adaptive_fir_ccc() { } /**************************************************************/ adaptive_fir_ccf::adaptive_fir_ccf(int decimation, const std::vector &taps) : fir_filter_ccf(decimation, taps) { } adaptive_fir_ccf::~adaptive_fir_ccf() { } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/iir_filter_ffd_impl.cc0000664000175000017500000000457012207440367022277 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "iir_filter_ffd_impl.h" #include namespace gr { namespace filter { iir_filter_ffd::sptr iir_filter_ffd::make(const std::vector &fftaps, const std::vector &fbtaps, bool oldstyle) { return gnuradio::get_initial_sptr (new iir_filter_ffd_impl(fftaps, fbtaps, oldstyle)); } iir_filter_ffd_impl::iir_filter_ffd_impl(const std::vector &fftaps, const std::vector &fbtaps, bool oldstyle) : sync_block("iir_filter_ffd", io_signature::make(1, 1, sizeof (float)), io_signature::make(1, 1, sizeof (float))), d_updated(false) { d_iir = new kernel::iir_filter(fftaps, fbtaps, oldstyle); } iir_filter_ffd_impl::~iir_filter_ffd_impl() { delete d_iir; } void iir_filter_ffd_impl::set_taps(const std::vector &fftaps, const std::vector &fbtaps) { d_new_fftaps = fftaps; d_new_fbtaps = fbtaps; d_updated = true; } int iir_filter_ffd_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; if(d_updated) { d_iir->set_taps(d_new_fftaps, d_new_fbtaps); d_updated = false; } d_iir->filter_n(out, in, noutput_items); return noutput_items; }; } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fft_filter_ccc_impl.cc0000664000175000017500000000572312207440367022265 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fft_filter_ccc_impl.h" #include #include #include #include namespace gr { namespace filter { fft_filter_ccc::sptr fft_filter_ccc::make(int decimation, const std::vector &taps, int nthreads) { return gnuradio::get_initial_sptr(new fft_filter_ccc_impl (decimation, taps, nthreads)); } fft_filter_ccc_impl::fft_filter_ccc_impl(int decimation, const std::vector &taps, int nthreads) : sync_decimator("fft_filter_ccc", io_signature::make (1, 1, sizeof(gr_complex)), io_signature::make (1, 1, sizeof(gr_complex)), decimation), d_updated(false) { set_history(1); d_filter = new kernel::fft_filter_ccc(decimation, taps, nthreads); d_new_taps = taps; d_nsamples = d_filter->set_taps(taps); set_output_multiple(d_nsamples); } fft_filter_ccc_impl::~fft_filter_ccc_impl() { delete d_filter; } void fft_filter_ccc_impl::set_taps(const std::vector &taps) { d_new_taps = taps; d_updated = true; } std::vector fft_filter_ccc_impl::taps() const { return d_new_taps; } void fft_filter_ccc_impl::set_nthreads(int n) { if(d_filter) d_filter->set_nthreads(n); } int fft_filter_ccc_impl::nthreads() const { if(d_filter) return d_filter->nthreads(); else return 0; } int fft_filter_ccc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; if (d_updated){ d_nsamples = d_filter->set_taps(d_new_taps); d_updated = false; set_output_multiple(d_nsamples); return 0; // output multiple may have changed } d_filter->filter(noutput_items, in, out); return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/gnuradio-filter.rc.in0000664000175000017500000000332612207440367022024 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-filter" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-filter.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-filter.dll" VALUE "ProductName", "gnuradio-filter" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-filter/lib/qa_filter.h0000664000175000017500000000222512207440367020112 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_GR_FILTER_H_ #define _QA_GR_FILTER_H_ #include #include //! collect all the tests for the gr-filter directory class __GR_ATTR_EXPORT qa_gr_filter { public: //! return suite of tests for all of gr-filter directory static CppUnit::TestSuite *suite (); }; #endif /* _QA_GR_FILTER_H_ */ gnuradio-3.7.2.1/gr-filter/lib/pfb_decimator_ccf_impl.h0000664000175000017500000000377312245466767022625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_DECIMATOR_CCF_IMPL_H #define INCLUDED_PFB_DECIMATOR_CCF_IMPL_H #include #include #include #include #include namespace gr { namespace filter { class FILTER_API pfb_decimator_ccf_impl : public pfb_decimator_ccf, kernel::polyphase_filterbank { private: bool d_updated; unsigned int d_rate; unsigned int d_chan; gr_complex *d_rotator; gr::thread::mutex d_mutex; // mutex to protect set/work access public: pfb_decimator_ccf_impl(unsigned int decim, const std::vector &taps, unsigned int channel); ~pfb_decimator_ccf_impl(); void set_taps(const std::vector &taps); void print_taps(); std::vector > taps() const; //void set_channel(unsigned int channel); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_DECIMATOR_CCF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/single_pole_iir_filter_cc_impl.cc0000664000175000017500000000464712207440367024512 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "single_pole_iir_filter_cc_impl.h" #include namespace gr { namespace filter { single_pole_iir_filter_cc::sptr single_pole_iir_filter_cc::make(double alpha, unsigned int vlen) { return gnuradio::get_initial_sptr (new single_pole_iir_filter_cc_impl(alpha, vlen)); } single_pole_iir_filter_cc_impl::single_pole_iir_filter_cc_impl (double alpha, unsigned int vlen) : sync_block("single_pole_iir_filter_cc", io_signature::make(1, 1, sizeof (gr_complex) * vlen), io_signature::make(1, 1, sizeof (gr_complex) * vlen)), d_vlen(vlen), d_iir(vlen) { set_taps(alpha); } single_pole_iir_filter_cc_impl::~single_pole_iir_filter_cc_impl() { } void single_pole_iir_filter_cc_impl::set_taps(double alpha) { for(unsigned int i = 0; i < d_vlen; i++) { d_iir[i].set_taps(alpha); } } int single_pole_iir_filter_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; unsigned int vlen = d_vlen; if(d_vlen == 1) { for(int i = 0; i < noutput_items; i++) { out[i] = d_iir[0].filter(in[i]); } } else { for(int i = 0; i < noutput_items; i++) { for(unsigned int j = 0; j < vlen; j++) { *out++ = d_iir[j].filter(*in++); } } } return noutput_items; }; } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/adaptive_fir_ccc_impl.h0000664000175000017500000000370412245466767022453 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_ADAPTIVE_FIR_CCC_IMPL_H #define INCLUDED_FILTER_ADAPTIVE_FIR_CCC_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API adaptive_fir_ccc_impl : public adaptive_fir_ccc, public kernel::adaptive_fir_ccc { private: std::vector d_new_taps; bool d_updated; protected: // Override to calculate error signal per output gr_complex error(const gr_complex &out); // Override to calculate new weight from old, corresponding input void update_tap(gr_complex &tap, const gr_complex &in); public: void set_taps(const std::vector &taps); std::vector taps() const; adaptive_fir_ccc_impl(const char *name, int decimation, const std::vector &taps); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_ADAPTIVE_FIR_CCC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/pfb_arb_resampler_fff_impl.cc0000664000175000017500000001123212207440367023607 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pfb_arb_resampler_fff_impl.h" #include #include namespace gr { namespace filter { pfb_arb_resampler_fff::sptr pfb_arb_resampler_fff::make(float rate, const std::vector &taps, unsigned int filter_size) { return gnuradio::get_initial_sptr (new pfb_arb_resampler_fff_impl(rate, taps, filter_size)); } pfb_arb_resampler_fff_impl::pfb_arb_resampler_fff_impl(float rate, const std::vector &taps, unsigned int filter_size) : block("pfb_arb_resampler_fff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))) { d_updated = false; d_resamp = new kernel::pfb_arb_resampler_fff(rate, taps, filter_size); set_history(d_resamp->taps_per_filter()); set_relative_rate(rate); } pfb_arb_resampler_fff_impl::~pfb_arb_resampler_fff_impl() { delete d_resamp; } void pfb_arb_resampler_fff_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); if(noutput_items / relative_rate() < 1) { for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = max_output_buffer(i)-1; } else { for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = noutput_items/relative_rate() + history() - 1; } } void pfb_arb_resampler_fff_impl::set_taps(const std::vector &taps) { gr::thread::scoped_lock guard(d_mutex); d_resamp->set_taps(taps); set_history(d_resamp->taps_per_filter()); d_updated = true; } std::vector > pfb_arb_resampler_fff_impl::taps() const { return d_resamp->taps(); } void pfb_arb_resampler_fff_impl::print_taps() { d_resamp->print_taps(); } void pfb_arb_resampler_fff_impl::set_rate(float rate) { gr::thread::scoped_lock guard(d_mutex); d_resamp->set_rate(rate); set_relative_rate(rate); } void pfb_arb_resampler_fff_impl::set_phase(float ph) { gr::thread::scoped_lock guard(d_mutex); d_resamp->set_phase(ph); } float pfb_arb_resampler_fff_impl::phase() const { return d_resamp->phase(); } unsigned int pfb_arb_resampler_fff_impl::interpolation_rate() const { return d_resamp->interpolation_rate(); } unsigned int pfb_arb_resampler_fff_impl::decimation_rate() const { return d_resamp->decimation_rate(); } float pfb_arb_resampler_fff_impl::fractional_rate() const { return d_resamp->fractional_rate(); } unsigned int pfb_arb_resampler_fff_impl::taps_per_filter() const { return d_resamp->taps_per_filter(); } int pfb_arb_resampler_fff_impl::group_delay() const { return d_resamp->group_delay(); } float pfb_arb_resampler_fff_impl::phase_offset(float freq, float fs) { return d_resamp->phase_offset(freq, fs); } int pfb_arb_resampler_fff_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock guard(d_mutex); float *in = (float*)input_items[0]; float *out = (float*)output_items[0]; if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } int nitems_read; int nitems = floorf((float)noutput_items / relative_rate()); int processed = d_resamp->filter(out, in, nitems, nitems_read); consume_each(nitems_read); return processed; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_mmse_fir_interpolator_cc.cc0000664000175000017500000000703212207440367024034 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include namespace gr { namespace filter { static float test_fcn_sin(double index) { return (2 * sin (index * 0.25 * 2 * M_PI + 0.125 * M_PI) + 3 * sin (index * 0.077 * 2 * M_PI + 0.3 * M_PI)); } static float test_fcn_cos(double index) { return (2 * cos (index * 0.25 * 2 * M_PI + 0.125 * M_PI) + 3 * cos (index * 0.077 * 2 * M_PI + 0.3 * M_PI)); } static gr_complex test_fcn(double index) { return gr_complex(test_fcn_cos(index), test_fcn_sin(index)); } void qa_mmse_fir_interpolator_cc::t1() { static const unsigned N = 100; gr_complex *input = fft::malloc_complex(N + 10); for(unsigned i = 0; i < N+10; i++) input[i] = test_fcn((double) i); mmse_fir_interpolator_cc intr; float inv_nsteps = 1.0 / intr.nsteps(); for(unsigned i = 0; i < N; i++) { for(unsigned imu = 0; imu <= intr.nsteps (); imu += 1) { gr_complex expected = test_fcn((i + 3) + imu * inv_nsteps); gr_complex actual = intr.interpolate(&input[i], imu * inv_nsteps); CPPUNIT_ASSERT_COMPLEXES_EQUAL(expected, actual, 0.004); // printf ("%9.6f %9.6f %9.6f\n", expected, actual, expected - actual); } } fft::free(input); } /* * Force bad alignment and confirm that it raises an exception */ void qa_mmse_fir_interpolator_cc::t2_body() { static const unsigned N = 100; float float_input[2*(N+10) + 1]; gr_complex *input; // We require that gr_complex be aligned on an 8-byte boundary. // Ensure that we ARE NOT ;) if(((intptr_t) float_input & 0x7) == 0) input = reinterpret_cast(&float_input[1]); else input = reinterpret_cast(&float_input[0]); for(unsigned i = 0; i < (N+10); i++) input[i] = test_fcn((double) i); mmse_fir_interpolator_cc intr; float inv_nsteps = 1.0 / intr.nsteps(); for(unsigned i = 0; i < N; i++) { for(unsigned imu = 0; imu <= intr.nsteps (); imu += 1) { gr_complex expected = test_fcn((i + 3) + imu * inv_nsteps); gr_complex actual = intr.interpolate(&input[i], imu * inv_nsteps); CPPUNIT_ASSERT_COMPLEXES_EQUAL(expected, actual, 0.004); // printf ("%9.6f %9.6f %9.6f\n", expected, actual, expected - actual); } } } void qa_mmse_fir_interpolator_cc::t2() { CPPUNIT_ASSERT_THROW(t2_body(), std::invalid_argument); } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_filter.cc0000644000175000017500000000316112021532024020230 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This class gathers together all the test cases for the gr-filter * directory into a single test suite. As you create new test cases, * add them here. */ #include #include #include #include #include CppUnit::TestSuite * qa_gr_filter::suite () { CppUnit::TestSuite *s = new CppUnit::TestSuite ("gr-filter"); s->addTest(gr::filter::qa_firdes::suite()); s->addTest(gr::filter::fff::qa_fir_filter_with_buffer_fff::suite()); s->addTest(gr::filter::ccc::qa_fir_filter_with_buffer_ccc::suite()); s->addTest(gr::filter::ccf::qa_fir_filter_with_buffer_ccf::suite()); s->addTest(gr::filter::qa_mmse_fir_interpolator_cc::suite()); s->addTest(gr::filter::qa_mmse_fir_interpolator_ff::suite()); return s; } gnuradio-3.7.2.1/gr-filter/lib/interp_fir_filter_XXX_impl.h.t0000664000175000017500000000331212207440367023702 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include namespace gr { namespace filter { class FILTER_API @IMPL_NAME@ : public @BASE_NAME@ { private: bool d_updated; std::vector d_firs; std::vector<@TAP_TYPE@> d_new_taps; void install_taps(const std::vector<@TAP_TYPE@> &taps); public: @IMPL_NAME@(unsigned interpolation, const std::vector<@TAP_TYPE@> &taps); ~@IMPL_NAME@(); void set_taps(const std::vector<@TAP_TYPE@> &taps); std::vector<@TAP_TYPE@> taps() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/lib/iir_filter_ffd_impl.h0000664000175000017500000000334312207440367022136 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_IIR_FILTER_FFD_IMPL_H #define INCLUDED_IIR_FILTER_FFD_IMPL_H #include #include namespace gr { namespace filter { class FILTER_API iir_filter_ffd_impl : public iir_filter_ffd { private: bool d_updated; kernel::iir_filter *d_iir; std::vector d_new_fftaps; std::vector d_new_fbtaps; public: iir_filter_ffd_impl(const std::vector &fftaps, const std::vector &fbtaps, bool oldstyle=true); ~iir_filter_ffd_impl(); void set_taps(const std::vector &fftaps, const std::vector &fbtaps); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_IIR_FILTER_FFD_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/fractional_resampler_ff_impl.cc0000664000175000017500000001003012207702530024154 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "fractional_resampler_ff_impl.h" #include namespace gr { namespace filter { fractional_resampler_ff::sptr fractional_resampler_ff::make(float phase_shift, float resamp_ratio) { return gnuradio::get_initial_sptr (new fractional_resampler_ff_impl(phase_shift, resamp_ratio)); } fractional_resampler_ff_impl::fractional_resampler_ff_impl (float phase_shift, float resamp_ratio) : block("fractional_resampler_ff", io_signature::make(1, 2, sizeof(float)), io_signature::make(1, 1, sizeof(float))), d_mu (phase_shift), d_mu_inc (resamp_ratio), d_resamp(new mmse_fir_interpolator_ff()) { if(resamp_ratio <= 0) throw std::out_of_range("resampling ratio must be > 0"); if(phase_shift < 0 || phase_shift > 1) throw std::out_of_range("phase shift ratio must be > 0 and < 1"); set_relative_rate(1.0 / resamp_ratio); } fractional_resampler_ff_impl::~fractional_resampler_ff_impl() { delete d_resamp; } void fractional_resampler_ff_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) { ninput_items_required[i] = (int)ceil((noutput_items * d_mu_inc) + d_resamp->ntaps()); } } int fractional_resampler_ff_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; int ii = 0; // input index int oo = 0; // output index if(ninput_items.size() == 1) { while(oo < noutput_items) { out[oo++] = d_resamp->interpolate(&in[ii], d_mu); double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } consume_each(ii); return noutput_items; } else { const float *rr = (const float*)input_items[1]; while(oo < noutput_items) { out[oo++] = d_resamp->interpolate(&in[ii], d_mu); d_mu_inc = rr[ii]; double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } set_relative_rate(1.0 / d_mu_inc); consume_each(ii); return noutput_items; } } float fractional_resampler_ff_impl::mu() const { return d_mu; } float fractional_resampler_ff_impl::resamp_ratio() const { return d_mu_inc; } void fractional_resampler_ff_impl::set_mu(float mu) { d_mu = mu; } void fractional_resampler_ff_impl::set_resamp_ratio(float resamp_ratio) { d_mu_inc = resamp_ratio; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/filter_delay_fc_impl.h0000664000175000017500000000327212207440367022303 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FILTER_DELAY_FC_IMPL_H #define INCLUDED_FILTER_FILTER_DELAY_FC_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API filter_delay_fc_impl : public filter_delay_fc { private: unsigned int d_delay; kernel::fir_filter_fff *d_fir; std::vector d_taps; bool d_update; public: filter_delay_fc_impl(const std::vector &taps); ~filter_delay_fc_impl(); std::vector taps(); void set_taps(const std::vector &taps); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FILTER_DELAY_FC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/qa_mmse_fir_interpolator_ff.h0000644000175000017500000000247412021532024023671 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_MMSE_FIR_INTERPOLATOR_FF_H_ #define _QA_MMSE_FIR_INTERPOLATOR_FF_H_ #include #include namespace gr { namespace filter { class qa_mmse_fir_interpolator_ff : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_mmse_fir_interpolator_ff); CPPUNIT_TEST(t1); CPPUNIT_TEST_SUITE_END(); private: void t1(); }; } /* namespace filter */ } /* namespace gr */ #endif /* _QA_MMSE_FIR_INTERPOLATOR_FF_H_ */ gnuradio-3.7.2.1/gr-filter/lib/single_pole_iir_filter_ff_impl.h0000664000175000017500000000327112207440367024352 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SINGLE_POLE_IIR_FILTER_FF_IMPL_H #define INCLUDED_SINGLE_POLE_IIR_FILTER_FF_IMPL_H #include #include #include #include namespace gr { namespace filter { class FILTER_API single_pole_iir_filter_ff_impl : public single_pole_iir_filter_ff { private: unsigned int d_vlen; std::vector > d_iir; public: single_pole_iir_filter_ff_impl(double alpha, unsigned int vlen); ~single_pole_iir_filter_ff_impl(); void set_taps(double alpha); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_SINGLE_POLE_IIR_FILTER_FF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/qa_mmse_fir_interpolator_ff.cc0000664000175000017500000000413412207440367024042 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include namespace gr { namespace filter { static float test_fcn(double index) { return (2 * sin(index * 0.25 * 2 * M_PI + 0.125 * M_PI) + 3 * sin(index * 0.077 * 2 * M_PI + 0.3 * M_PI)); } void qa_mmse_fir_interpolator_ff::t1() { // use aligned malloc and make sure that everything in this // buffer is properly initialized. static const unsigned N = 100; float *input = fft::malloc_float(N + 10); for(unsigned i = 0; i < N+10; i++) input[i] = test_fcn((double) i); mmse_fir_interpolator_ff intr; float inv_nsteps = 1.0 / intr.nsteps(); for(unsigned i = 0; i < N; i++) { for(unsigned imu = 0; imu <= intr.nsteps (); imu += 1) { float expected = test_fcn((i + 3) + imu * inv_nsteps); float actual = intr.interpolate(&input[i], imu * inv_nsteps); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected, actual, 0.004); // printf ("%9.6f %9.6f %9.6f\n", expected, actual, expected - actual); } } fft::free(input); } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/hilbert_fc_impl.h0000664000175000017500000000314612221050153021253 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_HILBERT_FC_IMPL_H #define INCLUDED_FILTER_HILBERT_FC_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API hilbert_fc_impl : public hilbert_fc { private: unsigned int d_ntaps; kernel::fir_filter_fff *d_hilb; public: hilbert_fc_impl(unsigned int ntaps, firdes::win_type window=firdes::WIN_HAMMING, double beta=6.76); ~hilbert_fc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_HILBERT_FC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/mmse_fir_interpolator_cc.cc0000664000175000017500000000374112207440367023356 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include namespace gr { namespace filter { mmse_fir_interpolator_cc::mmse_fir_interpolator_cc() { filters.resize (NSTEPS + 1); for(int i = 0; i < NSTEPS + 1; i++) { std::vector t (&taps[i][0], &taps[i][NTAPS]); filters[i] = new kernel::fir_filter_ccf(1, t); } } mmse_fir_interpolator_cc::~mmse_fir_interpolator_cc() { for(int i = 0; i < NSTEPS + 1; i++) delete filters[i]; } unsigned mmse_fir_interpolator_cc::ntaps() const { return NTAPS; } unsigned mmse_fir_interpolator_cc::nsteps() const { return NSTEPS; } gr_complex mmse_fir_interpolator_cc::interpolate(const gr_complex input[], float mu) const { int imu = (int)rint(mu * NSTEPS); if((imu < 0) || (imu > NSTEPS)) { throw std::runtime_error("mmse_fir_interpolator_cc: imu out of bounds.\n"); } gr_complex r = filters[imu]->filter(input); return r; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_synthesizer_ccf_impl.h0000664000175000017500000000532012207440367023215 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_SYNTHESIZER_CCF_IMPL_H #define INCLUDED_PFB_SYNTHESIZER_CCF_IMPL_H #include #include #include #include namespace gr { namespace filter { // While this is a polyphase_filterbank, we don't use the normal // parent class because we have to use the fir_filter_with_buffer // objects instead of normal filters. class FILTER_API pfb_synthesizer_ccf_impl : public pfb_synthesizer_ccf { private: bool d_updated; unsigned int d_numchans; unsigned int d_taps_per_filter; fft::fft_complex *d_fft; std::vector< kernel::fir_filter_with_buffer_ccf*> d_filters; std::vector< std::vector > d_taps; int d_state; std::vector d_channel_map; unsigned int d_twox; gr::thread::mutex d_mutex; // mutex to protect set/work access /*! * \brief Tap setting algorithm for critically sampled channels */ void set_taps1(const std::vector &taps); /*! * \brief Tap setting algorithm for 2x over-sampled channels */ void set_taps2(const std::vector &taps); public: pfb_synthesizer_ccf_impl(unsigned int numchans, const std::vector &taps, bool twox); ~pfb_synthesizer_ccf_impl(); void set_taps(const std::vector &taps); std::vector > taps() const; void print_taps(); void set_channel_map(const std::vector &map); std::vector channel_map() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_SYNTHESIZER_CCF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/pm_remez.cc0000664000175000017500000005671712220054710020123 0ustar jcorganjcorgan/************************************************************************** * Parks-McClellan algorithm for FIR filter design (C version) *------------------------------------------------- * Copyright (c) 1995,1998 Jake Janovetz (janovetz@uiuc.edu) * Copyright (c) 2004 Free Software Foundation, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301 USA * * * Sep 1999 - Paul Kienzle (pkienzle@cs.indiana.edu) * Modified for use in octave as a replacement for the matlab function * remez.mex. In particular, magnitude responses are required for all * band edges rather than one per band, griddensity is a parameter, * and errors are returned rather than printed directly. * Mar 2000 - Kai Habel (kahacjde@linux.zrz.tu-berlin.de) * Change: ColumnVector x=arg(i).vector_value(); * to: ColumnVector x(arg(i).vector_value()); * There appear to be some problems with the routine search. See comments * therein [search for PAK:]. I haven't looked closely at the rest * of the code---it may also have some problems. *************************************************************************/ /* * This code was extracted from octave.sf.net, and wrapped with * GNU Radio glue. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #ifndef LOCAL_BUFFER #include #define LOCAL_BUFFER(T, buf, size) \ std::vector buf ## _vector (size); \ T *buf = &(buf ## _vector[0]) #endif namespace gr { namespace filter { #define CONST const #define BANDPASS 1 #define DIFFERENTIATOR 2 #define HILBERT 3 #define NEGATIVE 0 #define POSITIVE 1 #define Pi 3.14159265358979323846 #define Pi2 (2*Pi) #define GRIDDENSITY 16 #define MAXITERATIONS 40 /******************* * create_dense_grid *================= * * Creates the dense grid of frequencies from the specified bands. * Also creates the Desired Frequency Response function (D[]) and * the Weight function (W[]) on that dense grid * * * INPUT: * ------ * int r - 1/2 the number of filter coefficients * int numtaps - Number of taps in the resulting filter * int numband - Number of bands in user specification * double bands[] - User-specified band edges [2*numband] * double des[] - Desired response per band [2*numband] * double weight[] - Weight per band [numband] * int symmetry - Symmetry of filter - used for grid check * int griddensity * * OUTPUT: * ------- * int gridsize - Number of elements in the dense frequency grid * double Grid[] - Frequencies (0 to 0.5) on the dense grid [gridsize] * double D[] - Desired response on the dense grid [gridsize] * double W[] - Weight function on the dense grid [gridsize] *******************/ static void create_dense_grid(int r, int numtaps, int numband, const double bands[], const double des[], const double weight[], int gridsize, double Grid[], double D[], double W[], int symmetry, int griddensity) { int i, j, k, band; double delf, lowf, highf, grid0; delf = 0.5/(griddensity*r); /* * For differentiator, hilbert, * symmetry is odd and Grid[0] = max(delf, bands[0]) */ grid0 = (symmetry == NEGATIVE) && (delf > bands[0]) ? delf : bands[0]; j=0; for(band=0; band < numband; band++) { lowf = (band==0 ? grid0 : bands[2*band]); highf = bands[2*band + 1]; k = (int)((highf - lowf)/delf + 0.5); /* .5 for rounding */ for(i=0; i (0.5 - delf)) && (numtaps % 2)) { Grid[gridsize-1] = 0.5-delf; } } /******************** * initial_guess *============== * Places Extremal Frequencies evenly throughout the dense grid. * * * INPUT: * ------ * int r - 1/2 the number of filter coefficients * int gridsize - Number of elements in the dense frequency grid * * OUTPUT: * ------- * int ext[] - Extremal indexes to dense frequency grid [r+1] ********************/ static void initial_guess(int r, int Ext[], int gridsize) { int i; for(i=0; i<=r; i++) Ext[i] = i * (gridsize-1) / r; } /*********************** * calc_parms *=========== * * * INPUT: * ------ * int r - 1/2 the number of filter coefficients * int Ext[] - Extremal indexes to dense frequency grid [r+1] * double Grid[] - Frequencies (0 to 0.5) on the dense grid [gridsize] * double D[] - Desired response on the dense grid [gridsize] * double W[] - Weight function on the dense grid [gridsize] * * OUTPUT: * ------- * double ad[] - 'b' in Oppenheim & Schafer [r+1] * double x[] - [r+1] * double y[] - 'C' in Oppenheim & Schafer [r+1] ***********************/ static void calc_parms(int r, int Ext[], double Grid[], double D[], double W[], double ad[], double x[], double y[]) { int i, j, k, ld; double sign, xi, delta, denom, numer; /* * Find x[] */ for(i = 0; i <= r; i++) x[i] = cos(Pi2 * Grid[Ext[i]]); /* * Calculate ad[] - Oppenheim & Schafer eq 7.132 */ ld = (r-1)/15 + 1; /* Skips around to avoid round errors */ for(i = 0; i <= r; i++) { denom = 1.0; xi = x[i]; for(j = 0; j < ld; j++) { for(k = j; k <= r; k += ld) if(k != i) denom *= 2.0*(xi - x[k]); } if(fabs(denom) < 0.00001) denom = 0.00001; ad[i] = 1.0/denom; } /* * Calculate delta - Oppenheim & Schafer eq 7.131 */ numer = denom = 0; sign = 1; for(i = 0; i <= r; i++) { numer += ad[i] * D[Ext[i]]; denom += sign * ad[i]/W[Ext[i]]; sign = -sign; } delta = numer/denom; sign = 1; /* * Calculate y[] - Oppenheim & Schafer eq 7.133b */ for(i = 0; i <= r; i++) { y[i] = D[Ext[i]] - sign * delta/W[Ext[i]]; sign = -sign; } } /********************* * compute_A *========== * Using values calculated in calc_parms, compute_A calculates the * actual filter response at a given frequency (freq). Uses * eq 7.133a from Oppenheim & Schafer. * * * INPUT: * ------ * double freq - Frequency (0 to 0.5) at which to calculate A * int r - 1/2 the number of filter coefficients * double ad[] - 'b' in Oppenheim & Schafer [r+1] * double x[] - [r+1] * double y[] - 'C' in Oppenheim & Schafer [r+1] * * OUTPUT: * ------- * Returns double value of A[freq] *********************/ static double compute_A(double freq, int r, double ad[], double x[], double y[]) { int i; double xc, c, denom, numer; denom = numer = 0; xc = cos(Pi2 * freq); for(i = 0; i <= r; i++) { c = xc - x[i]; if(fabs(c) < 1.0e-7) { numer = y[i]; denom = 1; break; } c = ad[i]/c; denom += c; numer += c*y[i]; } return numer/denom; } /************************ * calc_error *=========== * Calculates the Error function from the desired frequency response * on the dense grid (D[]), the weight function on the dense grid (W[]), * and the present response calculation (A[]) * * * INPUT: * ------ * int r - 1/2 the number of filter coefficients * double ad[] - [r+1] * double x[] - [r+1] * double y[] - [r+1] * int gridsize - Number of elements in the dense frequency grid * double Grid[] - Frequencies on the dense grid [gridsize] * double D[] - Desired response on the dense grid [gridsize] * double W[] - Weight function on the desnse grid [gridsize] * * OUTPUT: * ------- * double E[] - Error function on dense grid [gridsize] ************************/ static void calc_error(int r, double ad[], double x[], double y[], int gridsize, double Grid[], double D[], double W[], double E[]) { int i; double A; for(i = 0; i < gridsize; i++) { A = compute_A(Grid[i], r, ad, x, y); E[i] = W[i] * (D[i] - A); } } /************************ * search *======== * Searches for the maxima/minima of the error curve. If more than * r+1 extrema are found, it uses the following heuristic (thanks * Chris Hanson): * 1) Adjacent non-alternating extrema deleted first. * 2) If there are more than one excess extrema, delete the * one with the smallest error. This will create a non-alternation * condition that is fixed by 1). * 3) If there is exactly one excess extremum, delete the smaller * of the first/last extremum * * * INPUT: * ------ * int r - 1/2 the number of filter coefficients * int Ext[] - Indexes to Grid[] of extremal frequencies [r+1] * int gridsize - Number of elements in the dense frequency grid * double E[] - Array of error values. [gridsize] * OUTPUT: * ------- * int Ext[] - New indexes to extremal frequencies [r+1] ************************/ static int search(int r, int Ext[], int gridsize, double E[]) { int i, j, k, l, extra; /* Counters */ int up, alt; int *foundExt; /* Array of found extremals */ /* * Allocate enough space for found extremals. */ foundExt = (int *)malloc((2*r) * sizeof(int)); k = 0; /* * Check for extremum at 0. */ if(((E[0] > 0.0) && (E[0] > E[1])) || ((E[0] < 0.0) && (E[0] < E[1]))) foundExt[k++] = 0; /* * Check for extrema inside dense grid */ for(i = 1; i < gridsize-1; i++) { if(((E[i] >= E[i-1]) && (E[i] > E[i+1]) && (E[i] > 0.0)) || ((E[i] <= E[i-1]) && (E[i] < E[i+1]) && (E[i] < 0.0))) { // PAK: we sometimes get too many extremal frequencies if(k >= 2*r) { free(foundExt); return -3; } foundExt[k++] = i; } } /* * Check for extremum at 0.5 */ j = gridsize-1; if(((E[j] > 0.0) && (E[j] > E[j-1])) || ((E[j] < 0.0) && (E[j] < E[j-1]))) { if(k >= 2*r) { free(foundExt); return -3; } foundExt[k++] = j; } // PAK: we sometimes get not enough extremal frequencies if(k < r+1) { free(foundExt); return -2; } /* * Remove extra extremals */ extra = k - (r+1); assert(extra >= 0); while(extra > 0) { if(E[foundExt[0]] > 0.0) up = 1; /* first one is a maxima */ else up = 0; /* first one is a minima */ l=0; alt = 1; for(j = 1; j < k; j++) { if(fabs(E[foundExt[j]]) < fabs(E[foundExt[l]])) l = j; /* new smallest error. */ if((up) && (E[foundExt[j]] < 0.0)) up = 0; /* switch to a minima */ else if((!up) && (E[foundExt[j]] > 0.0)) up = 1; /* switch to a maxima */ else { alt = 0; // PAK: break now and you will delete the smallest overall // extremal. If you want to delete the smallest of the // pair of non-alternating extremals, then you must do: // // if(fabs(E[foundExt[j]]) < fabs(E[foundExt[j-1]])) l=j; // else l=j-1; break; /* Ooops, found two non-alternating */ } /* extrema. Delete smallest of them */ } /* if the loop finishes, all extrema are alternating */ /* * If there's only one extremal and all are alternating, * delete the smallest of the first/last extremals. */ if((alt) && (extra == 1)) { if(fabs(E[foundExt[k-1]]) < fabs(E[foundExt[0]])) /* Delete last extremal */ l = k-1; // PAK: changed from l = foundExt[k-1]; else /* Delete first extremal */ l = 0; // PAK: changed from l = foundExt[0]; } for(j = l; j < k-1; j++) { /* Loop that does the deletion */ foundExt[j] = foundExt[j+1]; assert(foundExt[j] max) max = current; } return(((max-min)/max) < 0.0001); } /******************** * remez *======= * Calculates the optimal (in the Chebyshev/minimax sense) * FIR filter impulse response given a set of band edges, * the desired reponse on those bands, and the weight given to * the error in those bands. * * INPUT: * ------ * int numtaps - Number of filter coefficients * int numband - Number of bands in filter specification * double bands[] - User-specified band edges [2 * numband] * double des[] - User-specified band responses [2 * numband] * double weight[] - User-specified error weights [numband] * int type - Type of filter * * OUTPUT: * ------- * double h[] - Impulse response of final filter [numtaps] * returns - true on success, false on failure to converge ********************/ static int remez(double h[], int numtaps, int numband, const double bands[], const double des[], const double weight[], int type, int griddensity) { double *Grid, *W, *D, *E; int i, iter, gridsize, r, *Ext; double *taps, c; double *x, *y, *ad; int symmetry; if(type == BANDPASS) symmetry = POSITIVE; else symmetry = NEGATIVE; r = numtaps/2; /* number of extrema */ if((numtaps % 2) && (symmetry == POSITIVE)) r++; /* * Predict dense grid size in advance for memory allocation * .5 is so we round up, not truncate */ gridsize = 0; for(i = 0; i < numband; i++) { gridsize +=(int)(2*r*griddensity*(bands[2*i+1] - bands[2*i]) + .5); } if(symmetry == NEGATIVE) { gridsize--; } /* * Dynamically allocate memory for arrays with proper sizes */ Grid = (double *)malloc(gridsize * sizeof(double)); D = (double *)malloc(gridsize * sizeof(double)); W = (double *)malloc(gridsize * sizeof(double)); E = (double *)malloc(gridsize * sizeof(double)); Ext = (int *)malloc((r+1) * sizeof(int)); taps = (double *)malloc((r+1) * sizeof(double)); x = (double *)malloc((r+1) * sizeof(double)); y = (double *)malloc((r+1) * sizeof(double)); ad = (double *)malloc((r+1) * sizeof(double)); /* * Create dense frequency grid */ create_dense_grid(r, numtaps, numband, bands, des, weight, gridsize, Grid, D, W, symmetry, griddensity); initial_guess(r, Ext, gridsize); /* * For Differentiator: (fix grid) */ if(type == DIFFERENTIATOR) { for(i = 0; i < gridsize; i++) { /* D[i] = D[i]*Grid[i]; */ if(D[i] > 0.0001) W[i] = W[i]/Grid[i]; } } /* * For odd or Negative symmetry filters, alter the * D[] and W[] according to Parks McClellan */ if(symmetry == POSITIVE) { if(numtaps % 2 == 0) { for(i = 0; i < gridsize; i++) { c = cos(Pi * Grid[i]); D[i] /= c; W[i] *= c; } } } else { if(numtaps % 2) { for(i = 0; i < gridsize; i++) { c = sin(Pi2 * Grid[i]); D[i] /= c; W[i] *= c; } } else { for(i = 0; i < gridsize; i++) { c = sin(Pi * Grid[i]); D[i] /= c; W[i] *= c; } } } /* * Perform the Remez Exchange algorithm */ for(iter = 0; iter < MAXITERATIONS; iter++) { calc_parms(r, Ext, Grid, D, W, ad, x, y); calc_error(r, ad, x, y, gridsize, Grid, D, W, E); int err = search(r, Ext, gridsize, E); if(err) { free(Grid); free(W); free(D); free(E); free(Ext); free(taps); free(x); free(y); free(ad); return err; } for(int i = 0; i <= r; i++) assert(Ext[i] < gridsize); if(is_done(r, Ext, E)) break; } calc_parms(r, Ext, Grid, D, W, ad, x, y); /* * Find the 'taps' of the filter for use with Frequency * Sampling. If odd or Negative symmetry, fix the taps * according to Parks McClellan */ for(i = 0; i <= numtaps/2; i++) { if(symmetry == POSITIVE) { if(numtaps % 2) c = 1; else c = cos(Pi * (double)i/numtaps); } else { if(numtaps % 2) c = sin(Pi2 * (double)i/numtaps); else c = sin(Pi * (double)i/numtaps); } taps[i] = compute_A((double)i/numtaps, r, ad, x, y)*c; } /* * Frequency sampling design with calculated taps */ freq_sample(numtaps, taps, h, symmetry); /* * Delete allocated memory */ free(Grid); free(W); free(D); free(E); free(Ext); free(taps); free(x); free(y); free(ad); return iter pm_remez(int order, const std::vector &arg_bands, const std::vector &arg_response, const std::vector &arg_weight, const std::string filter_type, int grid_density ) throw (std::runtime_error) { int numtaps = order + 1; if(numtaps < 4) punt("gr_remez: number of taps must be >= 3"); int numbands = arg_bands.size() / 2; LOCAL_BUFFER(double, bands, numbands * 2); if(numbands < 1 || arg_bands.size() % 2 == 1) punt("gr_remez: must have an even number of band edges"); for(unsigned int i = 1; i < arg_bands.size(); i++){ if(arg_bands[i] < arg_bands[i-1]) punt("gr_remez: band edges must be nondecreasing"); } if(arg_bands[0] < 0 || arg_bands[arg_bands.size() - 1] > 1) punt("gr_remez: band edges must be in the range [0,1]"); // Divide by 2 to fit with the implementation that uses a // sample rate of [0, 0.5] instead of [0, 1.0] for(int i = 0; i < 2 * numbands; i++) bands[i] = arg_bands[i] / 2; LOCAL_BUFFER(double, response, numbands * 2); if(arg_response.size() != arg_bands.size()) punt("gr_remez: must have one response magnitude for each band edge"); for(int i = 0; i < 2 * numbands; i++) response[i] = arg_response[i]; LOCAL_BUFFER(double, weight, numbands); for(int i = 0; i < numbands; i++) weight[i] = 1.0; if(arg_weight.size() != 0) { if((int) arg_weight.size() != numbands) punt("gr_remez: need one weight for each band [=length(band)/2]"); for(int i = 0; i < numbands; i++) weight[i] = arg_weight [i]; } int itype = 0; if(filter_type == "bandpass") itype = BANDPASS; else if(filter_type == "differentiator") itype = DIFFERENTIATOR; else if(filter_type == "hilbert") itype = HILBERT; else punt("gr_remez: unknown ftype '" + filter_type + "'"); if(grid_density < 16) punt("gr_remez: grid_density is too low; must be >= 16"); LOCAL_BUFFER(double, coeff, numtaps + 5); // FIXME why + 5? int err = remez(coeff, numtaps, numbands, bands, response, weight, itype, grid_density); if(err == -1) punt("gr_remez: failed to converge"); if(err == -2) punt("gr_remez: insufficient extremals -- cannot continue"); if(err == -3) punt("gr_remez: too many extremals -- cannot continue"); return std::vector(&coeff[0], &coeff[numtaps]); } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_channelizer_ccf_impl.h0000664000175000017500000000431212207440367023130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_PFB_CHANNELIZER_CCF_IMPL_H #define INCLUDED_FILTER_PFB_CHANNELIZER_CCF_IMPL_H #include #include #include #include #include namespace gr { namespace filter { class FILTER_API pfb_channelizer_ccf_impl : public pfb_channelizer_ccf, kernel::polyphase_filterbank { private: bool d_updated; float d_oversample_rate; int *d_idxlut; int d_rate_ratio; int d_output_multiple; std::vector d_channel_map; gr::thread::mutex d_mutex; // mutex to protect set/work access public: pfb_channelizer_ccf_impl(unsigned int nfilts, const std::vector &taps, float oversample_rate); ~pfb_channelizer_ccf_impl(); void set_taps(const std::vector &taps); void print_taps(); std::vector > taps() const; void set_channel_map(const std::vector &map); std::vector channel_map() const; int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-filter/lib/hilbert_fc_impl.cc0000664000175000017500000000462112221050153021410 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "hilbert_fc_impl.h" #include #include namespace gr { namespace filter { hilbert_fc::sptr hilbert_fc::make(unsigned int ntaps, firdes::win_type window, double beta) { return gnuradio::get_initial_sptr (new hilbert_fc_impl(ntaps, window, beta)); } hilbert_fc_impl::hilbert_fc_impl(unsigned int ntaps, firdes::win_type window, double beta) : sync_block("hilbert_fc", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))), d_ntaps(ntaps | 0x1) // ensure ntaps is odd { d_hilb = new kernel::fir_filter_fff(1, firdes::hilbert(d_ntaps, window, beta)); set_history(d_ntaps); const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } hilbert_fc_impl::~hilbert_fc_impl() { delete d_hilb; } int hilbert_fc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *in = (float *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = gr_complex(in[i + d_ntaps/2], d_hilb->filter(&in[i])); } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/single_pole_iir_filter_ff_impl.cc0000664000175000017500000000457512207440367024520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "single_pole_iir_filter_ff_impl.h" #include namespace gr { namespace filter { single_pole_iir_filter_ff::sptr single_pole_iir_filter_ff::make(double alpha, unsigned int vlen) { return gnuradio::get_initial_sptr (new single_pole_iir_filter_ff_impl(alpha, vlen)); } single_pole_iir_filter_ff_impl::single_pole_iir_filter_ff_impl (double alpha, unsigned int vlen) : sync_block("single_pole_iir_filter_ff", io_signature::make(1, 1, sizeof(float)*vlen), io_signature::make(1, 1, sizeof(float)*vlen)), d_vlen(vlen), d_iir(vlen) { set_taps(alpha); } single_pole_iir_filter_ff_impl::~single_pole_iir_filter_ff_impl() { } void single_pole_iir_filter_ff_impl::set_taps(double alpha) { for(unsigned int i = 0; i < d_vlen; i++) { d_iir[i].set_taps(alpha); } } int single_pole_iir_filter_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; unsigned int vlen = d_vlen; if(d_vlen == 1) { for(int i = 0; i < noutput_items; i++) { out[i] = d_iir[0].filter (in[i]); } } else { for(int i = 0; i < noutput_items; i++) { for(unsigned int j = 0; j < vlen; j++) { *out++ = d_iir[j].filter(*in++); } } } return noutput_items; }; } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/test_gr_filter.cc0000664000175000017500000000257112207440367021322 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include int main (int argc, char **argv) { CppUnit::TextTestRunner runner; std::ofstream xmlfile(get_unittest_path("gr_filter.xml").c_str()); CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); runner.addTest(qa_gr_filter::suite()); runner.setOutputter(xmlout); bool was_successful = runner.run("", false); return was_successful ? 0 : 1; } gnuradio-3.7.2.1/gr-filter/lib/pfb_arb_resampler.cc0000664000175000017500000003745112207440367021760 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include namespace gr { namespace filter { namespace kernel { pfb_arb_resampler_ccf::pfb_arb_resampler_ccf(float rate, const std::vector &taps, unsigned int filter_size) { d_acc = 0; // start accumulator at 0 /* The number of filters is specified by the user as the filter size; this is also the interpolation rate of the filter. We use it and the rate provided to determine the decimation rate. This acts as a rational resampler. The flt_rate is calculated as the residual between the integer decimation rate and the real decimation rate and will be used to determine to interpolation point of the resampling process. */ d_int_rate = filter_size; set_rate(rate); d_last_filter = (taps.size()/2) % filter_size; d_filters = std::vector(d_int_rate); d_diff_filters = std::vector(d_int_rate); // Create an FIR filter for each channel and zero out the taps std::vector vtaps(0, d_int_rate); for(unsigned int i = 0; i < d_int_rate; i++) { d_filters[i] = new fir_filter_ccf(1, vtaps); d_diff_filters[i] = new fir_filter_ccf(1, vtaps); } // Now, actually set the filters' taps set_taps(taps); // Delay is based on number of taps per filter arm. Round to // the nearest integer. float delay = -rate * (taps_per_filter() - 1.0) / 2.0; d_delay = static_cast(boost::math::iround(delay)); // This calculation finds the phase offset induced by the // arbitrary resampling. It's based on which filter arm we are // at the filter's group delay plus the fractional offset // between the samples. Calculated here based on the rotation // around nfilts starting at start_filter. float accum = -d_delay * d_flt_rate; int accum_int = static_cast(accum); float accum_frac = accum - accum_int; int end_filter = static_cast (boost::math::iround(fmodf(d_last_filter - d_delay * d_dec_rate + accum_int, \ static_cast(d_int_rate)))); d_est_phase_change = d_last_filter - (end_filter + accum_frac); } pfb_arb_resampler_ccf::~pfb_arb_resampler_ccf() { for(unsigned int i = 0; i < d_int_rate; i++) { delete d_filters[i]; delete d_diff_filters[i]; } } void pfb_arb_resampler_ccf::create_taps(const std::vector &newtaps, std::vector< std::vector > &ourtaps, std::vector &ourfilter) { unsigned int ntaps = newtaps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_int_rate); // Create d_numchan vectors to store each channel's taps ourtaps.resize(d_int_rate); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = newtaps; while((float)(tmp_taps.size()) < d_int_rate*d_taps_per_filter) { tmp_taps.push_back(0.0); } for(unsigned int i = 0; i < d_int_rate; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out ourtaps[i] = std::vector(d_taps_per_filter, 0); for(unsigned int j = 0; j < d_taps_per_filter; j++) { ourtaps[i][j] = tmp_taps[i + j*d_int_rate]; } // Build a filter for each channel and add it's taps to it ourfilter[i]->set_taps(ourtaps[i]); } } void pfb_arb_resampler_ccf::create_diff_taps(const std::vector &newtaps, std::vector &difftaps) { // Calculate the differential taps using a derivative filter std::vector diff_filter(2); diff_filter[0] = -1; diff_filter[1] = 1; for(unsigned int i = 0; i < newtaps.size()-1; i++) { float tap = 0; for(unsigned int j = 0; j < diff_filter.size(); j++) { tap += diff_filter[j]*newtaps[i+j]; } difftaps.push_back(tap); } difftaps.push_back(0); } void pfb_arb_resampler_ccf::set_taps(const std::vector &taps) { std::vector dtaps; create_diff_taps(taps, dtaps); create_taps(taps, d_taps, d_filters); create_taps(dtaps, d_dtaps, d_diff_filters); } std::vector > pfb_arb_resampler_ccf::taps() const { return d_taps; } void pfb_arb_resampler_ccf::print_taps() { unsigned int i, j; for(i = 0; i < d_int_rate; i++) { printf("filter[%d]: [", i); for(j = 0; j < d_taps_per_filter; j++) { printf(" %.4e", d_taps[i][j]); } printf("]\n"); } } void pfb_arb_resampler_ccf::set_rate(float rate) { d_dec_rate = (unsigned int)floor(d_int_rate/rate); d_flt_rate = (d_int_rate/rate) - d_dec_rate; } void pfb_arb_resampler_ccf::set_phase(float ph) { if((ph < 0) || (ph >= 2.0*M_PI)) { throw std::runtime_error("pfb_arb_resampler_ccf: set_phase value out of bounds [0, 2pi).\n"); } float ph_diff = 2.0*M_PI / (float)d_filters.size(); d_last_filter = static_cast(ph / ph_diff); } float pfb_arb_resampler_ccf::phase() const { float ph_diff = 2.0*M_PI / static_cast(d_filters.size()); return d_last_filter * ph_diff; } unsigned int pfb_arb_resampler_ccf::taps_per_filter() const { return d_taps_per_filter; } float pfb_arb_resampler_ccf::phase_offset(float freq, float fs) { float adj = (2.0*M_PI)*(freq/fs)/static_cast(d_int_rate); return -adj * d_est_phase_change; } int pfb_arb_resampler_ccf::filter(gr_complex *output, gr_complex *input, int n_to_read, int &n_read) { int i_out = 0, i_in = 0; unsigned int j = d_last_filter;; gr_complex o0, o1; while(i_in < n_to_read) { // start j by wrapping around mod the number of channels while(j < d_int_rate) { // Take the current filter and derivative filter output o0 = d_filters[j]->filter(&input[i_in]); o1 = d_diff_filters[j]->filter(&input[i_in]); output[i_out] = o0 + o1*d_acc; // linearly interpolate between samples i_out++; // Adjust accumulator and index into filterbank d_acc += d_flt_rate; j += d_dec_rate + (int)floor(d_acc); d_acc = fmodf(d_acc, 1.0); } i_in += (int)(j / d_int_rate); j = j % d_int_rate; } d_last_filter = j; // save last filter state for re-entry n_read = i_in; // return how much we've actually read return i_out; // return how much we've produced } /****************************************************************/ pfb_arb_resampler_fff::pfb_arb_resampler_fff(float rate, const std::vector &taps, unsigned int filter_size) { d_acc = 0; // start accumulator at 0 /* The number of filters is specified by the user as the filter size; this is also the interpolation rate of the filter. We use it and the rate provided to determine the decimation rate. This acts as a rational resampler. The flt_rate is calculated as the residual between the integer decimation rate and the real decimation rate and will be used to determine to interpolation point of the resampling process. */ d_int_rate = filter_size; set_rate(rate); d_last_filter = (taps.size()/2) % filter_size; d_filters = std::vector(d_int_rate); d_diff_filters = std::vector(d_int_rate); // Create an FIR filter for each channel and zero out the taps std::vector vtaps(0, d_int_rate); for(unsigned int i = 0; i < d_int_rate; i++) { d_filters[i] = new fir_filter_fff(1, vtaps); d_diff_filters[i] = new fir_filter_fff(1, vtaps); } // Now, actually set the filters' taps set_taps(taps); // Delay is based on number of taps per filter arm. Round to // the nearest integer. float delay = -rate * (taps_per_filter() - 1.0) / 2.0; d_delay = static_cast(boost::math::iround(delay)); // This calculation finds the phase offset induced by the // arbitrary resampling. It's based on which filter arm we are // at the filter's group delay plus the fractional offset // between the samples. Calculated here based on the rotation // around nfilts starting at start_filter. float accum = -d_delay * d_flt_rate; int accum_int = static_cast(accum); float accum_frac = accum - accum_int; int end_filter = static_cast (boost::math::iround(fmodf(d_last_filter - d_delay * d_dec_rate + accum_int, \ static_cast(d_int_rate)))); d_est_phase_change = d_last_filter - (end_filter + accum_frac); } pfb_arb_resampler_fff::~pfb_arb_resampler_fff() { for(unsigned int i = 0; i < d_int_rate; i++) { delete d_filters[i]; delete d_diff_filters[i]; } } void pfb_arb_resampler_fff::create_taps(const std::vector &newtaps, std::vector< std::vector > &ourtaps, std::vector &ourfilter) { unsigned int ntaps = newtaps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_int_rate); // Create d_numchan vectors to store each channel's taps ourtaps.resize(d_int_rate); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = newtaps; while((float)(tmp_taps.size()) < d_int_rate*d_taps_per_filter) { tmp_taps.push_back(0.0); } for(unsigned int i = 0; i < d_int_rate; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out ourtaps[i] = std::vector(d_taps_per_filter, 0); for(unsigned int j = 0; j < d_taps_per_filter; j++) { ourtaps[i][j] = tmp_taps[i + j*d_int_rate]; } // Build a filter for each channel and add it's taps to it ourfilter[i]->set_taps(ourtaps[i]); } } void pfb_arb_resampler_fff::create_diff_taps(const std::vector &newtaps, std::vector &difftaps) { // Calculate the differential taps using a derivative filter std::vector diff_filter(2); diff_filter[0] = -1; diff_filter[1] = 1; for(unsigned int i = 0; i < newtaps.size()-1; i++) { float tap = 0; for(unsigned int j = 0; j < diff_filter.size(); j++) { tap += diff_filter[j]*newtaps[i+j]; } difftaps.push_back(tap); } difftaps.push_back(0); } void pfb_arb_resampler_fff::set_taps(const std::vector &taps) { std::vector dtaps; create_diff_taps(taps, dtaps); create_taps(taps, d_taps, d_filters); create_taps(dtaps, d_dtaps, d_diff_filters); } std::vector > pfb_arb_resampler_fff::taps() const { return d_taps; } void pfb_arb_resampler_fff::print_taps() { unsigned int i, j; for(i = 0; i < d_int_rate; i++) { printf("filter[%d]: [", i); for(j = 0; j < d_taps_per_filter; j++) { printf(" %.4e", d_taps[i][j]); } printf("]\n"); } } void pfb_arb_resampler_fff::set_rate(float rate) { d_dec_rate = (unsigned int)floor(d_int_rate/rate); d_flt_rate = (d_int_rate/rate) - d_dec_rate; } void pfb_arb_resampler_fff::set_phase(float ph) { if((ph < 0) || (ph >= 2.0*M_PI)) { throw std::runtime_error("pfb_arb_resampler_fff: set_phase value out of bounds [0, 2pi).\n"); } float ph_diff = 2.0*M_PI / (float)d_filters.size(); d_last_filter = static_cast(ph / ph_diff); } float pfb_arb_resampler_fff::phase() const { float ph_diff = 2.0*M_PI / static_cast(d_filters.size()); return d_last_filter * ph_diff; } unsigned int pfb_arb_resampler_fff::taps_per_filter() const { return d_taps_per_filter; } float pfb_arb_resampler_fff::phase_offset(float freq, float fs) { float adj = (2.0*M_PI)*(freq/fs)/static_cast(d_int_rate); return -adj * d_est_phase_change; } int pfb_arb_resampler_fff::filter(float *output, float *input, int n_to_read, int &n_read) { int i_out = 0, i_in = 0; unsigned int j = d_last_filter;; float o0, o1; while(i_in < n_to_read) { // start j by wrapping around mod the number of channels while(j < d_int_rate) { // Take the current filter and derivative filter output o0 = d_filters[j]->filter(&input[i_in]); o1 = d_diff_filters[j]->filter(&input[i_in]); output[i_out] = o0 + o1*d_acc; // linearly interpolate between samples i_out++; // Adjust accumulator and index into filterbank d_acc += d_flt_rate; j += d_dec_rate + (int)floor(d_acc); d_acc = fmodf(d_acc, 1.0); } i_in += (int)(j / d_int_rate); j = j % d_int_rate; } d_last_filter = j; // save last filter state for re-entry n_read = i_in; // return how much we've actually read return i_out; // return how much we've produced } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/dc_blocker_ff_impl.h0000664000175000017500000000375512207440367021740 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_DC_BLOCKER_FF_IMPL_H #define INCLUDED_FILTER_DC_BLOCKER_FF_IMPL_H #include #include namespace gr { namespace filter { class moving_averager_f { public: moving_averager_f(int D); ~moving_averager_f(); float filter(float x); float delayed_sig() { return d_out; } private: int d_length; float d_out, d_out_d1, d_out_d2; std::deque d_delay_line; }; class FILTER_API dc_blocker_ff_impl : public dc_blocker_ff { private: int d_length; bool d_long_form; moving_averager_f *d_ma_0; moving_averager_f *d_ma_1; moving_averager_f *d_ma_2; moving_averager_f *d_ma_3; std::deque d_delay_line; public: dc_blocker_ff_impl(int D, bool long_form); ~dc_blocker_ff_impl(); int group_delay(); //int set_length(int D); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_DC_BLOCKER_FF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/freq_xlating_fir_filter_XXX_impl.cc.t0000664000175000017500000001003212225565277025227 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * WARNING: This file is automatically generated by cmake. * Any changes made to this file will be overwritten. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@IMPL_NAME@.h" #include #include namespace gr { namespace filter { @BASE_NAME@::sptr @BASE_NAME@::make(int decimation, const std::vector<@TAP_TYPE@> &taps, double center_freq, double sampling_freq) { return gnuradio::get_initial_sptr(new @IMPL_NAME@ (decimation, taps, center_freq, sampling_freq)); } @IMPL_NAME@::@IMPL_NAME@(int decimation, const std::vector<@TAP_TYPE@> &taps, double center_freq, double sampling_freq) : sync_decimator("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@)), decimation), d_proto_taps(taps), d_center_freq(center_freq), d_sampling_freq(sampling_freq), d_updated(false) { std::vector dummy_taps; d_composite_fir = new kernel::@CFIR_TYPE@(decimation, dummy_taps); set_history(d_proto_taps.size()); build_composite_fir(); } @IMPL_NAME@::~@IMPL_NAME@() { delete d_composite_fir; } void @IMPL_NAME@::build_composite_fir() { std::vector ctaps(d_proto_taps.size()); // The basic principle of this block is to perform: // x(t) -> (mult by -fwT0) -> LPF -> decim -> y(t) // We switch things up here to: // x(t) -> BPF -> decim -> (mult by fwT0*decim) -> y(t) // The BPF is the baseband filter (LPF) moved up to the // center frequency fwT0. We then apply a derotator // with -fwT0 to downshift the signal to baseband. float fwT0 = 2 * M_PI * d_center_freq / d_sampling_freq; for(unsigned int i = 0; i < d_proto_taps.size(); i++) { ctaps[i] = d_proto_taps[i] * exp(gr_complex(0, i * fwT0)); } d_composite_fir->set_taps(ctaps); d_r.set_phase_incr(exp(gr_complex(0, -fwT0 * decimation()))); } void @IMPL_NAME@::set_center_freq(double center_freq) { d_center_freq = center_freq; d_updated = true; } double @IMPL_NAME@::center_freq() const { return d_center_freq; } void @IMPL_NAME@::set_taps(const std::vector<@TAP_TYPE@> &taps) { d_proto_taps = taps; d_updated = true; } std::vector<@TAP_TYPE@> @IMPL_NAME@::taps() const { return d_proto_taps; } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *in = (@I_TYPE@ *)input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[0]; // rebuild composite FIR if the center freq has changed if(d_updated) { set_history(d_proto_taps.size()); build_composite_fir(); d_updated = false; return 0; // history requirements may have changed. } unsigned j = 0; for (int i = 0; i < noutput_items; i++){ out[i] = d_r.rotate(d_composite_fir->filter(&in[j])); j += decimation(); } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_fir_filter_with_buffer.h0000644000175000017500000000424712021532024023324 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_FIR_FILTER_WITH_BUFFER_H_ #define _QA_FIR_FILTER_WITH_BUFFER_H_ #include #include namespace gr { namespace filter { namespace fff { class qa_fir_filter_with_buffer_fff : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fir_filter_with_buffer_fff); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void test_decimate(unsigned int decimate); void t1(); void t2(); void t3(); }; } /* namespace fff */ namespace ccc { class qa_fir_filter_with_buffer_ccc : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fir_filter_with_buffer_ccc); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void test_decimate(unsigned int decimate); void t1(); void t2(); void t3(); }; } /* namespace ccc */ namespace ccf { class qa_fir_filter_with_buffer_ccf : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fir_filter_with_buffer_ccf); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void test_decimate(unsigned int decimate); void t1(); void t2(); void t3(); }; } /* namespace ccf */ } /* namespace filter */ } /* namespace gr */ #endif /* _QA_FIR_FILTER_WITH_BUFFER_H_ */ gnuradio-3.7.2.1/gr-filter/lib/polyphase_filterbank.cc0000664000175000017500000000654512207440367022520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { namespace filter { namespace kernel { polyphase_filterbank::polyphase_filterbank(unsigned int nfilts, const std::vector &taps) : d_nfilts(nfilts) { d_filters = std::vector(d_nfilts); // Create an FIR filter for each channel and zero out the taps std::vector vtaps(0, d_nfilts); for(unsigned int i = 0; i < d_nfilts; i++) { d_filters[i] = new kernel::fir_filter_ccf(1, vtaps); } // Now, actually set the filters' taps set_taps(taps); // Create the FFT to handle the output de-spinning of the channels d_fft = new fft::fft_complex(d_nfilts, false); } polyphase_filterbank::~polyphase_filterbank() { delete d_fft; for(unsigned int i = 0; i < d_nfilts; i++) { delete d_filters[i]; } } void polyphase_filterbank::set_taps(const std::vector &taps) { unsigned int i,j; unsigned int ntaps = taps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_nfilts); // Create d_numchan vectors to store each channel's taps d_taps.resize(d_nfilts); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = taps; while((float)(tmp_taps.size()) < d_nfilts*d_taps_per_filter) { tmp_taps.push_back(0.0); } // Reverse taps here; set_taps in filter will then re-reverse, // but order them propely, anyways. std::reverse(tmp_taps.begin(), tmp_taps.end()); // Partition the filter for(i = 0; i < d_nfilts; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out d_taps[i] = std::vector(d_taps_per_filter, 0); for(j = 0; j < d_taps_per_filter; j++) { d_taps[i][j] = tmp_taps[i + j*d_nfilts]; } // Build a filter for each channel and add it's taps to it d_filters[i]->set_taps(d_taps[i]); } } void polyphase_filterbank::print_taps() { unsigned int i, j; for(i = 0; i < d_nfilts; i++) { printf("filter[%d]: [", i); for(j = 0; j < d_taps_per_filter; j++) { printf(" %.4e", d_taps[i][j]); } printf("]\n\n"); } } std::vector< std::vector > polyphase_filterbank::taps() const { return d_taps; } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fractional_interpolator_ff_impl.h0000664000175000017500000000361712207440367024572 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_INTERPOLATOR_FF_IMPL_H #define INCLUDED_FRACTIONAL_INTERPOLATOR_FF_IMPL_H #include #include namespace gr { namespace filter { class FILTER_API fractional_interpolator_ff_impl : public fractional_interpolator_ff { private: float d_mu; float d_mu_inc; mmse_fir_interpolator_ff *d_interp; public: fractional_interpolator_ff_impl(float phase_shift, float interp_ratio); ~fractional_interpolator_ff_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const; float interp_ratio() const; void set_mu(float mu); void set_interp_ratio(float interp_ratio); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_INTERPOLATOR_FF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/adaptive_fir_ccf_impl.h0000664000175000017500000000364012245466767022455 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_ADAPTIVE_FIR_CCF_IMPL_H #define INCLUDED_FILTER_ADAPTIVE_FIR_CCF_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API adaptive_fir_ccf_impl : public adaptive_fir_ccf, public kernel::adaptive_fir_ccf { private: std::vector d_new_taps; bool d_updated; protected: // Override to calculate error signal per output float error(const gr_complex &out); // Override to calculate new weight from old, corresponding input void update_tap(float &tap, const gr_complex &in); public: void set_taps(const std::vector &taps); std::vector taps(); adaptive_fir_ccf_impl(const char *name, int decimation, const std::vector &taps); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_ADAPTIVE_FIR_CCF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/single_pole_iir_filter_cc_impl.h0000664000175000017500000000334412207440367024345 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SINGLE_POLE_IIR_FILTER_CC_IMPL_H #define INCLUDED_SINGLE_POLE_IIR_FILTER_CC_IMPL_H #include #include #include #include #include namespace gr { namespace filter { class FILTER_API single_pole_iir_filter_cc_impl : public single_pole_iir_filter_cc { private: unsigned int d_vlen; std::vector > d_iir; public: single_pole_iir_filter_cc_impl(double alpha, unsigned int vlen); ~single_pole_iir_filter_cc_impl(); void set_taps(double alpha); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_SINGLE_POLE_IIR_FILTER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/0000775000175000017500000000000012207440367022374 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/simpson.h0000664000175000017500000000010312207440367024227 0ustar jcorganjcorgandouble qsimp (double (*func)(double), double a, double b); gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/gen_interpolator_taps.c0000664000175000017500000001050612207440367027144 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #define NSTEPS 10 // how many steps of mu are in the generated table #define MAX_NSTEPS 256 #define NTAPS 8 // # of taps in the interpolator #define MAX_NTAPS 128 extern void initpt (double x[], int ntaps); extern double objective (double x[], int *ntaps); extern double global_mu; extern double global_B; // fortran extern double prax2_ (double (fct)(double x[], int *ntaps), double initv[], int *ntaps, double result[]); static void usage (char *name) { fprintf (stderr, "usage: %s [-v] [-n ] [-t ] [-B ]\n", name); exit (1); } static void printline (double x[], int ntaps, int imu, int nsteps) { int i; printf (" { "); for (i = 0; i < ntaps; i++){ printf ("%12.5e", x[i]); if (i != ntaps - 1) printf (", "); else printf (" }, // %3d/%d\n", imu, nsteps); } } int main (int argc, char **argv) { double xx[MAX_NSTEPS+1][MAX_NTAPS]; int ntaps = NTAPS; int nsteps = NSTEPS; int i, j; double result; double step_size; int c; int verbose = 0; global_B = 0.25; while ((c = getopt (argc, argv, "n:t:B:v")) != EOF){ switch (c){ case 'n': nsteps = strtol (optarg, 0, 0); break; case 't': ntaps = strtol (optarg, 0, 0); break; case 'B': global_B = strtod (optarg, 0); break; case 'v': verbose = 1; break; default: usage (argv[0]); break; } } if ((nsteps & 1) != 0){ fprintf (stderr, "%s: nsteps must be even\n", argv[0]); exit (1); } if (nsteps > MAX_NSTEPS){ fprintf (stderr, "%s: nsteps must be < %d\n", argv[0], MAX_NSTEPS); exit (1); } if ((ntaps & 1) != 0){ fprintf (stderr, "%s: ntaps must be even\n", argv[0]); exit (1); } if (nsteps > MAX_NTAPS){ fprintf (stderr, "%s: ntaps must be < %d\n", argv[0], MAX_NTAPS); exit (1); } if (global_B < 0 || global_B > 0.5){ fprintf (stderr, "%s: bandwidth must be in the range (0, 0.5)\n", argv[0]); exit (1); } step_size = 1.0/nsteps; // the optimizer chokes on the two easy cases (0/N and N/N). We do them by hand... for (i = 0; i < ntaps; i++) xx[0][i] = 0.0; xx[0][ntaps/2] = 1.0; // compute optimal values for mu <= 0.5 for (j = 1; j <= nsteps/2; j++){ global_mu = j * step_size; // this determines the MU for which we're computing the taps // initialize X to a reasonable starting value initpt (&xx[j][0], ntaps); // find the value of X that minimizes the value of OBJECTIVE result = prax2_ (objective, &xx[j][0], &ntaps, &xx[j][0]); if (verbose){ fprintf (stderr, "Mu: %10.8f\t", global_mu); fprintf (stderr, "Objective: %g\n", result); } } // now compute remaining values via symmetry for (j = 0; j < nsteps/2; j++){ for (i = 0; i < ntaps; i++){ xx[nsteps - j][i] = xx[j][ntaps-i-1]; } } // now print out the table printf ("\ /*\n\ * This file was machine generated by gen_interpolator_taps.\n\ * DO NOT EDIT BY HAND.\n\ */\n\n"); printf ("static const int NTAPS = %4d;\n", ntaps); printf ("static const int NSTEPS = %4d;\n", nsteps); printf ("static const double BANDWIDTH = %g;\n\n", global_B); printf ("static const float taps[NSTEPS+1][NTAPS] = {\n"); printf (" // -4 -3 -2 -1 0 1 2 3 mu\n"); for (i = 0; i <= nsteps; i++) printline (xx[i], ntaps, i, nsteps); printf ("};\n\n"); return 0; } gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/praxis.f0000664000175000017500000011405612207440367024060 0ustar jcorganjcorganC C Copyright 2002 Free Software Foundation, Inc. C C This file is part of GNU Radio C C GNU Radio is free software; you can redistribute it and/or modify C it under the terms of the GNU General Public License as published by C the Free Software Foundation; either version 3, or (at your option) C any later version. C C GNU Radio is distributed in the hope that it will be useful, C but WITHOUT ANY WARRANTY; without even the implied warranty of C MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the C GNU General Public License for more details. C C You should have received a copy of the GNU General Public License C along with GNU Radio; see the file COPYING. If not, write to C the Free Software Foundation, Inc., 51 Franklin Street, C Boston, MA 02110-1301, USA. C DOUBLE PRECISION FUNCTION PRAX2(F,INITV,NDIM,OUT) DOUBLE PRECISION INITV(128),OUT(128), F INTEGER NDIM EXTERNAL F C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C N=NDIM do 10 I=1,N 10 X(I) = INITV(I) C call praset C -1 produces no diagnostic output jprint = -1 nfmax = 3000 C tighter tolerance T=1.0D-6 C call praxis(f) C do 30 I=1,N 30 OUT(I) = X(I) C prax2 = fx return end SUBROUTINE PRASET C C PRASET 1.0 JUNE 1995 C C SET INITIAL VALUES FOR SOME QUANTITIES USED IN SUBROUTINE PRAXIS. C THE USER CAN RESET THESE, IF DESIRED, C AFTER CALLING PRASET AND BEFORE CALLING PRAXIS. C C J. P. CHANDLER, COMPUTER SCIENCE DEPARTMENT, C OKLAHOMA STATE UNIVERSITY C C ON MANY MACHINES, SUBROUTINE PRAXIS WILL CAUSE UNDERFLOW AND/OR C DIVIDE CHECK WHEN COMPUTING EPSMCH**4 AND EPSMCH**(-4). C IN THAT CASE, SET EPSMCH=1.0D-9 (OR POSSIBLY EPSMCH=1.0D-8) C AFTER CALLING SUBROUTINE PRASET. C INTEGER N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH INTEGER J C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD DOUBLE PRECISION A,B,XMID,XPLUS,RZERO,UNITR,RTWO C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C RZERO=0.0D0 UNITR=1.0D0 RTWO=2.0D0 C C NMAX IS THE DIMENSION OF THE ARRAYS V(*,*), X(*), D(*), C Q0(*), AND Q1(*). C NMAX=128 C C NFMAX IS THE MAXIMUM NUMBER OF FUNCTION EVALUATIONS PERMITTED. C NFMAX=100000 C C LP IS THE LOGICAL UNIT NUMBER FOR PRINTED OUTPUT. C LP=6 C C T IS A CONVERGENCE TOLERANCE USED IN SUBROUTINE PRAXIS. C T=1.0D-5 C C JPRINT CONTROLS PRINTED OUTPUT IN PRAXIS. C JPRINT=4 C C H IS AN ESTIMATE OF THE DISTANCE FROM THE INITIAL POINT C TO THE SOLUTION. C H=1.0D0 C C USE BISECTION TO COMPUTE THE VALUE OF EPSMCH, "MACHINE EPSILON". C EPSMCH IS THE SMALLEST FLOATING POINT (REAL OR DOUBLE PRECISION) C NUMBER WHICH, WHEN ADDED TO ONE, GIVES A RESULT GREATER THAN ONE. C A=RZERO B=UNITR 10 XMID=A+(B-A)/RTWO IF(XMID.LE.A .OR. XMID.GE.B) GO TO 20 XPLUS=UNITR+XMID IF(XPLUS.GT.UNITR) THEN B=XMID ELSE A=XMID ENDIF GO TO 10 C 20 EPSMCH=B C DO 30 J=1,NMAX X(J)=RZERO 30 CONTINUE C C JRANCH = 1 TO USE BRENT'S RANDOM, C JRANCH = 2 TO USE FUNCTION DRANDM. C JRANCH=1 C CALL RANINI(4.0D0) C C DSEED IS AN INITIAL SEED FOR DRANDM, C A SUBROUTINE THAT GENERATES PSEUDORANDOM NUMBERS C UNIFORMLY DISTRIBUTED ON (0,1). C DSEED=1234567.0D0 C C SCBD IS AN UPPER BOUND ON THE SCALE FACTORS IN PRAXIS. C IF THE AXES MAY BE BADLY SCALED (WHICH IS TO BE AVOIDED IF C POSSIBLE) THEN SET SCBD = 10, OTHERWISE 1. C SCBD=1.0D0 C C ILLCIN IS THE INITIAL VALUE OF ILLC, C THE FLAG THAT SIGNALS AN ILL-CONDITIONED PROBLEM. C IF THE PROBLEM IS KNOWN TO BE ILL-CONDITIONED SET ILLCIN=1, C OTHERWISE 0. C ILLCIN=0 C C KTM IS A CONVERGENCE SWITCH USED IN PRAXIS. C KTM+1 IS THE NUMBER OF ITERATIONS WITHOUT IMPROVEMENT C BEFORE THE ALGORITHM TERMINATES. C KTM=4 IS VERY CAUTIOUS. C USUALLY KTM=1 IS SATISFACTORY. C KTM=1 C RETURN C C END PRASET C END SUBROUTINE PRAXIS(F) C C PRAXIS 2.0 JUNE 1995 C C THE PRAXIS PACKAGE MINIMIZES THE FUNCTION F(X,N) OF N C VARIABLES X(1),...,X(N), USING THE PRINCIPAL AXIS METHOD. C F MUST BE A SMOOTH (CONTINUOUSLY DIFFERENTIABLE) FUNCTION. C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973 (ISBN 0-13-022335-2), C PAGES 156-167 C C TRANSLATED FROM ALGOL W TO A.N.S.I. 1966 STANDARD BASIC FORTRAN C BY ROSALEE TAYLOR AND SUE PINSKI, COMPUTER SCIENCE DEPARTMENT, C OKLAHOMA STATE UNIVERSITY (DECEMBER 1973). C C UPDATED TO A.N.S.I. STANDARD FORTRAN 77 BY J. P. CHANDLER C COMPUTER SCIENCE DEPARTMENT, OKLAHOMA STATE UNIVERSITY C C C SUBROUTINE PRAXIS CALLS SUBPROGRAMS C F, MINX, RANDOM (OR DRANDM), QUAD, MINFIT, SORT. C C SUBROUTINE QUAD CALLS MINX. C C SUBROUTINE MINX CALLS FLIN. C C SUBROUTINE FLIN CALLS F. C C C INPUT QUANTITIES (SET IN THE CALLING PROGRAM)... C C F FUNCTION F(X,N) TO BE MINIMIZED C C X(*) INITIAL GUESS OF MINIMUM C C N DIMENSION OF X (NOTE... N MUST BE .GE. 2) C C H MAXIMUM STEP SIZE C C T TOLERANCE C C EPSMCH MACHINE PRECISION C C JPRINT PRINT SWITCH C C C OUTPUT QUANTITIES... C C X(*) ESTIMATED POINT OF MINIMUM C C FX VALUE OF F AT X C C NL NUMBER OF LINEAR SEARCHES C C NF NUMBER OF FUNCTION EVALUATIONS C C V(*,*) EIGENVECTORS OF A C NEW DIRECTIONS C C D(*) EIGENVALUES OF A C NEW D C C Z(*) SCALE FACTORS C C C ON ENTRY X(*) HOLDS A GUESS. ON RETURN IT HOLDS THE ESTIMATED C POINT OF MINIMUM, WITH (HOPEFULLY) C ABS(ERROR) LESS THAN SQRT(EPSMCH)*ABS(X) + T, WHERE C EPSMCH IS THE MACHINE PRECISION, THE SMALLEST NUMBER SUCH THAT C (1 + EPSMCH) IS GREATER THAN 1. C C T IS A TOLERANCE. C C H IS THE MAXIMUM STEP SIZE, SET TO ABOUT THE MAXIMUM EXPECTED C DISTANCE FROM THE GUESS TO THE MINIMUM. IF H IS SET TOO C SMALL OR TOO LARGE THEN THE INITIAL RATE OF CONVERGENCE WILL C BE SLOW. C C THE USER SHOULD OBSERVE THE COMMENT ON HEURISTIC NUMBERS C AT THE BEGINNING OF THE SUBROUTINE. C C JPRINT CONTROLS THE PRINTING OF INTERMEDIATE RESULTS. C IT USES SUBROUTINES FLIN, MINX, QUAD, SORT, AND MINFIT. C IF JPRINT = 1, F IS PRINTED AFTER EVERY N+1 OR N+2 LINEAR C MINIMIZATIONS, AND FINAL X IS PRINTED, BUT INTERMEDIATE C X ONLY IF N IS LESS THAN OR EQUAL TO 4. C IF JPRINT = 2, EIGENVALUES OF A AND SCALE FACTORS ARE ALSO PRINTED. C IF JPRINT = 3, F AND X ARE PRINTED AFTER EVERY FEW LINEAR C MINIMIZATIONS. C IF JPRINT = 4, EIGENVECTORS ARE ALSO PRINTED. C IF JPRINT = 5, ADDITIONAL DEBUGGING INFORMATION IS ALSO PRINTED. C C RANDOM RETURNS A RANDOM NUMBER UNIFORMLY DISTRIBUTED IN (0, 1). C C THIS SUBROUTINE IS MACHINE-INDEPENDENT, APART FROM THE C SPECIFICATION OF EPSMCH. WE ASSUME THAT EPSMCH**(-4) DOES NOT C OVERFLOW (IF IT DOES THEN EPSMCH MUST BE INCREASED), AND THAT ON C FLOATING-POINT UNDERFLOW THE RESULT IS SET TO ZERO. C INTEGER N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH INTEGER ILLC,I,IK,IM,IMU,J,K,KL,KM1,KT,K2 C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD DOUBLE PRECISION F, Y,Z,E, DABS,DSQRT,ZABS,ZSQRT,DRANDM, * HUNDRD,HUNDTH,ONE,PT9,RHALF,TEN,TENTH,TWO,ZERO, * DF,DLDFAC,DN,F1,XF,XL,T2,RANVAL,ARG, * VLARGE,VSMALL,XLARGE,XLDS,FXVALU,F1VALU,S,SF,SL C EXTERNAL F C DIMENSION Y(128),Z(128),E(128) C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C ZABS(ARG)=DABS(ARG) ZSQRT(ARG)=DSQRT(ARG) C C INITIALIZATION... C RHALF=0.5D0 ONE=1.0D0 TENTH=0.1D0 HUNDTH=0.01D0 HUNDRD=100.0D0 ZERO=0.0D0 PT9=0.9D0 TEN=10.0D0 TWO=2.0D0 C C MACHINE DEPENDENT NUMBERS... C C ON MANY COMPUTERS, VSMALL WILL UNDERFLOW, C AND COMPUTING XLARGE MAY CAUSE A DIVISION BY ZERO. C IN THAT CASE, EPSMCH SHOULD BE SET EQUAL TO 1.0D-9 C (OR POSSIBLY 1.0D-8) BEFORE CALLING PRAXIS. C SMALL=EPSMCH*EPSMCH VSMALL=SMALL*SMALL XLARGE=ONE/SMALL VLARGE=ONE/VSMALL XM2=ZSQRT(EPSMCH) XM4=ZSQRT(XM2) C C HEURISTIC NUMBERS... C C IF THE AXES MAY BE BADLY SCALED (WHICH IS TO BE AVOIDED IF C POSSIBLE) THEN SET SCBD = 10, OTHERWISE 1. C C IF THE PROBLEM IS KNOWN TO BE ILL-CONDITIONED SET ILLC = 1, C OTHERWISE 0. C C KTM+1 IS THE NUMBER OF ITERATIONS WITHOUT IMPROVEMENT C BEFORE THE ALGORITHM TERMINATES. C KTM=4 IS VERY CAUTIOUS. C USUALLY KTM=1 IS SATISFACTORY. C C BRENT RECOMMENDED THE FOLLOWING VALUES FOR MOST PROBLEMS... C C SCBD=1.0 C ILLC=0 C KTM=1 C C SCBD, ILLCIN, AND KTM ARE NOW IN COMMON. C THEY ARE INITIALIZED IN SUBROUTINE PRASET, C AND CAN BE RESET BY THE USER AFTER CALLING PRASET. C ILLC=ILLCIN C IF(ILLC.EQ.1) THEN DLDFAC=TENTH ELSE DLDFAC=HUNDTH ENDIF C KT=0 NL=0 NF=1 FX=F(X,N) QF1=FX T=SMALL+ZABS(T) T2=T DMIN=SMALL IF(H.LT.HUNDRD*T) H=HUNDRD*T XLDT=H C DO 20 I=1,N DO 10 J=1,N V(I,J)=ZERO 10 CONTINUE V(I,I)=ONE 20 CONTINUE C QD0=ZERO D(1)=ZERO C C Q0(*) AND Q1(*) ARE PREVIOUS X(*) POINTS, C INITIALIZED IN PRAXIS, USED IN FLIN, C AND CHANGED IN QUAD. C DO 30 I=1,N Q1(I)=X(I) C C Q0(*) WAS NOT INITIALIZED IN BRENT'S ALGOL PROCEDURE. C Q0(I)=X(I) 30 CONTINUE C IF(JPRINT.GT.0) THEN WRITE(LP,40)NL,NF,FX 40 FORMAT(/' NL =',I10,5X,'NF =',I10/5X,'FX =',1PG15.7) C IF(N.LE.4 .OR. JPRINT.GT.2) THEN WRITE(LP,50)(X(I),I=1,N) 50 FORMAT(/8X,'X'/(1X,1PG15.7,4G15.7)) ENDIF ENDIF C C MAIN LOOP... C LABEL L0... C 60 SF=D(1) S=ZERO D(1)=ZERO C C MINIMIZE ALONG THE FIRST DIRECTION. C IF(JPRINT.GE.5) WRITE(LP,70)D(1),S,FX 70 FORMAT(/' CALL NO. 1 TO MINX.'/ * 5X,'D(1) =',1PG15.7,5X,'S =',G15.7,5X,'FX =',G15.7) C FXVALU=FX CALL MINX(1,2,D(1),S,FXVALU,0,F) C IF(S.LE.ZERO) THEN DO 80 I=1,N V(I,1)=-V(I,1) 80 CONTINUE ENDIF C IF(SF.LE.PT9*D(1) .OR. PT9*SF.GE.D(1)) THEN C IF(N.GE.2) THEN DO 90 I=2,N D(I)=ZERO 90 CONTINUE ENDIF C ENDIF C IF(N.LT.2) GO TO 320 DO 310 K=2,N C DO 100 I=1,N Y(I)=X(I) 100 CONTINUE C SF=FX IF(KT.GT.0) ILLC=1 C C LABEL L1... C 110 KL=K DF=ZERO C IF(ILLC.EQ.1) THEN C C TAKE A RANDOM STEP TO GET OUT OF A RESOLUTION VALLEY. C C PRAXIS ASSUMES THAT RANDOM (OR DRANDM) RETURNS C A PSEUDORANDOM NUMBER UNIFORMLY DISTRIBUTED IN (0,1), C AND THAT ANY INITIALIZATION OF THE RANDOM NUMBER GENERATOR C HAS ALREADY BEEN DONE. C DO 130 I=1,N C IF(JRANCH.EQ.1) THEN CALL RANDOM(RANVAL) ELSE RANVAL=DRANDM(DSEED) ENDIF C S=(TENTH*XLDT+T2*TEN**KT)*(RANVAL-RHALF) Z(I)=S C DO 120 J=1,N X(J)=X(J)+S*V(J,I) 120 CONTINUE 130 CONTINUE C FX=F(X,N) NF=NF+1 C IF(JPRINT.GE.1) WRITE(LP,140)NF,SF,FX 140 FORMAT(/' ***** RANDOM STEP IN PRAXIS. NF =',I11/ * 5X,'SF =',1PG15.7,5X,'FX =',G15.7) ENDIF C IF(K.GT.N) GO TO 170 DO 160 K2=K,N SL=FX S=ZERO C C MINIMIZE ALONG NON-CONJUGATE DIRECTIONS. C IF(JPRINT.GE.5) WRITE(LP,150)K2,D(K2),S,FX 150 FORMAT(/' CALL NO. 2 TO MINX.'/ * 5X,'K2 =',I4,5X,'D(K2) =',1PG15.7,5X, * 'S =',G15.7/5X,'FX =',G15.7) C FXVALU=FX CALL MINX(K2,2,D(K2),S,FXVALU,0,F) C IF(ILLC.EQ.1) THEN S=D(K2)*(S+Z(K2))**2 ELSE S=SL-FX ENDIF C IF(DF.LT.S) THEN DF=S KL=K2 ENDIF 160 CONTINUE C 170 IF(ILLC.EQ.0 .AND. DF.LT.ZABS(HUNDRD*EPSMCH*FX)) THEN C C NO SUCCESS WITH ILLC=0, SO TRY ONCE WITH ILLC=1 . C ILLC=1 C C GO TO L1. C GO TO 110 ENDIF C IF(K.EQ.2 .AND. JPRINT.GT.1) THEN WRITE(LP,180)(D(I),I=1,N) 180 FORMAT(/' NEW D'/(1X,1PG15.7,4G15.7)) ENDIF C KM1=K-1 IF(KM1.LT.1) GO TO 210 DO 200 K2=1,KM1 C C MINIMIZE ALONG CONJUGATE DIRECTIONS. C IF(JPRINT.GE.5) WRITE(LP,190)K2,D(K2),S,FX 190 FORMAT(/' CALL NO. 3 TO MINX.'/ * 5X,'K2 =',I4,5X,'D(K2) =',1PG15.7,5X, * 'S =',G15.7/5X,'FX =',G15.7) C S=ZERO FXVALU=FX CALL MINX(K2,2,D(K2),S,FXVALU,0,F) 200 CONTINUE C 210 F1=FX FX=SF C XLDS=ZERO DO 220 I=1,N SL=X(I) X(I)=Y(I) SL=SL-Y(I) Y(I)=SL XLDS=XLDS+SL*SL 220 CONTINUE C XLDS=ZSQRT(XLDS) IF(XLDS.GT.SMALL) THEN C C THROW AWAY THE DIRECTION KL AND MINIMIZE ALONG C THE NEW CONJUGATE DIRECTION. C IK=KL-1 IF(K.GT.IK) GO TO 250 DO 240 IM=K,IK I=IK-IM+K C DO 230 J=1,N V(J,I+1)=V(J,I) 230 CONTINUE C D(I+1)=D(I) 240 CONTINUE C 250 D(K)=ZERO C DO 260 I=1,N V(I,K)=Y(I)/XLDS 260 CONTINUE C IF(JPRINT.GE.5) WRITE(LP,270)K,D(K),XLDS,F1 270 FORMAT(/' CALL NO. 4 TO MINX.'/ * 5X,'K =',I4,5X,'D(K) =',1PG15.7,5X, * 'XLDS =',G15.7/5X,'F1 =',G15.7) C F1VALU=F1 CALL MINX(K,4,D(K),XLDS,F1VALU,1,F) C IF(XLDS.LE.ZERO) THEN XLDS=-XLDS C DO 280 I=1,N V(I,K)=-V(I,K) 280 CONTINUE ENDIF ENDIF C XLDT=DLDFAC*XLDT IF(XLDT.LT.XLDS) XLDT=XLDS C IF(JPRINT.GT.0) THEN WRITE(LP,40)NL,NF,FX IF(N.LE.4 .OR. JPRINT.GT.2) THEN WRITE(LP,50)(X(I),I=1,N) ENDIF ENDIF C T2=ZERO DO 290 I=1,N T2=T2+X(I)**2 290 CONTINUE T2=XM2*ZSQRT(T2)+T C C SEE IF THE STEP LENGTH EXCEEDS HALF THE TOLERANCE. C IF(XLDT.GT.RHALF*T2) THEN KT=0 ELSE KT=KT+1 ENDIF C C IF(...) GO TO L2 C IF(KT.GT.KTM) GO TO 550 C IF(NF.GE.NFMAX) THEN WRITE(LP,300)NFMAX 300 FORMAT(/' IN PRAXIS, NF REACHED THE LIMIT NFMAX =',I11/ * 5X,'THIS IS AN ABNORMAL TERMINATION.'/ * 5X,'THE FUNCTION HAS NOT BEEN MINIMIZED AND', * ' THE RESULTING X(*) VECTOR SHOULD NOT BE USED.') GO TO 550 ENDIF C 310 CONTINUE C C TRY QUADRATIC EXTRAPOLATION IN CASE WE ARE STUCK IN A CURVED VALLEY. C 320 CALL QUAD(F) C DN=ZERO DO 330 I=1,N D(I)=ONE/ZSQRT(D(I)) IF(DN.LT.D(I)) DN=D(I) 330 CONTINUE C IF(JPRINT.GT.3) THEN C WRITE(LP,340) 340 FORMAT(/' NEW DIRECTIONS') C DO 360 I=1,N WRITE(LP,350)I,(V(I,J),J=1,N) 350 FORMAT(1X,I5,4X,1PG15.7,4G15.7/(10X,5G15.7)) 360 CONTINUE ENDIF C DO 380 J=1,N C S=D(J)/DN DO 370 I=1,N V(I,J)=S*V(I,J) 370 CONTINUE 380 CONTINUE C IF(SCBD.GT.ONE) THEN C C SCALE THE AXES TO TRY TO REDUCE THE CONDITION NUMBER. C S=VLARGE DO 400 I=1,N C SL=ZERO DO 390 J=1,N SL=SL+V(I,J)**2 390 CONTINUE C Z(I)=ZSQRT(SL) IF(Z(I).LT.XM4) Z(I)=XM4 IF(S.GT.Z(I)) S=Z(I) 400 CONTINUE C DO 410 I=1,N SL=S/Z(I) Z(I)=ONE/SL C IF(Z(I).GT.SCBD) THEN SL=ONE/SCBD Z(I)=SCBD ENDIF C C IT APPEARS THAT THERE ARE TWO MISSING END; STATEMENTS C AT THIS POINT IN BRENT'S LISTING. C 410 CONTINUE ENDIF C C TRANSPOSE V FOR MINFIT. C IF(N.LT.2) GO TO 440 DO 430 I=2,N C IMU=I-1 DO 420 J=1,IMU S=V(I,J) V(I,J)=V(J,I) V(J,I)=S 420 CONTINUE 430 CONTINUE C C FIND THE SINGULAR VALUE DECOMPOSITION OF V. C THIS GIVES THE EIGENVALUES AND PRINCIPAL AXES C OF THE APPROXIMATING QUADRATIC FORM C WITHOUT SQUARING THE CONDITION NUMBER. C 440 CALL MINFIT(N,EPSMCH,VSMALL,V,D,E,NMAX,LP) C IF(SCBD.GT.ONE) THEN C C UNSCALING... C DO 460 I=1,N C S=Z(I) DO 450 J=1,N V(I,J)=S*V(I,J) 450 CONTINUE 460 CONTINUE C DO 490 I=1,N C S=ZERO DO 470 J=1,N S=S+V(J,I)**2 470 CONTINUE S=ZSQRT(S) C D(I)=S*D(I) C S=ONE/S DO 480 J=1,N V(J,I)=S*V(J,I) 480 CONTINUE 490 CONTINUE ENDIF C DO 500 I=1,N C IF(DN*D(I).GT.XLARGE) THEN D(I)=VSMALL ELSE IF(DN*D(I).LT.SMALL) THEN D(I)=VLARGE ELSE D(I)=ONE/(DN*D(I))**2 ENDIF 500 CONTINUE C C SORT THE NEW EIGENVALUES AND EIGENVECTORS. C CALL SORT C DMIN=D(N) IF(DMIN.LT.SMALL) DMIN=SMALL C IF(XM2*D(1).GT.DMIN) THEN ILLC=1 ELSE ILLC=0 ENDIF C IF(JPRINT.GT.1 .AND. SCBD.GT.ONE) THEN WRITE(LP,510)(Z(I),I=1,N) 510 FORMAT(/' SCALE FACTORS'/(1X,1PG15.7,4G15.7)) ENDIF C IF(JPRINT.GT.1) THEN WRITE(LP,520)(D(I),I=1,N) 520 FORMAT(/' EIGENVALUES OF A'/(1X,1PG15.7,4G15.7)) ENDIF C IF(JPRINT.GT.3) THEN C WRITE(LP,530) 530 FORMAT(/' EIGENVECTORS OF A') C DO 540 I=1,N WRITE(LP,350)I,(V(I,J),J=1,N) 540 CONTINUE ENDIF C C GO BACK TO THE MAIN LOOP. C GO TO L0 C C HANDLE THE CASE N .EQ. 1 IN AN AD HOC WAY. C (BRENT DID NOT PROVIDE FOR THIS CASE.) C IF(N.GE.2) GO TO 60 C C LABEL L2... C 550 IF(JPRINT.GT.0) THEN WRITE(LP,560)(X(I),I=1,N) 560 FORMAT(//7X,'X'/(1X,1PG15.7,4G15.7)) ENDIF C FX=F(X,N) C IF(JPRINT.GE.0) WRITE(LP,570)FX,NL,NF 570 FORMAT(/' EXIT PRAXIS. FX =',1PG25.17,5X,'NL =',I8, * 5X,'NF =',I9) C RETURN C C END PRAXIS C END SUBROUTINE QUAD(F) C C THIS SUBROUTINE LOOKS FOR THE MINIMUM ALONG C A CURVE DEFINED BY Q0, Q1, AND X. C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGE 161 C C SUBROUTINE QUAD IS CALLED BY SUBROUTINE PRAXIS. C INTEGER N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH INTEGER I C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD DOUBLE PRECISION F, DSQRT,ZSQRT,ARG, * ONE,QA,QB,QC,S,TWO,XL,ZERO,QF1VAL C EXTERNAL F C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C ZSQRT(ARG)=DSQRT(ARG) C ZERO=0.0D0 ONE=1.0D0 C S=FX FX=QF1 QF1=S QD1=ZERO C DO 10 I=1,N S=X(I) XL=Q1(I) X(I)=XL Q1(I)=S QD1=QD1+(S-XL)**2 10 CONTINUE C QD1=ZSQRT(QD1) XL=QD1 S=ZERO C IF(QD0.GT.ZERO .AND. QD1.GT.ZERO .AND. NL.GE.3*N*N) THEN C IF(JPRINT.GE.1) WRITE(LP,20)NF,QD0,QD1,FX,QF1 20 FORMAT(/' ***** CALL MINX FROM QUAD. NF =',I11/ * 5X,'QD0 =',1PG15.7,5X,'QD1 =',G15.7/ * 5X,'FX =',G15.7,5X,'QF1 =',G15.7) C QF1VAL=QF1 CALL MINX(0,2,S,XL,QF1VAL,1,F) QA=XL*(XL-QD1)/(QD0*(QD0+QD1)) QB=(XL+QD0)*(QD1-XL)/(QD0*QD1) QC=XL*(XL+QD0)/(QD1*(QD0+QD1)) ELSE FX=QF1 QA=ZERO QB=ZERO QC=ONE ENDIF C QD0=QD1 C DO 30 I=1,N S=Q0(I) Q0(I)=X(I) X(I)=QA*S+QB*X(I)+QC*Q1(I) 30 CONTINUE C RETURN C C END QUAD C END SUBROUTINE MINX(J,NITS,D2,X1,F1,IFK,F) C C SUBROUTINE MINX MINIMIZES F FROM X IN THE DIRECTION V(*,J) C UNLESS J IS LESS THAN 1, WHEN A QUADRATIC SEARCH IS DONE IN C THE PLANE DEFINED BY Q0, Q1, AND X. C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGES 159-160 C C SUBROUTINE MINX IS CALLED BY SUBROUTINES PRAXIS AND QUAD. C C D2 AND X1 RETURN RESULTS. C J, NITS, F1 AND IFK ARE VALUE PARAMETERS THAT RETURN NOTHING. C DO NOT SEND A COMMON VARIABLE TO MINX FOR PARAMETER F1. C C C D2 IS AN APPROXIMATION TO HALF OF C THE SECOND DERIVATIVE OF F (OR ZERO). C C X1 IS AN ESTIMATE OF DISTANCE TO MINIMUM, C RETURNED AS THE DISTANCE FOUND. C C IF IFK = 1 THEN F1 IS FLIN(X1), OTHERWISE X1 AND F1 ARE C IGNORED ON ENTRY UNLESS FINAL FX IS GREATER THAN F1. C C NITS CONTROLS THE NUMBER OF TIMES AN ATTEMPT IS MADE TO C HALVE THE INTERVAL. C EXTERNAL F C INTEGER N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH INTEGER IFK,J,NITS, I,IDZ,K C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD DOUBLE PRECISION D2,X1, * DABS,DSQRT,ZABS,ZSQRT,ARG, * HUNDTH,RHALF,TWO,ZERO, * DENOM,D1,FM,F0,F1,F2,S,SF1,SX1,T2,XM,X2 C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C ZSQRT(ARG)=DSQRT(ARG) ZABS(ARG)=DABS(ARG) C HUNDTH=0.01D0 ZERO=0.0D0 TWO=2.0D0 RHALF=0.5D0 C SF1=F1 SX1=X1 K=0 XM=ZERO FM=FX F0=FX C IF(D2.LT.EPSMCH) THEN IDZ=1 ELSE IDZ=0 ENDIF C C FIND THE STEP SIZE. C S=ZERO DO 10 I=1,N S=S+X(I)**2 10 CONTINUE S=ZSQRT(S) C IF(IDZ.EQ.1) THEN DENOM=DMIN ELSE DENOM=D2 ENDIF C T2=XM4*ZSQRT(ZABS(FX)/DENOM+S*XLDT)+XM2*XLDT S=XM4*S+T IF(IDZ.EQ.1 .AND. T2.GT.S) T2=S IF(T2.LT.SMALL) T2=SMALL IF(T2.GT.HUNDTH*H) T2=HUNDTH*H C IF(IFK.EQ.1 .AND. F1.LE.FM) THEN XM=X1 FM=F1 ENDIF C IF(IFK.EQ.0 .OR. ZABS(X1).LT.T2) THEN C IF(X1.GE.ZERO) THEN X1=T2 ELSE X1=-T2 ENDIF C CALL FLIN(X1,J,F,F1) ENDIF C IF(F1.LT.FM) THEN XM=X1 FM=F1 ENDIF C C LABEL L0... C 20 IF(IDZ.EQ.1) THEN C C EVALUATE FLIN AT ANOTHER POINT, C AND ESTIMATE THE SECOND DERIVATIVE. C IF(F0.LT.F1) THEN X2=-X1 ELSE X2=TWO*X1 ENDIF C CALL FLIN(X2,J,F,F2) C IF(F2.LE.FM) THEN XM=X2 FM=F2 ENDIF C D2=(X2*(F1-F0)-X1*(F2-F0))/(X1*X2*(X1-X2)) C IF(JPRINT.GE.5) WRITE(LP,30)X1,X2,F0,F1,F2,D2 30 FORMAT(/' COMPUTE D2 IN SUBROUTINE MINX.'/ * 5X,'X1 =',1PG15.7,5X,'X2 =',G15.7/ * 5X,'F0 =',G15.7,5X,'F1 =',G15.7,5X,'F2 =',G15.7/ * 5X,'D2 =',G15.7) ENDIF C C ESTIMATE THE FIRST DERIVATIVE AT 0. C D1=(F1-F0)/X1-X1*D2 IDZ=1 C C PREDICT THE MINIMUM. C IF(D2.LE.SMALL) THEN C IF(D1.LT.ZERO) THEN X2=H ELSE X2=-H ENDIF C ELSE X2=-RHALF*D1/D2 ENDIF C IF(ZABS(X2).GT.H) THEN C IF(X2.GT.ZERO) THEN X2=H ELSE X2=-H ENDIF ENDIF C C EVALUATE F AT THE PREDICTED MINIMUM. C LABEL L1... C 40 CALL FLIN(X2,J,F,F2) C IF(K.LT.NITS .AND. F2.GT.F0) THEN C C NO SUCCESS, SO TRY AGAIN. C K=K+1 C C IF(...) GO TO L0 C IF(F0.LT.F1 .AND. X1*X2.GT.ZERO) GO TO 20 X2=X2/TWO C C GO TO L1 C GO TO 40 C ENDIF C C INCREMENT THE ONE-DIMENSIONAL SEARCH COUNTER. C NL=NL+1 C IF(F2.GT.FM) THEN X2=XM ELSE FM=F2 ENDIF C C GET A NEW ESTIMATE OF THE SECOND DERIVATIVE. C IF(ZABS(X2*(X2-X1)).GT.SMALL) THEN D2=(X2*(F1-F0)-X1*(FM-F0))/(X1*X2*(X1-X2)) C IF(JPRINT.GE.5) WRITE(LP,50)X1,X2,F0,FM,F1,D2 50 FORMAT(/' RECOMPUTE D2 IN SUBROUTINE MINX.'/ * 5X,'X1 =',1PG15.7,5X,'X2 =',G15.7/ * 5X,'F0 =',G15.7,5X,'FM =',G15.7,5X,'F1 =',G15.7/ * 5X,'D2 =',G15.7) C ELSE IF(K.GT.0) THEN D2=ZERO C IF(JPRINT.GE.5) WRITE(LP,60) 60 FORMAT(/' SET D2=0 IN SUBROUTINE MINX.') ELSE D2=D2 ENDIF C IF(D2.LE.SMALL) THEN D2=SMALL C IF(JPRINT.GE.5) WRITE(LP,70)D2 70 FORMAT(/' SET D2=SMALL=',1PG15.7,' IN SUBROUTINE MINX.') ENDIF C IF(JPRINT.GE.5) WRITE(LP,80)X1,X2,FX,FM,SF1 80 FORMAT(/' SUBROUTINE MINX. X1 =',1PG15.7,5X,'X2 =',G15.7/ * 5X,'FX =',G15.7,5X,'FM =',G15.7,5X,'SF1 =',G15.7) C X1=X2 FX=FM IF(SF1.LT.FX) THEN FX=SF1 X1=SX1 ENDIF C C UPDATE X FOR A LINEAR SEARCH BUT NOT FOR A PARABOLIC SEARCH. C IF(J.GT.0) THEN C DO 90 I=1,N X(I)=X(I)+X1*V(I,J) 90 CONTINUE ENDIF C IF(JPRINT.GE.5) WRITE(LP,100)D2,X1,F1,FX 100 FORMAT(/' LEAVE SUBROUTINE MINX.'/ * 5X,'D2 =',1PG15.7,5X,'X1 =',G15.7,5X,'F1 =',G15.7/ * 5X,'FX =',G15.7) C RETURN C C END MINX C END SUBROUTINE FLIN(XL,J,F,FLN) C C FLIN IS A FUNCTION OF ONE VARIABLE XL WHICH IS MINIMIZED BY C SUBROUTINE MINX. C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGES 159-160 C C SUBROUTINE FLIN IS CALLED BY SUBROUTINE MINX. C INTEGER N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH INTEGER J, I C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD DOUBLE PRECISION XL,F,FLN, TT, QA,QB,QC C DIMENSION TT(128) C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C IF(J.GT.0) THEN C C LINEAR SEARCH... C DO 10 I=1,N TT(I)=X(I)+XL*V(I,J) 10 CONTINUE C ELSE C C SEARCH ALONG A PARABOLIC SPACE CURVE. C QA=XL*(XL-QD1)/(QD0*(QD0+QD1)) QB=(XL+QD0)*(QD1-XL)/(QD0*QD1) QC=XL*(XL+QD0)/(QD1*(QD0+QD1)) C DO 20 I=1,N TT(I)=QA*Q0(I)+QB*X(I)+QC*Q1(I) 20 CONTINUE ENDIF C C INCREMENT FUNCTION EVALUATION COUNTER. C NF=NF+1 FLN=F(TT,N) C RETURN C C END FLIN C END SUBROUTINE MINFIT(N,EPS,TOL,AB,Q,E,NMAX,LP) C C AN IMPROVED VERSION OF MINFIT, RESTRICTED TO M=N, P=0. C SEE GOLUB AND REINSCH (1970). C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGES 156-158 C C G. H. GOLUB AND C. REINSCH, C "SINGULAR VALUE DECOMPOSITION AND LEAST SQUARES SOLUTIONS', C NUMERISCHE MATHEMATIK 14 (1970) PAGES 403-420 C C THE SINGULAR VALUES OF THE ARRAY AB ARE RETURNED IN Q, C AND AB IS OVERWRITTEN WITH THE ORTHOGONAL MATRIX V SUCH THAT C U.DIAG(Q)=AB.V, WHERE U IS ANOTHER ORTHOGONAL MATRIX. C C SUBROUTINE MINFIT IS CALLED BY SUBROUTINE PRAXIS. C INTEGER N,NMAX,LP, * I,II,J,JTHIRT,K,KK,KT,L,LL2,LPI,L2 C DOUBLE PRECISION EPS,TOL,AB,Q,E, * DABS,DSQRT,ZABS,ZSQRT,ARG, * C,DENOM,F,G,H,ONE,X,Y,Z,ZERO,S,TWO C DIMENSION AB(NMAX,N),Q(N),E(N) C ZABS(ARG)=DABS(ARG) ZSQRT(ARG)=DSQRT(ARG) C JTHIRT=30 C ZERO=0.0D0 ONE=1.0D0 TWO=2.0D0 C C HOUSEHOLDER'S REDUCTION TO BIDIAGONAL FORM... C X=ZERO G=ZERO C DO 140 I=1,N E(I)=G S=ZERO L=I+1 C DO 10 J=I,N S=S+AB(J,I)**2 10 CONTINUE C IF(S.LT.TOL) THEN G=ZERO ELSE F=AB(I,I) C IF(F.LT.ZERO) THEN G=ZSQRT(S) ELSE G=-ZSQRT(S) ENDIF C H=F*G-S AB(I,I)=F-G C IF(L.GT.N) GO TO 60 DO 50 J=L,N C F=ZERO IF(I.GT.N) GO TO 30 DO 20 K=I,N F=F+AB(K,I)*AB(K,J) 20 CONTINUE 30 F=F/H C IF(I.GT.N) GO TO 50 DO 40 K=I,N AB(K,J)=AB(K,J)+F*AB(K,I) 40 CONTINUE 50 CONTINUE ENDIF C 60 Q(I)=G S=ZERO C IF(I.LE.N) THEN C IF(L.GT.N) GO TO 80 DO 70 J=L,N S=S+AB(I,J)**2 70 CONTINUE ENDIF C 80 IF(S.LT.TOL) THEN G=ZERO ELSE F=AB(I,I+1) C IF(F.LT.ZERO) THEN G=ZSQRT(S) ELSE G=-ZSQRT(S) ENDIF C H=F*G-S AB(I,I+1)=F-G IF(L.GT.N) GO TO 130 DO 90 J=L,N E(J)=AB(I,J)/H 90 CONTINUE C DO 120 J=L,N C S=ZERO DO 100 K=L,N S=S+AB(J,K)*AB(I,K) 100 CONTINUE C DO 110 K=L,N AB(J,K)=AB(J,K)+S*E(K) 110 CONTINUE 120 CONTINUE ENDIF C 130 Y=ZABS(Q(I))+ZABS(E(I)) C IF(Y.GT.X) X=Y 140 CONTINUE C C ACCUMULATION OF RIGHT-HAND TRANSFORMATIONS... C DO 210 II=1,N I=N-II+1 C IF(G.NE.ZERO) THEN H=AB(I,I+1)*G C IF(L.GT.N) GO TO 200 DO 150 J=L,N AB(J,I)=AB(I,J)/H 150 CONTINUE C DO 180 J=L,N C S=ZERO DO 160 K=L,N S=S+AB(I,K)*AB(K,J) 160 CONTINUE C DO 170 K=L,N AB(K,J)=AB(K,J)+S*AB(K,I) 170 CONTINUE 180 CONTINUE ENDIF C IF(L.GT.N) GO TO 200 DO 190 J=L,N AB(J,I)=ZERO AB(I,J)=ZERO 190 CONTINUE C 200 AB(I,I)=ONE G=E(I) L=I 210 CONTINUE C C DIAGONALIZATION OF THE BIDIAGONAL FORM... C EPS=EPS*X DO 330 KK=1,N K=N-KK+1 KT=0 C C LABEL TESTFSPLITTING... C 220 KT=KT+1 C IF(KT.GT.JTHIRT) THEN E(K)=ZERO WRITE(LP,230) 230 FORMAT(' QR FAILED.') ENDIF C DO 240 LL2=1,K L2=K-LL2+1 L=L2 C C IF(...) GO TO TESTFCONVERGENCE C IF(ZABS(E(L)).LE.EPS) GO TO 270 C C IF(...) GO TO CANCELLATION C IF(ZABS(Q(L-1)).LE.EPS) GO TO 250 240 CONTINUE C C CANCELLATION OF E(L) IF L IS GREATER THAN 1... C LABEL CANCELLATION... C 250 C=ZERO S=ONE IF(L.GT.K) GO TO 270 DO 260 I=L,K F=S*E(I) E(I)=C*E(I) C C IF(...) GO TO TESTFCONVERGENCE C IF(ZABS(F).LE.EPS) GO TO 270 G=Q(I) C IF(ZABS(F).LT.ZABS(G)) THEN H=ZABS(G)*ZSQRT(ONE+(F/G)**2) ELSE IF(F.NE.ZERO) THEN H=ZABS(F)*ZSQRT(ONE+(G/F)**2) ELSE H=ZERO ENDIF C Q(I)=H C IF(H.EQ.ZERO) THEN H=ONE G=ONE ENDIF C C THE ABOVE REPLACES Q(I) AND H BY SQUARE ROOT OF (G*G+F*F) C WHICH MAY GIVE INCORRECT RESULTS IF THE SQUARES UNDERFLOW OR IF C F = G = 0 . C C=G/H S=-F/H 260 CONTINUE C C LABEL TESTFCONVERGENCE... C 270 Z=Q(K) C C IF(...) GO TO CONVERGENCE C IF(L.EQ.K) GO TO 310 C C SHIFT FROM BOTTOM 2*2 MINOR. C X=Q(L) Y=Q(K-1) G=E(K-1) H=E(K) F=((Y-Z)*(Y+Z)+(G-H)*(G+H))/(TWO*H*Y) G=ZSQRT(F*F+ONE) C IF(F.LT.ZERO) THEN DENOM=F-G ELSE DENOM=F+G ENDIF C F=((X-Z)*(X+Z)+H*(Y/DENOM-H))/X C C NEXT QR TRANSFORMATION... C S=ONE C=ONE LPI=L+1 IF(LPI.GT.K) GO TO 300 DO 290 I=LPI,K G=E(I) Y=Q(I) H=S*G G=G*C C IF(ZABS(F).LT.ZABS(H)) THEN Z=ZABS(H)*ZSQRT(ONE+(F/H)**2) ELSE IF(F.NE.ZERO) THEN Z=ZABS(F)*ZSQRT(ONE+(H/F)**2) ELSE Z=ZERO ENDIF C E(I-1)=Z C IF(Z.EQ.ZERO) THEN F=ONE Z=ONE ENDIF C C=F/Z S=H/Z F=X*C+G*S G=-X*S+G*C H=Y*S Y=Y*C C DO 280 J=1,N X=AB(J,I-1) Z=AB(J,I) AB(J,I-1)=X*C+Z*S AB(J,I)=-X*S+Z*C 280 CONTINUE C IF(ZABS(F).LT.ZABS(H)) THEN Z=ZABS(H)*ZSQRT(ONE+(F/H)**2) ELSE IF(F.NE.ZERO) THEN Z=ZABS(F)*ZSQRT(ONE+(H/F)**2) ELSE Z=ZERO ENDIF C Q(I-1)=Z C IF(Z.EQ.ZERO) THEN F=ONE Z=ONE ENDIF C C=F/Z S=H/Z F=C*G+S*Y X=-S*G+C*Y 290 CONTINUE C 300 E(L)=ZERO E(K)=F Q(K)=X C C GO TO TESTFSPLITTING C GO TO 220 C C LABEL CONVERGENCE... C 310 IF(Z.LT.ZERO) THEN C C Q(K) IS MADE NON-NEGATIVE. C Q(K)=-Z DO 320 J=1,N AB(J,K)=-AB(J,K) 320 CONTINUE ENDIF 330 CONTINUE C RETURN C C END MINFIT C END SUBROUTINE SORT C C THIS SUBROUTINE SORTS THE ELEMENTS OF D C AND THE CORRESPONDING COLUMNS OF V INTO DESCENDING ORDER. C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGES 158-159 C INTEGER N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH INTEGER I,IPI,J,K,NMI C DOUBLE PRECISION V,X,D,Q0,Q1,DMIN,EPSMCH,FX,H,QD0,QD1,QF1, * SMALL,T,XLDT,XM2,XM4,DSEED,SCBD DOUBLE PRECISION S C COMMON /CPRAX/ V(128,128),X(128),D(128),Q0(128),Q1(128), * DMIN,EPSMCH,FX,H,QD0,QD1,QF1,SMALL,T,XLDT,XM2,XM4,DSEED,SCBD, * N,NL,NF,LP,JPRINT,NMAX,ILLCIN,KTM,NFMAX,JRANCH C NMI=N-1 IF(NMI.LT.1) GO TO 50 DO 40 I=1,NMI K=I S=D(I) IPI=I+1 IF(IPI.GT.N) GO TO 20 C DO 10 J=IPI,N C IF(D(J).GT.S) THEN K=J S=D(J) ENDIF 10 CONTINUE C 20 IF(K.GT.I) THEN D(K)=D(I) D(I)=S C DO 30 J=1,N S=V(J,I) V(J,I)=V(J,K) V(J,K)=S 30 CONTINUE ENDIF 40 CONTINUE C 50 RETURN C C END SORT C END SUBROUTINE RANINI(RVALUE) C C SUBROUTINE RANINI PERFORMS INITIALIZATION FOR SUBROUTINE RANDOM. C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGES 163-164 C INTEGER JRAN2,I C DOUBLE PRECISION RVALUE,R,RAN3,DMOD,DABS,RAN1 C COMMON /COMRAN/ RAN3(127),RAN1,JRAN2 C R=DMOD(DABS(RVALUE),8190.0D0)+1 JRAN2=127 C 10 IF(JRAN2.GT.0) THEN JRAN2=JRAN2-1 RAN1=-2.0D0**55 C DO 20 I=1,7 R=DMOD(1756.0D0*R,8191.0D0) RAN1=(RAN1+(R-DMOD(R,32.0D0))/32.0D0)/256.0D0 20 CONTINUE C RAN3(JRAN2+1)=RAN1 GO TO 10 ENDIF C RETURN C C END RANINI C END SUBROUTINE RANDOM(RANVAL) C C SUBROUTINE RANDOM RETURNS A DOUBLE PRECISION PSEUDORANDOM NUMBER C UNIFORMLY DISTRIBUTED IN (0,1) (INCLUDING 0 BUT NOT 1). C C "ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES", C RICHARD P. BRENT, PRENTICE-HALL 1973, PAGES 163-164 C C BEFORE THE FIRST CALL TO RANDOM, THE USER MUST C CALL RANINI(R) ONCE (ONLY) WITH R A DOUBLE PRECISION NUMBER C EQUAL TO ANY INTEGER VALUE. C BRENT (PAGE 166) USED THE EQUIVALENT OF C CALL RANINI(4.0D0) . C C THE ALGORITHM USED IN SUBROUTINE RANDOM RETURNS X(N)/2**56, C WHERE X(N) = X(N-1) + X(N-127) (MOD 2**56) . C SINCE (1 + X + X**127) IS PRIMITIVE (MOD 2), C THE PERIOD IS AT LEAST (2**127 - 1), WHICH EXCEEDS 10**38. C C SEE "SEMINUMERICAL ALGORITHMS", VOLUME 2 OF C "THE ART OF COMPUTER PROGRAMMING" BY DONALD E. KNUTH, C ADDISON-WESLEY 1969, PAGES 26, 34, AND 464. C C X(N) IS STORED IN DOUBLE PRECISION AS RAN3 = X(N)/2**56 - 1/2, C AND ALL DOUBLE PRECISION ARITHMETIC IS EXACT. C INTEGER JRAN2 C DOUBLE PRECISION RANVAL,RAN3,RAN1 C COMMON /COMRAN/ RAN3(127),RAN1,JRAN2 C IF(JRAN2.EQ.0) THEN JRAN2=126 ELSE JRAN2=JRAN2-1 ENDIF C RAN1=RAN1+RAN3(JRAN2+1) IF(RAN1.LT.0.0D0) THEN RAN1=RAN1+0.5D0 ELSE RAN1=RAN1-0.5D0 ENDIF C RAN3(JRAN2+1)=RAN1 RANVAL=RAN1+0.5D0 C RETURN C C END RANDOM C END DOUBLE PRECISION FUNCTION DRANDM(DL) C C SIMPLE PORTABLE PSEUDORANDOM NUMBER GENERATOR. C C DRANDM RETURNS FUNCTION VALUES THAT ARE PSEUDORANDOM C NUMBERS UNIFORMLY DISTRIBUTED ON THE INTERVAL (0,1). C C 'NUMERICAL MATHEMATICS AND COMPUTING' BY WARD CHENEY AND C DAVID KINCAID, BROOKS/COLE PUBLISHING COMPANY C (FIRST EDITION, 1980), PAGE 203 C C AT THE BEGINNING OF EXECUTION, OR WHENEVER A NEW SEQUENCE IS C TO BE INITIATED, SET DL EQUAL TO AN INTEGER VALUE BETWEEN C 1.0D0 AND 2147483646.0D0, INCLUSIVE. DO THIS ONLY ONCE. C THEREAFTER, DO NOT SET OR ALTER DL IN ANY WAY. C FUNCTION DRANDM WILL MODIFY DL FOR ITS OWN PURPOSES. C C DRANDM USES A MULTIPLICATIVE CONGRUENTIAL METHOD. C THE NUMBERS GENERATED BY DRANDM SUFFER FROM THE PARALLEL C PLANES DEFECT DISCOVERED BY G. MARSAGLIA, AND SHOULD NOT BE C USED WHEN HIGH-QUALITY RANDOMNESS IS REQUIRED. IN THAT C CASE, USE A "SHUFFLING" METHOD. C DOUBLE PRECISION DL,DMOD C 10 DL=DMOD(16807.0D0*DL,2147483647.0D0) DRANDM=DL/2147483647.0D0 IF(DRANDM.LE.0.0D0 .OR. DRANDM.GE.1.0D0) GO TO 10 RETURN END gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/README0000664000175000017500000000347112207440367023261 0ustar jcorganjcorgan# # Copyright 2002 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # This file contains the source for gen_interpolator_taps, a program which generates optimal interpolator taps for a fractional interpolator. The ideal interpolator requires an infinite tap FIR filter to realize. We design a separate 8 tap filter for each value of mu, the fractional delay, that we are interested in. The taps are selected such that the mean squared error between the ideal frequency response and the approximation is mininimized over all frequencies of interest. In this implementation we define ``frequencies of interest'' as those from -B to +B, where B = 1/(4*Ts), where Ts is the sampling period. For a detailed look at what this is all about, please see Chapter 9 of "Digital Communication Receivers: Synchronization, Channel Estimation and Signal Processing" by Meyr, Moeneclaey and Fechtel, ISBN 0-471-50275-8 NOTE, if you're running gen_interpolator_taps and it seg faults in RANDOM, you're probably using g77-2.96. The fix is to use g77 3.0 or later cd rm config.cache export F77=g77-3.0.4 ./configure make gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/praxis.txt0000664000175000017500000001673112207440367024453 0ustar jcorganjcorganBrent's PRAXIS minimizer is available in FORTRAN 77. July 1995 "Algorithms for Minimization Without Derivatives" by Richard P. Brent, Prentice-Hall, 1973 ISBN: 0-13-022335-2 This book by Brent was a groundbreaking effort. (I believe that it was his Ph.D. thesis at Stanford.) His algorithms for finding roots and minima in one dimension have good performance for typical problems and guaranteed performance in the worst case. (A later rootfinder by J. Bus and Dekker gave a much lower bound for the worst case, but no better performance in typical problems.) These algorithms were implemented in both ALGOL W and FORTRAN by Brent, and have been used fairly widely. Brent also gave a multi-dimensional minimization algorithm, PRAXIS, but only shows an implementation in ALGOL W. This routine has not been widely used, at least in the U.S. The PRAXIS package has been translated into FORTRAN by Rosalee Taylor, Sue Pinski, and me, and I am making it available via anonymous ftp for use as freeware (please do not remove our names). ftp a.cs.okstate.edu anonymous [enter your userid as password] cd /pub/jpc get praxis.f quit Brent's method and its performance Newton's method for minimization can find the minimum of a quadratic function in one iteration, but is sometimes not convenient to use. In the 1960s, several researchers found iterative methods that solve quadratic problems exactly in a finite number of steps. C. S. Smith (1962) and M. J. D. Powell (1964) devised methods that had this property and did not require derivatives. G. W. Stewart modified the Davidon-Fletcher-Powell quasi-Newton method to use finite difference approximations to approximate the gradient. Powell's method, or later versions by Zangwill, were the most successful of the early direct search methods having the property of finite convergence on quadratic functions. Powell's method was programmed at Harwell as subroutine VA04A, and is available as file va04a.f in the same directory as praxis.f. VA04A is not extremely robust, and can give underflow, overflow, or division by zero. va04a.f has several documented patches in it where I tried to get around various abnormal terminations. I do not recommend VA04A very strongly. Brent's PRAXIS added orthogonalization and several other features to Powell's method. Brent also dealt carefully with roundoff. William H. Press et al. in their book "Numerical Recipes" comment that "Brent has a number of other cute tricks up his sleeve, and his modification of Powell's method is probably the best presently known." Roger Fletcher was less enthusiastic in his review of Brent's book in The Computer Journal 16 (1973) 314: "... I am not convinced that the modifications to Powell's method are the best. Use of eigenvector directions is not independent of scale changes to the variables, and the use of searches in random directions is hardly appealing. Nonetheless all the algorithms are demonstrated to be competitive by numerical examples." The methods of Powell, Brent, et al. require that the function for which a local minimum is sought must be smooth; that is, the function and all of its first partial derivatives must be continuous. Brent compared his method to the methods of Powell, of Stewart, and of Davies, Swann, and Campey. Indirectly, he compared it also to the Davidon-Fletcher-Powell quasi-Newton method. He found that his method was about as efficient as the best of these in most cases, and that it was more robust than others in some cases. (Pages 139-155 in Brent's book give fair comparisons to other methods. The results in Table 7.1 on page 138 are correct, but do not include progress all the way to convergence, and are therefore not too useful.) On least squares problems, all of these general minimization methods are likely to be inefficient compared to least squares methods such as the Gauss-Newton or Marquardt methods. In addition to the scale dependence that Fletcher deplored, PRAXIS also had the disadvantage that it required N, the number of parameters, to be greater than or equal to two. The failure to handle N=1 is an unnecessary and pointless limitation. The FORTRAN version We have followed Brent's PRAXIS rather closely. I have added a patch to try to handle the case N=1, and an option to use a simpler pseudorandom number generator, DRANDM. The handling of N=1 is not guaranteed. The user writes a main program and a function subprogram to compute the function to be minimized. All communication between the user's main program and PRAXIS is done via COMMON, except for an EXTERNAL parameter giving the name of the function subprogram. The disadvantages of using COMMON are at least two-fold: 1) Arrays cannot have adjustable dimensions. 2) Because some actual parameters are COMMON variables, the FORTRAN version of PRAXIS probably will not pass the Bell Labs PFORT package as being 100% standard FORTRAN. Nevertheless, this usage will not cause any conflict in any commercial FORTRAN compiler ever written. (If it does, I will apologize and rewrite PRAXIS.) The advantage of using COMMON is that it is not necessary to pass about fifteen more parameters every time the user calls PRAXIS. At present all arrays are dimensioned (20) or (20,20), and this can easily be increased using two simple global editing commands. (In this case, increase the value of NMAX.) There are no DATA statements in PRAXIS, and it was not necessary to use any SAVE statements. We have used DOUBLE PRECISION for all floating point computations, as Brent did. We recommend using DOUBLE PRECISION on all computers except possibly Cray computers, in which REAL is reasonably precise. The value of "machine epsilon" is computed in subroutine PRASET using bisection, and is called EPSMCH. Brent computes EPSMCH**4 and 1/EPSMCH**4 in PRAXIS, and uses these quantities later. Because EPSMCH in DOUBLE PRECISION is less than 1E-16, these fourth powers of EPSMCH and 1/EPSMCH will underflow and overflow on such machines as VAXs and PCs, which have a range of only about 1E38, grossly insufficient for scientific computation. For such machines, Brent recommends increasing the value of EPSMCH. EPSMCH=1E-9 or possibly even 1E-8 might be necessary. A better solution would be to eliminate the explicit use of these fourth powers, accomplishing the same result implicitly. A "bug bounty" of $10 U.S. will be paid by me for the first notification of any error in PRAXIS. The same bounty also applies to any substantive poor design choice (having no redeeming advantages whatever) in the FORTRAN package. (The patch for N=1 is not included, although any suggested improvements in that will be considered carefully.) praxis.f includes test software to run any of the test problems that Brent ran, and is set to run at least one case of each problem. I have run these on an IBM 3090, essentially the same architecture that Brent used, and obtained essentially the same results that Brent shows on pages 140-155. The Hilbert problem with N=12, for which Brent shows no termination results and for which the results in Table 7.1 are correct but not relevant, runs a long time; I cut it off at 3000 function evaluations. I don't particularly like Brent's convergence criterion, which allows this sort of extremely slow creeping progress, but have not modified it. Please notify me of any problems with this software, or of any suggested modifications. John Chandler Computer Science Department Oklahoma State University Stillwater, Oklahoma 74078, U.S.A. (405) 744-5676 jpc@a.cs.okstate.edu gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/objective_fct.c0000664000175000017500000000554712207440367025361 0ustar jcorganjcorgan/* -*- c -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * generate MMSE FIR interpolation table values */ #include #include #include "simpson.h" #define MU 0.5 /* the MU for which we're computing coeffs */ #define Ts (1.0) /* sampling period */ #define B (1.0/(4*Ts)) /* one-sided signal bandwidth */ //#define B (1.0/(8./3*Ts)) /* one-sided signal bandwidth */ static unsigned global_n; static double *global_h; double global_mu = MU; double global_B = B; /* * This function computes the difference squared between the ideal * interpolator frequency response at frequency OMEGA and the * approximation defined by the FIR coefficients in global_h[] * * See eqn (9-7), "Digital Communication Receivers", Meyr, Moeneclaey * and Fechtel, Wiley, 1998. */ static double integrand (double omega) { double real_ideal; double real_approx; double real_diff; double imag_ideal; double imag_approx; double imag_diff; int i, n; int I1; double *h; real_ideal = cos (omega * Ts * global_mu); imag_ideal = sin (omega * Ts * global_mu); n = global_n; h = global_h; I1 = -(n / 2); real_approx = 0; imag_approx = 0; for (i = 0; i < n; i++){ real_approx += h[i] * cos (-omega * Ts * (i + I1)); imag_approx += h[i] * sin (-omega * Ts * (i + I1)); } real_diff = real_ideal - real_approx; imag_diff = imag_ideal - imag_approx; return real_diff * real_diff + imag_diff * imag_diff; } /* * Integrate the difference squared over all frequencies of interest. */ double c_fcn (double *x, int n) { assert ((n & 1) == 0); /* assert n is even */ global_n = n; global_h = x; return qsimp (integrand, -2 * M_PI * global_B, 2 * M_PI * global_B); } /* this is the interface expected by the calling fortran code */ double objective (double x[], int *ndim) { return c_fcn (x, *ndim); } static double si (double x) { if (fabs (x) < 1e-9) return 1.0; return sin(x) / x; } /* * starting guess for optimization */ void initpt (double x[], int ndim) { int i; for (i = 0; i < ndim; i++){ x[i] = si (M_PI * ((double) (i - ndim/2) + global_mu)); } } gnuradio-3.7.2.1/gr-filter/lib/gen_interpolator_taps/simpson.c0000664000175000017500000000354012207440367024232 0ustar jcorganjcorgan/* -*- c -*- */ #include #include #define EPS (1.0e-5) #define JMAX 16 /* * Compute the Nth stage of refinement of an extended trapezoidal * rule. FUNC is input as a pointer to a function to be integrated * between limits A and B. When called with N = 1, the routine * returns the crudest estimate of the integral from A to B of f(x) * dx. Subsequent calls with N=2,3,... (in that sequential order) * will improve the accuracy by adding 2**(N-2) additional interior * points. * * N.B., this function contains static state and IS NEITHER RENTRANT * NOR THREAD SAFE! */ double trapzd (double (*func)(double), double a, double b, int n) { long double x, tnm, sum, del; static long double s; static int it; int j; if (n == 1){ it = 1; /* # of points to add on the next call */ s = 0.5 * (b - a) * (func(a) + func(b)); return s; } else { tnm = it; del = (b-a)/tnm; /* this is the spacing of the points to be added */ x = a + 0.5*del; for (sum = 0.0, j = 1; j <= it; j++, x += del) sum += func(x); it *= 2; s = 0.5 * (s + (b-a) * sum/tnm); /* replace s by it's refined value */ return s; } } /* * Returns the integral of the function FUNC from A to B. The * parameters EPS can be set to the desired fractional accuracy and * JMAX so that 2**(JMAX-1) is the maximum allowed number of steps. * Integration is performed by Simpson's rule. */ double qsimp (double (*func)(double), double a, /* lower limit */ double b) /* upper limit */ { int j; long double s, st, ost, os; ost = os = -1.0e30; for (j = 1; j <= JMAX; j++){ st = trapzd (func, a, b, j); s = (4.0 * st - ost)/3.0; if (fabs (s - os) < EPS * fabs(os)) return s; os = s; ost = st; } fprintf (stderr, "Too many steps in routine QSIMP\n"); // exit (1); return s; } gnuradio-3.7.2.1/gr-filter/lib/interp_fir_filter_XXX_impl.cc.t0000664000175000017500000000757012207440367024052 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@IMPL_NAME@.h" #include #include #include namespace gr { namespace filter { @BASE_NAME@::sptr @BASE_NAME@::make(unsigned interpolation, const std::vector<@TAP_TYPE@> &taps) { return gnuradio::get_initial_sptr(new @IMPL_NAME@ (interpolation, taps)); } @IMPL_NAME@::@IMPL_NAME@(unsigned interpolation, const std::vector<@TAP_TYPE@> &taps) : sync_interpolator("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@)), interpolation), d_updated(false), d_firs(interpolation) { if(interpolation == 0) { throw std::out_of_range("@IMPL_NAME@: interpolation must be > 0\n"); } if(taps.size() == 0) { throw std::runtime_error("@IMPL_NAME@: no filter taps provided.\n"); } std::vector<@TAP_TYPE@> dummy_taps; for(unsigned i = 0; i < interpolation; i++) { d_firs[i] = new kernel::@FIR_TYPE@(1, dummy_taps); } set_taps(taps); install_taps(d_new_taps); } @IMPL_NAME@::~@IMPL_NAME@() { for(unsigned i = 0; i < interpolation(); i++) { delete d_firs[i]; } } void @IMPL_NAME@::set_taps(const std::vector<@TAP_TYPE@> &taps) { d_new_taps = taps; d_updated = true; // round up length to a multiple of the interpolation factor int n = taps.size() % interpolation(); if(n > 0) { n = interpolation() - n; while(n-- > 0) { d_new_taps.insert(d_new_taps.begin(), 0); } } if(d_new_taps.size() % interpolation() != 0) { throw std::runtime_error("@IMPL_NAME@: error setting interpolator taps.\n"); } } void @IMPL_NAME@::install_taps(const std::vector<@TAP_TYPE@> &taps) { unsigned nfilters = interpolation(); int nt = taps.size() / nfilters; std::vector< std::vector <@TAP_TYPE@> > xtaps(nfilters); for(unsigned n = 0; n < nfilters; n++) { xtaps[n].resize (nt); } for(size_t i = 0; i < taps.size(); i++) { xtaps[i % nfilters][i / nfilters] = taps[i]; } for(unsigned n = 0; n < nfilters; n++) { d_firs[n]->set_taps (xtaps[n]); } set_history(nt); d_updated = false; } std::vector<@TAP_TYPE@> @IMPL_NAME@::taps() const { return d_new_taps; } int @NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const @I_TYPE@ *in = (const @I_TYPE@ *)input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[0]; if(d_updated) { install_taps(d_new_taps); return 0; // history requirements may have changed. } int nfilters = interpolation(); int ni = noutput_items / interpolation(); for(int i = 0; i < ni; i++) { for(int nf = 0; nf < nfilters; nf++) { out[nf] = d_firs[nf]->filter(&in[i]); } out += nfilters; } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fractional_interpolator_cc_impl.cc0000664000175000017500000000677412207440367024731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "fractional_interpolator_cc_impl.h" #include namespace gr { namespace filter { fractional_interpolator_cc::sptr fractional_interpolator_cc::make(float phase_shift, float interp_ratio) { return gnuradio::get_initial_sptr( new fractional_interpolator_cc_impl(phase_shift, interp_ratio)); } fractional_interpolator_cc_impl::fractional_interpolator_cc_impl (float phase_shift, float interp_ratio) : block("fractional_interpolator_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_mu (phase_shift), d_mu_inc (interp_ratio), d_interp(new mmse_fir_interpolator_cc()) { GR_LOG_WARN(d_logger, "fractional_interpolator is deprecated. Please use fractional_resampler instead."); if(interp_ratio <= 0) throw std::out_of_range("interpolation ratio must be > 0"); if(phase_shift < 0 || phase_shift > 1) throw std::out_of_range("phase shift ratio must be > 0 and < 1"); set_relative_rate(1.0 / interp_ratio); } fractional_interpolator_cc_impl::~fractional_interpolator_cc_impl() { delete d_interp; } void fractional_interpolator_cc_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) { ninput_items_required[i] = (int)ceil((noutput_items * d_mu_inc) + d_interp->ntaps()); } } int fractional_interpolator_cc_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; int ii = 0; // input index int oo = 0; // output index while(oo < noutput_items) { out[oo++] = d_interp->interpolate(&in[ii], d_mu); double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } consume_each(ii); return noutput_items; } float fractional_interpolator_cc_impl::mu() const { return d_mu; } float fractional_interpolator_cc_impl::interp_ratio() const { return d_mu_inc; } void fractional_interpolator_cc_impl::set_mu(float mu) { d_mu = mu; } void fractional_interpolator_cc_impl::set_interp_ratio(float interp_ratio) { d_mu_inc = interp_ratio; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_mmse_fir_interpolator_cc.h0000644000175000017500000000260412021532024023656 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_MMSE_FIR_INTERPOLATOR_CC_H_ #define _QA_MMSE_FIR_INTERPOLATOR_CC_H_ #include #include namespace gr { namespace filter { class qa_mmse_fir_interpolator_cc : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_mmse_fir_interpolator_cc); CPPUNIT_TEST(t1); // CPPUNIT_TEST(t2); CPPUNIT_TEST_SUITE_END(); private: void t1(); void t2(); void t2_body(); }; } /* namespace filter */ } /* namespace gr */ #endif /* _QA_MMSE_FIR_INTERPOLATOR_CC_H_ */ gnuradio-3.7.2.1/gr-filter/lib/fft_filter_ccc_impl.h0000664000175000017500000000346512207440367022130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FFT_FILTER_CCC_IMPL_H #define INCLUDED_FILTER_FFT_FILTER_CCC_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API fft_filter_ccc_impl : public fft_filter_ccc { private: int d_nsamples; bool d_updated; kernel::fft_filter_ccc *d_filter; std::vector d_new_taps; public: fft_filter_ccc_impl(int decimation, const std::vector &taps, int nthreads=1); ~fft_filter_ccc_impl(); void set_taps(const std::vector &taps); std::vector taps() const; void set_nthreads(int n); int nthreads() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FFT_FILTER_CCC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/dc_blocker_cc_impl.h0000664000175000017500000000401212207440367021715 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_DC_BLOCKER_CC_IMPL_H #define INCLUDED_FILTER_DC_BLOCKER_CC_IMPL_H #include #include namespace gr { namespace filter { class moving_averager_c { public: moving_averager_c(int D); ~moving_averager_c(); gr_complex filter(gr_complex x); gr_complex delayed_sig() { return d_out; } private: int d_length; gr_complex d_out, d_out_d1, d_out_d2; std::deque d_delay_line; }; class FILTER_API dc_blocker_cc_impl : public dc_blocker_cc { private: int d_length; bool d_long_form; moving_averager_c *d_ma_0; moving_averager_c *d_ma_1; moving_averager_c *d_ma_2; moving_averager_c *d_ma_3; std::deque d_delay_line; public: dc_blocker_cc_impl(int D, bool long_form); ~dc_blocker_cc_impl(); int group_delay(); //int set_length(int D); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_DC_BLOCKER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/rational_resampler_base_XXX_impl.cc.t0000664000175000017500000001077212207440367025217 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@IMPL_NAME@.h" #include #include #include namespace gr { namespace filter { @BASE_NAME@::sptr @BASE_NAME@::make(unsigned interpolation, unsigned decimation, const std::vector<@TAP_TYPE@> &taps) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(interpolation, decimation, taps)); } @IMPL_NAME@::@IMPL_NAME@(unsigned interpolation, unsigned decimation, const std::vector<@TAP_TYPE@> &taps) : block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_history(1), d_interpolation(interpolation), d_decimation(decimation), d_ctr(0), d_firs(interpolation), d_updated(false) { if(interpolation == 0) throw std::out_of_range("@IMPL_NAME@: interpolation must be > 0"); if(decimation == 0) throw std::out_of_range("@IMPL_NAME@: decimation must be > 0"); set_relative_rate(1.0 * interpolation / decimation); set_output_multiple(1); std::vector<@TAP_TYPE@> dummy_taps; for(unsigned i = 0; i < interpolation; i++) { d_firs[i] = new kernel::@FIR_TYPE@(1, dummy_taps); } set_taps(taps); install_taps(d_new_taps); } @IMPL_NAME@::~@IMPL_NAME@() { int interp = interpolation(); for(int i = 0; i < interp; i++) { delete d_firs[i]; } } void @IMPL_NAME@::set_taps(const std::vector<@TAP_TYPE@> &taps) { d_new_taps = taps; d_updated = true; // round up length to a multiple of the interpolation factor int n = taps.size() % interpolation(); if(n > 0) { n = interpolation() - n; while(n-- > 0) { d_new_taps.insert(d_new_taps.begin(), 0); } } assert(d_new_taps.size() % interpolation() == 0); } void @IMPL_NAME@::install_taps(const std::vector<@TAP_TYPE@> &taps) { int nfilters = interpolation(); int nt = taps.size() / nfilters; assert(nt * nfilters == (int) taps.size()); std::vector< std::vector <@TAP_TYPE@> > xtaps(nfilters); for(int n = 0; n < nfilters; n++) xtaps[n].resize (nt); for(int i = 0; i < (int)taps.size(); i++) xtaps[i % nfilters][i / nfilters] = taps[i]; for(int n = 0; n < nfilters; n++) d_firs[n]->set_taps(xtaps[n]); set_history(nt); d_updated = false; } std::vector<@TAP_TYPE@> @IMPL_NAME@::taps() const { return d_new_taps; } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int nreqd = std::max((unsigned)1, (int)((double) (noutput_items+1) * \ decimation() / interpolation()) + history() - 1); unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = nreqd; } int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const @I_TYPE@ *in = (const @I_TYPE@ *)input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[0]; if(d_updated) { install_taps(d_new_taps); return 0; // history requirement may have increased. } unsigned int ctr = d_ctr; int i = 0; while(i < noutput_items) { out[i++] = d_firs[ctr]->filter(in); ctr += decimation(); while(ctr >= interpolation()) { ctr -= interpolation(); in++; } } d_ctr = ctr; consume_each(in - (@I_TYPE@*)input_items[0]); return i; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fractional_interpolator_ff_impl.cc0000664000175000017500000000673112207440367024730 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "fractional_interpolator_ff_impl.h" #include namespace gr { namespace filter { fractional_interpolator_ff::sptr fractional_interpolator_ff::make(float phase_shift, float interp_ratio) { return gnuradio::get_initial_sptr( new fractional_interpolator_ff_impl(phase_shift, interp_ratio)); } fractional_interpolator_ff_impl::fractional_interpolator_ff_impl (float phase_shift, float interp_ratio) : block("fractional_interpolator_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), d_mu (phase_shift), d_mu_inc (interp_ratio), d_interp(new mmse_fir_interpolator_ff()) { GR_LOG_WARN(d_logger, "fractional_interpolator is deprecated. Please use fractional_resampler instead."); if(interp_ratio <= 0) throw std::out_of_range("interpolation ratio must be > 0"); if(phase_shift < 0 || phase_shift > 1) throw std::out_of_range("phase shift ratio must be > 0 and < 1"); set_relative_rate(1.0 / interp_ratio); } fractional_interpolator_ff_impl::~fractional_interpolator_ff_impl() { delete d_interp; } void fractional_interpolator_ff_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) { ninput_items_required[i] = (int)ceil((noutput_items * d_mu_inc) + d_interp->ntaps()); } } int fractional_interpolator_ff_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; int ii = 0; // input index int oo = 0; // output index while(oo < noutput_items) { out[oo++] = d_interp->interpolate(&in[ii], d_mu); double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } consume_each(ii); return noutput_items; } float fractional_interpolator_ff_impl::mu() const { return d_mu; } float fractional_interpolator_ff_impl::interp_ratio() const { return d_mu_inc; } void fractional_interpolator_ff_impl::set_mu(float mu) { d_mu = mu; } void fractional_interpolator_ff_impl::set_interp_ratio(float interp_ratio) { d_mu_inc = interp_ratio; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_arb_resampler_ccf_impl.cc0000664000175000017500000001132312207440367023602 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pfb_arb_resampler_ccf_impl.h" #include #include namespace gr { namespace filter { pfb_arb_resampler_ccf::sptr pfb_arb_resampler_ccf::make(float rate, const std::vector &taps, unsigned int filter_size) { return gnuradio::get_initial_sptr (new pfb_arb_resampler_ccf_impl(rate, taps, filter_size)); } pfb_arb_resampler_ccf_impl::pfb_arb_resampler_ccf_impl(float rate, const std::vector &taps, unsigned int filter_size) : block("pfb_arb_resampler_ccf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))) { d_updated = false; d_resamp = new kernel::pfb_arb_resampler_ccf(rate, taps, filter_size); set_history(d_resamp->taps_per_filter()); set_relative_rate(rate); } pfb_arb_resampler_ccf_impl::~pfb_arb_resampler_ccf_impl() { delete d_resamp; } void pfb_arb_resampler_ccf_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); if(noutput_items / relative_rate() < 1) { for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = max_output_buffer(i)-1; } else { for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = noutput_items/relative_rate() + history() - 1; } } void pfb_arb_resampler_ccf_impl::set_taps(const std::vector &taps) { gr::thread::scoped_lock guard(d_mutex); d_resamp->set_taps(taps); set_history(d_resamp->taps_per_filter()); d_updated = true; } std::vector > pfb_arb_resampler_ccf_impl::taps() const { return d_resamp->taps(); } void pfb_arb_resampler_ccf_impl::print_taps() { d_resamp->print_taps(); } void pfb_arb_resampler_ccf_impl::set_rate(float rate) { gr::thread::scoped_lock guard(d_mutex); d_resamp->set_rate(rate); set_relative_rate(rate); } void pfb_arb_resampler_ccf_impl::set_phase(float ph) { gr::thread::scoped_lock guard(d_mutex); d_resamp->set_phase(ph); } float pfb_arb_resampler_ccf_impl::phase() const { return d_resamp->phase(); } unsigned int pfb_arb_resampler_ccf_impl::interpolation_rate() const { return d_resamp->interpolation_rate(); } unsigned int pfb_arb_resampler_ccf_impl::decimation_rate() const { return d_resamp->decimation_rate(); } float pfb_arb_resampler_ccf_impl::fractional_rate() const { return d_resamp->fractional_rate(); } unsigned int pfb_arb_resampler_ccf_impl::taps_per_filter() const { return d_resamp->taps_per_filter(); } int pfb_arb_resampler_ccf_impl::group_delay() const { return d_resamp->group_delay(); } float pfb_arb_resampler_ccf_impl::phase_offset(float freq, float fs) { return d_resamp->phase_offset(freq, fs); } int pfb_arb_resampler_ccf_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock guard(d_mutex); gr_complex *in = (gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } int nitems_read; int nitems = floorf((float)noutput_items / relative_rate()); int processed = d_resamp->filter(out, in, nitems, nitems_read); consume_each(nitems_read); return processed; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fft_filter_fff_impl.cc0000664000175000017500000000567212207440367022301 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fft_filter_fff_impl.h" #include #include #include #include namespace gr { namespace filter { fft_filter_fff::sptr fft_filter_fff::make(int decimation, const std::vector &taps, int nthreads) { return gnuradio::get_initial_sptr(new fft_filter_fff_impl (decimation, taps, nthreads)); } fft_filter_fff_impl::fft_filter_fff_impl(int decimation, const std::vector &taps, int nthreads) : sync_decimator("fft_filter_fff", io_signature::make (1, 1, sizeof(float)), io_signature::make (1, 1, sizeof(float)), decimation), d_updated(false) { set_history(1); d_filter = new kernel::fft_filter_fff(decimation, taps, nthreads); d_new_taps = taps; d_nsamples = d_filter->set_taps(taps); set_output_multiple(d_nsamples); } fft_filter_fff_impl::~fft_filter_fff_impl() { delete d_filter; } void fft_filter_fff_impl::set_taps(const std::vector &taps) { d_new_taps = taps; d_updated = true; } std::vector fft_filter_fff_impl::taps() const { return d_new_taps; } void fft_filter_fff_impl::set_nthreads(int n) { if(d_filter) d_filter->set_nthreads(n); } int fft_filter_fff_impl::nthreads() const { if(d_filter) return d_filter->nthreads(); else return 0; } int fft_filter_fff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; float *out = (float *)output_items[0]; if (d_updated){ d_nsamples = d_filter->set_taps(d_new_taps); d_updated = false; set_output_multiple(d_nsamples); return 0; // output multiple may have changed } d_filter->filter(noutput_items, in, out); return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/filter_delay_fc_impl.cc0000664000175000017500000000553412207440367022444 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "filter_delay_fc_impl.h" #include namespace gr { namespace filter { filter_delay_fc::sptr filter_delay_fc::make(const std::vector &taps) { return gnuradio::get_initial_sptr(new filter_delay_fc_impl(taps)); } filter_delay_fc_impl::filter_delay_fc_impl(const std::vector &taps) : sync_block("filter_delay_fc", io_signature::make(1, 2, sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))), d_update(false) { d_taps = taps; d_fir = new kernel::fir_filter_fff(1, taps); d_delay = d_fir->ntaps() / 2; set_history(d_fir->ntaps()); const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } filter_delay_fc_impl::~filter_delay_fc_impl() { delete d_fir; } std::vector filter_delay_fc_impl::taps() { return d_fir->taps(); } void filter_delay_fc_impl::set_taps(const std::vector &taps) { // don't reset taps in case history changes d_taps = taps; d_update = true; } int filter_delay_fc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *in0 = (float *)input_items[0]; float *in1 = (float *)input_items[1]; gr_complex *out = (gr_complex *)output_items[0]; if(d_update) { d_fir->set_taps(d_taps); d_delay = d_fir->ntaps() / 2; set_history(d_fir->ntaps()); return 0; } switch(input_items.size ()) { case 1: for(int i = 0; i < noutput_items; i++) { out[i] = gr_complex(in0[i + d_delay], d_fir->filter(&in0[i])); } break; case 2: for(int j = 0; j < noutput_items; j++) { out[j] = gr_complex(in0[j + d_delay], d_fir->filter(&in1[j])); } break; default: assert(0); } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fir_filter_with_buffer.cc0000664000175000017500000003063412241734612023015 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include namespace gr { namespace filter { namespace kernel { fir_filter_with_buffer_fff::fir_filter_with_buffer_fff(const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(float)); d_buffer_ptr = NULL; d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_float(1); } fir_filter_with_buffer_fff::~fir_filter_with_buffer_fff() { if(d_buffer_ptr != NULL) { fft::free(d_buffer_ptr); d_buffer_ptr = NULL; } // Free aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_with_buffer_fff::set_taps(const std::vector &taps) { if(d_buffer_ptr != NULL) { fft::free(d_buffer_ptr); d_buffer_ptr = NULL; } // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // We allocate enough to be able to look back and forth // d_naligned beyond the buffer boundaries and make sure these // are zeroed out (or they may be nan, which will cause // problems). We then set d_buffer to the position in the // d_buffer_ptr such that we only touch the internally // allocated space. d_buffer_ptr = fft::malloc_float(2*(d_ntaps + d_naligned)); memset(d_buffer_ptr, 0, 2*(d_ntaps + d_naligned)*sizeof(float)); d_buffer = d_buffer_ptr + d_naligned; // Allocate aligned taps d_aligned_taps = (float**)malloc(d_naligned*sizeof(float*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_float(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(float)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } d_idx = 0; } std::vector fir_filter_with_buffer_fff::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } float fir_filter_with_buffer_fff::filter(float input) { d_buffer[d_idx] = input; d_buffer[d_idx+ntaps()] = input; d_idx++; if(d_idx >= ntaps()) d_idx = 0; const float *ar = (float*)((unsigned long)(&d_buffer[d_idx]) & ~(d_align-1)); unsigned al = (&d_buffer[d_idx]) - ar; volk_32f_x2_dot_prod_32f_a(d_output, ar, d_aligned_taps[al], ntaps()+al); return *d_output; } float fir_filter_with_buffer_fff::filter(const float input[], unsigned long dec) { unsigned int i; for(i = 0; i < dec; i++) { d_buffer[d_idx] = input[i]; d_buffer[d_idx+ntaps()] = input[i]; d_idx++; if(d_idx >= ntaps()) d_idx = 0; } const float *ar = (float*)((unsigned long)(&d_buffer[d_idx]) & ~(d_align-1)); unsigned al = (&d_buffer[d_idx]) - ar; volk_32f_x2_dot_prod_32f_a(d_output, ar, d_aligned_taps[al], ntaps()+al); return *d_output; } void fir_filter_with_buffer_fff::filterN(float output[], const float input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) { output[i] = filter(input[i]); } } void fir_filter_with_buffer_fff::filterNdec(float output[], const float input[], unsigned long n, unsigned long decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++) { output[i] = filter(&input[j], decimate); j += decimate; } } /**************************************************************/ fir_filter_with_buffer_ccc::fir_filter_with_buffer_ccc(const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(gr_complex)); d_buffer_ptr = NULL; d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_complex(1); } fir_filter_with_buffer_ccc::~fir_filter_with_buffer_ccc() { if(d_buffer_ptr != NULL) { fft::free(d_buffer_ptr); d_buffer_ptr = NULL; } // Free aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_with_buffer_ccc::set_taps(const std::vector &taps) { if(d_buffer_ptr != NULL) { fft::free(d_buffer_ptr); d_buffer_ptr = NULL; } // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // We allocate enough to be able to look back and forth // d_naligned beyond the buffer boundaries and make sure these // are zeroed out (or they may be nan, which will cause // problems). We then set d_buffer to the position in the // d_buffer_ptr such that we only touch the internally // allocated space. d_buffer_ptr = fft::malloc_complex(2*(d_ntaps + d_naligned)); memset(d_buffer_ptr, 0, 2*(d_ntaps + d_naligned)*sizeof(gr_complex)); d_buffer = d_buffer_ptr + d_naligned; // Allocate aligned taps d_aligned_taps = (gr_complex**)malloc(d_naligned*sizeof(gr_complex*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_complex(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(gr_complex)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } d_idx = 0; } std::vector fir_filter_with_buffer_ccc::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } gr_complex fir_filter_with_buffer_ccc::filter(gr_complex input) { d_buffer[d_idx] = input; d_buffer[d_idx+ntaps()] = input; d_idx++; if(d_idx >= ntaps()) d_idx = 0; const gr_complex *ar = (gr_complex *)((unsigned long)(&d_buffer[d_idx]) & ~(d_align-1)); unsigned al = (&d_buffer[d_idx]) - ar; volk_32fc_x2_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], (ntaps()+al)); return *d_output; } gr_complex fir_filter_with_buffer_ccc::filter(const gr_complex input[], unsigned long dec) { unsigned int i; for(i = 0; i < dec; i++) { d_buffer[d_idx] = input[i]; d_buffer[d_idx+ntaps()] = input[i]; d_idx++; if(d_idx >= ntaps()) d_idx = 0; } const gr_complex *ar = (gr_complex *)((unsigned long)(&d_buffer[d_idx]) & ~(d_align-1)); unsigned al = (&d_buffer[d_idx]) - ar; volk_32fc_x2_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], (ntaps()+al)); return *d_output; } void fir_filter_with_buffer_ccc::filterN(gr_complex output[], const gr_complex input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) { output[i] = filter(input[i]); } } void fir_filter_with_buffer_ccc::filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned long decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++) { output[i] = filter(&input[j], decimate); j += decimate; } } /**************************************************************/ fir_filter_with_buffer_ccf::fir_filter_with_buffer_ccf(const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(gr_complex)); d_buffer_ptr = NULL; d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_complex(1); } fir_filter_with_buffer_ccf::~fir_filter_with_buffer_ccf() { if(d_buffer_ptr != NULL) { fft::free(d_buffer_ptr); d_buffer_ptr = NULL; } // Free aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_with_buffer_ccf::set_taps(const std::vector &taps) { if(d_buffer_ptr != NULL) { fft::free(d_buffer_ptr); d_buffer_ptr = NULL; } // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // We allocate enough to be able to look back and forth // d_naligned beyond the buffer boundaries and make sure these // are zeroed out (or they may be nan, which will cause // problems). We then set d_buffer to the position in the // d_buffer_ptr such that we only touch the internally // allocated space. d_buffer_ptr = fft::malloc_complex(2*(d_ntaps + d_naligned)); memset(d_buffer_ptr, 0, 2*(d_ntaps + d_naligned)*sizeof(gr_complex)); d_buffer = d_buffer_ptr + d_naligned; // Allocate aligned taps d_aligned_taps = (float**)malloc(d_naligned*sizeof(float*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_float(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(float)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } d_idx = 0; } std::vector fir_filter_with_buffer_ccf::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } gr_complex fir_filter_with_buffer_ccf::filter(gr_complex input) { d_buffer[d_idx] = input; d_buffer[d_idx+ntaps()] = input; d_idx++; if(d_idx >= ntaps()) d_idx = 0; const gr_complex *ar = (gr_complex *)((unsigned long)(&d_buffer[d_idx]) & ~(d_align-1)); unsigned al = (&d_buffer[d_idx]) - ar; volk_32fc_32f_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], ntaps()+al); return *d_output; } gr_complex fir_filter_with_buffer_ccf::filter(const gr_complex input[], unsigned long dec) { unsigned int i; for(i = 0; i < dec; i++) { d_buffer[d_idx] = input[i]; d_buffer[d_idx+ntaps()] = input[i]; d_idx++; if(d_idx >= ntaps()) d_idx = 0; } const gr_complex *ar = (gr_complex *)((unsigned long)(&d_buffer[d_idx]) & ~(d_align-1)); unsigned al = (&d_buffer[d_idx]) - ar; volk_32fc_32f_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], ntaps()+al); return *d_output; } void fir_filter_with_buffer_ccf::filterN(gr_complex output[], const gr_complex input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) { output[i] = filter(input[i]); } } void fir_filter_with_buffer_ccf::filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned long decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++) { output[i] = filter(&input[j], decimate); j += decimate; } } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_firdes.h0000644000175000017500000000277112021532024020067 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_FILTER_FIRDES_H_ #define _QA_FILTER_FIRDES_H_ #include #include namespace gr { namespace filter { class qa_firdes : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_firdes); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST(t4); CPPUNIT_TEST(t5); CPPUNIT_TEST(t6); CPPUNIT_TEST(t7); CPPUNIT_TEST_SUITE_END(); private: void t1(); void t2(); void t3(); void t4(); void t5(); void t6(); void t7(); }; } /* namespace filter */ } /* namespace gr */ #endif /* _QA_FILTER_FIRDES_H_ */ gnuradio-3.7.2.1/gr-filter/lib/adaptive_fir_ccc_impl.cc0000664000175000017500000000547312245466767022616 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "adaptive_fir_ccc_impl.h" #include namespace gr { namespace filter { adaptive_fir_ccc::sptr adaptive_fir_ccc::make(const char *name, int decimation, const std::vector &taps) { return gnuradio::get_initial_sptr(new adaptive_fir_ccc_impl (name, decimation, taps)); } adaptive_fir_ccc_impl::adaptive_fir_ccc_impl(const char *name, int decimation, const std::vector &taps) : sync_decimator(name, io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), decimation), kernel::adaptive_fir_ccc(decimation, taps), d_updated(false) { set_history(d_ntaps); } void adaptive_fir_ccc_impl::set_taps(const std::vector &taps) { d_new_taps = taps; d_updated = true; } std::vector adaptive_fir_ccc_impl::taps() const { return kernel::fir_filter_ccc::taps(); } gr_complex adaptive_fir_ccc_impl::error(const gr_complex &out) { return 0; } void adaptive_fir_ccc_impl::update_tap(gr_complex &tap, const gr_complex &in) { tap = tap; } int adaptive_fir_ccc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; if (d_updated) { kernel::fir_filter_ccc::set_taps(d_new_taps); set_history(d_ntaps); d_updated = false; return 0; // history requirements may have changed. } // Call base class filtering function that uses // overloaded error and update_tap functions. if (decimation() == 1) { filterN(out, in, noutput_items); } else { filterNdec(out, in, noutput_items, decimation()); } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fractional_interpolator_cc_impl.h0000664000175000017500000000361712207440367024564 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_INTERPOLATOR_CC_IMPL_H #define INCLUDED_FRACTIONAL_INTERPOLATOR_CC_IMPL_H #include #include namespace gr { namespace filter { class FILTER_API fractional_interpolator_cc_impl : public fractional_interpolator_cc { private: float d_mu; float d_mu_inc; mmse_fir_interpolator_cc *d_interp; public: fractional_interpolator_cc_impl(float phase_shift, float interp_ratio); ~fractional_interpolator_cc_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const; float interp_ratio() const; void set_mu(float mu); void set_interp_ratio(float interp_ratio); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_INTERPOLATOR_CC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/mmse_fir_interpolator_ff.cc0000664000175000017500000000372012207440367023361 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include namespace gr { namespace filter { mmse_fir_interpolator_ff::mmse_fir_interpolator_ff() { filters.resize(NSTEPS + 1); for(int i = 0; i < NSTEPS + 1; i++) { std::vector t(&taps[i][0], &taps[i][NTAPS]); filters[i] = new kernel::fir_filter_fff(1, t); } } mmse_fir_interpolator_ff::~mmse_fir_interpolator_ff() { for(int i = 0; i < NSTEPS + 1; i++) delete filters[i]; } unsigned mmse_fir_interpolator_ff::ntaps() const { return NTAPS; } unsigned mmse_fir_interpolator_ff::nsteps() const { return NSTEPS; } float mmse_fir_interpolator_ff::interpolate(const float input[], float mu) const { int imu = (int)rint(mu * NSTEPS); if((imu < 0) || (imu > NSTEPS)) { throw std::runtime_error("mmse_fir_interpolator_ff: imu out of bounds.\n"); } float r = filters[imu]->filter(input); return r; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fft_filter_fff_impl.h0000664000175000017500000000343312207440367022134 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_FFT_FILTER_FFF_IMPL_H #define INCLUDED_FILTER_FFT_FILTER_FFF_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API fft_filter_fff_impl : public fft_filter_fff { private: int d_nsamples; bool d_updated; kernel::fft_filter_fff *d_filter; std::vector d_new_taps; public: fft_filter_fff_impl(int decimation, const std::vector &taps, int nthreads=1); ~fft_filter_fff_impl(); void set_taps(const std::vector &taps); std::vector taps() const; void set_nthreads(int n); int nthreads() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_FFT_FILTER_FFF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/fir_filter_XXX_impl.h.t0000664000175000017500000000303212207440367022320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace filter { class FILTER_API @IMPL_NAME@ : public @BASE_NAME@ { private: kernel::@BASE_NAME@ *d_fir; bool d_updated; public: @IMPL_NAME@(int decimation, const std::vector<@TAP_TYPE@> &taps); ~@IMPL_NAME@(); void set_taps(const std::vector<@TAP_TYPE@> &taps); std::vector<@TAP_TYPE@> taps() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/lib/fft_filter.cc0000664000175000017500000002000412237515112020413 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include namespace gr { namespace filter { namespace kernel { #define VERBOSE 0 fft_filter_fff::fft_filter_fff(int decimation, const std::vector &taps, int nthreads) : d_fftsize(-1), d_decimation(decimation), d_fwdfft(0), d_invfft(0), d_nthreads(nthreads) { set_taps(taps); } fft_filter_fff::~fft_filter_fff() { delete d_fwdfft; delete d_invfft; fft::free(d_xformed_taps); } /* * determines d_ntaps, d_nsamples, d_fftsize, d_xformed_taps */ int fft_filter_fff::set_taps(const std::vector &taps) { int i = 0; d_taps = taps; compute_sizes(taps.size()); d_tail.resize(tailsize()); for(i = 0; i < tailsize(); i++) d_tail[i] = 0; float *in = d_fwdfft->get_inbuf(); gr_complex *out = d_fwdfft->get_outbuf(); float scale = 1.0 / d_fftsize; // Compute forward xform of taps. // Copy taps into first ntaps slots, then pad with zeros for (i = 0; i < d_ntaps; i++) in[i] = taps[i] * scale; for (; i < d_fftsize; i++) in[i] = 0; d_fwdfft->execute(); // do the xform // now copy output to d_xformed_taps for (i = 0; i < d_fftsize/2+1; i++) d_xformed_taps[i] = out[i]; return d_nsamples; } // determine and set d_ntaps, d_nsamples, d_fftsize void fft_filter_fff::compute_sizes(int ntaps) { int old_fftsize = d_fftsize; d_ntaps = ntaps; d_fftsize = (int) (2 * pow(2.0, ceil(log(double(ntaps)) / log(2.0)))); d_nsamples = d_fftsize - d_ntaps + 1; if(VERBOSE) { std::cerr << "fft_filter_fff: ntaps = " << d_ntaps << " fftsize = " << d_fftsize << " nsamples = " << d_nsamples << std::endl; } // compute new plans if(d_fftsize != old_fftsize) { delete d_fwdfft; delete d_invfft; d_fwdfft = new fft::fft_real_fwd(d_fftsize); d_invfft = new fft::fft_real_rev(d_fftsize); d_xformed_taps = fft::malloc_complex(d_fftsize/2+1); } } void fft_filter_fff::set_nthreads(int n) { d_nthreads = n; if(d_fwdfft) d_fwdfft->set_nthreads(n); if(d_invfft) d_invfft->set_nthreads(n); } std::vector fft_filter_fff::taps() const { return d_taps; } unsigned int fft_filter_fff::ntaps() const { return d_ntaps; } int fft_filter_fff::nthreads() const { return d_nthreads; } int fft_filter_fff::filter(int nitems, const float *input, float *output) { int dec_ctr = 0; int j = 0; int ninput_items = nitems * d_decimation; for (int i = 0; i < ninput_items; i += d_nsamples){ memcpy(d_fwdfft->get_inbuf(), &input[i], d_nsamples * sizeof(float)); for (j = d_nsamples; j < d_fftsize; j++) d_fwdfft->get_inbuf()[j] = 0; d_fwdfft->execute(); // compute fwd xform gr_complex *a = d_fwdfft->get_outbuf(); gr_complex *b = d_xformed_taps; gr_complex *c = d_invfft->get_inbuf(); volk_32fc_x2_multiply_32fc_a(c, a, b, d_fftsize/2+1); d_invfft->execute(); // compute inv xform // add in the overlapping tail for (j = 0; j < tailsize(); j++) d_invfft->get_outbuf()[j] += d_tail[j]; // copy nsamples to output j = dec_ctr; while (j < d_nsamples) { *output++ = d_invfft->get_outbuf()[j]; j += d_decimation; } dec_ctr = (j - d_nsamples); // stash the tail memcpy(&d_tail[0], d_invfft->get_outbuf() + d_nsamples, tailsize() * sizeof(float)); } return nitems; } /**************************************************************/ fft_filter_ccc::fft_filter_ccc(int decimation, const std::vector &taps, int nthreads) : d_fftsize(-1), d_decimation(decimation), d_fwdfft(0), d_invfft(0), d_nthreads(nthreads) { set_taps(taps); } fft_filter_ccc::~fft_filter_ccc() { delete d_fwdfft; delete d_invfft; fft::free(d_xformed_taps); } /* * determines d_ntaps, d_nsamples, d_fftsize, d_xformed_taps */ int fft_filter_ccc::set_taps(const std::vector &taps) { int i = 0; d_taps = taps; compute_sizes(taps.size()); d_tail.resize(tailsize()); for(i = 0; i < tailsize(); i++) d_tail[i] = 0; gr_complex *in = d_fwdfft->get_inbuf(); gr_complex *out = d_fwdfft->get_outbuf(); float scale = 1.0 / d_fftsize; // Compute forward xform of taps. // Copy taps into first ntaps slots, then pad with zeros for(i = 0; i < d_ntaps; i++) in[i] = taps[i] * scale; for(; i < d_fftsize; i++) in[i] = 0; d_fwdfft->execute(); // do the xform // now copy output to d_xformed_taps for(i = 0; i < d_fftsize; i++) d_xformed_taps[i] = out[i]; return d_nsamples; } // determine and set d_ntaps, d_nsamples, d_fftsize void fft_filter_ccc::compute_sizes(int ntaps) { int old_fftsize = d_fftsize; d_ntaps = ntaps; d_fftsize = (int) (2 * pow(2.0, ceil(log(double(ntaps)) / log(2.0)))); d_nsamples = d_fftsize - d_ntaps + 1; if(VERBOSE) { std::cerr << "fft_filter_ccc: ntaps = " << d_ntaps << " fftsize = " << d_fftsize << " nsamples = " << d_nsamples << std::endl; } // compute new plans if(d_fftsize != old_fftsize) { delete d_fwdfft; delete d_invfft; d_fwdfft = new fft::fft_complex(d_fftsize, true, d_nthreads); d_invfft = new fft::fft_complex(d_fftsize, false, d_nthreads); d_xformed_taps = fft::malloc_complex(d_fftsize); } } void fft_filter_ccc::set_nthreads(int n) { d_nthreads = n; if(d_fwdfft) d_fwdfft->set_nthreads(n); if(d_invfft) d_invfft->set_nthreads(n); } std::vector fft_filter_ccc::taps() const { return d_taps; } unsigned int fft_filter_ccc::ntaps() const { return d_ntaps; } int fft_filter_ccc::nthreads() const { return d_nthreads; } int fft_filter_ccc::filter(int nitems, const gr_complex *input, gr_complex *output) { int dec_ctr = 0; int j = 0; int ninput_items = nitems * d_decimation; for(int i = 0; i < ninput_items; i += d_nsamples) { memcpy(d_fwdfft->get_inbuf(), &input[i], d_nsamples * sizeof(gr_complex)); for(j = d_nsamples; j < d_fftsize; j++) d_fwdfft->get_inbuf()[j] = 0; d_fwdfft->execute(); // compute fwd xform gr_complex *a = d_fwdfft->get_outbuf(); gr_complex *b = d_xformed_taps; gr_complex *c = d_invfft->get_inbuf(); volk_32fc_x2_multiply_32fc_a(c, a, b, d_fftsize); d_invfft->execute(); // compute inv xform // add in the overlapping tail for(j = 0; j < tailsize(); j++) d_invfft->get_outbuf()[j] += d_tail[j]; // copy nsamples to output j = dec_ctr; while(j < d_nsamples) { *output++ = d_invfft->get_outbuf()[j]; j += d_decimation; } dec_ctr = (j - d_nsamples); // stash the tail memcpy(&d_tail[0], d_invfft->get_outbuf() + d_nsamples, tailsize() * sizeof(gr_complex)); } return nitems; } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_arb_resampler_fff_impl.h0000664000175000017500000000443612207440367023461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_ARB_RESAMPLER_FFF_IMPL_H #define INCLUDED_PFB_ARB_RESAMPLER_FFF_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API pfb_arb_resampler_fff_impl : public pfb_arb_resampler_fff { private: kernel::pfb_arb_resampler_fff *d_resamp; bool d_updated; gr::thread::mutex d_mutex; // mutex to protect set/work access public: pfb_arb_resampler_fff_impl(float rate, const std::vector &taps, unsigned int filter_size); ~pfb_arb_resampler_fff_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); void set_taps(const std::vector &taps); std::vector > taps() const; void print_taps(); void set_rate(float rate); void set_phase(float ph); float phase() const; unsigned int interpolation_rate() const; unsigned int decimation_rate() const; float fractional_rate() const; unsigned int taps_per_filter() const; int group_delay() const; float phase_offset(float freq, float fs); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_ARB_RESAMPLER_FFF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/fir_filter_XXX_impl.cc.t0000664000175000017500000000532312207440367022463 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@IMPL_NAME@.h" #include #include namespace gr { namespace filter { @BASE_NAME@::sptr @BASE_NAME@::make(int decimation, const std::vector<@TAP_TYPE@> &taps) { return gnuradio::get_initial_sptr(new @IMPL_NAME@ (decimation, taps)); } @IMPL_NAME@::@IMPL_NAME@(int decimation, const std::vector<@TAP_TYPE@> &taps) : sync_decimator("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@)), decimation) { d_fir = new kernel::@BASE_NAME@(decimation, taps); d_updated = false; set_history(d_fir->ntaps()); const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } @IMPL_NAME@::~@IMPL_NAME@() { delete d_fir; } void @IMPL_NAME@::set_taps(const std::vector<@TAP_TYPE@> &taps) { gr::thread::scoped_lock l(d_setlock); d_fir->set_taps(taps); d_updated = true; } std::vector<@TAP_TYPE@> @IMPL_NAME@::taps() const { return d_fir->taps(); } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_setlock); const @I_TYPE@ *in = (const @I_TYPE@*)input_items[0]; @O_TYPE@ *out = (@O_TYPE@*)output_items[0]; if (d_updated) { set_history(d_fir->ntaps()); d_updated = false; return 0; // history requirements may have changed. } if (decimation() == 1) { d_fir->filterN(out, in, noutput_items); } else { d_fir->filterNdec(out, in, noutput_items, decimation()); } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/freq_xlating_fir_filter_XXX_impl.h.t0000664000175000017500000000404212207440367025065 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * WARNING: This file is automatically generated by cmake. * Any changes made to this file will be overwritten. */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include namespace gr { namespace filter { class FILTER_API @IMPL_NAME@ : public @BASE_NAME@ { protected: std::vector<@TAP_TYPE@> d_proto_taps; kernel::@CFIR_TYPE@ *d_composite_fir; blocks::rotator d_r; double d_center_freq; double d_sampling_freq; bool d_updated; virtual void build_composite_fir(); public: @IMPL_NAME@(int decimation, const std::vector<@TAP_TYPE@> &taps, double center_freq, double sampling_freq); virtual ~@IMPL_NAME@(); void set_center_freq(double center_freq); double center_freq() const; void set_taps(const std::vector<@TAP_TYPE@> &taps); std::vector<@TAP_TYPE@> taps() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/lib/firdes.cc0000664000175000017500000005324612245466767017605 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2007,2008,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include using std::vector; namespace gr { namespace filter { std::vector firdes::window(win_type type, int ntaps, double beta) { return fft::window::build(static_cast(type), ntaps, beta); } // // === Low Pass === // vector firdes::low_pass_2(double gain, double sampling_freq, // Hz double cutoff_freq, // Hz BEGINNING of transition band double transition_width, // Hz width of transition band double attenuation_dB, // attenuation dB win_type window_type, double beta) // used only with Kaiser { sanity_check_1f(sampling_freq, cutoff_freq, transition_width); int ntaps = compute_ntaps_windes(sampling_freq, transition_width, attenuation_dB); // construct the truncated ideal impulse response // [sin(x)/x for the low pass case] vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if (n == 0) taps[n + M] = fwT0 / M_PI * w[n + M]; else { // a little algebra gets this into the more familiar sin(x)/x form taps[n + M] = sin(n * fwT0) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For low-pass, gain @ zero freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M]; gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } vector firdes::low_pass(double gain, double sampling_freq, double cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window_type, double beta) // used only with Kaiser { sanity_check_1f(sampling_freq, cutoff_freq, transition_width); int ntaps = compute_ntaps(sampling_freq, transition_width, window_type, beta); // construct the truncated ideal impulse response // [sin(x)/x for the low pass case] vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if(n == 0) taps[n + M] = fwT0 / M_PI * w[n + M]; else { // a little algebra gets this into the more familiar sin(x)/x form taps[n + M] = sin(n * fwT0) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For low-pass, gain @ zero freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M]; gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } // // === High Pass === // vector firdes::high_pass_2(double gain, double sampling_freq, double cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band double attenuation_dB, // attenuation dB win_type window_type, double beta) // used only with Kaiser { sanity_check_1f(sampling_freq, cutoff_freq, transition_width); int ntaps = compute_ntaps_windes(sampling_freq, transition_width, attenuation_dB); // construct the truncated ideal impulse response times the window function vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if(n == 0) taps[n + M] = (1 - (fwT0 / M_PI)) * w[n + M]; else { // a little algebra gets this into the more familiar sin(x)/x form taps[n + M] = -sin(n * fwT0) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For high-pass, gain @ fs/2 freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M] * cos(n * M_PI); gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } vector firdes::high_pass(double gain, double sampling_freq, double cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window_type, double beta) // used only with Kaiser { sanity_check_1f(sampling_freq, cutoff_freq, transition_width); int ntaps = compute_ntaps(sampling_freq, transition_width, window_type, beta); // construct the truncated ideal impulse response times the window function vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if(n == 0) taps[n + M] = (1 - (fwT0 / M_PI)) * w[n + M]; else { // a little algebra gets this into the more familiar sin(x)/x form taps[n + M] = -sin(n * fwT0) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For high-pass, gain @ fs/2 freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M] * cos(n * M_PI); gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } // // === Band Pass === // vector firdes::band_pass_2(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band double attenuation_dB, // attenuation dB win_type window_type, double beta) // used only with Kaiser { sanity_check_2f(sampling_freq, low_cutoff_freq, high_cutoff_freq, transition_width); int ntaps = compute_ntaps_windes(sampling_freq, transition_width, attenuation_dB); vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * low_cutoff_freq / sampling_freq; double fwT1 = 2 * M_PI * high_cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if (n == 0) taps[n + M] = (fwT1 - fwT0) / M_PI * w[n + M]; else { taps[n + M] = (sin(n * fwT1) - sin(n * fwT0)) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For band-pass, gain @ center freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M] * cos(n * (fwT0 + fwT1) * 0.5); gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } vector firdes::band_pass(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window_type, double beta) // used only with Kaiser { sanity_check_2f(sampling_freq, low_cutoff_freq, high_cutoff_freq, transition_width); int ntaps = compute_ntaps(sampling_freq, transition_width, window_type, beta); // construct the truncated ideal impulse response times the window function vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * low_cutoff_freq / sampling_freq; double fwT1 = 2 * M_PI * high_cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if (n == 0) taps[n + M] = (fwT1 - fwT0) / M_PI * w[n + M]; else { taps[n + M] = (sin(n * fwT1) - sin(n * fwT0)) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For band-pass, gain @ center freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M] * cos(n * (fwT0 + fwT1) * 0.5); gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } // // === Complex Band Pass === // vector firdes::complex_band_pass_2(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band double attenuation_dB, // attenuation dB win_type window_type, double beta) // used only with Kaiser { sanity_check_2f_c(sampling_freq, low_cutoff_freq, high_cutoff_freq, transition_width); int ntaps = compute_ntaps_windes(sampling_freq, transition_width, attenuation_dB); vector taps(ntaps); vector lptaps(ntaps); vector w = window(window_type, ntaps, beta); lptaps = low_pass_2(gain, sampling_freq, (high_cutoff_freq - low_cutoff_freq)/2, transition_width, attenuation_dB, window_type, beta); gr_complex *optr = &taps[0]; float *iptr = &lptaps[0]; float freq = M_PI * (high_cutoff_freq + low_cutoff_freq)/sampling_freq; float phase = 0; if (lptaps.size() & 01) { phase = - freq * ( lptaps.size() >> 1 ); } else phase = - freq/2.0 * ((1 + 2*lptaps.size()) >> 1); for(unsigned int i = 0; i < lptaps.size(); i++) { *optr++ = gr_complex(*iptr * cos(phase), *iptr * sin(phase)); iptr++, phase += freq; } return taps; } vector firdes::complex_band_pass(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window_type, double beta) // used only with Kaiser { sanity_check_2f_c (sampling_freq, low_cutoff_freq, high_cutoff_freq, transition_width); int ntaps = compute_ntaps(sampling_freq, transition_width, window_type, beta); // construct the truncated ideal impulse response times the window function vector taps(ntaps); vector lptaps(ntaps); vector w = window(window_type, ntaps, beta); lptaps = low_pass(gain, sampling_freq, (high_cutoff_freq - low_cutoff_freq)/2, transition_width, window_type, beta); gr_complex *optr = &taps[0]; float *iptr = &lptaps[0]; float freq = M_PI * (high_cutoff_freq + low_cutoff_freq)/sampling_freq; float phase = 0; if(lptaps.size() & 01) { phase = - freq * ( lptaps.size() >> 1 ); } else phase = - freq/2.0 * ((1 + 2*lptaps.size()) >> 1); for(unsigned int i=0;i firdes::band_reject_2(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band double attenuation_dB, // attenuation dB win_type window_type, double beta) // used only with Kaiser { sanity_check_2f(sampling_freq, low_cutoff_freq, high_cutoff_freq, transition_width); int ntaps = compute_ntaps_windes(sampling_freq, transition_width, attenuation_dB); // construct the truncated ideal impulse response times the window function vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * low_cutoff_freq / sampling_freq; double fwT1 = 2 * M_PI * high_cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if (n == 0) taps[n + M] = 1.0 + ((fwT0 - fwT1) / M_PI * w[n + M]); else { taps[n + M] = (sin(n * fwT0) - sin(n * fwT1)) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For band-reject, gain @ zero freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M]; gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } vector firdes::band_reject(double gain, double sampling_freq, double low_cutoff_freq, // Hz center of transition band double high_cutoff_freq, // Hz center of transition band double transition_width, // Hz width of transition band win_type window_type, double beta) // used only with Kaiser { sanity_check_2f(sampling_freq, low_cutoff_freq, high_cutoff_freq, transition_width); int ntaps = compute_ntaps(sampling_freq, transition_width, window_type, beta); // construct the truncated ideal impulse response times the window function vector taps(ntaps); vector w = window(window_type, ntaps, beta); int M = (ntaps - 1) / 2; double fwT0 = 2 * M_PI * low_cutoff_freq / sampling_freq; double fwT1 = 2 * M_PI * high_cutoff_freq / sampling_freq; for(int n = -M; n <= M; n++) { if (n == 0) taps[n + M] = 1.0 + ((fwT0 - fwT1) / M_PI * w[n + M]); else { taps[n + M] = (sin(n * fwT0) - sin(n * fwT1)) / (n * M_PI) * w[n + M]; } } // find the factor to normalize the gain, fmax. // For band-reject, gain @ zero freq = 1.0 double fmax = taps[0 + M]; for(int n = 1; n <= M; n++) fmax += 2 * taps[n + M]; gain /= fmax; // normalize for(int i = 0; i < ntaps; i++) taps[i] *= gain; return taps; } // // Hilbert Transform // vector firdes::hilbert(unsigned int ntaps, win_type windowtype, double beta) { if(!(ntaps & 1)) throw std::out_of_range("Hilbert: Must have odd number of taps"); vector taps(ntaps); vector w = window (windowtype, ntaps, beta); unsigned int h = (ntaps-1)/2; float gain=0; for(unsigned int i = 1; i <= h; i++) { if(i & 1) { float x = 1/(float)i; taps[h+i] = x * w[h+i]; taps[h-i] = -x * w[h-i]; gain = taps[h+i] - gain; } else taps[h+i] = taps[h-i] = 0; } gain = 2 * fabs(gain); for(unsigned int i = 0; i < ntaps; i++) taps[i] /= gain; return taps; } // // Gaussian // vector firdes::gaussian(double gain, double spb, double bt, int ntaps) { vector taps(ntaps); double scale = 0; double dt = 1.0/spb; double s = 1.0/(sqrt(log(2.0)) / (2*M_PI*bt)); double t0 = -0.5 * ntaps; double ts; for(int i=0;i firdes::root_raised_cosine(double gain, double sampling_freq, double symbol_rate, double alpha, int ntaps) { ntaps |= 1; // ensure that ntaps is odd double spb = sampling_freq/symbol_rate; // samples per bit/symbol vector taps(ntaps); double scale = 0; for(int i = 0; i < ntaps; i++) { double x1,x2,x3,num,den; double xindx = i - ntaps/2; x1 = M_PI * xindx/spb; x2 = 4 * alpha * xindx / spb; x3 = x2*x2 - 1; if(fabs(x3) >= 0.000001) { // Avoid Rounding errors... if(i != ntaps/2) num = cos((1+alpha)*x1) + sin((1-alpha)*x1)/(4*alpha*xindx/spb); else num = cos((1+alpha)*x1) + (1-alpha) * M_PI / (4*alpha); den = x3 * M_PI; } else { if(alpha==1) { taps[i] = -1; continue; } x3 = (1-alpha)*x1; x2 = (1+alpha)*x1; num = (sin(x2)*(1+alpha)*M_PI - cos(x3)*((1-alpha)*M_PI*spb)/(4*alpha*xindx) + sin(x3)*spb*spb/(4*alpha*xindx*xindx)); den = -32 * M_PI * alpha * alpha * xindx/spb; } taps[i] = 4 * alpha * num / den; scale += taps[i]; } for(int i = 0; i < ntaps; i++) taps[i] = taps[i] * gain / scale; return taps; } // // === Utilities === // // delta_f / width_factor gives number of taps required. const int MAX_WIDTH_FACTOR = 8; static const float width_factor[8] = { // indexed by win_type 3.3, // WIN_HAMMING 3.1, // WIN_HANN 5.5, // WIN_BLACKMAN 2.0, // WIN_RECTANGULAR //5.0 // WIN_KAISER (guesstimate compromise) //2.0 // WIN_KAISER (guesstimate compromise) 10.0, // WIN_KAISER 6.0, // WIN_BLACKMAN_HARRIS (est.) 3.0, // WIN_BARTLETT (est.) 5.5, // WIN_FLATTOP (est.) }; int firdes::compute_ntaps_windes(double sampling_freq, double transition_width, // this is frequency, not relative frequency double attenuation_dB) { // Based on formula from Multirate Signal Processing for // Communications Systems, fredric j harris int ntaps = (int)(attenuation_dB*sampling_freq/(22.0*transition_width)); if ((ntaps & 1) == 0) // if even... ntaps++; // ...make odd return ntaps; } int firdes::compute_ntaps(double sampling_freq, double transition_width, win_type window_type, double beta) { // normalized transition width double delta_f = transition_width / sampling_freq; // compute number of taps required for given transition width if(window_type >= MAX_WIDTH_FACTOR) throw std::runtime_error("firdes::compute_ntaps: window_type out of range."); int ntaps = (int)(width_factor[window_type] / delta_f + 0.5); if((ntaps & 1) == 0) // if even... ntaps++; // ...make odd return ntaps; } double firdes::bessi0(double x) { double ax,ans; double y; ax=fabs(x); if (ax < 3.75) { y=x/3.75; y*=y; ans=1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492 +y*(0.2659732+y*(0.360768e-1+y*0.45813e-2))))); } else { y=3.75/ax; ans=(exp(ax)/sqrt(ax))*(0.39894228+y*(0.1328592e-1 +y*(0.225319e-2+y*(-0.157565e-2+y*(0.916281e-2 +y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1 +y*0.392377e-2)))))))); } return ans; } void firdes::sanity_check_1f(double sampling_freq, double fa, // cutoff freq double transition_width) { if(sampling_freq <= 0.0) throw std::out_of_range("firdes check failed: sampling_freq > 0"); if(fa <= 0.0 || fa > sampling_freq / 2) throw std::out_of_range("firdes check failed: 0 < fa <= sampling_freq / 2"); if(transition_width <= 0) throw std::out_of_range("gr_dirdes check failed: transition_width > 0"); } void firdes::sanity_check_2f(double sampling_freq, double fa, // first cutoff freq double fb, // second cutoff freq double transition_width) { if (sampling_freq <= 0.0) throw std::out_of_range("firdes check failed: sampling_freq > 0"); if (fa <= 0.0 || fa > sampling_freq / 2) throw std::out_of_range("firdes check failed: 0 < fa <= sampling_freq / 2"); if (fb <= 0.0 || fb > sampling_freq / 2) throw std::out_of_range("firdes check failed: 0 < fb <= sampling_freq / 2"); if (fa > fb) throw std::out_of_range("firdes check failed: fa <= fb"); if (transition_width <= 0) throw std::out_of_range("firdes check failed: transition_width > 0"); } void firdes::sanity_check_2f_c(double sampling_freq, double fa, // first cutoff freq double fb, // second cutoff freq double transition_width) { if(sampling_freq <= 0.0) throw std::out_of_range("firdes check failed: sampling_freq > 0"); if(fa < -sampling_freq / 2 || fa > sampling_freq / 2) throw std::out_of_range("firdes check failed: 0 < fa <= sampling_freq / 2"); if(fb < -sampling_freq / 2 || fb > sampling_freq / 2) throw std::out_of_range("firdes check failed: 0 < fb <= sampling_freq / 2"); if(fa > fb) throw std::out_of_range("firdes check failed: fa <= fb"); if(transition_width <= 0) throw std::out_of_range("firdes check failed: transition_width > 0"); } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_interpolator_ccf_impl.h0000664000175000017500000000360512207440367023354 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_INTERPOLATOR_CCF_IMPL_H #define INCLUDED_PFB_INTERPOLATOR_CCF_IMPL_H #include #include #include #include #include namespace gr { namespace filter { class FILTER_API pfb_interpolator_ccf_impl : public pfb_interpolator_ccf, kernel::polyphase_filterbank { private: bool d_updated; unsigned int d_rate; gr::thread::mutex d_mutex; // mutex to protect set/work access public: pfb_interpolator_ccf_impl(unsigned int interp, const std::vector &taps); ~pfb_interpolator_ccf_impl(); void set_taps(const std::vector &taps); void print_taps(); std::vector > taps() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_INTERPOLATOR_CCF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/dc_blocker_cc_impl.cc0000664000175000017500000000704712241734632022065 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "dc_blocker_cc_impl.h" #include #include namespace gr { namespace filter { moving_averager_c::moving_averager_c(int D) : d_length(D), d_out(0), d_out_d1(0), d_out_d2(0) { d_delay_line = std::deque(d_length-1, gr_complex(0,0)); } moving_averager_c::~moving_averager_c() { } gr_complex moving_averager_c::filter(gr_complex x) { d_out_d1 = d_out; d_delay_line.push_back(x); d_out = d_delay_line[0]; d_delay_line.pop_front(); gr_complex y = x - d_out_d1 + d_out_d2; d_out_d2 = y; return (y / (float)(d_length)); } dc_blocker_cc::sptr dc_blocker_cc::make(int D, bool long_form) { return gnuradio::get_initial_sptr(new dc_blocker_cc_impl(D, long_form)); } dc_blocker_cc_impl::dc_blocker_cc_impl(int D, bool long_form) : sync_block("dc_blocker_cc", io_signature::make (1, 1, sizeof(gr_complex)), io_signature::make (1, 1, sizeof(gr_complex))), d_length(D), d_long_form(long_form) { if(d_long_form) { d_ma_0 = new moving_averager_c(D); d_ma_1 = new moving_averager_c(D); d_ma_2 = new moving_averager_c(D); d_ma_3 = new moving_averager_c(D); d_delay_line = std::deque(d_length-1, gr_complex(0,0)); } else { d_ma_0 = new moving_averager_c(D); d_ma_1 = new moving_averager_c(D); d_ma_2 = NULL; d_ma_3 = NULL; } } dc_blocker_cc_impl::~dc_blocker_cc_impl() { if(d_long_form) { delete d_ma_0; delete d_ma_1; delete d_ma_2; delete d_ma_3; } else { delete d_ma_0; delete d_ma_1; } } int dc_blocker_cc_impl::group_delay() { if(d_long_form) return (2*d_length-2); else return d_length - 1; } int dc_blocker_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; if(d_long_form) { gr_complex y1, y2, y3, y4, d; for(int i = 0; i < noutput_items; i++) { y1 = d_ma_0->filter(in[i]); y2 = d_ma_1->filter(y1); y3 = d_ma_2->filter(y2); y4 = d_ma_3->filter(y3); d_delay_line.push_back(d_ma_0->delayed_sig()); d = d_delay_line[0]; d_delay_line.pop_front(); out[i] = d - y4; } } else { gr_complex y1, y2; for(int i = 0; i < noutput_items; i++) { y1 = d_ma_0->filter(in[i]); y2 = d_ma_1->filter(y1); out[i] = d_ma_0->delayed_sig() - y2; } } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fir_filter.cc0000664000175000017500000004224512241734612020432 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include namespace gr { namespace filter { namespace kernel { fir_filter_fff::fir_filter_fff(int decimation, const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(float)); d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_float(1); } fir_filter_fff::~fir_filter_fff() { // Free all aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_fff::set_taps(const std::vector &taps) { // Free the taps if already allocated if(d_aligned_taps!= NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // Make a set of taps at all possible arch alignments d_aligned_taps = (float**)malloc(d_naligned*sizeof(float*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_float(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(float)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } } void fir_filter_fff::update_tap(float t, unsigned int index) { d_taps[index] = t; for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i][i+index] = t; } } std::vector fir_filter_fff::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } unsigned int fir_filter_fff::ntaps() const { return d_ntaps; } float fir_filter_fff::filter(const float input[]) { const float *ar = (float *)((unsigned long) input & ~(d_align-1)); unsigned al = input - ar; volk_32f_x2_dot_prod_32f_a(d_output, ar, d_aligned_taps[al], d_ntaps+al); return *d_output; } void fir_filter_fff::filterN(float output[], const float input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) { output[i] = filter(&input[i]); } } void fir_filter_fff::filterNdec(float output[], const float input[], unsigned long n, unsigned int decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++) { output[i] = filter(&input[j]); j += decimate; } } /**************************************************************/ fir_filter_ccf::fir_filter_ccf(int decimation, const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(gr_complex)); d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_complex(1); } fir_filter_ccf::~fir_filter_ccf() { // Free all aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_ccf::set_taps(const std::vector &taps) { // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // Make a set of taps at all possible arch alignments d_aligned_taps = (float**)malloc(d_naligned*sizeof(float*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_float(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(float)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } } void fir_filter_ccf::update_tap(float t, unsigned int index) { d_taps[index] = t; for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i][i+index] = t; } } std::vector fir_filter_ccf::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } unsigned int fir_filter_ccf::ntaps() const { return d_ntaps; } gr_complex fir_filter_ccf::filter(const gr_complex input[]) { const gr_complex *ar = (gr_complex *)((unsigned long) input & ~(d_align-1)); unsigned al = input - ar; volk_32fc_32f_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], (d_ntaps+al)); return *d_output; } void fir_filter_ccf::filterN(gr_complex output[], const gr_complex input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) output[i] = filter(&input[i]); } void fir_filter_ccf::filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned int decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++){ output[i] = filter(&input[j]); j += decimate; } } /**************************************************************/ fir_filter_fcc::fir_filter_fcc(int decimation, const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(float)); d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_complex(1); } fir_filter_fcc::~fir_filter_fcc() { // Free all aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_fcc::set_taps(const std::vector &taps) { // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // Make a set of taps at all possible arch alignments d_aligned_taps = (gr_complex**)malloc(d_naligned*sizeof(gr_complex*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_complex(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(gr_complex)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } } void fir_filter_fcc::update_tap(gr_complex t, unsigned int index) { d_taps[index] = t; for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i][i+index] = t; } } std::vector fir_filter_fcc::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } unsigned int fir_filter_fcc::ntaps() const { return d_ntaps; } gr_complex fir_filter_fcc::filter(const float input[]) { const float *ar = (float *)((unsigned long) input & ~(d_align-1)); unsigned al = input - ar; volk_32fc_32f_dot_prod_32fc_a(d_output, d_aligned_taps[al], ar, (d_ntaps+al)); return *d_output; } void fir_filter_fcc::filterN(gr_complex output[], const float input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) output[i] = filter(&input[i]); } void fir_filter_fcc::filterNdec(gr_complex output[], const float input[], unsigned long n, unsigned int decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++){ output[i] = filter(&input[j]); j += decimate; } } /**************************************************************/ fir_filter_ccc::fir_filter_ccc(int decimation, const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(gr_complex)); d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_complex(1); } fir_filter_ccc::~fir_filter_ccc() { // Free all aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_ccc::set_taps(const std::vector &taps) { // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // Make a set of taps at all possible arch alignments d_aligned_taps = (gr_complex**)malloc(d_naligned*sizeof(gr_complex*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_complex(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(gr_complex)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } } void fir_filter_ccc::update_tap(gr_complex t, unsigned int index) { d_taps[index] = t; for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i][i+index] = t; } } std::vector fir_filter_ccc::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } unsigned int fir_filter_ccc::ntaps() const { return d_ntaps; } gr_complex fir_filter_ccc::filter(const gr_complex input[]) { const gr_complex *ar = (gr_complex *)((unsigned long) input & ~(d_align-1)); unsigned al = input - ar; volk_32fc_x2_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], (d_ntaps+al)); return *d_output; } void fir_filter_ccc::filterN(gr_complex output[], const gr_complex input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) output[i] = filter(&input[i]); } void fir_filter_ccc::filterNdec(gr_complex output[], const gr_complex input[], unsigned long n, unsigned int decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++){ output[i] = filter(&input[j]); j += decimate; } } /**************************************************************/ fir_filter_scc::fir_filter_scc(int decimation, const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(short)); d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = fft::malloc_complex(1); } fir_filter_scc::~fir_filter_scc() { // Free all aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_scc::set_taps(const std::vector &taps) { // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // Make a set of taps at all possible arch alignments d_aligned_taps = (gr_complex**)malloc(d_naligned*sizeof(gr_complex*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_complex(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(gr_complex)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } } void fir_filter_scc::update_tap(gr_complex t, unsigned int index) { d_taps[index] = t; for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i][i+index] = t; } } std::vector fir_filter_scc::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } unsigned int fir_filter_scc::ntaps() const { return d_ntaps; } gr_complex fir_filter_scc::filter(const short input[]) { const short *ar = (short *)((unsigned long) input & ~(d_align-1)); unsigned al = input - ar; volk_16i_32fc_dot_prod_32fc_a(d_output, ar, d_aligned_taps[al], (d_ntaps+al)); return *d_output; } void fir_filter_scc::filterN(gr_complex output[], const short input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) output[i] = filter(&input[i]); } void fir_filter_scc::filterNdec(gr_complex output[], const short input[], unsigned long n, unsigned int decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++){ output[i] = filter(&input[j]); j += decimate; } } /**************************************************************/ fir_filter_fsf::fir_filter_fsf(int decimation, const std::vector &taps) { d_align = volk_get_alignment(); d_naligned = std::max((size_t)1, d_align / sizeof(float)); d_aligned_taps = NULL; set_taps(taps); // Make sure the output sample is always aligned, too. d_output = (short*)fft::malloc_float(1); } fir_filter_fsf::~fir_filter_fsf() { // Free all aligned taps if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } // Free output sample fft::free(d_output); } void fir_filter_fsf::set_taps(const std::vector &taps) { // Free the taps if already allocated if(d_aligned_taps != NULL) { for(int i = 0; i < d_naligned; i++) { fft::free(d_aligned_taps[i]); } ::free(d_aligned_taps); d_aligned_taps = NULL; } d_ntaps = (int)taps.size(); d_taps = taps; std::reverse(d_taps.begin(), d_taps.end()); // Make a set of taps at all possible arch alignments d_aligned_taps = (float**)malloc(d_naligned*sizeof(float*)); for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i] = fft::malloc_float(d_ntaps+d_naligned-1); memset(d_aligned_taps[i], 0, sizeof(float)*(d_ntaps+d_naligned-1)); for(unsigned int j = 0; j < d_ntaps; j++) d_aligned_taps[i][i+j] = d_taps[j]; } } void fir_filter_fsf::update_tap(float t, unsigned int index) { d_taps[index] = t; for(int i = 0; i < d_naligned; i++) { d_aligned_taps[i][i+index] = t; } } std::vector fir_filter_fsf::taps() const { std::vector t = d_taps; std::reverse(t.begin(), t.end()); return t; } unsigned int fir_filter_fsf::ntaps() const { return d_ntaps; } short fir_filter_fsf::filter(const float input[]) { const float *ar = (float *)((unsigned long) input & ~(d_align-1)); unsigned al = input - ar; volk_32f_x2_dot_prod_16i_a(d_output, ar, d_aligned_taps[al], (d_ntaps+al)); return *d_output; } void fir_filter_fsf::filterN(short output[], const float input[], unsigned long n) { for(unsigned long i = 0; i < n; i++) output[i] = filter(&input[i]); } void fir_filter_fsf::filterNdec(short output[], const float input[], unsigned long n, unsigned int decimate) { unsigned long j = 0; for(unsigned long i = 0; i < n; i++){ output[i] = filter(&input[j]); j += decimate; } } } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_channelizer_ccf_impl.cc0000664000175000017500000001336612207440367023277 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pfb_channelizer_ccf_impl.h" #include namespace gr { namespace filter { pfb_channelizer_ccf::sptr pfb_channelizer_ccf::make(unsigned int nfilts, const std::vector &taps, float oversample_rate) { return gnuradio::get_initial_sptr(new pfb_channelizer_ccf_impl(nfilts, taps, oversample_rate)); } pfb_channelizer_ccf_impl::pfb_channelizer_ccf_impl(unsigned int nfilts, const std::vector &taps, float oversample_rate) : block("pfb_channelizer_ccf", io_signature::make(nfilts, nfilts, sizeof(gr_complex)), io_signature::make(1, nfilts, sizeof(gr_complex))), polyphase_filterbank(nfilts, taps), d_updated(false), d_oversample_rate(oversample_rate) { // The over sampling rate must be rationally related to the number of channels // in that it must be N/i for i in [1,N], which gives an outputsample rate // of [fs/N, fs] where fs is the input sample rate. // This tests the specified input sample rate to see if it conforms to this // requirement within a few significant figures. double intp = 0; double fltp = modf(nfilts / oversample_rate, &intp); if(fltp != 0.0) throw std::invalid_argument("pfb_channelizer: oversample rate must be N/i for i in [1, N]"); set_relative_rate(1.0/intp); // Default channel map d_channel_map.resize(d_nfilts); for(unsigned int i = 0; i < d_nfilts; i++) { d_channel_map[i] = i; } // Although the filters change, we use this look up table // to set the index of the FFT input buffer, which equivalently // performs the FFT shift operation on every other turn. d_rate_ratio = (int)rintf(d_nfilts / d_oversample_rate); d_idxlut = new int[d_nfilts]; for(unsigned int i = 0; i < d_nfilts; i++) { d_idxlut[i] = d_nfilts - ((i + d_rate_ratio) % d_nfilts) - 1; } // Calculate the number of filtering rounds to do to evenly // align the input vectors with the output channels d_output_multiple = 1; while((d_output_multiple * d_rate_ratio) % d_nfilts != 0) d_output_multiple++; set_output_multiple(d_output_multiple); // History is the length of each filter arm plus 1. // The +1 comes from the channel mapping in the work function // where we start n=1 so that we can look at in[n-1] set_history(d_taps_per_filter+1); } pfb_channelizer_ccf_impl::~pfb_channelizer_ccf_impl() { delete [] d_idxlut; } void pfb_channelizer_ccf_impl::set_taps(const std::vector &taps) { gr::thread::scoped_lock guard(d_mutex); polyphase_filterbank::set_taps(taps); set_history(d_taps_per_filter+1); d_updated = true; } void pfb_channelizer_ccf_impl::print_taps() { polyphase_filterbank::print_taps(); } std::vector > pfb_channelizer_ccf_impl::taps() const { return polyphase_filterbank::taps(); } void pfb_channelizer_ccf_impl::set_channel_map(const std::vector &map) { gr::thread::scoped_lock guard(d_mutex); if(map.size() > 0) { unsigned int max = (unsigned int)*std::max_element(map.begin(), map.end()); if(max >= d_nfilts) { throw std::invalid_argument("pfb_channelizer_ccf_impl::set_channel_map: map range out of bounds.\n"); } d_channel_map = map; } } std::vector pfb_channelizer_ccf_impl::channel_map() const { return d_channel_map; } int pfb_channelizer_ccf_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock guard(d_mutex); gr_complex *in = (gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } size_t noutputs = output_items.size(); int n=1, i=-1, j=0, oo=0, last; int toconsume = (int)rintf(noutput_items/d_oversample_rate); while(n <= toconsume) { j = 0; i = (i + d_rate_ratio) % d_nfilts; last = i; while(i >= 0) { in = (gr_complex*)input_items[j]; d_fft->get_inbuf()[d_idxlut[j]] = d_filters[i]->filter(&in[n]); j++; i--; } i = d_nfilts-1; while(i > last) { in = (gr_complex*)input_items[j]; d_fft->get_inbuf()[d_idxlut[j]] = d_filters[i]->filter(&in[n-1]); j++; i--; } n += (i+d_rate_ratio) >= (int)d_nfilts; // despin through FFT d_fft->execute(); // Send to output channels for(unsigned int nn = 0; nn < noutputs; nn++) { out = (gr_complex*)output_items[nn]; out[oo] = d_fft->get_outbuf()[d_channel_map[nn]]; } oo++; } consume_each(toconsume); return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_arb_resampler_ccf_impl.h0000664000175000017500000000444312207440367023451 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_ARB_RESAMPLER_CCF_IMPL_H #define INCLUDED_PFB_ARB_RESAMPLER_CCF_IMPL_H #include #include #include namespace gr { namespace filter { class FILTER_API pfb_arb_resampler_ccf_impl : public pfb_arb_resampler_ccf { private: kernel::pfb_arb_resampler_ccf *d_resamp; bool d_updated; gr::thread::mutex d_mutex; // mutex to protect set/work access public: pfb_arb_resampler_ccf_impl(float rate, const std::vector &taps, unsigned int filter_size); ~pfb_arb_resampler_ccf_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); void set_taps(const std::vector &taps); std::vector > taps() const; void print_taps(); void set_rate(float rate); void set_phase(float ph); float phase() const; unsigned int interpolation_rate() const; unsigned int decimation_rate() const; float fractional_rate() const; unsigned int taps_per_filter() const; int group_delay() const; float phase_offset(float freq, float fs); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_PFB_ARB_RESAMPLER_CCF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/pfb_interpolator_ccf_impl.cc0000664000175000017500000000542312207440367023512 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pfb_interpolator_ccf_impl.h" #include namespace gr { namespace filter { pfb_interpolator_ccf::sptr pfb_interpolator_ccf::make(unsigned int interp, const std::vector &taps) { return gnuradio::get_initial_sptr (new pfb_interpolator_ccf_impl(interp, taps)); } pfb_interpolator_ccf_impl::pfb_interpolator_ccf_impl(unsigned int interp, const std::vector &taps) : sync_interpolator("pfb_interpolator_ccf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), interp), polyphase_filterbank(interp, taps), d_updated (false), d_rate(interp) { set_history(d_taps_per_filter); } pfb_interpolator_ccf_impl::~pfb_interpolator_ccf_impl() { } void pfb_interpolator_ccf_impl::set_taps(const std::vector &taps) { gr::thread::scoped_lock guard(d_mutex); polyphase_filterbank::set_taps(taps); set_history(d_taps_per_filter); d_updated = true; } void pfb_interpolator_ccf_impl::print_taps() { polyphase_filterbank::print_taps(); } std::vector > pfb_interpolator_ccf_impl::taps() const { return polyphase_filterbank::taps(); } int pfb_interpolator_ccf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } int i = 0, count = 0; while(i < noutput_items) { for(unsigned int j = 0; j < d_rate; j++) { out[i] = d_filters[j]->filter(&in[count]); i++; } count++; } return i; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_fir_filter_with_buffer.cc0000664000175000017500000002565312241734465023511 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include namespace gr { namespace filter { #define MAX_DATA (16383) #define ERR_DELTA (1e-5) static float uniform() { return 2.0 * ((float)(::random()) / RANDOM_MAX - 0.5); // uniformly (-1, 1) } static void random_floats(float *buf, unsigned n) { for(unsigned i = 0; i < n; i++) buf[i] = (float)rint(uniform() * 32767); } static void random_complex(gr_complex *buf, unsigned n) { for(unsigned i = 0; i < n; i++) { float re = rint(uniform() * MAX_DATA); float im = rint(uniform() * MAX_DATA); buf[i] = gr_complex(re, im); } } namespace fff { typedef float i_type; typedef float o_type; typedef float tap_type; typedef float acc_type; using std::vector; static o_type ref_dotprod(const i_type input[], const tap_type taps[], int ntaps) { acc_type sum = 0; for (int i = 0; i < ntaps; i++) { sum += input[i] * taps[i]; } return sum; } void qa_fir_filter_with_buffer_fff::t1() { test_decimate(1); } void qa_fir_filter_with_buffer_fff::t2() { test_decimate(2); } void qa_fir_filter_with_buffer_fff::t3() { test_decimate(5); } // // Test for ntaps in [0,9], and input lengths in [0,17]. // This ensures that we are building the shifted taps correctly, // and exercises all corner cases on input alignment and length. // void qa_fir_filter_with_buffer_fff::test_decimate(unsigned int decimate) { const int MAX_TAPS = 29; const int OUTPUT_LEN = 37; const int INPUT_LEN = MAX_TAPS + OUTPUT_LEN; // Mem aligned buffer not really necessary, but why not? i_type *input = fft::malloc_float(INPUT_LEN); i_type *dline = fft::malloc_float(INPUT_LEN); o_type *expected_output = fft::malloc_float(OUTPUT_LEN); o_type *actual_output = fft::malloc_float(OUTPUT_LEN); tap_type *taps = fft::malloc_float(MAX_TAPS); srandom(0); // we want reproducibility memset(dline, 0, INPUT_LEN*sizeof(i_type)); for(int n = 0; n <= MAX_TAPS; n++) { for(int ol = 0; ol <= OUTPUT_LEN; ol++) { // build random test case random_floats(input, INPUT_LEN); random_floats(taps, MAX_TAPS); // compute expected output values memset(dline, 0, INPUT_LEN*sizeof(i_type)); for(int o = 0; o < (int)(ol/decimate); o++) { // use an actual delay line for this test for(int dd = 0; dd < (int)decimate; dd++) { for(int oo = INPUT_LEN-1; oo > 0; oo--) dline[oo] = dline[oo-1]; dline[0] = input[decimate*o+dd]; } expected_output[o] = ref_dotprod(dline, taps, n); } // build filter vector f1_taps(&taps[0], &taps[n]); kernel::fir_filter_with_buffer_fff *f1 = \ new kernel::fir_filter_with_buffer_fff(f1_taps); // zero the output, then do the filtering memset(actual_output, 0, OUTPUT_LEN*sizeof(o_type)); f1->filterNdec(actual_output, input, ol/decimate, decimate); // check results // // we use a sloppy error margin because on the x86 architecture, // our reference implementation is using 80 bit floating point // arithmetic, while the SSE version is using 32 bit float point // arithmetic. for(int o = 0; o < (int)(ol/decimate); o++) { CPPUNIT_ASSERT_DOUBLES_EQUAL(expected_output[o], actual_output[o], sqrt((float)n)*0.25*MAX_DATA*MAX_DATA * ERR_DELTA); } delete f1; } } fft::free(input); fft::free(dline); fft::free(expected_output); fft::free(actual_output); fft::free(taps); } } /* namespace fff */ /**************************************************************/ namespace ccc { typedef gr_complex i_type; typedef gr_complex o_type; typedef gr_complex tap_type; typedef gr_complex acc_type; using std::vector; static o_type ref_dotprod(const i_type input[], const tap_type taps[], int ntaps) { acc_type sum = 0; for(int i = 0; i < ntaps; i++) { sum += input[i] * taps[i]; } return sum; } void qa_fir_filter_with_buffer_ccc::t1() { test_decimate(1); } void qa_fir_filter_with_buffer_ccc::t2() { test_decimate(2); } void qa_fir_filter_with_buffer_ccc::t3() { test_decimate(5); } // // Test for ntaps in [0,9], and input lengths in [0,17]. // This ensures that we are building the shifted taps correctly, // and exercises all corner cases on input alignment and length. // void qa_fir_filter_with_buffer_ccc::test_decimate(unsigned int decimate) { const int MAX_TAPS = 29; const int OUTPUT_LEN = 37; const int INPUT_LEN = MAX_TAPS + OUTPUT_LEN; // Mem aligned buffer not really necessary, but why not? i_type *input = fft::malloc_complex(INPUT_LEN); i_type *dline = fft::malloc_complex(INPUT_LEN); o_type *expected_output = fft::malloc_complex(OUTPUT_LEN); o_type *actual_output = fft::malloc_complex(OUTPUT_LEN); tap_type *taps = fft::malloc_complex(MAX_TAPS); srandom(0); // we want reproducibility memset(dline, 0, INPUT_LEN*sizeof(i_type)); for(int n = 0; n <= MAX_TAPS; n++) { for(int ol = 0; ol <= OUTPUT_LEN; ol++) { // build random test case random_complex(input, INPUT_LEN); random_complex(taps, MAX_TAPS); // compute expected output values memset(dline, 0, INPUT_LEN*sizeof(i_type)); for(int o = 0; o < (int)(ol/decimate); o++) { // use an actual delay line for this test for(int dd = 0; dd < (int)decimate; dd++) { for(int oo = INPUT_LEN-1; oo > 0; oo--) dline[oo] = dline[oo-1]; dline[0] = input[decimate*o+dd]; } expected_output[o] = ref_dotprod(dline, taps, n); } // build filter vector f1_taps(&taps[0], &taps[n]); kernel::fir_filter_with_buffer_ccc *f1 = \ new kernel::fir_filter_with_buffer_ccc(f1_taps); // zero the output, then do the filtering memset(actual_output, 0, OUTPUT_LEN*sizeof(o_type)); f1->filterNdec(actual_output, input, ol/decimate, decimate); // check results // // we use a sloppy error margin because on the x86 architecture, // our reference implementation is using 80 bit floating point // arithmetic, while the SSE version is using 32 bit float point // arithmetic. for(int o = 0; o < (int)(ol/decimate); o++) { CPPUNIT_ASSERT_COMPLEXES_EQUAL(expected_output[o], actual_output[o], sqrt((float)n)*0.25*MAX_DATA*MAX_DATA * ERR_DELTA); } delete f1; } } fft::free(input); fft::free(dline); fft::free(expected_output); fft::free(actual_output); fft::free(taps); } } /* namespace ccc */ /**************************************************************/ namespace ccf { typedef gr_complex i_type; typedef gr_complex o_type; typedef float tap_type; typedef gr_complex acc_type; using std::vector; static o_type ref_dotprod(const i_type input[], const tap_type taps[], int ntaps) { acc_type sum = 0; for(int i = 0; i < ntaps; i++) { sum += input[i] * taps[i]; } //return gr_complex(121,9)*sum; return sum; } void qa_fir_filter_with_buffer_ccf::t1() { test_decimate(1); } void qa_fir_filter_with_buffer_ccf::t2() { test_decimate(2); } void qa_fir_filter_with_buffer_ccf::t3() { test_decimate(5); } // // Test for ntaps in [0,9], and input lengths in [0,17]. // This ensures that we are building the shifted taps correctly, // and exercises all corner cases on input alignment and length. // void qa_fir_filter_with_buffer_ccf::test_decimate(unsigned int decimate) { const int MAX_TAPS = 29; const int OUTPUT_LEN = 37; const int INPUT_LEN = MAX_TAPS + OUTPUT_LEN; // Mem aligned buffer not really necessary, but why not? i_type *input = fft::malloc_complex(INPUT_LEN); i_type *dline = fft::malloc_complex(INPUT_LEN); o_type *expected_output = fft::malloc_complex(OUTPUT_LEN); o_type *actual_output = fft::malloc_complex(OUTPUT_LEN); tap_type *taps = fft::malloc_float(MAX_TAPS); srandom(0); // we want reproducibility memset(dline, 0, INPUT_LEN*sizeof(i_type)); for(int n = 0; n <= MAX_TAPS; n++) { for(int ol = 0; ol <= OUTPUT_LEN; ol++) { // build random test case random_complex(input, INPUT_LEN); random_floats(taps, MAX_TAPS); // compute expected output values memset(dline, 0, INPUT_LEN*sizeof(i_type)); for(int o = 0; o < (int)(ol/decimate); o++) { // use an actual delay line for this test for(int dd = 0; dd < (int)decimate; dd++) { for(int oo = INPUT_LEN-1; oo > 0; oo--) dline[oo] = dline[oo-1]; dline[0] = input[decimate*o+dd]; } expected_output[o] = ref_dotprod(dline, taps, n); } // build filter vector f1_taps(&taps[0], &taps[n]); kernel::fir_filter_with_buffer_ccf *f1 = \ new kernel::fir_filter_with_buffer_ccf(f1_taps); // zero the output, then do the filtering memset(actual_output, 0, OUTPUT_LEN*sizeof(gr_complex)); f1->filterNdec(actual_output, input, ol/decimate, decimate); // check results // // we use a sloppy error margin because on the x86 architecture, // our reference implementation is using 80 bit floating point // arithmetic, while the SSE version is using 32 bit float point // arithmetic. for(int o = 0; o < (int)(ol/decimate); o++) { CPPUNIT_ASSERT_COMPLEXES_EQUAL(expected_output[o], actual_output[o], sqrt((float)n)*0.25*MAX_DATA*MAX_DATA * ERR_DELTA); } delete f1; } } fft::free(input); fft::free(dline); fft::free(expected_output); fft::free(actual_output); fft::free(taps); } } /* namespace ccf */ } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_decimator_ccf_impl.cc0000664000175000017500000000742212245466767022756 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pfb_decimator_ccf_impl.h" #include namespace gr { namespace filter { pfb_decimator_ccf::sptr pfb_decimator_ccf::make(unsigned int decim, const std::vector &taps, unsigned int channel) { return gnuradio::get_initial_sptr (new pfb_decimator_ccf_impl(decim, taps, channel)); } pfb_decimator_ccf_impl::pfb_decimator_ccf_impl(unsigned int decim, const std::vector &taps, unsigned int channel) : sync_block("pfb_decimator_ccf", io_signature::make(decim, decim, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), polyphase_filterbank(decim, taps), d_updated(false), d_chan(channel) { d_rate = decim; d_rotator = new gr_complex[d_rate]; set_relative_rate(1.0/(float)decim); set_history(d_taps_per_filter); } pfb_decimator_ccf_impl::~pfb_decimator_ccf_impl() { } void pfb_decimator_ccf_impl::set_taps(const std::vector &taps) { gr::thread::scoped_lock guard(d_mutex); polyphase_filterbank::set_taps(taps); set_history(d_taps_per_filter); d_updated = true; } void pfb_decimator_ccf_impl::print_taps() { polyphase_filterbank::print_taps(); } std::vector > pfb_decimator_ccf_impl::taps() const { return polyphase_filterbank::taps(); } #define ROTATEFFT int pfb_decimator_ccf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock guard(d_mutex); gr_complex *in; gr_complex *out = (gr_complex *)output_items[0]; if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } int i; for(i = 0; i < noutput_items; i++) { // Move through filters from bottom to top out[i] = 0; for(int j = d_rate-1; j >= 0; j--) { // Take in the items from the first input stream to d_rate in = (gr_complex*)input_items[d_rate - 1 - j]; // Filter current input stream from bottom filter to top // The rotate them by expj(j*k*2pi/M) where M is the number of filters // (the decimation rate) and k is the channel number to extract // This is the real math that goes on; we abuse the FFT to do this quickly // for decimation rates > N where N is a small number (~5): // out[i] += d_filters[j]->filter(&in[i])*gr_expj(j*d_chan*2*M_PI/d_rate); #ifdef ROTATEFFT d_fft->get_inbuf()[j] = d_filters[j]->filter(&in[i]); #else out[i] += d_filters[j]->filter(&in[i])*d_rotator[i]; #endif } #ifdef ROTATEFFT // Perform the FFT to do the complex multiply despinning for all channels d_fft->execute(); // Select only the desired channel out out[i] = d_fft->get_outbuf()[d_chan]; #endif } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/fractional_resampler_ff_impl.h0000664000175000017500000000362512207440367024041 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_RESAMPLER_FF_IMPL_H #define INCLUDED_FRACTIONAL_RESAMPLER_FF_IMPL_H #include #include namespace gr { namespace filter { class FILTER_API fractional_resampler_ff_impl : public fractional_resampler_ff { private: float d_mu; float d_mu_inc; mmse_fir_interpolator_ff *d_resamp; public: fractional_resampler_ff_impl(float phase_shift, float resamp_ratio); ~fractional_resampler_ff_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const; float resamp_ratio() const; void set_mu(float mu); void set_resamp_ratio(float resamp_ratio); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_RESAMPLER_FF_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/rational_resampler_base_XXX_impl.h.t0000664000175000017500000000417312207440367025057 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace filter { class FILTER_API @IMPL_NAME@ : public @BASE_NAME@ { private: unsigned d_history; unsigned d_interpolation; unsigned d_decimation; unsigned d_ctr; std::vector<@TAP_TYPE@> d_new_taps; std::vector d_firs; bool d_updated; void install_taps(const std::vector<@TAP_TYPE@> &taps); public: @IMPL_NAME@(unsigned interpolation, unsigned decimation, const std::vector<@TAP_TYPE@> &taps); ~@IMPL_NAME@(); unsigned history() const { return d_history; } void set_history(unsigned history) { d_history = history; } unsigned interpolation() const { return d_interpolation; } unsigned decimation() const { return d_decimation; } void set_taps(const std::vector<@TAP_TYPE@> &taps); std::vector<@TAP_TYPE@> taps() const; void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-filter/lib/fractional_resampler_cc_impl.h0000664000175000017500000000362512207440367024033 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FRACTIONAL_RESAMPLER_CC_IMPL_H #define INCLUDED_FRACTIONAL_RESAMPLER_CC_IMPL_H #include #include namespace gr { namespace filter { class FILTER_API fractional_resampler_cc_impl : public fractional_resampler_cc { private: float d_mu; float d_mu_inc; mmse_fir_interpolator_cc *d_resamp; public: fractional_resampler_cc_impl(float phase_shift, float resamp_ratio); ~fractional_resampler_cc_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const; float resamp_ratio() const; void set_mu(float mu); void set_resamp_ratio(float resamp_ratio); }; } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FRACTIONAL_RESAMPLER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-filter/lib/fractional_resampler_cc_impl.cc0000664000175000017500000001011212207702530024147 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2010,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "fractional_resampler_cc_impl.h" #include namespace gr { namespace filter { fractional_resampler_cc::sptr fractional_resampler_cc::make(float phase_shift, float resamp_ratio) { return gnuradio::get_initial_sptr (new fractional_resampler_cc_impl(phase_shift, resamp_ratio)); } fractional_resampler_cc_impl::fractional_resampler_cc_impl (float phase_shift, float resamp_ratio) : block("fractional_resampler_cc", io_signature::make2(1, 2, sizeof(gr_complex), sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))), d_mu(phase_shift), d_mu_inc(resamp_ratio), d_resamp(new mmse_fir_interpolator_cc()) { if(resamp_ratio <= 0) throw std::out_of_range("resampling ratio must be > 0"); if(phase_shift < 0 || phase_shift > 1) throw std::out_of_range("phase shift ratio must be > 0 and < 1"); set_relative_rate(1.0 / resamp_ratio); } fractional_resampler_cc_impl::~fractional_resampler_cc_impl() { delete d_resamp; } void fractional_resampler_cc_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) { ninput_items_required[i] = (int)ceil((noutput_items * d_mu_inc) + d_resamp->ntaps()); } } int fractional_resampler_cc_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; int ii = 0; // input index int oo = 0; // output index if(ninput_items.size() == 1) { while(oo < noutput_items) { out[oo++] = d_resamp->interpolate(&in[ii], d_mu); double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } consume_each(ii); return noutput_items; } else { const float *rr = (const float*)input_items[1]; while(oo < noutput_items) { out[oo++] = d_resamp->interpolate(&in[ii], d_mu); d_mu_inc = rr[ii]; double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } set_relative_rate(1.0 / d_mu_inc); consume_each(ii); return noutput_items; } } float fractional_resampler_cc_impl::mu() const { return d_mu; } float fractional_resampler_cc_impl::resamp_ratio() const { return d_mu_inc; } void fractional_resampler_cc_impl::set_mu(float mu) { d_mu = mu; } void fractional_resampler_cc_impl::set_resamp_ratio(float resamp_ratio) { d_mu_inc = resamp_ratio; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/pfb_synthesizer_ccf_impl.cc0000664000175000017500000002055612231726612023360 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pfb_synthesizer_ccf_impl.h" #include #include namespace gr { namespace filter { pfb_synthesizer_ccf::sptr pfb_synthesizer_ccf::make(unsigned int numchans, const std::vector &taps, bool twox) { return gnuradio::get_initial_sptr (new pfb_synthesizer_ccf_impl(numchans, taps, twox)); } pfb_synthesizer_ccf_impl::pfb_synthesizer_ccf_impl(unsigned int numchans, const std::vector &taps, bool twox) : sync_interpolator("pfb_synthesizer_ccf", io_signature::make(1, numchans, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), (twox ? numchans/2 : numchans)), d_updated(false), d_numchans(numchans), d_state(0) { // set up 2x multiplier; if twox==True, set to 2, otherwise to 1 d_twox = (twox ? 2 : 1); if(d_numchans % d_twox != 0) { throw std::invalid_argument("pfb_synthesizer_ccf: number of channels must be even for 2x oversampling.\n"); } d_filters = std::vector(d_numchans); d_channel_map.resize(d_numchans); // Create a FIR filter for each channel and zero out the taps std::vector vtaps(0, d_numchans); for(unsigned int i = 0; i < d_numchans; i++) { d_filters[i] = new kernel::fir_filter_with_buffer_ccf(vtaps); d_channel_map[i] = i; } // Now, actually set the filters' taps set_taps(taps); // Create the IFFT to handle the input channel rotations d_fft = new fft::fft_complex(d_numchans, false); memset(d_fft->get_inbuf(), 0, d_numchans*sizeof(gr_complex)); set_output_multiple(d_numchans); } pfb_synthesizer_ccf_impl::~pfb_synthesizer_ccf_impl() { delete d_fft; for(unsigned int i = 0; i < d_numchans; i++) { delete d_filters[i]; } } void pfb_synthesizer_ccf_impl::set_taps(const std::vector &taps) { gr::thread::scoped_lock guard(d_mutex); if(d_twox == 1) set_taps1(taps); else set_taps2(taps); // Set the history to ensure enough input items for each filter set_history(d_taps_per_filter+1); d_updated = true; } void pfb_synthesizer_ccf_impl::set_taps1(const std::vector &taps) { unsigned int i,j; unsigned int ntaps = taps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_numchans); // Create d_numchan vectors to store each channel's taps d_taps.resize(d_numchans); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = taps; while((float)(tmp_taps.size()) < d_numchans*d_taps_per_filter) { tmp_taps.push_back(0.0); } // Partition the filter for(i = 0; i < d_numchans; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out d_taps[i] = std::vector(d_taps_per_filter, 0); for(j = 0; j < d_taps_per_filter; j++) { d_taps[i][j] = tmp_taps[i + j*d_numchans]; // add taps to channels in reverse order } // Build a filter for each channel and add it's taps to it d_filters[i]->set_taps(d_taps[i]); } } void pfb_synthesizer_ccf_impl::set_taps2 (const std::vector &taps) { unsigned int i,j; int state = 0; unsigned int ntaps = 2*taps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_numchans); // Create d_numchan vectors to store each channel's taps d_taps.resize(d_numchans); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = taps; while((float)(tmp_taps.size()) < d_numchans*d_taps_per_filter) { tmp_taps.push_back(0.0); } // Partition the filter unsigned int halfchans = d_numchans/2; for(i = 0; i < halfchans; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out d_taps[i] = std::vector(d_taps_per_filter, 0); d_taps[halfchans+i] = std::vector(d_taps_per_filter, 0); state = 0; for(j = 0; j < d_taps_per_filter; j++) { // add taps to channels in reverse order // Zero out every other tap if(state == 0) { d_taps[i][j] = tmp_taps[i + j*halfchans]; d_taps[halfchans + i][j] = 0; state = 1; } else { d_taps[i][j] = 0; d_taps[halfchans + i][j] = tmp_taps[i + j*halfchans]; state = 0; } } // Build a filter for each channel and add it's taps to it d_filters[i]->set_taps(d_taps[i]); d_filters[halfchans + i]->set_taps(d_taps[halfchans + i]); } } void pfb_synthesizer_ccf_impl::print_taps() { unsigned int i, j; for(i = 0; i < d_numchans; i++) { printf("filter[%d]: [", i); for(j = 0; j < d_taps_per_filter; j++) { printf(" %.4e", d_taps[i][j]); } printf("]\n\n"); } } std::vector< std::vector > pfb_synthesizer_ccf_impl::taps() const { return d_taps; } void pfb_synthesizer_ccf_impl::set_channel_map(const std::vector &map) { gr::thread::scoped_lock guard(d_mutex); if(map.size() > 0) { unsigned int max = (unsigned int)*std::max_element(map.begin(), map.end()); if(max >= d_numchans) { throw std::invalid_argument("gr_pfb_synthesizer_ccf::set_channel_map: map range out of bounds.\n"); } d_channel_map = map; // Zero out fft buffer so that unused channels are always 0 memset(d_fft->get_inbuf(), 0, d_numchans*sizeof(gr_complex)); } } std::vector pfb_synthesizer_ccf_impl::channel_map() const { return d_channel_map; } int pfb_synthesizer_ccf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock guard(d_mutex); gr_complex *in = (gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } unsigned int n, i; size_t ninputs = input_items.size(); // Algoritm for critically sampled channels if(d_twox == 1) { for(n = 0; n < noutput_items/d_numchans; n++) { for(i = 0; i < ninputs; i++) { in = (gr_complex*)input_items[i]; d_fft->get_inbuf()[d_channel_map[i]] = in[n]; } // spin through IFFT d_fft->execute(); for(i = 0; i < d_numchans; i++) { out[i] = d_filters[i]->filter(d_fft->get_outbuf()[i]); } out += d_numchans; } } // Algorithm for oversampling by 2x else { unsigned int halfchans = d_numchans/2; for(n = 0; n < noutput_items/halfchans; n++) { for(i = 0; i < ninputs; i++) { in = (gr_complex*)input_items[i]; d_fft->get_inbuf()[d_channel_map[i]] = in[n]; } // spin through IFFT d_fft->execute(); // Output is sum of two filters, but the input buffer to the filters must be circularly // shifted by numchans every time through, done by using d_state to determine which IFFT // buffer position to pull from. for(i = 0; i < halfchans; i++) { out[i] = d_filters[i]->filter(d_fft->get_outbuf()[d_state*halfchans+i]); out[i] += d_filters[halfchans+i]->filter(d_fft->get_outbuf()[(d_state^1)*halfchans+i]); } d_state ^= 1; out += halfchans; } } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/qa_firdes.cc0000664000175000017500000003306512245466767020263 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include namespace gr { namespace filter { #define NELEM(x) (sizeof(x) / sizeof(x[0])) using std::vector; #if 0 static void print_taps(std::ostream &s, vector &v) { for(unsigned int i = 0; i < v.size(); i++) { printf("tap[%2d] = %16.7e\n", i, v[i]); } } #endif static void check_symmetry(vector &v) { int n = v.size(); int m = n / 2; for(int i = 0; i < m; i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(v[i], v[n - i - 1], 1e-9); } const static float t1_exp[53] = { -9.0525491e-04, 2.0713841e-04, 1.2388536e-03, 2.9683491e-04, -1.7744775e-03, -1.3599906e-03, 2.2031884e-03, 3.2744040e-03, -1.8868084e-03, -5.9935520e-03, 6.4301129e-18, 8.9516686e-03, 4.2178580e-03, -1.0998557e-02, -1.1173409e-02, 1.0455756e-02, 2.0686293e-02, -5.2032238e-03, -3.1896964e-02, -7.4998410e-03, 4.3362070e-02, 3.2502845e-02, -5.3328082e-02, -8.5621715e-02, 6.0117975e-02, 3.1128189e-01, 4.3769023e-01, 3.1128189e-01, 6.0117975e-02, -8.5621715e-02, -5.3328082e-02, 3.2502845e-02, 4.3362070e-02, -7.4998410e-03, -3.1896964e-02, -5.2032238e-03, 2.0686293e-02, 1.0455756e-02, -1.1173409e-02, -1.0998557e-02, 4.2178580e-03, 8.9516686e-03, 6.4301129e-18, -5.9935520e-03, -1.8868084e-03, 3.2744040e-03, 2.2031884e-03, -1.3599906e-03, -1.7744775e-03, 2.9683491e-04, 1.2388536e-03, 2.0713841e-04, -9.0525491e-04 }; const static float t2_exp[53] = { 9.0380036e-04, -2.0680559e-04, -1.2368630e-03, -2.9635796e-04, 1.7716263e-03, 1.3578053e-03, -2.1996482e-03, -3.2691427e-03, 1.8837767e-03, 5.9839217e-03, -6.4197810e-18, -8.9372853e-03, -4.2110807e-03, 1.0980885e-02, 1.1155456e-02, -1.0438956e-02, -2.0653054e-02, 5.1948633e-03, 3.1845711e-02, 7.4877902e-03, -4.3292396e-02, -3.2450620e-02, 5.3242393e-02, 8.5484132e-02, -6.0021374e-02, -3.1078172e-01, 5.6184036e-01, -3.1078172e-01, -6.0021374e-02, 8.5484132e-02, 5.3242393e-02, -3.2450620e-02, -4.3292396e-02, 7.4877902e-03, 3.1845711e-02, 5.1948633e-03, -2.0653054e-02, -1.0438956e-02, 1.1155456e-02, 1.0980885e-02, -4.2110807e-03, -8.9372853e-03, -6.4197810e-18, 5.9839217e-03, 1.8837767e-03, -3.2691427e-03, -2.1996482e-03, 1.3578053e-03, 1.7716263e-03, -2.9635796e-04, -1.2368630e-03, -2.0680559e-04, 9.0380036e-04 }; const static float t3_exp[107] = { -1.8970841e-06, -7.1057165e-04, 5.4005696e-04, 4.6233178e-04, 2.0572044e-04, 3.5209916e-04, -1.4098573e-03, 1.1279077e-04, -6.2994129e-04, 1.1450432e-03, 1.3637283e-03, -6.4360141e-04, 3.6509900e-04, -3.2864159e-03, 7.0192874e-04, 3.7524730e-04, 2.0256115e-03, 3.0641893e-03, -3.6618244e-03, 7.5592739e-05, -5.5586505e-03, 2.3849572e-03, 4.0114378e-03, 1.6636450e-03, 4.7835698e-03, -1.0191196e-02, -3.8158931e-04, -5.5551580e-03, 5.3901658e-03, 1.1366769e-02, -3.0000482e-03, 4.9341680e-03, -2.0093076e-02, 5.5752542e-17, 1.2093617e-03, 8.6089745e-03, 2.2382140e-02, -1.6854567e-02, 1.6913920e-03, -3.1222520e-02, 3.2711059e-03, 2.2604836e-02, 8.1451107e-03, 3.7583180e-02, -5.2293688e-02, -8.0551542e-03, -4.0092729e-02, 1.5582236e-02, 9.7452506e-02, -1.6183170e-02, 8.3281815e-02, -2.8196752e-01, -1.0965768e-01, 5.2867508e-01, -1.0965768e-01, -2.8196752e-01, 8.3281815e-02, -1.6183170e-02, 9.7452506e-02, 1.5582236e-02, -4.0092729e-02, -8.0551542e-03, -5.2293688e-02, 3.7583180e-02, 8.1451107e-03, 2.2604836e-02, 3.2711059e-03, -3.1222520e-02, 1.6913920e-03, -1.6854567e-02, 2.2382140e-02, 8.6089745e-03, 1.2093617e-03, 5.5752542e-17, -2.0093076e-02, 4.9341680e-03, -3.0000482e-03, 1.1366769e-02, 5.3901658e-03, -5.5551580e-03, -3.8158931e-04, -1.0191196e-02, 4.7835698e-03, 1.6636450e-03, 4.0114378e-03, 2.3849572e-03, -5.5586505e-03, 7.5592739e-05, -3.6618244e-03, 3.0641893e-03, 2.0256115e-03, 3.7524730e-04, 7.0192874e-04, -3.2864159e-03, 3.6509900e-04, -6.4360141e-04, 1.3637283e-03, 1.1450432e-03, -6.2994129e-04, 1.1279077e-04, -1.4098573e-03, 3.5209916e-04, 2.0572044e-04, 4.6233178e-04, 5.4005696e-04, -7.1057165e-04, -1.8970841e-06 }; const static float t4_exp[] = { // low pass 0.001059958362, 0.0002263929928, -0.001277606934, -0.0009675776237, 0.001592264394, 0.00243603508, -0.001451682881, -0.004769335967, 5.281541594e-18, 0.007567512803, 0.003658855334, -0.009761494584, -0.01011830103, 0.009636915289, 0.0193619132, -0.004935568199, -0.03060629964, -0.007267376408, 0.04236677289, 0.03197422624, -0.05274848267, -0.0850463286, 0.05989059806, 0.31065014, 0.4370569289, 0.31065014, 0.05989059806, -0.0850463286, -0.05274848267, 0.03197422624, 0.04236677289, -0.007267376408, -0.03060629964, -0.004935568199, 0.0193619132, 0.009636915289, -0.01011830103, -0.009761494584, 0.003658855334, 0.007567512803, 5.281541594e-18, -0.004769335967, -0.001451682881, 0.00243603508, 0.001592264394, -0.0009675776237, -0.001277606934, 0.0002263929928, 0.001059958362, }; const static float t5_exp[] = { //high pass -0.001062123571, -0.0002268554381, 0.001280216733, 0.000969554123, -0.001595516922, -0.002441011136, 0.001454648213, 0.004779078532, -5.292330097e-18, -0.007582970895, -0.00366632943, 0.009781434201, 0.01013896987, -0.009656600654, -0.01940146461, 0.004945650231, 0.03066881932, 0.00728222169, -0.04245331511, -0.03203954175, 0.05285623297, 0.08522006124, -0.06001294032, -0.3112847209, 0.5630782247, -0.3112847209, -0.06001294032, 0.08522006124, 0.05285623297, -0.03203954175, -0.04245331511, 0.00728222169, 0.03066881932, 0.004945650231, -0.01940146461, -0.009656600654, 0.01013896987, 0.009781434201, -0.00366632943, -0.007582970895, -5.292330097e-18, 0.004779078532, 0.001454648213, -0.002441011136, -0.001595516922, 0.000969554123, 0.001280216733, -0.0002268554381, -0.001062123571, }; const static float t6_exp[] = { // bandpass 0.0002809273137, -0.001047327649, 7.936541806e-05, -0.0004270860809, 0.0007595835486, 0.0008966081077, -0.0004236323002, 0.0002423936094, -0.002212299034, 0.0004807534278, 0.0002620361629, 0.001443728455, 0.002229931997, -0.002720607212, 5.731141573e-05, -0.004297634587, 0.001878833398, 0.003217151389, 0.001357055153, 0.003965090029, -0.008576190099, -0.0003257228818, -0.004805727862, 0.004721920472, 0.01007549558, -0.002688719891, 0.004467967432, -0.01837076992, 5.119658377e-17, 0.001125075156, 0.008071650751, 0.02113764361, -0.01602453552, 0.001618095324, -0.03004053794, 0.003163811285, 0.0219683405, 0.007950295694, 0.03682873398, -0.05142467469, -0.00794606097, -0.03965795785, 0.01544955093, 0.09681399167, -0.01610304788, 0.08297294378, -0.2811714709, -0.1094062924, 0.5275565982, -0.1094062924, -0.2811714709, 0.08297294378, -0.01610304788, 0.09681399167, 0.01544955093, -0.03965795785, -0.00794606097, -0.05142467469, 0.03682873398, 0.007950295694, 0.0219683405, 0.003163811285, -0.03004053794, 0.001618095324, -0.01602453552, 0.02113764361, 0.008071650751, 0.001125075156, 5.119658377e-17, -0.01837076992, 0.004467967432, -0.002688719891, 0.01007549558, 0.004721920472, -0.004805727862, -0.0003257228818, -0.008576190099, 0.003965090029, 0.001357055153, 0.003217151389, 0.001878833398, -0.004297634587, 5.731141573e-05, -0.002720607212, 0.002229931997, 0.001443728455, 0.0002620361629, 0.0004807534278, -0.002212299034, 0.0002423936094, -0.0004236323002, 0.0008966081077, 0.0007595835486, -0.0004270860809, 7.936541806e-05, -0.001047327649, 0.0002809273137, }; void qa_firdes::t1() { vector taps = firdes::low_pass(1.0, 8000, 1750, 500, firdes::WIN_HAMMING); // cout << "ntaps: " << taps.size() << endl; // print_taps(cout, taps); CPPUNIT_ASSERT_EQUAL(NELEM(t1_exp), taps.size()); for(unsigned int i = 0; i < taps.size(); i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(t1_exp[i], taps[i], 1e-9); check_symmetry(taps); } void qa_firdes::t2() { vector taps = firdes::high_pass(1.0, 8000, 1750, 500, firdes::WIN_HAMMING); // cout << "ntaps: " << taps.size() << endl; // print_taps(cout, taps); CPPUNIT_ASSERT_EQUAL(NELEM(t2_exp), taps.size()); for(unsigned int i = 0; i < taps.size(); i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(t2_exp[i], taps[i], 1e-9); check_symmetry(taps); } void qa_firdes::t3() { vector taps = firdes::band_pass(1.0, 20e6, 5.75e6 - (5.28e6/2), 5.75e6 + (5.28e6/2), 0.62e6, firdes::WIN_HAMMING); // cout << "ntaps: " << taps.size() << endl; // print_taps(cout, taps); CPPUNIT_ASSERT_EQUAL(NELEM(t3_exp), taps.size()); for(unsigned int i = 0; i < taps.size(); i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(t3_exp[i], taps[i], 1e-7); check_symmetry(taps); } void qa_firdes::t4() { vector taps = firdes::low_pass_2(1.0, 8000, 1750, 500, 66, firdes::WIN_HAMMING); // std::cout << "ntaps: " << taps.size() << std::endl; // print_taps(std::cout, taps); CPPUNIT_ASSERT_EQUAL(NELEM(t4_exp), taps.size()); for(unsigned int i = 0; i < taps.size(); i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(t4_exp[i], taps[i], 1e-9); check_symmetry(taps); } void qa_firdes::t5() { vector taps = firdes::high_pass_2(1.0, 8000, 1750, 500, 66, firdes::WIN_HAMMING); // std::cout << "ntaps: " << taps.size() << std::endl; // print_taps(std::cout, taps); CPPUNIT_ASSERT_EQUAL(NELEM(t5_exp), taps.size()); for(unsigned int i = 0; i < taps.size(); i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(t5_exp[i], taps[i], 1e-9); check_symmetry(taps); } void qa_firdes::t6() { vector taps = firdes::band_pass_2(1.0, 20e6, 5.75e6 - (5.28e6/2), 5.75e6 + (5.28e6/2), 0.62e6, 66, firdes::WIN_HAMMING); // std::cout << "ntaps: " << taps.size() << std::endl; // print_taps(std::cout, taps); CPPUNIT_ASSERT_EQUAL(NELEM(t6_exp), taps.size()); for(unsigned int i = 0; i < taps.size(); i++) CPPUNIT_ASSERT_DOUBLES_EQUAL(t6_exp[i], taps[i], 1e-7); check_symmetry(taps); } void qa_firdes::t7() { } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/lib/dc_blocker_ff_impl.cc0000664000175000017500000000667612241734632022102 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "dc_blocker_ff_impl.h" #include #include namespace gr { namespace filter { moving_averager_f::moving_averager_f(int D) : d_length(D), d_out(0), d_out_d1(0), d_out_d2(0) { d_delay_line = std::deque(d_length-1, 0); } moving_averager_f::~moving_averager_f() { } float moving_averager_f::filter(float x) { d_out_d1 = d_out; d_delay_line.push_back(x); d_out = d_delay_line[0]; d_delay_line.pop_front(); float y = x - d_out_d1 + d_out_d2; d_out_d2 = y; return (y / (float)(d_length)); } dc_blocker_ff::sptr dc_blocker_ff::make(int D, bool long_form) { return gnuradio::get_initial_sptr(new dc_blocker_ff_impl(D, long_form)); } dc_blocker_ff_impl::dc_blocker_ff_impl(int D, bool long_form) : sync_block("dc_blocker_ff", io_signature::make (1, 1, sizeof(float)), io_signature::make (1, 1, sizeof(float))), d_length(D), d_long_form(long_form) { if(d_long_form) { d_ma_0 = new moving_averager_f(D); d_ma_1 = new moving_averager_f(D); d_ma_2 = new moving_averager_f(D); d_ma_3 = new moving_averager_f(D); d_delay_line = std::deque(d_length-1, 0); } else { d_ma_0 = new moving_averager_f(D); d_ma_1 = new moving_averager_f(D); d_ma_2 = NULL; d_ma_3 = NULL; } } dc_blocker_ff_impl::~dc_blocker_ff_impl() { if(d_long_form) { delete d_ma_0; delete d_ma_1; delete d_ma_2; delete d_ma_3; } else { delete d_ma_0; delete d_ma_1; } } int dc_blocker_ff_impl::group_delay() { if(d_long_form) return (2*d_length-2); else return d_length - 1; } int dc_blocker_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; if(d_long_form) { float y1, y2, y3, y4, d; for(int i = 0; i < noutput_items; i++) { y1 = d_ma_0->filter(in[i]); y2 = d_ma_1->filter(y1); y3 = d_ma_2->filter(y2); y4 = d_ma_3->filter(y3); d_delay_line.push_back(d_ma_0->delayed_sig()); d = d_delay_line[0]; d_delay_line.pop_front(); out[i] = d - y4; } } else { float y1, y2; for(int i = 0; i < noutput_items; i++) { y1 = d_ma_0->filter(in[i]); y2 = d_ma_1->filter(y1); out[i] = d_ma_0->delayed_sig() - y2; } } return noutput_items; } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-filter/swig/0000755000175000017500000000000012245466767016211 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/swig/CMakeLists.txt0000664000175000017500000000404412207440367020737 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_FILTER_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${FFTW3F_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) # FIXME: rename to filter_swig_doc.i when gnuradio-runtime is updated set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/gr_filter_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/filter ${CMAKE_CURRENT_BINARY_DIR}/../include/gnuradio/filter ) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_TARGET_DEPS filter_generated_includes) set(GR_SWIG_LIBRARIES gnuradio-filter gnuradio-fft) GR_SWIG_MAKE(filter_swig filter_swig.i) GR_SWIG_INSTALL( TARGETS filter_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/filter COMPONENT "filter_python" ) install( FILES filter_swig.i ${CMAKE_CURRENT_BINARY_DIR}/gr_filter_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "filter_swig" ) gnuradio-3.7.2.1/gr-filter/swig/filter_swig.i0000664000175000017500000001750112245466767020707 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define FILTER_API %include "gnuradio.i" //load generated python docstrings %include "gr_filter_swig_doc.i" %{ #include "gnuradio/filter/firdes.h" #include "gnuradio/filter/pm_remez.h" #include "gnuradio/filter/adaptive_fir_ccc.h" #include "gnuradio/filter/adaptive_fir_ccf.h" #include "gnuradio/filter/dc_blocker_cc.h" #include "gnuradio/filter/dc_blocker_ff.h" #include "gnuradio/filter/filter_delay_fc.h" #include "gnuradio/filter/fir_filter_ccc.h" #include "gnuradio/filter/fir_filter_ccf.h" #include "gnuradio/filter/fir_filter_fcc.h" #include "gnuradio/filter/fir_filter_fff.h" #include "gnuradio/filter/fir_filter_fsf.h" #include "gnuradio/filter/fir_filter_scc.h" #include "gnuradio/filter/fft_filter_ccc.h" #include "gnuradio/filter/fft_filter_fff.h" #include "gnuradio/filter/fractional_interpolator_cc.h" #include "gnuradio/filter/fractional_interpolator_ff.h" #include "gnuradio/filter/fractional_resampler_cc.h" #include "gnuradio/filter/fractional_resampler_ff.h" #include "gnuradio/filter/freq_xlating_fir_filter_ccc.h" #include "gnuradio/filter/freq_xlating_fir_filter_ccf.h" #include "gnuradio/filter/freq_xlating_fir_filter_fcc.h" #include "gnuradio/filter/freq_xlating_fir_filter_fcf.h" #include "gnuradio/filter/freq_xlating_fir_filter_scf.h" #include "gnuradio/filter/freq_xlating_fir_filter_scc.h" #include "gnuradio/filter/hilbert_fc.h" #include "gnuradio/filter/iir_filter_ffd.h" #include "gnuradio/filter/interp_fir_filter_ccc.h" #include "gnuradio/filter/interp_fir_filter_ccf.h" #include "gnuradio/filter/interp_fir_filter_fcc.h" #include "gnuradio/filter/interp_fir_filter_fff.h" #include "gnuradio/filter/interp_fir_filter_fsf.h" #include "gnuradio/filter/interp_fir_filter_scc.h" #include "gnuradio/filter/pfb_arb_resampler_ccf.h" #include "gnuradio/filter/pfb_arb_resampler_fff.h" #include "gnuradio/filter/pfb_channelizer_ccf.h" #include "gnuradio/filter/pfb_decimator_ccf.h" #include "gnuradio/filter/pfb_interpolator_ccf.h" #include "gnuradio/filter/pfb_synthesizer_ccf.h" #include "gnuradio/filter/rational_resampler_base_ccc.h" #include "gnuradio/filter/rational_resampler_base_ccf.h" #include "gnuradio/filter/rational_resampler_base_fcc.h" #include "gnuradio/filter/rational_resampler_base_fff.h" #include "gnuradio/filter/rational_resampler_base_fsf.h" #include "gnuradio/filter/rational_resampler_base_scc.h" #include "gnuradio/filter/single_pole_iir_filter_cc.h" #include "gnuradio/filter/single_pole_iir_filter_ff.h" %} %include "gnuradio/filter/firdes.h" %include "gnuradio/filter/pm_remez.h" %include "gnuradio/filter/adaptive_fir_ccc.h" %include "gnuradio/filter/adaptive_fir_ccf.h" %include "gnuradio/filter/dc_blocker_cc.h" %include "gnuradio/filter/dc_blocker_ff.h" %include "gnuradio/filter/filter_delay_fc.h" %include "gnuradio/filter/fir_filter_ccc.h" %include "gnuradio/filter/fir_filter_ccf.h" %include "gnuradio/filter/fir_filter_fcc.h" %include "gnuradio/filter/fir_filter_fff.h" %include "gnuradio/filter/fir_filter_fsf.h" %include "gnuradio/filter/fir_filter_scc.h" %include "gnuradio/filter/fft_filter_ccc.h" %include "gnuradio/filter/fft_filter_fff.h" %include "gnuradio/filter/fractional_interpolator_cc.h" %include "gnuradio/filter/fractional_interpolator_ff.h" %include "gnuradio/filter/fractional_resampler_cc.h" %include "gnuradio/filter/fractional_resampler_ff.h" %include "gnuradio/filter/freq_xlating_fir_filter_ccc.h" %include "gnuradio/filter/freq_xlating_fir_filter_ccf.h" %include "gnuradio/filter/freq_xlating_fir_filter_fcc.h" %include "gnuradio/filter/freq_xlating_fir_filter_fcf.h" %include "gnuradio/filter/freq_xlating_fir_filter_scf.h" %include "gnuradio/filter/freq_xlating_fir_filter_scc.h" %include "gnuradio/filter/hilbert_fc.h" %include "gnuradio/filter/iir_filter_ffd.h" %include "gnuradio/filter/interp_fir_filter_ccc.h" %include "gnuradio/filter/interp_fir_filter_ccf.h" %include "gnuradio/filter/interp_fir_filter_fcc.h" %include "gnuradio/filter/interp_fir_filter_fff.h" %include "gnuradio/filter/interp_fir_filter_fsf.h" %include "gnuradio/filter/interp_fir_filter_scc.h" %include "gnuradio/filter/pfb_arb_resampler_ccf.h" %include "gnuradio/filter/pfb_arb_resampler_fff.h" %include "gnuradio/filter/pfb_channelizer_ccf.h" %include "gnuradio/filter/pfb_decimator_ccf.h" %include "gnuradio/filter/pfb_interpolator_ccf.h" %include "gnuradio/filter/pfb_synthesizer_ccf.h" %include "gnuradio/filter/rational_resampler_base_ccc.h" %include "gnuradio/filter/rational_resampler_base_ccf.h" %include "gnuradio/filter/rational_resampler_base_fcc.h" %include "gnuradio/filter/rational_resampler_base_fff.h" %include "gnuradio/filter/rational_resampler_base_fsf.h" %include "gnuradio/filter/rational_resampler_base_scc.h" %include "gnuradio/filter/single_pole_iir_filter_cc.h" %include "gnuradio/filter/single_pole_iir_filter_ff.h" GR_SWIG_BLOCK_MAGIC2(filter, adaptive_fir_ccc); GR_SWIG_BLOCK_MAGIC2(filter, adaptive_fir_ccf); GR_SWIG_BLOCK_MAGIC2(filter, dc_blocker_cc); GR_SWIG_BLOCK_MAGIC2(filter, dc_blocker_ff); GR_SWIG_BLOCK_MAGIC2(filter, filter_delay_fc); GR_SWIG_BLOCK_MAGIC2(filter, fir_filter_ccc); GR_SWIG_BLOCK_MAGIC2(filter, fir_filter_ccf); GR_SWIG_BLOCK_MAGIC2(filter, fir_filter_fcc); GR_SWIG_BLOCK_MAGIC2(filter, fir_filter_fff); GR_SWIG_BLOCK_MAGIC2(filter, fir_filter_fsf); GR_SWIG_BLOCK_MAGIC2(filter, fir_filter_scc); GR_SWIG_BLOCK_MAGIC2(filter, fft_filter_ccc); GR_SWIG_BLOCK_MAGIC2(filter, fft_filter_fff); GR_SWIG_BLOCK_MAGIC2(filter, fractional_interpolator_cc); GR_SWIG_BLOCK_MAGIC2(filter, fractional_interpolator_ff); GR_SWIG_BLOCK_MAGIC2(filter, fractional_resampler_cc); GR_SWIG_BLOCK_MAGIC2(filter, fractional_resampler_ff); GR_SWIG_BLOCK_MAGIC2(filter, freq_xlating_fir_filter_ccc); GR_SWIG_BLOCK_MAGIC2(filter, freq_xlating_fir_filter_ccf); GR_SWIG_BLOCK_MAGIC2(filter, freq_xlating_fir_filter_fcc); GR_SWIG_BLOCK_MAGIC2(filter, freq_xlating_fir_filter_fcf); GR_SWIG_BLOCK_MAGIC2(filter, freq_xlating_fir_filter_scf); GR_SWIG_BLOCK_MAGIC2(filter, freq_xlating_fir_filter_scc); GR_SWIG_BLOCK_MAGIC2(filter, hilbert_fc); GR_SWIG_BLOCK_MAGIC2(filter, iir_filter_ffd); GR_SWIG_BLOCK_MAGIC2(filter, interp_fir_filter_ccc); GR_SWIG_BLOCK_MAGIC2(filter, interp_fir_filter_ccf); GR_SWIG_BLOCK_MAGIC2(filter, interp_fir_filter_fcc); GR_SWIG_BLOCK_MAGIC2(filter, interp_fir_filter_fff); GR_SWIG_BLOCK_MAGIC2(filter, interp_fir_filter_fsf); GR_SWIG_BLOCK_MAGIC2(filter, interp_fir_filter_scc); GR_SWIG_BLOCK_MAGIC2(filter, pfb_arb_resampler_ccf); GR_SWIG_BLOCK_MAGIC2(filter, pfb_arb_resampler_fff); GR_SWIG_BLOCK_MAGIC2(filter, pfb_channelizer_ccf); GR_SWIG_BLOCK_MAGIC2(filter, pfb_decimator_ccf); GR_SWIG_BLOCK_MAGIC2(filter, pfb_interpolator_ccf); GR_SWIG_BLOCK_MAGIC2(filter, pfb_synthesizer_ccf); GR_SWIG_BLOCK_MAGIC2(filter, rational_resampler_base_ccc); GR_SWIG_BLOCK_MAGIC2(filter, rational_resampler_base_ccf); GR_SWIG_BLOCK_MAGIC2(filter, rational_resampler_base_fcc); GR_SWIG_BLOCK_MAGIC2(filter, rational_resampler_base_fff); GR_SWIG_BLOCK_MAGIC2(filter, rational_resampler_base_fsf); GR_SWIG_BLOCK_MAGIC2(filter, rational_resampler_base_scc); GR_SWIG_BLOCK_MAGIC2(filter, single_pole_iir_filter_cc); GR_SWIG_BLOCK_MAGIC2(filter, single_pole_iir_filter_ff); gnuradio-3.7.2.1/gr-filter/apps/0000775000175000017500000000000012207440367016167 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/apps/CMakeLists.txt0000664000175000017500000000210712207440367020727 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install python files and apps ######################################################################## include(GrPython) GR_PYTHON_INSTALL( PROGRAMS gr_filter_design DESTINATION ${GR_RUNTIME_DIR} COMPONENT "filter_python" ) gnuradio-3.7.2.1/gr-filter/apps/gr_filter_design0000775000175000017500000000164112207440367021425 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio.filter import filter_design import sys # Call filter desgin main function filter_design.main(sys.argv) gnuradio-3.7.2.1/gr-filter/gnuradio-filter.pc.in0000664000175000017500000000043012207440367021245 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-filter Description: GNU Radio's filter signal processing blocks Requires: gnuradio-runtime gnuradio-fft Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-filter Cflags: -I${includedir} gnuradio-3.7.2.1/gr-filter/examples/0000755000175000017500000000000012242521224017027 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-filter/examples/CMakeLists.txt0000664000175000017500000000252312207440367021604 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) # Base stuff GR_PYTHON_INSTALL(PROGRAMS channelize.py chirp_channelize.py decimate.py fft_filter_ccc.py fir_filter_ccc.py fir_filter_fff.py interpolate.py reconstruction.py resampler.py synth_filter.py synth_to_chan.py gr_filtdes_api.py gr_filtdes_callback.py gr_filtdes_restrict.py gr_filtdes_live_upd.py DESTINATION ${GR_PKG_FILTER_EXAMPLES_DIR} COMPONENT "filter_python" ) install( FILES resampler_demo.grc DESTINATION ${GR_PKG_FILTER_EXAMPLES_DIR} COMPONENT "filter_python" ) gnuradio-3.7.2.1/gr-filter/examples/fir_filter_ccc.py0000775000175000017500000000766712242521224022363 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import analog from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: import scipy except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) class example_fir_filter_ccc(gr.top_block): def __init__(self, N, fs, bw, tw, atten, D): gr.top_block.__init__(self) self._nsamps = N self._fs = fs self._bw = bw self._tw = tw self._at = atten self._decim = D taps = filter.firdes.low_pass_2(1, self._fs, self._bw, self._tw, self._at) print "Num. Taps: ", len(taps) self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_gr_complex, self._nsamps) self.filt0 = filter.fir_filter_ccc(self._decim, taps) self.vsnk_src = blocks.vector_sink_c() self.vsnk_out = blocks.vector_sink_c() self.connect(self.src, self.head, self.vsnk_src) self.connect(self.head, self.filt0, self.vsnk_out) def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=10000, help="Number of samples to process [default=%default]") parser.add_option("-s", "--samplerate", type="eng_float", default=8000, help="System sample rate [default=%default]") parser.add_option("-B", "--bandwidth", type="eng_float", default=1000, help="Filter bandwidth [default=%default]") parser.add_option("-T", "--transition", type="eng_float", default=100, help="Transition band [default=%default]") parser.add_option("-A", "--attenuation", type="eng_float", default=80, help="Stopband attenuation [default=%default]") parser.add_option("-D", "--decimation", type="int", default=1, help="Decmation factor [default=%default]") (options, args) = parser.parse_args () put = example_fir_filter_ccc(options.nsamples, options.samplerate, options.bandwidth, options.transition, options.attenuation, options.decimation) put.run() data_src = scipy.array(put.vsnk_src.data()) data_snk = scipy.array(put.vsnk_out.data()) # Plot the signals PSDs nfft = 1024 f1 = pylab.figure(1, figsize=(12,10)) s1 = f1.add_subplot(1,1,1) s1.psd(data_src, NFFT=nfft, noverlap=nfft/4, Fs=options.samplerate) s1.psd(data_snk, NFFT=nfft, noverlap=nfft/4, Fs=options.samplerate) f2 = pylab.figure(2, figsize=(12,10)) s2 = f2.add_subplot(1,1,1) s2.plot(data_src) s2.plot(data_snk.real, 'g') pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/decimate.py0000775000175000017500000001365512207440367021204 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import sys, time try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy from scipy import fftpack except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab from pylab import mlab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 10000000 # number of samples to use self._fs = 10000 # initial sampling rate self._decim = 20 # Decimation rate # Generate the prototype filter taps for the decimators with a 200 Hz bandwidth self._taps = filter.firdes.low_pass_2(1, self._fs, 200, 150, attenuation_dB=120, window=filter.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._decim)) print "Number of taps: ", len(self._taps) print "Number of filters: ", self._decim print "Taps per channel: ", tpc # Build the input signal source # We create a list of freqs, and a sine wave is generated and added to the source # for each one of these frequencies. self.signals = list() self.add = blocks.add_cc() freqs = [10, 20, 2040] for i in xrange(len(freqs)): self.signals.append(analog.sig_source_c(self._fs, analog.GR_SIN_WAVE, freqs[i], 1)) self.connect(self.signals[i], (self.add,i)) self.head = blocks.head(gr.sizeof_gr_complex, self._N) # Construct a PFB decimator filter self.pfb = filter.pfb.decimator_ccf(self._decim, self._taps, 0) # Construct a standard FIR decimating filter self.dec = filter.fir_filter_ccf(self._decim, self._taps) self.snk_i = blocks.vector_sink_c() # Connect the blocks self.connect(self.add, self.head, self.pfb) self.connect(self.add, self.snk_i) # Create the sink for the decimated siganl self.snk = blocks.vector_sink_c() self.connect(self.pfb, self.snk) def main(): tb = pfb_top_block() tstart = time.time() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig1 = pylab.figure(1, figsize=(16,9)) fig2 = pylab.figure(2, figsize=(16,9)) Ns = 10000 Ne = 10000 fftlen = 8192 winfunc = scipy.blackman fs = tb._fs # Plot the input to the decimator d = tb.snk_i.data()[Ns:Ns+Ne] sp1_f = fig1.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) p1_f = sp1_f.plot(f_in, X_in, "b") sp1_f.set_xlim([min(f_in), max(f_in)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title("Input Signal", weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) sp1_t = fig1.add_subplot(2, 1, 2) p1_t = sp1_t.plot(t_in, x_in.real, "b") p1_t = sp1_t.plot(t_in, x_in.imag, "r") sp1_t.set_ylim([-tb._decim*1.1, tb._decim*1.1]) sp1_t.set_xlabel("Time (s)") sp1_t.set_ylabel("Amplitude") # Plot the output of the decimator fs_o = tb._fs / tb._decim sp2_f = fig2.add_subplot(2, 1, 1) d = tb.snk.data()[Ns:Ns+Ne] X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_o = scipy.arange(-fs_o/2.0, fs_o/2.0, fs_o/float(X_o.size)) p2_f = sp2_f.plot(f_o, X_o, "b") sp2_f.set_xlim([min(f_o), max(f_o)+1]) sp2_f.set_ylim([-200.0, 50.0]) sp2_f.set_title("PFB Decimated Signal", weight="bold") sp2_f.set_xlabel("Frequency (Hz)") sp2_f.set_ylabel("Power (dBW)") Ts_o = 1.0/fs_o Tmax_o = len(d)*Ts_o x_o = scipy.array(d) t_o = scipy.arange(0, Tmax_o, Ts_o) sp2_t = fig2.add_subplot(2, 1, 2) p2_t = sp2_t.plot(t_o, x_o.real, "b-o") p2_t = sp2_t.plot(t_o, x_o.imag, "r-o") sp2_t.set_ylim([-2.5, 2.5]) sp2_t.set_xlabel("Time (s)") sp2_t.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/gr_filtdes_restrict.py0000775000175000017500000000301712207440367023461 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio.filter import filter_design import sys try: from PyQt4 import Qt, QtCore, QtGui except ImportError: print "Please install PyQt4 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)" raise SystemExit, 1 ''' Callback with restrict example Function called when "design" button is pressed or pole-zero plot is changed ''' def print_params(filtobj): print "Filter Count:", filtobj.get_filtercount() print "Filter type:", filtobj.get_restype() print "Filter params", filtobj.get_params() print "Filter Coefficients", filtobj.get_taps() app = Qt.QApplication(sys.argv) main_win = filter_design.launch(sys.argv, callback = print_params, restype = "iir") main_win.show() app.exec_() gnuradio-3.7.2.1/gr-filter/examples/synth_filter.py0000775000175000017500000000477012207440367022141 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter from gnuradio import blocks import sys try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) def main(): N = 1000000 fs = 8000 freqs = [100, 200, 300, 400, 500] nchans = 7 sigs = list() for fi in freqs: s = analog.sig_source_c(fs, analog.GR_SIN_WAVE, fi, 1) sigs.append(s) taps = filter.firdes.low_pass_2(len(freqs), fs, fs/float(nchans)/2, 100, 100) print "Num. Taps = %d (taps per filter = %d)" % (len(taps), len(taps)/nchans) filtbank = filter.pfb_synthesizer_ccf(nchans, taps) head = blocks.head(gr.sizeof_gr_complex, N) snk = blocks.vector_sink_c() tb = gr.top_block() tb.connect(filtbank, head, snk) for i,si in enumerate(sigs): tb.connect(si, (filtbank, i)) tb.run() if 1: f1 = pylab.figure(1) s1 = f1.add_subplot(1,1,1) s1.plot(snk.data()[1000:]) fftlen = 2048 f2 = pylab.figure(2) s2 = f2.add_subplot(1,1,1) winfunc = scipy.blackman s2.psd(snk.data()[10000:], NFFT=fftlen, Fs = nchans*fs, noverlap=fftlen/4, window = lambda d: d*winfunc(fftlen)) pylab.show() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-filter/examples/fft_filter_ccc.py0000775000175000017500000001041712242521224022345 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import analog from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: import scipy except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) class example_fft_filter_ccc(gr.top_block): def __init__(self, N, fs, bw0, bw1, tw, atten, D): gr.top_block.__init__(self) self._nsamps = N self._fs = fs self._bw0 = bw0 self._bw1 = bw1 self._tw = tw self._at = atten self._decim = D taps = filter.firdes.complex_band_pass_2(1, self._fs, self._bw0, self._bw1, self._tw, self._at) print "Num. Taps: ", len(taps) self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_gr_complex, self._nsamps) self.filt0 = filter.fft_filter_ccc(self._decim, taps) self.vsnk_src = blocks.vector_sink_c() self.vsnk_out = blocks.vector_sink_c() self.connect(self.src, self.head, self.vsnk_src) self.connect(self.head, self.filt0, self.vsnk_out) def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=10000, help="Number of samples to process [default=%default]") parser.add_option("-s", "--samplerate", type="eng_float", default=8000, help="System sample rate [default=%default]") parser.add_option("-S", "--start-pass", type="eng_float", default=1000, help="Start of Passband [default=%default]") parser.add_option("-E", "--end-pass", type="eng_float", default=2000, help="End of Passband [default=%default]") parser.add_option("-T", "--transition", type="eng_float", default=100, help="Transition band [default=%default]") parser.add_option("-A", "--attenuation", type="eng_float", default=80, help="Stopband attenuation [default=%default]") parser.add_option("-D", "--decimation", type="int", default=1, help="Decmation factor [default=%default]") (options, args) = parser.parse_args () put = example_fft_filter_ccc(options.nsamples, options.samplerate, options.start_pass, options.end_pass, options.transition, options.attenuation, options.decimation) put.run() data_src = scipy.array(put.vsnk_src.data()) data_snk = scipy.array(put.vsnk_out.data()) # Plot the signals PSDs nfft = 1024 f1 = pylab.figure(1, figsize=(12,10)) s1 = f1.add_subplot(1,1,1) s1.psd(data_src, NFFT=nfft, noverlap=nfft/4, Fs=options.samplerate) s1.psd(data_snk, NFFT=nfft, noverlap=nfft/4, Fs=options.samplerate) f2 = pylab.figure(2, figsize=(12,10)) s2 = f2.add_subplot(1,1,1) s2.plot(data_src) s2.plot(data_snk.real, 'g') pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/chirp_channelize.py0000775000175000017500000001600112207440367022722 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import sys, time try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy from scipy import fftpack except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab from pylab import mlab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 200000 # number of samples to use self._fs = 9000 # initial sampling rate self._M = 9 # Number of channels to channelize # Create a set of taps for the PFB channelizer self._taps = filter.firdes.low_pass_2(1, self._fs, 500, 20, attenuation_dB=10, window=filter.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._M)) print "Number of taps: ", len(self._taps) print "Number of channels: ", self._M print "Taps per channel: ", tpc repeated = True if(repeated): self.vco_input = analog.sig_source_f(self._fs, analog.GR_SIN_WAVE, 0.25, 110) else: amp = 100 data = scipy.arange(0, amp, amp/float(self._N)) self.vco_input = blocks.vector_source_f(data, False) # Build a VCO controlled by either the sinusoid or single chirp tone # Then convert this to a complex signal self.vco = blocks.vco_f(self._fs, 225, 1) self.f2c = blocks.float_to_complex() self.head = blocks.head(gr.sizeof_gr_complex, self._N) # Construct the channelizer filter self.pfb = filter.pfb.channelizer_ccf(self._M, self._taps) # Construct a vector sink for the input signal to the channelizer self.snk_i = blocks.vector_sink_c() # Connect the blocks self.connect(self.vco_input, self.vco, self.f2c) self.connect(self.f2c, self.head, self.pfb) self.connect(self.f2c, self.snk_i) # Create a vector sink for each of M output channels of the filter and connect it self.snks = list() for i in xrange(self._M): self.snks.append(blocks.vector_sink_c()) self.connect((self.pfb, i), self.snks[i]) def main(): tstart = time.time() tb = pfb_top_block() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") fig3 = pylab.figure(4, figsize=(16,9), facecolor="w") Ns = 650 Ne = 20000 fftlen = 8192 winfunc = scipy.blackman fs = tb._fs # Plot the input signal on its own figure d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") spin_f.set_xlim([min(f_in), max(f_in)+1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) spin_t = fig_in.add_subplot(2, 1, 2) pin_t = spin_t.plot(t_in, x_in.real, "b") pin_t = spin_t.plot(t_in, x_in.imag, "r") spin_t.set_xlabel("Time (s)") spin_t.set_ylabel("Amplitude") Ncols = int(scipy.floor(scipy.sqrt(tb._M))) Nrows = int(scipy.floor(tb._M / Ncols)) if(tb._M % Ncols != 0): Nrows += 1 # Plot each of the channels outputs. Frequencies on Figure 2 and # time signals on Figure 3 fs_o = tb._fs / tb._M Ts_o = 1.0/fs_o Tmax_o = len(d)*Ts_o for i in xrange(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(X)) f_o = freq p2_f = sp1_f.plot(f_o, X_o, "b") sp1_f.set_xlim([min(f_o), max(f_o)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") x_o = scipy.array(d) t_o = scipy.arange(0, Tmax_o, Ts_o) sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") sp2_o.set_xlim([min(t_o), max(t_o)+1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") sp2_o.set_xlabel("Time (s)") sp2_o.set_ylabel("Amplitude") sp3 = fig3.add_subplot(1,1,1) p3 = sp3.plot(t_o, x_o.real) sp3.set_xlim([min(t_o), max(t_o)+1]) sp3.set_ylim([-2, 2]) sp3.set_title("All Channels") sp3.set_xlabel("Time (s)") sp3.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/gr_filtdes_callback.py0000775000175000017500000000316612207440367023363 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio.filter import filter_design import sys try: from PyQt4 import Qt, QtCore, QtGui except ImportError: print "Please install PyQt4 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)" raise SystemExit, 1 ''' Callback example Function called when "design" button is pressed or pole-zero plot is changed launch function returns gr_filter_design mainwindow object when callback is not None ''' def print_params(filtobj): print "Filter Count:", filtobj.get_filtercount() print "Filter type:", filtobj.get_restype() print "Filter params", filtobj.get_params() print "Filter Coefficients", filtobj.get_taps() app = Qt.QApplication(sys.argv) #launch function returns gr_filter_design mainwindow object main_win = filter_design.launch(sys.argv, print_params) main_win.show() app.exec_() gnuradio-3.7.2.1/gr-filter/examples/resampler_demo.grc0000664000175000017500000003156012207440367022542 0ustar jcorganjcorgan Sun Feb 24 19:43:22 2013 options id resampler_demo _enabled True title author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id rs_taps _enabled True value firdes.low_pass(nphases, nphases, frac_bw, 0.5-frac_bw) _coordinate (273, 154) _rotation 0 variable id nphases _enabled True value 32 _coordinate (185, 153) _rotation 0 variable_static_text id samp_rate _enabled True label Sample Rate value 44100 converver float_converter formatter None grid_pos 0, 0, 1, 1 notebook _coordinate (179, 14) _rotation 0 variable_static_text id new_rate _enabled True label Resampled Rate value 48000 converver float_converter formatter None grid_pos 0, 1, 1, 1 notebook _coordinate (328, 15) _rotation 0 variable_static_text id frac_bw _enabled True label Fractional Bandwidth value 0.45 converver float_converter formatter lambda x: "%0.2f"%x grid_pos 0,2,1,1 notebook _coordinate (473, 14) _rotation 0 pfb_arb_resampler_xxx id pfb_arb_resampler_xxx_0 _enabled True type ccf rrate float(new_rate)/samp_rate taps rs_taps nfilts nphases atten 100 _coordinate (649, 469) _rotation 0 analog_frequency_modulator_fc id analog_frequency_modulator_fc_0 _enabled True sensitivity math.pi _coordinate (429, 501) _rotation 0 wxgui_fftsink2 id orig_fft _enabled True type complex title Original Spectrum samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 30 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos 1, 0, 1, 3 notebook freqvar None _coordinate (414, 279) _rotation 180 wxgui_fftsink2 id resamp_fft _enabled True type complex title Resampled Spectrum samp_rate new_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 30 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold True average False avg_alpha 0 win None win_size grid_pos 2, 0, 1, 3 notebook freqvar None _coordinate (645, 241) _rotation 180 blocks_add_const_vxx id adder _enabled True type float const -1.0 vlen 1 _coordinate (227, 303) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_TRI_WAVE freq 0.05 amp 2 offset 0 _coordinate (36, 271) _rotation 0 import id import_0 _enabled True import import math _coordinate (11, 75) _rotation 0 blocks_throttle id throttle _enabled True type float samples_per_second samp_rate vlen 1 _coordinate (227, 492) _rotation 0 adder throttle 0 0 pfb_arb_resampler_xxx_0 resamp_fft 0 0 throttle analog_frequency_modulator_fc_0 0 0 analog_frequency_modulator_fc_0 pfb_arb_resampler_xxx_0 0 0 analog_frequency_modulator_fc_0 orig_fft 0 0 analog_sig_source_x_0 adder 0 0 gnuradio-3.7.2.1/gr-filter/examples/interpolate.py0000775000175000017500000002116012207440367021745 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import sys, time try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy from scipy import fftpack except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab from pylab import mlab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 100000 # number of samples to use self._fs = 2000 # initial sampling rate self._interp = 5 # Interpolation rate for PFB interpolator self._ainterp = 5.5 # Resampling rate for the PFB arbitrary resampler # Frequencies of the signals we construct freq1 = 100 freq2 = 200 # Create a set of taps for the PFB interpolator # This is based on the post-interpolation sample rate self._taps = filter.firdes.low_pass_2(self._interp, self._interp*self._fs, freq2+50, 50, attenuation_dB=120, window=filter.firdes.WIN_BLACKMAN_hARRIS) # Create a set of taps for the PFB arbitrary resampler # The filter size is the number of filters in the filterbank; 32 will give very low side-lobes, # and larger numbers will reduce these even farther # The taps in this filter are based on a sampling rate of the filter size since it acts # internally as an interpolator. flt_size = 32 self._taps2 = filter.firdes.low_pass_2(flt_size, flt_size*self._fs, freq2+50, 150, attenuation_dB=120, window=filter.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._interp)) print "Number of taps: ", len(self._taps) print "Number of filters: ", self._interp print "Taps per channel: ", tpc # Create a couple of signals at different frequencies self.signal1 = analog.sig_source_c(self._fs, analog.GR_SIN_WAVE, freq1, 0.5) self.signal2 = analog.sig_source_c(self._fs, analog.GR_SIN_WAVE, freq2, 0.5) self.signal = blocks.add_cc() self.head = blocks.head(gr.sizeof_gr_complex, self._N) # Construct the PFB interpolator filter self.pfb = filter.pfb.interpolator_ccf(self._interp, self._taps) # Construct the PFB arbitrary resampler filter self.pfb_ar = filter.pfb.arb_resampler_ccf(self._ainterp, self._taps2, flt_size) self.snk_i = blocks.vector_sink_c() #self.pfb_ar.pfb.print_taps() #self.pfb.pfb.print_taps() # Connect the blocks self.connect(self.signal1, self.head, (self.signal,0)) self.connect(self.signal2, (self.signal,1)) self.connect(self.signal, self.pfb) self.connect(self.signal, self.pfb_ar) self.connect(self.signal, self.snk_i) # Create the sink for the interpolated signals self.snk1 = blocks.vector_sink_c() self.snk2 = blocks.vector_sink_c() self.connect(self.pfb, self.snk1) self.connect(self.pfb_ar, self.snk2) def main(): tb = pfb_top_block() tstart = time.time() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig1 = pylab.figure(1, figsize=(12,10), facecolor="w") fig2 = pylab.figure(2, figsize=(12,10), facecolor="w") fig3 = pylab.figure(3, figsize=(12,10), facecolor="w") Ns = 10000 Ne = 10000 fftlen = 8192 winfunc = scipy.blackman # Plot input signal fs = tb._fs d = tb.snk_i.data()[Ns:Ns+Ne] sp1_f = fig1.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) p1_f = sp1_f.plot(f_in, X_in, "b") sp1_f.set_xlim([min(f_in), max(f_in)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title("Input Signal", weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) sp1_t = fig1.add_subplot(2, 1, 2) p1_t = sp1_t.plot(t_in, x_in.real, "b-o") #p1_t = sp1_t.plot(t_in, x_in.imag, "r-o") sp1_t.set_ylim([-2.5, 2.5]) sp1_t.set_title("Input Signal", weight="bold") sp1_t.set_xlabel("Time (s)") sp1_t.set_ylabel("Amplitude") # Plot output of PFB interpolator fs_int = tb._fs*tb._interp sp2_f = fig2.add_subplot(2, 1, 1) d = tb.snk1.data()[Ns:Ns+(tb._interp*Ne)] X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_o = scipy.arange(-fs_int/2.0, fs_int/2.0, fs_int/float(X_o.size)) p2_f = sp2_f.plot(f_o, X_o, "b") sp2_f.set_xlim([min(f_o), max(f_o)+1]) sp2_f.set_ylim([-200.0, 50.0]) sp2_f.set_title("Output Signal from PFB Interpolator", weight="bold") sp2_f.set_xlabel("Frequency (Hz)") sp2_f.set_ylabel("Power (dBW)") Ts_int = 1.0/fs_int Tmax = len(d)*Ts_int t_o = scipy.arange(0, Tmax, Ts_int) x_o1 = scipy.array(d) sp2_t = fig2.add_subplot(2, 1, 2) p2_t = sp2_t.plot(t_o, x_o1.real, "b-o") #p2_t = sp2_t.plot(t_o, x_o.imag, "r-o") sp2_t.set_ylim([-2.5, 2.5]) sp2_t.set_title("Output Signal from PFB Interpolator", weight="bold") sp2_t.set_xlabel("Time (s)") sp2_t.set_ylabel("Amplitude") # Plot output of PFB arbitrary resampler fs_aint = tb._fs * tb._ainterp sp3_f = fig3.add_subplot(2, 1, 1) d = tb.snk2.data()[Ns:Ns+(tb._interp*Ne)] X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_o = scipy.arange(-fs_aint/2.0, fs_aint/2.0, fs_aint/float(X_o.size)) p3_f = sp3_f.plot(f_o, X_o, "b") sp3_f.set_xlim([min(f_o), max(f_o)+1]) sp3_f.set_ylim([-200.0, 50.0]) sp3_f.set_title("Output Signal from PFB Arbitrary Resampler", weight="bold") sp3_f.set_xlabel("Frequency (Hz)") sp3_f.set_ylabel("Power (dBW)") Ts_aint = 1.0/fs_aint Tmax = len(d)*Ts_aint t_o = scipy.arange(0, Tmax, Ts_aint) x_o2 = scipy.array(d) sp3_f = fig3.add_subplot(2, 1, 2) p3_f = sp3_f.plot(t_o, x_o2.real, "b-o") p3_f = sp3_f.plot(t_o, x_o1.real, "m-o") #p3_f = sp3_f.plot(t_o, x_o2.imag, "r-o") sp3_f.set_ylim([-2.5, 2.5]) sp3_f.set_title("Output Signal from PFB Arbitrary Resampler", weight="bold") sp3_f.set_xlabel("Time (s)") sp3_f.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/gr_filtdes_api.py0000775000175000017500000000231212207440367022370 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio.filter import filter_design import sys ''' API Blocking call returns filter taps for FIR filter design returns b,a for IIR filter design ''' filtobj = filter_design.launch(sys.argv) # Displaying all filter paramters print "Filter Count:", filtobj.get_filtercount() print "Filter type:", filtobj.get_restype() print "Filter params", filtobj.get_params() print "Filter Coefficients", filtobj.get_taps() gnuradio-3.7.2.1/gr-filter/examples/resampler.py0000775000175000017500000001054612207440367021417 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter from gnuradio import blocks import sys try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) class mytb(gr.top_block): def __init__(self, fs_in, fs_out, fc, N=10000): gr.top_block.__init__(self) rerate = float(fs_out) / float(fs_in) print "Resampling from %f to %f by %f " %(fs_in, fs_out, rerate) # Creating our own taps taps = filter.firdes.low_pass_2(32, 32, 0.25, 0.1, 80) self.src = analog.sig_source_c(fs_in, analog.GR_SIN_WAVE, fc, 1) #self.src = analog.noise_source_c(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_gr_complex, N) # A resampler with our taps self.resamp_0 = filter.pfb.arb_resampler_ccf(rerate, taps, flt_size=32) # A resampler that just needs a resampling rate. # Filter is created for us and designed to cover # entire bandwidth of the input signal. # An optional atten=XX rate can be used here to # specify the out-of-band rejection (default=80). self.resamp_1 = filter.pfb.arb_resampler_ccf(rerate) self.snk_in = blocks.vector_sink_c() self.snk_0 = blocks.vector_sink_c() self.snk_1 = blocks.vector_sink_c() self.connect(self.src, self.head, self.snk_in) self.connect(self.head, self.resamp_0, self.snk_0) self.connect(self.head, self.resamp_1, self.snk_1) def main(): fs_in = 8000 fs_out = 20000 fc = 1000 N = 10000 tb = mytb(fs_in, fs_out, fc, N) tb.run() # Plot PSD of signals nfftsize = 2048 fig1 = pylab.figure(1, figsize=(10,10), facecolor="w") sp1 = fig1.add_subplot(2,1,1) sp1.psd(tb.snk_in.data(), NFFT=nfftsize, noverlap=nfftsize/4, Fs = fs_in) sp1.set_title(("Input Signal at f_s=%.2f kHz" % (fs_in/1000.0))) sp1.set_xlim([-fs_in/2, fs_in/2]) sp2 = fig1.add_subplot(2,1,2) sp2.psd(tb.snk_0.data(), NFFT=nfftsize, noverlap=nfftsize/4, Fs = fs_out, label="With our filter") sp2.psd(tb.snk_1.data(), NFFT=nfftsize, noverlap=nfftsize/4, Fs = fs_out, label="With auto-generated filter") sp2.set_title(("Output Signals at f_s=%.2f kHz" % (fs_out/1000.0))) sp2.set_xlim([-fs_out/2, fs_out/2]) sp2.legend() # Plot signals in time Ts_in = 1.0/fs_in Ts_out = 1.0/fs_out t_in = scipy.arange(0, len(tb.snk_in.data())*Ts_in, Ts_in) t_out = scipy.arange(0, len(tb.snk_0.data())*Ts_out, Ts_out) fig2 = pylab.figure(2, figsize=(10,10), facecolor="w") sp21 = fig2.add_subplot(2,1,1) sp21.plot(t_in, tb.snk_in.data()) sp21.set_title(("Input Signal at f_s=%.2f kHz" % (fs_in/1000.0))) sp21.set_xlim([t_in[100], t_in[200]]) sp22 = fig2.add_subplot(2,1,2) sp22.plot(t_out, tb.snk_0.data(), label="With our filter") sp22.plot(t_out, tb.snk_1.data(), label="With auto-generated filter") sp22.set_title(("Output Signals at f_s=%.2f kHz" % (fs_out/1000.0))) r = float(fs_out)/float(fs_in) sp22.set_xlim([t_out[r * 100], t_out[r * 200]]) sp22.legend() pylab.show() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-filter/examples/gr_filtdes_live_upd.py0000775000175000017500000000605712207440367023440 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio.filter import filter_design from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import blocks except ImportError: sys.stderr.write("Error: Program requires gr-blocks.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 1000 f2 = 2000 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) self.filt_taps = [1,] src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_cc() channel = channels.channel_model(0.01) self.filt = filter.fft_filter_ccc(1, self.filt_taps) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) self.snk1 = qtgui.freq_sink_c(npts, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Freq Example", 1) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, self.filt, (self.snk1, 0)) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) pyWin.show() def update_filter(self, filtobj): print "Filter type:", filtobj.get_restype() print "Filter params", filtobj.get_params() self.filt.set_taps(filtobj.get_taps()) if __name__ == "__main__": tb = my_top_block(); tb.start() mw = filter_design.launch(sys.argv, tb.update_filter) mw.show() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-filter/examples/synth_to_chan.py0000775000175000017500000000741612207440367022267 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import sys try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) def main(): N = 1000000 fs = 8000 freqs = [100, 200, 300, 400, 500] nchans = 7 sigs = list() fmtx = list() for fi in freqs: s = analog.sig_source_f(fs, analog.GR_SIN_WAVE, fi, 1) fm = analog.nbfm_tx(fs, 4*fs, max_dev=10000, tau=75e-6) sigs.append(s) fmtx.append(fm) syntaps = filter.firdes.low_pass_2(len(freqs), fs, fs/float(nchans)/2, 100, 100) print "Synthesis Num. Taps = %d (taps per filter = %d)" % (len(syntaps), len(syntaps)/nchans) chtaps = filter.firdes.low_pass_2(len(freqs), fs, fs/float(nchans)/2, 100, 100) print "Channelizer Num. Taps = %d (taps per filter = %d)" % (len(chtaps), len(chtaps)/nchans) filtbank = filter.pfb_synthesizer_ccf(nchans, syntaps) channelizer = filter.pfb.channelizer_ccf(nchans, chtaps) noise_level = 0.01 head = blocks.head(gr.sizeof_gr_complex, N) noise = analog.noise_source_c(analog.GR_GAUSSIAN, noise_level) addnoise = blocks.add_cc() snk_synth = blocks.vector_sink_c() tb = gr.top_block() tb.connect(noise, (addnoise,0)) tb.connect(filtbank, head, (addnoise, 1)) tb.connect(addnoise, channelizer) tb.connect(addnoise, snk_synth) snk = list() for i,si in enumerate(sigs): tb.connect(si, fmtx[i], (filtbank, i)) for i in xrange(nchans): snk.append(blocks.vector_sink_c()) tb.connect((channelizer, i), snk[i]) tb.run() if 1: channel = 1 data = snk[channel].data()[1000:] f1 = pylab.figure(1) s1 = f1.add_subplot(1,1,1) s1.plot(data[10000:10200] ) s1.set_title(("Output Signal from Channel %d" % channel)) fftlen = 2048 winfunc = scipy.blackman #winfunc = scipy.hamming f2 = pylab.figure(2) s2 = f2.add_subplot(1,1,1) s2.psd(data, NFFT=fftlen, Fs = nchans*fs, noverlap=fftlen/4, window = lambda d: d*winfunc(fftlen)) s2.set_title(("Output PSD from Channel %d" % channel)) f3 = pylab.figure(3) s3 = f3.add_subplot(1,1,1) s3.psd(snk_synth.data()[1000:], NFFT=fftlen, Fs = nchans*fs, noverlap=fftlen/4, window = lambda d: d*winfunc(fftlen)) s3.set_title("Output of Synthesis Filter") pylab.show() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-filter/examples/channelize.py0000775000175000017500000001553312207440367021546 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import sys, time try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy from scipy import fftpack except ImportError: sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n") sys.exit(1) try: import pylab from pylab import mlab except ImportError: sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n") sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 2000000 # number of samples to use self._fs = 1000 # initial sampling rate self._M = M = 9 # Number of channels to channelize self._ifs = M*self._fs # initial sampling rate # Create a set of taps for the PFB channelizer self._taps = filter.firdes.low_pass_2(1, self._ifs, 475.50, 50, attenuation_dB=100, window=filter.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._M)) print "Number of taps: ", len(self._taps) print "Number of channels: ", self._M print "Taps per channel: ", tpc # Create a set of signals at different frequencies # freqs lists the frequencies of the signals that get stored # in the list "signals", which then get summed together self.signals = list() self.add = blocks.add_cc() freqs = [-70, -50, -30, -10, 10, 20, 40, 60, 80] for i in xrange(len(freqs)): f = freqs[i] + (M/2-M+i+1)*self._fs self.signals.append(analog.sig_source_c(self._ifs, analog.GR_SIN_WAVE, f, 1)) self.connect(self.signals[i], (self.add,i)) self.head = blocks.head(gr.sizeof_gr_complex, self._N) # Construct the channelizer filter self.pfb = filter.pfb.channelizer_ccf(self._M, self._taps, 1) # Construct a vector sink for the input signal to the channelizer self.snk_i = blocks.vector_sink_c() # Connect the blocks self.connect(self.add, self.head, self.pfb) self.connect(self.add, self.snk_i) # Use this to play with the channel mapping #self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4]) # Create a vector sink for each of M output channels of the filter and connect it self.snks = list() for i in xrange(self._M): self.snks.append(blocks.vector_sink_c()) self.connect((self.pfb, i), self.snks[i]) def main(): tstart = time.time() tb = pfb_top_block() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") Ns = 1000 Ne = 10000 fftlen = 8192 winfunc = scipy.blackman fs = tb._ifs # Plot the input signal on its own figure d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(X)) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") spin_f.set_xlim([min(f_in), max(f_in)+1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) spin_t = fig_in.add_subplot(2, 1, 2) pin_t = spin_t.plot(t_in, x_in.real, "b") pin_t = spin_t.plot(t_in, x_in.imag, "r") spin_t.set_xlabel("Time (s)") spin_t.set_ylabel("Amplitude") Ncols = int(scipy.floor(scipy.sqrt(tb._M))) Nrows = int(scipy.floor(tb._M / Ncols)) if(tb._M % Ncols != 0): Nrows += 1 # Plot each of the channels outputs. Frequencies on Figure 2 and # time signals on Figure 3 fs_o = tb._fs Ts_o = 1.0/fs_o Tmax_o = len(d)*Ts_o for i in xrange(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(X)) f_o = scipy.arange(-fs_o/2.0, fs_o/2.0, fs_o/float(X_o.size)) p2_f = sp1_f.plot(f_o, X_o, "b") sp1_f.set_xlim([min(f_o), max(f_o)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") x_o = scipy.array(d) t_o = scipy.arange(0, Tmax_o, Ts_o) sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") sp2_o.set_xlim([min(t_o), max(t_o)+1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") sp2_o.set_xlabel("Time (s)") sp2_o.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/benchmark_filters.py0000775000175000017500000000523712207440367023110 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import time import random from optparse import OptionParser from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option def make_random_complex_tuple(L): result = [] for x in range(L): result.append(complex(random.uniform(-1000,1000), random.uniform(-1000,1000))) return tuple(result) def benchmark(name, creator, dec, ntaps, total_test_size, block_size): block_size = 32768 tb = gr.top_block() taps = make_random_complex_tuple(ntaps) src = blocks.vector_source_c(make_random_complex_tuple(block_size), True) head = blocks.head(gr.sizeof_gr_complex, int(total_test_size)) op = creator(dec, taps) dst = blocks.null_sink(gr.sizeof_gr_complex) tb.connect(src, head, op, dst) start = time.time() tb.run() stop = time.time() delta = stop - start print "%16s: taps: %4d input: %4g, time: %6.3f taps/sec: %10.4g" % ( name, ntaps, total_test_size, delta, ntaps*total_test_size/delta) def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-n", "--ntaps", type="int", default=256) parser.add_option("-t", "--total-input-size", type="eng_float", default=40e6) parser.add_option("-b", "--block-size", type="intx", default=50000) parser.add_option("-d", "--decimation", type="int", default=1) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) ntaps = options.ntaps total_input_size = options.total_input_size block_size = options.block_size dec = options.decimation benchmark("filter.fir_filter_ccc", filter.fir_filter_ccc, dec, ntaps, total_input_size, block_size) benchmark("filter.fft_filter_ccc", filter.fft_filter_ccc, dec, ntaps, total_input_size, block_size) if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-filter/examples/reconstruction.py0000775000175000017500000001162512242521224022474 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, digital from gnuradio import filter from gnuradio import blocks import sys try: from gnuradio import channels except ImportError: print "Error: Program requires gr-channels." sys.exit(1) try: import scipy from scipy import fftpack except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) try: import pylab except ImportError: print "Error: Program requires matplotlib (see: matplotlib.sourceforge.net)." sys.exit(1) fftlen = 8192 def main(): N = 10000 fs = 2000.0 Ts = 1.0/fs t = scipy.arange(0, N*Ts, Ts) # When playing with the number of channels, be careful about the filter # specs and the channel map of the synthesizer set below. nchans = 10 # Build the filter(s) bw = 1000 tb = 400 proto_taps = filter.firdes.low_pass_2(1, nchans*fs, bw, tb, 80, filter.firdes.WIN_BLACKMAN_hARRIS) print "Filter length: ", len(proto_taps) # Create a modulated signal npwr = 0.01 data = scipy.random.randint(0, 256, N) rrc_taps = filter.firdes.root_raised_cosine(1, 2, 1, 0.35, 41) src = blocks.vector_source_b(data.astype(scipy.uint8).tolist(), False) mod = digital.bpsk_mod(samples_per_symbol=2) chan = filter.channel_model(npwr) rrc = filter.fft_filter_ccc(1, rrc_taps) # Split it up into pieces channelizer = filter.pfb.channelizer_ccf(nchans, proto_taps, 2) # Put the pieces back together again syn_taps = [nchans*t for t in proto_taps] synthesizer = filter.pfb_synthesizer_ccf(nchans, syn_taps, True) src_snk = blocks.vector_sink_c() snk = blocks.vector_sink_c() # Remap the location of the channels # Can be done in synth or channelizer (watch out for rotattions in # the channelizer) synthesizer.set_channel_map([ 0, 1, 2, 3, 4, 15, 16, 17, 18, 19]) tb = gr.top_block() tb.connect(src, mod, chan, rrc, channelizer) tb.connect(rrc, src_snk) vsnk = [] for i in xrange(nchans): tb.connect((channelizer,i), (synthesizer, i)) vsnk.append(blocks.vector_sink_c()) tb.connect((channelizer,i), vsnk[i]) tb.connect(synthesizer, snk) tb.run() sin = scipy.array(src_snk.data()[1000:]) sout = scipy.array(snk.data()[1000:]) # Plot original signal fs_in = nchans*fs f1 = pylab.figure(1, figsize=(16,12), facecolor='w') s11 = f1.add_subplot(2,2,1) s11.psd(sin, NFFT=fftlen, Fs=fs_in) s11.set_title("PSD of Original Signal") s11.set_ylim([-200, -20]) s12 = f1.add_subplot(2,2,2) s12.plot(sin.real[1000:1500], "o-b") s12.plot(sin.imag[1000:1500], "o-r") s12.set_title("Original Signal in Time") start = 1 skip = 4 s13 = f1.add_subplot(2,2,3) s13.plot(sin.real[start::skip], sin.imag[start::skip], "o") s13.set_title("Constellation") s13.set_xlim([-2, 2]) s13.set_ylim([-2, 2]) # Plot channels nrows = int(scipy.sqrt(nchans)) ncols = int(scipy.ceil(float(nchans)/float(nrows))) f2 = pylab.figure(2, figsize=(16,12), facecolor='w') for n in xrange(nchans): s = f2.add_subplot(nrows, ncols, n+1) s.psd(vsnk[n].data(), NFFT=fftlen, Fs=fs_in) s.set_title("Channel {0}".format(n)) s.set_ylim([-200, -20]) # Plot reconstructed signal fs_out = 2*nchans*fs f3 = pylab.figure(3, figsize=(16,12), facecolor='w') s31 = f3.add_subplot(2,2,1) s31.psd(sout, NFFT=fftlen, Fs=fs_out) s31.set_title("PSD of Reconstructed Signal") s31.set_ylim([-200, -20]) s32 = f3.add_subplot(2,2,2) s32.plot(sout.real[1000:1500], "o-b") s32.plot(sout.imag[1000:1500], "o-r") s32.set_title("Reconstructed Signal in Time") start = 2 skip = 4 s33 = f3.add_subplot(2,2,3) s33.plot(sout.real[start::skip], sout.imag[start::skip], "o") s33.set_title("Constellation") s33.set_xlim([-2, 2]) s33.set_ylim([-2, 2]) pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-filter/examples/fir_filter_fff.py0000775000175000017500000000766212242521224022367 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import analog from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: import scipy except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) class example_fir_filter_fff(gr.top_block): def __init__(self, N, fs, bw, tw, atten, D): gr.top_block.__init__(self) self._nsamps = N self._fs = fs self._bw = bw self._tw = tw self._at = atten self._decim = D taps = filter.firdes.low_pass_2(1, self._fs, self._bw, self._tw, self._at) print "Num. Taps: ", len(taps) self.src = analog.noise_source_f(analog.GR_GAUSSIAN, 1) self.head = blocks.head(gr.sizeof_float, self._nsamps) self.filt0 = filter.fir_filter_fff(self._decim, taps) self.vsnk_src = blocks.vector_sink_f() self.vsnk_out = blocks.vector_sink_f() self.connect(self.src, self.head, self.vsnk_src) self.connect(self.head, self.filt0, self.vsnk_out) def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=10000, help="Number of samples to process [default=%default]") parser.add_option("-s", "--samplerate", type="eng_float", default=8000, help="System sample rate [default=%default]") parser.add_option("-B", "--bandwidth", type="eng_float", default=1000, help="Filter bandwidth [default=%default]") parser.add_option("-T", "--transition", type="eng_float", default=100, help="Transition band [default=%default]") parser.add_option("-A", "--attenuation", type="eng_float", default=80, help="Stopband attenuation [default=%default]") parser.add_option("-D", "--decimation", type="int", default=1, help="Decmation factor [default=%default]") (options, args) = parser.parse_args () put = example_fir_filter_fff(options.nsamples, options.samplerate, options.bandwidth, options.transition, options.attenuation, options.decimation) put.run() data_src = scipy.array(put.vsnk_src.data()) data_snk = scipy.array(put.vsnk_out.data()) # Plot the signals PSDs nfft = 1024 f1 = pylab.figure(1, figsize=(12,10)) s1 = f1.add_subplot(1,1,1) s1.psd(data_src, NFFT=nfft, noverlap=nfft/4, Fs=options.samplerate) s1.psd(data_snk, NFFT=nfft, noverlap=nfft/4, Fs=options.samplerate) f2 = pylab.figure(2, figsize=(12,10)) s2 = f2.add_subplot(1,1,1) s2.plot(data_src) s2.plot(data_snk.real, 'g') pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-fec/0000775000175000017500000000000012207440367014474 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/CMakeLists.txt0000664000175000017500000000663012207440367017241 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-fec" ENABLE_GR_FEC Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_BLOCKS ) GR_SET_GLOBAL(GR_FEC_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/lib/viterbi ${CMAKE_CURRENT_SOURCE_DIR}/lib/reed-solomon ${CMAKE_CURRENT_SOURCE_DIR}/include ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_FEC) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_FEC_DESCRIPTION "GNU Radio FEC Blocks") CPACK_COMPONENT("fec_runtime" GROUP "FEC" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("fec_devel" GROUP "FEC" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("fec_python" GROUP "FEC" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;fec_runtime" ) CPACK_COMPONENT("fec_swig" GROUP "FEC" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;fec_python;fec_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/fec) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/fec) add_subdirectory(grc) endif(ENABLE_PYTHON) #add_subdirectory(examples) add_subdirectory(doc) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-fec.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fec.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fec.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "fec_devel" ) endif(ENABLE_GR_FEC) gnuradio-3.7.2.1/gr-fec/include/0000775000175000017500000000000012207440367016117 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/include/gnuradio/0000775000175000017500000000000012207440367017727 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/0000775000175000017500000000000012207440367020464 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/CMakeLists.txt0000664000175000017500000000541112207440367023225 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict(name, sig, 'fec') build_utils.expand_template(d, inp) ") macro(expand_h root) #make a list of all the generated files unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the files add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #install rules for the generated h files list(APPEND generated_includes ${expanded_files_h}) endmacro(expand_h) ######################################################################## # Invoke macro to generate various sources ######################################################################## #expand_h(foo_XX ss ii cc) add_custom_target(fec_generated_includes DEPENDS ${generated_includes} ) ######################################################################## # Install header files ######################################################################## install(FILES ${generated_includes} api.h decode_ccsds_27_fb.h encode_ccsds_27_bb.h rs.h viterbi.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/fec COMPONENT "fec_devel" ) gnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/encode_ccsds_27_bb.h0000664000175000017500000000366012207440367024231 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FEC_ENCODE_CCSDS_27_BB_H #define INCLUDED_FEC_ENCODE_CCSDS_27_BB_H #include #include namespace gr { namespace fec { /*! \brief A rate 1/2, k=7 convolutional encoder for the CCSDS standard * \ingroup error_coding_blk * * \details * This block performs convolutional encoding using the CCSDS standard * polynomial ("Voyager"). * * The input is an MSB first packed stream of bits. * * The output is a stream of symbols 0 or 1 representing the encoded data. * * As a rate 1/2 code, there will be 16 output symbols for every input byte. * * This block is designed for continuous data streaming, not packetized data. * There is no provision to "flush" the encoder. */ class FEC_API encode_ccsds_27_bb : virtual public sync_interpolator { public: // gr::fec::encode_ccsds_27_bb::sptr typedef boost::shared_ptr sptr; static sptr make(); }; } /* namespace fec */ } /* namespace gr */ #endif /* INCLUDED_FEC_ENCODE_CCSDS_27_BB_H */ gnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/viterbi.h0000664000175000017500000000343112207440367022302 0ustar jcorganjcorgan/* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* The path memory for each state is 32 bits. This is slightly shorter * than we'd like for K=7, especially since we chain back every 8 bits. * But it fits so nicely into a 32-bit machine word... */ #include struct viterbi_state { unsigned long path; /* Decoded path to this state */ long metric; /* Cumulative metric to this state */ }; FEC_API int gen_met(int mettab[2][256], /* Metric table */ int amp, /* Signal amplitude */ double esn0, /* Es/N0 ratio in dB */ double bias, /* Metric bias */ int scale); /* Scale factor */ FEC_API unsigned char encode(unsigned char *symbols, unsigned char *data, unsigned int nbytes,unsigned char encstate); FEC_API void viterbi_chunks_init(struct viterbi_state* state); FEC_API void viterbi_butterfly2(unsigned char *symbols, int mettab[2][256], struct viterbi_state *state0, struct viterbi_state *state1); FEC_API unsigned char viterbi_get_output(struct viterbi_state *state, unsigned char *outbuf); gnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/decode_ccsds_27_fb.h0000664000175000017500000000417312207440367024223 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FEC_DECODE_CCSDS_27_FB_H #define INCLUDED_FEC_DECODE_CCSDS_27_FB_H #include #include namespace gr { namespace fec { /*! \brief A rate 1/2, k=7 convolutional decoder for the CCSDS standard * \ingroup error_coding_blk * * \details * This block performs soft-decision convolutional decoding using the Viterbi * algorithm. * * The input is a stream of (possibly noise corrupted) floating point values * nominally spanning [-1.0, 1.0], representing the encoded channel symbols * 0 (-1.0) and 1 (1.0), with erased symbols at 0.0. * * The output is MSB first packed bytes of decoded values. * * As a rate 1/2 code, there will be one output byte for every 16 input symbols. * * This block is designed for continuous data streaming, not packetized data. * The first 32 bits out will be zeroes, with the output delayed four bytes * from the corresponding inputs. */ class FEC_API decode_ccsds_27_fb : virtual public sync_decimator { public: // gr::fec::decode_ccsds_27_fb::sptr typedef boost::shared_ptr sptr; static sptr make(); }; } /* namespace fec */ } /* namespace gr */ #endif /* INCLUDED_FEC_DECODE_CCSDS_27_FB_H */ gnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/rs.h0000664000175000017500000000247612207440367021272 0ustar jcorganjcorgan#include /* User include file for the Reed-Solomon codec * Copyright 2002, Phil Karn KA9Q * May be used under the terms of the GNU General Public License (GPL) */ /* General purpose RS codec, 8-bit symbols */ FEC_API void encode_rs_char(void *rs,unsigned char *data,unsigned char *parity); FEC_API int decode_rs_char(void *rs,unsigned char *data,int *eras_pos, int no_eras); FEC_API void *init_rs_char(unsigned int symsize,unsigned int gfpoly, unsigned int fcr,unsigned int prim,unsigned int nroots); FEC_API void free_rs_char(void *rs); /* General purpose RS codec, integer symbols */ FEC_API void encode_rs_int(void *rs,int *data,int *parity); FEC_API int decode_rs_int(void *rs,int *data,int *eras_pos,int no_eras); FEC_API void *init_rs_int(unsigned int symsize,unsigned int gfpoly,unsigned int fcr, unsigned int prim,unsigned int nroots); FEC_API void free_rs_int(void *rs); /* CCSDS standard (255,223) RS codec with conventional (*not* dual-basis) * symbol representation */ FEC_API void encode_rs_8(unsigned char *data,unsigned char *parity); FEC_API int decode_rs_8(unsigned char *data,int *eras_pos,int no_eras); /* Tables to map from conventional->dual (Taltab) and * dual->conventional (Tal1tab) bases */ extern unsigned char Taltab[],Tal1tab[]; gnuradio-3.7.2.1/gr-fec/include/gnuradio/fec/api.h0000664000175000017500000000201512207440367021404 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FEC_API_H #define INCLUDED_FEC_API_H #include #ifdef gnuradio_fec_EXPORTS # define FEC_API __GR_ATTR_EXPORT #else # define FEC_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_FEC_API_H */ gnuradio-3.7.2.1/gr-fec/grc/0000775000175000017500000000000012207440367015247 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/grc/CMakeLists.txt0000664000175000017500000000170212207440367020007 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "fec_python") gnuradio-3.7.2.1/gr-fec/grc/fec_decode_ccsds_27_bb.xml0000664000175000017500000000066112207440367022166 0ustar jcorganjcorgan Encode CCSDS 27 fec_encode_ccsds_27_bb from gnuradio import fec fec.encode_ccsds_27_bb() in byte out byte gnuradio-3.7.2.1/gr-fec/grc/fec_decode_ccsds_27_fb.xml0000664000175000017500000000066212207440367022173 0ustar jcorganjcorgan Decode CCSDS 27 fec_decode_ccsds_27_fb from gnuradio import fec fec.decode_ccsds_27_fb() in float out byte gnuradio-3.7.2.1/gr-fec/grc/fec_block_tree.xml0000664000175000017500000000052412207440367020720 0ustar jcorganjcorgan Error Coding fec_decode_ccsds_27_fb fec_encode_ccsds_27_bb gnuradio-3.7.2.1/gr-fec/doc/0000775000175000017500000000000012207440367015241 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/doc/CMakeLists.txt0000664000175000017500000000152112207440367020000 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.fec DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-fec/doc/README.fec0000664000175000017500000000061012207440367016652 0ustar jcorganjcorganThis is the gr-fec package. It contains all of the FEC encoders and decoders. To use the FEC blocks, the Python namespace is in gnuradio.fec, which would be normally imported as: from gnuradio import fec See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(fec) gnuradio-3.7.2.1/gr-fec/doc/fec.dox0000664000175000017500000000102412207440367016507 0ustar jcorganjcorgan/*! \page page_fec Forward Error Correction \section Introduction This is the gr-fec package. It contains all of the forward error correction (FEC) blocks, utilities, and examples. To use the FEC blocks, the Python namespaces is in gnuradio.fec, which would be normally imported as: \code from gnuradio import fec \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(fec) \endcode */ gnuradio-3.7.2.1/gr-fec/python/0000775000175000017500000000000012207440367016015 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/python/fec/0000775000175000017500000000000012214652673016555 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/python/fec/CMakeLists.txt0000664000175000017500000000330312207440367021311 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/fec COMPONENT "fec_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) list(APPEND GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gr-fec/python ${CMAKE_BINARY_DIR}/gr-fec/swig ${CMAKE_BINARY_DIR}/gr-blocks/python ${CMAKE_BINARY_DIR}/gr-blocks/swig ) list(APPEND GR_TEST_TARGET_DEPS gnuradio-fec) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-fec/python/fec/qa_ecc_ccsds_27.py0000775000175000017500000000315712207440367022037 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest import fec_swig as fec import blocks_swig as blocks class test_ccsds_27 (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def xtest_ccsds_27 (self): src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) expected = (0, 0, 0, 0, 1, 2, 3, 4, 5, 6) src = blocks.vector_source_b(src_data) enc = fec.encode_ccsds_27_bb() b2f = blocks.char_to_float() add = blocks.add_const_ff(-0.5) mul = blocks.multiply_const_ff(2.0) dec = fec.decode_ccsds_27_fb() dst = blocks.vector_sink_b() self.tb.connect(src, enc, b2f, add, mul, dec, dst) self.tb.run() dst_data = dst.data() self.assertEqual(expected, dst_data) if __name__ == '__main__': gr_unittest.run(test_ccsds_27, "test_ccsds_27.xml") gnuradio-3.7.2.1/gr-fec/python/fec/__init__.py0000664000175000017500000000203212214652673020663 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks for forward error correction. ''' try: from fec_swig import * except ImportError: import os dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from fec_swig import * gnuradio-3.7.2.1/gr-fec/lib/0000775000175000017500000000000012220601656015235 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/lib/decode_ccsds_27_fb_impl.cc0000664000175000017500000000513212220601656022147 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "decode_ccsds_27_fb_impl.h" #include namespace gr { namespace fec { decode_ccsds_27_fb::sptr decode_ccsds_27_fb::make() { return gnuradio::get_initial_sptr(new decode_ccsds_27_fb_impl()); } decode_ccsds_27_fb_impl::decode_ccsds_27_fb_impl() : sync_decimator("decode_ccsds_27_fb", io_signature::make (1, 1, sizeof(float)), io_signature::make (1, 1, sizeof(char)), 2*8), d_count(0) // Rate 1/2 code, unpacked to packed conversion { float RATE = 0.5; float ebn0 = 12.0; float esn0 = RATE*pow(10.0, ebn0/10.0); gen_met(d_mettab, 100, esn0, 0.0, 256); viterbi_chunks_init(d_state0); viterbi_chunks_init(d_state1); } int decode_ccsds_27_fb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; for (int i = 0; i < noutput_items*16; i++) { // Translate and clip [-1.0..1.0] to [28..228] float sample = in[i]*100.0+128.0; if (sample > 255.0) sample = 255.0; else if (sample < 0.0) sample = 0.0; unsigned char sym = (unsigned char)(floor(sample)); d_viterbi_in[d_count % 4] = sym; if ((d_count % 4) == 3) { // Every fourth symbol, perform butterfly operation viterbi_butterfly2(d_viterbi_in, d_mettab, d_state0, d_state1); // Every sixteenth symbol, read out a byte if (d_count % 16 == 11) { // long metric = viterbi_get_output(d_state0, out++); // printf("%li\n", *(out-1), metric); } } d_count++; } return noutput_items; } } /* namespace fec */ }/* namespace gr */ gnuradio-3.7.2.1/gr-fec/lib/CMakeLists.txt0000664000175000017500000000452412207440367020007 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # These are convenience libraries of 3rd party code. # Change to test for distro provided packages GR_INCLUDE_SUBDIRECTORY(reed-solomon) GR_INCLUDE_SUBDIRECTORY(viterbi) ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${GR_FEC_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) link_directories(${Boost_LIBRARY_DIRS}) ######################################################################## # Setup library ######################################################################## list(APPEND gnuradio_fec_sources decode_ccsds_27_fb_impl.cc encode_ccsds_27_bb_impl.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-fec.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fec.rc @ONLY) list(APPEND gnuradio_fec_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fec.rc ) endif(MSVC) list(APPEND gnuradio_fec_libs gnuradio-runtime ${Boost_LIBRARIES} ) add_library(gnuradio-fec SHARED ${gnuradio_fec_sources}) target_link_libraries(gnuradio-fec ${gnuradio_fec_libs}) GR_LIBRARY_FOO(gnuradio-fec RUNTIME_COMPONENT "fec_runtime" DEVEL_COMPONENT "fec_devel") gnuradio-3.7.2.1/gr-fec/lib/encode_ccsds_27_bb_impl.h0000664000175000017500000000256512207440367022033 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FEC_ENCODE_CCSDS_27_BB_IMPL_H #define INCLUDED_FEC_ENCODE_CCSDS_27_BB_IMPL_H #include namespace gr { namespace fec { class FEC_API encode_ccsds_27_bb_impl : public encode_ccsds_27_bb { private: unsigned char d_encstate; public: encode_ccsds_27_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace fec */ } /* namespace gr */ #endif /* INCLUDED_FEC_ENCODE_CCSDS_27_BB_IMPL_H */ gnuradio-3.7.2.1/gr-fec/lib/gnuradio-fec.rc.in0000664000175000017500000000331212207440367020537 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-fec" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-fec.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-fec.dll" VALUE "ProductName", "gnuradio-fec" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-fec/lib/viterbi/0000775000175000017500000000000012207440367016706 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/lib/viterbi/CMakeLists.txt0000664000175000017500000000515112207440367021450 0ustar jcorganjcorgan# Copyright 2010-2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # This file included, use CMake directory variables ######################################################################## set(viterbi_sources ${CMAKE_CURRENT_SOURCE_DIR}/metrics.c ${CMAKE_CURRENT_SOURCE_DIR}/tab.c ${CMAKE_CURRENT_SOURCE_DIR}/viterbi.c ) ######################################################################## # define missing erf function with C linkage (hack for metrics.c) ######################################################################## if(MSVC) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/boost_math_erf.cc " #include extern \"C\" double erf(double x){ return boost::math::erf(x); } ") list(APPEND viterbi_sources ${CMAKE_CURRENT_BINARY_DIR}/boost_math_erf.cc) endif(MSVC) ######################################################################## # Append gnuradio-runtime library sources ######################################################################## list(APPEND gnuradio_fec_sources ${viterbi_sources}) ######################################################################## # Install runtime headers ######################################################################## #install( # FILES ${CMAKE_CURRENT_SOURCE_DIR}/viterbi.h # DESTINATION ${GR_INCLUDE_DIR}/gnuradio/fec # COMPONENT "fec_devel" #) ######################################################################## # Create some text executables (not registered tests) # Its not much to build so the sources are just re-listed, # rather than create a new library just for these two apps. ######################################################################## #ADD_EXECUTABLE(viterbi_encode ${CMAKE_CURRENT_SOURCE_DIR}/encode.cc ${viterbi_sources}) #ADD_EXECUTABLE(viterbi_decode ${CMAKE_CURRENT_SOURCE_DIR}/decode.cc ${viterbi_sources}) gnuradio-3.7.2.1/gr-fec/lib/viterbi/tab.c0000664000175000017500000000327312207440367017625 0ustar jcorganjcorgan/* * Copyright 1995 Phil Karn, KA9Q * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* 8-bit parity lookup table, generated by partab.c */ unsigned char Partab[] = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, }; gnuradio-3.7.2.1/gr-fec/lib/viterbi/decode.cc0000664000175000017500000000445412207440367020447 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This is a minimal example demonstrating how to call the Viterbi decoder * in continuous streaming mode. It accepts data on stdin and writes to * stdout. * */ extern "C" { #include } #include #include #define MAXCHUNKSIZE 4096 #define MAXENCSIZE MAXCHUNKSIZE*16 int main() { unsigned char data[MAXCHUNKSIZE]; signed char syms[MAXENCSIZE]; int count = 0; // Initialize metric table int mettab[2][256]; int amp = 100; float RATE=0.5; float ebn0 = 12.0; float esn0 = RATE*pow(10.0, ebn0/10); gen_met(mettab, amp, esn0, 0.0, 4); // Initialize decoder state struct viterbi_state state0[64]; struct viterbi_state state1[64]; unsigned char viterbi_in[16]; viterbi_chunks_init(state0); while (!feof(stdin)) { unsigned int n = fread(syms, 1, MAXENCSIZE, stdin); unsigned char *out = data; for (unsigned int i = 0; i < n; i++) { // FIXME: This implements hard decoding by slicing the input stream unsigned char sym = syms[i] > 0 ? -amp : amp; // Write the symbol to the decoder input viterbi_in[count % 4] = sym; // Every four symbols, perform the butterfly2 operation if ((count % 4) == 3) { viterbi_butterfly2(viterbi_in, mettab, state0, state1); // Every sixteen symbols, perform the readback operation if ((count > 64) && (count % 16) == 11) { viterbi_get_output(state0, out); fwrite(out++, 1, 1, stdout); } } count++; } } return 0; } gnuradio-3.7.2.1/gr-fec/lib/viterbi/viterbi.c0000664000175000017500000002600012207440367020514 0ustar jcorganjcorgan/* * Copyright 1995 Phil Karn, KA9Q * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * Viterbi decoder for K=7 rate=1/2 convolutional code * Some modifications from original Karn code by Matt Ettus */ #include /* The two generator polynomials for the NASA Standard K=7 code. * Since these polynomials are known to be optimal for this constraint * length there is not much point in changing them. But if you do, you * will have to regenerate the BUTTERFLY macro calls in viterbi() */ #define POLYA 0x6d #define POLYB 0x4f /* The basic Viterbi decoder operation, called a "butterfly" * operation because of the way it looks on a trellis diagram. Each * butterfly involves an Add-Compare-Select (ACS) operation on the two nodes * where the 0 and 1 paths from the current node merge at the next step of * the trellis. * * The code polynomials are assumed to have 1's on both ends. Given a * function encode_state() that returns the two symbols for a given * encoder state in the low two bits, such a code will have the following * identities for even 'n' < 64: * * encode_state(n) = encode_state(n+65) * encode_state(n+1) = encode_state(n+64) = (3 ^ encode_state(n)) * * Any convolutional code you would actually want to use will have * these properties, so these assumptions aren't too limiting. * * Doing this as a macro lets the compiler evaluate at compile time the * many expressions that depend on the loop index and encoder state and * emit them as immediate arguments. * This makes an enormous difference on register-starved machines such * as the Intel x86 family where evaluating these expressions at runtime * would spill over into memory. */ #define BUTTERFLY(i,sym) { \ int m0,m1;\ \ /* ACS for 0 branch */\ m0 = state[i].metric + mets[sym]; /* 2*i */\ m1 = state[i+32].metric + mets[3^sym]; /* 2*i + 64 */\ if(m0 > m1){\ next[2*i].metric = m0;\ next[2*i].path = state[i].path << 1;\ } else {\ next[2*i].metric = m1;\ next[2*i].path = (state[i+32].path << 1)|1;\ }\ /* ACS for 1 branch */\ m0 = state[i].metric + mets[3^sym]; /* 2*i + 1 */\ m1 = state[i+32].metric + mets[sym]; /* 2*i + 65 */\ if(m0 > m1){\ next[2*i+1].metric = m0;\ next[2*i+1].path = state[i].path << 1;\ } else {\ next[2*i+1].metric = m1;\ next[2*i+1].path = (state[i+32].path << 1)|1;\ }\ } extern unsigned char Partab[]; /* Parity lookup table */ /* Convolutionally encode data into binary symbols */ unsigned char encode(unsigned char *symbols, unsigned char *data, unsigned int nbytes, unsigned char encstate) { int i; while(nbytes-- != 0){ for(i=7;i>=0;i--){ encstate = (encstate << 1) | ((*data >> i) & 1); *symbols++ = Partab[encstate & POLYA]; *symbols++ = Partab[encstate & POLYB]; } data++; } return encstate; } /* Viterbi decoder */ int viterbi(unsigned long *metric, /* Final path metric (returned value) */ unsigned char *data, /* Decoded output data */ unsigned char *symbols, /* Raw deinterleaved input symbols */ unsigned int nbits, /* Number of output bits */ int mettab[2][256] /* Metric table, [sent sym][rx symbol] */ ){ unsigned int bitcnt = 0; int mets[4]; long bestmetric; int beststate,i; struct viterbi_state state0[64],state1[64],*state,*next; state = state0; next = state1; /* Initialize starting metrics to prefer 0 state */ state[0].metric = 0; for(i=1;i<64;i++) state[i].metric = -999999; state[0].path = 0; for(bitcnt = 0;bitcnt < nbits;bitcnt++){ /* Read input symbol pair and compute all possible branch * metrics */ mets[0] = mettab[0][symbols[0]] + mettab[0][symbols[1]]; mets[1] = mettab[0][symbols[0]] + mettab[1][symbols[1]]; mets[2] = mettab[1][symbols[0]] + mettab[0][symbols[1]]; mets[3] = mettab[1][symbols[0]] + mettab[1][symbols[1]]; symbols += 2; /* These macro calls were generated by genbut.c */ BUTTERFLY(0,0); BUTTERFLY(1,1); BUTTERFLY(2,3); BUTTERFLY(3,2); BUTTERFLY(4,3); BUTTERFLY(5,2); BUTTERFLY(6,0); BUTTERFLY(7,1); BUTTERFLY(8,0); BUTTERFLY(9,1); BUTTERFLY(10,3); BUTTERFLY(11,2); BUTTERFLY(12,3); BUTTERFLY(13,2); BUTTERFLY(14,0); BUTTERFLY(15,1); BUTTERFLY(16,2); BUTTERFLY(17,3); BUTTERFLY(18,1); BUTTERFLY(19,0); BUTTERFLY(20,1); BUTTERFLY(21,0); BUTTERFLY(22,2); BUTTERFLY(23,3); BUTTERFLY(24,2); BUTTERFLY(25,3); BUTTERFLY(26,1); BUTTERFLY(27,0); BUTTERFLY(28,1); BUTTERFLY(29,0); BUTTERFLY(30,2); BUTTERFLY(31,3); /* Swap current and next states */ if(bitcnt & 1){ state = state0; next = state1; } else { state = state1; next = state0; } // ETTUS //if(bitcnt > nbits-7){ /* In tail, poison non-zero nodes */ //for(i=1;i<64;i += 2) // state[i].metric = -9999999; //} /* Produce output every 8 bits once path memory is full */ if((bitcnt % 8) == 5 && bitcnt > 32){ /* Find current best path */ bestmetric = state[0].metric; beststate = 0; for(i=1;i<64;i++){ if(state[i].metric > bestmetric){ bestmetric = state[i].metric; beststate = i; } } #ifdef notdef printf("metrics[%d] = %d state = %lx\n",beststate, state[beststate].metric,state[beststate].path); #endif *data++ = state[beststate].path >> 24; } } /* Output remaining bits from 0 state */ // ETTUS Find best state instead bestmetric = state[0].metric; beststate = 0; for(i=1;i<64;i++){ if(state[i].metric > bestmetric){ bestmetric = state[i].metric; beststate = i; } } if((i = bitcnt % 8) != 6) state[beststate].path <<= 6-i; *data++ = state[beststate].path >> 24; *data++ = state[beststate].path >> 16; *data++ = state[beststate].path >> 8; *data = state[beststate].path; //printf ("BS = %d\tBSM = %d\tM0 = %d\n",beststate,state[beststate].metric,state[0].metric); *metric = state[beststate].metric; return 0; } void viterbi_chunks_init(struct viterbi_state* state) { // Initialize starting metrics to prefer 0 state int i; state[0].metric = 0; state[0].path = 0; for(i=1;i<64;i++) state[i].metric = -999999; } void viterbi_butterfly8(unsigned char *symbols, int mettab[2][256], struct viterbi_state *state0, struct viterbi_state *state1) { unsigned int bitcnt; int mets[4]; struct viterbi_state *state, *next; state = state0; next = state1; // Operate on 16 symbols (8 bits) at a time for(bitcnt = 0;bitcnt < 8;bitcnt++){ // Read input symbol pair and compute all possible branch metrics mets[0] = mettab[0][symbols[0]] + mettab[0][symbols[1]]; mets[1] = mettab[0][symbols[0]] + mettab[1][symbols[1]]; mets[2] = mettab[1][symbols[0]] + mettab[0][symbols[1]]; mets[3] = mettab[1][symbols[0]] + mettab[1][symbols[1]]; symbols += 2; // These macro calls were generated by genbut.c BUTTERFLY(0,0);BUTTERFLY(1,1);BUTTERFLY(2,3);BUTTERFLY(3,2); BUTTERFLY(4,3);BUTTERFLY(5,2);BUTTERFLY(6,0);BUTTERFLY(7,1); BUTTERFLY(8,0);BUTTERFLY(9,1);BUTTERFLY(10,3);BUTTERFLY(11,2); BUTTERFLY(12,3);BUTTERFLY(13,2);BUTTERFLY(14,0);BUTTERFLY(15,1); BUTTERFLY(16,2);BUTTERFLY(17,3);BUTTERFLY(18,1);BUTTERFLY(19,0); BUTTERFLY(20,1);BUTTERFLY(21,0);BUTTERFLY(22,2);BUTTERFLY(23,3); BUTTERFLY(24,2);BUTTERFLY(25,3);BUTTERFLY(26,1);BUTTERFLY(27,0); BUTTERFLY(28,1);BUTTERFLY(29,0);BUTTERFLY(30,2);BUTTERFLY(31,3); // Swap current and next states if(bitcnt & 1){ state = state0; next = state1; } else { state = state1; next = state0; } } } void viterbi_butterfly2(unsigned char *symbols, int mettab[2][256], struct viterbi_state *state0, struct viterbi_state *state1) { //unsigned int bitcnt; int mets[4]; struct viterbi_state *state, *next; state = state0; next = state1; // Operate on 4 symbols (2 bits) at a time // Read input symbol pair and compute all possible branch metrics mets[0] = mettab[0][symbols[0]] + mettab[0][symbols[1]]; mets[1] = mettab[0][symbols[0]] + mettab[1][symbols[1]]; mets[2] = mettab[1][symbols[0]] + mettab[0][symbols[1]]; mets[3] = mettab[1][symbols[0]] + mettab[1][symbols[1]]; // These macro calls were generated by genbut.c BUTTERFLY(0,0);BUTTERFLY(1,1);BUTTERFLY(2,3);BUTTERFLY(3,2); BUTTERFLY(4,3);BUTTERFLY(5,2);BUTTERFLY(6,0);BUTTERFLY(7,1); BUTTERFLY(8,0);BUTTERFLY(9,1);BUTTERFLY(10,3);BUTTERFLY(11,2); BUTTERFLY(12,3);BUTTERFLY(13,2);BUTTERFLY(14,0);BUTTERFLY(15,1); BUTTERFLY(16,2);BUTTERFLY(17,3);BUTTERFLY(18,1);BUTTERFLY(19,0); BUTTERFLY(20,1);BUTTERFLY(21,0);BUTTERFLY(22,2);BUTTERFLY(23,3); BUTTERFLY(24,2);BUTTERFLY(25,3);BUTTERFLY(26,1);BUTTERFLY(27,0); BUTTERFLY(28,1);BUTTERFLY(29,0);BUTTERFLY(30,2);BUTTERFLY(31,3); state = state1; next = state0; // Read input symbol pair and compute all possible branch metrics mets[0] = mettab[0][symbols[2]] + mettab[0][symbols[3]]; mets[1] = mettab[0][symbols[2]] + mettab[1][symbols[3]]; mets[2] = mettab[1][symbols[2]] + mettab[0][symbols[3]]; mets[3] = mettab[1][symbols[2]] + mettab[1][symbols[3]]; // These macro calls were generated by genbut.c BUTTERFLY(0,0);BUTTERFLY(1,1);BUTTERFLY(2,3);BUTTERFLY(3,2); BUTTERFLY(4,3);BUTTERFLY(5,2);BUTTERFLY(6,0);BUTTERFLY(7,1); BUTTERFLY(8,0);BUTTERFLY(9,1);BUTTERFLY(10,3);BUTTERFLY(11,2); BUTTERFLY(12,3);BUTTERFLY(13,2);BUTTERFLY(14,0);BUTTERFLY(15,1); BUTTERFLY(16,2);BUTTERFLY(17,3);BUTTERFLY(18,1);BUTTERFLY(19,0); BUTTERFLY(20,1);BUTTERFLY(21,0);BUTTERFLY(22,2);BUTTERFLY(23,3); BUTTERFLY(24,2);BUTTERFLY(25,3);BUTTERFLY(26,1);BUTTERFLY(27,0); BUTTERFLY(28,1);BUTTERFLY(29,0);BUTTERFLY(30,2);BUTTERFLY(31,3); } unsigned char viterbi_get_output(struct viterbi_state *state, unsigned char *outbuf) { // Produce output every 8 bits once path memory is full // if((bitcnt % 8) == 5 && bitcnt > 32) { // Find current best path unsigned int i,beststate; int bestmetric; bestmetric = state[0].metric; beststate = 0; for(i=1;i<64;i++) if(state[i].metric > bestmetric) { bestmetric = state[i].metric; beststate = i; } *outbuf = state[beststate].path >> 24; return bestmetric; } //printf ("BS = %d\tBSM = %d\tM0 = %d\n",beststate,state[beststate].metric,state[0].metric); // In tail, poison non-zero nodes //if(bits_out > packet_size-7) // for(i=1;i<64;i += 2) // state[i].metric = -9999999; gnuradio-3.7.2.1/gr-fec/lib/viterbi/metrics.c0000664000175000017500000000764412207440367020533 0ustar jcorganjcorgan/* * Copyright 1995 Phil Karn, KA9Q * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * Generate metric tables for a soft-decision convolutional decoder * assuming gaussian noise on a PSK channel. * * Works from "first principles" by evaluating the normal probability * function and then computing the log-likelihood function * for every possible received symbol value * */ #ifdef HAVE_CONFIG_H #include #endif /* Symbols are offset-binary, with 128 corresponding to an erased (no * information) symbol */ #define OFFSET 128 #include #include //declare erf in case it was missing in math.h and provided for by the build system extern double erf(double x); /* Normal function integrated from -Inf to x. Range: 0-1 */ #define normal(x) (0.5 + 0.5*erf((x)/M_SQRT2)) /* Logarithm base 2 */ #define gr_log2(x) (log(x)*M_LOG2E) /* Generate log-likelihood metrics for 8-bit soft quantized channel * assuming AWGN and BPSK */ void gen_met(int mettab[2][256], /* Metric table, [sent sym][rx symbol] */ int amp, /* Signal amplitude, units */ double esn0, /* Es/N0 ratio in dB */ double bias, /* Metric bias; 0 for viterbi, rate for sequential */ int scale) /* Scale factor */ { double noise; int s,bit; double metrics[2][256]; double p0,p1; /* Es/N0 as power ratio */ esn0 = pow(10.,esn0/10); noise = 0.5/esn0; /* only half the noise for BPSK */ noise = sqrt(noise); /* noise/signal Voltage ratio */ /* Zero is a special value, since this sample includes all * lower samples that were clipped to this value, i.e., it * takes the whole lower tail of the curve */ p1 = normal(((0-OFFSET+0.5)/amp - 1)/noise); /* P(s|1) */ /* Prob of this value occurring for a 0-bit */ /* P(s|0) */ p0 = normal(((0-OFFSET+0.5)/amp + 1)/noise); metrics[0][0] = gr_log2(2*p0/(p1+p0)) - bias; metrics[1][0] = gr_log2(2*p1/(p1+p0)) - bias; for(s=1;s<255;s++){ /* P(s|1), prob of receiving s given 1 transmitted */ p1 = normal(((s-OFFSET+0.5)/amp - 1)/noise) - normal(((s-OFFSET-0.5)/amp - 1)/noise); /* P(s|0), prob of receiving s given 0 transmitted */ p0 = normal(((s-OFFSET+0.5)/amp + 1)/noise) - normal(((s-OFFSET-0.5)/amp + 1)/noise); #ifdef notdef printf("P(%d|1) = %lg, P(%d|0) = %lg\n",s,p1,s,p0); #endif metrics[0][s] = gr_log2(2*p0/(p1+p0)) - bias; metrics[1][s] = gr_log2(2*p1/(p1+p0)) - bias; } /* 255 is also a special value */ /* P(s|1) */ p1 = 1 - normal(((255-OFFSET-0.5)/amp - 1)/noise); /* P(s|0) */ p0 = 1 - normal(((255-OFFSET-0.5)/amp + 1)/noise); metrics[0][255] = gr_log2(2*p0/(p1+p0)) - bias; metrics[1][255] = gr_log2(2*p1/(p1+p0)) - bias; #ifdef notdef /* The probability of a raw symbol error is the probability * that a 1-bit would be received as a sample with value * 0-128. This is the offset normal curve integrated from -Inf to 0. */ printf("symbol Pe = %lg\n",normal(-1/noise)); #endif for(bit=0;bit<2;bit++){ for(s=0;s<256;s++){ /* Scale and round to nearest integer */ mettab[bit][s] = floor(metrics[bit][s] * scale + 0.5); #ifdef notdef printf("metrics[%d][%d] = %lg, mettab = %d\n", bit,s,metrics[bit][s],mettab[bit][s]); #endif } } } gnuradio-3.7.2.1/gr-fec/lib/viterbi/encode.cc0000664000175000017500000000273512207440367020461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This is a minimal example demonstrating how to call the ECC encoder * in continuous streaming mode. It accepts data on stdin and writes to * stdout. * * FIXME: This does not flush the final bits out of the encoder. * */ extern "C" { #include } #include #define MAXCHUNKSIZE 4096 #define MAXENCSIZE MAXCHUNKSIZE*16 int main() { unsigned char encoder_state = 0; unsigned char data[MAXCHUNKSIZE]; unsigned char syms[MAXENCSIZE]; while (!feof(stdin)) { unsigned int n = fread(data, 1, MAXCHUNKSIZE, stdin); encoder_state = encode(syms, data, n, encoder_state); fwrite(syms, 1, n*16, stdout); } return 0; } gnuradio-3.7.2.1/gr-fec/lib/encode_ccsds_27_bb_impl.cc0000664000175000017500000000353712207440367022171 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "encode_ccsds_27_bb_impl.h" #include extern "C" { #include } namespace gr { namespace fec { encode_ccsds_27_bb::sptr encode_ccsds_27_bb::make() { return gnuradio::get_initial_sptr(new encode_ccsds_27_bb_impl()); } encode_ccsds_27_bb_impl::encode_ccsds_27_bb_impl() : sync_interpolator("encode_ccsds_27_bb", io_signature::make (1, 1, sizeof(char)), io_signature::make (1, 1, sizeof(char)), 16) // Rate 1/2 code, packed to unpacked conversion { d_encstate = 0; } int encode_ccsds_27_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned char *in = (unsigned char *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; d_encstate = encode(out, in, noutput_items/16, d_encstate); return noutput_items; } } /* namespace fec */ }/* namespace gr */ gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/0000775000175000017500000000000012207440367017645 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/lib/reed-solomon/encode_rs_ccsds.c0000664000175000017500000000123612207440367023133 0ustar jcorganjcorgan/* This function wraps around the fixed 8-bit encoder, performing the * basis transformations necessary to meet the CCSDS standard * * Copyright 2002, Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #define FIXED #include "fixed.h" #include "ccsds.h" void encode_rs_ccsds(unsigned char *data,unsigned char *parity){ int i; unsigned char cdata[NN-NROOTS]; /* Convert data from dual basis to conventional */ for(i=0;i /* Reed-Solomon codec control block */ struct FEC_API rs { unsigned int mm; /* Bits per symbol */ unsigned int nn; /* Symbols per block (= (1<= rs->nn) { x -= rs->nn; x = (x >> rs->mm) + (x & rs->nn); } return x; } #define MODNN(x) modnn(rs,x) #define MM (rs->mm) #define NN (rs->nn) #define ALPHA_TO (rs->alpha_to) #define INDEX_OF (rs->index_of) #define GENPOLY (rs->genpoly) #define NROOTS (rs->nroots) #define FCR (rs->fcr) #define PRIM (rs->prim) #define IPRIM (rs->iprim) #define A0 (NN) #define ENCODE_RS encode_rs_int #define DECODE_RS decode_rs_int #define INIT_RS init_rs_int #define FREE_RS free_rs_int FEC_API void ENCODE_RS(void *p,DTYPE *data,DTYPE *parity); FEC_API int DECODE_RS(void *p,DTYPE *data,int *eras_pos,int no_eras); void *INIT_RS(unsigned int symsize,unsigned int gfpoly,unsigned int fcr, unsigned int prim,unsigned int nroots); FEC_API void FREE_RS(void *p); gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/gen_ccsds.c0000664000175000017500000000142012207440367021736 0ustar jcorganjcorgan/* Generate tables for CCSDS code * Copyright 2002 Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #include #include "char.h" int main(){ struct rs *rs; int i; rs = init_rs_char(8,0x187,112,11,32); /* CCSDS standard */ printf("unsigned char CCSDS_alpha_to[] = {"); for(i=0;i<256;i++){ if((i % 16) == 0) printf("\n"); printf("0x%02x,",rs->alpha_to[i]); } printf("\n};\n\nunsigned char CCSDS_index_of[] = {"); for(i=0;i<256;i++){ if((i % 16) == 0) printf("\n"); printf("%3d,",rs->index_of[i]); } printf("\n};\n\nunsigned char CCSDS_poly[] = {"); for(i=0;i<33;i++){ if((i % 16) == 0) printf("\n"); printf("%3d,",rs->genpoly[i]); } printf("\n};\n"); exit(0); } gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/CMakeLists.txt0000664000175000017500000000451112207440367022406 0ustar jcorganjcorgan# Copyright 2010-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # This file included, use CMake directory variables ######################################################################## #MSVC workaround: we cant have dynamically sized arrays. #So ifdef a max array bounds that is larger than NN and NROOTS #Its a bit of a hack, but if you look at the code, its so full of ifdefs, #and lacks optimization where it should be pre-allocating these arrays. if(MSVC) set_source_files_properties( ${CMAKE_CURRENT_SOURCE_DIR}/exercise.c ${CMAKE_CURRENT_SOURCE_DIR}/decode_rs.c PROPERTIES COMPILE_DEFINITIONS "MAX_ARRAY=256;" ) endif(MSVC) set(gr_fec_rs_sources ${CMAKE_CURRENT_SOURCE_DIR}/encode_rs.c ${CMAKE_CURRENT_SOURCE_DIR}/decode_rs.c ${CMAKE_CURRENT_SOURCE_DIR}/init_rs.c ) ######################################################################## # Setup sources and includes ######################################################################## list(APPEND gnuradio_fec_sources ${gr_fec_rs_sources}) #install( # FILES ${CMAKE_CURRENT_SOURCE_DIR}/rs.h # DESTINATION ${GR_INCLUDE_DIR}/gnuradio/fec # COMPONENT "fec_devel" #) ######################################################################## # Register unit tests ######################################################################## if(ENABLE_TESTING) add_executable(gr_fec_rstest ${gr_fec_rs_sources} ${CMAKE_CURRENT_SOURCE_DIR}/rstest.c ${CMAKE_CURRENT_SOURCE_DIR}/exercise.c ) add_test(gr-fec-reed-solomon-test gr_fec_rstest) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/README.karn0000664000175000017500000000116712207440367021464 0ustar jcorganjcorganThis package implements a general purpose Reed-Solomon encoding and decoding facility. See the rs.3 man page for details. To install, simply do the following after extracting this tarball into an empty directory: ./configure make make install The command "make test" runs a battery of encode/decode tests using a variety of RS codes using random data and random errors. Each test should pass with an "OK"; if any fail, please let me know so I can track down the problem. Phil Karn (karn@ka9q.net) 1 Jan 2002 Copyright 2002, Phil Karn, KA9Q This software may be used under the terms of the GNU General Public License (GPL). gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/encode_rs.c0000664000175000017500000000212612207440367021753 0ustar jcorganjcorgan/* Reed-Solomon encoder * Copyright 2002, Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #include #ifdef FIXED #include "fixed.h" #elif defined(BIGSYM) #include "int.h" #else #include "char.h" #endif void ENCODE_RS( #ifndef FIXED void *p, #endif DTYPE *data, DTYPE *bb){ #ifndef FIXED struct rs *rs = (struct rs *)p; #endif unsigned int i, j; DTYPE feedback; memset(bb,0,NROOTS*sizeof(DTYPE)); for(i=0;i static inline int mod255(int x){ while (x >= 255) { x -= 255; x = (x >> 8) + (x & 255); } return x; } #define MODNN(x) mod255(x) extern unsigned char CCSDS_alpha_to[]; extern unsigned char CCSDS_index_of[]; extern unsigned char CCSDS_poly[]; #define MM 8 #define NN 255 #define ALPHA_TO CCSDS_alpha_to #define INDEX_OF CCSDS_index_of #define GENPOLY CCSDS_poly #define NROOTS 32 #define FCR 112 #define PRIM 11 #define IPRIM 116 #define A0 (NN) #define ENCODE_RS encode_rs_8 #define DECODE_RS decode_rs_8 FEC_API void ENCODE_RS(DTYPE *data,DTYPE *parity); FEC_API int DECODE_RS(DTYPE *data, int *eras_pos, int no_eras);gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/rstest.c0000664000175000017500000000500112207440367021331 0ustar jcorganjcorgan/* Test the Reed-Solomon codecs * for various block sizes and with random data and random error patterns * * Copyright 2002 Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include int exercise_char(void *,int); #ifdef ALL_VERSIONS int exercise_int(void *,int); int exercise_8(int); int exercise_ccsds(int); #endif struct { int symsize; int genpoly; int fcs; int prim; int nroots; int ntrials; } Tab[] = { {2, 0x7, 1, 1, 1, 10 }, {3, 0xb, 1, 1, 2, 10 }, {4, 0x13, 1, 1, 4, 10 }, {5, 0x25, 1, 1, 6, 10 }, {6, 0x43, 1, 1, 8, 10 }, {7, 0x89, 1, 1, 10, 10 }, {8, 0x11d, 1, 1, 32, 10 }, {8, 0x187, 112,11, 32, 10 }, /* Duplicates CCSDS codec */ #ifdef ALL_VESIONS {9, 0x211, 1, 1, 32, 10 }, {10,0x409, 1, 1, 32, 10 }, {11,0x805, 1, 1, 32, 10 }, {12,0x1053, 1, 1, 32, 5 }, {13,0x201b, 1, 1, 32, 2 }, {14,0x4443, 1, 1, 32, 1 }, {15,0x8003, 1, 1, 32, 1 }, {16,0x1100b, 1, 1, 32, 1 }, #endif {0, 0, 0, 0, 0}, }; int main(){ void *handle; int errs,terrs; int i; terrs = 0; srandom(time(NULL)); #ifdef ALL_VERSIONS printf("Testing fixed (255,223) RS codec..."); fflush(stdout); errs = exercise_8(10); terrs += errs; if(errs == 0){ printf("OK\n"); } printf("Testing CCSDS standard (255,223) RS codec..."); fflush(stdout); errs = exercise_ccsds(10); terrs += errs; if(errs == 0){ printf("OK\n"); } #endif for(i=0;Tab[i].symsize != 0;i++){ int nn,kk; nn = (1< 0){ /* Convert from conventional to dual basis */ for(i=0;i /* Reed-Solomon codec control block */ struct rs { unsigned int mm; /* Bits per symbol */ unsigned int nn; /* Symbols per block (= (1<= rs->nn) { x -= rs->nn; x = (x >> rs->mm) + (x & rs->nn); } return x; } #define MODNN(x) modnn(rs,x) #define MM (rs->mm) #define NN (rs->nn) #define ALPHA_TO (rs->alpha_to) #define INDEX_OF (rs->index_of) #define GENPOLY (rs->genpoly) #define NROOTS (rs->nroots) #define FCR (rs->fcr) #define PRIM (rs->prim) #define IPRIM (rs->iprim) #define A0 (NN) #define ENCODE_RS encode_rs_char #define DECODE_RS decode_rs_char #define INIT_RS init_rs_char #define FREE_RS free_rs_char FEC_API void ENCODE_RS(void *p,DTYPE *data,DTYPE *parity); FEC_API int DECODE_RS(void *p,DTYPE *data,int *eras_pos,int no_eras); FEC_API void *INIT_RS(unsigned int symsize,unsigned int gfpoly,unsigned int fcr, unsigned int prim,unsigned int nroots); FEC_API void FREE_RS(void *p); gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/decode_rs.c0000664000175000017500000001605612207440367021750 0ustar jcorganjcorgan/* Reed-Solomon decoder * Copyright 2002 Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #ifdef DEBUG #include #endif #include #define NULL ((void *)0) #define min(a,b) ((a) < (b) ? (a) : (b)) #ifdef FIXED #include "fixed.h" #elif defined(BIGSYM) #include "int.h" #else #include "char.h" #endif int DECODE_RS( #ifndef FIXED void *p, #endif DTYPE *data, int *eras_pos, int no_eras){ #ifndef FIXED struct rs *rs = (struct rs *)p; #endif int deg_lambda, el, deg_omega; int i, j, r, k; #ifdef MAX_ARRAY DTYPE u,q,tmp,num1,num2,den,discr_r; DTYPE lambda[MAX_ARRAY], s[MAX_ARRAY]; /* Err+Eras Locator poly * and syndrome poly */ DTYPE b[MAX_ARRAY], t[MAX_ARRAY], omega[MAX_ARRAY]; DTYPE root[MAX_ARRAY], reg[MAX_ARRAY], loc[MAX_ARRAY]; #else DTYPE u,q,tmp,num1,num2,den,discr_r; DTYPE lambda[NROOTS+1], s[NROOTS]; /* Err+Eras Locator poly * and syndrome poly */ DTYPE b[NROOTS+1], t[NROOTS+1], omega[NROOTS+1]; DTYPE root[NROOTS], reg[NROOTS+1], loc[NROOTS]; #endif int syn_error, count; /* form the syndromes; i.e., evaluate data(x) at roots of g(x) */ for(i=0;(unsigned int)i 0) { /* Init lambda to be the erasure locator polynomial */ lambda[1] = ALPHA_TO[MODNN(PRIM*(NN-1-eras_pos[0]))]; for (i = 1; i < no_eras; i++) { u = MODNN(PRIM*(NN-1-eras_pos[i])); for (j = i+1; j > 0; j--) { tmp = INDEX_OF[lambda[j - 1]]; if(tmp != A0) lambda[j] ^= ALPHA_TO[MODNN(u + tmp)]; } } #if DEBUG >= 1 /* Test code that verifies the erasure locator polynomial just constructed Needed only for decoder debugging. */ /* find roots of the erasure location polynomial */ for(i=1;i<=no_eras;i++) reg[i] = INDEX_OF[lambda[i]]; count = 0; for (i = 1,k=IPRIM-1; i <= NN; i++,k = MODNN(k+IPRIM)) { q = 1; for (j = 1; j <= no_eras; j++) if (reg[j] != A0) { reg[j] = MODNN(reg[j] + j); q ^= ALPHA_TO[reg[j]]; } if (q != 0) continue; /* store root and error location number indices */ root[count] = i; loc[count] = k; count++; } if (count != no_eras) { printf("count = %d no_eras = %d\n lambda(x) is WRONG\n",count,no_eras); count = -1; goto finish; } #if DEBUG >= 2 printf("\n Erasure positions as determined by roots of Eras Loc Poly:\n"); for (i = 0; i < count; i++) printf("%d ", loc[i]); printf("\n"); #endif #endif } for(i=0;(unsigned int)i 0; j--){ if (reg[j] != A0) { reg[j] = MODNN(reg[j] + j); q ^= ALPHA_TO[reg[j]]; } } if (q != 0) continue; /* Not a root */ /* store root (index-form) and error location number */ #if DEBUG>=2 printf("count %d root %d loc %d\n",count,i,k); #endif root[count] = i; loc[count] = k; /* If we've already found max possible roots, * abort the search to save time */ if(++count == deg_lambda) break; } if (deg_lambda != count) { /* * deg(lambda) unequal to number of roots => uncorrectable * error detected */ count = -1; goto finish; } /* * Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo * x**NROOTS). in index form. Also find deg(omega). */ deg_omega = 0; for (i = 0; (unsigned int)i < NROOTS;i++){ tmp = 0; j = (deg_lambda < i) ? deg_lambda : i; for(;j >= 0; j--){ if ((s[i - j] != A0) && (lambda[j] != A0)) tmp ^= ALPHA_TO[MODNN(s[i - j] + lambda[j])]; } if(tmp != 0) deg_omega = i; omega[i] = INDEX_OF[tmp]; } omega[NROOTS] = A0; /* * Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = * inv(X(l))**(FCR-1) and den = lambda_pr(inv(X(l))) all in poly-form */ for (j = count-1; j >=0; j--) { num1 = 0; for (i = deg_omega; i >= 0; i--) { if (omega[i] != A0) num1 ^= ALPHA_TO[MODNN(omega[i] + i * root[j])]; } num2 = ALPHA_TO[MODNN(root[j] * (FCR - 1) + NN)]; den = 0; /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */ for (i = (int)min((unsigned int)deg_lambda,NROOTS-1) & ~1; i >= 0; i -=2) { if(lambda[i+1] != A0) den ^= ALPHA_TO[MODNN(lambda[i+1] + i * root[j])]; } if (den == 0) { #if DEBUG >= 1 printf("\n ERROR: denominator = 0\n"); #endif count = -1; goto finish; } /* Apply error to data */ if (num1 != 0) { data[loc[j]] ^= ALPHA_TO[MODNN(INDEX_OF[num1] + INDEX_OF[num2] + NN - INDEX_OF[den])]; } } finish: if(eras_pos != NULL){ for(i=0;i ccsds_tab.c gen_ccsds: gen_ccsds.o init_rs_char.o gcc -o $@ $^ gen_ccsds.o: gen_ccsds.c gcc $(CFLAGS) -c -o $@ $^ ccsds_tal.o: ccsds_tal.c ccsds_tal.c: gen_ccsds_tal ./gen_ccsds_tal > ccsds_tal.c exercise_char.o: exercise.c gcc $(CFLAGS) -c -o $@ $^ exercise_int.o: exercise.c gcc -DBIGSYM=1 $(CFLAGS) -c -o $@ $^ exercise_8.o: exercise.c gcc -DFIXED=1 $(CFLAGS) -c -o $@ $^ exercise_ccsds.o: exercise.c gcc -DCCSDS=1 $(CFLAGS) -c -o $@ $^ clean: rm -f *.o *.a ccsds_tab.c ccsds_tal.c gen_ccsds gen_ccsds_tal \ rstest librs.so.@SO_VERSION@ distclean: clean rm -f config.log config.cache config.status config.h makefile gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/init_rs.c0000664000175000017500000000626512207440367021471 0ustar jcorganjcorgan/* Initialize a RS codec * * Copyright 2002 Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #include #ifdef CCSDS #include "ccsds.h" #elif defined(BIGSYM) #include "int.h" #else #include "char.h" #endif #define NULL ((void *)0) void FREE_RS(void *p){ struct rs *rs = (struct rs *)p; free(rs->alpha_to); free(rs->index_of); free(rs->genpoly); free(rs); } /* Initialize a Reed-Solomon codec * symsize = symbol size, bits (1-8) * gfpoly = Field generator polynomial coefficients * fcr = first root of RS code generator polynomial, index form * prim = primitive element to generate polynomial roots * nroots = RS code generator polynomial degree (number of roots) */ void *INIT_RS(unsigned int symsize,unsigned int gfpoly,unsigned fcr,unsigned prim, unsigned int nroots){ struct rs *rs; int sr,root,iprim; unsigned int i, j; if(symsize > 8*sizeof(DTYPE)) return NULL; /* Need version with ints rather than chars */ if(fcr >= (1u<= (1u<= (1u<mm = symsize; rs->nn = (1<alpha_to = (DTYPE *)malloc(sizeof(DTYPE)*(rs->nn+1)); if(rs->alpha_to == NULL){ free(rs); return NULL; } rs->index_of = (DTYPE *)malloc(sizeof(DTYPE)*(rs->nn+1)); if(rs->index_of == NULL){ free(rs->alpha_to); free(rs); return NULL; } /* Generate Galois field lookup tables */ rs->index_of[0] = A0; /* log(zero) = -inf */ rs->alpha_to[A0] = 0; /* alpha**-inf = 0 */ sr = 1; for(i=0;inn;i++){ rs->index_of[sr] = i; rs->alpha_to[i] = sr; sr <<= 1; if(sr & (1<nn; } if(sr != 1){ /* field generator polynomial is not primitive! */ free(rs->alpha_to); free(rs->index_of); free(rs); return NULL; } /* Form RS code generator polynomial from its roots */ rs->genpoly = (DTYPE *)malloc(sizeof(DTYPE)*(nroots+1)); if(rs->genpoly == NULL){ free(rs->alpha_to); free(rs->index_of); free(rs); return NULL; } rs->fcr = fcr; rs->prim = prim; rs->nroots = nroots; /* Find prim-th root of 1, used in decoding */ for(iprim=1;(iprim % prim) != 0;iprim += rs->nn) ; rs->iprim = iprim / prim; rs->genpoly[0] = 1; for (i = 0,root=fcr*prim; i < nroots; i++,root += prim) { rs->genpoly[i+1] = 1; /* Multiply rs->genpoly[] by @**(root + x) */ for (j = i; j > 0; j--){ if (rs->genpoly[j] != 0) rs->genpoly[j] = rs->genpoly[j-1] ^ rs->alpha_to[modnn(rs,rs->index_of[rs->genpoly[j]] + root)]; else rs->genpoly[j] = rs->genpoly[j-1]; } /* rs->genpoly[0] can never be zero */ rs->genpoly[0] = rs->alpha_to[modnn(rs,rs->index_of[rs->genpoly[0]] + root)]; } /* convert rs->genpoly[] to index form for quicker encoding */ for (i = 0; i <= nroots; i++) rs->genpoly[i] = rs->index_of[rs->genpoly[i]]; #if 0 printf ("genpoly:\n"); for (i = nroots; i >= 0; i--){ printf (" %3d*X^%d\n", rs->alpha_to[rs->genpoly[i]], i); } #endif return rs; } gnuradio-3.7.2.1/gr-fec/lib/reed-solomon/exercise.c0000664000175000017500000000616612207440367021631 0ustar jcorganjcorgan/* Exercise an RS codec a specified number of times using random * data and error patterns * * Copyright 2002 Phil Karn, KA9Q * May be used under the terms of the GNU General Public License (GPL) */ #define FLAG_ERASURE 1 /* Randomly flag 50% of errors as erasures */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #ifdef FIXED #include "fixed.h" #define EXERCISE exercise_8 #elif defined(CCSDS) #include "fixed.h" #include "ccsds.h" #define EXERCISE exercise_ccsds #elif defined(BIGSYM) #include "int.h" #define EXERCISE exercise_int #else #include "char.h" #define EXERCISE exercise_char #endif #ifdef FIXED #define PRINTPARM printf("(255,223):"); #elif defined(CCSDS) #define PRINTPARM printf("CCSDS (255,223):"); #else #define PRINTPARM printf("(%d,%d):",rs->nn,rs->nn-rs->nroots); #endif /* Exercise the RS codec passed as an argument */ int EXERCISE( #if !defined(CCSDS) && !defined(FIXED) void *p, #endif int trials){ #if !defined(CCSDS) && !defined(FIXED) struct rs *rs = (struct rs *)p; #endif #if MAX_ARRAY DTYPE block[MAX_ARRAY],tblock[MAX_ARRAY]; unsigned int i; int errors; int errlocs[MAX_ARRAY]; int derrlocs[MAX_ARRAY]; #else DTYPE block[NN],tblock[NN]; unsigned int i; int errors; int errlocs[NN]; int derrlocs[NROOTS]; #endif int derrors; int errval,errloc; int erasures; int decoder_errors = 0; while(trials-- != 0){ /* Test up to the error correction capacity of the code */ for(errors=0;(unsigned int)errors <= NROOTS/2;errors++){ /* Load block with random data and encode */ for(i=0;i unsigned char Taltab[256],Tal1tab[256]; static unsigned char tal[] = { 0x8d, 0xef, 0xec, 0x86, 0xfa, 0x99, 0xaf, 0x7b }; /* Generate conversion lookup tables between conventional alpha representation * (@**7, @**6, ...@**0) * and Berlekamp's dual basis representation * (l0, l1, ...l7) */ int main(){ int i,j,k; for(i=0;i<256;i++){/* For each value of input */ Taltab[i] = 0; for(j=0;j<8;j++) /* for each column of matrix */ for(k=0;k<8;k++){ /* for each row of matrix */ if(i & (1< extern "C" { #include } namespace gr { namespace fec { class FEC_API decode_ccsds_27_fb_impl : public decode_ccsds_27_fb { private: // Viterbi state int d_mettab[2][256]; struct viterbi_state d_state0[64]; struct viterbi_state d_state1[64]; unsigned char d_viterbi_in[16]; int d_count; public: decode_ccsds_27_fb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace fec */ } /* namespace gr */ #endif /* INCLUDED_FEC_DECODE_CCSDS_27_FB_IMPL_H */ gnuradio-3.7.2.1/gr-fec/swig/0000775000175000017500000000000012207440367015445 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fec/swig/CMakeLists.txt0000664000175000017500000000345112207440367020210 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/../include ${GR_FEC_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/fec_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/fec) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-fec) GR_SWIG_MAKE(fec_swig fec_swig.i) GR_SWIG_INSTALL( TARGETS fec_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/fec COMPONENT "fec_python" ) install( FILES fec_swig.i ${CMAKE_CURRENT_BINARY_DIR}/fec_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "fec_swig" ) gnuradio-3.7.2.1/gr-fec/swig/fec_swig.i0000664000175000017500000000226612207440367017413 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define FEC_API %include "gnuradio.i" //load generated python docstrings %include "fec_swig_doc.i" %{ #include "gnuradio/fec/decode_ccsds_27_fb.h" #include "gnuradio/fec/encode_ccsds_27_bb.h" %} %include "gnuradio/fec/decode_ccsds_27_fb.h" %include "gnuradio/fec/encode_ccsds_27_bb.h" GR_SWIG_BLOCK_MAGIC2(fec, decode_ccsds_27_fb); GR_SWIG_BLOCK_MAGIC2(fec, encode_ccsds_27_bb); gnuradio-3.7.2.1/gr-fec/gnuradio-fec.pc.in0000664000175000017500000000040212207440367017764 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-fec Description: GNU Radio's FEC signal processing blocks Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-fec Cflags: -I${includedir} gnuradio-3.7.2.1/gr-analog/0000775000175000017500000000000012207440367015200 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/CMakeLists.txt0000664000175000017500000000715112207440367017744 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-analog" ENABLE_GR_ANALOG Boost_FOUND ENABLE_VOLK ENABLE_GNURADIO_RUNTIME ENABLE_GR_FFT ENABLE_GR_FILTER ) GR_SET_GLOBAL(GR_ANALOG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) GR_SET_GLOBAL(GR_ANALOG_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/swig ) SET(GR_PKG_ANALOG_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/analog) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_ANALOG) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_ANALOG_DESCRIPTION "GNU Radio Analog Blocks") CPACK_COMPONENT("analog_runtime" GROUP "Analog" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("analog_devel" GROUP "Analog" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("analog_python" GROUP "Analog" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime" DEPENDS "runtime_python;analog_runtime" ) CPACK_COMPONENT("analog_swig" GROUP "Analog" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;analog_python;analog_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/analog) add_subdirectory(lib) add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/analog) add_subdirectory(grc) add_subdirectory(examples) add_subdirectory(examples/tags) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-analog.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-analog.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-analog.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "analog_devel" ) endif(ENABLE_GR_ANALOG) gnuradio-3.7.2.1/gr-analog/include/0000775000175000017500000000000012207440367016623 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/include/gnuradio/0000775000175000017500000000000012207440367020433 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/0000775000175000017500000000000012237515111021665 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/quadrature_demod_cf.h0000664000175000017500000000362312207440367026046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_QUADRATURE_DEMOD_CF_H #define INCLUDED_ANALOG_QUADRATURE_DEMOD_CF_H #include #include namespace gr { namespace analog { /*! * \brief quadrature demodulator: complex in, float out * \ingroup modulators_blk * * \details * This can be used to demod FM, FSK, GMSK, etc. * The input is complex baseband. */ class ANALOG_API quadrature_demod_cf : virtual public sync_block { public: // gr::analog::quadrature_demod_cf::sptr typedef boost::shared_ptr sptr; /* \brief Make a quadrature demodulator block. * * \param gain Gain setting to adjust the output amplitude. Set * based on converting the phase difference between * samples to a nominal output value. */ static sptr make(float gain); virtual void set_gain(float gain) = 0; virtual float gain() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_QUADRATURE_DEMOD_CF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/CMakeLists.txt0000664000175000017500000000653712207440367024447 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict2(name, sig, 'analog') build_utils.expand_template(d, inp) ") macro(expand_h root) #make a list of all the generated files unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the files add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #install rules for the generated h files list(APPEND generated_includes ${expanded_files_h}) endmacro(expand_h) ######################################################################## # Invoke macro to generate various sources ####################################################################### expand_h(noise_source_X s i f c) expand_h(fastnoise_source_X s i f c) expand_h(sig_source_X s i f c) add_custom_target(analog_generated_includes DEPENDS ${generated_includes} ) ######################################################################## # Install header files ######################################################################## install(FILES ${generated_includes} api.h cpm.h noise_type.h agc.h agc2.h noise_type.h squelch_base_ff.h agc_cc.h agc_ff.h agc2_cc.h agc2_ff.h agc3_cc.h cpfsk_bc.h ctcss_squelch_ff.h dpll_bb.h feedforward_agc_cc.h fmdet_cf.h frequency_modulator_fc.h phase_modulator_fc.h pll_carriertracking_cc.h pll_freqdet_cf.h pll_refout_cc.h probe_avg_mag_sqrd_c.h probe_avg_mag_sqrd_cf.h probe_avg_mag_sqrd_f.h pwr_squelch_cc.h pwr_squelch_ff.h quadrature_demod_cf.h rail_ff.h sig_source_waveform.h simple_squelch_cc.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/analog COMPONENT "analog_devel" ) gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc_cc.h0000664000175000017500000000422112207440367023243 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC_CC_H #define INCLUDED_ANALOG_AGC_CC_H #include #include #include namespace gr { namespace analog { /*! * \brief high performance Automatic Gain Control class * \ingroup level_controllers_blk * * \details * For Power the absolute value of the complex number is used. */ class ANALOG_API agc_cc : virtual public sync_block { public: // gr::analog::agc_cc::sptr typedef boost::shared_ptr sptr; /*! * Build a complex value AGC loop block. * * \param rate the update rate of the loop. * \param reference reference value to adjust signal power to. * \param gain initial gain value. */ static sptr make(float rate = 1e-4, float reference = 1.0, float gain = 1.0); virtual float rate() const = 0; virtual float reference() const = 0; virtual float gain() const = 0; virtual float max_gain() const = 0; virtual void set_rate(float rate) = 0; virtual void set_reference(float reference) = 0; virtual void set_gain(float gain) = 0; virtual void set_max_gain(float max_gain) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/ctcss_squelch_ff.h0000664000175000017500000000501112207440367025360 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_CTCSS_SQUELCH_FF_H #define INCLUDED_ANALOG_CTCSS_SQUELCH_FF_H #include #include #include namespace gr { namespace analog { /*! * \brief gate or zero output if CTCSS tone not present * \ingroup level_controllers_blk */ class ANALOG_API ctcss_squelch_ff : public squelch_base_ff, virtual public block { protected: virtual void update_state(const float &in) = 0; virtual bool mute() const = 0; public: // gr::analog::ctcss_squelch_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Make CTCSS tone squelch block. * * \param rate gain of the internal frequency filters. * \param freq frequency value to use as the squelch tone. * \param level threshold level for the squelch tone. * \param len length of the frequency filters. * \param ramp sets response characteristic. * \param gate if true, no output if no squelch tone. * if false, output 0's if no squelch tone. */ static sptr make(int rate, float freq, float level, int len, int ramp, bool gate); virtual std::vector squelch_range() const = 0; virtual float level() const = 0; virtual void set_level(float level) = 0; virtual int len() const = 0; virtual int ramp() const = 0; virtual void set_ramp(int ramp) = 0; virtual bool gate() const = 0; virtual void set_gate(bool gate) = 0; virtual bool unmuted() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_CTCSS_SQUELCH_FF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc2_cc.h0000664000175000017500000000471312207440367023333 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC2_CC_H #define INCLUDED_ANALOG_AGC2_CC_H #include #include #include namespace gr { namespace analog { /*! * \brief high performance Automatic Gain Control class with * attack and decay rates. * \ingroup level_controllers_blk * * \details * For Power the absolute value of the complex number is used. */ class ANALOG_API agc2_cc : virtual public sync_block { public: // gr::analog::agc2_cc::sptr typedef boost::shared_ptr sptr; /*! * Build a complex value AGC loop block with attack and decay rates. * * \param attack_rate the update rate of the loop when in attack mode. * \param decay_rate the update rate of the loop when in decay mode. * \param reference reference value to adjust signal power to. * \param gain initial gain value. */ static sptr make(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0); virtual float attack_rate() const = 0; virtual float decay_rate() const = 0; virtual float reference() const = 0; virtual float gain() const = 0; virtual float max_gain() const = 0; virtual void set_attack_rate(float rate) = 0; virtual void set_decay_rate(float rate) = 0; virtual void set_reference(float reference) = 0; virtual void set_gain(float gain) = 0; virtual void set_max_gain(float max_gain) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC2_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/pll_carriertracking_cc.h0000664000175000017500000000643612207440367026544 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PLL_CARRIERTRACKING_CC_H #define INCLUDED_ANALOG_PLL_CARRIERTRACKING_CC_H #include #include #include namespace gr { namespace analog { /*! * \brief Implements a PLL which locks to the input frequency and outputs the * input signal mixed with that carrier. * \ingroup synchronizers_blk * * \details * Input stream 0: complex * Output stream 0: complex * * This PLL locks onto a [possibly noisy] reference carrier on the * input and outputs that signal, downconverted to DC * * All settings max_freq and min_freq are in terms of radians per * sample, NOT HERTZ. The loop bandwidth determins the lock range * and should be set around pi/200 -- 2pi/100. \sa * pll_freqdet_cf, pll_carriertracking_cc */ class ANALOG_API pll_carriertracking_cc : virtual public sync_block, virtual public blocks::control_loop { public: // gr::analog::pll_carriertracking_cc::sptr typedef boost::shared_ptr sptr; /* \brief Make a carrier tracking PLL block. * * \param loop_bw: control loop's bandwidth parameter. * \param max_freq: maximum (normalized) frequency PLL will lock to. * \param min_freq: minimum (normalized) frequency PLL will lock to. */ static sptr make(float loop_bw, float max_freq, float min_freq); virtual bool lock_detector(void) = 0; virtual bool squelch_enable(bool) = 0; virtual float set_lock_threshold(float) = 0; virtual void set_loop_bandwidth(float bw) = 0; virtual void set_damping_factor(float df) = 0; virtual void set_alpha(float alpha) = 0; virtual void set_beta(float beta) = 0; virtual void set_frequency(float freq) = 0; virtual void set_phase(float phase) = 0; virtual void set_min_freq(float freq) = 0; virtual void set_max_freq(float freq) = 0; virtual float get_loop_bandwidth() const = 0; virtual float get_damping_factor() const = 0; virtual float get_alpha() const = 0; virtual float get_beta() const = 0; virtual float get_frequency() const = 0; virtual float get_phase() const = 0; virtual float get_min_freq() const = 0; virtual float get_max_freq() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PLL_CARRIERTRACKING_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/simple_squelch_cc.h0000664000175000017500000000365212207440367025535 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_SIMPLE_SQUELCH_CC_H #define INCLUDED_ANALOG_SIMPLE_SQUELCH_CC_H #include #include namespace gr { namespace analog { /*! * \brief simple squelch block based on average signal power and threshold in dB. * \ingroup level_controllers_blk */ class ANALOG_API simple_squelch_cc : virtual public sync_block { public: // gr::analog::simple_squelch_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a simple squelch block. * * \param threshold_db Threshold for muting. * \param alpha Gain parameter for the running average filter. */ static sptr make(double threshold_db, double alpha); virtual bool unmuted() const = 0; virtual void set_alpha(double alpha) = 0; virtual void set_threshold(double decibels) = 0; virtual double threshold() const = 0; virtual std::vector squelch_range() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SIMPLE_SQUELCH_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/pwr_squelch_ff.h0000664000175000017500000000460612207440367025062 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PWR_SQUELCH_FF_H #define INCLUDED_ANALOG_PWR_SQUELCH_FF_H #include #include #include namespace gr { namespace analog { /*! * \brief gate or zero output when input power below threshold * \ingroup level_controllers_blk */ class ANALOG_API pwr_squelch_ff : public squelch_base_ff, virtual public block { protected: virtual void update_state(const float &in) = 0; virtual bool mute() const = 0; public: // gr::analog::pwr_squelch_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Make power-based squelch block. * * \param db threshold (in dB) for power squelch * \param alpha Gain of averaging filter * \param ramp sets response characteristic. * \param gate if true, no output if no squelch tone. * if false, output 0's if no squelch tone. */ static sptr make(double db, double alpha=0.0001, int ramp=0, bool gate=false); virtual std::vector squelch_range() const = 0; virtual double threshold() const = 0; virtual void set_threshold(double db) = 0; virtual void set_alpha(double alpha) = 0; virtual int ramp() const = 0; virtual void set_ramp(int ramp) = 0; virtual bool gate() const = 0; virtual void set_gate(bool gate) = 0; virtual bool unmuted() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PWR_SQUELCH_FF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc.h0000664000175000017500000001106012207440367022575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC_H #define INCLUDED_ANALOG_AGC_H #include #include #include namespace gr { namespace analog { namespace kernel { /*! * \brief high performance Automatic Gain Control class for complex signals. * \ingroup level_controllers_blk * * \details * For Power the absolute value of the complex number is used. */ class ANALOG_API agc_cc { public: /*! * Construct a complex value AGC loop implementation object. * * \param rate the update rate of the loop. * \param reference reference value to adjust signal power to. * \param gain initial gain value. * \param max_gain maximum gain value (0 for unlimited). */ agc_cc(float rate = 1e-4, float reference = 1.0, float gain = 1.0, float max_gain = 0.0) : _rate(rate), _reference(reference), _gain(gain), _max_gain(max_gain) {}; virtual ~agc_cc() {}; float rate() const { return _rate; } float reference() const { return _reference; } float gain() const { return _gain; } float max_gain() const { return _max_gain; } void set_rate(float rate) { _rate = rate; } void set_reference(float reference) { _reference = reference; } void set_gain(float gain) { _gain = gain; } void set_max_gain(float max_gain) { _max_gain = max_gain; } gr_complex scale(gr_complex input) { gr_complex output = input * _gain; _gain += _rate * (_reference - sqrt(output.real()*output.real() + output.imag()*output.imag())); if(_max_gain > 0.0 && _gain > _max_gain) { _gain = _max_gain; } return output; } void scaleN(gr_complex output[], const gr_complex input[], unsigned n) { for(unsigned i = 0; i < n; i++) { output[i] = scale (input[i]); } } protected: float _rate; // adjustment rate float _reference; // reference value float _gain; // current gain float _max_gain; // max allowable gain }; /*! * \brief high performance Automatic Gain Control class for float signals. * * Power is approximated by absolute value */ class ANALOG_API agc_ff { public: /*! * Construct a floating point value AGC loop implementation object. * * \param rate the update rate of the loop. * \param reference reference value to adjust signal power to. * \param gain initial gain value. * \param max_gain maximum gain value (0 for unlimited). */ agc_ff(float rate = 1e-4, float reference = 1.0, float gain = 1.0, float max_gain = 0.0) : _rate(rate), _reference(reference), _gain(gain), _max_gain(max_gain) {}; ~agc_ff() {}; float rate () const { return _rate; } float reference () const { return _reference; } float gain () const { return _gain; } float max_gain () const { return _max_gain; } void set_rate (float rate) { _rate = rate; } void set_reference (float reference) { _reference = reference; } void set_gain (float gain) { _gain = gain; } void set_max_gain (float max_gain) { _max_gain = max_gain; } float scale (float input) { float output = input * _gain; _gain += (_reference - fabsf (output)) * _rate; if(_max_gain > 0.0 && _gain > _max_gain) _gain = _max_gain; return output; } void scaleN(float output[], const float input[], unsigned n) { for(unsigned i = 0; i < n; i++) output[i] = scale (input[i]); } protected: float _rate; // adjustment rate float _reference; // reference value float _gain; // current gain float _max_gain; // maximum gain }; } /* namespace kernel */ } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/pll_freqdet_cf.h0000664000175000017500000000621312207440367025020 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PLL_FREQDET_CF_H #define INCLUDED_ANALOG_PLL_FREQDET_CF_H #include #include #include namespace gr { namespace analog { /*! * \brief Implements a PLL which locks to the input frequency and outputs * an estimate of that frequency. Useful for FM Demod. * \ingroup synchronizers_blk * * \details * Input stream 0: complex * Output stream 0: float * * This PLL locks onto a [possibly noisy] reference carrier on * the input and outputs an estimate of that frequency in radians per sample. * All settings max_freq and min_freq are in terms of radians per sample, * NOT HERTZ. The loop bandwidth determins the lock range and should be set * around pi/200 -- 2pi/100. * \sa pll_refout_cc, pll_carriertracking_cc */ class ANALOG_API pll_freqdet_cf : virtual public sync_block, virtual public blocks::control_loop { public: // gr::analog::pll_freqdet_cf::sptr typedef boost::shared_ptr sptr; /* \brief Make PLL block that outputs the tracked signal's frequency. * * \param loop_bw: control loop's bandwidth parameter. * \param max_freq: maximum (normalized) frequency PLL will lock to. * \param min_freq: minimum (normalized) frequency PLL will lock to. */ static sptr make(float loop_bw, float max_freq, float min_freq); virtual void set_loop_bandwidth(float bw) = 0; virtual void set_damping_factor(float df) = 0; virtual void set_alpha(float alpha) = 0; virtual void set_beta(float beta) = 0; virtual void set_frequency(float freq) = 0; virtual void set_phase(float phase) = 0; virtual void set_min_freq(float freq) = 0; virtual void set_max_freq(float freq) = 0; virtual float get_loop_bandwidth() const = 0; virtual float get_damping_factor() const = 0; virtual float get_alpha() const = 0; virtual float get_beta() const = 0; virtual float get_frequency() const = 0; virtual float get_phase() const = 0; virtual float get_min_freq() const = 0; virtual float get_max_freq() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PLL_FREQDET_CF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/frequency_modulator_fc.h0000664000175000017500000000337212207440367026611 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_FREQUENCY_MODULATOR_FC_H #define INCLUDED_ANALOG_FREQUENCY_MODULATOR_FC_H #include #include namespace gr { namespace analog { /*! * \brief Frequency modulator block * \ingroup modulators_blk * * \details * float input; complex baseband output */ class ANALOG_API frequency_modulator_fc : virtual public sync_block { public: // gr::analog::frequency_modulator_fc::sptr typedef boost::shared_ptr sptr; /*! * Build a frequency modulator block. * * \param sensitivity radians/sample = amplitude * sensitivity */ static sptr make(double sensitivity); virtual void set_sensitivity(float sens) = 0; virtual float sensitivity() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_FREQUENCY_MODULATOR_FC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/cpfsk_bc.h0000664000175000017500000000350212207440367023617 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_CPFSK_BC_H #define INCLUDED_ANALOG_CPFSK_BC_H #include #include namespace gr { namespace analog { /*! * \brief Perform continuous phase 2-level frequency shift keying modulation * on an input stream of unpacked bits. * \ingroup modulators_blk */ class ANALOG_API cpfsk_bc : virtual public sync_interpolator { public: // gr::analog::cpfsk_bc::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a CPFSK block. * * \param k modulation index * \param ampl output amplitude * \param samples_per_sym number of output samples per input bit */ static sptr make(float k, float ampl, int samples_per_sym); virtual void set_amplitude(float amplitude) = 0; virtual float amplitude() = 0; virtual float freq() = 0; virtual float phase() = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_CPFSK_BC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc2.h0000664000175000017500000001304212207440367022661 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC2_H #define INCLUDED_ANALOG_AGC2_H #include #include #include namespace gr { namespace analog { namespace kernel { /*! * \brief high performance Automatic Gain Control class * \ingroup level_controllers_blk * * \details * For Power the absolute value of the complex number is used. */ class ANALOG_API agc2_cc { public: /*! * Construct a comple value AGC loop implementation object. * * \param attack_rate the update rate of the loop when in attack mode. * \param decay_rate the update rate of the loop when in decay mode. * \param reference reference value to adjust signal power to. * \param gain initial gain value. * \param max_gain maximum gain value (0 for unlimited). */ agc2_cc(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0, float max_gain = 0.0) : _attack_rate(attack_rate), _decay_rate(decay_rate), _reference(reference), _gain(gain), _max_gain(max_gain) {}; float decay_rate() const { return _decay_rate; } float attack_rate() const { return _attack_rate; } float reference() const { return _reference; } float gain() const { return _gain; } float max_gain() const { return _max_gain; } void set_decay_rate(float rate) { _decay_rate = rate; } void set_attack_rate(float rate) { _attack_rate = rate; } void set_reference(float reference) { _reference = reference; } void set_gain(float gain) { _gain = gain; } void set_max_gain(float max_gain) { _max_gain = max_gain; } gr_complex scale(gr_complex input) { gr_complex output = input * _gain; float tmp = -_reference + sqrt(output.real()*output.real() + output.imag()*output.imag()); float rate = _decay_rate; if((tmp) > _gain) { rate = _attack_rate; } _gain -= tmp*rate; // Not sure about this; will blow up if _gain < 0 (happens // when rates are too high), but is this the solution? if(_gain < 0.0) _gain = 10e-5; if(_max_gain > 0.0 && _gain > _max_gain) { _gain = _max_gain; } return output; } void scaleN(gr_complex output[], const gr_complex input[], unsigned n) { for(unsigned i = 0; i < n; i++) output[i] = scale (input[i]); } protected: float _attack_rate; // attack rate for fast changing signals float _decay_rate; // decay rate for slow changing signals float _reference; // reference value float _gain; // current gain float _max_gain; // max allowable gain }; class ANALOG_API agc2_ff { public: /*! * Construct a floating point value AGC loop implementation object. * * \param attack_rate the update rate of the loop when in attack mode. * \param decay_rate the update rate of the loop when in decay mode. * \param reference reference value to adjust signal power to. * \param gain initial gain value. * \param max_gain maximum gain value (0 for unlimited). */ agc2_ff(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0, float max_gain = 0.0) : _attack_rate(attack_rate), _decay_rate(decay_rate), _reference(reference), _gain(gain), _max_gain(max_gain) {}; float attack_rate() const { return _attack_rate; } float decay_rate() const { return _decay_rate; } float reference() const { return _reference; } float gain() const { return _gain; } float max_gain() const { return _max_gain; } void set_attack_rate(float rate) { _attack_rate = rate; } void set_decay_rate(float rate) { _decay_rate = rate; } void set_reference(float reference) { _reference = reference; } void set_gain(float gain) { _gain = gain; } void set_max_gain(float max_gain) { _max_gain = max_gain; } float scale(float input) { float output = input * _gain; float tmp = (fabsf(output)) - _reference; float rate = _decay_rate; if(fabsf(tmp) > _gain) { rate = _attack_rate; } _gain -= tmp*rate; // Not sure about this if(_gain < 0.0) _gain = 10e-5; if(_max_gain > 0.0 && _gain > _max_gain) { _gain = _max_gain; } return output; } void scaleN(float output[], const float input[], unsigned n) { for(unsigned i = 0; i < n; i++) output[i] = scale (input[i]); } protected: float _attack_rate; // attack_rate for fast changing signals float _decay_rate; // decay rate for slow changing signals float _reference; // reference value float _gain; // current gain float _max_gain; // maximum gain }; } /* namespace kernel */ } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC2_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/squelch_base_ff.h0000664000175000017500000000325412207440367025162 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_SQUELCH_BASE_FF_H #define INCLUDED_ANALOG_SQUELCH_BASE_FF_H #include #include namespace gr { namespace analog { /*! * \brief basic squelch block; to be subclassed for other squelches. * \ingroup level_blk */ class ANALOG_API squelch_base_ff : virtual public block { protected: virtual void update_state(const float &sample) = 0; virtual bool mute() const = 0; public: squelch_base_ff() {}; virtual int ramp() const = 0; virtual void set_ramp(int ramp) = 0; virtual bool gate() const = 0; virtual void set_gate(bool gate) = 0; virtual bool unmuted() const = 0; virtual std::vector squelch_range() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SQUELCH_BASE_FF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/probe_avg_mag_sqrd_c.h0000664000175000017500000000427612207440367026201 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_C_H #define INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_C_H #include #include namespace gr { namespace analog { /*! * \brief compute avg magnitude squared. * \ingroup measurement_tools_blk * * \details * Input stream 0: complex * * Compute a running average of the magnitude squared of the the * input. The level and indication as to whether the level exceeds * threshold can be retrieved with the level and unmuted * accessors. */ class ANALOG_API probe_avg_mag_sqrd_c : virtual public sync_block { public: // gr::analog::probe_avg_mag_sqrd_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a complex sink that computes avg magnitude squared. * * \param threshold_db Threshold for muting. * \param alpha Gain parameter for the running average filter. */ static sptr make(double threshold_db, double alpha = 0.0001); virtual bool unmuted() const = 0; virtual double level() const = 0; virtual double threshold() const = 0; virtual void set_alpha(double alpha) = 0; virtual void set_threshold(double decibels) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_C_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/sig_source_X.h.t0000664000175000017500000000456412207440367024751 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace analog { /*! * \brief signal generator with @TYPE@ output. * \ingroup waveform_generators_blk */ class ANALOG_API @BASE_NAME@ : virtual public sync_block { public: // gr::analog::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! * Build a signal source block. * * \param sampling_freq Sampling rate of signal. * \param waveform wavetform type. * \param wave_freq Frequency of waveform (relative to sampling_freq). * \param ampl Signal amplitude. * \param offset offset of signal. */ static sptr make(double sampling_freq, gr::analog::gr_waveform_t waveform, double wave_freq, double ampl, @TYPE@ offset = 0); virtual double sampling_freq() const = 0; virtual gr::analog::gr_waveform_t waveform() const = 0; virtual double frequency() const = 0; virtual double amplitude() const = 0; virtual @TYPE@ offset() const = 0; virtual void set_sampling_freq(double sampling_freq) = 0; virtual void set_waveform(gr::analog::gr_waveform_t waveform) = 0; virtual void set_frequency(double frequency) = 0; virtual void set_amplitude(double ampl) = 0; virtual void set_offset(@TYPE@ offset) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/dpll_bb.h0000664000175000017500000000337712207440367023455 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_DPLL_BB_H #define INCLUDED_ANALOG_DPLL_BB_H #include #include namespace gr { namespace analog { /*! * \brief Detect the peak of a signal * \ingroup peak_detectors_blk * * \details * If a peak is detected, this block outputs a 1, * or it outputs 0's. */ class ANALOG_API dpll_bb : virtual public sync_block { public: // gr::analog::dpll_bb::sptr typedef boost::shared_ptr sptr; static sptr make(float period, float gain); virtual void set_gain(float gain) = 0; virtual void set_decision_threshold(float thresh) = 0; virtual float gain() const = 0; virtual float freq() const = 0; virtual float phase() const = 0; virtual float decision_threshold() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_DPLL_BB_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/probe_avg_mag_sqrd_f.h0000664000175000017500000000427112207440367026177 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_F_H #define INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_F_H #include #include namespace gr { namespace analog { /*! * \brief compute avg magnitude squared. * \ingroup measurement_tools_blk * * \details * input stream 0: float * * Compute a running average of the magnitude squared of the the * input. The level and indication as to whether the level exceeds * threshold can be retrieved with the level and unmuted * accessors. */ class ANALOG_API probe_avg_mag_sqrd_f : virtual public sync_block { public: // gr::analog::probe_avg_mag_sqrd_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a float sink that computes avg magnitude squared. * * \param threshold_db Threshold for muting. * \param alpha Gain parameter for the running average filter. */ static sptr make(double threshold_db, double alpha = 0.0001); virtual bool unmuted() const = 0; virtual double level() const = 0; virtual double threshold() const = 0; virtual void set_alpha (double alpha) = 0; virtual void set_threshold (double decibels) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_F_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/cpm.h0000664000175000017500000000665212207440367022635 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_CPM_H #define INCLUDED_ANALOG_CPM_H #include #include namespace gr { namespace analog { /*! \brief Return the taps for an interpolating FIR filter * (gr::filter::interp_fir_filter_fff). */ class ANALOG_API cpm { public: enum cpm_type { LRC, LSRC, LREC, TFM, GAUSSIAN, GENERIC = 999 }; /*! \brief Return the taps for an interpolating FIR filter * (gr::filter::interp_fir_filter_fff). * * \details * These taps represent the phase response \f$g(k)\f$ for use in a CPM modulator, * see also gr_cpmmod_bc. * * \param type The CPM type (Rectangular, Raised Cosine, * Spectral Raised Cosine, Tamed FM or Gaussian). * \param samples_per_sym Samples per symbol. * \param L The length of the phase response in symbols. * \param beta For Spectral Raised Cosine, this is the rolloff * factor. For Gaussian phase responses, this the * 3dB-time-bandwidth product. For all other cases, * it is ignored. * * Output: returns a vector of length \a K = \p samples_per_sym * x \p L. This can be used directly in an * interpolating FIR filter such as * gr_interp_fir_filter_fff with interpolation factor \p * samples_per_sym. * * All phase responses are normalised s.t. \f$ \sum_{k=0}^{K-1} * g(k) = 1\f$; this will cause a maximum phase change of \f$ h * \cdot \pi\f$ between two symbols, where \a h is the * modulation index. * * The following phase responses can be generated: * - LREC: Rectangular phase response. * - LRC: Raised cosine phase response, looks like 1 - cos(x). * - LSRC: Spectral raised cosine. This requires a rolloff factor beta. * The phase response is the Fourier transform of raised cosine * function. * - TFM: Tamed frequency modulation. This scheme minimizes phase change for * rapidly varying input symbols. * - GAUSSIAN: A Gaussian phase response. For a modulation index h = 1/2, this * results in GMSK. * * A short description of all these phase responses can be found in [1]. * * [1]: Anderson, Aulin and Sundberg; Digital Phase Modulation */ static std::vector phase_response(cpm_type type, unsigned samples_per_sym, unsigned L, double beta=0.3); }; } // namespace analog } // namespace gr #endif /* INCLUDED_ANALOG_CPM_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/fmdet_cf.h0000664000175000017500000000434412207440367023621 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_FMDET_CF_H #define INCLUDED_ANALOG_FMDET_CF_H #include #include namespace gr { namespace analog { /*! * \brief Implements an IQ slope detector * \ingroup modulators_blk * * \details * input: stream of complex; output: stream of floats * * This implements a limiting slope detector. The limiter is in * the normalization by the magnitude of the sample */ class ANALOG_API fmdet_cf : virtual public sync_block { public: // gr::analog::fmdet_cf::sptr typedef boost::shared_ptr sptr; /*! * \brief Make FM detector block. * * \param samplerate sample rate of signal (is not used; to be removed) * \param freq_low lowest frequency of signal (Hz) * \param freq_high highest frequency of signal (Hz) * \param scl scale factor */ static sptr make(float samplerate, float freq_low, float freq_high, float scl); virtual void set_scale(float scl) = 0; virtual void set_freq_range(float freq_low, float freq_high) = 0; virtual float freq() const = 0; virtual float freq_high() const = 0; virtual float freq_low() const = 0; virtual float scale() const = 0; virtual float bias() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_FMDET_CF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/fastnoise_source_X.h.t0000664000175000017500000000433412237515111026146 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace analog { /*! * \brief Random number source * \ingroup source_blk * * \details * Generate random values from different distributions. * Currently, only Gaussian and uniform are enabled. */ class ANALOG_API @BASE_NAME@ : virtual public sync_block { public: // gr::analog::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! \brief Make a fast noise source * \param type the random distribution to use (see gnuradio/analog/noise_type.h) * \param ampl a scaling factor for the output * \param seed seed for random generators. Note that for uniform and * \param samples Number of samples to pre-generate * Gaussian distributions, this should be a negative number. */ static sptr make(noise_type_t type, float ampl, long seed = 0, long samples=1024*16); virtual @TYPE@ sample() = 0; virtual @TYPE@ sample_unbiased() = 0; virtual void set_type(noise_type_t type) = 0; virtual void set_amplitude(float ampl) = 0; virtual noise_type_t type() const = 0; virtual float amplitude() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/feedforward_agc_cc.h0000664000175000017500000000333112207440367025614 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_FEEDFORWARD_AGC_CC_H #define INCLUDED_ANALOG_FEEDFORWARD_AGC_CC_H #include #include namespace gr { namespace analog { /*! * \brief Non-causal AGC which computes required gain based on max * absolute value over nsamples * \ingroup level_controllers_blk */ class ANALOG_API feedforward_agc_cc : virtual public sync_block { public: // gr::analog::feedforward_agc_cc::sptr typedef boost::shared_ptr sptr; /*! * Build a complex valued feed-forward AGC loop block. * * \param nsamples number of samples to look ahead. * \param reference reference value to adjust signal power to. */ static sptr make(int nsamples, float reference); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_GR_FEEDFORWARD_AGC_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/rail_ff.h0000664000175000017500000000325212207440367023451 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_RAIL_FF_H #define INCLUDED_ANALOG_RAIL_FF_H #include #include namespace gr { namespace analog { /*! * \brief clips input values to min, max * \ingroup level_controllers_blk */ class ANALOG_API rail_ff : virtual public sync_block { public: // gr::analog::rail_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a rail block. * * \param lo the low value to clip to. * \param hi the high value to clip to. */ static sptr make(float lo, float hi); virtual float lo() const = 0; virtual float hi() const = 0; virtual void set_lo(float lo) = 0; virtual void set_hi(float hi) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_RAIL_FF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc3_cc.h0000664000175000017500000000542012237515111023321 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC3_CC_H #define INCLUDED_ANALOG_AGC3_CC_H #include #include namespace gr { namespace analog { /*! * \brief high performance Automatic Gain Control class with * attack and decay rates. * \ingroup level_controllers_blk * * \details * Unlike the AGC2 loop, this uses an initial linear calculation * at the beginning for very fast initial acquisition. Moves to * IIR model for tracking purposes. * * For Power the absolute value of the complex number is used. */ class ANALOG_API agc3_cc : virtual public sync_block { public: // gr::analog::agc3_cc::sptr typedef boost::shared_ptr sptr; /*! * Build a complex value AGC loop block with attack and decay rates. * * \param attack_rate the update rate of the loop when in attack mode. * \param decay_rate the update rate of the loop when in decay mode. * \param reference reference value to adjust signal power to. * \param gain initial gain value. * \param iir_update_decim stride by this number of samples before * computing an IIR gain update */ static sptr make(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0, int iir_update_decim=1); virtual float attack_rate() const = 0; virtual float decay_rate() const = 0; virtual float reference() const = 0; virtual float gain() const = 0; virtual float max_gain() const = 0; virtual void set_attack_rate(float rate) = 0; virtual void set_decay_rate(float rate) = 0; virtual void set_reference(float reference) = 0; virtual void set_gain(float gain) = 0; virtual void set_max_gain(float max_gain) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC3_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/noise_source_X.h.t0000664000175000017500000000410012207440367025266 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace analog { /*! * \brief Random number source * \ingroup waveform_generators_blk * * \details * Generate random values from different distributions. * Currently, only Gaussian and uniform are enabled. */ class ANALOG_API @BASE_NAME@ : virtual public sync_block { public: // gr::analog::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! Build a noise source * \param type the random distribution to use (see gnuradio/analog/noise_type.h) * \param ampl a scaling factor for the output * \param seed seed for random generators. Note that for uniform and * Gaussian distributions, this should be a negative number. */ static sptr make(noise_type_t type, float ampl, long seed=0); virtual void set_type(noise_type_t type) = 0; virtual void set_amplitude(float ampl) = 0; virtual noise_type_t type() const = 0; virtual float amplitude() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/pll_refout_cc.h0000664000175000017500000000455712207440367024700 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PLL_REFOUT_CC_H #define INCLUDED_ANALOG_PLL_REFOUT_CC_H #include #include #include namespace gr { namespace analog { /*! * \brief Implements a PLL which locks to the input frequency and outputs a carrier * \ingroup synchronizers_blk * * \details * Input stream 0: complex * Output stream 0: complex * * This PLL locks onto a [possibly noisy] reference carrier on the * input and outputs a clean version which is phase and frequency * aligned to it. * * All settings max_freq and min_freq are in terms of radians per * sample, NOT HERTZ. The loop bandwidth determins the lock range * and should be set around pi/200 -- 2pi/100. \sa * pll_freqdet_cf, pll_carriertracking_cc */ class ANALOG_API pll_refout_cc : virtual public sync_block, virtual public blocks::control_loop { public: // gr::analog::pll_refout_cc::sptr typedef boost::shared_ptr sptr; /* \brief Make PLL block that outputs the tracked carrier signal. * * \param loop_bw: control loop's bandwidth parameter. * \param max_freq: maximum (normalized) frequency PLL will lock to. * \param min_freq: minimum (normalized) frequency PLL will lock to. */ static sptr make(float loop_bw, float max_freq, float min_freq); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PLL_REFOUT_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/pwr_squelch_cc.h0000664000175000017500000000461312207440367025052 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PWR_SQUELCH_CC_H #define INCLUDED_ANALOG_PWR_SQUELCH_CC_H #include #include #include namespace gr { namespace analog { /*! * \brief gate or zero output when input power below threshold * \ingroup level_controllers_blk */ class ANALOG_API pwr_squelch_cc : public squelch_base_cc, virtual public block { protected: virtual void update_state(const gr_complex &in) = 0; virtual bool mute() const = 0; public: // gr::analog::pwr_squelch_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Make power-based squelch block. * * \param db threshold (in dB) for power squelch * \param alpha Gain of averaging filter * \param ramp sets response characteristic. * \param gate if true, no output if no squelch tone. * if false, output 0's if no squelch tone. */ static sptr make(double db, double alpha=0.0001, int ramp=0, bool gate=false); virtual std::vector squelch_range() const = 0; virtual double threshold() const = 0; virtual void set_threshold(double db) = 0; virtual void set_alpha(double alpha) = 0; virtual int ramp() const = 0; virtual void set_ramp(int ramp) = 0; virtual bool gate() const = 0; virtual void set_gate(bool gate) = 0; virtual bool unmuted() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PWR_SQUELCH_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/probe_avg_mag_sqrd_cf.h0000664000175000017500000000433412207440367026342 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_CF_H #define INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_CF_H #include #include namespace gr { namespace analog { /*! * \brief compute avg magnitude squared. * \ingroup measurement_tools_blk * * \details * Input stream 0: complex * Output stream 0: float * * Compute a running average of the magnitude squared of the the * input. The level and indication as to whether the level exceeds * threshold can be retrieved with the level and unmuted * accessors. */ class ANALOG_API probe_avg_mag_sqrd_cf : virtual public sync_block { public: // gr::analog::probe_avg_mag_sqrd_cf::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a block that computes avg magnitude squared. * * \param threshold_db Threshold for muting. * \param alpha Gain parameter for the running average filter. */ static sptr make(double threshold_db, double alpha = 0.0001); virtual bool unmuted() const = 0; virtual double level() const = 0; virtual double threshold() const = 0; virtual void set_alpha(double alpha) = 0; virtual void set_threshold(double decibels) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_CF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc2_ff.h0000664000175000017500000000467512207440367023350 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC2_FF_H #define INCLUDED_ANALOG_AGC2_FF_H #include #include #include namespace gr { namespace analog { /*! * \brief high performance Automatic Gain Control class with * attack and decay rates. * \ingroup level_controllers_blk * * \details * Power is approximated by absolute value */ class ANALOG_API agc2_ff : virtual public sync_block { public: // gr::analog::agc2_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a floating point AGC loop block with attack and decay rates. * * \param attack_rate the update rate of the loop when in attack mode. * \param decay_rate the update rate of the loop when in decay mode. * \param reference reference value to adjust signal power to. * \param gain initial gain value. */ static sptr make(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0); virtual float attack_rate() const = 0; virtual float decay_rate() const = 0; virtual float reference() const = 0; virtual float gain() const = 0; virtual float max_gain() const = 0; virtual void set_attack_rate(float rate) = 0; virtual void set_decay_rate(float rate) = 0; virtual void set_reference(float reference) = 0; virtual void set_gain(float gain) = 0; virtual void set_max_gain(float max_gain) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC2_FF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/agc_ff.h0000664000175000017500000000421112207440367023250 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC_FF_H #define INCLUDED_ANALOG_AGC_FF_H #include #include #include namespace gr { namespace analog { /*! * \brief high performance Automatic Gain Control class * \ingroup level_controllers_blk * * \details * Power is approximated by absolute value */ class ANALOG_API agc_ff : virtual public sync_block { public: // gr::analog::agc_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a floating point AGC loop block. * * \param rate the update rate of the loop. * \param reference reference value to adjust signal power to. * \param gain initial gain value. */ static sptr make(float rate = 1e-4, float reference = 1.0, float gain = 1.0); virtual float rate() const = 0; virtual float reference() const = 0; virtual float gain() const = 0; virtual float max_gain() const = 0; virtual void set_rate(float rate) = 0; virtual void set_reference(float reference) = 0; virtual void set_gain(float gain) = 0; virtual void set_max_gain(float max_gain) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC_FF_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/squelch_base_cc.h0000664000175000017500000000326112207440367025152 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_SQUELCH_BASE_CC_H #define INCLUDED_ANALOG_SQUELCH_BASE_CC_H #include #include namespace gr { namespace analog { /*! * \brief basic squelch block; to be subclassed for other squelches. * \ingroup level_blk */ class ANALOG_API squelch_base_cc : virtual public block { protected: virtual void update_state(const gr_complex &sample) = 0; virtual bool mute() const = 0; public: squelch_base_cc() {}; virtual int ramp() const = 0; virtual void set_ramp(int ramp) = 0; virtual bool gate() const = 0; virtual void set_gate(bool gate) = 0; virtual bool unmuted() const = 0; virtual std::vector squelch_range() const = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SQUELCH_BASE_CC_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/api.h0000664000175000017500000000203712207440367022620 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_API_H #define INCLUDED_ANALOG_API_H #include #ifdef gnuradio_analog_EXPORTS # define ANALOG_API __GR_ATTR_EXPORT #else # define ANALOG_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_ANALOG_API_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/noise_type.h0000664000175000017500000000216012207440367024222 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_NOISE_TYPE_H #define INCLUDED_ANALOG_NOISE_TYPE_H namespace gr { namespace analog { typedef enum { GR_UNIFORM = 200, GR_GAUSSIAN, GR_LAPLACIAN, GR_IMPULSE } noise_type_t; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_NOISE_TYPE_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/sig_source_waveform.h0000664000175000017500000000245612207440367026124 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_SIG_SOURCE_WAVEFORM_H #define INCLUDED_ANALOG_SIG_SOURCE_WAVEFORM_H namespace gr { namespace analog { /*! * \brief Types of signal generator waveforms. * \ingroup waveform_generators_blk */ typedef enum { GR_CONST_WAVE = 100, GR_SIN_WAVE, GR_COS_WAVE, GR_SQR_WAVE, GR_TRI_WAVE, GR_SAW_WAVE } gr_waveform_t; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SIG_SOURCE_WAVEFORM_H */ gnuradio-3.7.2.1/gr-analog/include/gnuradio/analog/phase_modulator_fc.h0000664000175000017500000000361312207440367025706 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PHASE_MODULATOR_FC_H #define INCLUDED_ANALOG_PHASE_MODULATOR_FC_H #include #include namespace gr { namespace analog { /*! * \brief Phase modulator block * \ingroup modulators_blk * * \details * output = complex(cos(in*sensitivity), sin(in*sensitivity)) * * Input stream 0: floats * Ouput stream 0: complex */ class ANALOG_API phase_modulator_fc : virtual public sync_block { public: // gr::analog::phase_modulator_fc::sptr typedef boost::shared_ptr sptr; /* \brief Make a phase modulator block. * * \param sensitivity Phase change sensitivity of input amplitude. */ static sptr make(double sensitivity); virtual double sensitivity() const = 0; virtual double phase() const = 0; virtual void set_sensitivity(double s) = 0; virtual void set_phase(double p) = 0; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PHASE_MODULATOR_FC_H */ gnuradio-3.7.2.1/gr-analog/grc/0000775000175000017500000000000012237515111015744 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/grc/analog_dpll_bb.xml0000664000175000017500000000115612207440367021417 0ustar jcorganjcorgan Detect Peak analog_dpll_bb from gnuradio import analog analog.dpll_bb($period, $gain) set_gain($gain) Period period real Gain gain real in byte out byte gnuradio-3.7.2.1/gr-analog/grc/CMakeLists.txt0000664000175000017500000000157412207440367020522 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "analog_python") gnuradio-3.7.2.1/gr-analog/grc/analog_pll_freqdet_cf.xml0000664000175000017500000000152412207440367022771 0ustar jcorganjcorgan PLL Freq Det analog_pll_freqdet_cf from gnuradio import analog analog.pll_freqdet_cf($w, $max_freq, $min_freq) set_loop_bandwidth($w) set_max_freq($max_freq) set_min_freq($min_freq) Loop Bandwidth w real Max Freq max_freq real Min Freq min_freq real in complex out float gnuradio-3.7.2.1/gr-analog/grc/analog_agc_xx.xml0000664000175000017500000000242412207440367021271 0ustar jcorganjcorgan AGC analog_agc_xx from gnuradio import analog analog.agc_$(type.fcn)($rate, $reference, $gain) self.$(id).set_max_gain($max_gain) set_rate($rate) set_reference($reference) set_gain($gain) set_max_gain($max_gain) Type type enum Rate rate 1e-4 real Reference reference 1.0 real Gain gain 1.0 real Max Gain max_gain 65536 real in $type out $type gnuradio-3.7.2.1/gr-analog/grc/analog_noise_source_x.xml0000664000175000017500000000302712207440367023044 0ustar jcorganjcorgan Noise Source analog_noise_source_x from gnuradio import analog analog.noise_source_$(type.fcn)($noise_type, $amp, $seed) set_type($noise_type) set_amplitude($amp) Output Type type enum Noise Type noise_type analog.GR_GAUSSIAN int Amplitude amp 1 real Seed seed 0 int out $type gnuradio-3.7.2.1/gr-analog/grc/analog_quadrature_demod_cf.xml0000664000175000017500000000135612207440367024020 0ustar jcorganjcorgan Quadrature Demod analog_quadrature_demod_cf from gnuradio import analog import math analog.quadrature_demod_cf($gain) set_gain($gain) Gain gain samp_rate/(2*math.pi*fsk_deviation_hz/8.0) real in complex out float gnuradio-3.7.2.1/gr-analog/grc/analog_wfm_tx.xml0000664000175000017500000000164212207440367021325 0ustar jcorganjcorgan WBFM Transmit analog_wfm_tx from gnuradio import analog analog.wfm_tx( audio_rate=$audio_rate, quad_rate=$quad_rate, tau=$tau, max_dev=$max_dev, ) Audio Rate audio_rate int Quadrature Rate quad_rate int Tau tau 75e-6 real Max Deviation max_dev 75e3 real $quad_rate%$audio_rate == 0 in float out complex gnuradio-3.7.2.1/gr-analog/grc/analog_frequency_modulator_fc.xml0000664000175000017500000000114312207440367024554 0ustar jcorganjcorgan Frequency Mod analog_frequency_modulator_fc from gnuradio import analog analog.frequency_modulator_fc($sensitivity) set_sensitivity($sensitivity) Sensitivity sensitivity real in float out complex gnuradio-3.7.2.1/gr-analog/grc/analog_fastnoise_source_x.xml0000664000175000017500000000361612207440367023726 0ustar jcorganjcorgan Fast Noise Source analog_fastnoise_source_x from gnuradio import analog analog.fastnoise_source_$(type.fcn)($noise_type, $amp, $seed, $samples) set_type($noise_type) set_amplitude($amp) Output Type type enum Noise Type noise_type analog.GR_GAUSSIAN int Amplitude amp 1 real Seed seed 0 int Variate Pool Size samples 8192 int out $type The fast noise source works by pre-generating a pool of random variates taken from the specified distribution. At runtime, samples are then uniform randomly chosen from this pool which is a very fast operation. gnuradio-3.7.2.1/gr-analog/grc/analog_fm_demod_cf.xml0000664000175000017500000000240412207440367022240 0ustar jcorganjcorgan FM Demod analog_fm_demod_cf from gnuradio import analog analog.fm_demod_cf( channel_rate=$chan_rate, audio_decim=$audio_decim, deviation=$deviation, audio_pass=$audio_pass, audio_stop=$audio_stop, gain=$gain, tau=$tau, ) Channel Rate chan_rate real Audio Decimation audio_decim int Deviation deviation 75000 real Audio Pass audio_pass 15000 real Audio Stop audio_stop 16000 real Gain gain 1.0 real Tau tau 75e-6 real in complex out float gnuradio-3.7.2.1/gr-analog/grc/analog_wfm_rcv.xml0000664000175000017500000000124012207440367021456 0ustar jcorganjcorgan WBFM Receive analog_wfm_rcv from gnuradio import analog analog.wfm_rcv( quad_rate=$quad_rate, audio_decimation=$audio_decimation, ) Quadrature Rate quad_rate real Audio Decimation audio_decimation int in complex out float gnuradio-3.7.2.1/gr-analog/grc/analog_nbfm_rx.xml0000664000175000017500000000164112207440367021453 0ustar jcorganjcorgan NBFM Receive analog_nbfm_rx from gnuradio import analog analog.nbfm_rx( audio_rate=$audio_rate, quad_rate=$quad_rate, tau=$tau, max_dev=$max_dev, ) Audio Rate audio_rate int Quadrature Rate quad_rate int Tau tau 75e-6 real Max Deviation max_dev 5e3 real $quad_rate%$audio_rate == 0 in complex out float gnuradio-3.7.2.1/gr-analog/grc/analog_block_tree.xml0000664000175000017500000000501312207440367022126 0ustar jcorganjcorgan Level Controllers analog_agc_xx analog_agc2_xx analog_agc3_xx analog_feedforward_agc_cc analog_ctcss_squelch_ff analog_pwr_squelch_xx analog_simple_squelch_cc analog_standard_squelch analog_rail_ff Modulators analog_cpfsk_bc analog_frequency_modulator_fc analog_phase_modulator_fc analog_quadrature_demod_cf analog_nbfm_tx analog_nbfm_rx analog_wfm_tx analog_wfm_rcv analog_wfm_rcv_pll analog_am_demod_cf analog_fm_demod_cf analog_fm_deemph analog_fm_preemph Waveform Generators analog_sig_source_x analog_const_source_x analog_noise_source_x analog_fastnoise_source_x analog_random_source_x Synchronizers analog_pll_carriertracking_cc analog_pll_freqdet_cf analog_pll_refout_cc Peak Detectors analog_dpll_bb Measurement Tools analog_probe_avg_mag_sqrd_x gnuradio-3.7.2.1/gr-analog/grc/analog_pwr_squelch_xx.xml0000664000175000017500000000235612207440367023077 0ustar jcorganjcorgan Power Squelch analog_pwr_squelch_xx from gnuradio import analog analog.pwr_squelch_$(type.fcn)($threshold, $alpha, $ramp, $gate) set_threshold($threshold) set_alpha($alpha) Type type enum Threshold (dB) threshold real Alpha alpha real Ramp ramp int Gate gate enum in $type out $type gnuradio-3.7.2.1/gr-analog/grc/analog_const_source_x.xml0000664000175000017500000000216412207440367023056 0ustar jcorganjcorgan Constant Source analog_const_source_x from gnuradio import analog analog.sig_source_$(type.fcn)(0, analog.GR_CONST_WAVE, 0, 0, $const) set_offset($const) Output Type type enum Constant const 0 $type.const_type out $type gnuradio-3.7.2.1/gr-analog/grc/analog_fm_preemph.xml0000664000175000017500000000117412207440367022143 0ustar jcorganjcorgan FM Preemphasis analog_fm_preemph from gnuradio import analog analog.fm_preemph(fs=$samp_rate, tau=$tau) Sample Rate samp_rate real Tau tau 75e-6 real in float out float gnuradio-3.7.2.1/gr-analog/grc/analog_simple_squelch_cc.xml0000664000175000017500000000132112207440367023475 0ustar jcorganjcorgan Simple Squelch analog_simple_squelch_cc from gnuradio import analog analog.simple_squelch_cc($threshold, $alpha) set_threshold($threshold) set_alpha($alpha) Threshold (dB) threshold real Alpha alpha real in complex out complex gnuradio-3.7.2.1/gr-analog/grc/analog_feedforward_agc_cc.xml0000664000175000017500000000126612207440367023572 0ustar jcorganjcorgan Feed Forward AGC analog_feedforward_agc_cc from gnuradio import analog analog.feedforward_agc_cc($num_samples, $reference) Num Samples num_samples 1024 int Reference reference 1.0 real in complex out complex gnuradio-3.7.2.1/gr-analog/grc/analog_agc3_xx.xml0000664000175000017500000000320212237515111021340 0ustar jcorganjcorgan AGC3 analog_agc3_xx from gnuradio import analog analog.agc3_$(type.fcn)($attack_rate, $decay_rate, $reference, $gain, $iir_update_decim) self.$(id).set_max_gain($max_gain) set_attack_rate($attack_rate) set_decay_rate($decay_rate) set_reference($reference) set_gain($gain) set_max_gain($max_gain) Type type enum Attack Rate attack_rate 1e-3 real Decay Rate decay_rate 1e-4 real Reference reference 1.0 real Gain gain 1.0 real Max Gain max_gain 65536 real IIR Update Decimation iir_update_decim 1 real in $type out $type gnuradio-3.7.2.1/gr-analog/grc/analog_am_demod_cf.xml0000664000175000017500000000164112207440367022235 0ustar jcorganjcorgan AM Demod analog_am_demod_cf from gnuradio import analog analog.am_demod_cf( channel_rate=$chan_rate, audio_decim=$audio_decim, audio_pass=$audio_pass, audio_stop=$audio_stop, ) Channel Rate chan_rate real Audio Decimation audio_decim int Audio Pass audio_pass 5000 real Audio Stop audio_stop 5500 real in complex out float gnuradio-3.7.2.1/gr-analog/grc/analog_sig_source_x.xml0000664000175000017500000000427112207440367022513 0ustar jcorganjcorgan Signal Source analog_sig_source_x from gnuradio import analog analog.sig_source_$(type.fcn)($samp_rate, $waveform, $freq, $amp, $offset) set_sampling_freq($samp_rate) set_waveform($waveform) set_frequency($freq) set_amplitude($amp) set_offset($offset) Output Type type enum Sample Rate samp_rate samp_rate real Waveform waveform analog.GR_COS_WAVE int Frequency freq 1000 real Amplitude amp 1 real Offset offset 0 $type.offset_type out $type gnuradio-3.7.2.1/gr-analog/grc/analog_wfm_rcv_pll.xml0000664000175000017500000000136012207440367022330 0ustar jcorganjcorgan WBFM Receive PLL analog_wfm_rcv_pll from gnuradio import analog analog.wfm_rcv_pll( demod_rate=$quad_rate, audio_decimation=$audio_decimation, ) Quadrature Rate quad_rate real Audio Decimation audio_decimation int in complex Lout float Rout float gnuradio-3.7.2.1/gr-analog/grc/analog_standard_squelch.xml0000664000175000017500000000132512207440367023343 0ustar jcorganjcorgan Standard Squelch analog_standard_squelch from gnuradio import analog analog.standard_squelch(audio_rate=$audio_rate) self.$(id).set_threshold($threshold) set_threshold($threshold) Audio Rate audio_rate real Threshold threshold real in float out float gnuradio-3.7.2.1/gr-analog/grc/analog_random_source_x.xml0000664000175000017500000000277412207440367023217 0ustar jcorganjcorgan Random Source analog_random_source_x from gnuradio import blocks import numpy blocks.vector_source_$(type.fcn)(map(int, numpy.random.randint($min, $max, $num_samps)), $repeat) Output Type type enum Minimum min 0 int Maximum max 2 int Num Samples num_samps 1000 int Repeat repeat True enum out $type Generate num samples of random numbers of [min, max). Repeat samples if specified. Ex: With min=0 and max=2, the sequence 01110101... will be generated. gnuradio-3.7.2.1/gr-analog/grc/analog_agc2_xx.xml0000664000175000017500000000275112207440367021356 0ustar jcorganjcorgan AGC2 analog_agc2_xx from gnuradio import analog analog.agc2_$(type.fcn)($attack_rate, $decay_rate, $reference, $gain) self.$(id).set_max_gain($max_gain) set_attack_rate($attack_rate) set_decay_rate($decay_rate) set_reference($reference) set_gain($gain) set_max_gain($max_gain) Type type enum Attack Rate attack_rate 1e-1 real Decay Rate decay_rate 1e-2 real Reference reference 1.0 real Gain gain 1.0 real Max Gain max_gain 65536 real in $type out $type gnuradio-3.7.2.1/gr-analog/grc/analog_rail_ff.xml0000664000175000017500000000262712207440367021427 0ustar jcorganjcorgan Rail analog_rail_ff from gnuradio import analog analog.rail_ff($lo, $hi) set_lo($lo) set_hi($hi) Low clipping lo real Hi clipping hi real in float out float gnuradio-3.7.2.1/gr-analog/grc/analog_nbfm_tx.xml0000664000175000017500000000164312207440367021457 0ustar jcorganjcorgan NBFM Transmit analog_nbfm_tx from gnuradio import analog analog.nbfm_tx( audio_rate=$audio_rate, quad_rate=$quad_rate, tau=$tau, max_dev=$max_dev, ) Audio Rate audio_rate int Quadrature Rate quad_rate int Tau tau 75e-6 real Max Deviation max_dev 5e3 real $quad_rate%$audio_rate == 0 in float out complex gnuradio-3.7.2.1/gr-analog/grc/analog_fm_deemph.xml0000664000175000017500000000117012207440367021741 0ustar jcorganjcorgan FM Deemphasis analog_fm_deemph from gnuradio import analog analog.fm_deemph(fs=$samp_rate, tau=$tau) Sample Rate samp_rate real Tau tau 75e-6 real in float out float gnuradio-3.7.2.1/gr-analog/grc/analog_pll_carriertracking_cc.xml0000664000175000017500000000156112207440367024507 0ustar jcorganjcorgan PLL Carrier Tracking analog_pll_carriertracking_cc from gnuradio import analog analog.pll_carriertracking_cc($w, $max_freq, $min_freq) set_loop_bandwidth($w) set_max_freq($max_freq) set_min_freq($min_freq) Loop Bandwidth w real Max Freq max_freq real Min Freq min_freq real in complex out complex gnuradio-3.7.2.1/gr-analog/grc/analog_ctcss_squelch_ff.xml0000664000175000017500000000360612207440367023341 0ustar jcorganjcorgan CTCSS Squelch analog_ctcss_squelch_ff from gnuradio import analog analog.ctcss_squelch_ff($rate, $freq, $level, $len, $ramp, $gate) set_level($level) Sampling Rate (Hz) rate samp_rate real Tone Frequency freq 100.0 real Level level 0.01 real Length len 0 int Ramp ramp 0 int Gate gate False bool in float out float gnuradio-3.7.2.1/gr-analog/grc/analog_cpfsk_bc.xml0000664000175000017500000000137512207440367021576 0ustar jcorganjcorgan CPFSK analog_cpfsk_bc from gnuradio import analog analog.cpfsk_bc($k, $amplitude, $samples_per_symbol) set_amplitude($amplitude) K k real Amplitude amplitude real Samples/Symbol samples_per_symbol 2 int in byte out complex gnuradio-3.7.2.1/gr-analog/grc/analog_probe_avg_mag_sqrd_x.xml0000664000175000017500000000206212207440367024166 0ustar jcorganjcorgan Probe Avg Mag^2 analog_probe_avg_mag_sqrd_x from gnuradio import analog analog.probe_avg_mag_sqrd_$(type)($threshold, $alpha) set_alpha($alpha) set_threshold($threshold) Type type enum Threshold (dB) threshold 0 real Alpha alpha 1 real in $type.input Available functions to probe: level() Use with the function probe block. gnuradio-3.7.2.1/gr-analog/grc/analog_pll_refout_cc.xml0000664000175000017500000000152312207440367022637 0ustar jcorganjcorgan PLL Ref Out analog_pll_refout_cc from gnuradio import analog analog.pll_refout_cc($w, $max_freq, $min_freq) set_loop_bandwidth($w) set_max_freq($max_freq) set_min_freq($min_freq) Loop Bandwidth w real Max Freq max_freq real Min Freq min_freq real in complex out complex gnuradio-3.7.2.1/gr-analog/grc/analog_phase_modulator_fc.xml0000664000175000017500000000112312207440367023651 0ustar jcorganjcorgan Phase Mod analog_phase_modulator_fc from gnuradio import analog analog.phase_modulator_fc($sensitivity) set_sensitivity($sensitivity) Sensitivity sensitivity real in float out complex gnuradio-3.7.2.1/gr-analog/gnuradio-analog.pc.in0000664000175000017500000000041212207440367021175 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-analog Description: GNU Radio blocks for analog communications Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-analog Cflags: -I${includedir} gnuradio-3.7.2.1/gr-analog/doc/0000775000175000017500000000000012207440367015745 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/doc/CMakeLists.txt0000664000175000017500000000152412207440367020507 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.analog DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-analog/doc/README.analog0000664000175000017500000000066112207440367020070 0ustar jcorganjcorganThis is the gr-analog package. It contains all of the analog modulation blocks, utilities, and examples. To use the analog blocks, the Python namespaces is in gnuradio.analog, which would be normally imported as: from gnuradio import analog See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(analog) gnuradio-3.7.2.1/gr-analog/doc/analog.dox0000664000175000017500000000102112207440367017714 0ustar jcorganjcorgan/*! \page page_analog Analog Modulation \section Introduction This is the gr-analog package. It contains all of the analog modulation blocks, utilities, and examples. To use the analog blocks, the Python namespaces is in gnuradio.analog, which would be normally imported as: \code from gnuradio import analog \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(analog) \endcode */ gnuradio-3.7.2.1/gr-analog/python/0000775000175000017500000000000012207440367016521 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/python/analog/0000775000175000017500000000000012207440367017762 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/python/analog/CMakeLists.txt0000664000175000017500000000357512207440367022534 0ustar jcorganjcorgan# Copyright 212 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py am_demod.py fm_demod.py fm_emph.py nbfm_rx.py nbfm_tx.py standard_squelch.py wfm_rcv.py wfm_rcv_fmdet.py wfm_rcv_pll.py wfm_tx.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/analog COMPONENT "analog_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-analog/python/analog/qa_pll_refout.py0000775000175000017500000001721012207440367023174 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks class test_pll_refout(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_pll_refout(self): expected_result = ((1+0j), (1+6.4087357643e-10j), (0.999985277653+0.00542619498447j), (0.999868750572+0.0162021834403j), (0.99948567152+0.0320679470897j), (0.99860727787+0.0527590736747j), (0.996953129768+0.0780025869608j), (0.994203746319+0.107512556016j), (0.990011692047+0.140985429287j), (0.984013140202+0.178095817566j), (0.975838363171+0.218493551016j), (0.965121984482+0.261800557375j), (0.95151245594+0.307610183954j), (0.934681296349+0.355486690998j), (0.914401650429+0.404808044434j), (0.890356600285+0.455263823271j), (0.862329125404+0.506348133087j), (0.830152392387+0.557536482811j), (0.793714106083+0.608290970325j), (0.752960026264+0.658066213131j), (0.707896590233+0.706316053867j), (0.658591926098+0.752500295639j), (0.605175673962+0.796091973782j), (0.547837555408+0.836584687233j), (0.48682525754+0.873499393463j), (0.42244040966+0.906390726566j), (0.355197101831+0.934791445732j), (0.285494059324+0.958380460739j), (0.213591173291+0.976923108101j), (0.139945343137+0.990159213543j), (0.065038472414+0.997882783413j), (-0.0106285437942+0.999943494797j), (-0.0865436866879+0.996248066425j), (-0.162189796567+0.986759603024j), (-0.23705175519+0.971496999264j), (-0.310622543097+0.950533330441j), (-0.38240903616+0.923993110657j), (-0.451937526464+0.89204955101j), (-0.518758952618+0.854920566082j), (-0.582311093807+0.812966048717j), (-0.642372369766+0.76639264822j), (-0.698591887951+0.715520322323j), (-0.750654160976+0.660695314407j), (-0.798280358315+0.602286040783j), (-0.841228663921+0.540679454803j), (-0.87929558754+0.476276367903j), (-0.912315964699+0.409486919641j), (-0.940161883831+0.340728074312j), (-0.962742805481+0.270418733358j), (-0.980004072189+0.198977485299j), (-0.991925954819+0.126818284392j), (-0.99851256609+0.0545223206282j), (-0.999846458435-0.0175215266645j), (-0.996021270752-0.0891158208251j), (-0.987133920193-0.159895718098j), (-0.973306238651-0.2295101583j), (-0.954683184624-0.297624111176j), (-0.931430280209-0.363919824362j), (-0.903732538223-0.428097635508j), (-0.871792256832-0.489875763655j), (-0.835827112198-0.548992812634j), (-0.796068251133-0.605206847191j), (-0.752758979797-0.658296227455j), (-0.706152498722-0.70805978775j), (-0.656641483307-0.754202902317j), (-0.604367733002-0.79670548439j), (-0.549597978592-0.835429251194j), (-0.492602348328-0.870254516602j), (-0.433654457331-0.901079237461j), (-0.373029649258-0.927819430828j), (-0.31100410223-0.950408577919j), (-0.247853919864-0.968797445297j), (-0.183855071664-0.982953369617j), (-0.119282215834-0.992860376835j), (-0.0544078871608-0.998518764973j), (0.0104992967099-0.999944865704j), (0.0749994292855-0.997183561325j), (0.138844624162-0.990314185619j), (0.201967850327-0.979392170906j), (0.264124274254-0.964488625526j), (0.325075358152-0.945688128471j), (0.3845885396-0.92308807373j), (0.442438393831-0.89679890871j), (0.498407125473-0.866943061352j), (0.552284479141-0.833655714989j), (0.603869199753-0.797083437443j), (0.652970373631-0.757383465767j), (0.69940674305-0.714723825455j), (0.743007957935-0.66928255558j), (0.78350687027-0.62138313055j), (0.820889055729-0.571087777615j), (0.855021059513-0.51859331131j), (0.885780930519-0.46410369873j), (0.913058102131-0.407829582691j), (0.936754107475-0.349988251925j), (0.956783294678-0.290801793337j), (0.973072886467-0.230497643352j), (0.985563337803-0.169307261705j), (0.9942086339-0.1074674353j), (0.9989772439-0.0452152714133j)) sampling_freq = 10e3 freq = sampling_freq / 100 loop_bw = math.pi/100.0 maxf = 1 minf = -1 src = analog.sig_source_c(sampling_freq, analog.GR_COS_WAVE, freq, 1.0) pll = analog.pll_refout_cc(loop_bw, maxf, minf) head = blocks.head(gr.sizeof_gr_complex, int (freq)) dst = blocks.vector_sink_c() self.tb.connect(src, pll, head) self.tb.connect(head, dst) self.tb.run() dst_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 4) if __name__ == '__main__': gr_unittest.run(test_pll_refout, "test_pll_refout.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_noise.py0000775000175000017500000000305712207440367022142 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog class test_noise_source(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): # Just confirm that we can instantiate a noise source op = analog.noise_source_f(analog.GR_GAUSSIAN, 10, 10) def test_002(self): # Test get methods set_type = analog.GR_GAUSSIAN set_ampl = 10 op = analog.noise_source_f(set_type, set_ampl, 10) get_type = op.type() get_ampl = op.amplitude() self.assertEqual(get_type, set_type) self.assertEqual(get_ampl, set_ampl) if __name__ == '__main__': gr_unittest.run(test_noise_source, "test_noise_source.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_fmdet.py0000775000175000017500000000446012207440367022123 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks class test_fmdet_cf(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_fmdet_cf_001(self): # Test set/gets fh1 = 10 fh2 = 20 fl1 = 1 fl2 = 2 scale1 = 3 scale2 = 4 op = analog.fmdet_cf(1, fl1, fh1, scale1) op.set_freq_range(fl2, fh2) lo = op.freq_low() hi = op.freq_high() f = op.freq() self.assertEqual(fl2, lo) self.assertEqual(fh2, hi) self.assertEqual(0, f) op.set_scale(scale2) s = op.scale() b = op.bias() eb = 0.5*scale2*(hi + lo) / (hi - lo); self.assertEqual(scale2, s) self.assertAlmostEqual(eb, b) # FIXME: This passes QA, but the it's only based off what the # block is saying, not what the values should actually be. def est_fmdet_cf_002(self): N = 100 src = analog.sig_source_c(1, analog.GR_SIN_WAVE, 0.2, 1) head = blocks.head(gr.sizeof_gr_complex, N) op = analog.fmdet_cf(1, 0.1, 0.3, 0.1) dst = blocks.vector_sink_f() self.tb.connect(src, head, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data()[4:N] expected_result = (100-4)*[-0.21755,] self.assertFloatTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_fmdet_cf, "test_fmdet_cf.xml") gnuradio-3.7.2.1/gr-analog/python/analog/fm_emph.py0000664000175000017500000000777612207440367021770 0ustar jcorganjcorgan# # Copyright 2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter import math # # 1 # H(s) = ------- # 1 + s # # tau is the RC time constant. # critical frequency: w_p = 1/tau # # We prewarp and use the bilinear z-transform to get our IIR coefficients. # See "Digital Signal Processing: A Practical Approach" by Ifeachor and Jervis # class fm_deemph(gr.hier_block2): """ FM Deemphasis IIR filter. """ def __init__(self, fs, tau=75e-6): """ Args: fs: sampling frequency in Hz (float) tau: Time constant in seconds (75us in US, 50us in EUR) (float) """ gr.hier_block2.__init__(self, "fm_deemph", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature w_p = 1/tau w_pp = math.tan(w_p / (fs * 2)) # prewarped analog freq a1 = (w_pp - 1)/(w_pp + 1) b0 = w_pp/(1 + w_pp) b1 = b0 btaps = [b0, b1] ataps = [1, a1] if 0: print "btaps =", btaps print "ataps =", ataps global plot1 plot1 = gru.gnuplot_freqz(gru.freqz(btaps, ataps), fs, True) deemph = filter.iir_filter_ffd(btaps, ataps) self.connect(self, deemph, self) # # 1 + s*t1 # H(s) = ---------- # 1 + s*t2 # # I think this is the right transfer function. # # # This fine ASCII rendition is based on Figure 5-15 # in "Digital and Analog Communication Systems", Leon W. Couch II # # # R1 # +-----||------+ # | | # o------+ +-----+--------o # | C1 | | # +----/\/\/\/--+ \ # / # \ R2 # / # \ # | # o--------------------------+--------o # # f1 = 1/(2*pi*t1) = 1/(2*pi*R1*C) # # 1 R1 + R2 # f2 = ------- = ------------ # 2*pi*t2 2*pi*R1*R2*C # # t1 is 75us in US, 50us in EUR # f2 should be higher than our audio bandwidth. # # # The Bode plot looks like this: # # # /---------------- # / # / <-- slope = 20dB/decade # / # -------------/ # f1 f2 # # We prewarp and use the bilinear z-transform to get our IIR coefficients. # See "Digital Signal Processing: A Practical Approach" by Ifeachor and Jervis # class fm_preemph(gr.hier_block2): """ FM Preemphasis IIR filter. """ def __init__(self, fs, tau=75e-6): """ Args: fs: sampling frequency in Hz (float) tau: Time constant in seconds (75us in US, 50us in EUR) (float) """ gr.hier_block2.__init__(self, "fm_deemph", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature # FIXME make this compute the right answer btaps = [1] ataps = [1] if 0: print "btaps =", btaps print "ataps =", ataps global plot2 plot2 = gru.gnuplot_freqz(gru.freqz(btaps, ataps), fs, True) preemph = filter.iir_filter_ffd(btaps, ataps) self.connect(self, preemph, self) gnuradio-3.7.2.1/gr-analog/python/analog/qa_simple_squelch.py0000775000175000017500000000363112207440367024040 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks class test_simple_squelch(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_simple_squelch_001(self): # Test set/gets alpha = 0.0001 thr1 = 10 thr2 = 20 op = analog.simple_squelch_cc(thr1, alpha) op.set_threshold(thr2) t = op.threshold() self.assertEqual(thr2, t) def test_simple_squelch_002(self): alpha = 0.0001 thr = -25 src_data = map(lambda x: float(x)/10.0, range(1, 40)) src = blocks.vector_source_c(src_data) op = analog.simple_squelch_cc(thr, alpha) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() expected_result = src_data expected_result[0:20] = 20*[0,] result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_simple_squelch, "test_simple_squelch.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_fastnoise.py0000664000175000017500000000310312207440367023005 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog class test_fastnoise_source(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): # Just confirm that we can instantiate a noise source op = analog.fastnoise_source_f(analog.GR_GAUSSIAN, 10, 10) def test_002(self): # Test get methods set_type = analog.GR_GAUSSIAN set_ampl = 10 op = analog.fastnoise_source_f(set_type, set_ampl, 10) get_type = op.type() get_ampl = op.amplitude() self.assertEqual(get_type, set_type) self.assertEqual(get_ampl, set_ampl) if __name__ == '__main__': gr_unittest.run(test_fastnoise_source, "test_fastnoise_source.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_sig_source.py0000775000175000017500000001314412207440367023165 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks class test_sig_source(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_const_f(self): tb = self.tb expected_result = (1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5) src1 = analog.sig_source_f(1e6, analog.GR_CONST_WAVE, 0, 1.5) op = blocks.head(gr.sizeof_float, 10) dst1 = blocks.vector_sink_f() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_const_i(self): tb = self.tb expected_result = (1, 1, 1, 1) src1 = analog.sig_source_i(1e6, analog.GR_CONST_WAVE, 0, 1) op = blocks.head(gr.sizeof_int, 4) dst1 = blocks.vector_sink_i() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_sine_f(self): tb = self.tb sqrt2 = math.sqrt(2) / 2 expected_result = (0, sqrt2, 1, sqrt2, 0, -sqrt2, -1, -sqrt2, 0) src1 = analog.sig_source_f(8, analog.GR_SIN_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_float, 9) dst1 = blocks.vector_sink_f() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) def test_cosine_f(self): tb = self.tb sqrt2 = math.sqrt(2) / 2 expected_result = (1, sqrt2, 0, -sqrt2, -1, -sqrt2, 0, sqrt2, 1) src1 = analog.sig_source_f(8, analog.GR_COS_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_float, 9) dst1 = blocks.vector_sink_f() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) def test_sqr_c(self): tb = self.tb #arg6 is a bit before -PI/2 expected_result = (1j, 1j, 0, 0, 1, 1, 1+0j, 1+1j, 1j) src1 = analog.sig_source_c(8, analog.GR_SQR_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_gr_complex, 9) dst1 = blocks.vector_sink_c() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_tri_c(self): tb = self.tb expected_result = (1+.5j, .75+.75j, .5+1j, .25+.75j, 0+.5j, .25+.25j, .5+0j, .75+.25j, 1+.5j) src1 = analog.sig_source_c(8, analog.GR_TRI_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_gr_complex, 9) dst1 = blocks.vector_sink_c() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) def test_saw_c(self): tb = self.tb expected_result = (.5+.25j, .625+.375j, .75+.5j, .875+.625j, 0+.75j, .125+.875j, .25+1j, .375+.125j, .5+.25j) src1 = analog.sig_source_c(8, analog.GR_SAW_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_gr_complex, 9) dst1 = blocks.vector_sink_c() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) def test_sqr_f(self): tb = self.tb expected_result = (0, 0, 0, 0, 1, 1, 1, 1, 0) src1 = analog.sig_source_f(8, analog.GR_SQR_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_float, 9) dst1 = blocks.vector_sink_f() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_tri_f(self): tb = self.tb expected_result = (1, .75, .5, .25, 0, .25, .5, .75, 1) src1 = analog.sig_source_f(8, analog.GR_TRI_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_float, 9) dst1 = blocks.vector_sink_f() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) def test_saw_f(self): tb = self.tb expected_result = (.5, .625, .75, .875, 0, .125, .25, .375, .5) src1 = analog.sig_source_f(8, analog.GR_SAW_WAVE, 1.0, 1.0) op = blocks.head(gr.sizeof_float, 9) dst1 = blocks.vector_sink_f() tb.connect(src1, op) tb.connect(op, dst1) tb.run() dst_data = dst1.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) if __name__ == '__main__': gr_unittest.run(test_sig_source, "test_sig_source.xml") gnuradio-3.7.2.1/gr-analog/python/analog/wfm_rcv_fmdet.py0000664000175000017500000002407512207440367023166 0ustar jcorganjcorgan# # Copyright 2005,2006,2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter from fm_emph import fm_deemph import math try: from gnuradio import analog except ImportError: import analog_swig as analog class wfm_rcv_fmdet(gr.hier_block2): def __init__ (self, demod_rate, audio_decimation): """ Hierarchical block for demodulating a broadcast FM signal. The input is the downconverted complex baseband signal (gr_complex). The output is two streams of the demodulated audio (float) 0=Left, 1=Right. Args: demod_rate: input sample rate of complex baseband input. (float) audio_decimation: how much to decimate demod_rate to get to audio. (integer) """ gr.hier_block2.__init__(self, "wfm_rcv_fmdet", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(2, 2, gr.sizeof_float)) # Output signature lowfreq = -125e3/demod_rate highfreq = 125e3/demod_rate audio_rate = demod_rate / audio_decimation # We assign to self so that outsiders can grab the demodulator # if they need to. E.g., to plot its output. # # input: complex; output: float self.fm_demod = analog.fmdet_cf(demod_rate, lowfreq, highfreq, 0.05) # input: float; output: float self.deemph_Left = fm_deemph(audio_rate) self.deemph_Right = fm_deemph(audio_rate) # compute FIR filter taps for audio filter width_of_transition_band = audio_rate / 32 audio_coeffs = filter.firdes.low_pass(1.0 , # gain demod_rate, # sampling rate 15000 , width_of_transition_band, filter.firdes.WIN_HAMMING) # input: float; output: float self.audio_filter = filter.fir_filter_fff(audio_decimation, audio_coeffs) if 1: # Pick off the stereo carrier/2 with this filter. It # attenuated 10 dB so apply 10 dB gain We pick off the # negative frequency half because we want to base band by # it! ## NOTE THIS WAS HACKED TO OFFSET INSERTION LOSS DUE TO ## DEEMPHASIS stereo_carrier_filter_coeffs = \ filter.firdes.complex_band_pass(10.0, demod_rate, -19020, -18980, width_of_transition_band, filter.firdes.WIN_HAMMING) #print "len stereo carrier filter = ",len(stereo_carrier_filter_coeffs) #print "stereo carrier filter ", stereo_carrier_filter_coeffs #print "width of transition band = ",width_of_transition_band, " audio rate = ", audio_rate # Pick off the double side band suppressed carrier # Left-Right audio. It is attenuated 10 dB so apply 10 dB # gain stereo_dsbsc_filter_coeffs = \ filter.firdes.complex_band_pass(20.0, demod_rate, 38000-15000/2, 38000+15000/2, width_of_transition_band, filter.firdes.WIN_HAMMING) #print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) #print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs # construct overlap add filter system from coefficients # for stereo carrier self.stereo_carrier_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_carrier_filter_coeffs) # carrier is twice the picked off carrier so arrange to do # a commplex multiply self.stereo_carrier_generator = blocks.multiply_cc(); # Pick off the rds signal stereo_rds_filter_coeffs = \ filter.firdes.complex_band_pass(30.0, demod_rate, 57000 - 1500, 57000 + 1500, width_of_transition_band, filter.firdes.WIN_HAMMING) #print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) #print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs # construct overlap add filter system from coefficients for stereo carrier self.rds_signal_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_rds_filter_coeffs) self.rds_carrier_generator = blocks.multiply_cc(); self.rds_signal_generator = blocks.multiply_cc(); self_rds_signal_processor = blocks.null_sink(gr.sizeof_gr_complex); loop_bw = 2*math.pi/100.0 max_freq = -2.0*math.pi*18990/audio_rate; min_freq = -2.0*math.pi*19010/audio_rate; self.stereo_carrier_pll_recovery = analog.pll_refout_cc(loop_bw, max_freq, min_freq); #self.stereo_carrier_pll_recovery.squelch_enable(False) ##pll_refout does not have squelch yet, so disabled for #now # set up mixer (multiplier) to get the L-R signal at # baseband self.stereo_basebander = blocks.multiply_cc(); # pick off the real component of the basebanded L-R # signal. The imaginary SHOULD be zero self.LmR_real = blocks.complex_to_real(); self.Make_Left = blocks.add_ff(); self.Make_Right = blocks.sub_ff(); self.stereo_dsbsc_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_dsbsc_filter_coeffs) if 1: # send the real signal to complex filter to pick off the # carrier and then to one side of a multiplier self.connect(self, self.fm_demod, self.stereo_carrier_filter, self.stereo_carrier_pll_recovery, (self.stereo_carrier_generator,0)) # send the already filtered carrier to the otherside of the carrier # the resulting signal from this multiplier is the carrier # with correct phase but at -38000 Hz. self.connect(self.stereo_carrier_pll_recovery, (self.stereo_carrier_generator,1)) # send the new carrier to one side of the mixer (multiplier) self.connect(self.stereo_carrier_generator, (self.stereo_basebander,0)) # send the demphasized audio to the DSBSC pick off filter, the complex # DSBSC signal at +38000 Hz is sent to the other side of the mixer/multiplier # the result is BASEBANDED DSBSC with phase zero! self.connect(self.fm_demod,self.stereo_dsbsc_filter, (self.stereo_basebander,1)) # Pick off the real part since the imaginary is # theoretically zero and then to one side of a summer self.connect(self.stereo_basebander, self.LmR_real, (self.Make_Left,0)) #take the same real part of the DSBSC baseband signal and #send it to negative side of a subtracter self.connect(self.LmR_real,(self.Make_Right,1)) # Make rds carrier by taking the squared pilot tone and # multiplying by pilot tone self.connect(self.stereo_basebander,(self.rds_carrier_generator,0)) self.connect(self.stereo_carrier_pll_recovery,(self.rds_carrier_generator,1)) # take signal, filter off rds, send into mixer 0 channel self.connect(self.fm_demod,self.rds_signal_filter,(self.rds_signal_generator,0)) # take rds_carrier_generator output and send into mixer 1 # channel self.connect(self.rds_carrier_generator,(self.rds_signal_generator,1)) # send basebanded rds signal and send into "processor" # which for now is a null sink self.connect(self.rds_signal_generator,self_rds_signal_processor) if 1: # pick off the audio, L+R that is what we used to have and # send it to the summer self.connect(self.fm_demod, self.audio_filter, (self.Make_Left, 1)) # take the picked off L+R audio and send it to the PLUS # side of the subtractor self.connect(self.audio_filter,(self.Make_Right, 0)) # The result of Make_Left gets (L+R) + (L-R) and results in 2*L # The result of Make_Right gets (L+R) - (L-R) and results in 2*R self.connect(self.Make_Left , self.deemph_Left, (self, 0)) self.connect(self.Make_Right, self.deemph_Right, (self, 1)) # NOTE: mono support will require variable number of outputs in hier_block2s # See ticket:174 in Trac database #else: # self.connect (self.fm_demod, self.audio_filter, self) gnuradio-3.7.2.1/gr-analog/python/analog/qa_quadrature_demod.py0000775000175000017500000000350412207440367024347 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import cmath from gnuradio import gr, gr_unittest, analog, blocks class test_quadrature_demod(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_quad_demod_001(self): f = 1000.0 fs = 8000.0 src_data = [] for i in xrange(200): ti = i/fs src_data.append(cmath.exp(2j*cmath.pi*f*ti)) # f/fs is a quarter turn per sample. # Set the gain based on this to get 1 out. gain = 1.0/(cmath.pi/4) expected_result = [0,] + 199*[1.0] src = blocks.vector_source_c(src_data) op = analog.quadrature_demod_cf(gain) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_quadrature_demod, "test_quadrature_demod.xml") gnuradio-3.7.2.1/gr-analog/python/analog/nbfm_rx.py0000664000175000017500000000636212207440367021776 0ustar jcorganjcorgan# # Copyright 2005,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr from gnuradio import filter from fm_emph import fm_deemph try: from gnuradio import analog except ImportError: import analog_swig as analog class nbfm_rx(gr.hier_block2): def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3): """ Narrow Band FM Receiver. Takes a single complex baseband input stream and produces a single float output stream of audio sample in the range [-1, +1]. Args: audio_rate: sample rate of audio stream, >= 16k (integer) quad_rate: sample rate of output stream (integer) tau: preemphasis time constant (default 75e-6) (float) max_dev: maximum deviation in Hz (default 5e3) (float) quad_rate must be an integer multiple of audio_rate. Exported sub-blocks (attributes): squelch quad_demod deemph audio_filter """ gr.hier_block2.__init__(self, "nbfm_rx", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature # FIXME audio_rate and quad_rate ought to be exact rationals audio_rate = int(audio_rate) quad_rate = int(quad_rate) if quad_rate % audio_rate != 0: raise ValueError, "quad_rate is not an integer multiple of audio_rate" squelch_threshold = 20 # dB #self.squelch = analog.simple_squelch_cc(squelch_threshold, 0.001) # FM Demodulator input: complex; output: float k = quad_rate/(2*math.pi*max_dev) self.quad_demod = analog.quadrature_demod_cf(k) # FM Deemphasis IIR filter self.deemph = fm_deemph(quad_rate, tau=tau) # compute FIR taps for audio filter audio_decim = quad_rate // audio_rate audio_taps = filter.firdes.low_pass(1.0, # gain quad_rate, # sampling rate 2.7e3, # Audio LPF cutoff 0.5e3, # Transition band filter.firdes.WIN_HAMMING) # filter type print "len(audio_taps) =", len(audio_taps) # Decimating audio filter # input: float; output: float; taps: float self.audio_filter = filter.fir_filter_fff(audio_decim, audio_taps) self.connect(self, self.quad_demod, self.deemph, self.audio_filter, self) gnuradio-3.7.2.1/gr-analog/python/analog/am_demod.py0000664000175000017500000000555612207440367022114 0ustar jcorganjcorgan# # Copyright 2006,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter class am_demod_cf(gr.hier_block2): """ Generalized AM demodulation block with audio filtering. This block demodulates a band-limited, complex down-converted AM channel into the the original baseband signal, applying low pass filtering to the audio output. It produces a float stream in the range [-1.0, +1.0]. Args: channel_rate: incoming sample rate of the AM baseband (integer) audio_decim: input to output decimation rate (integer) audio_pass: audio low pass filter passband frequency (float) audio_stop: audio low pass filter stop frequency (float) """ def __init__(self, channel_rate, audio_decim, audio_pass, audio_stop): gr.hier_block2.__init__(self, "am_demod_cf", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Input signature MAG = blocks.complex_to_mag() DCR = blocks.add_const_ff(-1.0) audio_taps = filter.optfir.low_pass(0.5, # Filter gain channel_rate, # Sample rate audio_pass, # Audio passband audio_stop, # Audio stopband 0.1, # Passband ripple 60) # Stopband attenuation LPF = filter.fir_filter_fff(audio_decim, audio_taps) self.connect(self, MAG, DCR, LPF, self) class demod_10k0a3e_cf(am_demod_cf): """ AM demodulation block, 10 KHz channel. This block demodulates an AM channel conformant to 10K0A3E emission standards, such as broadcast band AM transmissions. Args: channel_rate: incoming sample rate of the AM baseband (integer) audio_decim: input to output decimation rate (integer) """ def __init__(self, channel_rate, audio_decim): am_demod_cf.__init__(self, channel_rate, audio_decim, 5000, # Audio passband 5500) # Audio stopband gnuradio-3.7.2.1/gr-analog/python/analog/nbfm_tx.py0000664000175000017500000000676712207440367022011 0ustar jcorganjcorgan# # Copyright 2005,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, filter from fm_emph import fm_preemph try: from gnuradio import analog except ImportError: import analog_swig as analog class nbfm_tx(gr.hier_block2): def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=5e3): """ Narrow Band FM Transmitter. Takes a single float input stream of audio samples in the range [-1,+1] and produces a single FM modulated complex baseband output. Args: audio_rate: sample rate of audio stream, >= 16k (integer) quad_rate: sample rate of output stream (integer) tau: preemphasis time constant (default 75e-6) (float) max_dev: maximum deviation in Hz (default 5e3) (float) quad_rate must be an integer multiple of audio_rate. """ gr.hier_block2.__init__(self, "nbfm_tx", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature # FIXME audio_rate and quad_rate ought to be exact rationals audio_rate = int(audio_rate) quad_rate = int(quad_rate) if quad_rate % audio_rate != 0: raise ValueError, "quad_rate is not an integer multiple of audio_rate" do_interp = audio_rate != quad_rate if do_interp: interp_factor = quad_rate / audio_rate interp_taps = filter.optfir.low_pass(interp_factor, # gain quad_rate, # Fs 4500, # passband cutoff 7000, # stopband cutoff 0.1, # passband ripple dB 40) # stopband atten dB #print "len(interp_taps) =", len(interp_taps) self.interpolator = filter.interp_fir_filter_fff (interp_factor, interp_taps) self.preemph = fm_preemph(quad_rate, tau=tau) k = 2 * math.pi * max_dev / quad_rate self.modulator = analog.frequency_modulator_fc(k) if do_interp: self.connect(self, self.interpolator, self.preemph, self.modulator, self) else: self.connect(self, self.preemph, self.modulator, self) class ctcss_gen_f(gr.hier_block2): def __init__(self, sample_rate, tone_freq): gr.hier_block2.__init__(self, "ctcss_gen_f", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature self.plgen = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, tone_freq, 0.1, 0.0) self.connect(self.plgen, self) gnuradio-3.7.2.1/gr-analog/python/analog/qa_agc.py0000775000175000017500000005071012207440367021555 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks class test_agc(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001_sets(self): agc = analog.agc_cc(1e-3, 1, 1) agc.set_rate(1) agc.set_reference(1.1) agc.set_gain(1.1) agc.set_max_gain(100) self.assertAlmostEqual(agc.rate(), 1) self.assertAlmostEqual(agc.reference(), 1.1) self.assertAlmostEqual(agc.gain(), 1.1) self.assertAlmostEqual(agc.max_gain(), 100) def test_001(self): ''' Test the complex AGC loop (single rate input) ''' tb = self.tb expected_result = ( (100.000244140625+7.2191943445432116e-07j), (72.892257690429688+52.959323883056641j), (25.089065551757812+77.216217041015625j), (-22.611061096191406+69.589706420898438j), (-53.357715606689453+38.766635894775391j), (-59.458671569824219+3.4792964243024471e-07j), (-43.373462677001953-31.512666702270508j), (-14.94139289855957-45.984889984130859j), (13.478158950805664-41.48150634765625j), (31.838506698608398-23.132022857666016j), (35.519271850585938-3.1176801940091536e-07j), (25.942903518676758+18.848621368408203j), (8.9492912292480469+27.5430908203125j), (-8.0852642059326172+24.883890151977539j), (-19.131628036499023+13.899936676025391j), (-21.383295059204102+3.1281737733479531e-07j), (-15.650330543518066-11.370632171630859j), (-5.4110145568847656-16.65339469909668j), (4.9008159637451172-15.083160400390625j), (11.628337860107422-8.4484796524047852j), (13.036135673522949-2.288476110834381e-07j), (9.5726661682128906+6.954948902130127j), (3.3216962814331055+10.223132133483887j), (-3.0204284191131592+9.2959251403808594j), (-7.1977195739746094+5.2294478416442871j), (-8.1072216033935547+1.8976157889483147e-07j), (-5.9838657379150391-4.3475332260131836j), (-2.0879747867584229-6.4261269569396973j), (1.9100792407989502-5.8786196708679199j), (4.5814824104309082-3.3286411762237549j), (5.1967458724975586-1.3684227440080576e-07j), (3.8647139072418213+2.8078789710998535j), (1.3594740629196167+4.1840314865112305j), (-1.2544282674789429+3.8607344627380371j), (-3.0366206169128418+2.2062335014343262j), (-3.4781389236450195+1.1194014604143376e-07j), (-2.6133756637573242-1.8987287282943726j), (-0.9293016791343689-2.8600969314575195j), (0.86727333068847656-2.6691930294036865j), (2.1243946552276611-1.5434627532958984j), (2.4633183479309082-8.6486437567145913e-08j), (1.8744727373123169+1.3618841171264648j), (0.67528903484344482+2.0783262252807617j), (-0.63866174221038818+1.965599536895752j), (-1.5857341289520264+1.152103066444397j), (-1.8640764951705933+7.6355092915036948e-08j), (-1.4381576776504517-1.0448826551437378j), (-0.52529704570770264-1.6166983842849731j), (0.50366902351379395-1.5501341819763184j), (1.26766037940979-0.92100900411605835j)) sampling_freq = 100 src1 = analog.sig_source_c(sampling_freq, analog.GR_SIN_WAVE, sampling_freq * 0.10, 100.0) dst1 = blocks.vector_sink_c() head = blocks.head(gr.sizeof_gr_complex, int (5*sampling_freq * 0.10)) agc = analog.agc_cc(1e-3, 1, 1) tb.connect(src1, head) tb.connect(head, agc) tb.connect(agc, dst1) tb.run() dst_data = dst1.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 4) def test_002_sets(self): agc = analog.agc_ff(1e-3, 1, 1) agc.set_rate(1) agc.set_reference(1.1) agc.set_gain(1.1) agc.set_max_gain(100) self.assertAlmostEqual(agc.rate(), 1) self.assertAlmostEqual(agc.reference(), 1.1) self.assertAlmostEqual(agc.gain(), 1.1) self.assertAlmostEqual(agc.max_gain(), 100) def test_002(self): ''' Test the floating point AGC loop (single rate input) ''' tb = self.tb expected_result = ( 7.2191943445432116e-07, 58.837181091308594, 89.700050354003906, 81.264183044433594, 45.506141662597656, 4.269894304798072e-07, -42.948936462402344, -65.50335693359375, -59.368724822998047, -33.261005401611328, -4.683740257860336e-07, 31.423542022705078, 47.950984954833984, 43.485683441162109, 24.378345489501953, 5.7254135299444897e-07, -23.062990188598633, -35.218441009521484, -31.964075088500977, -17.934831619262695, -5.0591745548445033e-07, 16.998210906982422, 25.982204437255859, 23.606258392333984, 13.260685920715332, 4.9936483037527069e-07, -12.59880542755127, -19.28221321105957, -17.54347038269043, -9.8700437545776367, -4.188150626305287e-07, 9.4074573516845703, 14.422011375427246, 13.145503044128418, 7.41046142578125, 3.8512698097292741e-07, -7.0924453735351562, -10.896408081054688, -9.9552040100097656, -5.6262712478637695, -3.1982864356905338e-07, 5.4131259918212891, 8.3389215469360352, 7.6409502029418945, 4.3320145606994629, 2.882407841298118e-07, -4.194943904876709, -6.4837145805358887, -5.9621825218200684, -3.3931560516357422) sampling_freq = 100 src1 = analog.sig_source_f(sampling_freq, analog.GR_SIN_WAVE, sampling_freq * 0.10, 100.0) dst1 = blocks.vector_sink_f () head = blocks.head (gr.sizeof_float, int (5*sampling_freq * 0.10)) agc = analog.agc_ff(1e-3, 1, 1) tb.connect (src1, head) tb.connect (head, agc) tb.connect (agc, dst1) tb.run () dst_data = dst1.data () self.assertFloatTuplesAlmostEqual (expected_result, dst_data, 4) def test_003_sets(self): agc = analog.agc2_cc(1e-3, 1e-1, 1, 1) agc.set_attack_rate(1) agc.set_decay_rate(2) agc.set_reference(1.1) agc.set_gain(1.1) agc.set_max_gain(100) self.assertAlmostEqual(agc.attack_rate(), 1) self.assertAlmostEqual(agc.decay_rate(), 2) self.assertAlmostEqual(agc.reference(), 1.1) self.assertAlmostEqual(agc.gain(), 1.1) self.assertAlmostEqual(agc.max_gain(), 100) def test_003(self): ''' Test the complex AGC loop (attack and decay rate inputs) ''' tb = self.tb expected_result = \ ((100.000244140625+7.2191943445432116e-07j), (0.80881959199905396+0.58764183521270752j), (0.30894950032234192+0.95084899663925171j), (-0.30895623564720154+0.95086973905563354j), (-0.80887287855148315+0.58768033981323242j), (-0.99984413385391235+5.850709250410091e-09j), (-0.80889981985092163-0.58770018815994263j), (-0.30897706747055054-0.95093393325805664j), (0.30898112058639526-0.95094609260559082j), (0.80893135070800781-0.58772283792495728j), (0.99990922212600708-8.7766354184282136e-09j), (0.80894720554351807+0.58773452043533325j), (0.30899339914321899+0.95098406076431274j), (-0.30899572372436523+0.95099133253097534j), (-0.80896598100662231+0.58774799108505249j), (-0.99994778633117676+1.4628290578855285e-08j), (-0.80897533893585205-0.58775502443313599j), (-0.30900305509567261-0.95101380348205566j), (0.30900448560714722-0.95101797580718994j), (0.80898630619049072-0.58776277303695679j), (0.99997037649154663-1.7554345532744264e-08j), (0.80899184942245483+0.58776694536209106j), (0.30900871753692627+0.95103120803833008j), (-0.30900952219963074+0.95103377103805542j), (-0.8089984655380249+0.58777159452438354j), (-0.99998390674591064+2.3406109050938539e-08j), (-0.809001624584198-0.58777409791946411j), (-0.30901208519935608-0.95104163885116577j), (0.30901262164115906-0.95104306936264038j), (0.80900543928146362-0.587776780128479j), (0.99999171495437622-2.6332081404234486e-08j), (0.80900734663009644+0.58777821063995361j), (0.30901408195495605+0.95104765892028809j), (-0.30901429057121277+0.95104855298995972j), (-0.80900967121124268+0.58777981996536255j), (-0.99999648332595825+3.2183805842578295e-08j), (-0.80901080369949341-0.58778077363967896j), (-0.30901527404785156-0.95105135440826416j), (0.30901545286178589-0.95105189085006714j), (0.80901217460632324-0.58778166770935059j), (0.99999916553497314-3.5109700036173308e-08j), (0.809012770652771+0.58778214454650879j), (0.30901595950126648+0.9510534405708313j), (-0.30901598930358887+0.95105385780334473j), (-0.80901366472244263+0.58778274059295654j), (-1.0000008344650269+4.0961388947380328e-08j), (-0.8090139627456665-0.58778303861618042j), (-0.30901634693145752-0.95105475187301636j), (0.30901640653610229-0.95105493068695068j), (0.80901449918746948-0.5877833366394043j)) sampling_freq = 100 src1 = analog.sig_source_c(sampling_freq, analog.GR_SIN_WAVE, sampling_freq * 0.10, 100) dst1 = blocks.vector_sink_c() head = blocks.head(gr.sizeof_gr_complex, int(5*sampling_freq * 0.10)) agc = analog.agc2_cc(1e-2, 1e-3, 1, 1) tb.connect(src1, head) tb.connect(head, agc) tb.connect(agc, dst1) tb.run() dst_data = dst1.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 4) def test_004_sets(self): agc = analog.agc2_ff(1e-3, 1e-1, 1, 1) agc.set_attack_rate(1) agc.set_decay_rate(2) agc.set_reference(1.1) agc.set_gain(1.1) agc.set_max_gain(100) self.assertAlmostEqual(agc.attack_rate(), 1) self.assertAlmostEqual(agc.decay_rate(), 2) self.assertAlmostEqual(agc.reference(), 1.1) self.assertAlmostEqual(agc.gain(), 1.1) self.assertAlmostEqual(agc.max_gain(), 100) def test_004(self): ''' Test the floating point AGC loop (attack and decay rate inputs) ''' tb = self.tb expected_result = \ (7.2191943445432116e-07, 58.837181091308594, 40.194305419921875, 2.9183335304260254, 0.67606079578399658, 8.6260438791896377e-09, -1.4542514085769653, -1.9210131168365479, -1.0450780391693115, -0.61939650774002075, -1.2590258613442984e-08, 1.4308931827545166, 1.9054338932037354, 1.0443156957626343, 0.61937344074249268, 2.0983527804219193e-08, -1.4308838844299316, -1.9054274559020996, -1.0443152189254761, -0.61937344074249268, -2.5180233009791664e-08, 1.4308837652206421, 1.9054274559020996, 1.0443154573440552, 0.61937344074249268, 3.3573645197293445e-08, -1.4308838844299316, -1.9054274559020996, -1.0443152189254761, -0.61937350034713745, -3.7770352179222755e-08, 1.4308837652206421, 1.9054274559020996, 1.0443154573440552, 0.61937350034713745, 4.6163762590367696e-08, -1.4308838844299316, -1.9054274559020996, -1.0443153381347656, -0.61937344074249268, -5.0360466019583328e-08, 1.4308837652206421, 1.9054274559020996, 1.0443155765533447, 0.61937344074249268, 5.8753879983441948e-08, -1.4308837652206421, -1.9054274559020996, -1.0443153381347656, -0.61937344074249268) sampling_freq = 100 src1 = analog.sig_source_f(sampling_freq, analog.GR_SIN_WAVE, sampling_freq * 0.10, 100) dst1 = blocks.vector_sink_f() head = blocks.head(gr.sizeof_float, int(5*sampling_freq * 0.10)) agc = analog.agc2_ff(1e-2, 1e-3, 1, 1) tb.connect(src1, head) tb.connect(head, agc) tb.connect(agc, dst1) tb.run() dst_data = dst1.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 4) def test_005(self): ''' Test the complex AGC loop (attack and decay rate inputs) ''' tb = self.tb expected_result = \ ((100.000244140625+7.2191943445432116e-07j), (0.80881959199905396+0.58764183521270752j), (0.30894950032234192+0.95084899663925171j), (-0.30895623564720154+0.95086973905563354j), (-0.80887287855148315+0.58768033981323242j), (-0.99984413385391235+5.850709250410091e-09j), (-0.80889981985092163-0.58770018815994263j), (-0.30897706747055054-0.95093393325805664j), (0.30898112058639526-0.95094609260559082j), (0.80893135070800781-0.58772283792495728j), (0.99990922212600708-8.7766354184282136e-09j), (0.80894720554351807+0.58773452043533325j), (0.30899339914321899+0.95098406076431274j), (-0.30899572372436523+0.95099133253097534j), (-0.80896598100662231+0.58774799108505249j), (-0.99994778633117676+1.4628290578855285e-08j), (-0.80897533893585205-0.58775502443313599j), (-0.30900305509567261-0.95101380348205566j), (0.30900448560714722-0.95101797580718994j), (0.80898630619049072-0.58776277303695679j), (0.99997037649154663-1.7554345532744264e-08j), (0.80899184942245483+0.58776694536209106j), (0.30900871753692627+0.95103120803833008j), (-0.30900952219963074+0.95103377103805542j), (-0.8089984655380249+0.58777159452438354j), (-0.99998390674591064+2.3406109050938539e-08j), (-0.809001624584198-0.58777409791946411j), (-0.30901208519935608-0.95104163885116577j), (0.30901262164115906-0.95104306936264038j), (0.80900543928146362-0.587776780128479j), (0.99999171495437622-2.6332081404234486e-08j), (0.80900734663009644+0.58777821063995361j), (0.30901408195495605+0.95104765892028809j), (-0.30901429057121277+0.95104855298995972j), (-0.80900967121124268+0.58777981996536255j), (-0.99999648332595825+3.2183805842578295e-08j), (-0.80901080369949341-0.58778077363967896j), (-0.30901527404785156-0.95105135440826416j), (0.30901545286178589-0.95105189085006714j), (0.80901217460632324-0.58778166770935059j), (0.99999916553497314-3.5109700036173308e-08j), (0.809012770652771+0.58778214454650879j), (0.30901595950126648+0.9510534405708313j), (-0.30901598930358887+0.95105385780334473j), (-0.80901366472244263+0.58778274059295654j), (-1.0000008344650269+4.0961388947380328e-08j), (-0.8090139627456665-0.58778303861618042j), (-0.30901634693145752-0.95105475187301636j), (0.30901640653610229-0.95105493068695068j), (0.80901449918746948-0.5877833366394043j)) sampling_freq = 100 src1 = analog.sig_source_c(sampling_freq, analog.GR_SIN_WAVE, sampling_freq * 0.10, 100) dst1 = blocks.vector_sink_c() head = blocks.head(gr.sizeof_gr_complex, int(5*sampling_freq * 0.10)) agc = analog.agc2_cc(1e-2, 1e-3, 1, 1) tb.connect(src1, head) tb.connect(head, agc) tb.connect(agc, dst1) tb.run() dst_data = dst1.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 4) def test_006_sets(self): agc = analog.agc3_cc(1e-3, 1e-1, 1) agc.set_attack_rate(1) agc.set_decay_rate(2) agc.set_reference(1.1) agc.set_gain(1.1) self.assertAlmostEqual(agc.attack_rate(), 1) self.assertAlmostEqual(agc.decay_rate(), 2) self.assertAlmostEqual(agc.reference(), 1.1) self.assertAlmostEqual(agc.gain(), 1.1) def test_006(self): ''' Test the complex AGC loop (attack and decay rate inputs) ''' tb = self.tb sampling_freq = 100 N = int(5*sampling_freq) src1 = analog.sig_source_c(sampling_freq, analog.GR_SIN_WAVE, sampling_freq * 0.10, 100) dst1 = blocks.vector_sink_c() head = blocks.head(gr.sizeof_gr_complex, N) ref = 1 agc = analog.agc3_cc(1e-2, 1e-3, ref) tb.connect(src1, head) tb.connect(head, agc) tb.connect(agc, dst1) tb.run() dst_data = dst1.data() M = 100 result = map(lambda x: abs(x), dst_data[N-M:]) self.assertFloatTuplesAlmostEqual(result, M*[ref,], 4) def test_100(self): ''' Test complex feedforward agc with constant input ''' length = 8 gain = 2 input_data = 8*(0.0,) + 24*(1.0,) + 24*(0.0,) expected_result = (8+length-1)*(0.0,) + 24*(gain*1.0,) + (0,) src = blocks.vector_source_c(input_data) agc = analog.feedforward_agc_cc(8, 2.0) dst = blocks.vector_sink_c() self.tb.connect(src, agc, dst) self.tb.run() dst_data = dst.data()[0:len(expected_result)] self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 4) if __name__ == '__main__': gr_unittest.run(test_agc, "test_agc.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_pll_freqdet.py0000775000175000017500000001364512207440367023332 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks class test_pll_freqdet(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test_pll_freqdet(self): expected_result = (0.0, 4.33888922882e-08, 0.367369994515, 1.08135249597, 2.10983253908, 3.42221529438, 4.98940390402, 6.78379190842, 8.77923286024, 10.9510106794, 13.2758363182, 15.7317829127, 18.2982902299, 20.9561068599, 23.6755271122, 26.452952094, 29.2731265301, 32.1219053479, 34.9862418188, 37.8540971414, 40.7144315483, 43.5571390869, 46.3730179743, 49.1537231663, 51.8917218889, 54.58026103, 57.2015358514, 59.7513664199, 62.2380533124, 64.657612252, 67.006640002, 69.2822432184, 71.4820384499, 73.6041047056, 75.6469478817, 77.6094829742, 79.4909866472, 81.2911031615, 83.0097850853, 84.6355598352, 86.1820937186, 87.6504420946, 89.0418441206, 90.3577286819, 91.5996432431, 92.7692775646, 93.8684162704, 94.8989269904, 95.8627662892, 96.7619381633, 97.598505899, 98.362769679, 99.0579904444, 99.6992633875, 100.288805948, 100.828805921, 101.321421457, 101.76878699, 102.17300138, 102.536116055, 102.860158727, 103.147085962, 103.398830608, 103.617254366, 103.792467691, 103.939387906, 104.060030865, 104.15631756, 104.230085975, 104.283067372, 104.316933727, 104.333238432, 104.333440018, 104.318914008, 104.290941063, 104.250742554, 104.187634452, 104.103822339, 104.013227468, 103.916810336, 103.815448432, 103.709936239, 103.600997093, 103.489283183, 103.375351833, 103.259712936, 103.142828952, 103.025091195, 102.90686726, 102.776726069, 102.648078982, 102.521459607, 102.397294831, 102.275999684, 102.157882471, 102.043215927, 101.93218978, 101.824958181, 101.72159228, 101.622151366) sampling_freq = 10e3 freq = sampling_freq / 100 loop_bw = math.pi/100.0 maxf = 1 minf = -1 src = analog.sig_source_c(sampling_freq, analog.GR_COS_WAVE, freq, 1.0) pll = analog.pll_freqdet_cf(loop_bw, maxf, minf) head = blocks.head(gr.sizeof_float, int (freq)) dst = blocks.vector_sink_f() self.tb.connect(src, pll, head) self.tb.connect(head, dst) self.tb.run() dst_data = dst.data() # convert it from normalized frequency to absolute frequency (Hz) dst_data = [i*(sampling_freq/(2*math.pi)) for i in dst_data] self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 3) if __name__ == '__main__': gr_unittest.run(test_pll_freqdet, "test_pll_freqdet.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_dpll.py0000775000175000017500000000375312207440367021763 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks class test_dpll_bb(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_dpll_bb_001(self): # Test set/gets period = 1.0 gain = 0.1 op = analog.dpll_bb(period, gain) op.set_gain(0.2) g = op.gain() self.assertAlmostEqual(g, 0.2) f = op.freq() self.assertEqual(1/period, f) d0 = 1.0 - 0.5*f; d1 = op.decision_threshold() self.assertAlmostEqual(d0, d1) p = op.phase() self.assertEqual(0, p) def test_dpll_bb_002(self): period = 4 gain = 0.1 src_data = 10*((period-1)*[0,] + [1,]) expected_result = src_data src = blocks.vector_source_b(src_data) op = analog.dpll_bb(period, gain) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_dpll_bb, "test_dpll_bb.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_pll_carriertracking.py0000775000175000017500000001734612207440367025054 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks class test_pll_carriertracking(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test_pll_carriertracking(self): expected_result = ((1.00000238419+7.21919457547e-09j), (0.998025715351+0.062790453434j), (0.992777824402+0.119947694242j), (0.985192835331+0.171441286802j), (0.976061582565+0.217501848936j), (0.966034710407+0.258409559727j), (0.95565611124+0.294477283955j), (0.945357382298+0.326030552387j), (0.935475051403+0.353395611048j), (0.926258146763+0.376889169216j), (0.917895197868+0.39681750536j), (0.910515546799+0.413470208645j), (0.904196679592+0.427117019892j), (0.898972511292+0.438006043434j), (0.894769787788+0.446523308754j), (0.891652584076+0.452715367079j), (0.8895829916+0.456773489714j), (0.888502895832+0.458873122931j), (0.888343691826+0.459175437689j), (0.889035582542+0.457833081484j), (0.890497922897+0.454985737801j), (0.892645597458+0.450762689114j), (0.895388305187+0.445282936096j), (0.898648142815+0.438664674759j), (0.902342617512+0.431016951799j), (0.906392872334+0.422441422939j), (0.910642921925+0.413191765547j), (0.915039420128+0.403358519077j), (0.919594764709+0.392864197493j), (0.92425006628+0.381792247295j), (0.928944349289+0.370217680931j), (0.933634519577+0.358220815659j), (0.938279032707+0.345874190331j), (0.942840516567+0.333247303963j), (0.947280526161+0.32040438056j), (0.951574921608+0.307409763336j), (0.955703914165+0.294323593378j), (0.959648966789+0.281201630831j), (0.963392794132+0.268095195293j), (0.966880619526+0.255221515894j), (0.970162451267+0.242447137833j), (0.973235487938+0.229809194803j), (0.97609680891+0.217341512442j), (0.978744983673+0.20507311821j), (0.981189727783+0.193033605814j), (0.983436584473+0.181248426437j), (0.985490739346+0.169738590717j), (0.987353682518+0.158523857594j), (0.989041447639+0.147622272372j), (0.990563035011+0.137049794197j), (0.991928339005+0.126818582416j), (0.993117690086+0.117111675441j), (0.994156062603+0.107930034399j), (0.995076179504+0.0990980416536j), (0.995887458324+0.0906178802252j), (0.996591091156+0.0824909061193j), (0.997202515602+0.0747182965279j), (0.997730851173+0.0672992765903j), (0.998185396194+0.0602316558361j), (0.99856698513+0.0535135567188j), (0.998885989189+0.0471420884132j), (0.99915266037+0.0411129891872j), (0.999372899532+0.0354214012623j), (0.999548316002+0.0300626158714j), (0.999680638313+0.0252036750317j), (0.999784469604+0.020652115345j), (0.999865531921+0.0163950324059j), (0.999923825264+0.0124222636223j), (0.999960243702+0.00872156023979j), (0.999983668327+0.00528120994568j), (0.999997138977+0.00209015607834j), (1.00000119209-0.00086285173893j), (0.999992132187-0.00358882546425j), (0.999979138374-0.00609711557627j), (0.999963641167-0.00839691981673j), (0.999947249889-0.0104993218556j), (0.999924004078-0.0122378543019j), (0.999904811382-0.0136305987835j), (0.999888062477-0.0148707330227j), (0.9998742342-0.0159679055214j), (0.999856114388-0.0169314742088j), (0.999839782715-0.0177700817585j), (0.999826967716-0.0184917747974j), (0.999818325043-0.0191045701504j), (0.999807476997-0.0196143388748j), (0.999797284603-0.0200265944004j), (0.999791204929-0.0203481912613j), (0.99978852272-0.0205836892128j), (0.99978530407-0.0207380950451j), (0.999785065651-0.0206423997879j), (0.999787807465-0.0204866230488j), (0.999794304371-0.0202808082104j), (0.999800384045-0.0200312435627j), (0.999803245068-0.0197458267212j), (0.9998087883-0.0194311738014j), (0.999816894531-0.0190933048725j), (0.999825954437-0.0187371373177j), (0.999829888344-0.0183679759502j), (0.999835848808-0.017987690866j), (0.999844014645-0.0176006518304j)) sampling_freq = 10e3 freq = sampling_freq / 100 loop_bw = math.pi/100.0 maxf = 1 minf = -1 src = analog.sig_source_c(sampling_freq, analog.GR_COS_WAVE, freq, 1.0) pll = analog.pll_carriertracking_cc(loop_bw, maxf, minf) head = blocks.head(gr.sizeof_gr_complex, int (freq)) dst = blocks.vector_sink_c() self.tb.connect(src, pll, head) self.tb.connect(head, dst) self.tb.run() dst_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) if __name__ == '__main__': gr_unittest.run(test_pll_carriertracking, "test_pll_carriertracking.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_rail_ff.py0000775000175000017500000000376612207440367022436 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks def clip(x, lo, hi): if(x < lo): return lo elif(x > hi): return hi else: return x class test_rail(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_rail_001(self): # Test set/gets hi1 = 1 hi2 = 2 lo1 = -1 lo2 = -2 op = analog.rail_ff(lo1, hi1) op.set_hi(hi2) h = op.hi() self.assertEqual(hi2, h) op.set_lo(lo2) l = op.lo() self.assertEqual(lo2, l) def test_rail_002(self): lo = -0.75 hi = 0.90 src_data = [-2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2] expected_result = map(lambda x: clip(x, lo, hi), src_data) src = blocks.vector_source_f(src_data) op = analog.rail_ff(lo, hi) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_rail, "test_rail.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_phase_modulator.py0000775000175000017500000000333612207440367024213 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks def sincos(x): return math.cos(x) + math.sin(x) * 1j class test_phase_modulator(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_fm_001(self): pi = math.pi sensitivity = pi/4 src_data = (1.0/4, 1.0/2, 1.0/4, -1.0/4, -1.0/2, -1/4.0) expected_result = tuple([sincos(sensitivity*x) for x in src_data]) src = blocks.vector_source_f(src_data) op = analog.phase_modulator_fc(sensitivity) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_phase_modulator, "test_phase_modulator.xml") gnuradio-3.7.2.1/gr-analog/python/analog/wfm_rcv_pll.py0000664000175000017500000002311212207440367022645 0ustar jcorganjcorgan# # Copyright 2005,2006,2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter from fm_emph import fm_deemph import math try: from gnuradio import analog except ImportError: import analog_swig as analog class wfm_rcv_pll(gr.hier_block2): def __init__(self, demod_rate, audio_decimation): """ Hierarchical block for demodulating a broadcast FM signal. The input is the downconverted complex baseband signal (gr_complex). The output is two streams of the demodulated audio (float) 0=Left, 1=Right. Args: demod_rate: input sample rate of complex baseband input. (float) audio_decimation: how much to decimate demod_rate to get to audio. (integer) """ gr.hier_block2.__init__(self, "wfm_rcv_pll", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(2, 2, gr.sizeof_float)) # Output signature bandwidth = 250e3 audio_rate = demod_rate / audio_decimation # We assign to self so that outsiders can grab the demodulator # if they need to. E.g., to plot its output. # # input: complex; output: float loop_bw = 2*math.pi/100.0 max_freq = 2.0*math.pi*90e3/demod_rate self.fm_demod = analog.pll_freqdet_cf(loop_bw, max_freq,-max_freq) # input: float; output: float self.deemph_Left = fm_deemph(audio_rate) self.deemph_Right = fm_deemph(audio_rate) # compute FIR filter taps for audio filter width_of_transition_band = audio_rate / 32 audio_coeffs = filter.firdes.low_pass(1.0 , # gain demod_rate, # sampling rate 15000 , width_of_transition_band, filter.firdes.WIN_HAMMING) # input: float; output: float self.audio_filter = filter.fir_filter_fff(audio_decimation, audio_coeffs) if 1: # Pick off the stereo carrier/2 with this filter. It attenuated 10 dB so apply 10 dB gain # We pick off the negative frequency half because we want to base band by it! ## NOTE THIS WAS HACKED TO OFFSET INSERTION LOSS DUE TO DEEMPHASIS stereo_carrier_filter_coeffs = \ filter.firdes.complex_band_pass(10.0, demod_rate, -19020, -18980, width_of_transition_band, filter.firdes.WIN_HAMMING) #print "len stereo carrier filter = ",len(stereo_carrier_filter_coeffs) #print "stereo carrier filter ", stereo_carrier_filter_coeffs #print "width of transition band = ",width_of_transition_band, " audio rate = ", audio_rate # Pick off the double side band suppressed carrier Left-Right audio. It is attenuated 10 dB so apply 10 dB gain stereo_dsbsc_filter_coeffs = \ filter.firdes.complex_band_pass(20.0, demod_rate, 38000-15000/2, 38000+15000/2, width_of_transition_band, filter.firdes.WIN_HAMMING) #print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) #print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs # construct overlap add filter system from coefficients for stereo carrier self.stereo_carrier_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_carrier_filter_coeffs) # carrier is twice the picked off carrier so arrange to do a commplex multiply self.stereo_carrier_generator = blocks.multiply_cc(); # Pick off the rds signal stereo_rds_filter_coeffs = \ filter.firdes.complex_band_pass(30.0, demod_rate, 57000 - 1500, 57000 + 1500, width_of_transition_band, filter.firdes.WIN_HAMMING) #print "len stereo dsbsc filter = ",len(stereo_dsbsc_filter_coeffs) #print "stereo dsbsc filter ", stereo_dsbsc_filter_coeffs # construct overlap add filter system from coefficients for stereo carrier self.rds_signal_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_rds_filter_coeffs) self.rds_carrier_generator = blocks.multiply_cc(); self.rds_signal_generator = blocks.multiply_cc(); self_rds_signal_processor = blocks.null_sink(gr.sizeof_gr_complex); loop_bw = 2*math.pi/100.0 max_freq = -2.0*math.pi*18990/audio_rate; min_freq = -2.0*math.pi*19010/audio_rate; self.stereo_carrier_pll_recovery = \ analog.pll_refout_cc(loop_bw, max_freq, min_freq); #self.stereo_carrier_pll_recovery.squelch_enable(False) #pll_refout does not have squelch yet, so disabled for now # set up mixer (multiplier) to get the L-R signal at baseband self.stereo_basebander = blocks.multiply_cc(); # pick off the real component of the basebanded L-R signal. The imaginary SHOULD be zero self.LmR_real = blocks.complex_to_real(); self.Make_Left = blocks.add_ff(); self.Make_Right = blocks.sub_ff(); self.stereo_dsbsc_filter = \ filter.fir_filter_fcc(audio_decimation, stereo_dsbsc_filter_coeffs) if 1: # send the real signal to complex filter to pick off the carrier and then to one side of a multiplier self.connect(self, self.fm_demod, self.stereo_carrier_filter, self.stereo_carrier_pll_recovery, (self.stereo_carrier_generator,0)) # send the already filtered carrier to the otherside of the carrier self.connect(self.stereo_carrier_pll_recovery, (self.stereo_carrier_generator,1)) # the resulting signal from this multiplier is the carrier with correct phase but at -38000 Hz. # send the new carrier to one side of the mixer (multiplier) self.connect(self.stereo_carrier_generator, (self.stereo_basebander,0)) # send the demphasized audio to the DSBSC pick off filter, the complex # DSBSC signal at +38000 Hz is sent to the other side of the mixer/multiplier self.connect(self.fm_demod,self.stereo_dsbsc_filter, (self.stereo_basebander,1)) # the result is BASEBANDED DSBSC with phase zero! # Pick off the real part since the imaginary is theoretically zero and then to one side of a summer self.connect(self.stereo_basebander, self.LmR_real, (self.Make_Left,0)) #take the same real part of the DSBSC baseband signal and send it to negative side of a subtracter self.connect(self.LmR_real,(self.Make_Right,1)) # Make rds carrier by taking the squared pilot tone and multiplying by pilot tone self.connect(self.stereo_basebander,(self.rds_carrier_generator,0)) self.connect(self.stereo_carrier_pll_recovery,(self.rds_carrier_generator,1)) # take signal, filter off rds, send into mixer 0 channel self.connect(self.fm_demod,self.rds_signal_filter,(self.rds_signal_generator,0)) # take rds_carrier_generator output and send into mixer 1 channel self.connect(self.rds_carrier_generator,(self.rds_signal_generator,1)) # send basebanded rds signal and send into "processor" which for now is a null sink self.connect(self.rds_signal_generator,self_rds_signal_processor) if 1: # pick off the audio, L+R that is what we used to have and send it to the summer self.connect(self.fm_demod, self.audio_filter, (self.Make_Left, 1)) # take the picked off L+R audio and send it to the PLUS side of the subtractor self.connect(self.audio_filter,(self.Make_Right, 0)) # The result of Make_Left gets (L+R) + (L-R) and results in 2*L # The result of Make_Right gets (L+R) - (L-R) and results in 2*R self.connect(self.Make_Left , self.deemph_Left, (self, 0)) self.connect(self.Make_Right, self.deemph_Right, (self, 1)) # NOTE: mono support will require variable number of outputs in hier_block2s # See ticket:174 in Trac database #else: # self.connect (self.fm_demod, self.audio_filter, self) gnuradio-3.7.2.1/gr-analog/python/analog/qa_frequency_modulator.py0000775000175000017500000000344112207440367025111 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks def sincos(x): return math.cos(x) + math.sin(x) * 1j class test_frequency_modulator(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_fm_001(self): pi = math.pi sensitivity = pi/4 src_data = (1.0/4, 1.0/2, 1.0/4, -1.0/4, -1.0/2, -1/4.0) running_sum = (pi/16, 3*pi/16, pi/4, 3*pi/16, pi/16, 0) expected_result = tuple([sincos(x) for x in running_sum]) src = blocks.vector_source_f(src_data) op = analog.frequency_modulator_fc(sensitivity) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_frequency_modulator, "test_frequency_modulator.xml") gnuradio-3.7.2.1/gr-analog/python/analog/standard_squelch.py0000664000175000017500000000571212207440367023665 0ustar jcorganjcorgan# # Copyright 2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr from gnuradio import blocks from gnuradio import filter class standard_squelch(gr.hier_block2): def __init__(self, audio_rate): gr.hier_block2.__init__(self, "standard_squelch", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature self.input_node = blocks.add_const_ff(0) # FIXME kludge self.low_iir = filter.iir_filter_ffd((0.0193,0,-0.0193),(1,1.9524,-0.9615)) self.low_square = blocks.multiply_ff() self.low_smooth = filter.single_pole_iir_filter_ff(1/(0.01*audio_rate)) # 100ms time constant self.hi_iir = filter.iir_filter_ffd((0.0193,0,-0.0193),(1,1.3597,-0.9615)) self.hi_square = blocks.multiply_ff() self.hi_smooth = filter.single_pole_iir_filter_ff(1/(0.01*audio_rate)) self.sub = blocks.sub_ff(); self.add = blocks.add_ff(); self.gate = blocks.threshold_ff(0.3,0.43,0) self.squelch_lpf = filter.single_pole_iir_filter_ff(1/(0.01*audio_rate)) self.div = blocks.divide_ff() self.squelch_mult = blocks.multiply_ff() self.connect(self, self.input_node) self.connect(self.input_node, (self.squelch_mult, 0)) self.connect(self.input_node,self.low_iir) self.connect(self.low_iir,(self.low_square,0)) self.connect(self.low_iir,(self.low_square,1)) self.connect(self.low_square,self.low_smooth,(self.sub,0)) self.connect(self.low_smooth, (self.add,0)) self.connect(self.input_node,self.hi_iir) self.connect(self.hi_iir,(self.hi_square,0)) self.connect(self.hi_iir,(self.hi_square,1)) self.connect(self.hi_square,self.hi_smooth,(self.sub,1)) self.connect(self.hi_smooth, (self.add,1)) self.connect(self.sub, (self.div, 0)) self.connect(self.add, (self.div, 1)) self.connect(self.div, self.gate, self.squelch_lpf, (self.squelch_mult,1)) self.connect(self.squelch_mult, self) def set_threshold(self, threshold): self.gate.set_hi(threshold) def threshold(self): return self.gate.hi() def squelch_range(self): return (0.0, 1.0, 1.0/100) gnuradio-3.7.2.1/gr-analog/python/analog/__init__.py0000664000175000017500000000256012207440367022076 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks and utilities for analog modulation and demodulation. ''' # The presence of this file turns this directory into a Python package import os try: from analog_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from analog_swig import * from am_demod import * from fm_demod import * from fm_emph import * from nbfm_rx import * from nbfm_tx import * from standard_squelch import * from wfm_rcv import * from wfm_rcv_fmdet import * from wfm_rcv_pll import * from wfm_tx import * gnuradio-3.7.2.1/gr-analog/python/analog/fm_demod.py0000664000175000017500000001022012207440367022101 0ustar jcorganjcorgan# # Copyright 2006,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from fm_emph import fm_deemph from math import pi try: from gnuradio import analog except ImportError: import analog_swig as analog class fm_demod_cf(gr.hier_block2): """ Generalized FM demodulation block with deemphasis and audio filtering. This block demodulates a band-limited, complex down-converted FM channel into the the original baseband signal, optionally applying deemphasis. Low pass filtering is done on the resultant signal. It produces an output float strem in the range of [-1.0, +1.0]. Args: channel_rate: incoming sample rate of the FM baseband (integer) deviation: maximum FM deviation (default = 5000) (float) audio_decim: input to output decimation rate (integer) audio_pass: audio low pass filter passband frequency (float) audio_stop: audio low pass filter stop frequency (float) gain: gain applied to audio output (default = 1.0) (float) tau: deemphasis time constant (default = 75e-6), specify 'None' to prevent deemphasis """ def __init__(self, channel_rate, audio_decim, deviation, audio_pass, audio_stop, gain=1.0, tau=75e-6): gr.hier_block2.__init__(self, "fm_demod_cf", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature k = channel_rate/(2*pi*deviation) QUAD = analog.quadrature_demod_cf(k) audio_taps = filter.optfir.low_pass(gain, # Filter gain channel_rate, # Sample rate audio_pass, # Audio passband audio_stop, # Audio stopband 0.1, # Passband ripple 60) # Stopband attenuation LPF = filter.fir_filter_fff(audio_decim, audio_taps) if tau is not None: DEEMPH = fm_deemph(channel_rate, tau) self.connect(self, QUAD, DEEMPH, LPF, self) else: self.connect(self, QUAD, LPF, self) class demod_20k0f3e_cf(fm_demod_cf): """ NBFM demodulation block, 20 KHz channels This block demodulates a complex, downconverted, narrowband FM channel conforming to 20K0F3E emission standards, outputting floats in the range [-1.0, +1.0]. Args: sample_rate: incoming sample rate of the FM baseband (integer) audio_decim: input to output decimation rate (integer) """ def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 5000, # Deviation 3000, # Audio passband frequency 4500) # Audio stopband frequency class demod_200kf3e_cf(fm_demod_cf): """ WFM demodulation block, mono. This block demodulates a complex, downconverted, wideband FM channel conforming to 200KF3E emission standards, outputting floats in the range [-1.0, +1.0]. Args: sample_rate: incoming sample rate of the FM baseband (integer) audio_decim: input to output decimation rate (integer) """ def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 75000, # Deviation 15000, # Audio passband 16000, # Audio stopband 20.0) # Audio gain gnuradio-3.7.2.1/gr-analog/python/analog/qa_ctcss_squelch.py0000775000175000017500000000600212207440367023661 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks class test_ctcss_squelch(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_ctcss_squelch_001(self): # Test set/gets rate = 1 rate2 = 2 freq = 100 level = 0.5 length = 1 ramp = 1 ramp2 = 2 gate = True gate2 = False op = analog.ctcss_squelch_ff(rate, freq, level, length, ramp, gate) op.set_ramp(ramp2) r = op.ramp() self.assertEqual(ramp2, r) op.set_gate(gate2) g = op.gate() self.assertEqual(gate2, g) def test_ctcss_squelch_002(self): # Test runtime, gate=True rate = 1 freq = 100 level = 0.0 length = 1 ramp = 1 gate = True src_data = map(lambda x: float(x)/10.0, range(1, 40)) expected_result = src_data expected_result[0] = 0 src = blocks.vector_source_f(src_data) op = analog.ctcss_squelch_ff(rate, freq, level, length, ramp, gate) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 4) def test_ctcss_squelch_003(self): # Test runtime, gate=False rate = 1 freq = 100 level = 0.5 length = 1 ramp = 1 gate = False src_data = map(lambda x: float(x)/10.0, range(1, 40)) src = blocks.vector_source_f(src_data) op = analog.ctcss_squelch_ff(rate, freq, level, length, ramp, gate) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() expected_result = src_data expected_result[0:5] = [0, 0, 0, 0, 0] result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_ctcss_squelch, "test_ctcss_squelch.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_pwr_squelch.py0000775000175000017500000000633712207440367023365 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks class test_pwr_squelch(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_pwr_squelch_001(self): # Test set/gets alpha = 0.0001 thr1 = 10 thr2 = 20 ramp = 1 ramp2 = 2 gate = True gate2 = False op = analog.pwr_squelch_cc(thr1, alpha, ramp, gate) op.set_threshold(thr2) t = op.threshold() self.assertEqual(thr2, t) op.set_ramp(ramp2) r = op.ramp() self.assertEqual(ramp2, r) op.set_gate(gate2) g = op.gate() self.assertEqual(gate2, g) def test_pwr_squelch_002(self): # Test runtime, gate=True alpha = 0.0001 thr = -25 src_data = map(lambda x: float(x)/10.0, range(1, 40)) src = blocks.vector_source_c(src_data) op = analog.pwr_squelch_cc(thr, alpha) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() expected_result = src_data expected_result[0:20] = 20*[0,] result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 4) def test_pwr_squelch_003(self): # Test set/gets alpha = 0.0001 thr1 = 10 thr2 = 20 ramp = 1 ramp2 = 2 gate = True gate2 = False op = analog.pwr_squelch_ff(thr1, alpha, ramp, gate) op.set_threshold(thr2) t = op.threshold() self.assertEqual(thr2, t) op.set_ramp(ramp2) r = op.ramp() self.assertEqual(ramp2, r) op.set_gate(gate2) g = op.gate() self.assertEqual(gate2, g) def test_pwr_squelch_004(self): alpha = 0.0001 thr = -25 src_data = map(lambda x: float(x)/10.0, range(1, 40)) src = blocks.vector_source_f(src_data) op = analog.pwr_squelch_ff(thr, alpha) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() expected_result = src_data expected_result[0:20] = 20*[0,] result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_pwr_squelch, "test_pwr_squelch.xml") gnuradio-3.7.2.1/gr-analog/python/analog/wfm_tx.py0000664000175000017500000000614412207440367021645 0ustar jcorganjcorgan# # Copyright 2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr from gnuradio import filter from fm_emph import fm_preemph try: from gnuradio import analog except ImportError: import analog_swig as analog class wfm_tx(gr.hier_block2): def __init__(self, audio_rate, quad_rate, tau=75e-6, max_dev=75e3): """ Wide Band FM Transmitter. Takes a single float input stream of audio samples in the range [-1,+1] and produces a single FM modulated complex baseband output. Args: audio_rate: sample rate of audio stream, >= 16k (integer) quad_rate: sample rate of output stream (integer) tau: preemphasis time constant (default 75e-6) (float) max_dev: maximum deviation in Hz (default 75e3) (float) quad_rate must be an integer multiple of audio_rate. """ gr.hier_block2.__init__(self, "wfm_tx", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature # FIXME audio_rate and quad_rate ought to be exact rationals audio_rate = int(audio_rate) quad_rate = int(quad_rate) if quad_rate % audio_rate != 0: raise ValueError, "quad_rate is not an integer multiple of audio_rate" do_interp = audio_rate != quad_rate if do_interp: interp_factor = quad_rate / audio_rate interp_taps = filter.optfir.low_pass(interp_factor, # gain quad_rate, # Fs 16000, # passband cutoff 18000, # stopband cutoff 0.1, # passband ripple dB 40) # stopband atten dB print "len(interp_taps) =", len(interp_taps) self.interpolator = filter.interp_fir_filter_fff (interp_factor, interp_taps) self.preemph = fm_preemph(quad_rate, tau=tau) k = 2 * math.pi * max_dev / quad_rate self.modulator = analog.frequency_modulator_fc (k) if do_interp: self.connect(self, self.interpolator, self.preemph, self.modulator, self) else: self.connect(self, self.preemph, self.modulator, self) gnuradio-3.7.2.1/gr-analog/python/analog/wfm_rcv.py0000664000175000017500000000533612207440367022006 0ustar jcorganjcorgan# # Copyright 2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from fm_emph import fm_deemph import math try: from gnuradio import analog except ImportError: import analog_swig as analog class wfm_rcv(gr.hier_block2): def __init__ (self, quad_rate, audio_decimation): """ Hierarchical block for demodulating a broadcast FM signal. The input is the downconverted complex baseband signal (gr_complex). The output is the demodulated audio (float). Args: quad_rate: input sample rate of complex baseband input. (float) audio_decimation: how much to decimate quad_rate to get to audio. (integer) """ gr.hier_block2.__init__(self, "wfm_rcv", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature volume = 20. max_dev = 75e3 fm_demod_gain = quad_rate/(2*math.pi*max_dev) audio_rate = quad_rate / audio_decimation # We assign to self so that outsiders can grab the demodulator # if they need to. E.g., to plot its output. # # input: complex; output: float self.fm_demod = analog.quadrature_demod_cf(fm_demod_gain) # input: float; output: float self.deemph = fm_deemph(audio_rate) # compute FIR filter taps for audio filter width_of_transition_band = audio_rate / 32 audio_coeffs = filter.firdes.low_pass(1.0, # gain quad_rate, # sampling rate audio_rate/2 - width_of_transition_band, width_of_transition_band, filter.firdes.WIN_HAMMING) # input: float; output: float self.audio_filter = filter.fir_filter_fff(audio_decimation, audio_coeffs) self.connect (self, self.fm_demod, self.audio_filter, self.deemph, self) gnuradio-3.7.2.1/gr-analog/python/analog/qa_probe_avg_mag_sqrd.py0000775000175000017500000000567712207440367024660 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks def avg_mag_sqrd_c(x, alpha): y = [0,] for xi in x: tmp = alpha*(xi.real*xi.real + xi.imag*xi.imag) + (1-alpha)*y[-1] y.append(tmp) return y def avg_mag_sqrd_f(x, alpha): y = [0,] for xi in x: tmp = alpha*(xi*xi) + (1-alpha)*y[-1] y.append(tmp) return y class test_probe_avg_mag_sqrd(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_c_001(self): alpha = 0.0001 src_data = [1.0+1.0j, 2.0+2.0j, 3.0+3.0j, 4.0+4.0j, 5.0+5.0j, 6.0+6.0j, 7.0+7.0j, 8.0+8.0j, 9.0+9.0j, 10.0+10.0j] expected_result = avg_mag_sqrd_c(src_data, alpha)[-1] src = blocks.vector_source_c(src_data) op = analog.probe_avg_mag_sqrd_c(0, alpha) self.tb.connect(src, op) self.tb.run() result_data = op.level() self.assertAlmostEqual(expected_result, result_data, 5) def test_cf_002(self): alpha = 0.0001 src_data = [1.0+1.0j, 2.0+2.0j, 3.0+3.0j, 4.0+4.0j, 5.0+5.0j, 6.0+6.0j, 7.0+7.0j, 8.0+8.0j, 9.0+9.0j, 10.0+10.0j] expected_result = avg_mag_sqrd_c(src_data, alpha)[0:-1] src = blocks.vector_source_c(src_data) op = analog.probe_avg_mag_sqrd_cf(0, alpha) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) def test_f_003(self): alpha = 0.0001 src_data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] expected_result = avg_mag_sqrd_f(src_data, alpha)[-1] src = blocks.vector_source_f(src_data) op = analog.probe_avg_mag_sqrd_f(0, alpha) self.tb.connect(src, op) self.tb.run() result_data = op.level() self.assertAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_probe_avg_mag_sqrd, "test_probe_avg_mag_sqrd.xml") gnuradio-3.7.2.1/gr-analog/python/analog/qa_cpfsk.py0000775000175000017500000000361012207440367022126 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks class test_cpfsk_bc(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_cpfsk_bc_001(self): # Test set/gets op = analog.cpfsk_bc(2, 1, 2) op.set_amplitude(2) a = op.amplitude() self.assertEqual(2, a) freq = 2*math.pi/2.0 f = op.freq() self.assertAlmostEqual(freq, f, 5) p = op.phase() self.assertEqual(0, p) def test_cpfsk_bc_002(self): src_data = 10*[0, 1] expected_result = map(lambda x: complex(2*x-1,0), src_data) src = blocks.vector_source_b(src_data) op = analog.cpfsk_bc(2, 1, 2) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data()[0:len(expected_result)] self.assertComplexTuplesAlmostEqual(expected_result, result_data, 4) if __name__ == '__main__': gr_unittest.run(test_cpfsk_bc, "test_cpfsk_bc.xml") gnuradio-3.7.2.1/gr-analog/lib/0000775000175000017500000000000012237515111015737 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/lib/probe_avg_mag_sqrd_f_impl.cc0000664000175000017500000000477212207440367023436 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "probe_avg_mag_sqrd_f_impl.h" #include #include namespace gr { namespace analog { probe_avg_mag_sqrd_f::sptr probe_avg_mag_sqrd_f::make(double threshold_db, double alpha) { return gnuradio::get_initial_sptr (new probe_avg_mag_sqrd_f_impl(threshold_db, alpha)); } probe_avg_mag_sqrd_f_impl::probe_avg_mag_sqrd_f_impl(double threshold_db, double alpha) : sync_block("probe_avg_mag_sqrd_f", io_signature::make(1, 1, sizeof(float)), io_signature::make(0, 0, 0)), d_unmuted(false), d_level(0), d_iir(alpha) { set_threshold(threshold_db); } probe_avg_mag_sqrd_f_impl::~probe_avg_mag_sqrd_f_impl() { } int probe_avg_mag_sqrd_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; for(int i = 0; i < noutput_items; i++) { double mag_sqrd = in[i]*in[i]; d_iir.filter(mag_sqrd); // computed for side effect: prev_output() } d_unmuted = d_iir.prev_output() >= d_threshold; d_level = d_iir.prev_output(); return noutput_items; } double probe_avg_mag_sqrd_f_impl::threshold() const { return 10 * std::log10(d_threshold); } void probe_avg_mag_sqrd_f_impl::set_threshold(double decibels) { // convert to absolute threshold (mag sqrd) d_threshold = std::pow(10.0, decibels/10); } void probe_avg_mag_sqrd_f_impl::set_alpha(double alpha) { d_iir.set_taps(alpha); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/probe_avg_mag_sqrd_f_impl.h0000664000175000017500000000346712207440367023300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_F_IMPL_H #define INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_F_IMPL_H #include #include namespace gr { namespace analog { class probe_avg_mag_sqrd_f_impl : public probe_avg_mag_sqrd_f { private: double d_threshold; bool d_unmuted; double d_level; filter::single_pole_iir d_iir; public: probe_avg_mag_sqrd_f_impl(double threshold_db, double alpha); ~probe_avg_mag_sqrd_f_impl(); bool unmuted() const { return d_unmuted; } double level() const { return d_level; } double threshold() const; void set_alpha(double alpha); void set_threshold(double decibels); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_F_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/dpll_bb_impl.cc0000664000175000017500000000475212207440367020704 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2009,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "dpll_bb_impl.h" #include #include namespace gr { namespace analog { dpll_bb::sptr dpll_bb::make(float period, float gain) { return gnuradio::get_initial_sptr (new dpll_bb_impl(period, gain)); } dpll_bb_impl::dpll_bb_impl(float period, float gain) : sync_block("dpll_bb", io_signature::make(1, 1, sizeof(char)), io_signature::make(1, 1, sizeof(char))), d_restart(0), d_pulse_phase(0) { d_pulse_frequency = 1.0/period; d_gain = gain; d_decision_threshold = 1.0 - 0.5*d_pulse_frequency; #if 0 fprintf(stderr,"frequency = %f period = %f gain = %f threshold = %f\n", d_pulse_frequency, period, d_gain, d_decision_threshold); #endif } dpll_bb_impl::~dpll_bb_impl() { } int dpll_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *iptr = (const char*)input_items[0]; char *optr = (char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { optr[i]= 0; if(iptr[i] == 1) { if(d_restart == 0) { d_pulse_phase = 1; } else { if(d_pulse_phase > 0.5) d_pulse_phase += d_gain*(1.0-d_pulse_phase); else d_pulse_phase -= d_gain*d_pulse_phase; } d_restart = 3; } if(d_pulse_phase > d_decision_threshold) { d_pulse_phase -= 1.0; if(d_restart > 0) { d_restart -= 1; optr[i] = 1; } } d_pulse_phase += d_pulse_frequency; } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/CMakeLists.txt0000664000175000017500000001421012207440367020504 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_BINARY_DIR}/../include ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${GR_ANALOG_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_impl_dict2(name, sig, 'analog') build_utils.expand_template(d, inp) ") macro(expand_cc root) #make a list of all the generated files unset(expanded_files_cc) unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_cc ${CMAKE_CURRENT_BINARY_DIR}/${name}.cc) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the source files add_custom_command( OUTPUT ${expanded_files_cc} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.cc.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.cc.t ${ARGN} ) #create a command to generate the header file add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #make source files depends on headers to force generation set_source_files_properties(${expanded_files_cc} PROPERTIES OBJECT_DEPENDS "${expanded_files_h}" ) #install rules for the generated cc files list(APPEND generated_sources ${expanded_files_cc}) list(APPEND generated_headers ${expanded_files_h}) endmacro(expand_cc) ######################################################################## # Invoke macro to generate various sources ######################################################################## expand_cc(noise_source_X_impl s i f c) expand_cc(fastnoise_source_X_impl s i f c) expand_cc(sig_source_X_impl s i f c) ######################################################################## # Setup library ######################################################################## list(APPEND analog_sources ${generated_sources} cpm.cc squelch_base_cc_impl.cc squelch_base_ff_impl.cc agc_cc_impl.cc agc_ff_impl.cc agc2_cc_impl.cc agc2_ff_impl.cc agc3_cc_impl.cc cpfsk_bc_impl.cc ctcss_squelch_ff_impl.cc dpll_bb_impl.cc feedforward_agc_cc_impl.cc fmdet_cf_impl.cc frequency_modulator_fc_impl.cc phase_modulator_fc_impl.cc pll_carriertracking_cc_impl.cc pll_freqdet_cf_impl.cc pll_refout_cc_impl.cc probe_avg_mag_sqrd_c_impl.cc probe_avg_mag_sqrd_cf_impl.cc probe_avg_mag_sqrd_f_impl.cc pwr_squelch_cc_impl.cc pwr_squelch_ff_impl.cc quadrature_demod_cf_impl.cc rail_ff_impl.cc simple_squelch_cc_impl.cc ) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-analog.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-analog.rc @ONLY) list(APPEND analog_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-analog.rc ) ENDIF(MSVC) list(APPEND analog_libs volk gnuradio-runtime gnuradio-blocks gnuradio-filter ${Boost_LIBRARIES} ) add_library(gnuradio-analog SHARED ${analog_sources}) target_link_libraries(gnuradio-analog ${analog_libs}) GR_LIBRARY_FOO(gnuradio-analog RUNTIME_COMPONENT "analog_runtime" DEVEL_COMPONENT "analog_devel") add_dependencies(gnuradio-analog analog_generated_includes analog_generated_swigs gnuradio-filter) ######################################################################## # QA C++ Code for gr-filter ######################################################################## if(ENABLE_TESTING) include(GrTest) include_directories(${CPPUNIT_INCLUDE_DIRS}) link_directories(${CPPUNIT_LIBRARY_DIRS}) list(APPEND test_gr_analog_sources ${CMAKE_CURRENT_SOURCE_DIR}/test_gr_analog.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_analog.cc ) add_executable(test-gr-analog ${test_gr_analog_sources}) target_link_libraries( test-gr-analog gnuradio-runtime gnuradio-analog ${Boost_LIBRARIES} ${CPPUNIT_LIBRARIES} ) list(APPEND GR_TEST_TARGET_DEPS gnuradio-analog gnuradio-filter gnuradio-fft) GR_ADD_TEST(test_gr_analog test-gr-analog) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-analog/lib/phase_modulator_fc_impl.cc0000664000175000017500000000403112207440367023132 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "phase_modulator_fc_impl.h" #include #include #include namespace gr { namespace analog { phase_modulator_fc::sptr phase_modulator_fc::make(double sensitivity) { return gnuradio::get_initial_sptr (new phase_modulator_fc_impl(sensitivity)); } phase_modulator_fc_impl::phase_modulator_fc_impl(double sensitivity) : sync_block("phase_modulator_fc", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))), d_sensitivity(sensitivity), d_phase(0) { } phase_modulator_fc_impl::~phase_modulator_fc_impl() { } int phase_modulator_fc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; for(int i = 0; i < noutput_items; i++) { d_phase = d_sensitivity * in[i]; float oi, oq; gr::sincosf(d_phase, &oq, &oi); out[i] = gr_complex(oi, oq); } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/cpfsk_bc_impl.h0000664000175000017500000000331012207440367020707 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_CPFSK_BC_IMPL_H #define INCLUDED_ANALOG_CPFSK_BC_IMPL_H #include namespace gr { namespace analog { class cpfsk_bc_impl : public cpfsk_bc { private: int d_samples_per_sym; // Samples per symbol, square pulse float d_freq; // Modulation index*pi/samples_per_sym float d_ampl; // Output amplitude float d_phase; // Current phase public: cpfsk_bc_impl(float k, float ampl, int samples_per_sym); ~cpfsk_bc_impl(); void set_amplitude(float amplitude) { d_ampl = amplitude; } float amplitude() { return d_ampl; } float freq() { return d_freq; } float phase() { return d_phase; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_CPFSK_BC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/pll_freqdet_cf_impl.h0000664000175000017500000000407112207440367022113 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PLL_FREQDET_CF_IMPL_H #define INCLUDED_ANALOG_PLL_FREQDET_CF_IMPL_H #include namespace gr { namespace analog { class pll_freqdet_cf_impl : public pll_freqdet_cf { private: float phase_detector(gr_complex sample,float ref_phase); public: pll_freqdet_cf_impl(float loop_bw, float max_freq, float min_freq); ~pll_freqdet_cf_impl(); float mod_2pi(float in); void set_loop_bandwidth(float bw); void set_damping_factor(float df); void set_alpha(float alpha); void set_beta(float beta); void set_frequency(float freq); void set_phase(float phase); void set_min_freq(float freq); void set_max_freq(float freq); float get_loop_bandwidth() const; float get_damping_factor() const; float get_alpha() const; float get_beta() const; float get_frequency() const; float get_phase() const; float get_min_freq() const; float get_max_freq() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PLL_FREQDET_CF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/agc_ff_impl.cc0000664000175000017500000000343612207440367020511 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "agc_ff_impl.h" #include namespace gr { namespace analog { agc_ff::sptr agc_ff::make(float rate, float reference, float gain) { return gnuradio::get_initial_sptr (new agc_ff_impl(rate, reference, gain)); } agc_ff_impl::agc_ff_impl(float rate, float reference, float gain) : sync_block("agc_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), kernel::agc_ff(rate, reference, gain, 65536) { } agc_ff_impl::~agc_ff_impl() { } int agc_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; scaleN(out, in, noutput_items); return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/fmdet_cf_impl.cc0000664000175000017500000000650512207440367021053 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fmdet_cf_impl.h" #include #include namespace gr { namespace analog { #define M_TWOPI (2*M_PI) fmdet_cf::sptr fmdet_cf::make(float samplerate, float freq_low, float freq_high, float scl) { return gnuradio::get_initial_sptr (new fmdet_cf_impl(samplerate, freq_low, freq_high, scl)); } fmdet_cf_impl::fmdet_cf_impl(float samplerate, float freq_low, float freq_high, float scl) : sync_block("fmdet_cf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(float))), d_S1(0.1), d_S2(0.1), d_S3(0.1), d_S4(0.1) { //const float h[] = { 0.003118678733, -0.012139843428, 0.027270898036, // -0.051318579352, 0.090406910552, -0.162926865366, // 0.361885392563, 0.000000000000, -0.361885392563, // 0.162926865366, -0.090406910552, 0.051318579352, // -0.027270898036, 0.012139843428, -0.003118678733}; //std::vector taps(15); d_freq = 0; d_freqhi = freq_high; d_freqlo = freq_low; set_scale(scl); //for(int i = 0; i < 15; i++) { //taps[i] = h[i]; //} // d_filter = gr_fir_util::create_gr_fir_ccf(taps); } fmdet_cf_impl::~fmdet_cf_impl() { } void fmdet_cf_impl::set_scale(float scl) { float delta = d_freqhi - d_freqlo; d_scl = scl; d_bias = 0.5*scl*(d_freqhi + d_freqlo) / delta; } void fmdet_cf_impl::set_freq_range(float freq_low, float freq_high) { d_freqhi = freq_high; d_freqlo = freq_low; set_scale(d_scl); } int fmdet_cf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *iptr = (gr_complex*)input_items[0]; float *optr = (float*)output_items[0]; //const gr_complex *scaleiptr = (gr_complex*)input_items[0]; int size = noutput_items; gr_complex Sdot, S0; gr_complex S1=d_S1, S2=d_S2, S3=d_S3, S4=d_S4; float d_8 = 8.0; while(size-- > 0) { S0 = *iptr++; Sdot = d_scl * (-S0+d_8*S1-d_8*S1+S4); d_freq = (S2.real()*Sdot.imag()-S2.imag()*Sdot.real()) / (S2.real()*S2.real()+S2.imag()*S2.imag()); S4 = S3; S3 = S2; S2 = S1; S1 = S0; *optr++ = d_freq-d_bias; } d_S1 = S1; d_S2 = S2; d_S3 = S3; d_S4 = S4; return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/pll_freqdet_cf_impl.cc0000664000175000017500000001070612207440367022253 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pll_freqdet_cf_impl.h" #include #include #include namespace gr { namespace analog { #ifndef M_TWOPI #define M_TWOPI (2.0f*M_PI) #endif pll_freqdet_cf::sptr pll_freqdet_cf::make(float loop_bw, float max_freq, float min_freq) { return gnuradio::get_initial_sptr (new pll_freqdet_cf_impl(loop_bw, max_freq, min_freq)); } pll_freqdet_cf_impl::pll_freqdet_cf_impl(float loop_bw, float max_freq, float min_freq) : sync_block("pll_freqdet_cf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(float))), blocks::control_loop(loop_bw, max_freq, min_freq) { } pll_freqdet_cf_impl::~pll_freqdet_cf_impl() { } float pll_freqdet_cf_impl::mod_2pi(float in) { if(in > M_PI) return in - M_TWOPI; else if(in < -M_PI) return in + M_TWOPI; else return in; } float pll_freqdet_cf_impl::phase_detector(gr_complex sample, float ref_phase) { float sample_phase; sample_phase = gr::fast_atan2f(sample.imag(), sample.real()); return mod_2pi(sample_phase - ref_phase); } int pll_freqdet_cf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *iptr = (gr_complex*)input_items[0]; float *optr = (float*)output_items[0]; float error; int size = noutput_items; while(size-- > 0) { *optr++ = d_freq; error = phase_detector(*iptr++, d_phase); advance_loop(error); phase_wrap(); frequency_limit(); } return noutput_items; } void pll_freqdet_cf_impl::set_loop_bandwidth(float bw) { blocks::control_loop::set_loop_bandwidth(bw); } void pll_freqdet_cf_impl::set_damping_factor(float df) { blocks::control_loop::set_damping_factor(df); } void pll_freqdet_cf_impl::set_alpha(float alpha) { blocks::control_loop::set_alpha(alpha); } void pll_freqdet_cf_impl::set_beta(float beta) { blocks::control_loop::set_beta(beta); } void pll_freqdet_cf_impl::set_frequency(float freq) { blocks::control_loop::set_frequency(freq); } void pll_freqdet_cf_impl::set_phase(float phase) { blocks::control_loop::set_phase(phase); } void pll_freqdet_cf_impl::set_min_freq(float freq) { blocks::control_loop::set_min_freq(freq); } void pll_freqdet_cf_impl::set_max_freq(float freq) { blocks::control_loop::set_max_freq(freq); } float pll_freqdet_cf_impl::get_loop_bandwidth() const { return blocks::control_loop::get_loop_bandwidth(); } float pll_freqdet_cf_impl::get_damping_factor() const { return blocks::control_loop::get_damping_factor(); } float pll_freqdet_cf_impl::get_alpha() const { return blocks::control_loop::get_alpha(); } float pll_freqdet_cf_impl::get_beta() const { return blocks::control_loop::get_beta(); } float pll_freqdet_cf_impl::get_frequency() const { return blocks::control_loop::get_frequency(); } float pll_freqdet_cf_impl::get_phase() const { return blocks::control_loop::get_phase(); } float pll_freqdet_cf_impl::get_min_freq() const { return blocks::control_loop::get_min_freq(); } float pll_freqdet_cf_impl::get_max_freq() const { return blocks::control_loop::get_max_freq(); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/pwr_squelch_cc_impl.cc0000664000175000017500000000377512220601630022276 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pwr_squelch_cc_impl.h" namespace gr { namespace analog { pwr_squelch_cc::sptr pwr_squelch_cc::make(double threshold, double alpha, int ramp, bool gate) { return gnuradio::get_initial_sptr (new pwr_squelch_cc_impl(threshold, alpha, ramp, gate)); } pwr_squelch_cc_impl::pwr_squelch_cc_impl(double threshold, double alpha, int ramp, bool gate) : block("pwr_squelch_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), squelch_base_cc_impl("pwr_squelch_cc", ramp, gate), d_pwr(0), d_iir(alpha) { set_threshold(threshold); } pwr_squelch_cc_impl::~pwr_squelch_cc_impl() { } std::vector pwr_squelch_cc_impl::squelch_range() const { std::vector r(3); r[0] = -50.0; // min FIXME r[1] = +50.0; // max FIXME r[2] = (r[1] - r[0]) / 100; // step size return r; } void pwr_squelch_cc_impl::update_state(const gr_complex &in) { d_pwr = d_iir.filter(in.real()*in.real()+in.imag()*in.imag()); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/noise_source_X_impl.h.t0000664000175000017500000000310512207440367022365 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace analog { class @IMPL_NAME@ : public @BASE_NAME@ { noise_type_t d_type; float d_ampl; gr::random d_rng; public: @IMPL_NAME@(noise_type_t type, float ampl, long seed = 0); ~@IMPL_NAME@(); void set_type(noise_type_t type); void set_amplitude(float ampl); noise_type_t type() const { return d_type; } float amplitude() const { return d_ampl; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-analog/lib/pll_refout_cc_impl.cc0000664000175000017500000001105012207440367022113 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pll_refout_cc_impl.h" #include #include #include #include namespace gr { namespace analog { #ifndef M_TWOPI #define M_TWOPI (2.0f*M_PI) #endif pll_refout_cc::sptr pll_refout_cc::make(float loop_bw, float max_freq, float min_freq) { return gnuradio::get_initial_sptr (new pll_refout_cc_impl(loop_bw, max_freq, min_freq)); } pll_refout_cc_impl::pll_refout_cc_impl(float loop_bw, float max_freq, float min_freq) : sync_block("pll_refout_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), blocks::control_loop(loop_bw, max_freq, min_freq) { } pll_refout_cc_impl::~pll_refout_cc_impl() { } float pll_refout_cc_impl::mod_2pi(float in) { if(in > M_PI) return in - M_TWOPI; else if(in < -M_PI) return in+ M_TWOPI; else return in; } float pll_refout_cc_impl::phase_detector(gr_complex sample,float ref_phase) { float sample_phase; sample_phase = gr::fast_atan2f(sample.imag(),sample.real()); return mod_2pi(sample_phase-ref_phase); } int pll_refout_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *iptr = (gr_complex*)input_items[0]; gr_complex *optr = (gr_complex*)output_items[0]; float error; float t_imag, t_real; int size = noutput_items; while(size-- > 0) { gr::sincosf(d_phase,&t_imag,&t_real); *optr++ = gr_complex(t_real,t_imag); error = phase_detector(*iptr++,d_phase); advance_loop(error); phase_wrap(); frequency_limit(); } return noutput_items; } void pll_refout_cc_impl::set_loop_bandwidth(float bw) { blocks::control_loop::set_loop_bandwidth(bw); } void pll_refout_cc_impl::set_damping_factor(float df) { blocks::control_loop::set_damping_factor(df); } void pll_refout_cc_impl::set_alpha(float alpha) { blocks::control_loop::set_alpha(alpha); } void pll_refout_cc_impl::set_beta(float beta) { blocks::control_loop::set_beta(beta); } void pll_refout_cc_impl::set_frequency(float freq) { blocks::control_loop::set_frequency(freq); } void pll_refout_cc_impl::set_phase(float phase) { blocks::control_loop::set_phase(phase); } void pll_refout_cc_impl::set_min_freq(float freq) { blocks::control_loop::set_min_freq(freq); } void pll_refout_cc_impl::set_max_freq(float freq) { blocks::control_loop::set_max_freq(freq); } float pll_refout_cc_impl::get_loop_bandwidth() const { return blocks::control_loop::get_loop_bandwidth(); } float pll_refout_cc_impl::get_damping_factor() const { return blocks::control_loop::get_damping_factor(); } float pll_refout_cc_impl::get_alpha() const { return blocks::control_loop::get_alpha(); } float pll_refout_cc_impl::get_beta() const { return blocks::control_loop::get_beta(); } float pll_refout_cc_impl::get_frequency() const { return blocks::control_loop::get_frequency(); } float pll_refout_cc_impl::get_phase() const { return blocks::control_loop::get_phase(); } float pll_refout_cc_impl::get_min_freq() const { return blocks::control_loop::get_min_freq(); } float pll_refout_cc_impl::get_max_freq() const { return blocks::control_loop::get_max_freq(); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/test_gr_analog.cc0000664000175000017500000000257112207440367021252 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include "qa_analog.h" #include int main (int argc, char **argv) { CppUnit::TextTestRunner runner; std::ofstream xmlfile(get_unittest_path("gr_analog.xml").c_str()); CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); runner.addTest(qa_gr_analog::suite()); runner.setOutputter(xmlout); bool was_successful = runner.run("", false); return was_successful ? 0 : 1; } gnuradio-3.7.2.1/gr-analog/lib/agc3_cc_impl.h0000664000175000017500000000421112237515111020411 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC3_IMPL_CC_H #define INCLUDED_ANALOG_AGC3_IMPL_CC_H #include namespace gr { namespace analog { class agc3_cc_impl : public agc3_cc { public: agc3_cc_impl(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0, int iir_update_decim=1); ~agc3_cc_impl(); float attack_rate() const { return d_attack; } float decay_rate() const { return d_decay; } float reference() const { return d_reference; } float gain() const { return d_gain; } float max_gain() const { return d_max_gain; } void set_attack_rate(float rate) { d_attack = rate; } void set_decay_rate(float rate) { d_decay = rate; } void set_reference(float reference) { d_reference = reference; } void set_gain(float gain) { d_gain = gain; } void set_max_gain(float max_gain) { d_max_gain = max_gain; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); private: float d_attack; float d_decay; float d_reference; float d_gain; float d_max_gain; bool d_reset; int d_iir_update_decim; }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC3_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/agc2_ff_impl.cc0000664000175000017500000000370112207440367020566 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "agc2_ff_impl.h" #include namespace gr { namespace analog { agc2_ff::sptr agc2_ff::make(float attack_rate, float decay_rate, float reference, float gain) { return gnuradio::get_initial_sptr (new agc2_ff_impl(attack_rate, decay_rate, reference, gain)); } agc2_ff_impl::~agc2_ff_impl() { } agc2_ff_impl::agc2_ff_impl(float attack_rate, float decay_rate, float reference, float gain) : sync_block("agc2_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), kernel::agc2_ff(attack_rate, decay_rate, reference, gain, 65536) { } int agc2_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; scaleN(out, in, noutput_items); return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/sig_source_X_impl.cc.t0000664000175000017500000001453612207440367022202 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include #endif #include "@IMPL_NAME@.h" #include #include #include #include #include namespace gr { namespace analog { @BASE_NAME@::sptr @BASE_NAME@::make(double sampling_freq, gr_waveform_t waveform, double frequency, double ampl, @TYPE@ offset) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(sampling_freq, waveform, frequency, ampl, offset)); } @IMPL_NAME@::@IMPL_NAME@(double sampling_freq, gr_waveform_t waveform, double frequency, double ampl, @TYPE@ offset) : sync_block("@BASE_NAME@", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(@TYPE@))), d_sampling_freq(sampling_freq), d_waveform(waveform), d_frequency(frequency), d_ampl(ampl), d_offset(offset) { d_nco.set_freq(2 * M_PI * d_frequency / d_sampling_freq); } @IMPL_NAME@::~@IMPL_NAME@() { } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @TYPE@ *optr = (@TYPE@*)output_items[0]; @TYPE@ t; switch(d_waveform) { #if @IS_COMPLEX@ // complex? case GR_CONST_WAVE: t = (gr_complex) d_ampl + d_offset; std::fill_n(optr, noutput_items, t); break; case GR_SIN_WAVE: case GR_COS_WAVE: d_nco.sincos(optr, noutput_items, d_ampl); if(d_offset == gr_complex(0,0)) break; for(int i = 0; i < noutput_items; i++) { optr[i] += d_offset; } break; /* Implements a real square wave high from -PI to 0. * The imaginary square wave leads by 90 deg. */ case GR_SQR_WAVE: for(int i = 0; i < noutput_items; i++) { if(d_nco.get_phase() < -1*M_PI/2) optr[i] = gr_complex(d_ampl, 0) + d_offset; else if(d_nco.get_phase() < 0) optr[i] = gr_complex(d_ampl, d_ampl) + d_offset; else if(d_nco.get_phase() < M_PI/2) optr[i] = gr_complex(0, d_ampl) + d_offset; else optr[i] = d_offset; d_nco.step(); } break; /* Implements a real triangle wave rising from -PI to 0 and * falling from 0 to PI. The imaginary triangle wave leads by * 90 deg. */ case GR_TRI_WAVE: for(int i = 0; i < noutput_items; i++) { if(d_nco.get_phase() < -1*M_PI/2){ optr[i] = gr_complex(d_ampl*d_nco.get_phase()/M_PI + d_ampl, -1*d_ampl*d_nco.get_phase()/M_PI - d_ampl/2) + d_offset; } else if(d_nco.get_phase() < 0) { optr[i] = gr_complex(d_ampl*d_nco.get_phase()/M_PI + d_ampl, d_ampl*d_nco.get_phase()/M_PI + d_ampl/2) + d_offset; } else if(d_nco.get_phase() < M_PI/2) { optr[i] = gr_complex(-1*d_ampl*d_nco.get_phase()/M_PI + d_ampl, d_ampl*d_nco.get_phase()/M_PI + d_ampl/2) + d_offset; } else { optr[i] = gr_complex(-1*d_ampl*d_nco.get_phase()/M_PI + d_ampl, -1*d_ampl*d_nco.get_phase()/M_PI + 3*d_ampl/2) + d_offset; } d_nco.step(); } break; /* Implements a real saw tooth wave rising from -PI to PI. * The imaginary saw tooth wave leads by 90 deg. */ case GR_SAW_WAVE: for(int i = 0; i < noutput_items; i++) { if(d_nco.get_phase() < -1*M_PI/2) { optr[i] = gr_complex(d_ampl*d_nco.get_phase()/(2*M_PI) + d_ampl/2, d_ampl*d_nco.get_phase()/(2*M_PI) + 5*d_ampl/4) + d_offset; } else { optr[i] = gr_complex(d_ampl*d_nco.get_phase()/(2*M_PI) + d_ampl/2, d_ampl*d_nco.get_phase()/(2*M_PI) + d_ampl/4) + d_offset; } d_nco.step(); } break; #else // nope... case GR_CONST_WAVE: t = (@TYPE@)d_ampl + d_offset; std::fill_n(optr, noutput_items, t); break; case GR_SIN_WAVE: d_nco.sin(optr, noutput_items, d_ampl); if(d_offset == 0) break; for(int i = 0; i < noutput_items; i++) { optr[i] += d_offset; } break; case GR_COS_WAVE: d_nco.cos(optr, noutput_items, d_ampl); if(d_offset == 0) break; for(int i = 0; i < noutput_items; i++) { optr[i] += d_offset; } break; /* The square wave is high from -PI to 0. */ case GR_SQR_WAVE: t = (@TYPE@)d_ampl + d_offset; for(int i = 0; i < noutput_items; i++) { if(d_nco.get_phase() < 0) optr[i] = t; else optr[i] = d_offset; d_nco.step(); } break; /* The triangle wave rises from -PI to 0 and falls from 0 to PI. */ case GR_TRI_WAVE: for(int i = 0; i < noutput_items; i++) { double t = d_ampl*d_nco.get_phase()/M_PI; if (d_nco.get_phase() < 0) optr[i] = static_cast<@TYPE@>(t + d_ampl + d_offset); else optr[i] = static_cast<@TYPE@>(-1*t + d_ampl + d_offset); d_nco.step(); } break; /* The saw tooth wave rises from -PI to PI. */ case GR_SAW_WAVE: for(int i = 0; i < noutput_items; i++) { t = static_cast<@TYPE@>(d_ampl*d_nco.get_phase()/(2*M_PI) + d_ampl/2 + d_offset); optr[i] = t; d_nco.step(); } break; #endif default: throw std::runtime_error("analog::sig_source: invalid waveform"); } return noutput_items; } void @NAME@::set_sampling_freq(double sampling_freq) { d_sampling_freq = sampling_freq; d_nco.set_freq (2 * M_PI * d_frequency / d_sampling_freq); } void @NAME@::set_waveform(gr_waveform_t waveform) { d_waveform = waveform; } void @NAME@::set_frequency(double frequency) { d_frequency = frequency; d_nco.set_freq(2 * M_PI * d_frequency / d_sampling_freq); } void @NAME@::set_amplitude(double ampl) { d_ampl = ampl; } void @NAME@::set_offset(@TYPE@ offset) { d_offset = offset; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/phase_modulator_fc_impl.h0000664000175000017500000000324712207440367023004 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PHASE_MODULATOR_FC_IMPL_H #define INCLUDED_ANALOG_PHASE_MODULATOR_FC_IMPL_H #include namespace gr { namespace analog { class phase_modulator_fc_impl : public phase_modulator_fc { private: double d_sensitivity; double d_phase; public: phase_modulator_fc_impl(double sensitivity); ~phase_modulator_fc_impl(); double sensitivity() const { return d_sensitivity; } double phase() const { return d_phase; } void set_sensitivity(double s) { d_sensitivity = s; } void set_phase(double p) { d_phase = p; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PHASE_MODULATOR_FC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/fastnoise_source_X_impl.h.t0000664000175000017500000000331012237515111023232 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace analog { class @IMPL_NAME@ : public @BASE_NAME@ { private: noise_type_t d_type; float d_ampl; gr::random d_rng; std::vector<@TYPE@> d_samples; public: @IMPL_NAME@(noise_type_t type, float ampl, long seed, long samples); ~@IMPL_NAME@(); @TYPE@ sample(); @TYPE@ sample_unbiased(); void set_type(noise_type_t type); void set_amplitude(float ampl); void generate(); noise_type_t type() const { return d_type; } float amplitude() const { return d_ampl; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace filter */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-analog/lib/pll_refout_cc_impl.h0000664000175000017500000000406212207440367021762 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PLL_REFOUT_CC_IMPL_H #define INCLUDED_ANALOG_PLL_REFOUT_CC_IMPL_H #include namespace gr { namespace analog { class pll_refout_cc_impl : public pll_refout_cc { private: float mod_2pi (float in); float phase_detector(gr_complex sample, float ref_phase); public: pll_refout_cc_impl(float loop_bw, float max_freq, float min_freq); ~pll_refout_cc_impl(); void set_loop_bandwidth(float bw); void set_damping_factor(float df); void set_alpha(float alpha); void set_beta(float beta); void set_frequency(float freq); void set_phase(float phase); void set_min_freq(float freq); void set_max_freq(float freq); float get_loop_bandwidth() const; float get_damping_factor() const; float get_alpha() const; float get_beta() const; float get_frequency() const; float get_phase() const; float get_min_freq() const; float get_max_freq() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PLL_REFOUT_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/squelch_base_ff_impl.h0000664000175000017500000000363512207440367022260 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SQUELCH_BASE_FF_IMPL_H #define INCLUDED_GR_SQUELCH_BASE_FF_IMPL_H #include namespace gr { namespace analog { class squelch_base_ff_impl : public squelch_base_ff { private: int d_ramp; int d_ramped; bool d_gate; double d_envelope; enum { ST_MUTED, ST_ATTACK, ST_UNMUTED, ST_DECAY } d_state; protected: virtual void update_state(const float &sample) {}; virtual bool mute() const { return false; }; public: squelch_base_ff_impl(const char *name, int ramp, bool gate); ~squelch_base_ff_impl(); int ramp() const; void set_ramp(int ramp); bool gate() const; void set_gate(bool gate); bool unmuted() const; virtual std::vector squelch_range() const = 0; int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SQUELCH_BASE_IMPL_FF_H */ gnuradio-3.7.2.1/gr-analog/lib/agc2_cc_impl.h0000664000175000017500000000422512207440367020424 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC2_IMPL_CC_H #define INCLUDED_ANALOG_AGC2_IMPL_CC_H #include namespace gr { namespace analog { class agc2_cc_impl : public agc2_cc, kernel::agc2_cc { public: agc2_cc_impl(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0); ~agc2_cc_impl(); float attack_rate() const { return kernel::agc2_cc::attack_rate(); } float decay_rate() const { return kernel::agc2_cc::decay_rate(); } float reference() const { return kernel::agc2_cc::reference(); } float gain() const { return kernel::agc2_cc::gain(); } float max_gain() const { return kernel::agc2_cc::max_gain(); } void set_attack_rate(float rate) { kernel::agc2_cc::set_attack_rate(rate); } void set_decay_rate(float rate) { kernel::agc2_cc::set_decay_rate(rate); } void set_reference(float reference) { kernel::agc2_cc::set_reference(reference); } void set_gain(float gain) { kernel::agc2_cc::set_gain(gain); } void set_max_gain(float max_gain) { kernel::agc2_cc::set_max_gain(max_gain); } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC2_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/probe_avg_mag_sqrd_c_impl.h0000664000175000017500000000350512207440367023266 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_C_IMPL_H #define INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_C_IMPL_H #include #include namespace gr { namespace analog { class probe_avg_mag_sqrd_c_impl : public probe_avg_mag_sqrd_c { private: double d_threshold; bool d_unmuted; double d_level; filter::single_pole_iir d_iir; public: probe_avg_mag_sqrd_c_impl(double threshold_db, double alpha = 0.0001); ~probe_avg_mag_sqrd_c_impl(); bool unmuted() const { return d_unmuted; } double level() const { return d_level; } double threshold() const; void set_alpha(double alpha); void set_threshold(double decibels); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_C_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/pll_carriertracking_cc_impl.cc0000664000175000017500000001275212207440367023773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pll_carriertracking_cc_impl.h" #include #include #include #include namespace gr { namespace analog { #ifndef M_TWOPI #define M_TWOPI (2.0f*M_PI) #endif pll_carriertracking_cc::sptr pll_carriertracking_cc::make(float loop_bw, float max_freq, float min_freq) { return gnuradio::get_initial_sptr (new pll_carriertracking_cc_impl(loop_bw, max_freq, min_freq)); } pll_carriertracking_cc_impl::pll_carriertracking_cc_impl(float loop_bw, float max_freq, float min_freq) : sync_block("pll_carriertracking_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), blocks::control_loop(loop_bw, max_freq, min_freq), d_locksig(0), d_lock_threshold(0), d_squelch_enable(false) { } pll_carriertracking_cc_impl::~pll_carriertracking_cc_impl() { } float pll_carriertracking_cc_impl::mod_2pi(float in) { if(in>M_PI) return in-M_TWOPI; else if(in<-M_PI) return in+M_TWOPI; else return in; } float pll_carriertracking_cc_impl::phase_detector(gr_complex sample, float ref_phase) { float sample_phase; // sample_phase = atan2(sample.imag(),sample.real()); sample_phase = gr::fast_atan2f(sample.imag(),sample.real()); return mod_2pi(sample_phase-ref_phase); } bool pll_carriertracking_cc_impl::lock_detector(void) { return (fabsf(d_locksig) > d_lock_threshold); } bool pll_carriertracking_cc_impl::squelch_enable(bool set_squelch) { return d_squelch_enable = set_squelch; } float pll_carriertracking_cc_impl::set_lock_threshold(float threshold) { return d_lock_threshold = threshold; } int pll_carriertracking_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *iptr = (gr_complex*)input_items[0]; gr_complex *optr = (gr_complex*)output_items[0]; float error; float t_imag, t_real; for(int i = 0; i < noutput_items; i++) { gr::sincosf(d_phase, &t_imag, &t_real); optr[i] = iptr[i] * gr_complex(t_real, -t_imag); error = phase_detector(iptr[i], d_phase); advance_loop(error); phase_wrap(); frequency_limit(); d_locksig = d_locksig * (1.0 - d_alpha) + \ d_alpha*(iptr[i].real() * t_real + iptr[i].imag() * t_imag); if((d_squelch_enable) && !lock_detector()) optr[i] = 0; } return noutput_items; } void pll_carriertracking_cc_impl::set_loop_bandwidth(float bw) { blocks::control_loop::set_loop_bandwidth(bw); } void pll_carriertracking_cc_impl::set_damping_factor(float df) { blocks::control_loop::set_damping_factor(df); } void pll_carriertracking_cc_impl::set_alpha(float alpha) { blocks::control_loop::set_alpha(alpha); } void pll_carriertracking_cc_impl::set_beta(float beta) { blocks::control_loop::set_beta(beta); } void pll_carriertracking_cc_impl::set_frequency(float freq) { blocks::control_loop::set_frequency(freq); } void pll_carriertracking_cc_impl::set_phase(float phase) { blocks::control_loop::set_phase(phase); } void pll_carriertracking_cc_impl::set_min_freq(float freq) { blocks::control_loop::set_min_freq(freq); } void pll_carriertracking_cc_impl::set_max_freq(float freq) { blocks::control_loop::set_max_freq(freq); } float pll_carriertracking_cc_impl::get_loop_bandwidth() const { return blocks::control_loop::get_loop_bandwidth(); } float pll_carriertracking_cc_impl::get_damping_factor() const { return blocks::control_loop::get_damping_factor(); } float pll_carriertracking_cc_impl::get_alpha() const { return blocks::control_loop::get_alpha(); } float pll_carriertracking_cc_impl::get_beta() const { return blocks::control_loop::get_beta(); } float pll_carriertracking_cc_impl::get_frequency() const { return blocks::control_loop::get_frequency(); } float pll_carriertracking_cc_impl::get_phase() const { return blocks::control_loop::get_phase(); } float pll_carriertracking_cc_impl::get_min_freq() const { return blocks::control_loop::get_min_freq(); } float pll_carriertracking_cc_impl::get_max_freq() const { return blocks::control_loop::get_max_freq(); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/simple_squelch_cc_impl.cc0000664000175000017500000000546512207440367022772 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "simple_squelch_cc_impl.h" #include #include namespace gr { namespace analog { simple_squelch_cc::sptr simple_squelch_cc::make(double threshold_db, double alpha) { return gnuradio::get_initial_sptr (new simple_squelch_cc_impl(threshold_db, alpha)); } simple_squelch_cc_impl::simple_squelch_cc_impl(double threshold_db, double alpha) : sync_block("simple_squelch_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_unmuted(false), d_iir(alpha) { set_threshold(threshold_db); } simple_squelch_cc_impl::~simple_squelch_cc_impl() { } void simple_squelch_cc_impl::set_threshold(double decibels) { // convert to absolute threshold (mag squared) d_threshold = std::pow(10.0, decibels/10); } double simple_squelch_cc_impl::threshold() const { return 10 * log10(d_threshold); } void simple_squelch_cc_impl::set_alpha(double alpha) { d_iir.set_taps(alpha); } std::vector simple_squelch_cc_impl::squelch_range() const { std::vector r(3); r[0] = -50.0; // min FIXME r[1] = +50.0; // max FIXME r[2] = (r[1] - r[0]) / 100; // step size return r; } int simple_squelch_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; for(int i = 0; i < noutput_items; i++) { double mag_sqrd = in[i].real()*in[i].real() + in[i].imag()*in[i].imag(); double f = d_iir.filter(mag_sqrd); if(f >= d_threshold) out[i] = in[i]; else out[i] = 0; } d_unmuted = d_iir.prev_output() >= d_threshold; return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/agc_cc_impl.cc0000664000175000017500000000375312207440367020505 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "agc_cc_impl.h" #include #include namespace gr { namespace analog { agc_cc::sptr agc_cc::make(float rate, float reference, float gain) { return gnuradio::get_initial_sptr (new agc_cc_impl(rate, reference, gain)); } agc_cc_impl::agc_cc_impl(float rate, float reference, float gain) : sync_block("agc_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), kernel::agc_cc(rate, reference, gain, 65536) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } agc_cc_impl::~agc_cc_impl() { } int agc_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; scaleN(out, in, noutput_items); return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/ctcss_squelch_ff_impl.cc0000664000175000017500000000737512207440367022630 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctcss_squelch_ff_impl.h" namespace gr { namespace analog { static float ctcss_tones[] = { 67.0, 71.9, 74.4, 77.0, 79.7, 82.5, 85.4, 88.5, 91.5, 94.8, 97.4, 100.0, 103.5, 107.2, 110.9, 114.8, 118.8, 123.0, 127.3, 131.8, 136.5, 141.3, 146.2, 151.4, 156.7, 162.2, 167.9, 173.8, 179.9, 186.2, 192.8, 203.5, 210.7, 218.1, 225.7, 233.6, 241.8, 250.3 }; static int max_tone_index = 37; ctcss_squelch_ff::sptr ctcss_squelch_ff::make(int rate, float freq, float level, int len, int ramp, bool gate) { return gnuradio::get_initial_sptr(new ctcss_squelch_ff_impl (rate, freq, level, len, ramp, gate)); } int ctcss_squelch_ff_impl::find_tone(float freq) { for(int i = 0; i <= max_tone_index; i++) if(ctcss_tones[i] == freq) // FIXME: make almost equal return i; return -1; } ctcss_squelch_ff_impl::ctcss_squelch_ff_impl(int rate, float freq, float level, int len, int ramp, bool gate) : block("ctcss_squelch_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), squelch_base_ff_impl("ctcss_squelch_ff", ramp, gate) { d_freq = freq; d_level = level; // Default is 100 ms detection time if(len == 0) d_len = (int)(rate/10.0); else d_len = len; int i = find_tone(freq); // Non-standard tones or edge tones get 2% guard band, otherwise // guards are set at adjacent ctcss tone frequencies float f_l, f_r; if(i == -1 || i == 0) f_l = freq*0.98; else f_l = ctcss_tones[i-1]; if(i == -1 || i == max_tone_index) f_r = freq*1.02; else f_r = ctcss_tones[i+1]; d_goertzel_l = new fft::goertzel(rate, d_len, f_l); d_goertzel_c = new fft::goertzel(rate, d_len, freq); d_goertzel_r = new fft::goertzel(rate, d_len, f_r); d_mute = true; } ctcss_squelch_ff_impl::~ctcss_squelch_ff_impl() { delete d_goertzel_l; delete d_goertzel_c; delete d_goertzel_r; } std::vector ctcss_squelch_ff_impl::squelch_range() const { std::vector r(3); r[0] = 0.0; r[1] = 1.0; r[2] = (r[1]-r[0])/100; // step size return r; } void ctcss_squelch_ff_impl::update_state(const float &in) { d_goertzel_l->input(in); d_goertzel_c->input(in); d_goertzel_r->input(in); float rounder = 100000; float d_out_l, d_out_c, d_out_r; if(d_goertzel_c->ready()) { d_out_l = floor(rounder*abs(d_goertzel_l->output()))/rounder; d_out_c = floor(rounder*abs(d_goertzel_c->output()))/rounder; d_out_r = floor(rounder*abs(d_goertzel_r->output()))/rounder; //printf("d_out_l=%f d_out_c=%f d_out_r=%f\n", d_out_l, d_out_c, d_out_r); d_mute = (d_out_c < d_level || d_out_c < d_out_l || d_out_c < d_out_r); } } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/squelch_base_cc_impl.cc0000664000175000017500000000667012207440367022412 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "squelch_base_cc_impl.h" #include namespace gr { namespace analog { squelch_base_cc_impl::squelch_base_cc_impl(const char *name, int ramp, bool gate) : block(name, io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))) { set_ramp(ramp); set_gate(gate); d_state = ST_MUTED; d_envelope = d_ramp ? 0.0 : 1.0; d_ramped = 0; } squelch_base_cc_impl::~squelch_base_cc_impl() { } int squelch_base_cc_impl::ramp() const { return d_ramp; } void squelch_base_cc_impl::set_ramp(int ramp) { d_ramp = ramp; } bool squelch_base_cc_impl::gate() const { return d_gate; } void squelch_base_cc_impl::set_gate(bool gate) { d_gate = gate; } bool squelch_base_cc_impl::unmuted() const { return (d_state == ST_UNMUTED || d_state == ST_ATTACK); } int squelch_base_cc_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; int j = 0; for(int i = 0; i < noutput_items; i++) { update_state(in[i]); // Adjust envelope based on current state switch(d_state) { case ST_MUTED: if(!mute()) { d_state = d_ramp ? ST_ATTACK : ST_UNMUTED; // If not ramping, go straight to unmuted } break; case ST_UNMUTED: if(mute()) { d_state = d_ramp ? ST_DECAY : ST_MUTED; // If not ramping, go straight to muted } break; case ST_ATTACK: d_envelope = 0.5-std::cos(M_PI*(++d_ramped)/d_ramp)/2.0; // FIXME: precalculate window for speed if(d_ramped >= d_ramp) { // use >= in case d_ramp is set to lower value elsewhere d_state = ST_UNMUTED; d_envelope = 1.0; } break; case ST_DECAY: d_envelope = 0.5-std::cos(M_PI*(--d_ramped)/d_ramp)/2.0; // FIXME: precalculate window for speed if(d_ramped == 0.0) { d_state = ST_MUTED; } break; }; // If unmuted, copy input times envelope to output // Otherwise, if not gating, copy zero to output if(d_state != ST_MUTED) { out[j++] = in[i]*gr_complex(d_envelope, 0.0); } else { if(!d_gate) { out[j++] = 0.0; } } } consume_each(noutput_items); // Use all the inputs return j; // But only report outputs copied } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/agc2_cc_impl.cc0000664000175000017500000000414612207440367020564 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "agc2_cc_impl.h" #include #include namespace gr { namespace analog { agc2_cc::sptr agc2_cc::make(float attack_rate, float decay_rate, float reference, float gain) { return gnuradio::get_initial_sptr (new agc2_cc_impl(attack_rate, decay_rate, reference, gain)); } agc2_cc_impl::agc2_cc_impl(float attack_rate, float decay_rate, float reference, float gain) : sync_block("agc2_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), kernel::agc2_cc(attack_rate, decay_rate, reference, gain, 65536) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } agc2_cc_impl::~agc2_cc_impl() { } int agc2_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; scaleN(out, in, noutput_items); return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/rail_ff_impl.cc0000664000175000017500000000422012207440367020676 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "rail_ff_impl.h" #include #include namespace gr { namespace analog { rail_ff::sptr rail_ff::make(float lo, float hi) { return gnuradio::get_initial_sptr (new rail_ff_impl(lo, hi)); } rail_ff_impl::rail_ff_impl(float lo, float hi) : sync_block("rail_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), d_lo(lo), d_hi(hi) { set_clipping(); } rail_ff_impl::~rail_ff_impl() { } void rail_ff_impl::set_lo(float lo) { d_lo = lo; set_clipping(); } void rail_ff_impl::set_hi(float hi) { d_hi = hi; set_clipping(); } void rail_ff_impl::set_clipping() { d_mid = (d_lo + d_hi)/2; d_clip = d_hi - d_mid; } int rail_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = d_mid + gr::branchless_clip(in[i] - d_mid, d_clip); } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/dpll_bb_impl.h0000664000175000017500000000345612207440367020546 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_DPLL_BB_IMPL_H #define INCLUDED_ANALOG_DPLL_BB_IMPL_H #include namespace gr { namespace analog { class dpll_bb_impl : public dpll_bb { private: unsigned char d_restart; float d_pulse_phase, d_pulse_frequency; float d_gain, d_decision_threshold; public: dpll_bb_impl(float period, float gain); ~dpll_bb_impl(); void set_gain(float gain) { d_gain = gain; } void set_decision_threshold(float thresh) { d_decision_threshold = thresh; } float gain() const { return d_gain; } float freq() const { return d_pulse_frequency; } float phase() const { return d_pulse_phase; } float decision_threshold() const { return d_decision_threshold; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_DPLL_BB_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/squelch_base_ff_impl.cc0000664000175000017500000000660712207440367022420 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "squelch_base_ff_impl.h" #include namespace gr { namespace analog { squelch_base_ff_impl::squelch_base_ff_impl(const char *name, int ramp, bool gate) : block(name, io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))) { set_ramp(ramp); set_gate(gate); d_state = ST_MUTED; d_envelope = d_ramp ? 0.0 : 1.0; d_ramped = 0; } squelch_base_ff_impl::~squelch_base_ff_impl() { } int squelch_base_ff_impl::ramp() const { return d_ramp; } void squelch_base_ff_impl::set_ramp(int ramp) { d_ramp = ramp; } bool squelch_base_ff_impl::gate() const { return d_gate; } void squelch_base_ff_impl::set_gate(bool gate) { d_gate = gate; } bool squelch_base_ff_impl::unmuted() const { return (d_state == ST_UNMUTED || d_state == ST_ATTACK); } int squelch_base_ff_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; int j = 0; for(int i = 0; i < noutput_items; i++) { update_state(in[i]); // Adjust envelope based on current state switch(d_state) { case ST_MUTED: if(!mute()) // If not ramping, go straight to unmuted d_state = d_ramp ? ST_ATTACK : ST_UNMUTED; break; case ST_UNMUTED: if(mute()) // If not ramping, go straight to muted d_state = d_ramp ? ST_DECAY : ST_MUTED; break; case ST_ATTACK: // FIXME: precalculate window for speed d_envelope = 0.5-std::cos(M_PI*(++d_ramped)/d_ramp)/2.0; // use >= in case d_ramp is set to lower value elsewhere if(d_ramped >= d_ramp) { d_state = ST_UNMUTED; d_envelope = 1.0; } break; case ST_DECAY: // FIXME: precalculate window for speed d_envelope = 0.5-std::cos(M_PI*(--d_ramped)/d_ramp)/2.0; if(d_ramped == 0.0) d_state = ST_MUTED; break; }; // If unmuted, copy input times envelope to output // Otherwise, if not gating, copy zero to output if(d_state != ST_MUTED) out[j++] = in[i]*d_envelope; else if(!d_gate) out[j++] = 0.0; } consume_each(noutput_items); // Use all the inputs return j; // But only report outputs copied } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/qa_analog.h0000664000175000017500000000222412207440367020041 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_GR_ANALOG_H_ #define _QA_GR_ANALOG_H_ #include #include //! collect all the tests for the gr-analog directory class __GR_ATTR_EXPORT qa_gr_analog { public: //! return suite of tests for all of gr-analog directory static CppUnit::TestSuite *suite(); }; #endif /* _QA_GR_ANALOG_H_ */ gnuradio-3.7.2.1/gr-analog/lib/feedforward_agc_cc_impl.cc0000664000175000017500000000542012207440367023046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "feedforward_agc_cc_impl.h" #include #include namespace gr { namespace analog { feedforward_agc_cc::sptr feedforward_agc_cc::make(int nsamples, float reference) { return gnuradio::get_initial_sptr (new feedforward_agc_cc_impl(nsamples, reference)); } feedforward_agc_cc_impl::feedforward_agc_cc_impl(int nsamples, float reference) : sync_block("feedforward_agc_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_nsamples(nsamples), d_reference(reference) { if(nsamples < 1) throw std::invalid_argument("feedforward_agc_cc_impl: nsamples must be >= 1"); set_history(nsamples); } feedforward_agc_cc_impl::~feedforward_agc_cc_impl() { } inline static float mag_squared(gr_complex x) { return x.real() * x.real() + x.imag() * x.imag(); } // approximate sqrt(x^2 + y^2) inline static float envelope(gr_complex x) { float r_abs = std::fabs(x.real()); float i_abs = std::fabs(x.imag()); if(r_abs > i_abs) return r_abs + 0.4 * i_abs; else return i_abs + 0.4 * r_abs; } int feedforward_agc_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; int nsamples = d_nsamples; float gain; for(int i = 0; i < noutput_items; i++) { //float max_env = 1e-12; // avoid divide by zero float max_env = 1e-4; // avoid divide by zero, indirectly set max gain for(int j = 0; j < nsamples; j++) { max_env = std::max(max_env, envelope(in[i+j])); } gain = d_reference / max_env; out[i] = gain * in[i]; } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/agc3_cc_impl.cc0000664000175000017500000001115712237515111020556 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "agc3_cc_impl.h" #include #include namespace gr { namespace analog { agc3_cc::sptr agc3_cc::make(float attack_rate, float decay_rate, float reference, float gain, int iir_update_decim) { return gnuradio::get_initial_sptr (new agc3_cc_impl(attack_rate, decay_rate, reference, gain, iir_update_decim)); } agc3_cc_impl::agc3_cc_impl(float attack_rate, float decay_rate, float reference, float gain, int iir_update_decim) : sync_block("agc3_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_attack(attack_rate), d_decay(decay_rate), d_reference(reference), d_gain(gain), d_max_gain(65536), d_reset(true), d_iir_update_decim(iir_update_decim) { set_output_multiple(iir_update_decim*4); const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } agc3_cc_impl::~agc3_cc_impl() { } int agc3_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; #ifdef __GNUC__ // Compute a linear average on reset (no expected) if(__builtin_expect(d_reset, false)) { float mags[noutput_items] __attribute__ ((aligned (16))); volk_32fc_magnitude_32f(mags, &in[0], noutput_items); #else // Compute a linear average on reset (no expected) if(!d_reset) { std::vector mags(noutput_items); volk_32fc_magnitude_32f(&mags[0], &in[0], noutput_items); #endif float mag(0.0); for(int i=0; i 0.0 && d_gain > d_max_gain) { d_gain = d_max_gain; } // scale output values for(int i=0; i mag_sq(noutput_items/d_iir_update_decim); std::vector inv_mag(noutput_items/d_iir_update_decim); #else float mag_sq[noutput_items/d_iir_update_decim] __attribute__ ((aligned (16))); float inv_mag[noutput_items/d_iir_update_decim] __attribute__ ((aligned (16))); #endif // generate squared magnitudes at decimated rate (gather operation) for(int i=0; i d_gain/d_reference)?d_decay:d_attack; d_gain = d_gain*(1-rate) + d_reference*magi*rate; } else { d_gain = d_gain*(1-d_decay); } for(int j=i*d_iir_update_decim; j<(i+1)*d_iir_update_decim; j++){ out[j] = in[j] * d_gain; } } } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/agc_cc_impl.h0000664000175000017500000000363612207440367020347 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC_CC_IMPL_H #define INCLUDED_ANALOG_AGC_CC_IMPL_H #include namespace gr { namespace analog { class agc_cc_impl : public agc_cc, kernel::agc_cc { public: agc_cc_impl(float rate = 1e-4, float reference = 1.0, float gain = 1.0); ~agc_cc_impl(); float rate() const { return kernel::agc_cc::rate(); } float reference() const { return kernel::agc_cc::reference(); } float gain() const { return kernel::agc_cc::gain(); } float max_gain() const { return kernel::agc_cc::max_gain(); } void set_rate(float rate) { kernel::agc_cc::set_rate(rate); } void set_reference(float reference) { kernel::agc_cc::set_reference(reference); } void set_gain(float gain) { kernel::agc_cc::set_gain(gain); } void set_max_gain(float max_gain) { kernel::agc_cc::set_max_gain(max_gain); } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/quadrature_demod_cf_impl.h0000664000175000017500000000302012207440367023130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_QUADRATURE_DEMOD_CF_IMPL_H #define INCLUDED_ANALOG_QUADRATURE_DEMOD_CF_IMPL_H #include namespace gr { namespace analog { class quadrature_demod_cf_impl : public quadrature_demod_cf { private: float d_gain; public: quadrature_demod_cf_impl(float gain); ~quadrature_demod_cf_impl(); void set_gain(float gain) { d_gain = gain; } float gain() const { return d_gain; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_QUADRATURE_DEMOD_CF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/frequency_modulator_fc_impl.h0000664000175000017500000000315612207440367023704 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_FREQUENCY_MODULATOR_FC_IMPL_H #define INCLUDED_ANALOG_FREQUENCY_MODULATOR_FC_IMPL_H #include namespace gr { namespace analog { class frequency_modulator_fc_impl : public frequency_modulator_fc { private: float d_sensitivity; float d_phase; public: frequency_modulator_fc_impl(double sensitivity); ~frequency_modulator_fc_impl(); void set_sensitivity(float sens) { d_sensitivity = sens; } float sensitivity() const { return d_sensitivity; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_FREQUENCY_MODULATOR_FC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/quadrature_demod_cf_impl.cc0000664000175000017500000000442312207440367023276 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "quadrature_demod_cf_impl.h" #include #include #include namespace gr { namespace analog { quadrature_demod_cf::sptr quadrature_demod_cf::make(float gain) { return gnuradio::get_initial_sptr (new quadrature_demod_cf_impl(gain)); } quadrature_demod_cf_impl::quadrature_demod_cf_impl(float gain) : sync_block("quadrature_demod_cf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(float))), d_gain(gain) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); set_history(2); // we need to look at the previous value } quadrature_demod_cf_impl::~quadrature_demod_cf_impl() { } int quadrature_demod_cf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex*)input_items[0]; float *out = (float*)output_items[0]; std::vector tmp(noutput_items); volk_32fc_x2_multiply_conjugate_32fc(&tmp[0], &in[1], &in[0], noutput_items); for(int i = 0; i < noutput_items; i++) { out[i] = d_gain * gr::fast_atan2f(imag(tmp[i]), real(tmp[i])); } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/pwr_squelch_ff_impl.h0000664000175000017500000000506012207440367022150 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PWR_SQUELCH_FF_IMPL_H #define INCLUDED_ANALOG_PWR_SQUELCH_FF_IMPL_H #include #include "squelch_base_ff_impl.h" #include #include namespace gr { namespace analog { class ANALOG_API pwr_squelch_ff_impl : public pwr_squelch_ff, squelch_base_ff_impl { private: double d_threshold; double d_pwr; filter::single_pole_iir d_iir; protected: virtual void update_state(const float &in); virtual bool mute() const { return d_pwr < d_threshold; } public: pwr_squelch_ff_impl(double db, double alpha=0.0001, int ramp=0, bool gate=false); ~pwr_squelch_ff_impl(); std::vector squelch_range() const; double threshold() const { return 10*log10(d_threshold); } void set_threshold(double db) { d_threshold = std::pow(10.0, db/10); } void set_alpha(double alpha) { d_iir.set_taps(alpha); } int ramp() const { return squelch_base_ff_impl::ramp(); } void set_ramp(int ramp) { squelch_base_ff_impl::set_ramp(ramp); } bool gate() const { return squelch_base_ff_impl::gate(); } void set_gate(bool gate) { squelch_base_ff_impl::set_gate(gate); } bool unmuted() const { return squelch_base_ff_impl::unmuted(); } int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { return squelch_base_ff_impl::general_work(noutput_items, ninput_items, input_items, output_items); } }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PWR_SQUELCH_FF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/frequency_modulator_fc_impl.cc0000664000175000017500000000450112207440367024035 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "frequency_modulator_fc_impl.h" #include #include #include #include namespace gr { namespace analog { frequency_modulator_fc::sptr frequency_modulator_fc::make(double sensitivity) { return gnuradio::get_initial_sptr (new frequency_modulator_fc_impl(sensitivity)); } frequency_modulator_fc_impl::frequency_modulator_fc_impl(double sensitivity) : sync_block("frequency_modulator_fc", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))), d_sensitivity(sensitivity), d_phase(0) { } frequency_modulator_fc_impl::~frequency_modulator_fc_impl() { } int frequency_modulator_fc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; for(int i = 0; i < noutput_items; i++) { d_phase = d_phase + d_sensitivity * in[i]; while(d_phase > (float)(M_PI)) d_phase -= (float)(2.0 * M_PI); while(d_phase < (float)(-M_PI)) d_phase += (float)(2.0 * M_PI); float oi, oq; gr_int32 angle = gr::fxpt::float_to_fixed (d_phase); gr::fxpt::sincos(angle, &oq, &oi); out[i] = gr_complex(oi, oq); } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/noise_source_X_impl.cc.t0000664000175000017500000000604012207440367022524 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include #endif #include "@IMPL_NAME@.h" #include #include namespace gr { namespace analog { @BASE_NAME@::sptr @BASE_NAME@::make(noise_type_t type, float ampl, long seed) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(type, ampl, seed)); } @IMPL_NAME@::@IMPL_NAME@(noise_type_t type, float ampl, long seed) : sync_block("@BASE_NAME@", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(@TYPE@))), d_type(type), d_ampl(ampl), d_rng(seed) { } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_type(noise_type_t type) { gr::thread::scoped_lock l(d_setlock); d_type = type; } void @IMPL_NAME@::set_amplitude(float ampl) { gr::thread::scoped_lock l(d_setlock); d_ampl = ampl; } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_setlock); @TYPE@ *out = (@TYPE@*)output_items[0]; switch(d_type) { #if @IS_COMPLEX@ // complex? case GR_UNIFORM: for(int i = 0; i < noutput_items; i++) { out[i] = gr_complex(d_ampl * ((d_rng.ran1() * 2.0) - 1.0), d_ampl * ((d_rng.ran1() * 2.0) - 1.0)); } break; case GR_GAUSSIAN: for(int i = 0; i < noutput_items; i++) { out[i] = d_ampl * d_rng.rayleigh_complex(); } break; #else // nope... case GR_UNIFORM: for(int i = 0; i < noutput_items; i++) { out[i] = (@TYPE@)(d_ampl * ((d_rng.ran1() * 2.0) - 1.0)); } break; case GR_GAUSSIAN: for(int i = 0; i < noutput_items; i++) { out[i] = (@TYPE@)(d_ampl * d_rng.gasdev()); } break; case GR_LAPLACIAN: for(int i = 0; i < noutput_items; i++) { out[i] = (@TYPE@)(d_ampl * d_rng.laplacian()); } break; case GR_IMPULSE: // FIXME changeable impulse settings for(int i = 0; i < noutput_items; i++) { out[i] = (@TYPE@)(d_ampl * d_rng.impulse(9)); } break; #endif default: throw std::runtime_error("invalid type"); } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/ctcss_squelch_ff_impl.h0000664000175000017500000000507412207440367022464 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_CTCSS_SQUELCH_FF_IMPL_H #define INCLUDED_ANALOG_CTCSS_SQUELCH_FF_IMPL_H #include "squelch_base_ff_impl.h" #include #include namespace gr { namespace analog { class ctcss_squelch_ff_impl : public ctcss_squelch_ff, squelch_base_ff_impl { private: float d_freq; float d_level; int d_len; bool d_mute; fft::goertzel *d_goertzel_l; fft::goertzel *d_goertzel_c; fft::goertzel *d_goertzel_r; int find_tone(float freq); protected: virtual void update_state(const float &in); virtual bool mute() const { return d_mute; } public: ctcss_squelch_ff_impl(int rate, float freq, float level, int len, int ramp, bool gate); ~ctcss_squelch_ff_impl(); std::vector squelch_range() const; float level() const { return d_level; } void set_level(float level) { d_level = level; } int len() const { return d_len; } int ramp() const { return squelch_base_ff_impl::ramp(); } void set_ramp(int ramp) { squelch_base_ff_impl::set_ramp(ramp); } bool gate() const { return squelch_base_ff_impl::gate(); } void set_gate(bool gate) { squelch_base_ff_impl::set_gate(gate); } bool unmuted() const { return squelch_base_ff_impl::unmuted(); } int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { return squelch_base_ff_impl::general_work(noutput_items, ninput_items, input_items, output_items); } }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_CTCSS_SQUELCH_FF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/pwr_squelch_cc_impl.h0000664000175000017500000000506512207440367022147 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PWR_SQUELCH_CC_IMPL_H #define INCLUDED_ANALOG_PWR_SQUELCH_CC_IMPL_H #include #include "squelch_base_cc_impl.h" #include #include namespace gr { namespace analog { class ANALOG_API pwr_squelch_cc_impl : public pwr_squelch_cc, squelch_base_cc_impl { private: double d_threshold; double d_pwr; filter::single_pole_iir d_iir; protected: virtual void update_state(const gr_complex &in); virtual bool mute() const { return d_pwr < d_threshold; } public: pwr_squelch_cc_impl(double db, double alpha=0.0001, int ramp=0, bool gate=false); ~pwr_squelch_cc_impl(); std::vector squelch_range() const; double threshold() const { return 10*log10(d_threshold); } void set_threshold(double db) { d_threshold = std::pow(10.0, db/10); } void set_alpha(double alpha) { d_iir.set_taps(alpha); } int ramp() const { return squelch_base_cc_impl::ramp(); } void set_ramp(int ramp) { squelch_base_cc_impl::set_ramp(ramp); } bool gate() const { return squelch_base_cc_impl::gate(); } void set_gate(bool gate) { squelch_base_cc_impl::set_gate(gate); } bool unmuted() const { return squelch_base_cc_impl::unmuted(); } int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { return squelch_base_cc_impl::general_work(noutput_items, ninput_items, input_items, output_items); } }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PWR_SQUELCH_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/squelch_base_cc_impl.h0000664000175000017500000000364212207440367022250 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SQUELCH_BASE_CC_IMPL_H #define INCLUDED_GR_SQUELCH_BASE_CC_IMPL_H #include namespace gr { namespace analog { class squelch_base_cc_impl : public squelch_base_cc { private: int d_ramp; int d_ramped; bool d_gate; double d_envelope; enum { ST_MUTED, ST_ATTACK, ST_UNMUTED, ST_DECAY } d_state; protected: virtual void update_state(const gr_complex &sample) {}; virtual bool mute() const { return false; }; public: squelch_base_cc_impl(const char *name, int ramp, bool gate); ~squelch_base_cc_impl(); int ramp() const; void set_ramp(int ramp); bool gate() const; void set_gate(bool gate); bool unmuted() const; virtual std::vector squelch_range() const = 0; int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SQUELCH_BASE_IMPL_FF_H */ gnuradio-3.7.2.1/gr-analog/lib/fastnoise_source_X_impl.cc.t0000664000175000017500000000775112237515111023405 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include #endif #include "@IMPL_NAME@.h" #include #include namespace gr { namespace analog { @BASE_NAME@::sptr @BASE_NAME@::make(noise_type_t type, float ampl, long seed, long samples) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(type, ampl, seed, samples)); } @IMPL_NAME@::@IMPL_NAME@(noise_type_t type, float ampl, long seed, long samples) : sync_block("@BASE_NAME@", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(@TYPE@))), d_type(type), d_ampl(ampl), d_rng(seed) { d_samples.resize(samples); generate(); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_type(noise_type_t type) { gr::thread::scoped_lock l(d_setlock); d_type = type; generate(); } void @IMPL_NAME@::set_amplitude(float ampl) { gr::thread::scoped_lock l(d_setlock); d_ampl = ampl; generate(); } void @IMPL_NAME@::generate() { int noutput_items = d_samples.size(); switch(d_type){ #if @IS_COMPLEX@ // complex? case GR_UNIFORM: for(int i = 0; i < noutput_items; i++) d_samples[i] = gr_complex(d_ampl * ((d_rng.ran1() * 2.0) - 1.0), d_ampl * ((d_rng.ran1() * 2.0) - 1.0)); break; case GR_GAUSSIAN: for(int i = 0; i < noutput_items; i++) d_samples[i] = d_ampl * d_rng.rayleigh_complex(); break; #else // nope... case GR_UNIFORM: for(int i = 0; i < noutput_items; i++) d_samples[i] = (@TYPE@)(d_ampl * ((d_rng.ran1() * 2.0) - 1.0)); break; case GR_GAUSSIAN: for(int i = 0; i < noutput_items; i++) d_samples[i] = (@TYPE@)(d_ampl * d_rng.gasdev()); break; case GR_LAPLACIAN: for(int i = 0; i < noutput_items; i++) d_samples[i] = (@TYPE@)(d_ampl * d_rng.laplacian()); break; case GR_IMPULSE: // FIXME changeable impulse settings for(int i = 0; i < noutput_items; i++) d_samples[i] = (@TYPE@)(d_ampl * d_rng.impulse(9)); break; #endif default: throw std::runtime_error("invalid type"); } } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_setlock); @TYPE@ *out = (@TYPE@*)output_items[0]; for(int i=0; i pwr_squelch_ff_impl::squelch_range() const { std::vector r(3); r[0] = -50.0; // min FIXME r[1] = +50.0; // max FIXME r[2] = (r[1] - r[0]) / 100; // step size return r; } void pwr_squelch_ff_impl::update_state(const float &in) { d_pwr = d_iir.filter(in*in); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/agc2_ff_impl.h0000664000175000017500000000421512207440367020431 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC2_FF_IMPL_H #define INCLUDED_ANALOG_AGC2_FF_IMPL_H #include namespace gr { namespace analog { class agc2_ff_impl : public agc2_ff, kernel::agc2_ff { public: agc2_ff_impl(float attack_rate = 1e-1, float decay_rate = 1e-2, float reference = 1.0, float gain = 1.0); ~agc2_ff_impl(); float attack_rate() const { return kernel::agc2_ff::attack_rate(); } float decay_rate() const { return kernel::agc2_ff::decay_rate(); } float reference() const { return kernel::agc2_ff::reference(); } float gain() const { return kernel::agc2_ff::gain(); } float max_gain() const { return kernel::agc2_ff::max_gain(); } void set_attack_rate(float rate) { kernel::agc2_ff::set_attack_rate(rate); } void set_decay_rate(float rate) { kernel::agc2_ff::set_decay_rate(rate); } void set_reference(float reference) { kernel::agc2_ff::set_reference(reference); } void set_gain(float gain) { kernel::agc2_ff::set_gain(gain); } void set_max_gain(float max_gain) { kernel::agc2_ff::set_max_gain(max_gain); } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC2_IMPL_FF_H */ gnuradio-3.7.2.1/gr-analog/lib/qa_analog.cc0000664000175000017500000000213312207440367020176 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This class gathers together all the test cases for the gr-analog * directory into a single test suite. As you create new test cases, * add them here. */ #include CppUnit::TestSuite * qa_gr_analog::suite() { CppUnit::TestSuite *s = new CppUnit::TestSuite("gr-analog"); return s; } gnuradio-3.7.2.1/gr-analog/lib/fmdet_cf_impl.h0000664000175000017500000000362612207440367020716 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008, 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_FMDET_CF_IMPL_H #define INCLUDED_ANALOG_FMDET_CF_IMPL_H #include //#include #include namespace gr { namespace analog { class fmdet_cf_impl : public fmdet_cf { private: gr_complex d_S1, d_S2, d_S3, d_S4; float d_freq, d_freqlo, d_freqhi, d_scl, d_bias; //kernel::fir_filter_ccf* d_filter; public: fmdet_cf_impl(float samplerate, float freq_low, float freq_high, float scl); ~fmdet_cf_impl(); void set_scale(float scl); void set_freq_range(float freq_low, float freq_high); float freq() const { return d_freq; } float freq_high() const { return d_freqhi; } float freq_low() const { return d_freqlo; } float scale() const { return d_scl; } float bias() const { return d_bias; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_FMDET_CF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/probe_avg_mag_sqrd_cf_impl.cc0000664000175000017500000000523712207440367023576 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "probe_avg_mag_sqrd_cf_impl.h" #include #include namespace gr { namespace analog { probe_avg_mag_sqrd_cf::sptr probe_avg_mag_sqrd_cf::make(double threshold_db, double alpha) { return gnuradio::get_initial_sptr (new probe_avg_mag_sqrd_cf_impl(threshold_db, alpha)); } probe_avg_mag_sqrd_cf_impl::probe_avg_mag_sqrd_cf_impl(double threshold_db, double alpha) : sync_block("probe_avg_mag_sqrd_cf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(float))), d_unmuted(false), d_level(0), d_iir(alpha) { set_threshold(threshold_db); } probe_avg_mag_sqrd_cf_impl::~probe_avg_mag_sqrd_cf_impl() { } int probe_avg_mag_sqrd_cf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; float *out = (float*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = d_iir.prev_output(); double mag_sqrd = in[i].real()*in[i].real() + in[i].imag()*in[i].imag(); d_iir.filter(mag_sqrd); // computed for side effect: prev_output() } d_unmuted = d_iir.prev_output() >= d_threshold; d_level = d_iir.prev_output(); return noutput_items; } double probe_avg_mag_sqrd_cf_impl::threshold() const { return 10 * std::log10(d_threshold); } void probe_avg_mag_sqrd_cf_impl::set_threshold(double decibels) { // convert to absolute threshold (mag squared) d_threshold = std::pow(10.0, decibels/10); } void probe_avg_mag_sqrd_cf_impl::set_alpha(double alpha) { d_iir.set_taps(alpha); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/cpm.cc0000664000175000017500000001464612207440367017047 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // Calculate the taps for the CPM phase responses #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include //gives us erf on compilers without it #include namespace bm = boost::math; namespace gr { namespace analog { #ifndef M_TWOPI # define M_TWOPI (2*M_PI) #endif //! Normalised sinc function, sinc(x)=sin(pi*x)/pi*x inline double sinc(double x) { if(x == 0) { return 1.0; } return sin(M_PI * x) / (M_PI * x); } //! Taps for L-RC CPM (Raised cosine of length L symbols) std::vector generate_cpm_lrc_taps(unsigned samples_per_sym, unsigned L) { std::vector taps(samples_per_sym * L, 1.0/L/samples_per_sym); for(unsigned i = 0; i < samples_per_sym * L; i++) { taps[i] *= 1 - cos(M_TWOPI * i / L / samples_per_sym); } return taps; } /*! Taps for L-SRC CPM (Spectral raised cosine of length L symbols). * * L-SRC has a time-continuous phase response function of * * g(t) = 1/LT * sinc(2t/LT) * cos(beta * 2pi t / LT) / (1 - (4beta / LT * t)^2) * * which is the Fourier transform of a cos-rolloff function with rolloff * beta, and looks like a sinc-function, multiplied with a rolloff term. * We return the main lobe of the sinc, i.e., everything between the * zero crossings. * The time-discrete IR is thus * * g(k) = 1/Ls * sinc(2k/Ls) * cos(beta * pi k / Ls) / (1 - (4beta / Ls * k)^2) * where k = 0...Ls-1 * and s = samples per symbol. */ std::vector generate_cpm_lsrc_taps(unsigned samples_per_sym, unsigned L, double beta) { double Ls = (double) L * samples_per_sym; std::vector taps_d(L * samples_per_sym, 0.0); std::vector taps(L * samples_per_sym, 0.0); double sum = 0; for(unsigned i = 0; i < samples_per_sym * L; i++) { double k = i - Ls/2; // Causal to acausal taps_d[i] = 1.0 / Ls * sinc(2.0 * k / Ls); // For k = +/-Ls/4*beta, the rolloff term's cos-function becomes zero // and the whole thing converges to PI/4 (to prove this, use de // l'hopital's rule). if(fabs(fabs(k) - Ls/4/beta) < 2*DBL_EPSILON) { taps_d[i] *= M_PI_4; } else { double tmp = 4.0 * beta * k / Ls; taps_d[i] *= cos(beta * M_TWOPI * k / Ls) / (1 - tmp * tmp); } sum += taps_d[i]; } for(unsigned i = 0; i < samples_per_sym * L; i++) { taps[i] = (float) taps_d[i] / sum; } return taps; } //! Taps for L-REC CPM (Rectangular pulse shape of length L symbols) std::vector generate_cpm_lrec_taps(unsigned samples_per_sym, unsigned L) { return std::vector(samples_per_sym * L, 1.0/L/samples_per_sym); } //! Helper function for TFM double tfm_g0(double k, double sps) { if(fabs(k) < 2 * DBL_EPSILON) { return 1.145393004159143; // 1 + pi^2/48 / sqrt(2) } const double pi2_24 = 0.411233516712057; // pi^2/24 double f = M_PI * k / sps; return sinc(k/sps) - pi2_24 * (2 * sin(f) - 2*f*cos(f) - f*f*sin(f)) / (f*f*f); } //! Taps for TFM CPM (Tamed frequency modulation) // // See [2, Chapter 2.7.2]. // // [2]: Anderson, Aulin and Sundberg; Digital Phase Modulation std::vector generate_cpm_tfm_taps(unsigned sps, unsigned L) { unsigned causal_shift = sps * L / 2; std::vector taps_d(sps * L, 0.0); std::vector taps(sps * L, 0.0); double sum = 0; for(unsigned i = 0; i < sps * L; i++) { double k = (double)(((int)i) - ((int)causal_shift)); // Causal to acausal taps_d[i] = tfm_g0(k - sps, sps) + 2 * tfm_g0(k, sps) + tfm_g0(k + sps, sps); sum += taps_d[i]; } for(unsigned i = 0; i < sps * L; i++) { taps[i] = (float) taps_d[i] / sum; } return taps; } //! Taps for Gaussian CPM. Phase response is truncated after \p L symbols. // \p bt sets the 3dB-time-bandwidth product. // // Note: for h = 0.5, this is the phase response for GMSK. // // This C99-compatible formula for the taps is taken straight // from [1, Chapter 9.2.3]. // A version in Q-notation can be found in [2, Chapter 2.7.2]. // // [1]: Karl-Dirk Kammeyer; Nachrichtenübertragung, 4th Edition. // [2]: Anderson, Aulin and Sundberg; Digital Phase Modulation // std::vector generate_cpm_gaussian_taps(unsigned samples_per_sym, unsigned L, double bt) { double Ls = (double) L * samples_per_sym; std::vector taps_d(L * samples_per_sym, 0.0); std::vector taps(L * samples_per_sym, 0.0); // alpha = sqrt(2/ln(2)) * pi * BT double alpha = 5.336446256636997 * bt; for(unsigned i = 0; i < samples_per_sym * L; i++) { double k = i - Ls/2; // Causal to acausal taps_d[i] = (bm::erf(alpha * (k / samples_per_sym + 0.5)) - bm::erf(alpha * (k / samples_per_sym - 0.5))) * 0.5 / samples_per_sym; taps[i] = (float) taps_d[i]; } return taps; } std::vector cpm::phase_response(cpm_type type, unsigned samples_per_sym, unsigned L, double beta) { switch(type) { case LRC: return generate_cpm_lrc_taps(samples_per_sym, L); case LSRC: return generate_cpm_lsrc_taps(samples_per_sym, L, beta); case LREC: return generate_cpm_lrec_taps(samples_per_sym, L); case TFM: return generate_cpm_tfm_taps(samples_per_sym, L); case GAUSSIAN: return generate_cpm_gaussian_taps(samples_per_sym, L, beta); default: return generate_cpm_lrec_taps(samples_per_sym, 1); } } } // namespace analog } // namespace gr gnuradio-3.7.2.1/gr-analog/lib/feedforward_agc_cc_impl.h0000664000175000017500000000272212207440367022712 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_FEEDFORWARD_AGC_CC_IMPL_H #define INCLUDED_ANALOG_FEEDFORWARD_AGC_CC_IMPL_H #include namespace gr { namespace analog { class feedforward_agc_cc_impl : public feedforward_agc_cc { private: int d_nsamples; float d_reference; public: feedforward_agc_cc_impl(int nsamples, float reference); ~feedforward_agc_cc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_FEEDFORWARD_AGC_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/agc_ff_impl.h0000664000175000017500000000364312207440367020353 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_AGC_FF_IMPL_H #define INCLUDED_ANALOG_AGC_FF_IMPL_H #include namespace gr { namespace analog { class agc_ff_impl : public agc_ff, kernel::agc_ff { public: agc_ff_impl(float rate = 1e-4, float reference = 1.0, float gain = 1.0); ~agc_ff_impl(); float rate() const { return kernel::agc_ff::rate(); } float reference() const { return kernel::agc_ff::reference(); } float gain() const { return kernel::agc_ff::gain(); } float max_gain() const { return kernel::agc_ff::max_gain(); } void set_rate(float rate) { kernel::agc_ff::set_rate(rate); } void set_reference(float reference) { kernel::agc_ff::set_reference(reference); } void set_gain(float gain) { kernel::agc_ff::set_gain(gain); } void set_max_gain(float max_gain) { kernel::agc_ff::set_max_gain(max_gain); } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_AGC_FF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/pll_carriertracking_cc_impl.h0000664000175000017500000000445412207440367023635 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PLL_CARRIERTRACKING_CC_IMPL_H #define INCLUDED_ANALOG_PLL_CARRIERTRACKING_CC_IMPL_H #include namespace gr { namespace analog { class pll_carriertracking_cc_impl : public pll_carriertracking_cc { private: float d_locksig,d_lock_threshold; bool d_squelch_enable; float mod_2pi(float in); float phase_detector(gr_complex sample,float ref_phase); public: pll_carriertracking_cc_impl(float loop_bw, float max_freq, float min_freq); ~pll_carriertracking_cc_impl(); bool lock_detector(void); bool squelch_enable(bool); float set_lock_threshold(float); void set_loop_bandwidth(float bw); void set_damping_factor(float df); void set_alpha(float alpha); void set_beta(float beta); void set_frequency(float freq); void set_phase(float phase); void set_min_freq(float freq); void set_max_freq(float freq); float get_loop_bandwidth() const; float get_damping_factor() const; float get_alpha() const; float get_beta() const; float get_frequency() const; float get_phase() const; float get_min_freq() const; float get_max_freq() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PLL_CARRIERTRACKING_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/gnuradio-analog.rc.in0000664000175000017500000000332612207440367021754 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-analog" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-analog.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-analog.dll" VALUE "ProductName", "gnuradio-analog" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-analog/lib/probe_avg_mag_sqrd_cf_impl.h0000664000175000017500000000350412207440367023433 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_CF_IMPL_H #define INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_CF_IMPL_H #include #include namespace gr { namespace analog { class probe_avg_mag_sqrd_cf_impl : public probe_avg_mag_sqrd_cf { private: double d_threshold; bool d_unmuted; double d_level; filter::single_pole_iir d_iir; public: probe_avg_mag_sqrd_cf_impl(double threshold_db, double alpha); ~probe_avg_mag_sqrd_cf_impl(); bool unmuted() const { return d_unmuted; } double level() const { return d_level; } double threshold() const; void set_alpha(double alpha); void set_threshold(double decibels); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_PROBE_AVG_MAG_SQRD_CF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/cpfsk_bc_impl.cc0000664000175000017500000000435012207440367021052 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cpfsk_bc_impl.h" #include #include namespace gr { namespace analog { #define M_TWOPI (2*M_PI) cpfsk_bc::sptr cpfsk_bc::make(float k, float ampl, int samples_per_sym) { return gnuradio::get_initial_sptr (new cpfsk_bc_impl(k, ampl, samples_per_sym)); } cpfsk_bc_impl::cpfsk_bc_impl(float k, float ampl, int samples_per_sym) : sync_interpolator("cpfsk_bc", io_signature::make(1, 1, sizeof(char)), io_signature::make(1, 1, sizeof(gr_complex)), samples_per_sym) { d_samples_per_sym = samples_per_sym; d_freq = k*M_PI/samples_per_sym; d_ampl = ampl; d_phase = 0.0; } cpfsk_bc_impl::~cpfsk_bc_impl() { } int cpfsk_bc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; for(int i = 0; i < noutput_items/d_samples_per_sym; i++) { for(int j = 0; j < d_samples_per_sym; j++) { if(in[i] == 1) d_phase += d_freq; else d_phase -= d_freq; while(d_phase > M_TWOPI) d_phase -= M_TWOPI; while(d_phase < -M_TWOPI) d_phase += M_TWOPI; *out++ = gr_expj(d_phase)*d_ampl; } } return noutput_items; } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/simple_squelch_cc_impl.h0000664000175000017500000000341612207440367022626 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_SIMPLE_SQUELCH_CC_IMPL_H #define INCLUDED_ANALOG_SIMPLE_SQUELCH_CC_IMPL_H #include #include namespace gr { namespace analog { class simple_squelch_cc_impl : public simple_squelch_cc { private: double d_threshold; bool d_unmuted; filter::single_pole_iir d_iir; public: simple_squelch_cc_impl(double threshold_db, double alpha); ~simple_squelch_cc_impl(); bool unmuted() const { return d_unmuted; } void set_alpha(double alpha); void set_threshold(double decibels); double threshold() const; std::vector squelch_range() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_SIMPLE_SQUELCH_CC_IMPL_H */ gnuradio-3.7.2.1/gr-analog/lib/probe_avg_mag_sqrd_c_impl.cc0000664000175000017500000000506412207440367023426 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "probe_avg_mag_sqrd_c_impl.h" #include #include namespace gr { namespace analog { probe_avg_mag_sqrd_c::sptr probe_avg_mag_sqrd_c::make(double threshold_db, double alpha) { return gnuradio::get_initial_sptr (new probe_avg_mag_sqrd_c_impl(threshold_db, alpha)); } probe_avg_mag_sqrd_c_impl::probe_avg_mag_sqrd_c_impl(double threshold_db, double alpha) : sync_block("probe_avg_mag_sqrd_c", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_unmuted(false), d_level(0), d_iir(alpha) { set_threshold(threshold_db); } probe_avg_mag_sqrd_c_impl::~probe_avg_mag_sqrd_c_impl() { } int probe_avg_mag_sqrd_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; for(int i = 0; i < noutput_items; i++) { double mag_sqrd = in[i].real()*in[i].real() + in[i].imag()*in[i].imag(); d_iir.filter(mag_sqrd); // computed for side effect: prev_output() } d_unmuted = d_iir.prev_output() >= d_threshold; d_level = d_iir.prev_output(); return noutput_items; } double probe_avg_mag_sqrd_c_impl::threshold() const { return 10 * std::log10(d_threshold); } void probe_avg_mag_sqrd_c_impl::set_threshold(double decibels) { // convert to absolute threshold (mag squared) d_threshold = std::pow(10.0, decibels/10); } void probe_avg_mag_sqrd_c_impl::set_alpha(double alpha) { d_iir.set_taps(alpha); } } /* namespace analog */ } /* namespace gr */ gnuradio-3.7.2.1/gr-analog/lib/sig_source_X_impl.h.t0000664000175000017500000000412112207440367022031 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace analog { class @IMPL_NAME@ : public @BASE_NAME@ { private: double d_sampling_freq; gr_waveform_t d_waveform; double d_frequency; double d_ampl; @TYPE@ d_offset; gr::fxpt_nco d_nco; public: @IMPL_NAME@(double sampling_freq, gr_waveform_t waveform, double wave_freq, double ampl, @TYPE@ offset = 0); ~@IMPL_NAME@(); virtual int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); double sampling_freq() const { return d_sampling_freq; } gr_waveform_t waveform() const { return d_waveform; } double frequency() const { return d_frequency; } double amplitude() const { return d_ampl; } @TYPE@ offset() const { return d_offset; } void set_sampling_freq(double sampling_freq); void set_waveform(gr_waveform_t waveform); void set_frequency(double frequency); void set_amplitude(double ampl); void set_offset(@TYPE@ offset); }; } /* namespace analog */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-analog/lib/rail_ff_impl.h0000664000175000017500000000303712207440367020545 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ANALOG_RAIL_FF_IMPL_H #define INCLUDED_ANALOG_RAIL_FF_IMPL_H #include namespace gr { namespace analog { class rail_ff_impl : public rail_ff { private: float d_lo, d_hi; float d_mid, d_clip; void set_clipping(); public: rail_ff_impl(float lo, float hi); ~rail_ff_impl(); float lo() const { return d_lo; } float hi() const { return d_hi; } void set_lo(float lo); void set_hi(float hi); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace analog */ } /* namespace gr */ #endif /* INCLUDED_ANALOG_RAIL_FF_IMPL_H */ gnuradio-3.7.2.1/gr-analog/swig/0000775000175000017500000000000012207440367016151 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/swig/CMakeLists.txt0000664000175000017500000000377212207440367020722 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_BLOCKS_INCLUDE_DIRS} ${GR_ANALOG_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/analog_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/analog ${CMAKE_CURRENT_BINARY_DIR}/../include/gnuradio/analog ) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_TARGET_DEPS analog_generated_includes) set(GR_SWIG_LIBRARIES gnuradio-analog gnuradio-filter) GR_SWIG_MAKE(analog_swig analog_swig.i) GR_SWIG_INSTALL( TARGETS analog_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/analog COMPONENT "analog_python" ) install( FILES analog_swig.i ${CMAKE_CURRENT_BINARY_DIR}/analog_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "analog_swig" ) gnuradio-3.7.2.1/gr-analog/swig/analog_swig.i0000664000175000017500000001401712207440367020620 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define ANALOG_API #define BLOCKS_API %include "gnuradio.i" %include "stdint.i" //load generated python docstrings %include "analog_swig_doc.i" %{ #include %} %include %{ #include "gnuradio/analog/cpm.h" #include "gnuradio/analog/noise_type.h" #include "gnuradio/analog/agc_cc.h" #include "gnuradio/analog/agc_ff.h" #include "gnuradio/analog/agc2_cc.h" #include "gnuradio/analog/agc2_ff.h" #include "gnuradio/analog/agc3_cc.h" #include "gnuradio/analog/cpfsk_bc.h" #include "gnuradio/analog/ctcss_squelch_ff.h" #include "gnuradio/analog/dpll_bb.h" #include "gnuradio/analog/feedforward_agc_cc.h" #include "gnuradio/analog/fmdet_cf.h" #include "gnuradio/analog/frequency_modulator_fc.h" #include "gnuradio/analog/fastnoise_source_s.h" #include "gnuradio/analog/fastnoise_source_i.h" #include "gnuradio/analog/fastnoise_source_f.h" #include "gnuradio/analog/fastnoise_source_c.h" #include "gnuradio/analog/noise_source_s.h" #include "gnuradio/analog/noise_source_i.h" #include "gnuradio/analog/noise_source_f.h" #include "gnuradio/analog/noise_source_c.h" #include "gnuradio/analog/phase_modulator_fc.h" #include "gnuradio/analog/pll_carriertracking_cc.h" #include "gnuradio/analog/pll_freqdet_cf.h" #include "gnuradio/analog/pll_refout_cc.h" #include "gnuradio/analog/probe_avg_mag_sqrd_c.h" #include "gnuradio/analog/probe_avg_mag_sqrd_cf.h" #include "gnuradio/analog/probe_avg_mag_sqrd_f.h" #include "gnuradio/analog/pwr_squelch_cc.h" #include "gnuradio/analog/pwr_squelch_ff.h" #include "gnuradio/analog/quadrature_demod_cf.h" #include "gnuradio/analog/rail_ff.h" #include "gnuradio/analog/sig_source_s.h" #include "gnuradio/analog/sig_source_i.h" #include "gnuradio/analog/sig_source_f.h" #include "gnuradio/analog/sig_source_c.h" #include "gnuradio/analog/sig_source_waveform.h" #include "gnuradio/analog/simple_squelch_cc.h" #include "gnuradio/analog/squelch_base_cc.h" #include "gnuradio/analog/squelch_base_ff.h" %} %include "gnuradio/analog/cpm.h" %include "gnuradio/analog/noise_type.h" %include "gnuradio/analog/agc_cc.h" %include "gnuradio/analog/agc_ff.h" %include "gnuradio/analog/agc2_cc.h" %include "gnuradio/analog/agc2_ff.h" %include "gnuradio/analog/agc3_cc.h" %include "gnuradio/analog/cpfsk_bc.h" %include "gnuradio/analog/ctcss_squelch_ff.h" %include "gnuradio/analog/dpll_bb.h" %include "gnuradio/analog/feedforward_agc_cc.h" %include "gnuradio/analog/fmdet_cf.h" %include "gnuradio/analog/frequency_modulator_fc.h" %include "gnuradio/analog/fastnoise_source_s.h" %include "gnuradio/analog/fastnoise_source_i.h" %include "gnuradio/analog/fastnoise_source_f.h" %include "gnuradio/analog/fastnoise_source_c.h" %include "gnuradio/analog/noise_source_s.h" %include "gnuradio/analog/noise_source_i.h" %include "gnuradio/analog/noise_source_f.h" %include "gnuradio/analog/noise_source_c.h" %include "gnuradio/analog/phase_modulator_fc.h" %include "gnuradio/analog/pll_carriertracking_cc.h" %include "gnuradio/analog/pll_freqdet_cf.h" %include "gnuradio/analog/pll_refout_cc.h" %include "gnuradio/analog/probe_avg_mag_sqrd_c.h" %include "gnuradio/analog/probe_avg_mag_sqrd_cf.h" %include "gnuradio/analog/probe_avg_mag_sqrd_f.h" %include "gnuradio/analog/pwr_squelch_cc.h" %include "gnuradio/analog/pwr_squelch_ff.h" %include "gnuradio/analog/quadrature_demod_cf.h" %include "gnuradio/analog/rail_ff.h" %include "gnuradio/analog/sig_source_s.h" %include "gnuradio/analog/sig_source_i.h" %include "gnuradio/analog/sig_source_f.h" %include "gnuradio/analog/sig_source_c.h" %include "gnuradio/analog/sig_source_waveform.h" %include "gnuradio/analog/simple_squelch_cc.h" %include "gnuradio/analog/squelch_base_cc.h" %include "gnuradio/analog/squelch_base_ff.h" GR_SWIG_BLOCK_MAGIC2(analog, agc_cc); GR_SWIG_BLOCK_MAGIC2(analog, agc_ff); GR_SWIG_BLOCK_MAGIC2(analog, agc2_cc); GR_SWIG_BLOCK_MAGIC2(analog, agc2_ff); GR_SWIG_BLOCK_MAGIC2(analog, agc3_cc); GR_SWIG_BLOCK_MAGIC2(analog, cpfsk_bc); GR_SWIG_BLOCK_MAGIC2(analog, ctcss_squelch_ff); GR_SWIG_BLOCK_MAGIC2(analog, dpll_bb); GR_SWIG_BLOCK_MAGIC2(analog, feedforward_agc_cc); GR_SWIG_BLOCK_MAGIC2(analog, fmdet_cf); GR_SWIG_BLOCK_MAGIC2(analog, frequency_modulator_fc); GR_SWIG_BLOCK_MAGIC2(analog, fastnoise_source_s); GR_SWIG_BLOCK_MAGIC2(analog, fastnoise_source_i); GR_SWIG_BLOCK_MAGIC2(analog, fastnoise_source_f); GR_SWIG_BLOCK_MAGIC2(analog, fastnoise_source_c); GR_SWIG_BLOCK_MAGIC2(analog, noise_source_s); GR_SWIG_BLOCK_MAGIC2(analog, noise_source_i); GR_SWIG_BLOCK_MAGIC2(analog, noise_source_f); GR_SWIG_BLOCK_MAGIC2(analog, noise_source_c); GR_SWIG_BLOCK_MAGIC2(analog, phase_modulator_fc); GR_SWIG_BLOCK_MAGIC2(analog, pll_carriertracking_cc); GR_SWIG_BLOCK_MAGIC2(analog, pll_freqdet_cf); GR_SWIG_BLOCK_MAGIC2(analog, pll_refout_cc); GR_SWIG_BLOCK_MAGIC2(analog, probe_avg_mag_sqrd_c); GR_SWIG_BLOCK_MAGIC2(analog, probe_avg_mag_sqrd_cf); GR_SWIG_BLOCK_MAGIC2(analog, probe_avg_mag_sqrd_f); GR_SWIG_BLOCK_MAGIC2(analog, pwr_squelch_cc); GR_SWIG_BLOCK_MAGIC2(analog, pwr_squelch_ff); GR_SWIG_BLOCK_MAGIC2(analog, quadrature_demod_cf); GR_SWIG_BLOCK_MAGIC2(analog, rail_ff); GR_SWIG_BLOCK_MAGIC2(analog, sig_source_s); GR_SWIG_BLOCK_MAGIC2(analog, sig_source_i); GR_SWIG_BLOCK_MAGIC2(analog, sig_source_f); GR_SWIG_BLOCK_MAGIC2(analog, sig_source_c); GR_SWIG_BLOCK_MAGIC2(analog, simple_squelch_cc); gnuradio-3.7.2.1/gr-analog/README0000664000175000017500000000017112207440367016057 0ustar jcorganjcorganThis GNU Radio component for implementing analog modulators, demodulators, and other related blocks. FIXME: just fixme.gnuradio-3.7.2.1/gr-analog/examples/0000775000175000017500000000000012207440367017016 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/examples/CMakeLists.txt0000664000175000017500000000164212207440367021561 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) # Base stuff GR_PYTHON_INSTALL(PROGRAMS fmtest.py DESTINATION ${GR_PKG_ANALOG_EXAMPLES_DIR} COMPONENT "analog_python" ) gnuradio-3.7.2.1/gr-analog/examples/tags/0000775000175000017500000000000012207440367017754 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-analog/examples/tags/CMakeLists.txt0000664000175000017500000000163712207440367022523 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS uhd_burst_detector.py DESTINATION ${GR_PKG_DATA_DIR}/examples/tags COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gr-analog/examples/tags/uhd_burst_detector.py0000775000175000017500000001124612207440367024225 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import eng_notation from gnuradio import gr from gnuradio import filter, analog, blocks from gnuradio import uhd from gnuradio.fft import window from gnuradio.eng_option import eng_option from gnuradio.filter import firdes from optparse import OptionParser class uhd_burst_detector(gr.top_block): def __init__(self, uhd_address, options): gr.top_block.__init__(self) self.uhd_addr = uhd_address self.freq = options.freq self.samp_rate = options.samp_rate self.gain = options.gain self.threshold = options.threshold self.trigger = options.trigger self.uhd_src = uhd.single_usrp_source( device_addr=self.uhd_addr, stream_args=uhd.stream_args('fc32')) self.uhd_src.set_samp_rate(self.samp_rate) self.uhd_src.set_center_freq(self.freq, 0) self.uhd_src.set_gain(self.gain, 0) taps = firdes.low_pass_2(1, 1, 0.4, 0.1, 60) self.chanfilt = filter.fir_filter_ccc(10, taps) self.tagger = blocks.burst_tagger(gr.sizeof_gr_complex) # Dummy signaler to collect a burst on known periods data = 1000*[0,] + 1000*[1,] self.signal = blocks.vector_source_s(data, True) # Energy detector to get signal burst ## use squelch to detect energy self.det = analog.simple_squelch_cc(self.threshold, 0.01) ## convert to mag squared (float) self.c2m = blocks.complex_to_mag_squared() ## average to debounce self.avg = filter.single_pole_iir_filter_ff(0.01) ## rescale signal for conversion to short self.scale = blocks.multiply_const_ff(2**16) ## signal input uses shorts self.f2s = blocks.float_to_short() # Use file sink burst tagger to capture bursts self.fsnk = blocks.tagged_file_sink(gr.sizeof_gr_complex, self.samp_rate) ################################################## # Connections ################################################## self.connect((self.uhd_src, 0), (self.tagger, 0)) self.connect((self.tagger, 0), (self.fsnk, 0)) if self.trigger: # Connect a dummy signaler to the burst tagger self.connect((self.signal, 0), (self.tagger, 1)) else: # Connect an energy detector signaler to the burst tagger self.connect(self.uhd_src, self.det) self.connect(self.det, self.c2m, self.avg, self.scale, self.f2s) self.connect(self.f2s, (self.tagger, 1)) def set_samp_rate(self, samp_rate): self.samp_rate = samp_rate self.uhd_src_0.set_samp_rate(self.samp_rate) if __name__ == '__main__': parser = OptionParser(option_class=eng_option, usage="%prog: [options]") parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="select address of the device [default=%default]") #parser.add_option("-A", "--antenna", default=None, # help="select Rx Antenna (only on RFX-series boards)") parser.add_option("-f", "--freq", type="eng_float", default=450e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=0, help="set gain in dB [default=%default]") parser.add_option("-R", "--samp-rate", type="eng_float", default=200000, help="set USRP sample rate [default=%default]") parser.add_option("-t", "--threshold", type="float", default=-60, help="Set the detection power threshold (dBm) [default=%default") parser.add_option("-T", "--trigger", action="store_true", default=False, help="Use internal trigger instead of detector [default=%default]") (options, args) = parser.parse_args() uhd_addr = options.address tb = uhd_burst_detector(uhd_addr, options) tb.run() gnuradio-3.7.2.1/gr-analog/examples/fmtest.py0000775000175000017500000001740512207440367020704 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio import channels import sys, math, time try: import scipy from scipy import fftpack except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) try: import pylab except ImportError: print "Error: Program requires matplotlib (see: matplotlib.sourceforge.net)." sys.exit(1) class fmtx(gr.hier_block2): def __init__(self, lo_freq, audio_rate, if_rate): gr.hier_block2.__init__(self, "build_fm", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_gr_complex)) fmtx = analog.nbfm_tx(audio_rate, if_rate, max_dev=5e3, tau=75e-6) # Local oscillator lo = analog.sig_source_c(if_rate, # sample rate analog.GR_SIN_WAVE, # waveform type lo_freq, # frequency 1.0, # amplitude 0) # DC Offset mixer = blocks.multiply_cc() self.connect(self, fmtx, (mixer, 0)) self.connect(lo, (mixer, 1)) self.connect(mixer, self) class fmtest(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._nsamples = 1000000 self._audio_rate = 8000 # Set up N channels with their own baseband and IF frequencies self._N = 5 chspacing = 16000 freq = [10, 20, 30, 40, 50] f_lo = [0, 1*chspacing, -1*chspacing, 2*chspacing, -2*chspacing] self._if_rate = 4*self._N*self._audio_rate # Create a signal source and frequency modulate it self.sum = blocks.add_cc() for n in xrange(self._N): sig = analog.sig_source_f(self._audio_rate, analog.GR_SIN_WAVE, freq[n], 0.5) fm = fmtx(f_lo[n], self._audio_rate, self._if_rate) self.connect(sig, fm) self.connect(fm, (self.sum, n)) self.head = blocks.head(gr.sizeof_gr_complex, self._nsamples) self.snk_tx = blocks.vector_sink_c() self.channel = channels.channel_model(0.1) self.connect(self.sum, self.head, self.channel, self.snk_tx) # Design the channlizer self._M = 10 bw = chspacing/2.0 t_bw = chspacing/10.0 self._chan_rate = self._if_rate / self._M self._taps = filter.firdes.low_pass_2(1, self._if_rate, bw, t_bw, attenuation_dB=100, window=filter.firdes.WIN_BLACKMAN_hARRIS) tpc = math.ceil(float(len(self._taps)) / float(self._M)) print "Number of taps: ", len(self._taps) print "Number of channels: ", self._M print "Taps per channel: ", tpc self.pfb = filter.pfb.channelizer_ccf(self._M, self._taps) self.connect(self.channel, self.pfb) # Create a file sink for each of M output channels of the filter and connect it self.fmdet = list() self.squelch = list() self.snks = list() for i in xrange(self._M): self.fmdet.append(analog.nbfm_rx(self._audio_rate, self._chan_rate)) self.squelch.append(analog.standard_squelch(self._audio_rate*10)) self.snks.append(blocks.vector_sink_f()) self.connect((self.pfb, i), self.fmdet[i], self.squelch[i], self.snks[i]) def num_tx_channels(self): return self._N def num_rx_channels(self): return self._M def main(): fm = fmtest() tstart = time.time() fm.run() tend = time.time() if 1: fig1 = pylab.figure(1, figsize=(12,10), facecolor="w") fig2 = pylab.figure(2, figsize=(12,10), facecolor="w") fig3 = pylab.figure(3, figsize=(12,10), facecolor="w") Ns = 10000 Ne = 100000 fftlen = 8192 winfunc = scipy.blackman # Plot transmitted signal fs = fm._if_rate d = fm.snk_tx.data()[Ns:Ns+Ne] sp1_f = fig1.add_subplot(2, 1, 1) X,freq = sp1_f.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), visible=False) X_in = 10.0*scipy.log10(abs(fftpack.fftshift(X))) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) p1_f = sp1_f.plot(f_in, X_in, "b") sp1_f.set_xlim([min(f_in), max(f_in)+1]) sp1_f.set_ylim([-120.0, 20.0]) sp1_f.set_title("Input Signal", weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) sp1_t = fig1.add_subplot(2, 1, 2) p1_t = sp1_t.plot(t_in, x_in.real, "b-o") #p1_t = sp1_t.plot(t_in, x_in.imag, "r-o") sp1_t.set_ylim([-5, 5]) # Set up the number of rows and columns for plotting the subfigures Ncols = int(scipy.floor(scipy.sqrt(fm.num_rx_channels()))) Nrows = int(scipy.floor(fm.num_rx_channels() / Ncols)) if(fm.num_rx_channels() % Ncols != 0): Nrows += 1 # Plot each of the channels outputs. Frequencies on Figure 2 and # time signals on Figure 3 fs_o = fm._audio_rate for i in xrange(len(fm.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = fm.snks[i].data()[Ns:Ne] sp2_f = fig2.add_subplot(Nrows, Ncols, 1+i) X,freq = sp2_f.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), visible=False) #X_o = 10.0*scipy.log10(abs(fftpack.fftshift(X))) X_o = 10.0*scipy.log10(abs(X)) #f_o = scipy.arange(-fs_o/2.0, fs_o/2.0, fs_o/float(X_o.size)) f_o = scipy.arange(0, fs_o/2.0, fs_o/2.0/float(X_o.size)) p2_f = sp2_f.plot(f_o, X_o, "b") sp2_f.set_xlim([min(f_o), max(f_o)+0.1]) sp2_f.set_ylim([-120.0, 20.0]) sp2_f.grid(True) sp2_f.set_title(("Channel %d" % i), weight="bold") sp2_f.set_xlabel("Frequency (kHz)") sp2_f.set_ylabel("Power (dBW)") Ts = 1.0/fs_o Tmax = len(d)*Ts t_o = scipy.arange(0, Tmax, Ts) x_t = scipy.array(d) sp2_t = fig3.add_subplot(Nrows, Ncols, 1+i) p2_t = sp2_t.plot(t_o, x_t.real, "b") p2_t = sp2_t.plot(t_o, x_t.imag, "r") sp2_t.set_xlim([min(t_o), max(t_o)+1]) sp2_t.set_ylim([-1, 1]) sp2_t.set_xlabel("Time (s)") sp2_t.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": main() gnuradio-3.7.2.1/volk/0000755000175000017500000000000012207440367014302 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/CMakeLists.txt0000664000175000017500000001264012207440367017047 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # ######################################################################## # Project setup ######################################################################## cmake_minimum_required(VERSION 2.6) if(NOT DEFINED CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Choose build type: None Debug Release RelWithDebInfo MinSizeRel") project(volk) enable_language(CXX) enable_language(C) enable_testing() set(VERSION 0.1) set(LIBVER 0.0.0) set(CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) #allows this to be a sub-project set(CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}) #allows this to be a sub-project set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) #location for custom "Modules" ######################################################################## # Environment setup ######################################################################## IF(NOT DEFINED BOOST_ROOT) SET(BOOST_ROOT ${CMAKE_INSTALL_PREFIX}) ENDIF() IF(NOT DEFINED CROSSCOMPILE_MULTILIB) SET(CROSSCOMPILE_MULTILIB "") ENDIF() SET(CROSSCOMPILE_MULTILIB ${CROSSCOMPILE_MULTILIB} CACHE STRING "Define \"true\" if you have and want to use multiple C development libs installed for cross compile") ######################################################################## # Dependencies setup ######################################################################## include(GrPython) #sets PYTHON_EXECUTABLE and PYTHON_DASH_B GR_PYTHON_CHECK_MODULE("python >= 2.5" sys "sys.version.split()[0] >= '2.5'" PYTHON_MIN_VER_FOUND) GR_PYTHON_CHECK_MODULE("Cheetah >= 2.0.0" Cheetah "Cheetah.Version >= '2.0.0'" CHEETAH_FOUND) if(NOT PYTHON_MIN_VER_FOUND) message(FATAL_ERROR "Python 2.5 or greater required to build VOLK") endif() if(NOT CHEETAH_FOUND) message(FATAL_ERROR "Cheetah templates required to build VOLK") endif() if(MSVC) if (NOT DEFINED BOOST_ALL_DYN_LINK) set(BOOST_ALL_DYN_LINK TRUE) endif() set(BOOST_ALL_DYN_LINK "${BOOST_ALL_DYN_LINK}" CACHE BOOL "boost enable dynamic linking") if(BOOST_ALL_DYN_LINK) add_definitions(-DBOOST_ALL_DYN_LINK) #setup boost auto-linking in msvc else(BOOST_ALL_DYN_LINK) unset(BOOST_REQUIRED_COMPONENTS) #empty components list for static link endif(BOOST_ALL_DYN_LINK) endif(MSVC) include(GrBoost) if(NOT Boost_FOUND) message(FATAL_ERROR "VOLK Requires boost to build") endif() find_package(ORC) ######################################################################## # Setup the package config file ######################################################################## #set variables found in the pc.in file set(prefix ${CMAKE_INSTALL_PREFIX}) set(exec_prefix "\${prefix}") set(libdir "\${exec_prefix}/lib${LIB_SUFFIX}") set(includedir "\${prefix}/include") configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/volk.pc.in ${CMAKE_CURRENT_BINARY_DIR}/volk.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/volk.pc DESTINATION lib${LIB_SUFFIX}/pkgconfig COMPONENT "volk_devel" ) ######################################################################## # Install all headers in the include directories ######################################################################## install( DIRECTORY ${CMAKE_SOURCE_DIR}/kernels/volk DESTINATION include COMPONENT "volk_devel" FILES_MATCHING PATTERN "*.h" ) install(FILES ${CMAKE_SOURCE_DIR}/include/volk/volk_prefs.h ${CMAKE_SOURCE_DIR}/include/volk/volk_complex.h ${CMAKE_SOURCE_DIR}/include/volk/volk_common.h ${CMAKE_BINARY_DIR}/include/volk/volk.h ${CMAKE_BINARY_DIR}/include/volk/volk_cpu.h ${CMAKE_BINARY_DIR}/include/volk/volk_config_fixed.h ${CMAKE_BINARY_DIR}/include/volk/volk_typedefs.h DESTINATION include/volk COMPONENT "volk_devel" ) ######################################################################## # Install cmake search routine for external use ######################################################################## install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/VolkConfig.cmake DESTINATION lib${LIB_SUFFIX}/cmake/volk/ COMPONENT "volk_devel" ) ######################################################################## # Setup the library ######################################################################## add_subdirectory(lib) ######################################################################## # And the utility apps ######################################################################## add_subdirectory(apps) add_subdirectory(python/volk_modtool) ######################################################################## # Print summary ######################################################################## message(STATUS "Using install prefix: ${CMAKE_INSTALL_PREFIX}") gnuradio-3.7.2.1/volk/include/0000755000175000017500000000000011744612271015725 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/include/volk/0000755000175000017500000000000012207440367016700 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/include/volk/volk_prefs.h0000664000175000017500000000151012207440367021222 0ustar jcorganjcorgan#ifndef INCLUDED_VOLK_PREFS_H #define INCLUDED_VOLK_PREFS_H #include #include __VOLK_DECL_BEGIN typedef struct volk_arch_pref { char name[128]; //name of the kernel char impl_a[128]; //best aligned impl char impl_u[128]; //best unaligned impl } volk_arch_pref_t; //////////////////////////////////////////////////////////////////////// // get path to volk_config profiling info //////////////////////////////////////////////////////////////////////// VOLK_API void volk_get_config_path(char *); //////////////////////////////////////////////////////////////////////// // load prefs into global prefs struct //////////////////////////////////////////////////////////////////////// VOLK_API size_t volk_load_preferences(volk_arch_pref_t **); __VOLK_DECL_END #endif //INCLUDED_VOLK_PREFS_H gnuradio-3.7.2.1/volk/include/volk/volk_complex.h0000644000175000017500000000452411700377701021556 0ustar jcorganjcorgan#ifndef INCLUDE_VOLK_COMPLEX_H #define INCLUDE_VOLK_COMPLEX_H /*! * \brief Provide typedefs and operators for all complex types in C and C++. * * The typedefs encompass all signed integer and floating point types. * Each operator function is intended to work across all data types. * Under C++, these operators are defined as inline templates. * Under C, these operators are defined as preprocessor macros. * The use of macros makes the operators agnostic to the type. * * The following operator functions are defined: * - lv_cmake - make a complex type from components * - lv_creal - get the real part of the complex number * - lv_cimag - get the imaginary part of the complex number * - lv_conj - take the conjugate of the complex number */ #ifdef __cplusplus #include #include typedef std::complex lv_8sc_t; typedef std::complex lv_16sc_t; typedef std::complex lv_32sc_t; typedef std::complex lv_64sc_t; typedef std::complex lv_32fc_t; typedef std::complex lv_64fc_t; template inline std::complex lv_cmake(const T &r, const T &i){ return std::complex(r, i); } template inline typename T::value_type lv_creal(const T &x){ return x.real(); } template inline typename T::value_type lv_cimag(const T &x){ return x.imag(); } template inline T lv_conj(const T &x){ return std::conj(x); } #else /* __cplusplus */ #include typedef char complex lv_8sc_t; typedef short complex lv_16sc_t; typedef long complex lv_32sc_t; typedef long long complex lv_64sc_t; typedef float complex lv_32fc_t; typedef double complex lv_64fc_t; #define lv_cmake(r, i) ((r) + _Complex_I*(i)) // When GNUC is available, use the complex extensions. // The extensions always return the correct value type. // http://gcc.gnu.org/onlinedocs/gcc/Complex.html #ifdef __GNUC__ #define lv_creal(x) (__real__(x)) #define lv_cimag(x) (__imag__(x)) #define lv_conj(x) (~(x)) // When not available, use the c99 complex function family, // which always returns double regardless of the input type. #else /* __GNUC__ */ #define lv_creal(x) (creal(x)) #define lv_cimag(x) (cimag(x)) #define lv_conj(x) (conj(x)) #endif /* __GNUC__ */ #endif /* __cplusplus */ #endif /* INCLUDE_VOLK_COMPLEX_H */ gnuradio-3.7.2.1/volk/include/volk/volk_common.h0000644000175000017500000000570311700377701021377 0ustar jcorganjcorgan#ifndef INCLUDED_LIBVOLK_COMMON_H #define INCLUDED_LIBVOLK_COMMON_H //////////////////////////////////////////////////////////////////////// // Cross-platform attribute macros //////////////////////////////////////////////////////////////////////// #if defined __GNUC__ # define __VOLK_ATTR_ALIGNED(x) __attribute__((aligned(x))) # define __VOLK_ATTR_UNUSED __attribute__((unused)) # define __VOLK_ATTR_INLINE __attribute__((always_inline)) # define __VOLK_ATTR_DEPRECATED __attribute__((deprecated)) # if __GNUC__ >= 4 # define __VOLK_ATTR_EXPORT __attribute__((visibility("default"))) # define __VOLK_ATTR_IMPORT __attribute__((visibility("default"))) # else # define __VOLK_ATTR_EXPORT # define __VOLK_ATTR_IMPORT # endif #elif _MSC_VER # define __VOLK_ATTR_ALIGNED(x) __declspec(align(x)) # define __VOLK_ATTR_UNUSED # define __VOLK_ATTR_INLINE __forceinline # define __VOLK_ATTR_DEPRECATED __declspec(deprecated) # define __VOLK_ATTR_EXPORT __declspec(dllexport) # define __VOLK_ATTR_IMPORT __declspec(dllimport) #else # define __VOLK_ATTR_ALIGNED(x) # define __VOLK_ATTR_UNUSED # define __VOLK_ATTR_INLINE # define __VOLK_ATTR_DEPRECATED # define __VOLK_ATTR_EXPORT # define __VOLK_ATTR_IMPORT #endif //////////////////////////////////////////////////////////////////////// // Ignore annoying warnings in MSVC //////////////////////////////////////////////////////////////////////// #if defined(_MSC_VER) # pragma warning(disable: 4244) //'conversion' conversion from 'type1' to 'type2', possible loss of data # pragma warning(disable: 4305) //'identifier' : truncation from 'type1' to 'type2' #endif //////////////////////////////////////////////////////////////////////// // C-linkage declaration macros // FIXME: due to the usage of complex.h, require gcc for c-linkage //////////////////////////////////////////////////////////////////////// #if defined(__cplusplus) && (__GNUC__) # define __VOLK_DECL_BEGIN extern "C" { # define __VOLK_DECL_END } #else # define __VOLK_DECL_BEGIN # define __VOLK_DECL_END #endif //////////////////////////////////////////////////////////////////////// // Define VOLK_API for library symbols // http://gcc.gnu.org/wiki/Visibility //////////////////////////////////////////////////////////////////////// #ifdef volk_EXPORTS # define VOLK_API __VOLK_ATTR_EXPORT #else # define VOLK_API __VOLK_ATTR_IMPORT #endif //////////////////////////////////////////////////////////////////////// // The bit128 union used by some //////////////////////////////////////////////////////////////////////// #include #ifdef LV_HAVE_SSE #include #endif #ifdef LV_HAVE_SSE2 #include #endif union bit128{ uint16_t i16[8]; uint32_t i[4]; float f[4]; double d[2]; #ifdef LV_HAVE_SSE __m128 float_vec; #endif #ifdef LV_HAVE_SSE2 __m128i int_vec; __m128d double_vec; #endif }; #define bit128_p(x) ((union bit128 *)(x)) #endif /*INCLUDED_LIBVOLK_COMMON_H*/ gnuradio-3.7.2.1/volk/tmpl/0000755000175000017500000000000012231726356015260 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/tmpl/volk_config_fixed.tmpl.h0000644000175000017500000000175311765410647022075 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOLK_CONFIG_FIXED_H #define INCLUDED_VOLK_CONFIG_FIXED_H #for $i, $arch in enumerate($archs) #define LV_$(arch.name.upper()) $i #end for #endif /*INCLUDED_VOLK_CONFIG_FIXED*/ gnuradio-3.7.2.1/volk/tmpl/volk_machines.tmpl.c0000644000175000017500000000216111765410647021225 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include "volk_machines.h" struct volk_machine *volk_machines[] = { #for $machine in $machines #ifdef LV_MACHINE_$(machine.name.upper()) &volk_machine_$(machine.name), #endif #end for }; unsigned int n_volk_machines = sizeof(volk_machines)/sizeof(*volk_machines); gnuradio-3.7.2.1/volk/tmpl/volk_cpu.tmpl.c0000664000175000017500000001166712231726356020236 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include struct VOLK_CPU volk_cpu; #if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64) #define VOLK_CPU_x86 #endif #if defined(VOLK_CPU_x86) //implement get cpuid for gcc compilers using a system or local copy of cpuid.h #if defined(__GNUC__) #if defined(HAVE_CPUID_H) #include #else #include "gcc_x86_cpuid.h" #endif #define cpuid_x86(op, r) __get_cpuid(op, (unsigned int *)r+0, (unsigned int *)r+1, (unsigned int *)r+2, (unsigned int *)r+3) /* Return Intel AVX extended CPU capabilities register. * This function will bomb on non-AVX-capable machines, so * check for AVX capability before executing. */ #if (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4) && defined(HAVE_XGETBV) static inline unsigned long long _xgetbv(unsigned int index){ unsigned int eax, edx; __asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index)); return ((unsigned long long)edx << 32) | eax; } #define __xgetbv() _xgetbv(0) #else #define __xgetbv() 0 #endif //implement get cpuid for MSVC compilers using __cpuid intrinsic #elif defined(_MSC_VER) && defined(HAVE_INTRIN_H) #include #define cpuid_x86(op, r) __cpuid(((int*)r), op) #if defined(_XCR_XFEATURE_ENABLED_MASK) #define __xgetbv() _xgetbv(_XCR_XFEATURE_ENABLED_MASK) #else #define __xgetbv() 0 #endif #else #error "A get cpuid for volk is not available on this compiler..." #endif //defined(__GNUC__) #endif //defined(VOLK_CPU_x86) static inline unsigned int cpuid_x86_bit(unsigned int reg, unsigned int op, unsigned int bit) { #if defined(VOLK_CPU_x86) unsigned int regs[4]; cpuid_x86(op, regs); return regs[reg] >> bit & 0x01; #else return 0; #endif } static inline unsigned int check_extended_cpuid(unsigned int val) { #if defined(VOLK_CPU_x86) unsigned int regs[4]; cpuid_x86(0x80000000, regs); return regs[0] >= val; #else return 0; #endif } static inline unsigned int get_avx_enabled(void) { #if defined(VOLK_CPU_x86) return __xgetbv() & 0x6; #else return 0; #endif } //neon detection is linux specific #if defined(__arm__) && defined(__linux__) #include #include #include #define VOLK_CPU_ARM #endif static int has_neon(void){ #if defined(VOLK_CPU_ARM) FILE *auxvec_f; unsigned long auxvec[2]; unsigned int found_neon = 0; auxvec_f = fopen("/proc/self/auxv", "rb"); if(!auxvec_f) return 0; size_t r = 1; //so auxv is basically 32b of ID and 32b of value //so it goes like this while(!found_neon && r) { r = fread(auxvec, sizeof(unsigned long), 2, auxvec_f); if((auxvec[0] == AT_HWCAP) && (auxvec[1] & HWCAP_NEON)) found_neon = 1; } fclose(auxvec_f); return found_neon; #else return 0; #endif } static int has_ppc(void){ #ifdef __PPC__ return 1; #else return 0; #endif } #for $arch in $archs static int i_can_has_$arch.name (void) { #for $check, $params in $arch.checks if ($(check)($(', '.join($params))) == 0) return 0; #end for return 1; } #end for #if defined(HAVE_FENV_H) #if defined(FE_TONEAREST) #include static inline void set_float_rounding(void){ fesetround(FE_TONEAREST); } #else static inline void set_float_rounding(void){ //do nothing } #endif #elif defined(_MSC_VER) #include static inline void set_float_rounding(void){ unsigned int cwrd; _controlfp_s(&cwrd, 0, 0); _controlfp_s(&cwrd, _RC_NEAR, _MCW_RC); } #else static inline void set_float_rounding(void){ //do nothing } #endif void volk_cpu_init() { #for $arch in $archs volk_cpu.has_$arch.name = &i_can_has_$arch.name; #end for set_float_rounding(); } unsigned int volk_get_lvarch() { unsigned int retval = 0; volk_cpu_init(); #for $arch in $archs retval += volk_cpu.has_$(arch.name)() << LV_$(arch.name.upper()); #end for return retval; } gnuradio-3.7.2.1/volk/tmpl/volk_cpu.tmpl.h0000644000175000017500000000217111765410647020233 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOLK_CPU_H #define INCLUDED_VOLK_CPU_H #include __VOLK_DECL_BEGIN struct VOLK_CPU { #for $arch in $archs int (*has_$arch.name) (); #end for }; extern struct VOLK_CPU volk_cpu; void volk_cpu_init (); unsigned int volk_get_lvarch (); __VOLK_DECL_END #endif /*INCLUDED_VOLK_CPU_H*/ gnuradio-3.7.2.1/volk/tmpl/volk_typedefs.tmpl.h0000664000175000017500000000202512207440367021261 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOLK_TYPEDEFS #define INCLUDED_VOLK_TYPEDEFS #include #include #for $kern in $kernels typedef void (*$(kern.pname))($kern.arglist_types); #end for #endif /*INCLUDED_VOLK_TYPEDEFS*/ gnuradio-3.7.2.1/volk/tmpl/volk.tmpl.h0000664000175000017500000000504512207440367017363 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOLK_RUNTIME #define INCLUDED_VOLK_RUNTIME #include #include #include #include #include #include __VOLK_DECL_BEGIN typedef struct volk_func_desc { const char **impl_names; const int *impl_deps; const bool *impl_alignment; const size_t n_impls; } volk_func_desc_t; //! Get the machine alignment in bytes VOLK_API size_t volk_get_alignment(void); /*! * The VOLK_OR_PTR macro is a convenience macro * for checking the alignment of a set of pointers. * Example usage: * volk_is_aligned(VOLK_OR_PTR((VOLK_OR_PTR(p0, p1), p2))) */ #define VOLK_OR_PTR(ptr0, ptr1) \ (const void *)(((intptr_t)(ptr0)) | ((intptr_t)(ptr1))) /*! * Is the pointer on a machine alignment boundary? * * Note: for performance reasons, this function * is not usable until another volk API call is made * which will perform certain initialization tasks. * * \param ptr the pointer to some memory buffer * \return 1 for alignment boundary, else 0 */ VOLK_API bool volk_is_aligned(const void *ptr); #for $kern in $kernels //! A function pointer to the dispatcher implementation extern VOLK_API $kern.pname $kern.name; //! A function pointer to the fastest aligned implementation extern VOLK_API $kern.pname $(kern.name)_a; //! A function pointer to the fastest unaligned implementation extern VOLK_API $kern.pname $(kern.name)_u; //! Call into a specific implementation given by name extern VOLK_API void $(kern.name)_manual($kern.arglist_full, const char* impl_name); //! Get description paramaters for this kernel extern VOLK_API volk_func_desc_t $(kern.name)_get_func_desc(void); #end for __VOLK_DECL_END #endif /*INCLUDED_VOLK_RUNTIME*/ gnuradio-3.7.2.1/volk/tmpl/volk.tmpl.c0000664000175000017500000001151712207440367017357 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include "volk_machines.h" #include #include #include "volk_rank_archs.h" #include #include #include #include static size_t __alignment = 0; static intptr_t __alignment_mask = 0; struct volk_machine *get_machine(void) { extern struct volk_machine *volk_machines[]; extern unsigned int n_volk_machines; static struct volk_machine *machine = NULL; if(machine != NULL) return machine; else { unsigned int max_score = 0; unsigned int i; for(i=0; icaps & (~volk_get_lvarch()))) { if(volk_machines[i]->caps > max_score) { max_score = volk_machines[i]->caps; machine = volk_machines[i]; } } } printf("Using Volk machine: %s\n", machine->name); __alignment = machine->alignment; __alignment_mask = (intptr_t)(__alignment-1); return machine; } } size_t volk_get_alignment(void) { get_machine(); //ensures alignment is set return __alignment; } bool volk_is_aligned(const void *ptr) { return ((intptr_t)(ptr) & __alignment_mask) == 0; } #define LV_HAVE_GENERIC #define LV_HAVE_DISPATCHER #for $kern in $kernels #if $kern.has_dispatcher #include //pulls in the dispatcher #end if static inline void __$(kern.name)_d($kern.arglist_full) { #if $kern.has_dispatcher $(kern.name)_dispatcher($kern.arglist_names); return; #end if if (volk_is_aligned( #set $num_open_parens = 0 #for $arg_type, $arg_name in $kern.args #if '*' in $arg_type VOLK_OR_PTR($arg_name, #set $num_open_parens += 1 #end if #end for 0$(')'*$num_open_parens) )){ $(kern.name)_a($kern.arglist_names); } else{ $(kern.name)_u($kern.arglist_names); } } static inline void __init_$(kern.name)(void) { const char *name = get_machine()->$(kern.name)_name; const char **impl_names = get_machine()->$(kern.name)_impl_names; const int *impl_deps = get_machine()->$(kern.name)_impl_deps; const bool *alignment = get_machine()->$(kern.name)_impl_alignment; const size_t n_impls = get_machine()->$(kern.name)_n_impls; const size_t index_a = volk_rank_archs(name, impl_names, impl_deps, alignment, n_impls, true/*aligned*/); const size_t index_u = volk_rank_archs(name, impl_names, impl_deps, alignment, n_impls, false/*unaligned*/); $(kern.name)_a = get_machine()->$(kern.name)_impls[index_a]; $(kern.name)_u = get_machine()->$(kern.name)_impls[index_u]; assert($(kern.name)_a); assert($(kern.name)_u); $(kern.name) = &__$(kern.name)_d; } static inline void __$(kern.name)_a($kern.arglist_full) { __init_$(kern.name)(); $(kern.name)_a($kern.arglist_names); } static inline void __$(kern.name)_u($kern.arglist_full) { __init_$(kern.name)(); $(kern.name)_u($kern.arglist_names); } static inline void __$(kern.name)($kern.arglist_full) { __init_$(kern.name)(); $(kern.name)($kern.arglist_names); } $kern.pname $(kern.name)_a = &__$(kern.name)_a; $kern.pname $(kern.name)_u = &__$(kern.name)_u; $kern.pname $(kern.name) = &__$(kern.name); void $(kern.name)_manual($kern.arglist_full, const char* impl_name) { const int index = volk_get_index( get_machine()->$(kern.name)_impl_names, get_machine()->$(kern.name)_n_impls, impl_name ); get_machine()->$(kern.name)_impls[index]( $kern.arglist_names ); } volk_func_desc_t $(kern.name)_get_func_desc(void) { const char **impl_names = get_machine()->$(kern.name)_impl_names; const int *impl_deps = get_machine()->$(kern.name)_impl_deps; const bool *alignment = get_machine()->$(kern.name)_impl_alignment; const size_t n_impls = get_machine()->$(kern.name)_n_impls; volk_func_desc_t desc = { impl_names, impl_deps, alignment, n_impls }; return desc; } #end for gnuradio-3.7.2.1/volk/tmpl/volk_machines.tmpl.h0000664000175000017500000000342012207440367021225 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_LIBVOLK_MACHINES_H #define INCLUDED_LIBVOLK_MACHINES_H #include #include #include #include __VOLK_DECL_BEGIN struct volk_machine { const unsigned int caps; //capabilities (i.e., archs compiled into this machine, in the volk_get_lvarch format) const char *name; const size_t alignment; //the maximum byte alignment required for functions in this library #for $kern in $kernels const char *$(kern.name)_name; const char *$(kern.name)_impl_names[$(len($archs))]; const int $(kern.name)_impl_deps[$(len($archs))]; const bool $(kern.name)_impl_alignment[$(len($archs))]; const $(kern.pname) $(kern.name)_impls[$(len($archs))]; const size_t $(kern.name)_n_impls; #end for }; #for $machine in $machines #ifdef LV_MACHINE_$(machine.name.upper()) extern struct volk_machine volk_machine_$(machine.name); #endif #end for __VOLK_DECL_END #endif //INCLUDED_LIBVOLK_MACHINES_H gnuradio-3.7.2.1/volk/tmpl/volk_machine_xxx.tmpl.c0000664000175000017500000000556512207440367021760 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #set $this_machine = $machine_dict[$args[0]] #set $arch_names = $this_machine.arch_names #for $arch in $this_machine.archs #define LV_HAVE_$(arch.name.upper()) 1 #end for #include #include "volk_machines.h" #include #ifdef HAVE_CONFIG_H #include "config.h" #endif #for $kern in $kernels #include #end for ######################################################################## #def make_arch_have_list($archs) $(' | '.join(['(1 << LV_%s)'%a.name.upper() for a in $archs]))#slurp #end def ######################################################################## #def make_impl_name_list($impls) {$(', '.join(['"%s"'%i.name for i in $impls]))}#slurp #end def ######################################################################## #def make_impl_align_list($impls) {$(', '.join(['true' if i.is_aligned else 'false' for i in $impls]))}#slurp #end def ######################################################################## #def make_impl_deps_list($impls) {$(', '.join([' | '.join(['(1 << LV_%s)'%d.upper() for d in i.deps]) for i in $impls]))}#slurp #end def ######################################################################## #def make_impl_fcn_list($name, $impls) {$(', '.join(['%s_%s'%($name, i.name) for i in $impls]))}#slurp #end def struct volk_machine volk_machine_$(this_machine.name) = { $make_arch_have_list($this_machine.archs), "$this_machine.name", $this_machine.alignment, #for $kern in $kernels #set $impls = $kern.get_impls($arch_names) "$kern.name", ##//kernel name $make_impl_name_list($impls), ##//list of kernel implementations by name $make_impl_deps_list($impls), ##//list of arch dependencies per implementation $make_impl_align_list($impls), ##//alignment required? for each implementation $make_impl_fcn_list($kern.name, $impls), ##//pointer to each implementation $(len($impls)), ##//number of implementations listed here #end for }; gnuradio-3.7.2.1/volk/kernels/0000775000175000017500000000000012207440367015747 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/kernels/volk/0000775000175000017500000000000012237515112016714 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_32f_dot_prod_32fc.h0000664000175000017500000000565412207440367024056 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_32f_dot_prod_32fc_a_H #define INCLUDED_volk_32fc_32f_dot_prod_32fc_a_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32fc_32f_dot_prod_32fc_generic(lv_32fc_t* result, const lv_32fc_t* input, const float * taps, unsigned int num_points) { float res[2]; float *realpt = &res[0], *imagpt = &res[1]; const float* aPtr = (float*)input; const float* bPtr= taps; unsigned int number = 0; *realpt = 0; *imagpt = 0; for(number = 0; number < num_points; number++){ *realpt += ((*aPtr++) * (*bPtr)); *imagpt += ((*aPtr++) * (*bPtr++)); } *result = *(lv_32fc_t*)(&res[0]); } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE static inline void volk_32fc_32f_dot_prod_32fc_a_sse( lv_32fc_t* result, const lv_32fc_t* input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 8; float res[2]; float *realpt = &res[0], *imagpt = &res[1]; const float* aPtr = (float*)input; const float* bPtr = taps; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 x0Val, x1Val, x2Val, x3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm_load_ps(aPtr); a1Val = _mm_load_ps(aPtr+4); a2Val = _mm_load_ps(aPtr+8); a3Val = _mm_load_ps(aPtr+12); x0Val = _mm_load_ps(bPtr); x1Val = _mm_load_ps(bPtr); x2Val = _mm_load_ps(bPtr+4); x3Val = _mm_load_ps(bPtr+4); b0Val = _mm_unpacklo_ps(x0Val, x1Val); b1Val = _mm_unpackhi_ps(x0Val, x1Val); b2Val = _mm_unpacklo_ps(x2Val, x3Val); b3Val = _mm_unpackhi_ps(x2Val, x3Val); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm_add_ps(c1Val, dotProdVal1); dotProdVal2 = _mm_add_ps(c2Val, dotProdVal2); dotProdVal3 = _mm_add_ps(c3Val, dotProdVal3); aPtr += 16; bPtr += 8; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector *realpt = dotProductVector[0]; *imagpt = dotProductVector[1]; *realpt += dotProductVector[2]; *imagpt += dotProductVector[3]; number = sixteenthPoints*8; for(;number < num_points; number++){ *realpt += ((*aPtr++) * (*bPtr)); *imagpt += ((*aPtr++) * (*bPtr++)); } *result = *(lv_32fc_t*)(&res[0]); } #endif /*LV_HAVE_SSE*/ #endif /*INCLUDED_volk_32fc_32f_dot_prod_32fc_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_divide_32f.h0000664000175000017500000000541112207440367023130 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_divide_32f_a_H #define INCLUDED_volk_32f_x2_divide_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Divides the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector The vector to be divideed \param bVector The divisor vector \param num_points The number of values in aVector and bVector to be divideed together and stored into cVector */ static inline void volk_32f_x2_divide_32f_a_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_div_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) / (*bPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Divides the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector The vector to be divideed \param bVector The divisor vector \param num_points The number of values in aVector and bVector to be divideed together and stored into cVector */ static inline void volk_32f_x2_divide_32f_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) / (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Divides the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector The vector to be divideed \param bVector The divisor vector \param num_points The number of values in aVector and bVector to be divideed together and stored into cVector */ extern void volk_32f_x2_divide_32f_a_orc_impl(float* cVector, const float* aVector, const float* bVector, unsigned int num_points); static inline void volk_32f_x2_divide_32f_u_orc(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ volk_32f_x2_divide_32f_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_x2_divide_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_convert_64f.h0000664000175000017500000000763112207440367022746 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_convert_64f_u_H #define INCLUDED_volk_32f_convert_64f_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the float values into double values \param dVector The converted double vector values \param fVector The float vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_32f_convert_64f_u_sse2(double* outputVector, const float* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; double* outputVectorPtr = outputVector; __m128d ret; __m128 inputVal; for(;number < quarterPoints; number++){ inputVal = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; ret = _mm_cvtps_pd(inputVal); _mm_storeu_pd(outputVectorPtr, ret); outputVectorPtr += 2; inputVal = _mm_movehl_ps(inputVal, inputVal); ret = _mm_cvtps_pd(inputVal); _mm_storeu_pd(outputVectorPtr, ret); outputVectorPtr += 2; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] = (double)(inputVector[number]); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the float values into double values \param dVector The converted double vector values \param fVector The float vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_32f_convert_64f_generic(double* outputVector, const float* inputVector, unsigned int num_points){ double* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((double)(*inputVectorPtr++)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_convert_64f_u_H */ #ifndef INCLUDED_volk_32f_convert_64f_a_H #define INCLUDED_volk_32f_convert_64f_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the float values into double values \param dVector The converted double vector values \param fVector The float vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_32f_convert_64f_a_sse2(double* outputVector, const float* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; double* outputVectorPtr = outputVector; __m128d ret; __m128 inputVal; for(;number < quarterPoints; number++){ inputVal = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; ret = _mm_cvtps_pd(inputVal); _mm_store_pd(outputVectorPtr, ret); outputVectorPtr += 2; inputVal = _mm_movehl_ps(inputVal, inputVal); ret = _mm_cvtps_pd(inputVal); _mm_store_pd(outputVectorPtr, ret); outputVectorPtr += 2; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] = (double)(inputVector[number]); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the float values into double values \param dVector The converted double vector values \param fVector The float vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_32f_convert_64f_a_generic(double* outputVector, const float* inputVector, unsigned int num_points){ double* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((double)(*inputVectorPtr++)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_convert_64f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_normalize.h0000664000175000017500000000521712207440367023442 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_normalize_a_H #define INCLUDED_volk_32f_s32f_normalize_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Normalizes all points in the buffer by the scalar value ( divides each data point by the scalar value ) \param vecBuffer The buffer of values to be vectorized \param num_points The number of values in vecBuffer \param scalar The scale value to be applied to each buffer value */ static inline void volk_32f_s32f_normalize_a_sse(float* vecBuffer, const float scalar, unsigned int num_points){ unsigned int number = 0; float* inputPtr = vecBuffer; const float invScalar = 1.0 / scalar; __m128 vecScalar = _mm_set_ps1(invScalar); __m128 input1; const uint64_t quarterPoints = num_points / 4; for(;number < quarterPoints; number++){ input1 = _mm_load_ps(inputPtr); input1 = _mm_mul_ps(input1, vecScalar); _mm_store_ps(inputPtr, input1); inputPtr += 4; } number = quarterPoints*4; for(; number < num_points; number++){ *inputPtr *= invScalar; inputPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Normalizes the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be normalizeed \param bVector One of the vectors to be normalizeed \param num_points The number of values in aVector and bVector to be normalizeed together and stored into cVector */ static inline void volk_32f_s32f_normalize_generic(float* vecBuffer, const float scalar, unsigned int num_points){ unsigned int number = 0; float* inputPtr = vecBuffer; const float invScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *inputPtr *= invScalar; inputPtr++; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Normalizes the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be normalizeed \param bVector One of the vectors to be normalizeed \param num_points The number of values in aVector and bVector to be normalizeed together and stored into cVector */ extern void volk_32f_s32f_normalize_a_orc_impl(float* dst, float* src, const float scalar, unsigned int num_points); static inline void volk_32f_s32f_normalize_u_orc(float* vecBuffer, const float scalar, unsigned int num_points){ float invscalar = 1.0 / scalar; volk_32f_s32f_normalize_a_orc_impl(vecBuffer, vecBuffer, invscalar, num_points); } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_normalize_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_max_star_horizontal_16i.h0000664000175000017500000000615212207440367025357 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_max_star_horizontal_16i_a_H #define INCLUDED_volk_16i_max_star_horizontal_16i_a_H #include #include #include #ifdef LV_HAVE_SSSE3 #include #include #include static inline void volk_16i_max_star_horizontal_16i_a_ssse3(int16_t* target, int16_t* src0, unsigned int num_points) { const unsigned int num_bytes = num_points*2; const static uint8_t shufmask0[16] = {0x00, 0x01, 0x04, 0x05, 0x08, 0x09, 0x0c, 0x0d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; const static uint8_t shufmask1[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x04, 0x05, 0x08, 0x09, 0x0c, 0x0d}; const static uint8_t andmask0[16] = {0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; const static uint8_t andmask1[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02}; __m128i xmm0, xmm1, xmm2, xmm3, xmm4; __m128i xmm5, xmm6, xmm7, xmm8; xmm4 = _mm_load_si128((__m128i*)shufmask0); xmm5 = _mm_load_si128((__m128i*)shufmask1); xmm6 = _mm_load_si128((__m128i*)andmask0); xmm7 = _mm_load_si128((__m128i*)andmask1); __m128i *p_target, *p_src0; p_target = (__m128i*)target; p_src0 = (__m128i*)src0; int bound = num_bytes >> 5; int intermediate = (num_bytes >> 4) & 1; int leftovers = (num_bytes >> 1) & 7; int i = 0; for(i = 0; i < bound; ++i) { xmm0 = _mm_load_si128(p_src0); xmm1 = _mm_load_si128(&p_src0[1]); xmm2 = _mm_xor_si128(xmm2, xmm2); p_src0 += 2; xmm3 = _mm_hsub_epi16(xmm0, xmm1); xmm2 = _mm_cmpgt_epi16(xmm2, xmm3); xmm8 = _mm_and_si128(xmm2, xmm6); xmm3 = _mm_and_si128(xmm2, xmm7); xmm8 = _mm_add_epi8(xmm8, xmm4); xmm3 = _mm_add_epi8(xmm3, xmm5); xmm0 = _mm_shuffle_epi8(xmm0, xmm8); xmm1 = _mm_shuffle_epi8(xmm1, xmm3); xmm3 = _mm_add_epi16(xmm0, xmm1); _mm_store_si128(p_target, xmm3); p_target += 1; } for(i = 0; i < intermediate; ++i) { xmm0 = _mm_load_si128(p_src0); xmm2 = _mm_xor_si128(xmm2, xmm2); p_src0 += 1; xmm3 = _mm_hsub_epi16(xmm0, xmm1); xmm2 = _mm_cmpgt_epi16(xmm2, xmm3); xmm8 = _mm_and_si128(xmm2, xmm6); xmm3 = _mm_add_epi8(xmm8, xmm4); xmm0 = _mm_shuffle_epi8(xmm0, xmm3); _mm_storel_pd((double*)p_target, bit128_p(&xmm0)->double_vec); p_target = (__m128i*)((int8_t*)p_target + 8); } for(i = (bound << 4) + (intermediate << 3); i < (bound << 4) + (intermediate << 3) + leftovers ; i += 2) { target[i>>1] = ((int16_t)(src0[i] - src0[i + 1]) > 0) ? src0[i] : src0[i + 1]; } } #endif /*LV_HAVE_SSSE3*/ #ifdef LV_HAVE_GENERIC static inline void volk_16i_max_star_horizontal_16i_generic(int16_t* target, int16_t* src0, unsigned int num_points) { const unsigned int num_bytes = num_points*2; int i = 0; int bound = num_bytes >> 1; for(i = 0; i < bound; i += 2) { target[i >> 1] = ((int16_t) (src0[i] - src0[i + 1]) > 0) ? src0[i] : src0[i+1]; } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_16i_max_star_horizontal_16i_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_deinterleave_real_8i.h0000664000175000017500000000453712207440367024754 0ustar jcorganjcorgan#ifndef INCLUDED_VOLK_8sc_DEINTERLEAVE_REAL_8s_ALIGNED8_H #define INCLUDED_VOLK_8sc_DEINTERLEAVE_REAL_8s_ALIGNED8_H #include #include #ifdef LV_HAVE_SSSE3 #include /*! \brief Deinterleaves the complex 8 bit vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_deinterleave_real_8i_a_ssse3(int8_t* iBuffer, const lv_8sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (int8_t*)complexVector; int8_t* iBufferPtr = iBuffer; __m128i moveMask1 = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 14, 12, 10, 8, 6, 4, 2, 0); __m128i moveMask2 = _mm_set_epi8(14, 12, 10, 8, 6, 4, 2, 0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80); __m128i complexVal1, complexVal2, outputVal; unsigned int sixteenthPoints = num_points / 16; for(number = 0; number < sixteenthPoints; number++){ complexVal1 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal2 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal1 = _mm_shuffle_epi8(complexVal1, moveMask1); complexVal2 = _mm_shuffle_epi8(complexVal2, moveMask2); outputVal = _mm_or_si128(complexVal1, complexVal2); _mm_store_si128((__m128i*)iBufferPtr, outputVal); iBufferPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_SSSE3 */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 8 bit vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_deinterleave_real_8i_generic(int8_t* iBuffer, const lv_8sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (int8_t*)complexVector; int8_t* iBufferPtr = iBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_VOLK_8sc_DEINTERLEAVE_REAL_8s_ALIGNED8_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_index_max_16u.h0000664000175000017500000001255212207440367023417 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_index_max_16u_a_H #define INCLUDED_volk_32fc_index_max_16u_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include #include static inline void volk_32fc_index_max_16u_a_sse3(unsigned int* target, lv_32fc_t* src0, unsigned int num_points) { const unsigned int num_bytes = num_points*8; union bit128 holderf; union bit128 holderi; float sq_dist = 0.0; union bit128 xmm5, xmm4; __m128 xmm1, xmm2, xmm3; __m128i xmm8, xmm11, xmm12, xmmfive, xmmfour, xmm9, holder0, holder1, xmm10; xmm5.int_vec = xmmfive = _mm_setzero_si128(); xmm4.int_vec = xmmfour = _mm_setzero_si128(); holderf.int_vec = holder0 = _mm_setzero_si128(); holderi.int_vec = holder1 = _mm_setzero_si128(); int bound = num_bytes >> 5; int leftovers0 = (num_bytes >> 4) & 1; int leftovers1 = (num_bytes >> 3) & 1; int i = 0; xmm8 = _mm_set_epi32(3, 2, 1, 0);//remember the crazy reverse order! xmm9 = xmm8 = _mm_setzero_si128(); xmm10 = _mm_set_epi32(4, 4, 4, 4); xmm3 = _mm_setzero_ps(); ; //printf("%f, %f, %f, %f\n", ((float*)&xmm10)[0], ((float*)&xmm10)[1], ((float*)&xmm10)[2], ((float*)&xmm10)[3]); for(; i < bound; ++i) { xmm1 = _mm_load_ps((float*)src0); xmm2 = _mm_load_ps((float*)&src0[2]); src0 += 4; xmm1 = _mm_mul_ps(xmm1, xmm1); xmm2 = _mm_mul_ps(xmm2, xmm2); xmm1 = _mm_hadd_ps(xmm1, xmm2); xmm3 = _mm_max_ps(xmm1, xmm3); xmm4.float_vec = _mm_cmplt_ps(xmm1, xmm3); xmm5.float_vec = _mm_cmpeq_ps(xmm1, xmm3); xmm11 = _mm_and_si128(xmm8, xmm5.int_vec); xmm12 = _mm_and_si128(xmm9, xmm4.int_vec); xmm9 = _mm_add_epi32(xmm11, xmm12); xmm8 = _mm_add_epi32(xmm8, xmm10); //printf("%f, %f, %f, %f\n", ((float*)&xmm3)[0], ((float*)&xmm3)[1], ((float*)&xmm3)[2], ((float*)&xmm3)[3]); //printf("%u, %u, %u, %u\n", ((uint32_t*)&xmm10)[0], ((uint32_t*)&xmm10)[1], ((uint32_t*)&xmm10)[2], ((uint32_t*)&xmm10)[3]); } for(i = 0; i < leftovers0; ++i) { xmm2 = _mm_load_ps((float*)src0); xmm1 = _mm_movelh_ps(bit128_p(&xmm8)->float_vec, bit128_p(&xmm8)->float_vec); xmm8 = bit128_p(&xmm1)->int_vec; xmm2 = _mm_mul_ps(xmm2, xmm2); src0 += 2; xmm1 = _mm_hadd_ps(xmm2, xmm2); xmm3 = _mm_max_ps(xmm1, xmm3); xmm10 = _mm_set_epi32(2, 2, 2, 2);//load1_ps((float*)&init[2]); xmm4.float_vec = _mm_cmplt_ps(xmm1, xmm3); xmm5.float_vec = _mm_cmpeq_ps(xmm1, xmm3); xmm11 = _mm_and_si128(xmm8, xmm5.int_vec); xmm12 = _mm_and_si128(xmm9, xmm4.int_vec); xmm9 = _mm_add_epi32(xmm11, xmm12); xmm8 = _mm_add_epi32(xmm8, xmm10); //printf("egads%u, %u, %u, %u\n", ((uint32_t*)&xmm9)[0], ((uint32_t*)&xmm9)[1], ((uint32_t*)&xmm9)[2], ((uint32_t*)&xmm9)[3]); } for(i = 0; i < leftovers1; ++i) { //printf("%u, %u, %u, %u\n", ((uint32_t*)&xmm9)[0], ((uint32_t*)&xmm9)[1], ((uint32_t*)&xmm9)[2], ((uint32_t*)&xmm9)[3]); sq_dist = lv_creal(src0[0]) * lv_creal(src0[0]) + lv_cimag(src0[0]) * lv_cimag(src0[0]); xmm2 = _mm_load1_ps(&sq_dist); xmm1 = xmm3; xmm3 = _mm_max_ss(xmm3, xmm2); xmm4.float_vec = _mm_cmplt_ps(xmm1, xmm3); xmm5.float_vec = _mm_cmpeq_ps(xmm1, xmm3); xmm8 = _mm_shuffle_epi32(xmm8, 0x00); xmm11 = _mm_and_si128(xmm8, xmm4.int_vec); xmm12 = _mm_and_si128(xmm9, xmm5.int_vec); xmm9 = _mm_add_epi32(xmm11, xmm12); } //printf("%f, %f, %f, %f\n", ((float*)&xmm3)[0], ((float*)&xmm3)[1], ((float*)&xmm3)[2], ((float*)&xmm3)[3]); //printf("%u, %u, %u, %u\n", ((uint32_t*)&xmm9)[0], ((uint32_t*)&xmm9)[1], ((uint32_t*)&xmm9)[2], ((uint32_t*)&xmm9)[3]); _mm_store_ps((float*)&(holderf.f), xmm3); _mm_store_si128(&(holderi.int_vec), xmm9); target[0] = holderi.i[0]; sq_dist = holderf.f[0]; target[0] = (holderf.f[1] > sq_dist) ? holderi.i[1] : target[0]; sq_dist = (holderf.f[1] > sq_dist) ? holderf.f[1] : sq_dist; target[0] = (holderf.f[2] > sq_dist) ? holderi.i[2] : target[0]; sq_dist = (holderf.f[2] > sq_dist) ? holderf.f[2] : sq_dist; target[0] = (holderf.f[3] > sq_dist) ? holderi.i[3] : target[0]; sq_dist = (holderf.f[3] > sq_dist) ? holderf.f[3] : sq_dist; /* float placeholder = 0.0; uint32_t temp0, temp1; unsigned int g0 = (((float*)&xmm3)[0] > ((float*)&xmm3)[1]); unsigned int l0 = g0 ^ 1; unsigned int g1 = (((float*)&xmm3)[1] > ((float*)&xmm3)[2]); unsigned int l1 = g1 ^ 1; temp0 = g0 * ((uint32_t*)&xmm9)[0] + l0 * ((uint32_t*)&xmm9)[1]; temp1 = g0 * ((uint32_t*)&xmm9)[2] + l0 * ((uint32_t*)&xmm9)[3]; sq_dist = g0 * ((float*)&xmm3)[0] + l0 * ((float*)&xmm3)[1]; placeholder = g0 * ((float*)&xmm3)[2] + l0 * ((float*)&xmm3)[3]; g0 = (sq_dist > placeholder); l0 = g0 ^ 1; target[0] = g0 * temp0 + l0 * temp1; */ } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_GENERIC static inline void volk_32fc_index_max_16u_generic(unsigned int* target, lv_32fc_t* src0, unsigned int num_points) { const unsigned int num_bytes = num_points*8; float sq_dist = 0.0; float max = 0.0; unsigned int index = 0; unsigned int i = 0; for(; i < num_bytes >> 3; ++i) { sq_dist = lv_creal(src0[i]) * lv_creal(src0[i]) + lv_cimag(src0[i]) * lv_cimag(src0[i]); index = sq_dist > max ? i : index; max = sq_dist > max ? sq_dist : max; } target[0] = index; } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_32fc_index_max_16u_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_x2_conjugate_dot_prod_32fc.h0000664000175000017500000003463012207440367026050 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_x2_conjugate_dot_prod_32fc_u_H #define INCLUDED_volk_32fc_x2_conjugate_dot_prod_32fc_u_H #include #ifdef LV_HAVE_GENERIC static inline void volk_32fc_x2_conjugate_dot_prod_32fc_generic(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; float * res = (float*) result; float * in = (float*) input; float * tp = (float*) taps; unsigned int n_2_ccomplex_blocks = num_bytes >> 4; unsigned int isodd = (num_bytes >> 3) &1; float sum0[2] = {0,0}; float sum1[2] = {0,0}; unsigned int i = 0; for(i = 0; i < n_2_ccomplex_blocks; ++i) { sum0[0] += in[0] * tp[0] + in[1] * tp[1]; sum0[1] += (-in[0] * tp[1]) + in[1] * tp[0]; sum1[0] += in[2] * tp[2] + in[3] * tp[3]; sum1[1] += (-in[2] * tp[3]) + in[3] * tp[2]; in += 4; tp += 4; } res[0] = sum0[0] + sum1[0]; res[1] = sum0[1] + sum1[1]; for(i = 0; i < isodd; ++i) { *result += input[(num_bytes >> 3) - 1] * lv_conj(taps[(num_bytes >> 3) - 1]); } /* for(i = 0; i < num_bytes >> 3; ++i) { *result += input[i] * conjf(taps[i]); } */ } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE3 #include #include #include static inline void volk_32fc_x2_conjugate_dot_prod_32fc_u_sse3(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { unsigned int num_bytes = num_points*8; // Variable never used? //__VOLK_ATTR_ALIGNED(16) static const uint32_t conjugator[4]= {0x00000000, 0x80000000, 0x00000000, 0x80000000}; union HalfMask { uint32_t intRep[4]; __m128 vec; } halfMask; union NegMask { int intRep[4]; __m128 vec; } negMask; unsigned int offset = 0; float Rsum=0, Isum=0; float Im,Re; __m128 in1, in2, Rv, fehg, Iv, Rs, Ivm, Is; __m128 zv = {0,0,0,0}; halfMask.intRep[0] = halfMask.intRep[1] = 0xFFFFFFFF; halfMask.intRep[2] = halfMask.intRep[3] = 0x00000000; negMask.intRep[0] = negMask.intRep[2] = 0x80000000; negMask.intRep[1] = negMask.intRep[3] = 0; // main loop while(num_bytes >= 4*sizeof(float)){ in1 = _mm_loadu_ps( (float*) (input+offset) ); in2 = _mm_loadu_ps( (float*) (taps+offset) ); Rv = _mm_mul_ps(in1, in2); fehg = _mm_shuffle_ps(in2, in2, _MM_SHUFFLE(2,3,0,1)); Iv = _mm_mul_ps(in1, fehg); Rs = _mm_hadd_ps( _mm_hadd_ps(Rv, zv) ,zv); Ivm = _mm_xor_ps( negMask.vec, Iv ); Is = _mm_hadd_ps( _mm_hadd_ps(Ivm, zv) ,zv); _mm_store_ss( &Im, Is ); _mm_store_ss( &Re, Rs ); num_bytes -= 4*sizeof(float); offset += 2; Rsum += Re; Isum += Im; } // handle the last complex case ... if(num_bytes > 0){ if(num_bytes != 4){ // bad things are happening } in1 = _mm_loadu_ps( (float*) (input+offset) ); in2 = _mm_loadu_ps( (float*) (taps+offset) ); Rv = _mm_and_ps(_mm_mul_ps(in1, in2), halfMask.vec); fehg = _mm_shuffle_ps(in2, in2, _MM_SHUFFLE(2,3,0,1)); Iv = _mm_and_ps(_mm_mul_ps(in1, fehg), halfMask.vec); Rs = _mm_hadd_ps(_mm_hadd_ps(Rv, zv),zv); Ivm = _mm_xor_ps( negMask.vec, Iv ); Is = _mm_hadd_ps(_mm_hadd_ps(Ivm, zv),zv); _mm_store_ss( &Im, Is ); _mm_store_ss( &Re, Rs ); Rsum += Re; Isum += Im; } result[0] = lv_cmake(Rsum,Isum); return; } #endif /*LV_HAVE_SSE3*/ #endif /*INCLUDED_volk_32fc_x2_conjugate_dot_prod_32fc_u_H*/ #ifndef INCLUDED_volk_32fc_x2_conjugate_dot_prod_32fc_a_H #define INCLUDED_volk_32fc_x2_conjugate_dot_prod_32fc_a_H #include #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32fc_x2_conjugate_dot_prod_32fc_a_generic(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; float * res = (float*) result; float * in = (float*) input; float * tp = (float*) taps; unsigned int n_2_ccomplex_blocks = num_bytes >> 4; unsigned int isodd = (num_bytes >> 3) &1; float sum0[2] = {0,0}; float sum1[2] = {0,0}; unsigned int i = 0; for(i = 0; i < n_2_ccomplex_blocks; ++i) { sum0[0] += in[0] * tp[0] + in[1] * tp[1]; sum0[1] += (-in[0] * tp[1]) + in[1] * tp[0]; sum1[0] += in[2] * tp[2] + in[3] * tp[3]; sum1[1] += (-in[2] * tp[3]) + in[3] * tp[2]; in += 4; tp += 4; } res[0] = sum0[0] + sum1[0]; res[1] = sum0[1] + sum1[1]; for(i = 0; i < isodd; ++i) { *result += input[(num_bytes >> 3) - 1] * lv_conj(taps[(num_bytes >> 3) - 1]); } /* for(i = 0; i < num_bytes >> 3; ++i) { *result += input[i] * conjf(taps[i]); } */ } #endif /*LV_HAVE_GENERIC*/ #if LV_HAVE_SSE && LV_HAVE_64 static inline void volk_32fc_x2_conjugate_dot_prod_32fc_a_sse(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; __VOLK_ATTR_ALIGNED(16) static const uint32_t conjugator[4]= {0x00000000, 0x80000000, 0x00000000, 0x80000000}; asm volatile ( "# ccomplex_conjugate_dotprod_generic (float* result, const float *input,\n\t" "# const float *taps, unsigned num_bytes)\n\t" "# float sum0 = 0;\n\t" "# float sum1 = 0;\n\t" "# float sum2 = 0;\n\t" "# float sum3 = 0;\n\t" "# do {\n\t" "# sum0 += input[0] * taps[0] - input[1] * taps[1];\n\t" "# sum1 += input[0] * taps[1] + input[1] * taps[0];\n\t" "# sum2 += input[2] * taps[2] - input[3] * taps[3];\n\t" "# sum3 += input[2] * taps[3] + input[3] * taps[2];\n\t" "# input += 4;\n\t" "# taps += 4; \n\t" "# } while (--n_2_ccomplex_blocks != 0);\n\t" "# result[0] = sum0 + sum2;\n\t" "# result[1] = sum1 + sum3;\n\t" "# TODO: prefetch and better scheduling\n\t" " xor %%r9, %%r9\n\t" " xor %%r10, %%r10\n\t" " movq %[conjugator], %%r9\n\t" " movq %%rcx, %%rax\n\t" " movaps 0(%%r9), %%xmm8\n\t" " movq %%rcx, %%r8\n\t" " movq %[rsi], %%r9\n\t" " movq %[rdx], %%r10\n\t" " xorps %%xmm6, %%xmm6 # zero accumulators\n\t" " movaps 0(%%r9), %%xmm0\n\t" " xorps %%xmm7, %%xmm7 # zero accumulators\n\t" " movups 0(%%r10), %%xmm2\n\t" " shr $5, %%rax # rax = n_2_ccomplex_blocks / 2\n\t" " shr $4, %%r8\n\t" " xorps %%xmm8, %%xmm2\n\t" " jmp .%=L1_test\n\t" " # 4 taps / loop\n\t" " # something like ?? cycles / loop\n\t" ".%=Loop1: \n\t" "# complex prod: C += A * B, w/ temp Z & Y (or B), xmmPN=$0x8000000080000000\n\t" "# movaps (%%r9), %%xmmA\n\t" "# movaps (%%r10), %%xmmB\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# shufps $0xb1, %%xmmZ, %%xmmZ # swap internals\n\t" "# mulps %%xmmB, %%xmmA\n\t" "# mulps %%xmmZ, %%xmmB\n\t" "# # SSE replacement for: pfpnacc %%xmmB, %%xmmA\n\t" "# xorps %%xmmPN, %%xmmA\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# unpcklps %%xmmB, %%xmmA\n\t" "# unpckhps %%xmmB, %%xmmZ\n\t" "# movaps %%xmmZ, %%xmmY\n\t" "# shufps $0x44, %%xmmA, %%xmmZ # b01000100\n\t" "# shufps $0xee, %%xmmY, %%xmmA # b11101110\n\t" "# addps %%xmmZ, %%xmmA\n\t" "# addps %%xmmA, %%xmmC\n\t" "# A=xmm0, B=xmm2, Z=xmm4\n\t" "# A'=xmm1, B'=xmm3, Z'=xmm5\n\t" " movaps 16(%%r9), %%xmm1\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " movaps 16(%%r10), %%xmm3\n\t" " movaps %%xmm1, %%xmm5\n\t" " xorps %%xmm8, %%xmm3\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm3, %%xmm1\n\t" " shufps $0xb1, %%xmm5, %%xmm5 # swap internals\n\t" " addps %%xmm1, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " movaps 32(%%r9), %%xmm0\n\t" " addps %%xmm2, %%xmm7\n\t" " mulps %%xmm5, %%xmm3\n\t" " add $32, %%r9\n\t" " movaps 32(%%r10), %%xmm2\n\t" " addps %%xmm3, %%xmm7\n\t" " add $32, %%r10\n\t" " xorps %%xmm8, %%xmm2\n\t" ".%=L1_test:\n\t" " dec %%rax\n\t" " jge .%=Loop1\n\t" " # We've handled the bulk of multiplies up to here.\n\t" " # Let's sse if original n_2_ccomplex_blocks was odd.\n\t" " # If so, we've got 2 more taps to do.\n\t" " and $1, %%r8\n\t" " je .%=Leven\n\t" " # The count was odd, do 2 more taps.\n\t" " # Note that we've already got mm0/mm2 preloaded\n\t" " # from the main loop.\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " addps %%xmm2, %%xmm7\n\t" ".%=Leven:\n\t" " # neg inversor\n\t" " xorps %%xmm1, %%xmm1\n\t" " mov $0x80000000, %%r9\n\t" " movd %%r9, %%xmm1\n\t" " shufps $0x11, %%xmm1, %%xmm1 # b00010001 # 0 -0 0 -0\n\t" " # pfpnacc\n\t" " xorps %%xmm1, %%xmm6\n\t" " movaps %%xmm6, %%xmm2\n\t" " unpcklps %%xmm7, %%xmm6\n\t" " unpckhps %%xmm7, %%xmm2\n\t" " movaps %%xmm2, %%xmm3\n\t" " shufps $0x44, %%xmm6, %%xmm2 # b01000100\n\t" " shufps $0xee, %%xmm3, %%xmm6 # b11101110\n\t" " addps %%xmm2, %%xmm6\n\t" " # xmm6 = r1 i2 r3 i4\n\t" " movhlps %%xmm6, %%xmm4 # xmm4 = r3 i4 ?? ??\n\t" " addps %%xmm4, %%xmm6 # xmm6 = r1+r3 i2+i4 ?? ??\n\t" " movlps %%xmm6, (%[rdi]) # store low 2x32 bits (complex) to memory\n\t" : :[rsi] "r" (input), [rdx] "r" (taps), "c" (num_bytes), [rdi] "r" (result), [conjugator] "r" (conjugator) :"rax", "r8", "r9", "r10" ); int getem = num_bytes % 16; for(; getem > 0; getem -= 8) { *result += (input[(num_bytes >> 3) - 1] * lv_conj(taps[(num_bytes >> 3) - 1])); } return; } #endif #if LV_HAVE_SSE && LV_HAVE_32 static inline void volk_32fc_x2_conjugate_dot_prod_32fc_a_sse_32(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; __VOLK_ATTR_ALIGNED(16) static const uint32_t conjugator[4]= {0x00000000, 0x80000000, 0x00000000, 0x80000000}; int bound = num_bytes >> 4; int leftovers = num_bytes % 16; asm volatile ( " #pushl %%ebp\n\t" " #movl %%esp, %%ebp\n\t" " #movl 12(%%ebp), %%eax # input\n\t" " #movl 16(%%ebp), %%edx # taps\n\t" " #movl 20(%%ebp), %%ecx # n_bytes\n\t" " movaps 0(%[conjugator]), %%xmm1\n\t" " xorps %%xmm6, %%xmm6 # zero accumulators\n\t" " movaps 0(%[eax]), %%xmm0\n\t" " xorps %%xmm7, %%xmm7 # zero accumulators\n\t" " movaps 0(%[edx]), %%xmm2\n\t" " movl %[ecx], (%[out])\n\t" " shrl $5, %[ecx] # ecx = n_2_ccomplex_blocks / 2\n\t" " xorps %%xmm1, %%xmm2\n\t" " jmp .%=L1_test\n\t" " # 4 taps / loop\n\t" " # something like ?? cycles / loop\n\t" ".%=Loop1: \n\t" "# complex prod: C += A * B, w/ temp Z & Y (or B), xmmPN=$0x8000000080000000\n\t" "# movaps (%[eax]), %%xmmA\n\t" "# movaps (%[edx]), %%xmmB\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# shufps $0xb1, %%xmmZ, %%xmmZ # swap internals\n\t" "# mulps %%xmmB, %%xmmA\n\t" "# mulps %%xmmZ, %%xmmB\n\t" "# # SSE replacement for: pfpnacc %%xmmB, %%xmmA\n\t" "# xorps %%xmmPN, %%xmmA\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# unpcklps %%xmmB, %%xmmA\n\t" "# unpckhps %%xmmB, %%xmmZ\n\t" "# movaps %%xmmZ, %%xmmY\n\t" "# shufps $0x44, %%xmmA, %%xmmZ # b01000100\n\t" "# shufps $0xee, %%xmmY, %%xmmA # b11101110\n\t" "# addps %%xmmZ, %%xmmA\n\t" "# addps %%xmmA, %%xmmC\n\t" "# A=xmm0, B=xmm2, Z=xmm4\n\t" "# A'=xmm1, B'=xmm3, Z'=xmm5\n\t" " movaps 16(%[edx]), %%xmm3\n\t" " movaps %%xmm0, %%xmm4\n\t" " xorps %%xmm1, %%xmm3\n\t" " mulps %%xmm2, %%xmm0\n\t" " movaps 16(%[eax]), %%xmm1\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " movaps %%xmm1, %%xmm5\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm3, %%xmm1\n\t" " shufps $0xb1, %%xmm5, %%xmm5 # swap internals\n\t" " addps %%xmm1, %%xmm6\n\t" " movaps 0(%[conjugator]), %%xmm1\n\t" " mulps %%xmm4, %%xmm2\n\t" " movaps 32(%[eax]), %%xmm0\n\t" " addps %%xmm2, %%xmm7\n\t" " mulps %%xmm5, %%xmm3\n\t" " addl $32, %[eax]\n\t" " movaps 32(%[edx]), %%xmm2\n\t" " addps %%xmm3, %%xmm7\n\t" " xorps %%xmm1, %%xmm2\n\t" " addl $32, %[edx]\n\t" ".%=L1_test:\n\t" " decl %[ecx]\n\t" " jge .%=Loop1\n\t" " # We've handled the bulk of multiplies up to here.\n\t" " # Let's sse if original n_2_ccomplex_blocks was odd.\n\t" " # If so, we've got 2 more taps to do.\n\t" " movl 0(%[out]), %[ecx] # n_2_ccomplex_blocks\n\t" " shrl $4, %[ecx]\n\t" " andl $1, %[ecx]\n\t" " je .%=Leven\n\t" " # The count was odd, do 2 more taps.\n\t" " # Note that we've already got mm0/mm2 preloaded\n\t" " # from the main loop.\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " addps %%xmm2, %%xmm7\n\t" ".%=Leven:\n\t" " # neg inversor\n\t" " #movl 8(%%ebp), %[eax] \n\t" " xorps %%xmm1, %%xmm1\n\t" " movl $0x80000000, (%[out])\n\t" " movss (%[out]), %%xmm1\n\t" " shufps $0x11, %%xmm1, %%xmm1 # b00010001 # 0 -0 0 -0\n\t" " # pfpnacc\n\t" " xorps %%xmm1, %%xmm6\n\t" " movaps %%xmm6, %%xmm2\n\t" " unpcklps %%xmm7, %%xmm6\n\t" " unpckhps %%xmm7, %%xmm2\n\t" " movaps %%xmm2, %%xmm3\n\t" " shufps $0x44, %%xmm6, %%xmm2 # b01000100\n\t" " shufps $0xee, %%xmm3, %%xmm6 # b11101110\n\t" " addps %%xmm2, %%xmm6\n\t" " # xmm6 = r1 i2 r3 i4\n\t" " #movl 8(%%ebp), %[eax] # @result\n\t" " movhlps %%xmm6, %%xmm4 # xmm4 = r3 i4 ?? ??\n\t" " addps %%xmm4, %%xmm6 # xmm6 = r1+r3 i2+i4 ?? ??\n\t" " movlps %%xmm6, (%[out]) # store low 2x32 bits (complex) to memory\n\t" " #popl %%ebp\n\t" : : [eax] "r" (input), [edx] "r" (taps), [ecx] "r" (num_bytes), [out] "r" (result), [conjugator] "r" (conjugator) ); printf("%d, %d\n", leftovers, bound); for(; leftovers > 0; leftovers -= 8) { *result += (input[(bound << 1)] * lv_conj(taps[(bound << 1)])); } return; } #endif /*LV_HAVE_SSE*/ #endif /*INCLUDED_volk_32fc_x2_conjugate_dot_prod_32fc_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_s32f_deinterleave_real_32f.h0000664000175000017500000001025412207440367025733 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_s32f_deinterleave_real_32f_a_H #define INCLUDED_volk_16ic_s32f_deinterleave_real_32f_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Deinterleaves the complex 16 bit vector into I float vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_s32f_deinterleave_real_32f_a_sse4_1(float* iBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128 iFloatValue; const float iScalar= 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); __m128i complexVal, iIntVal; int8_t* complexVectorPtr = (int8_t*)complexVector; __m128i moveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 13, 12, 9, 8, 5, 4, 1, 0); for(;number < quarterPoints; number++){ complexVal = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal = _mm_shuffle_epi8(complexVal, moveMask); iIntVal = _mm_cvtepi16_epi32(complexVal); iFloatValue = _mm_cvtepi32_ps(iIntVal); iFloatValue = _mm_mul_ps(iFloatValue, invScalar); _mm_store_ps(iBufferPtr, iFloatValue); iBufferPtr += 4; } number = quarterPoints * 4; int16_t* sixteenTComplexVectorPtr = (int16_t*)&complexVector[number]; for(; number < num_points; number++){ *iBufferPtr++ = ((float)(*sixteenTComplexVectorPtr++)) * iScalar; sixteenTComplexVectorPtr++; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex 16 bit vector into I float vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_s32f_deinterleave_real_32f_a_sse(float* iBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128 iValue; const float iScalar = 1.0/scalar; __m128 invScalar = _mm_set_ps1(iScalar); int16_t* complexVectorPtr = (int16_t*)complexVector; __VOLK_ATTR_ALIGNED(16) float floatBuffer[4]; for(;number < quarterPoints; number++){ floatBuffer[0] = (float)(*complexVectorPtr); complexVectorPtr += 2; floatBuffer[1] = (float)(*complexVectorPtr); complexVectorPtr += 2; floatBuffer[2] = (float)(*complexVectorPtr); complexVectorPtr += 2; floatBuffer[3] = (float)(*complexVectorPtr); complexVectorPtr += 2; iValue = _mm_load_ps(floatBuffer); iValue = _mm_mul_ps(iValue, invScalar); _mm_store_ps(iBufferPtr, iValue); iBufferPtr += 4; } number = quarterPoints * 4; complexVectorPtr = (int16_t*)&complexVector[number]; for(; number < num_points; number++){ *iBufferPtr++ = ((float)(*complexVectorPtr++)) * iScalar; complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 16 bit vector into I float vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_s32f_deinterleave_real_32f_generic(float* iBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const int16_t* complexVectorPtr = (const int16_t*)complexVector; float* iBufferPtr = iBuffer; const float invScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *iBufferPtr++ = ((float)(*complexVectorPtr++)) * invScalar; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16ic_s32f_deinterleave_real_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8i_convert_16i.h0000664000175000017500000001206612207440367022672 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8i_convert_16i_u_H #define INCLUDED_volk_8i_convert_16i_u_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Converts the input 8 bit integer data into 16 bit integer data \param inputVector The 8 bit input data buffer \param outputVector The 16 bit output data buffer \param num_points The number of data values to be converted \note Input and output buffers do NOT need to be properly aligned */ static inline void volk_8i_convert_16i_u_sse4_1(int16_t* outputVector, const int8_t* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; const __m128i* inputVectorPtr = (const __m128i*)inputVector; __m128i* outputVectorPtr = (__m128i*)outputVector; __m128i inputVal; __m128i ret; for(;number < sixteenthPoints; number++){ inputVal = _mm_loadu_si128(inputVectorPtr); ret = _mm_cvtepi8_epi16(inputVal); ret = _mm_slli_epi16(ret, 8); // Multiply by 256 _mm_storeu_si128(outputVectorPtr, ret); outputVectorPtr++; inputVal = _mm_srli_si128(inputVal, 8); ret = _mm_cvtepi8_epi16(inputVal); ret = _mm_slli_epi16(ret, 8); // Multiply by 256 _mm_storeu_si128(outputVectorPtr, ret); outputVectorPtr++; inputVectorPtr++; } number = sixteenthPoints * 16; for(; number < num_points; number++){ outputVector[number] = (int16_t)(inputVector[number])*256; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 8 bit integer data into 16 bit integer data \param inputVector The 8 bit input data buffer \param outputVector The 16 bit output data buffer \param num_points The number of data values to be converted \note Input and output buffers do NOT need to be properly aligned */ static inline void volk_8i_convert_16i_generic(int16_t* outputVector, const int8_t* inputVector, unsigned int num_points){ int16_t* outputVectorPtr = outputVector; const int8_t* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((int16_t)(*inputVectorPtr++)) * 256; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_VOLK_8s_CONVERT_16s_UNALIGNED8_H */ #ifndef INCLUDED_volk_8i_convert_16i_a_H #define INCLUDED_volk_8i_convert_16i_a_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Converts the input 8 bit integer data into 16 bit integer data \param inputVector The 8 bit input data buffer \param outputVector The 16 bit output data buffer \param num_points The number of data values to be converted */ static inline void volk_8i_convert_16i_a_sse4_1(int16_t* outputVector, const int8_t* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; const __m128i* inputVectorPtr = (const __m128i*)inputVector; __m128i* outputVectorPtr = (__m128i*)outputVector; __m128i inputVal; __m128i ret; for(;number < sixteenthPoints; number++){ inputVal = _mm_load_si128(inputVectorPtr); ret = _mm_cvtepi8_epi16(inputVal); ret = _mm_slli_epi16(ret, 8); // Multiply by 256 _mm_store_si128(outputVectorPtr, ret); outputVectorPtr++; inputVal = _mm_srli_si128(inputVal, 8); ret = _mm_cvtepi8_epi16(inputVal); ret = _mm_slli_epi16(ret, 8); // Multiply by 256 _mm_store_si128(outputVectorPtr, ret); outputVectorPtr++; inputVectorPtr++; } number = sixteenthPoints * 16; for(; number < num_points; number++){ outputVector[number] = (int16_t)(inputVector[number])*256; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 8 bit integer data into 16 bit integer data \param inputVector The 8 bit input data buffer \param outputVector The 16 bit output data buffer \param num_points The number of data values to be converted */ static inline void volk_8i_convert_16i_a_generic(int16_t* outputVector, const int8_t* inputVector, unsigned int num_points){ int16_t* outputVectorPtr = outputVector; const int8_t* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((int16_t)(*inputVectorPtr++)) * 256; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Converts the input 8 bit integer data into 16 bit integer data \param inputVector The 8 bit input data buffer \param outputVector The 16 bit output data buffer \param num_points The number of data values to be converted */ extern void volk_8i_convert_16i_a_orc_impl(int16_t* outputVector, const int8_t* inputVector, unsigned int num_points); static inline void volk_8i_convert_16i_u_orc(int16_t* outputVector, const int8_t* inputVector, unsigned int num_points){ volk_8i_convert_16i_a_orc_impl(outputVector, inputVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_VOLK_8s_CONVERT_16s_ALIGNED8_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_deinterleave_real_32f.h0000664000175000017500000000374712207440367025102 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_deinterleave_real_32f_a_H #define INCLUDED_volk_32fc_deinterleave_real_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_real_32f_a_sse(float* iBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (const float*)complexVector; float* iBufferPtr = iBuffer; __m128 cplxValue1, cplxValue2, iValue; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); _mm_store_ps(iBufferPtr, iValue); iBufferPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_real_32f_generic(float* iBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; float* iBufferPtr = iBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_deinterleave_real_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_deinterleave_real_8i.h0000664000175000017500000000715012207440367025025 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_deinterleave_real_8i_a_H #define INCLUDED_volk_16ic_deinterleave_real_8i_a_H #include #include #ifdef LV_HAVE_SSSE3 #include /*! \brief Deinterleaves the complex 16 bit vector into 8 bit I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_real_8i_a_ssse3(int8_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (int8_t*)complexVector; int8_t* iBufferPtr = iBuffer; __m128i iMoveMask1 = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 13, 12, 9, 8, 5, 4, 1, 0); __m128i iMoveMask2 = _mm_set_epi8(13, 12, 9, 8, 5, 4, 1, 0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80); __m128i complexVal1, complexVal2, complexVal3, complexVal4, iOutputVal; unsigned int sixteenthPoints = num_points / 16; for(number = 0; number < sixteenthPoints; number++){ complexVal1 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal2 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal3 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal4 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal1 = _mm_shuffle_epi8(complexVal1, iMoveMask1); complexVal2 = _mm_shuffle_epi8(complexVal2, iMoveMask2); complexVal1 = _mm_or_si128(complexVal1, complexVal2); complexVal3 = _mm_shuffle_epi8(complexVal3, iMoveMask1); complexVal4 = _mm_shuffle_epi8(complexVal4, iMoveMask2); complexVal3 = _mm_or_si128(complexVal3, complexVal4); complexVal1 = _mm_srai_epi16(complexVal1, 8); complexVal3 = _mm_srai_epi16(complexVal3, 8); iOutputVal = _mm_packs_epi16(complexVal1, complexVal3); _mm_store_si128((__m128i*)iBufferPtr, iOutputVal); iBufferPtr += 16; } number = sixteenthPoints * 16; int16_t* int16ComplexVectorPtr = (int16_t*)complexVectorPtr; for(; number < num_points; number++){ *iBufferPtr++ = ((int8_t)(*int16ComplexVectorPtr++ >> 8)); int16ComplexVectorPtr++; } } #endif /* LV_HAVE_SSSE3 */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 16 bit vector into 8 bit I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_real_8i_generic(int8_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; int16_t* complexVectorPtr = (int16_t*)complexVector; int8_t* iBufferPtr = iBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = ((int8_t)(*complexVectorPtr++ >> 8)); complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Deinterleaves the complex 16 bit vector into 8 bit I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ extern void volk_16ic_deinterleave_real_8i_a_orc_impl(int8_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points); static inline void volk_16ic_deinterleave_real_8i_u_orc(int8_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ volk_16ic_deinterleave_real_8i_a_orc_impl(iBuffer, complexVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_16ic_deinterleave_real_8i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_x2_s32f_square_dist_scalar_mult_32f.h0000664000175000017500000000534212207440367027600 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_x2_s32f_square_dist_scalar_mult_32f_a_H #define INCLUDED_volk_32fc_x2_s32f_square_dist_scalar_mult_32f_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include #include static inline void volk_32fc_x2_s32f_square_dist_scalar_mult_32f_a_sse3(float* target, lv_32fc_t* src0, lv_32fc_t* points, float scalar, unsigned int num_points) { const unsigned int num_bytes = num_points*8; __m128 xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8; lv_32fc_t diff; memset(&diff, 0x0, 2*sizeof(float)); float sq_dist = 0.0; int bound = num_bytes >> 5; int leftovers0 = (num_bytes >> 4) & 1; int leftovers1 = (num_bytes >> 3) & 1; int i = 0; xmm1 = _mm_setzero_ps(); xmm1 = _mm_loadl_pi(xmm1, (__m64*)src0); xmm2 = _mm_load_ps((float*)&points[0]); xmm8 = _mm_load1_ps(&scalar); xmm1 = _mm_movelh_ps(xmm1, xmm1); xmm3 = _mm_load_ps((float*)&points[2]); for(; i < bound - 1; ++i) { xmm4 = _mm_sub_ps(xmm1, xmm2); xmm5 = _mm_sub_ps(xmm1, xmm3); points += 4; xmm6 = _mm_mul_ps(xmm4, xmm4); xmm7 = _mm_mul_ps(xmm5, xmm5); xmm2 = _mm_load_ps((float*)&points[0]); xmm4 = _mm_hadd_ps(xmm6, xmm7); xmm3 = _mm_load_ps((float*)&points[2]); xmm4 = _mm_mul_ps(xmm4, xmm8); _mm_store_ps(target, xmm4); target += 4; } xmm4 = _mm_sub_ps(xmm1, xmm2); xmm5 = _mm_sub_ps(xmm1, xmm3); points += 4; xmm6 = _mm_mul_ps(xmm4, xmm4); xmm7 = _mm_mul_ps(xmm5, xmm5); xmm4 = _mm_hadd_ps(xmm6, xmm7); xmm4 = _mm_mul_ps(xmm4, xmm8); _mm_store_ps(target, xmm4); target += 4; for(i = 0; i < leftovers0; ++i) { xmm2 = _mm_load_ps((float*)&points[0]); xmm4 = _mm_sub_ps(xmm1, xmm2); points += 2; xmm6 = _mm_mul_ps(xmm4, xmm4); xmm4 = _mm_hadd_ps(xmm6, xmm6); xmm4 = _mm_mul_ps(xmm4, xmm8); _mm_storeh_pi((__m64*)target, xmm4); target += 2; } for(i = 0; i < leftovers1; ++i) { diff = src0[0] - points[0]; sq_dist = scalar * (lv_creal(diff) * lv_creal(diff) + lv_cimag(diff) * lv_cimag(diff)); target[0] = sq_dist; } } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_GENERIC static inline void volk_32fc_x2_s32f_square_dist_scalar_mult_32f_generic(float* target, lv_32fc_t* src0, lv_32fc_t* points, float scalar, unsigned int num_points) { const unsigned int num_bytes = num_points*8; lv_32fc_t diff; float sq_dist; unsigned int i = 0; for(; i < num_bytes >> 3; ++i) { diff = src0[0] - points[i]; sq_dist = scalar * (lv_creal(diff) * lv_creal(diff) + lv_cimag(diff) * lv_cimag(diff)); target[i] = sq_dist; } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_32fc_x2_s32f_square_dist_scalar_mult_32f_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_convert_16i.h0000664000175000017500000002354412207440367023604 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_convert_16i_u_H #define INCLUDED_volk_32f_s32f_convert_16i_u_H #include #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 16 bit integer value \param inputVector The floating point input data buffer \param outputVector The 16 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_16i_u_sse2(int16_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; const float* inputVectorPtr = (const float*)inputVector; int16_t* outputVectorPtr = outputVector; float min_val = -32768; float max_val = 32767; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 inputVal1, inputVal2; __m128i intInputVal1, intInputVal2; __m128 ret1, ret2; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); for(;number < eighthPoints; number++){ inputVal1 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; inputVal2 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; // Scale and clip ret1 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); ret2 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal2, vScalar), vmax_val), vmin_val); intInputVal1 = _mm_cvtps_epi32(ret1); intInputVal2 = _mm_cvtps_epi32(ret2); intInputVal1 = _mm_packs_epi32(intInputVal1, intInputVal2); _mm_storeu_si128((__m128i*)outputVectorPtr, intInputVal1); outputVectorPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int16_t)rintf(r); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 16 bit integer value \param inputVector The floating point input data buffer \param outputVector The 16 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_16i_u_sse(int16_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int16_t* outputVectorPtr = outputVector; float min_val = -32768; float max_val = 32767; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 ret; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ ret = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; // Scale and clip ret = _mm_max_ps(_mm_min_ps(_mm_mul_ps(ret, vScalar), vmax_val), vmin_val); _mm_store_ps(outputFloatBuffer, ret); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[0]); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[1]); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[2]); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[3]); } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int16_t)rintf(r); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 16 bit integer value \param inputVector The floating point input data buffer \param outputVector The 16 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_16i_generic(int16_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ int16_t* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; float min_val = -32768; float max_val = 32767; float r; for(number = 0; number < num_points; number++){ r = *inputVectorPtr++ * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; *outputVectorPtr++ = (int16_t)rintf(r); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_convert_16i_u_H */ #ifndef INCLUDED_volk_32f_s32f_convert_16i_a_H #define INCLUDED_volk_32f_s32f_convert_16i_a_H #include #include #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 16 bit integer value \param inputVector The floating point input data buffer \param outputVector The 16 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_16i_a_sse2(int16_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; const float* inputVectorPtr = (const float*)inputVector; int16_t* outputVectorPtr = outputVector; float min_val = -32768; float max_val = 32767; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 inputVal1, inputVal2; __m128i intInputVal1, intInputVal2; __m128 ret1, ret2; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); for(;number < eighthPoints; number++){ inputVal1 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; inputVal2 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; // Scale and clip ret1 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); ret2 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal2, vScalar), vmax_val), vmin_val); intInputVal1 = _mm_cvtps_epi32(ret1); intInputVal2 = _mm_cvtps_epi32(ret2); intInputVal1 = _mm_packs_epi32(intInputVal1, intInputVal2); _mm_store_si128((__m128i*)outputVectorPtr, intInputVal1); outputVectorPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int16_t)rintf(r); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 16 bit integer value \param inputVector The floating point input data buffer \param outputVector The 16 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_16i_a_sse(int16_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int16_t* outputVectorPtr = outputVector; float min_val = -32768; float max_val = 32767; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 ret; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ ret = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; // Scale and clip ret = _mm_max_ps(_mm_min_ps(_mm_mul_ps(ret, vScalar), vmax_val), vmin_val); _mm_store_ps(outputFloatBuffer, ret); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[0]); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[1]); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[2]); *outputVectorPtr++ = (int16_t)rintf(outputFloatBuffer[3]); } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int16_t)rintf(r); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 16 bit integer value \param inputVector The floating point input data buffer \param outputVector The 16 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_16i_a_generic(int16_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ int16_t* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; float min_val = -32768; float max_val = 32767; float r; for(number = 0; number < num_points; number++){ r = *inputVectorPtr++ * scalar; if(r < min_val) r = min_val; else if(r > max_val) r = max_val; *outputVectorPtr++ = (int16_t)rintf(r); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_convert_16i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_add_32f.h0000664000175000017500000001150712207440367022417 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_add_32f_u_H #define INCLUDED_volk_32f_x2_add_32f_u_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Adds the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be added \param bVector One of the vectors to be added \param num_points The number of values in aVector and bVector to be added together and stored into cVector */ static inline void volk_32f_x2_add_32f_u_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_loadu_ps(aPtr); bVal = _mm_loadu_ps(bPtr); cVal = _mm_add_ps(aVal, bVal); _mm_storeu_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) + (*bPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Adds the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be added \param bVector One of the vectors to be added \param num_points The number of values in aVector and bVector to be added together and stored into cVector */ static inline void volk_32f_x2_add_32f_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) + (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_x2_add_32f_u_H */ #ifndef INCLUDED_volk_32f_x2_add_32f_a_H #define INCLUDED_volk_32f_x2_add_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Adds the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be added \param bVector One of the vectors to be added \param num_points The number of values in aVector and bVector to be added together and stored into cVector */ static inline void volk_32f_x2_add_32f_a_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_add_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) + (*bPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Adds the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be added \param bVector One of the vectors to be added \param num_points The number of values in aVector and bVector to be added together and stored into cVector */ static inline void volk_32f_x2_add_32f_a_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) + (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Adds the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be added \param bVector One of the vectors to be added \param num_points The number of values in aVector and bVector to be added together and stored into cVector */ extern void volk_32f_x2_add_32f_a_orc_impl(float* cVector, const float* aVector, const float* bVector, unsigned int num_points); static inline void volk_32f_x2_add_32f_u_orc(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ volk_32f_x2_add_32f_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_x2_add_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_multiply_32f.h0000664000175000017500000001517212207440367023774 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_multiply_32f_u_H #define INCLUDED_volk_32f_s32f_multiply_32f_u_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_s32f_multiply_32f_u_sse(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; __m128 aVal, bVal, cVal; bVal = _mm_set_ps1(scalar); for(;number < quarterPoints; number++){ aVal = _mm_loadu_ps(aPtr); cVal = _mm_mul_ps(aVal, bVal); _mm_storeu_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_AVX #include /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_s32f_multiply_32f_u_avx(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; float* cPtr = cVector; const float* aPtr = aVector; __m256 aVal, bVal, cVal; bVal = _mm256_set1_ps(scalar); for(;number < eighthPoints; number++){ aVal = _mm256_loadu_ps(aPtr); cVal = _mm256_mul_ps(aVal, bVal); _mm256_storeu_ps(cPtr,cVal); // Store the results back into the C container aPtr += 8; cPtr += 8; } number = eighthPoints * 8; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * scalar; } } #endif /* LV_HAVE_AVX */ #ifdef LV_HAVE_GENERIC /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_s32f_multiply_32f_generic(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const float* inputPtr = aVector; float* outputPtr = cVector; for(number = 0; number < num_points; number++){ *outputPtr = (*inputPtr) * scalar; inputPtr++; outputPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_multiply_32f_u_H */ #ifndef INCLUDED_volk_32f_s32f_multiply_32f_a_H #define INCLUDED_volk_32f_s32f_multiply_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_s32f_multiply_32f_a_sse(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; __m128 aVal, bVal, cVal; bVal = _mm_set_ps1(scalar); for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); cVal = _mm_mul_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_AVX #include /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_s32f_multiply_32f_a_avx(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; float* cPtr = cVector; const float* aPtr = aVector; __m256 aVal, bVal, cVal; bVal = _mm256_set1_ps(scalar); for(;number < eighthPoints; number++){ aVal = _mm256_load_ps(aPtr); cVal = _mm256_mul_ps(aVal, bVal); _mm256_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 8; cPtr += 8; } number = eighthPoints * 8; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * scalar; } } #endif /* LV_HAVE_AVX */ #ifdef LV_HAVE_GENERIC /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_s32f_multiply_32f_a_generic(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const float* inputPtr = aVector; float* outputPtr = cVector; for(number = 0; number < num_points; number++){ *outputPtr = (*inputPtr) * scalar; inputPtr++; outputPtr++; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Scalar float multiply \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param scalar the scalar value \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ extern void volk_32f_s32f_multiply_32f_a_orc_impl(float* dst, const float* src, const float scalar, unsigned int num_points); static inline void volk_32f_s32f_multiply_32f_u_orc(float* cVector, const float* aVector, const float scalar, unsigned int num_points){ volk_32f_s32f_multiply_32f_a_orc_impl(cVector, aVector, scalar, num_points); } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_multiply_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_max_32f.h0000664000175000017500000000566012207440367022457 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_max_32f_a_H #define INCLUDED_volk_32f_x2_max_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Selects maximum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_32f_x2_max_32f_a_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_max_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ const float a = *aPtr++; const float b = *bPtr++; *cPtr++ = ( a > b ? a : b); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Selects maximum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_32f_x2_max_32f_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float a = *aPtr++; const float b = *bPtr++; *cPtr++ = ( a > b ? a : b); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Selects maximum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ extern void volk_32f_x2_max_32f_a_orc_impl(float* cVector, const float* aVector, const float* bVector, unsigned int num_points); static inline void volk_32f_x2_max_32f_u_orc(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ volk_32f_x2_max_32f_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_x2_max_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_deinterleave_16i_x2.h0000664000175000017500000000535612207440367024441 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8ic_deinterleave_16i_x2_a_H #define INCLUDED_volk_8ic_deinterleave_16i_x2_a_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Deinterleaves the complex 8 bit vector into I & Q 16 bit vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_deinterleave_16i_x2_a_sse4_1(int16_t* iBuffer, int16_t* qBuffer, const lv_8sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (int8_t*)complexVector; int16_t* iBufferPtr = iBuffer; int16_t* qBufferPtr = qBuffer; __m128i iMoveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 14, 12, 10, 8, 6, 4, 2, 0); __m128i qMoveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 15, 13, 11, 9, 7, 5, 3, 1); __m128i complexVal, iOutputVal, qOutputVal; unsigned int eighthPoints = num_points / 8; for(number = 0; number < eighthPoints; number++){ complexVal = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; iOutputVal = _mm_shuffle_epi8(complexVal, iMoveMask); qOutputVal = _mm_shuffle_epi8(complexVal, qMoveMask); iOutputVal = _mm_cvtepi8_epi16(iOutputVal); iOutputVal = _mm_slli_epi16(iOutputVal, 8); qOutputVal = _mm_cvtepi8_epi16(qOutputVal); qOutputVal = _mm_slli_epi16(qOutputVal, 8); _mm_store_si128((__m128i*)iBufferPtr, iOutputVal); _mm_store_si128((__m128i*)qBufferPtr, qOutputVal); iBufferPtr += 8; qBufferPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = ((int16_t)*complexVectorPtr++) * 256; *qBufferPtr++ = ((int16_t)*complexVectorPtr++) * 256; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 8 bit vector into I & Q 16 bit vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_deinterleave_16i_x2_generic(int16_t* iBuffer, int16_t* qBuffer, const lv_8sc_t* complexVector, unsigned int num_points){ const int8_t* complexVectorPtr = (const int8_t*)complexVector; int16_t* iBufferPtr = iBuffer; int16_t* qBufferPtr = qBuffer; unsigned int number; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (int16_t)(*complexVectorPtr++)*256; *qBufferPtr++ = (int16_t)(*complexVectorPtr++)*256; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_8ic_deinterleave_16i_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_deinterleave_64f_x2.h0000664000175000017500000001146512207440367024511 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_deinterleave_64f_x2_u_H #define INCLUDED_volk_32fc_deinterleave_64f_x2_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Deinterleaves the lv_32fc_t vector into double I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_64f_x2_u_sse2(double* iBuffer, double* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; double* iBufferPtr = iBuffer; double* qBufferPtr = qBuffer; const unsigned int halfPoints = num_points / 2; __m128 cplxValue, fVal; __m128d dVal; for(;number < halfPoints; number++){ cplxValue = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i1i2 format fVal = _mm_shuffle_ps(cplxValue, cplxValue, _MM_SHUFFLE(2,0,2,0)); dVal = _mm_cvtps_pd(fVal); _mm_storeu_pd(iBufferPtr, dVal); // Arrange in q1q2q1q2 format fVal = _mm_shuffle_ps(cplxValue, cplxValue, _MM_SHUFFLE(3,1,3,1)); dVal = _mm_cvtps_pd(fVal); _mm_storeu_pd(qBufferPtr, dVal); iBufferPtr += 2; qBufferPtr += 2; } number = halfPoints * 2; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the lv_32fc_t vector into double I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_64f_x2_generic(double* iBuffer, double* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; double* iBufferPtr = iBuffer; double* qBufferPtr = qBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (double)*complexVectorPtr++; *qBufferPtr++ = (double)*complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_deinterleave_64f_x2_u_H */ #ifndef INCLUDED_volk_32fc_deinterleave_64f_x2_a_H #define INCLUDED_volk_32fc_deinterleave_64f_x2_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Deinterleaves the lv_32fc_t vector into double I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_64f_x2_a_sse2(double* iBuffer, double* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; double* iBufferPtr = iBuffer; double* qBufferPtr = qBuffer; const unsigned int halfPoints = num_points / 2; __m128 cplxValue, fVal; __m128d dVal; for(;number < halfPoints; number++){ cplxValue = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i1i2 format fVal = _mm_shuffle_ps(cplxValue, cplxValue, _MM_SHUFFLE(2,0,2,0)); dVal = _mm_cvtps_pd(fVal); _mm_store_pd(iBufferPtr, dVal); // Arrange in q1q2q1q2 format fVal = _mm_shuffle_ps(cplxValue, cplxValue, _MM_SHUFFLE(3,1,3,1)); dVal = _mm_cvtps_pd(fVal); _mm_store_pd(qBufferPtr, dVal); iBufferPtr += 2; qBufferPtr += 2; } number = halfPoints * 2; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the lv_32fc_t vector into double I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_64f_x2_a_generic(double* iBuffer, double* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; double* iBufferPtr = iBuffer; double* qBufferPtr = qBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (double)*complexVectorPtr++; *qBufferPtr++ = (double)*complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_deinterleave_64f_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_invsqrt_32f.h0000664000175000017500000000455512237515112022763 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_invsqrt_32f_a_H #define INCLUDED_volk_32f_invsqrt_32f_a_H #include #include #include static inline float Q_rsqrt( float number ) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // evil floating point bit level hacking i = 0x5f3759df - ( i >> 1 ); // what the fuck? y = * ( float * ) &i; y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; } #ifdef LV_HAVE_SSE #include /*! \brief Sqrts the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be invsqrted \param num_points The number of values in aVector and bVector to be invsqrted together and stored into cVector */ static inline void volk_32f_invsqrt_32f_a_sse(float* cVector, const float* aVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; __m128 aVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); cVal = _mm_rsqrt_ps(aVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = Q_rsqrt(*aPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Sqrts the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be invsqrted \param num_points The number of values in aVector and bVector to be invsqrted together and stored into cVector */ static inline void volk_32f_invsqrt_32f_generic(float* cVector, const float* aVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = Q_rsqrt(*aPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_invsqrt_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_magnitude_32f.h0000664000175000017500000002320312207440367023372 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_magnitude_32f_u_H #define INCLUDED_volk_32fc_magnitude_32f_u_H #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_32f_u_sse3(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); _mm_storeu_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_32f_u_sse(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, iValue, qValue, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); iValue = _mm_mul_ps(iValue, iValue); // Square the I values qValue = _mm_mul_ps(qValue, qValue); // Square the Q Values result = _mm_add_ps(iValue, qValue); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); _mm_storeu_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_32f_generic(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *magnitudeVectorPtr++ = sqrtf((real*real) + (imag*imag)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_magnitude_32f_u_H */ #ifndef INCLUDED_volk_32fc_magnitude_32f_a_H #define INCLUDED_volk_32fc_magnitude_32f_a_H #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_32f_a_sse3(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); _mm_store_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_32f_a_sse(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, iValue, qValue, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); iValue = _mm_mul_ps(iValue, iValue); // Square the I values qValue = _mm_mul_ps(qValue, qValue); // Square the Q Values result = _mm_add_ps(iValue, qValue); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); _mm_store_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_32f_a_generic(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *magnitudeVectorPtr++ = sqrtf((real*real) + (imag*imag)); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ extern void volk_32fc_magnitude_32f_a_orc_impl(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points); static inline void volk_32fc_magnitude_32f_u_orc(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ volk_32fc_magnitude_32f_a_orc_impl(magnitudeVector, complexVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32fc_magnitude_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_32fc_dot_prod_32fc.h0000664000175000017500000000634712207440367024063 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_32fc_dot_prod_32fc_a_H #define INCLUDED_volk_16i_32fc_dot_prod_32fc_a_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_16i_32fc_dot_prod_32fc_generic(lv_32fc_t* result, const short* input, const lv_32fc_t * taps, unsigned int num_points) { static const int N_UNROLL = 4; lv_32fc_t acc0 = 0; lv_32fc_t acc1 = 0; lv_32fc_t acc2 = 0; lv_32fc_t acc3 = 0; unsigned i = 0; unsigned n = (num_points / N_UNROLL) * N_UNROLL; for(i = 0; i < n; i += N_UNROLL) { acc0 += taps[i + 0] * (float)input[i + 0]; acc1 += taps[i + 1] * (float)input[i + 1]; acc2 += taps[i + 2] * (float)input[i + 2]; acc3 += taps[i + 3] * (float)input[i + 3]; } for(; i < num_points; i++) { acc0 += taps[i] * (float)input[i]; } *result = acc0 + acc1 + acc2 + acc3; } #endif /*LV_HAVE_GENERIC*/ #if LV_HAVE_SSE && LV_HAVE_MMX static inline void volk_16i_32fc_dot_prod_32fc_a_sse( lv_32fc_t* result, const short* input, const lv_32fc_t* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 8; float res[2]; float *realpt = &res[0], *imagpt = &res[1]; const short* aPtr = input; const float* bPtr = (float*)taps; __m64 m0, m1; __m128 f0, f1, f2, f3; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ m0 = _mm_set_pi16(*(aPtr+3), *(aPtr+2), *(aPtr+1), *(aPtr+0)); m1 = _mm_set_pi16(*(aPtr+7), *(aPtr+6), *(aPtr+5), *(aPtr+4)); f0 = _mm_cvtpi16_ps(m0); f1 = _mm_cvtpi16_ps(m0); f2 = _mm_cvtpi16_ps(m1); f3 = _mm_cvtpi16_ps(m1); a0Val = _mm_unpacklo_ps(f0, f1); a1Val = _mm_unpackhi_ps(f0, f1); a2Val = _mm_unpacklo_ps(f2, f3); a3Val = _mm_unpackhi_ps(f2, f3); b0Val = _mm_load_ps(bPtr); b1Val = _mm_load_ps(bPtr+4); b2Val = _mm_load_ps(bPtr+8); b3Val = _mm_load_ps(bPtr+12); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm_add_ps(c1Val, dotProdVal1); dotProdVal2 = _mm_add_ps(c2Val, dotProdVal2); dotProdVal3 = _mm_add_ps(c3Val, dotProdVal3); aPtr += 8; bPtr += 16; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector *realpt = dotProductVector[0]; *imagpt = dotProductVector[1]; *realpt += dotProductVector[2]; *imagpt += dotProductVector[3]; number = sixteenthPoints*8; for(;number < num_points; number++){ *realpt += ((*aPtr) * (*bPtr++)); *imagpt += ((*aPtr++) * (*bPtr++)); } *result = *(lv_32fc_t*)(&res[0]); } #endif /*LV_HAVE_SSE && LV_HAVE_MMX*/ #endif /*INCLUDED_volk_16i_32fc_dot_prod_32fc_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_magnitude_16i.h0000664000175000017500000001731412207440367023412 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_magnitude_16i_a_H #define INCLUDED_volk_16ic_magnitude_16i_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_16ic_magnitude_16i_a_sse3(int16_t* magnitudeVector, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const int16_t* complexVectorPtr = (const int16_t*)complexVector; int16_t* magnitudeVectorPtr = magnitudeVector; __m128 vScalar = _mm_set_ps1(32768.0); __m128 invScalar = _mm_set_ps1(1.0/32768.0); __m128 cplxValue1, cplxValue2, result; __VOLK_ATTR_ALIGNED(16) float inputFloatBuffer[8]; __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ inputFloatBuffer[0] = (float)(complexVectorPtr[0]); inputFloatBuffer[1] = (float)(complexVectorPtr[1]); inputFloatBuffer[2] = (float)(complexVectorPtr[2]); inputFloatBuffer[3] = (float)(complexVectorPtr[3]); inputFloatBuffer[4] = (float)(complexVectorPtr[4]); inputFloatBuffer[5] = (float)(complexVectorPtr[5]); inputFloatBuffer[6] = (float)(complexVectorPtr[6]); inputFloatBuffer[7] = (float)(complexVectorPtr[7]); cplxValue1 = _mm_load_ps(&inputFloatBuffer[0]); cplxValue2 = _mm_load_ps(&inputFloatBuffer[4]); complexVectorPtr += 8; cplxValue1 = _mm_mul_ps(cplxValue1, invScalar); cplxValue2 = _mm_mul_ps(cplxValue2, invScalar); cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); // Square root the values result = _mm_mul_ps(result, vScalar); // Scale the results _mm_store_ps(outputFloatBuffer, result); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[0]); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[1]); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[2]); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[3]); } number = quarterPoints * 4; magnitudeVectorPtr = &magnitudeVector[number]; complexVectorPtr = (const int16_t*)&complexVector[number]; for(; number < num_points; number++){ const float val1Real = (float)(*complexVectorPtr++) / 32768.0; const float val1Imag = (float)(*complexVectorPtr++) / 32768.0; const float val1Result = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)) * 32768.0; *magnitudeVectorPtr++ = (int16_t)(val1Result); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_16ic_magnitude_16i_a_sse(int16_t* magnitudeVector, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const int16_t* complexVectorPtr = (const int16_t*)complexVector; int16_t* magnitudeVectorPtr = magnitudeVector; __m128 vScalar = _mm_set_ps1(32768.0); __m128 invScalar = _mm_set_ps1(1.0/32768.0); __m128 cplxValue1, cplxValue2, iValue, qValue, result; __VOLK_ATTR_ALIGNED(16) float inputFloatBuffer[4]; __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ inputFloatBuffer[0] = (float)(complexVectorPtr[0]); inputFloatBuffer[1] = (float)(complexVectorPtr[1]); inputFloatBuffer[2] = (float)(complexVectorPtr[2]); inputFloatBuffer[3] = (float)(complexVectorPtr[3]); cplxValue1 = _mm_load_ps(inputFloatBuffer); complexVectorPtr += 4; inputFloatBuffer[0] = (float)(complexVectorPtr[0]); inputFloatBuffer[1] = (float)(complexVectorPtr[1]); inputFloatBuffer[2] = (float)(complexVectorPtr[2]); inputFloatBuffer[3] = (float)(complexVectorPtr[3]); cplxValue2 = _mm_load_ps(inputFloatBuffer); complexVectorPtr += 4; cplxValue1 = _mm_mul_ps(cplxValue1, invScalar); cplxValue2 = _mm_mul_ps(cplxValue2, invScalar); // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); iValue = _mm_mul_ps(iValue, iValue); // Square the I values qValue = _mm_mul_ps(qValue, qValue); // Square the Q Values result = _mm_add_ps(iValue, qValue); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); // Square root the values result = _mm_mul_ps(result, vScalar); // Scale the results _mm_store_ps(outputFloatBuffer, result); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[0]); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[1]); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[2]); *magnitudeVectorPtr++ = (int16_t)(outputFloatBuffer[3]); } number = quarterPoints * 4; magnitudeVectorPtr = &magnitudeVector[number]; complexVectorPtr = (const int16_t*)&complexVector[number]; for(; number < num_points; number++){ const float val1Real = (float)(*complexVectorPtr++) / 32768.0; const float val1Imag = (float)(*complexVectorPtr++) / 32768.0; const float val1Result = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)) * 32768.0; *magnitudeVectorPtr++ = (int16_t)(val1Result); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_16ic_magnitude_16i_generic(int16_t* magnitudeVector, const lv_16sc_t* complexVector, unsigned int num_points){ const int16_t* complexVectorPtr = (const int16_t*)complexVector; int16_t* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; const float scalar = 32768.0; for(number = 0; number < num_points; number++){ float real = ((float)(*complexVectorPtr++)) / scalar; float imag = ((float)(*complexVectorPtr++)) / scalar; *magnitudeVectorPtr++ = (int16_t)(sqrtf((real*real) + (imag*imag)) * scalar); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC_DISABLED /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ extern void volk_16ic_magnitude_16i_a_orc_impl(int16_t* magnitudeVector, const lv_16sc_t* complexVector, float scalar, unsigned int num_points); static inline void volk_16ic_magnitude_16i_u_orc(int16_t* magnitudeVector, const lv_16sc_t* complexVector, unsigned int num_points){ volk_16ic_magnitude_16i_a_orc_impl(magnitudeVector, complexVector, 32768.0, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_16ic_magnitude_16i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32fc_x2_rotator_32fc.h0000664000175000017500000003642112233506724024670 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32fc_rotator_32fc_a_H #define INCLUDED_volk_32fc_s32fc_rotator_32fc_a_H #include #include #include #define ROTATOR_RELOAD 512 #ifdef LV_HAVE_GENERIC /*! \brief rotate input vector at fixed rate per sample from initial phase offset \param outVector The vector where the results will be stored \param inVector Vector to be rotated \param phase_inc rotational velocity \param phase initial phase offset \param num_points The number of values in inVector to be rotated and stored into cVector */ static inline void volk_32fc_s32fc_x2_rotator_32fc_generic(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, lv_32fc_t* phase, unsigned int num_points){ unsigned int i = 0; int j = 0; for(i = 0; i < (unsigned int)(num_points/ROTATOR_RELOAD); ++i) { for(j = 0; j < ROTATOR_RELOAD; ++j) { *outVector++ = *inVector++ * (*phase); (*phase) *= phase_inc; } (*phase) /= abs((*phase)); } for(i = 0; i < num_points%ROTATOR_RELOAD; ++i) { *outVector++ = *inVector++ * (*phase); (*phase) *= phase_inc; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_SSE4_1 #include static inline void volk_32fc_s32fc_x2_rotator_32fc_a_sse4_1(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, lv_32fc_t* phase, unsigned int num_points){ lv_32fc_t* cPtr = outVector; const lv_32fc_t* aPtr = inVector; lv_32fc_t incr = 1; lv_32fc_t phase_Ptr[2] = {(*phase), (*phase)}; unsigned int i, j = 0; for(i = 0; i < 2; ++i) { phase_Ptr[i] *= incr; incr *= (phase_inc); } /*printf("%f, %f\n", lv_creal(phase_Ptr[0]), lv_cimag(phase_Ptr[0])); printf("%f, %f\n", lv_creal(phase_Ptr[1]), lv_cimag(phase_Ptr[1])); printf("%f, %f\n", lv_creal(phase_Ptr[2]), lv_cimag(phase_Ptr[2])); printf("%f, %f\n", lv_creal(phase_Ptr[3]), lv_cimag(phase_Ptr[3])); printf("incr: %f, %f\n", lv_creal(incr), lv_cimag(incr));*/ __m128 aVal, phase_Val, inc_Val, yl, yh, tmp1, tmp2, z, ylp, yhp, tmp1p, tmp2p; phase_Val = _mm_loadu_ps((float*)phase_Ptr); inc_Val = _mm_set_ps(lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr)); const unsigned int halfPoints = num_points / 2; for(i = 0; i < (unsigned int)(halfPoints/ROTATOR_RELOAD); i++) { for(j = 0; j < ROTATOR_RELOAD; ++j) { aVal = _mm_load_ps((float*)aPtr); yl = _mm_moveldup_ps(phase_Val); yh = _mm_movehdup_ps(phase_Val); ylp = _mm_moveldup_ps(inc_Val); yhp = _mm_movehdup_ps(inc_Val); tmp1 = _mm_mul_ps(aVal, yl); tmp1p = _mm_mul_ps(phase_Val, ylp); aVal = _mm_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm_mul_ps(aVal, yh); tmp2p = _mm_mul_ps(phase_Val, yhp); z = _mm_addsub_ps(tmp1, tmp2); phase_Val = _mm_addsub_ps(tmp1p, tmp2p); _mm_store_ps((float*)cPtr, z); aPtr += 2; cPtr += 2; } tmp1 = _mm_mul_ps(phase_Val, phase_Val); tmp2 = _mm_hadd_ps(tmp1, tmp1); tmp1 = _mm_shuffle_ps(tmp2, tmp2, 0xD8); phase_Val = _mm_div_ps(phase_Val, tmp1); } for(i = 0; i < halfPoints%ROTATOR_RELOAD; ++i) { aVal = _mm_load_ps((float*)aPtr); yl = _mm_moveldup_ps(phase_Val); yh = _mm_movehdup_ps(phase_Val); ylp = _mm_moveldup_ps(inc_Val); yhp = _mm_movehdup_ps(inc_Val); tmp1 = _mm_mul_ps(aVal, yl); tmp1p = _mm_mul_ps(phase_Val, ylp); aVal = _mm_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm_mul_ps(aVal, yh); tmp2p = _mm_mul_ps(phase_Val, yhp); z = _mm_addsub_ps(tmp1, tmp2); phase_Val = _mm_addsub_ps(tmp1p, tmp2p); _mm_store_ps((float*)cPtr, z); aPtr += 2; cPtr += 2; } _mm_storeu_ps((float*)phase_Ptr, phase_Val); for(i = 0; i < num_points%2; ++i) { *cPtr++ = *aPtr++ * phase_Ptr[0]; phase_Ptr[0] *= (phase_inc); } (*phase) = phase_Ptr[0]; } /*! \brief rotate input vector at fixed rate per sample from initial phase offset \param outVector The vector where the results will be stored \param inVector Vector to be rotated \param phase_inc rotational velocity \param phase initial phase offset \param num_points The number of values in inVector to be rotated and stored into cVector */ static inline void volk_32fc_s32fc_x2_rotator_32fc_u_sse4_1(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, lv_32fc_t* phase, unsigned int num_points){ lv_32fc_t* cPtr = outVector; const lv_32fc_t* aPtr = inVector; lv_32fc_t incr = 1; lv_32fc_t phase_Ptr[2] = {(*phase), (*phase)}; unsigned int i, j = 0; for(i = 0; i < 2; ++i) { phase_Ptr[i] *= incr; incr *= (phase_inc); } /*printf("%f, %f\n", lv_creal(phase_Ptr[0]), lv_cimag(phase_Ptr[0])); printf("%f, %f\n", lv_creal(phase_Ptr[1]), lv_cimag(phase_Ptr[1])); printf("%f, %f\n", lv_creal(phase_Ptr[2]), lv_cimag(phase_Ptr[2])); printf("%f, %f\n", lv_creal(phase_Ptr[3]), lv_cimag(phase_Ptr[3])); printf("incr: %f, %f\n", lv_creal(incr), lv_cimag(incr));*/ __m128 aVal, phase_Val, inc_Val, yl, yh, tmp1, tmp2, z, ylp, yhp, tmp1p, tmp2p; phase_Val = _mm_loadu_ps((float*)phase_Ptr); inc_Val = _mm_set_ps(lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr)); const unsigned int halfPoints = num_points / 2; for(i = 0; i < (unsigned int)(halfPoints/ROTATOR_RELOAD); i++) { for(j = 0; j < ROTATOR_RELOAD; ++j) { aVal = _mm_loadu_ps((float*)aPtr); yl = _mm_moveldup_ps(phase_Val); yh = _mm_movehdup_ps(phase_Val); ylp = _mm_moveldup_ps(inc_Val); yhp = _mm_movehdup_ps(inc_Val); tmp1 = _mm_mul_ps(aVal, yl); tmp1p = _mm_mul_ps(phase_Val, ylp); aVal = _mm_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm_mul_ps(aVal, yh); tmp2p = _mm_mul_ps(phase_Val, yhp); z = _mm_addsub_ps(tmp1, tmp2); phase_Val = _mm_addsub_ps(tmp1p, tmp2p); _mm_storeu_ps((float*)cPtr, z); aPtr += 2; cPtr += 2; } tmp1 = _mm_mul_ps(phase_Val, phase_Val); tmp2 = _mm_hadd_ps(tmp1, tmp1); tmp1 = _mm_shuffle_ps(tmp2, tmp2, 0xD8); phase_Val = _mm_div_ps(phase_Val, tmp1); } for(i = 0; i < halfPoints%ROTATOR_RELOAD; ++i) { aVal = _mm_loadu_ps((float*)aPtr); yl = _mm_moveldup_ps(phase_Val); yh = _mm_movehdup_ps(phase_Val); ylp = _mm_moveldup_ps(inc_Val); yhp = _mm_movehdup_ps(inc_Val); tmp1 = _mm_mul_ps(aVal, yl); tmp1p = _mm_mul_ps(phase_Val, ylp); aVal = _mm_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm_mul_ps(aVal, yh); tmp2p = _mm_mul_ps(phase_Val, yhp); z = _mm_addsub_ps(tmp1, tmp2); phase_Val = _mm_addsub_ps(tmp1p, tmp2p); _mm_storeu_ps((float*)cPtr, z); aPtr += 2; cPtr += 2; } _mm_storeu_ps((float*)phase_Ptr, phase_Val); for(i = 0; i < num_points%2; ++i) { *cPtr++ = *aPtr++ * phase_Ptr[0]; phase_Ptr[0] *= (phase_inc); } (*phase) = phase_Ptr[0]; } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_AVX #include /*! \brief rotate input vector at fixed rate per sample from initial phase offset \param outVector The vector where the results will be stored \param inVector Vector to be rotated \param phase_inc rotational velocity \param phase initial phase offset \param num_points The number of values in inVector to be rotated and stored into cVector */ static inline void volk_32fc_s32fc_x2_rotator_32fc_a_avx(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, lv_32fc_t* phase, unsigned int num_points){ lv_32fc_t* cPtr = outVector; const lv_32fc_t* aPtr = inVector; lv_32fc_t incr = 1; lv_32fc_t phase_Ptr[4] = {(*phase), (*phase), (*phase), (*phase)}; unsigned int i, j = 0; for(i = 0; i < 4; ++i) { phase_Ptr[i] *= incr; incr *= (phase_inc); } /*printf("%f, %f\n", lv_creal(phase_Ptr[0]), lv_cimag(phase_Ptr[0])); printf("%f, %f\n", lv_creal(phase_Ptr[1]), lv_cimag(phase_Ptr[1])); printf("%f, %f\n", lv_creal(phase_Ptr[2]), lv_cimag(phase_Ptr[2])); printf("%f, %f\n", lv_creal(phase_Ptr[3]), lv_cimag(phase_Ptr[3])); printf("incr: %f, %f\n", lv_creal(incr), lv_cimag(incr));*/ __m256 aVal, phase_Val, inc_Val, yl, yh, tmp1, tmp2, z, ylp, yhp, tmp1p, tmp2p; phase_Val = _mm256_loadu_ps((float*)phase_Ptr); inc_Val = _mm256_set_ps(lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr)); const unsigned int fourthPoints = num_points / 4; for(i = 0; i < (unsigned int)(fourthPoints/ROTATOR_RELOAD); i++) { for(j = 0; j < ROTATOR_RELOAD; ++j) { aVal = _mm256_load_ps((float*)aPtr); yl = _mm256_moveldup_ps(phase_Val); yh = _mm256_movehdup_ps(phase_Val); ylp = _mm256_moveldup_ps(inc_Val); yhp = _mm256_movehdup_ps(inc_Val); tmp1 = _mm256_mul_ps(aVal, yl); tmp1p = _mm256_mul_ps(phase_Val, ylp); aVal = _mm256_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm256_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm256_mul_ps(aVal, yh); tmp2p = _mm256_mul_ps(phase_Val, yhp); z = _mm256_addsub_ps(tmp1, tmp2); phase_Val = _mm256_addsub_ps(tmp1p, tmp2p); _mm256_store_ps((float*)cPtr, z); aPtr += 4; cPtr += 4; } tmp1 = _mm256_mul_ps(phase_Val, phase_Val); tmp2 = _mm256_hadd_ps(tmp1, tmp1); tmp1 = _mm256_shuffle_ps(tmp2, tmp2, 0xD8); phase_Val = _mm256_div_ps(phase_Val, tmp1); } for(i = 0; i < fourthPoints%ROTATOR_RELOAD; ++i) { aVal = _mm256_load_ps((float*)aPtr); yl = _mm256_moveldup_ps(phase_Val); yh = _mm256_movehdup_ps(phase_Val); ylp = _mm256_moveldup_ps(inc_Val); yhp = _mm256_movehdup_ps(inc_Val); tmp1 = _mm256_mul_ps(aVal, yl); tmp1p = _mm256_mul_ps(phase_Val, ylp); aVal = _mm256_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm256_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm256_mul_ps(aVal, yh); tmp2p = _mm256_mul_ps(phase_Val, yhp); z = _mm256_addsub_ps(tmp1, tmp2); phase_Val = _mm256_addsub_ps(tmp1p, tmp2p); _mm256_store_ps((float*)cPtr, z); aPtr += 4; cPtr += 4; } _mm256_storeu_ps((float*)phase_Ptr, phase_Val); for(i = 0; i < num_points%4; ++i) { *cPtr++ = *aPtr++ * phase_Ptr[0]; phase_Ptr[0] *= (phase_inc); } (*phase) = phase_Ptr[0]; } /*! \brief rotate input vector at fixed rate per sample from initial phase offset \param outVector The vector where the results will be stored \param inVector Vector to be rotated \param phase_inc rotational velocity \param phase initial phase offset \param num_points The number of values in inVector to be rotated and stored into cVector */ static inline void volk_32fc_s32fc_x2_rotator_32fc_u_avx(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, lv_32fc_t* phase, unsigned int num_points){ lv_32fc_t* cPtr = outVector; const lv_32fc_t* aPtr = inVector; lv_32fc_t incr = 1; lv_32fc_t phase_Ptr[4] = {(*phase), (*phase), (*phase), (*phase)}; unsigned int i, j = 0; for(i = 0; i < 4; ++i) { phase_Ptr[i] *= incr; incr *= (phase_inc); } /*printf("%f, %f\n", lv_creal(phase_Ptr[0]), lv_cimag(phase_Ptr[0])); printf("%f, %f\n", lv_creal(phase_Ptr[1]), lv_cimag(phase_Ptr[1])); printf("%f, %f\n", lv_creal(phase_Ptr[2]), lv_cimag(phase_Ptr[2])); printf("%f, %f\n", lv_creal(phase_Ptr[3]), lv_cimag(phase_Ptr[3])); printf("incr: %f, %f\n", lv_creal(incr), lv_cimag(incr));*/ __m256 aVal, phase_Val, inc_Val, yl, yh, tmp1, tmp2, z, ylp, yhp, tmp1p, tmp2p; phase_Val = _mm256_loadu_ps((float*)phase_Ptr); inc_Val = _mm256_set_ps(lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr),lv_cimag(incr), lv_creal(incr)); const unsigned int fourthPoints = num_points / 4; for(i = 0; i < (unsigned int)(fourthPoints/ROTATOR_RELOAD); i++) { for(j = 0; j < ROTATOR_RELOAD; ++j) { aVal = _mm256_loadu_ps((float*)aPtr); yl = _mm256_moveldup_ps(phase_Val); yh = _mm256_movehdup_ps(phase_Val); ylp = _mm256_moveldup_ps(inc_Val); yhp = _mm256_movehdup_ps(inc_Val); tmp1 = _mm256_mul_ps(aVal, yl); tmp1p = _mm256_mul_ps(phase_Val, ylp); aVal = _mm256_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm256_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm256_mul_ps(aVal, yh); tmp2p = _mm256_mul_ps(phase_Val, yhp); z = _mm256_addsub_ps(tmp1, tmp2); phase_Val = _mm256_addsub_ps(tmp1p, tmp2p); _mm256_storeu_ps((float*)cPtr, z); aPtr += 4; cPtr += 4; } tmp1 = _mm256_mul_ps(phase_Val, phase_Val); tmp2 = _mm256_hadd_ps(tmp1, tmp1); tmp1 = _mm256_shuffle_ps(tmp2, tmp2, 0xD8); phase_Val = _mm256_div_ps(phase_Val, tmp1); } for(i = 0; i < fourthPoints%ROTATOR_RELOAD; ++i) { aVal = _mm256_loadu_ps((float*)aPtr); yl = _mm256_moveldup_ps(phase_Val); yh = _mm256_movehdup_ps(phase_Val); ylp = _mm256_moveldup_ps(inc_Val); yhp = _mm256_movehdup_ps(inc_Val); tmp1 = _mm256_mul_ps(aVal, yl); tmp1p = _mm256_mul_ps(phase_Val, ylp); aVal = _mm256_shuffle_ps(aVal, aVal, 0xB1); phase_Val = _mm256_shuffle_ps(phase_Val, phase_Val, 0xB1); tmp2 = _mm256_mul_ps(aVal, yh); tmp2p = _mm256_mul_ps(phase_Val, yhp); z = _mm256_addsub_ps(tmp1, tmp2); phase_Val = _mm256_addsub_ps(tmp1p, tmp2p); _mm256_storeu_ps((float*)cPtr, z); aPtr += 4; cPtr += 4; } _mm256_storeu_ps((float*)phase_Ptr, phase_Val); for(i = 0; i < num_points%4; ++i) { *cPtr++ = *aPtr++ * phase_Ptr[0]; phase_Ptr[0] *= (phase_inc); } (*phase) = phase_Ptr[0]; } #endif /* LV_HAVE_AVX */ #endif /* INCLUDED_volk_32fc_s32fc_rotator_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_x5_add_quad_16i_x4.h0000664000175000017500000000716412207440367024065 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_x5_add_quad_16i_x4_a_H #define INCLUDED_volk_16i_x5_add_quad_16i_x4_a_H #include #include #ifdef LV_HAVE_SSE2 #include #include static inline void volk_16i_x5_add_quad_16i_x4_a_sse2(short* target0, short* target1, short* target2, short* target3, short* src0, short* src1, short* src2, short* src3, short* src4, unsigned int num_points) { const unsigned int num_bytes = num_points*2; __m128i xmm0, xmm1, xmm2, xmm3, xmm4; __m128i *p_target0, *p_target1, *p_target2, *p_target3, *p_src0, *p_src1, *p_src2, *p_src3, *p_src4; p_target0 = (__m128i*)target0; p_target1 = (__m128i*)target1; p_target2 = (__m128i*)target2; p_target3 = (__m128i*)target3; p_src0 = (__m128i*)src0; p_src1 = (__m128i*)src1; p_src2 = (__m128i*)src2; p_src3 = (__m128i*)src3; p_src4 = (__m128i*)src4; int i = 0; int bound = (num_bytes >> 4); int leftovers = (num_bytes >> 1) & 7; for(; i < bound; ++i) { xmm0 = _mm_load_si128(p_src0); xmm1 = _mm_load_si128(p_src1); xmm2 = _mm_load_si128(p_src2); xmm3 = _mm_load_si128(p_src3); xmm4 = _mm_load_si128(p_src4); p_src0 += 1; p_src1 += 1; xmm1 = _mm_add_epi16(xmm0, xmm1); xmm2 = _mm_add_epi16(xmm0, xmm2); xmm3 = _mm_add_epi16(xmm0, xmm3); xmm4 = _mm_add_epi16(xmm0, xmm4); p_src2 += 1; p_src3 += 1; p_src4 += 1; _mm_store_si128(p_target0, xmm1); _mm_store_si128(p_target1, xmm2); _mm_store_si128(p_target2, xmm3); _mm_store_si128(p_target3, xmm4); p_target0 += 1; p_target1 += 1; p_target2 += 1; p_target3 += 1; } /*asm volatile ( ".%=volk_16i_x5_add_quad_16i_x4_a_sse2_L1:\n\t" "cmp $0, %[bound]\n\t" "je .%=volk_16i_x5_add_quad_16i_x4_a_sse2_END\n\t" "movaps (%[src0]), %%xmm1\n\t" "movaps (%[src1]), %%xmm2\n\t" "movaps (%[src2]), %%xmm3\n\t" "movaps (%[src3]), %%xmm4\n\t" "movaps (%[src4]), %%xmm5\n\t" "add $16, %[src0]\n\t" "add $16, %[src1]\n\t" "add $16, %[src2]\n\t" "add $16, %[src3]\n\t" "add $16, %[src4]\n\t" "paddw %%xmm1, %%xmm2\n\t" "paddw %%xmm1, %%xmm3\n\t" "paddw %%xmm1, %%xmm4\n\t" "paddw %%xmm1, %%xmm5\n\t" "add $-1, %[bound]\n\t" "movaps %%xmm2, (%[target0])\n\t" "movaps %%xmm3, (%[target1])\n\t" "movaps %%xmm4, (%[target2])\n\t" "movaps %%xmm5, (%[target3])\n\t" "add $16, %[target0]\n\t" "add $16, %[target1]\n\t" "add $16, %[target2]\n\t" "add $16, %[target3]\n\t" "jmp .%=volk_16i_x5_add_quad_16i_x4_a_sse2_L1\n\t" ".%=volk_16i_x5_add_quad_16i_x4_a_sse2_END:\n\t" : :[bound]"r"(bound), [src0]"r"(src0), [src1]"r"(src1), [src2]"r"(src2), [src3]"r"(src3), [src4]"r"(src4), [target0]"r"(target0), [target1]"r"(target1), [target2]"r"(target2), [target3]"r"(target3) :"xmm1", "xmm2", "xmm3", "xmm4", "xmm5" ); */ for(i = bound * 8; i < (bound * 8) + leftovers; ++i) { target0[i] = src0[i] + src1[i]; target1[i] = src0[i] + src2[i]; target2[i] = src0[i] + src3[i]; target3[i] = src0[i] + src4[i]; } } #endif /*LV_HAVE_SSE2*/ #ifdef LV_HAVE_GENERIC static inline void volk_16i_x5_add_quad_16i_x4_generic(short* target0, short* target1, short* target2, short* target3, short* src0, short* src1, short* src2, short* src3, short* src4, unsigned int num_points) { const unsigned int num_bytes = num_points*2; int i = 0; int bound = num_bytes >> 1; for(i = 0; i < bound; ++i) { target0[i] = src0[i] + src1[i]; target1[i] = src0[i] + src2[i]; target2[i] = src0[i] + src3[i]; target3[i] = src0[i] + src4[i]; } } #endif /* LV_HAVE_GENERIC */ #endif /*INCLUDED_volk_16i_x5_add_quad_16i_x4_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_x4_quad_max_star_16i.h0000664000175000017500000000777612207440367024550 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_x4_quad_max_star_16i_a_H #define INCLUDED_volk_16i_x4_quad_max_star_16i_a_H #include #include #ifdef LV_HAVE_SSE2 #include static inline void volk_16i_x4_quad_max_star_16i_a_sse2(short* target, short* src0, short* src1, short* src2, short* src3, unsigned int num_points) { const unsigned int num_bytes = num_points*2; int i = 0; int bound = (num_bytes >> 4); int bound_copy = bound; int leftovers = (num_bytes >> 1) & 7; __m128i *p_target, *p_src0, *p_src1, *p_src2, *p_src3; p_target = (__m128i*) target; p_src0 = (__m128i*)src0; p_src1 = (__m128i*)src1; p_src2 = (__m128i*)src2; p_src3 = (__m128i*)src3; __m128i xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8; while(bound_copy > 0) { xmm1 = _mm_load_si128(p_src0); xmm2 = _mm_load_si128(p_src1); xmm3 = _mm_load_si128(p_src2); xmm4 = _mm_load_si128(p_src3); xmm5 = _mm_setzero_si128(); xmm6 = _mm_setzero_si128(); xmm7 = xmm1; xmm8 = xmm3; xmm1 = _mm_sub_epi16(xmm2, xmm1); xmm3 = _mm_sub_epi16(xmm4, xmm3); xmm5 = _mm_cmpgt_epi16(xmm1, xmm5); xmm6 = _mm_cmpgt_epi16(xmm3, xmm6); xmm2 = _mm_and_si128(xmm5, xmm2); xmm4 = _mm_and_si128(xmm6, xmm4); xmm5 = _mm_andnot_si128(xmm5, xmm7); xmm6 = _mm_andnot_si128(xmm6, xmm8); xmm5 = _mm_add_epi16(xmm2, xmm5); xmm6 = _mm_add_epi16(xmm4, xmm6); xmm1 = _mm_xor_si128(xmm1, xmm1); xmm2 = xmm5; xmm5 = _mm_sub_epi16(xmm6, xmm5); p_src0 += 1; bound_copy -= 1; xmm1 = _mm_cmpgt_epi16(xmm5, xmm1); p_src1 += 1; xmm6 = _mm_and_si128(xmm1, xmm6); xmm1 = _mm_andnot_si128(xmm1, xmm2); p_src2 += 1; xmm1 = _mm_add_epi16(xmm6, xmm1); p_src3 += 1; _mm_store_si128(p_target, xmm1); p_target += 1; } /*asm volatile ( "volk_16i_x4_quad_max_star_16i_a_sse2_L1:\n\t" "cmp $0, %[bound]\n\t" "je volk_16i_x4_quad_max_star_16i_a_sse2_END\n\t" "movaps (%[src0]), %%xmm1\n\t" "movaps (%[src1]), %%xmm2\n\t" "movaps (%[src2]), %%xmm3\n\t" "movaps (%[src3]), %%xmm4\n\t" "pxor %%xmm5, %%xmm5\n\t" "pxor %%xmm6, %%xmm6\n\t" "movaps %%xmm1, %%xmm7\n\t" "movaps %%xmm3, %%xmm8\n\t" "psubw %%xmm2, %%xmm1\n\t" "psubw %%xmm4, %%xmm3\n\t" "pcmpgtw %%xmm1, %%xmm5\n\t" "pcmpgtw %%xmm3, %%xmm6\n\t" "pand %%xmm5, %%xmm2\n\t" "pand %%xmm6, %%xmm4\n\t" "pandn %%xmm7, %%xmm5\n\t" "pandn %%xmm8, %%xmm6\n\t" "paddw %%xmm2, %%xmm5\n\t" "paddw %%xmm4, %%xmm6\n\t" "pxor %%xmm1, %%xmm1\n\t" "movaps %%xmm5, %%xmm2\n\t" "psubw %%xmm6, %%xmm5\n\t" "add $16, %[src0]\n\t" "add $-1, %[bound]\n\t" "pcmpgtw %%xmm5, %%xmm1\n\t" "add $16, %[src1]\n\t" "pand %%xmm1, %%xmm6\n\t" "pandn %%xmm2, %%xmm1\n\t" "add $16, %[src2]\n\t" "paddw %%xmm6, %%xmm1\n\t" "add $16, %[src3]\n\t" "movaps %%xmm1, (%[target])\n\t" "addw $16, %[target]\n\t" "jmp volk_16i_x4_quad_max_star_16i_a_sse2_L1\n\t" "volk_16i_x4_quad_max_star_16i_a_sse2_END:\n\t" : :[bound]"r"(bound), [src0]"r"(src0), [src1]"r"(src1), [src2]"r"(src2), [src3]"r"(src3), [target]"r"(target) : ); */ short temp0 = 0; short temp1 = 0; for(i = bound * 8; i < (bound * 8) + leftovers; ++i) { temp0 = ((short)(src0[i] - src1[i]) > 0) ? src0[i] : src1[i]; temp1 = ((short)(src2[i] - src3[i])>0) ? src2[i] : src3[i]; target[i] = ((short)(temp0 - temp1)>0) ? temp0 : temp1; } return; } #endif /*LV_HAVE_SSE2*/ #ifdef LV_HAVE_GENERIC static inline void volk_16i_x4_quad_max_star_16i_generic(short* target, short* src0, short* src1, short* src2, short* src3, unsigned int num_points) { const unsigned int num_bytes = num_points*2; int i = 0; int bound = num_bytes >> 1; short temp0 = 0; short temp1 = 0; for(i = 0; i < bound; ++i) { temp0 = ((short)(src0[i] - src1[i]) > 0) ? src0[i] : src1[i]; temp1 = ((short)(src2[i] - src3[i])>0) ? src2[i] : src3[i]; target[i] = ((short)(temp0 - temp1)>0) ? temp0 : temp1; } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_16i_x4_quad_max_star_16i_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_64f_convert_32f.h0000664000175000017500000000764312207440367022751 0ustar jcorganjcorgan#ifndef INCLUDED_volk_64f_convert_32f_u_H #define INCLUDED_volk_64f_convert_32f_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the double values into float values \param dVector The converted float vector values \param fVector The double vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_64f_convert_32f_u_sse2(float* outputVector, const double* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const double* inputVectorPtr = (const double*)inputVector; float* outputVectorPtr = outputVector; __m128 ret, ret2; __m128d inputVal1, inputVal2; for(;number < quarterPoints; number++){ inputVal1 = _mm_loadu_pd(inputVectorPtr); inputVectorPtr += 2; inputVal2 = _mm_loadu_pd(inputVectorPtr); inputVectorPtr += 2; ret = _mm_cvtpd_ps(inputVal1); ret2 = _mm_cvtpd_ps(inputVal2); ret = _mm_movelh_ps(ret, ret2); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] = (float)(inputVector[number]); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the double values into float values \param dVector The converted float vector values \param fVector The double vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_64f_convert_32f_generic(float* outputVector, const double* inputVector, unsigned int num_points){ float* outputVectorPtr = outputVector; const double* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64f_convert_32f_u_H */ #ifndef INCLUDED_volk_64f_convert_32f_a_H #define INCLUDED_volk_64f_convert_32f_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the double values into float values \param dVector The converted float vector values \param fVector The double vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_64f_convert_32f_a_sse2(float* outputVector, const double* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const double* inputVectorPtr = (const double*)inputVector; float* outputVectorPtr = outputVector; __m128 ret, ret2; __m128d inputVal1, inputVal2; for(;number < quarterPoints; number++){ inputVal1 = _mm_load_pd(inputVectorPtr); inputVectorPtr += 2; inputVal2 = _mm_load_pd(inputVectorPtr); inputVectorPtr += 2; ret = _mm_cvtpd_ps(inputVal1); ret2 = _mm_cvtpd_ps(inputVal2); ret = _mm_movelh_ps(ret, ret2); _mm_store_ps(outputVectorPtr, ret); outputVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] = (float)(inputVector[number]); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the double values into float values \param dVector The converted float vector values \param fVector The double vector values to be converted \param num_points The number of points in the two vectors to be converted */ static inline void volk_64f_convert_32f_a_generic(float* outputVector, const double* inputVector, unsigned int num_points){ float* outputVectorPtr = outputVector; const double* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64f_convert_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32f_atan2_32f.h0000664000175000017500000001331612207440367023263 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32f_atan2_32f_a_H #define INCLUDED_volk_32fc_s32f_atan2_32f_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief performs the atan2 on the input vector and stores the results in the output vector. \param outputVector The byte-aligned vector where the results will be stored. \param inputVector The byte-aligned input vector containing interleaved IQ data (I = cos, Q = sin). \param normalizeFactor The atan2 results will be divided by this normalization factor. \param num_points The number of complex values in the input vector. */ static inline void volk_32fc_s32f_atan2_32f_a_sse4_1(float* outputVector, const lv_32fc_t* complexVector, const float normalizeFactor, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* outPtr = outputVector; unsigned int number = 0; const float invNormalizeFactor = 1.0 / normalizeFactor; #ifdef LV_HAVE_LIB_SIMDMATH const unsigned int quarterPoints = num_points / 4; __m128 testVector = _mm_set_ps1(2*M_PI); __m128 correctVector = _mm_set_ps1(M_PI); __m128 vNormalizeFactor = _mm_set_ps1(invNormalizeFactor); __m128 phase; __m128 complex1, complex2, iValue, qValue; __m128 keepMask; for (; number < quarterPoints; number++) { // Load IQ data: complex1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; complex2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Deinterleave IQ data: iValue = _mm_shuffle_ps(complex1, complex2, _MM_SHUFFLE(2,0,2,0)); qValue = _mm_shuffle_ps(complex1, complex2, _MM_SHUFFLE(3,1,3,1)); // Arctan to get phase: phase = atan2f4(qValue, iValue); // When Q = 0 and I < 0, atan2f4 sucks and returns 2pi vice pi. // Compare to 2pi: keepMask = _mm_cmpneq_ps(phase,testVector); phase = _mm_blendv_ps(correctVector, phase, keepMask); // done with above correction. phase = _mm_mul_ps(phase, vNormalizeFactor); _mm_store_ps((float*)outPtr, phase); outPtr += 4; } number = quarterPoints * 4; #endif /* LV_HAVE_SIMDMATH_H */ for (; number < num_points; number++) { const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *outPtr++ = atan2f(imag, real) * invNormalizeFactor; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief performs the atan2 on the input vector and stores the results in the output vector. \param outputVector The byte-aligned vector where the results will be stored. \param inputVector The byte-aligned input vector containing interleaved IQ data (I = cos, Q = sin). \param normalizeFactor The atan2 results will be divided by this normalization factor. \param num_points The number of complex values in the input vector. */ static inline void volk_32fc_s32f_atan2_32f_a_sse(float* outputVector, const lv_32fc_t* complexVector, const float normalizeFactor, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* outPtr = outputVector; unsigned int number = 0; const float invNormalizeFactor = 1.0 / normalizeFactor; #ifdef LV_HAVE_LIB_SIMDMATH const unsigned int quarterPoints = num_points / 4; __m128 testVector = _mm_set_ps1(2*M_PI); __m128 correctVector = _mm_set_ps1(M_PI); __m128 vNormalizeFactor = _mm_set_ps1(invNormalizeFactor); __m128 phase; __m128 complex1, complex2, iValue, qValue; __m128 mask; __m128 keepMask; for (; number < quarterPoints; number++) { // Load IQ data: complex1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; complex2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Deinterleave IQ data: iValue = _mm_shuffle_ps(complex1, complex2, _MM_SHUFFLE(2,0,2,0)); qValue = _mm_shuffle_ps(complex1, complex2, _MM_SHUFFLE(3,1,3,1)); // Arctan to get phase: phase = atan2f4(qValue, iValue); // When Q = 0 and I < 0, atan2f4 sucks and returns 2pi vice pi. // Compare to 2pi: keepMask = _mm_cmpneq_ps(phase,testVector); phase = _mm_and_ps(phase, keepMask); mask = _mm_andnot_ps(keepMask, correctVector); phase = _mm_or_ps(phase, mask); // done with above correction. phase = _mm_mul_ps(phase, vNormalizeFactor); _mm_store_ps((float*)outPtr, phase); outPtr += 4; } number = quarterPoints * 4; #endif /* LV_HAVE_SIMDMATH_H */ for (; number < num_points; number++) { const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *outPtr++ = atan2f(imag, real) * invNormalizeFactor; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief performs the atan2 on the input vector and stores the results in the output vector. \param outputVector The vector where the results will be stored. \param inputVector Input vector containing interleaved IQ data (I = cos, Q = sin). \param normalizeFactor The atan2 results will be divided by this normalization factor. \param num_points The number of complex values in the input vector. */ static inline void volk_32fc_s32f_atan2_32f_generic(float* outputVector, const lv_32fc_t* inputVector, const float normalizeFactor, unsigned int num_points){ float* outPtr = outputVector; const float* inPtr = (float*)inputVector; const float invNormalizeFactor = 1.0 / normalizeFactor; unsigned int number; for ( number = 0; number < num_points; number++) { const float real = *inPtr++; const float imag = *inPtr++; *outPtr++ = atan2f(imag, real) * invNormalizeFactor; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_s32f_atan2_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32fc_multiply_32fc.h0000664000175000017500000001331412207440367024441 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32fc_multiply_32fc_u_H #define INCLUDED_volk_32fc_s32fc_multiply_32fc_u_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Multiplies the input vector by a scalar and stores the results in the third vector \param cVector The vector where the results will be stored \param aVector The vector to be multiplied \param scalar The complex scalar to multiply aVector \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_s32fc_multiply_32fc_u_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x, yl, yh, z, tmp1, tmp2; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; // Set up constant scalar vector yl = _mm_set_ps1(lv_creal(scalar)); yh = _mm_set_ps1(lv_cimag(scalar)); for(;number < halfPoints; number++){ x = _mm_loadu_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di _mm_storeu_ps((float*)c,z); // Store the results back into the C container a += 2; c += 2; } if((num_points % 2) != 0) { *c = (*a) * scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies the input vector by a scalar and stores the results in the third vector \param cVector The vector where the results will be stored \param aVector The vector to be multiplied \param scalar The complex scalar to multiply aVector \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_s32fc_multiply_32fc_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t scalar, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; unsigned int number = num_points; // unwrap loop while (number >= 8){ *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; number -= 8; } // clean up any remaining while (number-- > 0) *cPtr++ = *aPtr++ * scalar; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_x2_multiply_32fc_u_H */ #ifndef INCLUDED_volk_32fc_s32fc_multiply_32fc_a_H #define INCLUDED_volk_32fc_s32fc_multiply_32fc_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_s32fc_multiply_32fc_a_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x, yl, yh, z, tmp1, tmp2; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; // Set up constant scalar vector yl = _mm_set_ps1(lv_creal(scalar)); yh = _mm_set_ps1(lv_cimag(scalar)); for(;number < halfPoints; number++){ x = _mm_load_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di _mm_store_ps((float*)c,z); // Store the results back into the C container a += 2; c += 2; } if((num_points % 2) != 0) { *c = (*a) * scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_s32fc_multiply_32fc_a_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t scalar, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; unsigned int number = num_points; // unwrap loop while (number >= 8){ *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; *cPtr++ = (*aPtr++) * scalar; number -= 8; } // clean up any remaining while (number-- > 0) *cPtr++ = *aPtr++ * scalar; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_x2_multiply_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_deinterleave_16i_x2.h0000664000175000017500000001441212207440367024511 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_deinterleave_16i_x2_a_H #define INCLUDED_volk_16ic_deinterleave_16i_x2_a_H #include #include #ifdef LV_HAVE_SSSE3 #include /*! \brief Deinterleaves the complex 16 bit vector into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_16i_x2_a_ssse3(int16_t* iBuffer, int16_t* qBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (int8_t*)complexVector; int16_t* iBufferPtr = iBuffer; int16_t* qBufferPtr = qBuffer; __m128i iMoveMask1 = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 13, 12, 9, 8, 5, 4, 1, 0); __m128i iMoveMask2 = _mm_set_epi8(13, 12, 9, 8, 5, 4, 1, 0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80); __m128i qMoveMask1 = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 15, 14, 11, 10, 7, 6, 3, 2); __m128i qMoveMask2 = _mm_set_epi8(15, 14, 11, 10, 7, 6, 3, 2, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80); __m128i complexVal1, complexVal2, iOutputVal, qOutputVal; unsigned int eighthPoints = num_points / 8; for(number = 0; number < eighthPoints; number++){ complexVal1 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal2 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; iOutputVal = _mm_or_si128( _mm_shuffle_epi8(complexVal1, iMoveMask1) , _mm_shuffle_epi8(complexVal2, iMoveMask2)); qOutputVal = _mm_or_si128( _mm_shuffle_epi8(complexVal1, qMoveMask1) , _mm_shuffle_epi8(complexVal2, qMoveMask2)); _mm_store_si128((__m128i*)iBufferPtr, iOutputVal); _mm_store_si128((__m128i*)qBufferPtr, qOutputVal); iBufferPtr += 8; qBufferPtr += 8; } number = eighthPoints * 8; int16_t* int16ComplexVectorPtr = (int16_t*)complexVectorPtr; for(; number < num_points; number++){ *iBufferPtr++ = *int16ComplexVectorPtr++; *qBufferPtr++ = *int16ComplexVectorPtr++; } } #endif /* LV_HAVE_SSSE3 */ #ifdef LV_HAVE_SSE2 #include /*! \brief Deinterleaves the complex 16 bit vector into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_16i_x2_a_sse2(int16_t* iBuffer, int16_t* qBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int16_t* complexVectorPtr = (int16_t*)complexVector; int16_t* iBufferPtr = iBuffer; int16_t* qBufferPtr = qBuffer; __m128i complexVal1, complexVal2, iComplexVal1, iComplexVal2, qComplexVal1, qComplexVal2, iOutputVal, qOutputVal; __m128i lowMask = _mm_set_epi32(0x0, 0x0, 0xFFFFFFFF, 0xFFFFFFFF); __m128i highMask = _mm_set_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0x0, 0x0); unsigned int eighthPoints = num_points / 8; for(number = 0; number < eighthPoints; number++){ complexVal1 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 8; complexVal2 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 8; iComplexVal1 = _mm_shufflelo_epi16(complexVal1, _MM_SHUFFLE(3,1,2,0)); iComplexVal1 = _mm_shufflehi_epi16(iComplexVal1, _MM_SHUFFLE(3,1,2,0)); iComplexVal1 = _mm_shuffle_epi32(iComplexVal1, _MM_SHUFFLE(3,1,2,0)); iComplexVal2 = _mm_shufflelo_epi16(complexVal2, _MM_SHUFFLE(3,1,2,0)); iComplexVal2 = _mm_shufflehi_epi16(iComplexVal2, _MM_SHUFFLE(3,1,2,0)); iComplexVal2 = _mm_shuffle_epi32(iComplexVal2, _MM_SHUFFLE(2,0,3,1)); iOutputVal = _mm_or_si128(_mm_and_si128(iComplexVal1, lowMask), _mm_and_si128(iComplexVal2, highMask)); _mm_store_si128((__m128i*)iBufferPtr, iOutputVal); qComplexVal1 = _mm_shufflelo_epi16(complexVal1, _MM_SHUFFLE(2,0,3,1)); qComplexVal1 = _mm_shufflehi_epi16(qComplexVal1, _MM_SHUFFLE(2,0,3,1)); qComplexVal1 = _mm_shuffle_epi32(qComplexVal1, _MM_SHUFFLE(3,1,2,0)); qComplexVal2 = _mm_shufflelo_epi16(complexVal2, _MM_SHUFFLE(2,0,3,1)); qComplexVal2 = _mm_shufflehi_epi16(qComplexVal2, _MM_SHUFFLE(2,0,3,1)); qComplexVal2 = _mm_shuffle_epi32(qComplexVal2, _MM_SHUFFLE(2,0,3,1)); qOutputVal = _mm_or_si128(_mm_and_si128(qComplexVal1, lowMask), _mm_and_si128(qComplexVal2, highMask)); _mm_store_si128((__m128i*)qBufferPtr, qOutputVal); iBufferPtr += 8; qBufferPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 16 bit vector into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_16i_x2_generic(int16_t* iBuffer, int16_t* qBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ const int16_t* complexVectorPtr = (const int16_t*)complexVector; int16_t* iBufferPtr = iBuffer; int16_t* qBufferPtr = qBuffer; unsigned int number; for(number = 0; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Deinterleaves the complex 16 bit vector into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ extern void volk_16ic_deinterleave_16i_x2_a_orc_impl(int16_t* iBuffer, int16_t* qBuffer, const lv_16sc_t* complexVector, unsigned int num_points); static inline void volk_16ic_deinterleave_16i_x2_u_orc(int16_t* iBuffer, int16_t* qBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ volk_16ic_deinterleave_16i_x2_a_orc_impl(iBuffer, qBuffer, complexVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_16ic_deinterleave_16i_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_power_32f.h0000664000175000017500000001134112207440367023243 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_power_32f_a_H #define INCLUDED_volk_32f_s32f_power_32f_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief Takes each the input vector value to the specified power and stores the results in the return vector \param cVector The vector where the results will be stored \param aVector The vector of values to be taken to a power \param power The power value to be applied to each data point \param num_points The number of values in aVector to be taken to the specified power level and stored into cVector */ static inline void volk_32f_s32f_power_32f_a_sse4_1(float* cVector, const float* aVector, const float power, unsigned int num_points){ unsigned int number = 0; float* cPtr = cVector; const float* aPtr = aVector; #ifdef LV_HAVE_LIB_SIMDMATH const unsigned int quarterPoints = num_points / 4; __m128 vPower = _mm_set_ps1(power); __m128 zeroValue = _mm_setzero_ps(); __m128 signMask; __m128 negatedValues; __m128 negativeOneToPower = _mm_set_ps1(powf(-1, power)); __m128 onesMask = _mm_set_ps1(1); __m128 aVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); signMask = _mm_cmplt_ps(aVal, zeroValue); negatedValues = _mm_sub_ps(zeroValue, aVal); aVal = _mm_blendv_ps(aVal, negatedValues, signMask); // powf4 doesn't support negative values in the base, so we mask them off and then apply the negative after cVal = powf4(aVal, vPower); // Takes each input value to the specified power cVal = _mm_mul_ps( _mm_blendv_ps(onesMask, negativeOneToPower, signMask), cVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; cPtr += 4; } number = quarterPoints * 4; #endif /* LV_HAVE_LIB_SIMDMATH */ for(;number < num_points; number++){ *cPtr++ = powf((*aPtr++), power); } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief Takes each the input vector value to the specified power and stores the results in the return vector \param cVector The vector where the results will be stored \param aVector The vector of values to be taken to a power \param power The power value to be applied to each data point \param num_points The number of values in aVector to be taken to the specified power level and stored into cVector */ static inline void volk_32f_s32f_power_32f_a_sse(float* cVector, const float* aVector, const float power, unsigned int num_points){ unsigned int number = 0; float* cPtr = cVector; const float* aPtr = aVector; #ifdef LV_HAVE_LIB_SIMDMATH const unsigned int quarterPoints = num_points / 4; __m128 vPower = _mm_set_ps1(power); __m128 zeroValue = _mm_setzero_ps(); __m128 signMask; __m128 negatedValues; __m128 negativeOneToPower = _mm_set_ps1(powf(-1, power)); __m128 onesMask = _mm_set_ps1(1); __m128 aVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); signMask = _mm_cmplt_ps(aVal, zeroValue); negatedValues = _mm_sub_ps(zeroValue, aVal); aVal = _mm_or_ps(_mm_andnot_ps(signMask, aVal), _mm_and_ps(signMask, negatedValues) ); // powf4 doesn't support negative values in the base, so we mask them off and then apply the negative after cVal = powf4(aVal, vPower); // Takes each input value to the specified power cVal = _mm_mul_ps( _mm_or_ps( _mm_andnot_ps(signMask, onesMask), _mm_and_ps(signMask, negativeOneToPower) ), cVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; cPtr += 4; } number = quarterPoints * 4; #endif /* LV_HAVE_LIB_SIMDMATH */ for(;number < num_points; number++){ *cPtr++ = powf((*aPtr++), power); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Takes each the input vector value to the specified power and stores the results in the return vector \param cVector The vector where the results will be stored \param aVector The vector of values to be taken to a power \param power The power value to be applied to each data point \param num_points The number of values in aVector to be taken to the specified power level and stored into cVector */ static inline void volk_32f_s32f_power_32f_generic(float* cVector, const float* aVector, const float power, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = powf((*aPtr++), power); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_power_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_stddev_and_mean_32f_x2.h0000664000175000017500000001367012207440367025005 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_stddev_and_mean_32f_x2_a_H #define INCLUDED_volk_32f_stddev_and_mean_32f_x2_a_H #include #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Calculates the standard deviation and mean of the input buffer \param stddev The calculated standard deviation \param mean The mean of the input buffer \param inputBuffer The buffer of points to calculate the std deviation for \param num_points The number of values in input buffer to used in the stddev and mean calculations */ static inline void volk_32f_stddev_and_mean_32f_x2_a_sse4_1(float* stddev, float* mean, const float* inputBuffer, unsigned int num_points){ float returnValue = 0; float newMean = 0; if(num_points > 0){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; const float* aPtr = inputBuffer; __VOLK_ATTR_ALIGNED(16) float meanBuffer[4]; __VOLK_ATTR_ALIGNED(16) float squareBuffer[4]; __m128 accumulator = _mm_setzero_ps(); __m128 squareAccumulator = _mm_setzero_ps(); __m128 aVal1, aVal2, aVal3, aVal4; __m128 cVal1, cVal2, cVal3, cVal4; for(;number < sixteenthPoints; number++) { aVal1 = _mm_load_ps(aPtr); aPtr += 4; cVal1 = _mm_dp_ps(aVal1, aVal1, 0xF1); accumulator = _mm_add_ps(accumulator, aVal1); // accumulator += x aVal2 = _mm_load_ps(aPtr); aPtr += 4; cVal2 = _mm_dp_ps(aVal2, aVal2, 0xF2); accumulator = _mm_add_ps(accumulator, aVal2); // accumulator += x aVal3 = _mm_load_ps(aPtr); aPtr += 4; cVal3 = _mm_dp_ps(aVal3, aVal3, 0xF4); accumulator = _mm_add_ps(accumulator, aVal3); // accumulator += x aVal4 = _mm_load_ps(aPtr); aPtr += 4; cVal4 = _mm_dp_ps(aVal4, aVal4, 0xF8); accumulator = _mm_add_ps(accumulator, aVal4); // accumulator += x cVal1 = _mm_or_ps(cVal1, cVal2); cVal3 = _mm_or_ps(cVal3, cVal4); cVal1 = _mm_or_ps(cVal1, cVal3); squareAccumulator = _mm_add_ps(squareAccumulator, cVal1); // squareAccumulator += x^2 } _mm_store_ps(meanBuffer,accumulator); // Store the results back into the C container _mm_store_ps(squareBuffer,squareAccumulator); // Store the results back into the C container newMean = meanBuffer[0]; newMean += meanBuffer[1]; newMean += meanBuffer[2]; newMean += meanBuffer[3]; returnValue = squareBuffer[0]; returnValue += squareBuffer[1]; returnValue += squareBuffer[2]; returnValue += squareBuffer[3]; number = sixteenthPoints * 16; for(;number < num_points; number++){ returnValue += (*aPtr) * (*aPtr); newMean += *aPtr++; } newMean /= num_points; returnValue /= num_points; returnValue -= (newMean * newMean); returnValue = sqrtf(returnValue); } *stddev = returnValue; *mean = newMean; } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the standard deviation and mean of the input buffer \param stddev The calculated standard deviation \param mean The mean of the input buffer \param inputBuffer The buffer of points to calculate the std deviation for \param num_points The number of values in input buffer to used in the stddev and mean calculations */ static inline void volk_32f_stddev_and_mean_32f_x2_a_sse(float* stddev, float* mean, const float* inputBuffer, unsigned int num_points){ float returnValue = 0; float newMean = 0; if(num_points > 0){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* aPtr = inputBuffer; __VOLK_ATTR_ALIGNED(16) float meanBuffer[4]; __VOLK_ATTR_ALIGNED(16) float squareBuffer[4]; __m128 accumulator = _mm_setzero_ps(); __m128 squareAccumulator = _mm_setzero_ps(); __m128 aVal = _mm_setzero_ps(); for(;number < quarterPoints; number++) { aVal = _mm_load_ps(aPtr); // aVal = x accumulator = _mm_add_ps(accumulator, aVal); // accumulator += x aVal = _mm_mul_ps(aVal, aVal); // squareAccumulator += x^2 squareAccumulator = _mm_add_ps(squareAccumulator, aVal); aPtr += 4; } _mm_store_ps(meanBuffer,accumulator); // Store the results back into the C container _mm_store_ps(squareBuffer,squareAccumulator); // Store the results back into the C container newMean = meanBuffer[0]; newMean += meanBuffer[1]; newMean += meanBuffer[2]; newMean += meanBuffer[3]; returnValue = squareBuffer[0]; returnValue += squareBuffer[1]; returnValue += squareBuffer[2]; returnValue += squareBuffer[3]; number = quarterPoints * 4; for(;number < num_points; number++){ returnValue += (*aPtr) * (*aPtr); newMean += *aPtr++; } newMean /= num_points; returnValue /= num_points; returnValue -= (newMean * newMean); returnValue = sqrtf(returnValue); } *stddev = returnValue; *mean = newMean; } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the standard deviation and mean of the input buffer \param stddev The calculated standard deviation \param mean The mean of the input buffer \param inputBuffer The buffer of points to calculate the std deviation for \param num_points The number of values in input buffer to used in the stddev and mean calculations */ static inline void volk_32f_stddev_and_mean_32f_x2_generic(float* stddev, float* mean, const float* inputBuffer, unsigned int num_points){ float returnValue = 0; float newMean = 0; if(num_points > 0){ const float* aPtr = inputBuffer; unsigned int number = 0; for(number = 0; number < num_points; number++){ returnValue += (*aPtr) * (*aPtr); newMean += *aPtr++; } newMean /= num_points; returnValue /= num_points; returnValue -= (newMean * newMean); returnValue = sqrtf(returnValue); } *stddev = returnValue; *mean = newMean; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_stddev_and_mean_32f_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32fc_rotatorpuppet_32fc.h0000664000175000017500000000534312233557776025531 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32fc_rotatorpuppet_32fc_a_H #define INCLUDED_volk_32fc_s32fc_rotatorpuppet_32fc_a_H #include #include #include #ifdef LV_HAVE_GENERIC /*! \brief rotate input vector at fixed rate per sample from initial phase offset \param outVector The vector where the results will be stored \param inVector Vector to be rotated \param phase_inc rotational velocity \param phase initial phase offset \param num_points The number of values in inVector to be rotated and stored into cVector */ static inline void volk_32fc_s32fc_rotatorpuppet_32fc_generic(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, unsigned int num_points){ lv_32fc_t phase[1] = {lv_cmake(.3, 0.95393)}; volk_32fc_s32fc_x2_rotator_32fc_generic(outVector, inVector, phase_inc, phase, num_points); } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_SSE4_1 #include static inline void volk_32fc_s32fc_rotatorpuppet_32fc_a_sse4_1(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, unsigned int num_points){ lv_32fc_t phase[1] = {lv_cmake(.3, .95393)}; volk_32fc_s32fc_x2_rotator_32fc_a_sse4_1(outVector, inVector, phase_inc, phase, num_points); } static inline void volk_32fc_s32fc_rotatorpuppet_32fc_u_sse4_1(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, unsigned int num_points){ lv_32fc_t phase[1] = {lv_cmake(.3, .95393)}; volk_32fc_s32fc_x2_rotator_32fc_u_sse4_1(outVector, inVector, phase_inc, phase, num_points); } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_AVX #include /*! \brief rotate input vector at fixed rate per sample from initial phase offset \param outVector The vector where the results will be stored \param inVector Vector to be rotated \param phase_inc rotational velocity \param phase initial phase offset \param num_points The number of values in inVector to be rotated and stored into cVector */ static inline void volk_32fc_s32fc_rotatorpuppet_32fc_a_avx(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, unsigned int num_points){ lv_32fc_t phase[1] = {lv_cmake(.3, .95393)}; volk_32fc_s32fc_x2_rotator_32fc_a_avx(outVector, inVector, phase_inc, phase, num_points); } static inline void volk_32fc_s32fc_rotatorpuppet_32fc_u_avx(lv_32fc_t* outVector, const lv_32fc_t* inVector, const lv_32fc_t phase_inc, unsigned int num_points){ lv_32fc_t phase[1] = {lv_cmake(.3, .95393)}; volk_32fc_s32fc_x2_rotator_32fc_u_avx(outVector, inVector, phase_inc, phase, num_points); } #endif /* LV_HAVE_AVX */ #endif /* INCLUDED_volk_32fc_s32fc_rotatorpuppet_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32u_byteswap.h0000664000175000017500000001140412207440367022455 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32u_byteswap_u_H #define INCLUDED_volk_32u_byteswap_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Byteswaps (in-place) an aligned vector of int32_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_32u_byteswap_u_sse2(uint32_t* intsToSwap, unsigned int num_points){ unsigned int number = 0; uint32_t* inputPtr = intsToSwap; __m128i input, byte1, byte2, byte3, byte4, output; __m128i byte2mask = _mm_set1_epi32(0x00FF0000); __m128i byte3mask = _mm_set1_epi32(0x0000FF00); const uint64_t quarterPoints = num_points / 4; for(;number < quarterPoints; number++){ // Load the 32t values, increment inputPtr later since we're doing it in-place. input = _mm_loadu_si128((__m128i*)inputPtr); // Do the four shifts byte1 = _mm_slli_epi32(input, 24); byte2 = _mm_slli_epi32(input, 8); byte3 = _mm_srli_epi32(input, 8); byte4 = _mm_srli_epi32(input, 24); // Or bytes together output = _mm_or_si128(byte1, byte4); byte2 = _mm_and_si128(byte2, byte2mask); output = _mm_or_si128(output, byte2); byte3 = _mm_and_si128(byte3, byte3mask); output = _mm_or_si128(output, byte3); // Store the results _mm_storeu_si128((__m128i*)inputPtr, output); inputPtr += 4; } // Byteswap any remaining points: number = quarterPoints*4; for(; number < num_points; number++){ uint32_t outputVal = *inputPtr; outputVal = (((outputVal >> 24) & 0xff) | ((outputVal >> 8) & 0x0000ff00) | ((outputVal << 8) & 0x00ff0000) | ((outputVal << 24) & 0xff000000)); *inputPtr = outputVal; inputPtr++; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int32_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_32u_byteswap_generic(uint32_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = intsToSwap; unsigned int point; for(point = 0; point < num_points; point++){ uint32_t output = *inputPtr; output = (((output >> 24) & 0xff) | ((output >> 8) & 0x0000ff00) | ((output << 8) & 0x00ff0000) | ((output << 24) & 0xff000000)); *inputPtr = output; inputPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32u_byteswap_u_H */ #ifndef INCLUDED_volk_32u_byteswap_a_H #define INCLUDED_volk_32u_byteswap_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Byteswaps (in-place) an aligned vector of int32_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_32u_byteswap_a_sse2(uint32_t* intsToSwap, unsigned int num_points){ unsigned int number = 0; uint32_t* inputPtr = intsToSwap; __m128i input, byte1, byte2, byte3, byte4, output; __m128i byte2mask = _mm_set1_epi32(0x00FF0000); __m128i byte3mask = _mm_set1_epi32(0x0000FF00); const uint64_t quarterPoints = num_points / 4; for(;number < quarterPoints; number++){ // Load the 32t values, increment inputPtr later since we're doing it in-place. input = _mm_load_si128((__m128i*)inputPtr); // Do the four shifts byte1 = _mm_slli_epi32(input, 24); byte2 = _mm_slli_epi32(input, 8); byte3 = _mm_srli_epi32(input, 8); byte4 = _mm_srli_epi32(input, 24); // Or bytes together output = _mm_or_si128(byte1, byte4); byte2 = _mm_and_si128(byte2, byte2mask); output = _mm_or_si128(output, byte2); byte3 = _mm_and_si128(byte3, byte3mask); output = _mm_or_si128(output, byte3); // Store the results _mm_store_si128((__m128i*)inputPtr, output); inputPtr += 4; } // Byteswap any remaining points: number = quarterPoints*4; for(; number < num_points; number++){ uint32_t outputVal = *inputPtr; outputVal = (((outputVal >> 24) & 0xff) | ((outputVal >> 8) & 0x0000ff00) | ((outputVal << 8) & 0x00ff0000) | ((outputVal << 24) & 0xff000000)); *inputPtr = outputVal; inputPtr++; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int32_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_32u_byteswap_a_generic(uint32_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = intsToSwap; unsigned int point; for(point = 0; point < num_points; point++){ uint32_t output = *inputPtr; output = (((output >> 24) & 0xff) | ((output >> 8) & 0x0000ff00) | ((output << 8) & 0x00ff0000) | ((output << 24) & 0xff000000)); *inputPtr = output; inputPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32u_byteswap_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_64f_x2_min_64f.h0000664000175000017500000000431512207440367022463 0ustar jcorganjcorgan#ifndef INCLUDED_volk_64f_x2_min_64f_a_H #define INCLUDED_volk_64f_x2_min_64f_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Selects minimum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_64f_x2_min_64f_a_sse2(double* cVector, const double* aVector, const double* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; double* cPtr = cVector; const double* aPtr = aVector; const double* bPtr= bVector; __m128d aVal, bVal, cVal; for(;number < halfPoints; number++){ aVal = _mm_load_pd(aPtr); bVal = _mm_load_pd(bPtr); cVal = _mm_min_pd(aVal, bVal); _mm_store_pd(cPtr,cVal); // Store the results back into the C container aPtr += 2; bPtr += 2; cPtr += 2; } number = halfPoints * 2; for(;number < num_points; number++){ const double a = *aPtr++; const double b = *bPtr++; *cPtr++ = ( a < b ? a : b); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Selects minimum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_64f_x2_min_64f_generic(double* cVector, const double* aVector, const double* bVector, unsigned int num_points){ double* cPtr = cVector; const double* aPtr = aVector; const double* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const double a = *aPtr++; const double b = *bPtr++; *cPtr++ = ( a < b ? a : b); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64f_x2_min_64f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_subtract_32f.h0000664000175000017500000000543012207440367023514 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_subtract_32f_a_H #define INCLUDED_volk_32f_x2_subtract_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Subtracts bVector form aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The initial vector \param bVector The vector to be subtracted \param num_points The number of values in aVector and bVector to be subtracted together and stored into cVector */ static inline void volk_32f_x2_subtract_32f_a_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_sub_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) - (*bPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Subtracts bVector form aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The initial vector \param bVector The vector to be subtracted \param num_points The number of values in aVector and bVector to be subtracted together and stored into cVector */ static inline void volk_32f_x2_subtract_32f_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) - (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Subtracts bVector form aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The initial vector \param bVector The vector to be subtracted \param num_points The number of values in aVector and bVector to be subtracted together and stored into cVector */ extern void volk_32f_x2_subtract_32f_a_orc_impl(float* cVector, const float* aVector, const float* bVector, unsigned int num_points); static inline void volk_32f_x2_subtract_32f_u_orc(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ volk_32f_x2_subtract_32f_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_x2_subtract_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_min_32f.h0000664000175000017500000000566012207440367022455 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_min_32f_a_H #define INCLUDED_volk_32f_x2_min_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Selects minimum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_32f_x2_min_32f_a_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_min_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ const float a = *aPtr++; const float b = *bPtr++; *cPtr++ = ( a < b ? a : b); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Selects minimum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_32f_x2_min_32f_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float a = *aPtr++; const float b = *bPtr++; *cPtr++ = ( a < b ? a : b); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Selects minimum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ extern void volk_32f_x2_min_32f_a_orc_impl(float* cVector, const float* aVector, const float* bVector, unsigned int num_points); static inline void volk_32f_x2_min_32f_u_orc(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ volk_32f_x2_min_32f_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_x2_min_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_convert_32i.h0000664000175000017500000002536612207440367023606 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_convert_32i_u_H #define INCLUDED_volk_32f_s32f_convert_32i_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_32i_u_sse2(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int32_t* outputVectorPtr = outputVector; float min_val = -2147483647; float max_val = 2147483647; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 inputVal1; __m128i intInputVal1; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); for(;number < quarterPoints; number++){ inputVal1 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; inputVal1 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); intInputVal1 = _mm_cvtps_epi32(inputVal1); _mm_storeu_si128((__m128i*)outputVectorPtr, intInputVal1); outputVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int32_t)(r); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_32i_u_sse(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int32_t* outputVectorPtr = outputVector; float min_val = -2147483647; float max_val = 2147483647; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 ret; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ ret = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; ret = _mm_max_ps(_mm_min_ps(_mm_mul_ps(ret, vScalar), vmax_val), vmin_val); _mm_store_ps(outputFloatBuffer, ret); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[0]); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[1]); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[2]); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[3]); } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int32_t)(r); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_32i_generic(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ int32_t* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; float min_val = -2147483647; float max_val = 2147483647; float r; for(number = 0; number < num_points; number++){ r = *inputVectorPtr++ * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; *outputVectorPtr++ = (int32_t)(r); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_convert_32i_u_H */ #ifndef INCLUDED_volk_32f_s32f_convert_32i_a_H #define INCLUDED_volk_32f_s32f_convert_32i_a_H #include #include #include #ifdef LV_HAVE_AVX #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_32i_a_avx(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; const float* inputVectorPtr = (const float*)inputVector; int32_t* outputVectorPtr = outputVector; float min_val = -2147483647; float max_val = 2147483647; float r; __m256 vScalar = _mm256_set1_ps(scalar); __m256 inputVal1; __m256i intInputVal1; __m256 vmin_val = _mm256_set1_ps(min_val); __m256 vmax_val = _mm256_set1_ps(max_val); for(;number < eighthPoints; number++){ inputVal1 = _mm256_load_ps(inputVectorPtr); inputVectorPtr += 8; inputVal1 = _mm256_max_ps(_mm256_min_ps(_mm256_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); intInputVal1 = _mm256_cvtps_epi32(inputVal1); _mm256_store_si256((__m256i*)outputVectorPtr, intInputVal1); outputVectorPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int32_t)(r); } } #endif /* LV_HAVE_AVX */ #ifdef LV_HAVE_SSE2 #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_32i_a_sse2(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int32_t* outputVectorPtr = outputVector; float min_val = -2147483647; float max_val = 2147483647; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 inputVal1; __m128i intInputVal1; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); for(;number < quarterPoints; number++){ inputVal1 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; inputVal1 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); intInputVal1 = _mm_cvtps_epi32(inputVal1); _mm_store_si128((__m128i*)outputVectorPtr, intInputVal1); outputVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int32_t)(r); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_32i_a_sse(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int32_t* outputVectorPtr = outputVector; float min_val = -2147483647; float max_val = 2147483647; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 ret; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ ret = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; ret = _mm_max_ps(_mm_min_ps(_mm_mul_ps(ret, vScalar), vmax_val), vmin_val); _mm_store_ps(outputFloatBuffer, ret); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[0]); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[1]); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[2]); *outputVectorPtr++ = (int32_t)(outputFloatBuffer[3]); } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int32_t)(r); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 32 bit integer value \param inputVector The floating point input data buffer \param outputVector The 32 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_32i_a_generic(int32_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ int32_t* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; float min_val = -2147483647; float max_val = 2147483647; float r; for(number = 0; number < num_points; number++){ r = *inputVectorPtr++ * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; *outputVectorPtr++ = (int32_t)(r); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_convert_32i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_s32f_interleave_16ic.h0000664000175000017500000001325112207440367025030 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_s32f_interleave_16ic_a_H #define INCLUDED_volk_32f_x2_s32f_interleave_16ic_a_H #include #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Interleaves the I & Q vector data into the complex vector, scales the output values by the scalar, and converts to 16 bit data. \param iBuffer The I buffer data to be interleaved \param qBuffer The Q buffer data to be interleaved \param complexVector The complex output vector \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be interleaved */ static inline void volk_32f_x2_s32f_interleave_16ic_a_sse2(lv_16sc_t* complexVector, const float* iBuffer, const float* qBuffer, const float scalar, unsigned int num_points){ unsigned int number = 0; const float* iBufferPtr = iBuffer; const float* qBufferPtr = qBuffer; __m128 vScalar = _mm_set_ps1(scalar); const unsigned int quarterPoints = num_points / 4; __m128 iValue, qValue, cplxValue1, cplxValue2; __m128i intValue1, intValue2; int16_t* complexVectorPtr = (int16_t*)complexVector; for(;number < quarterPoints; number++){ iValue = _mm_load_ps(iBufferPtr); qValue = _mm_load_ps(qBufferPtr); // Interleaves the lower two values in the i and q variables into one buffer cplxValue1 = _mm_unpacklo_ps(iValue, qValue); cplxValue1 = _mm_mul_ps(cplxValue1, vScalar); // Interleaves the upper two values in the i and q variables into one buffer cplxValue2 = _mm_unpackhi_ps(iValue, qValue); cplxValue2 = _mm_mul_ps(cplxValue2, vScalar); intValue1 = _mm_cvtps_epi32(cplxValue1); intValue2 = _mm_cvtps_epi32(cplxValue2); intValue1 = _mm_packs_epi32(intValue1, intValue2); _mm_store_si128((__m128i*)complexVectorPtr, intValue1); complexVectorPtr += 8; iBufferPtr += 4; qBufferPtr += 4; } number = quarterPoints * 4; complexVectorPtr = (int16_t*)(&complexVector[number]); for(; number < num_points; number++){ *complexVectorPtr++ = (int16_t)(*iBufferPtr++ * scalar); *complexVectorPtr++ = (int16_t)(*qBufferPtr++ * scalar); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Interleaves the I & Q vector data into the complex vector, scales the output values by the scalar, and converts to 16 bit data. \param iBuffer The I buffer data to be interleaved \param qBuffer The Q buffer data to be interleaved \param complexVector The complex output vector \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be interleaved */ static inline void volk_32f_x2_s32f_interleave_16ic_a_sse(lv_16sc_t* complexVector, const float* iBuffer, const float* qBuffer, const float scalar, unsigned int num_points){ unsigned int number = 0; const float* iBufferPtr = iBuffer; const float* qBufferPtr = qBuffer; __m128 vScalar = _mm_set_ps1(scalar); const unsigned int quarterPoints = num_points / 4; __m128 iValue, qValue, cplxValue; int16_t* complexVectorPtr = (int16_t*)complexVector; __VOLK_ATTR_ALIGNED(16) float floatBuffer[4]; for(;number < quarterPoints; number++){ iValue = _mm_load_ps(iBufferPtr); qValue = _mm_load_ps(qBufferPtr); // Interleaves the lower two values in the i and q variables into one buffer cplxValue = _mm_unpacklo_ps(iValue, qValue); cplxValue = _mm_mul_ps(cplxValue, vScalar); _mm_store_ps(floatBuffer, cplxValue); *complexVectorPtr++ = (int16_t)(floatBuffer[0]); *complexVectorPtr++ = (int16_t)(floatBuffer[1]); *complexVectorPtr++ = (int16_t)(floatBuffer[2]); *complexVectorPtr++ = (int16_t)(floatBuffer[3]); // Interleaves the upper two values in the i and q variables into one buffer cplxValue = _mm_unpackhi_ps(iValue, qValue); cplxValue = _mm_mul_ps(cplxValue, vScalar); _mm_store_ps(floatBuffer, cplxValue); *complexVectorPtr++ = (int16_t)(floatBuffer[0]); *complexVectorPtr++ = (int16_t)(floatBuffer[1]); *complexVectorPtr++ = (int16_t)(floatBuffer[2]); *complexVectorPtr++ = (int16_t)(floatBuffer[3]); iBufferPtr += 4; qBufferPtr += 4; } number = quarterPoints * 4; complexVectorPtr = (int16_t*)(&complexVector[number]); for(; number < num_points; number++){ *complexVectorPtr++ = (int16_t)(*iBufferPtr++ * scalar); *complexVectorPtr++ = (int16_t)(*qBufferPtr++ * scalar); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Interleaves the I & Q vector data into the complex vector, scales the output values by the scalar, and converts to 16 bit data. \param iBuffer The I buffer data to be interleaved \param qBuffer The Q buffer data to be interleaved \param complexVector The complex output vector \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be interleaved */ static inline void volk_32f_x2_s32f_interleave_16ic_generic(lv_16sc_t* complexVector, const float* iBuffer, const float* qBuffer, const float scalar, unsigned int num_points){ int16_t* complexVectorPtr = (int16_t*)complexVector; const float* iBufferPtr = iBuffer; const float* qBufferPtr = qBuffer; unsigned int number = 0; for(number = 0; number < num_points; number++){ *complexVectorPtr++ = (int16_t)(*iBufferPtr++ * scalar); *complexVectorPtr++ = (int16_t)(*qBufferPtr++ * scalar); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_x2_s32f_interleave_16ic_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_convert_8i.h0000664000175000017500000001040612207440367022666 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_convert_8i_u_H #define INCLUDED_volk_16i_convert_8i_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the input 16 bit integer data into 8 bit integer data \param inputVector The 16 bit input data buffer \param outputVector The 8 bit output data buffer \param num_points The number of data values to be converted \note Input and output buffers do NOT need to be properly aligned */ static inline void volk_16i_convert_8i_u_sse2(int8_t* outputVector, const int16_t* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; int8_t* outputVectorPtr = outputVector; int16_t* inputPtr = (int16_t*)inputVector; __m128i inputVal1; __m128i inputVal2; __m128i ret; for(;number < sixteenthPoints; number++){ // Load the 16 values inputVal1 = _mm_loadu_si128((__m128i*)inputPtr); inputPtr += 8; inputVal2 = _mm_loadu_si128((__m128i*)inputPtr); inputPtr += 8; inputVal1 = _mm_srai_epi16(inputVal1, 8); inputVal2 = _mm_srai_epi16(inputVal2, 8); ret = _mm_packs_epi16(inputVal1, inputVal2); _mm_storeu_si128((__m128i*)outputVectorPtr, ret); outputVectorPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ outputVector[number] =(int8_t)(inputVector[number] >> 8); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 16 bit integer data into 8 bit integer data \param inputVector The 16 bit input data buffer \param outputVector The 8 bit output data buffer \param num_points The number of data values to be converted \note Input and output buffers do NOT need to be properly aligned */ static inline void volk_16i_convert_8i_generic(int8_t* outputVector, const int16_t* inputVector, unsigned int num_points){ int8_t* outputVectorPtr = outputVector; const int16_t* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((int8_t)(*inputVectorPtr++ >> 8)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16i_convert_8i_u_H */ #ifndef INCLUDED_volk_16i_convert_8i_a_H #define INCLUDED_volk_16i_convert_8i_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the input 16 bit integer data into 8 bit integer data \param inputVector The 16 bit input data buffer \param outputVector The 8 bit output data buffer \param num_points The number of data values to be converted */ static inline void volk_16i_convert_8i_a_sse2(int8_t* outputVector, const int16_t* inputVector, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; int8_t* outputVectorPtr = outputVector; int16_t* inputPtr = (int16_t*)inputVector; __m128i inputVal1; __m128i inputVal2; __m128i ret; for(;number < sixteenthPoints; number++){ // Load the 16 values inputVal1 = _mm_load_si128((__m128i*)inputPtr); inputPtr += 8; inputVal2 = _mm_load_si128((__m128i*)inputPtr); inputPtr += 8; inputVal1 = _mm_srai_epi16(inputVal1, 8); inputVal2 = _mm_srai_epi16(inputVal2, 8); ret = _mm_packs_epi16(inputVal1, inputVal2); _mm_store_si128((__m128i*)outputVectorPtr, ret); outputVectorPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ outputVector[number] =(int8_t)(inputVector[number] >> 8); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 16 bit integer data into 8 bit integer data \param inputVector The 16 bit input data buffer \param outputVector The 8 bit output data buffer \param num_points The number of data values to be converted */ static inline void volk_16i_convert_8i_a_generic(int8_t* outputVector, const int16_t* inputVector, unsigned int num_points){ int8_t* outputVectorPtr = outputVector; const int16_t* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((int8_t)(*inputVectorPtr++ >> 8)); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16i_convert_8i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32i_x2_or_32i.h0000664000175000017500000000550612207440367022317 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32i_x2_or_32i_a_H #define INCLUDED_volk_32i_x2_or_32i_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Ors the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be ored \param bVector One of the vectors to be ored \param num_points The number of values in aVector and bVector to be ored together and stored into cVector */ static inline void volk_32i_x2_or_32i_a_sse(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = (float*)cVector; const float* aPtr = (float*)aVector; const float* bPtr = (float*)bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_or_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ cVector[number] = aVector[number] | bVector[number]; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Ors the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be ored \param bVector One of the vectors to be ored \param num_points The number of values in aVector and bVector to be ored together and stored into cVector */ static inline void volk_32i_x2_or_32i_generic(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points){ int32_t* cPtr = cVector; const int32_t* aPtr = aVector; const int32_t* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) | (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Ors the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be ored \param bVector One of the vectors to be ored \param num_points The number of values in aVector and bVector to be ored together and stored into cVector */ extern void volk_32i_x2_or_32i_a_orc_impl(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points); static inline void volk_32i_x2_or_32i_u_orc(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points){ volk_32i_x2_or_32i_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32i_x2_or_32i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32i_x2_and_32i.h0000664000175000017500000000542312207440367022437 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32i_x2_and_32i_a_H #define INCLUDED_volk_32i_x2_and_32i_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Ands the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors \param bVector One of the vectors \param num_points The number of values in aVector and bVector to be anded together and stored into cVector */ static inline void volk_32i_x2_and_32i_a_sse(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = (float*)cVector; const float* aPtr = (float*)aVector; const float* bPtr = (float*)bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_and_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ cVector[number] = aVector[number] & bVector[number]; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Ands the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors \param bVector One of the vectors \param num_points The number of values in aVector and bVector to be anded together and stored into cVector */ static inline void volk_32i_x2_and_32i_generic(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points){ int32_t* cPtr = cVector; const int32_t* aPtr = aVector; const int32_t* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) & (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Ands the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors \param bVector One of the vectors \param num_points The number of values in aVector and bVector to be anded together and stored into cVector */ extern void volk_32i_x2_and_32i_a_orc_impl(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points); static inline void volk_32i_x2_and_32i_u_orc(int32_t* cVector, const int32_t* aVector, const int32_t* bVector, unsigned int num_points){ volk_32i_x2_and_32i_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32i_x2_and_32i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_calc_spectral_noise_floor_32f.h0000664000175000017500000001455612207440367027317 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_calc_spectral_noise_floor_32f_a_H #define INCLUDED_volk_32f_s32f_calc_spectral_noise_floor_32f_a_H #include #include #include #ifdef LV_HAVE_SSE #include /*! \brief Calculates the spectral noise floor of an input power spectrum Calculates the spectral noise floor of an input power spectrum by determining the mean of the input power spectrum, then recalculating the mean excluding any power spectrum values that exceed the mean by the spectralExclusionValue (in dB). Provides a rough estimation of the signal noise floor. \param realDataPoints The input power spectrum \param num_points The number of data points in the input power spectrum vector \param spectralExclusionValue The number of dB above the noise floor that a data point must be to be excluded from the noise floor calculation - default value is 20 \param noiseFloorAmplitude The noise floor of the input spectrum, in dB */ static inline void volk_32f_s32f_calc_spectral_noise_floor_32f_a_sse(float* noiseFloorAmplitude, const float* realDataPoints, const float spectralExclusionValue, const unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* dataPointsPtr = realDataPoints; __VOLK_ATTR_ALIGNED(16) float avgPointsVector[4]; __m128 dataPointsVal; __m128 avgPointsVal = _mm_setzero_ps(); // Calculate the sum (for mean) for all points for(; number < quarterPoints; number++){ dataPointsVal = _mm_load_ps(dataPointsPtr); dataPointsPtr += 4; avgPointsVal = _mm_add_ps(avgPointsVal, dataPointsVal); } _mm_store_ps(avgPointsVector, avgPointsVal); float sumMean = 0.0; sumMean += avgPointsVector[0]; sumMean += avgPointsVector[1]; sumMean += avgPointsVector[2]; sumMean += avgPointsVector[3]; number = quarterPoints * 4; for(;number < num_points; number++){ sumMean += realDataPoints[number]; } // calculate the spectral mean // +20 because for the comparison below we only want to throw out bins // that are significantly higher (and would, thus, affect the mean more const float meanAmplitude = (sumMean / ((float)num_points)) + spectralExclusionValue; dataPointsPtr = realDataPoints; // Reset the dataPointsPtr __m128 vMeanAmplitudeVector = _mm_set_ps1(meanAmplitude); __m128 vOnesVector = _mm_set_ps1(1.0); __m128 vValidBinCount = _mm_setzero_ps(); avgPointsVal = _mm_setzero_ps(); __m128 compareMask; number = 0; // Calculate the sum (for mean) for any points which do NOT exceed the mean amplitude for(; number < quarterPoints; number++){ dataPointsVal = _mm_load_ps(dataPointsPtr); dataPointsPtr += 4; // Identify which items do not exceed the mean amplitude compareMask = _mm_cmple_ps(dataPointsVal, vMeanAmplitudeVector); // Mask off the items that exceed the mean amplitude and add the avg Points that do not exceed the mean amplitude avgPointsVal = _mm_add_ps(avgPointsVal, _mm_and_ps(compareMask, dataPointsVal)); // Count the number of bins which do not exceed the mean amplitude vValidBinCount = _mm_add_ps(vValidBinCount, _mm_and_ps(compareMask, vOnesVector)); } // Calculate the mean from the remaining data points _mm_store_ps(avgPointsVector, avgPointsVal); sumMean = 0.0; sumMean += avgPointsVector[0]; sumMean += avgPointsVector[1]; sumMean += avgPointsVector[2]; sumMean += avgPointsVector[3]; // Calculate the number of valid bins from the remaning count __VOLK_ATTR_ALIGNED(16) float validBinCountVector[4]; _mm_store_ps(validBinCountVector, vValidBinCount); float validBinCount = 0; validBinCount += validBinCountVector[0]; validBinCount += validBinCountVector[1]; validBinCount += validBinCountVector[2]; validBinCount += validBinCountVector[3]; number = quarterPoints * 4; for(;number < num_points; number++){ if(realDataPoints[number] <= meanAmplitude){ sumMean += realDataPoints[number]; validBinCount += 1.0; } } float localNoiseFloorAmplitude = 0; if(validBinCount > 0.0){ localNoiseFloorAmplitude = sumMean / validBinCount; } else{ localNoiseFloorAmplitude = meanAmplitude; // For the odd case that all the amplitudes are equal... } *noiseFloorAmplitude = localNoiseFloorAmplitude; } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the spectral noise floor of an input power spectrum Calculates the spectral noise floor of an input power spectrum by determining the mean of the input power spectrum, then recalculating the mean excluding any power spectrum values that exceed the mean by the spectralExclusionValue (in dB). Provides a rough estimation of the signal noise floor. \param realDataPoints The input power spectrum \param num_points The number of data points in the input power spectrum vector \param spectralExclusionValue The number of dB above the noise floor that a data point must be to be excluded from the noise floor calculation - default value is 20 \param noiseFloorAmplitude The noise floor of the input spectrum, in dB */ static inline void volk_32f_s32f_calc_spectral_noise_floor_32f_generic(float* noiseFloorAmplitude, const float* realDataPoints, const float spectralExclusionValue, const unsigned int num_points){ float sumMean = 0.0; unsigned int number; // find the sum (for mean), etc for(number = 0; number < num_points; number++){ // sum (for mean) sumMean += realDataPoints[number]; } // calculate the spectral mean // +20 because for the comparison below we only want to throw out bins // that are significantly higher (and would, thus, affect the mean more) const float meanAmplitude = (sumMean / num_points) + spectralExclusionValue; // now throw out any bins higher than the mean sumMean = 0.0; unsigned int newNumDataPoints = num_points; for(number = 0; number < num_points; number++){ if (realDataPoints[number] <= meanAmplitude) sumMean += realDataPoints[number]; else newNumDataPoints--; } float localNoiseFloorAmplitude = 0.0; if (newNumDataPoints == 0) // in the odd case that all localNoiseFloorAmplitude = meanAmplitude; // amplitudes are equal! else localNoiseFloorAmplitude = sumMean / ((float)newNumDataPoints); *noiseFloorAmplitude = localNoiseFloorAmplitude; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_calc_spectral_noise_floor_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_64u_byteswap.h0000664000175000017500000001352612207440367022471 0ustar jcorganjcorgan#ifndef INCLUDED_volk_64u_byteswap_u_H #define INCLUDED_volk_64u_byteswap_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_u_sse2(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; __m128i input, byte1, byte2, byte3, byte4, output; __m128i byte2mask = _mm_set1_epi32(0x00FF0000); __m128i byte3mask = _mm_set1_epi32(0x0000FF00); uint64_t number = 0; const unsigned int halfPoints = num_points / 2; for(;number < halfPoints; number++){ // Load the 32t values, increment inputPtr later since we're doing it in-place. input = _mm_loadu_si128((__m128i*)inputPtr); // Do the four shifts byte1 = _mm_slli_epi32(input, 24); byte2 = _mm_slli_epi32(input, 8); byte3 = _mm_srli_epi32(input, 8); byte4 = _mm_srli_epi32(input, 24); // Or bytes together output = _mm_or_si128(byte1, byte4); byte2 = _mm_and_si128(byte2, byte2mask); output = _mm_or_si128(output, byte2); byte3 = _mm_and_si128(byte3, byte3mask); output = _mm_or_si128(output, byte3); // Reorder the two words output = _mm_shuffle_epi32(output, _MM_SHUFFLE(2, 3, 0, 1)); // Store the results _mm_storeu_si128((__m128i*)inputPtr, output); inputPtr += 4; } // Byteswap any remaining points: number = halfPoints*2; for(; number < num_points; number++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_generic(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; unsigned int point; for(point = 0; point < num_points; point++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64u_byteswap_u_H */ #ifndef INCLUDED_volk_64u_byteswap_a_H #define INCLUDED_volk_64u_byteswap_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_a_sse2(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; __m128i input, byte1, byte2, byte3, byte4, output; __m128i byte2mask = _mm_set1_epi32(0x00FF0000); __m128i byte3mask = _mm_set1_epi32(0x0000FF00); uint64_t number = 0; const unsigned int halfPoints = num_points / 2; for(;number < halfPoints; number++){ // Load the 32t values, increment inputPtr later since we're doing it in-place. input = _mm_load_si128((__m128i*)inputPtr); // Do the four shifts byte1 = _mm_slli_epi32(input, 24); byte2 = _mm_slli_epi32(input, 8); byte3 = _mm_srli_epi32(input, 8); byte4 = _mm_srli_epi32(input, 24); // Or bytes together output = _mm_or_si128(byte1, byte4); byte2 = _mm_and_si128(byte2, byte2mask); output = _mm_or_si128(output, byte2); byte3 = _mm_and_si128(byte3, byte3mask); output = _mm_or_si128(output, byte3); // Reorder the two words output = _mm_shuffle_epi32(output, _MM_SHUFFLE(2, 3, 0, 1)); // Store the results _mm_store_si128((__m128i*)inputPtr, output); inputPtr += 4; } // Byteswap any remaining points: number = halfPoints*2; for(; number < num_points; number++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_a_generic(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; unsigned int point; for(point = 0; point < num_points; point++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64u_byteswap_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_64u_popcnt.h0000664000175000017500000000255712207440367022140 0ustar jcorganjcorgan#ifndef INCLUDED_volk_64u_popcnt_a_H #define INCLUDED_volk_64u_popcnt_a_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_64u_popcnt_generic(uint64_t* ret, const uint64_t value) { //const uint32_t* valueVector = (const uint32_t*)&value; // This is faster than a lookup table //uint32_t retVal = valueVector[0]; uint32_t retVal = (uint32_t)(value & 0x00000000FFFFFFFF); retVal = (retVal & 0x55555555) + (retVal >> 1 & 0x55555555); retVal = (retVal & 0x33333333) + (retVal >> 2 & 0x33333333); retVal = (retVal + (retVal >> 4)) & 0x0F0F0F0F; retVal = (retVal + (retVal >> 8)); retVal = (retVal + (retVal >> 16)) & 0x0000003F; uint64_t retVal64 = retVal; //retVal = valueVector[1]; retVal = (uint32_t)((value & 0xFFFFFFFF00000000) >> 31); retVal = (retVal & 0x55555555) + (retVal >> 1 & 0x55555555); retVal = (retVal & 0x33333333) + (retVal >> 2 & 0x33333333); retVal = (retVal + (retVal >> 4)) & 0x0F0F0F0F; retVal = (retVal + (retVal >> 8)); retVal = (retVal + (retVal >> 16)) & 0x0000003F; retVal64 += retVal; *ret = retVal64; } #endif /*LV_HAVE_GENERIC*/ #if LV_HAVE_SSE4_2 && LV_HAVE_64 #include static inline void volk_64u_popcnt_a_sse4_2(uint64_t* ret, const uint64_t value) { *ret = _mm_popcnt_u64(value); } #endif /*LV_HAVE_SSE4_2*/ #endif /*INCLUDED_volk_64u_popcnt_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_deinterleave_real_16i.h0000664000175000017500000001014212207440367025077 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_deinterleave_real_16i_a_H #define INCLUDED_volk_16ic_deinterleave_real_16i_a_H #include #include #ifdef LV_HAVE_SSSE3 #include /*! \brief Deinterleaves the complex 16 bit vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_real_16i_a_ssse3(int16_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int16_t* complexVectorPtr = (int16_t*)complexVector; int16_t* iBufferPtr = iBuffer; __m128i iMoveMask1 = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 13, 12, 9, 8, 5, 4, 1, 0); __m128i iMoveMask2 = _mm_set_epi8(13, 12, 9, 8, 5, 4, 1, 0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80); __m128i complexVal1, complexVal2, iOutputVal; unsigned int eighthPoints = num_points / 8; for(number = 0; number < eighthPoints; number++){ complexVal1 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 8; complexVal2 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 8; complexVal1 = _mm_shuffle_epi8(complexVal1, iMoveMask1); complexVal2 = _mm_shuffle_epi8(complexVal2, iMoveMask2); iOutputVal = _mm_or_si128(complexVal1, complexVal2); _mm_store_si128((__m128i*)iBufferPtr, iOutputVal); iBufferPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_SSSE3 */ #ifdef LV_HAVE_SSE2 #include /*! \brief Deinterleaves the complex 16 bit vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_real_16i_a_sse2(int16_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int16_t* complexVectorPtr = (int16_t*)complexVector; int16_t* iBufferPtr = iBuffer; __m128i complexVal1, complexVal2, iOutputVal; __m128i lowMask = _mm_set_epi32(0x0, 0x0, 0xFFFFFFFF, 0xFFFFFFFF); __m128i highMask = _mm_set_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0x0, 0x0); unsigned int eighthPoints = num_points / 8; for(number = 0; number < eighthPoints; number++){ complexVal1 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 8; complexVal2 = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 8; complexVal1 = _mm_shufflelo_epi16(complexVal1, _MM_SHUFFLE(3,1,2,0)); complexVal1 = _mm_shufflehi_epi16(complexVal1, _MM_SHUFFLE(3,1,2,0)); complexVal1 = _mm_shuffle_epi32(complexVal1, _MM_SHUFFLE(3,1,2,0)); complexVal2 = _mm_shufflelo_epi16(complexVal2, _MM_SHUFFLE(3,1,2,0)); complexVal2 = _mm_shufflehi_epi16(complexVal2, _MM_SHUFFLE(3,1,2,0)); complexVal2 = _mm_shuffle_epi32(complexVal2, _MM_SHUFFLE(2,0,3,1)); iOutputVal = _mm_or_si128(_mm_and_si128(complexVal1, lowMask), _mm_and_si128(complexVal2, highMask)); _mm_store_si128((__m128i*)iBufferPtr, iOutputVal); iBufferPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 16 bit vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_deinterleave_real_16i_generic(int16_t* iBuffer, const lv_16sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int16_t* complexVectorPtr = (int16_t*)complexVector; int16_t* iBufferPtr = iBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16ic_deinterleave_real_16i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16u_byteswap.h0000664000175000017500000001035712207440367022465 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16u_byteswap_u_H #define INCLUDED_volk_16u_byteswap_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Byteswaps (in-place) an unaligned vector of int16_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_16u_byteswap_u_sse2(uint16_t* intsToSwap, unsigned int num_points){ unsigned int number = 0; uint16_t* inputPtr = intsToSwap; __m128i input, left, right, output; const unsigned int eighthPoints = num_points / 8; for(;number < eighthPoints; number++){ // Load the 16t values, increment inputPtr later since we're doing it in-place. input = _mm_loadu_si128((__m128i*)inputPtr); // Do the two shifts left = _mm_slli_epi16(input, 8); right = _mm_srli_epi16(input, 8); // Or the left and right halves together output = _mm_or_si128(left, right); // Store the results _mm_storeu_si128((__m128i*)inputPtr, output); inputPtr += 8; } // Byteswap any remaining points: number = eighthPoints*8; for(; number < num_points; number++){ uint16_t outputVal = *inputPtr; outputVal = (((outputVal >> 8) & 0xff) | ((outputVal << 8) & 0xff00)); *inputPtr = outputVal; inputPtr++; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an unaligned vector of int16_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_16u_byteswap_generic(uint16_t* intsToSwap, unsigned int num_points){ unsigned int point; uint16_t* inputPtr = intsToSwap; for(point = 0; point < num_points; point++){ uint16_t output = *inputPtr; output = (((output >> 8) & 0xff) | ((output << 8) & 0xff00)); *inputPtr = output; inputPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16u_byteswap_u_H */ #ifndef INCLUDED_volk_16u_byteswap_a_H #define INCLUDED_volk_16u_byteswap_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Byteswaps (in-place) an aligned vector of int16_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_16u_byteswap_a_sse2(uint16_t* intsToSwap, unsigned int num_points){ unsigned int number = 0; uint16_t* inputPtr = intsToSwap; __m128i input, left, right, output; const unsigned int eighthPoints = num_points / 8; for(;number < eighthPoints; number++){ // Load the 16t values, increment inputPtr later since we're doing it in-place. input = _mm_load_si128((__m128i*)inputPtr); // Do the two shifts left = _mm_slli_epi16(input, 8); right = _mm_srli_epi16(input, 8); // Or the left and right halves together output = _mm_or_si128(left, right); // Store the results _mm_store_si128((__m128i*)inputPtr, output); inputPtr += 8; } // Byteswap any remaining points: number = eighthPoints*8; for(; number < num_points; number++){ uint16_t outputVal = *inputPtr; outputVal = (((outputVal >> 8) & 0xff) | ((outputVal << 8) & 0xff00)); *inputPtr = outputVal; inputPtr++; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int16_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_16u_byteswap_a_generic(uint16_t* intsToSwap, unsigned int num_points){ unsigned int point; uint16_t* inputPtr = intsToSwap; for(point = 0; point < num_points; point++){ uint16_t output = *inputPtr; output = (((output >> 8) & 0xff) | ((output << 8) & 0xff00)); *inputPtr = output; inputPtr++; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Byteswaps (in-place) an aligned vector of int16_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ extern void volk_16u_byteswap_a_orc_impl(uint16_t* intsToSwap, unsigned int num_points); static inline void volk_16u_byteswap_u_orc(uint16_t* intsToSwap, unsigned int num_points){ volk_16u_byteswap_a_orc_impl(intsToSwap, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_16u_byteswap_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32u_popcnt.h0000664000175000017500000000151412207440367022123 0ustar jcorganjcorgan#ifndef INCLUDED_VOLK_32u_POPCNT_A16_H #define INCLUDED_VOLK_32u_POPCNT_A16_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32u_popcnt_generic(uint32_t* ret, const uint32_t value) { // This is faster than a lookup table uint32_t retVal = value; retVal = (retVal & 0x55555555) + (retVal >> 1 & 0x55555555); retVal = (retVal & 0x33333333) + (retVal >> 2 & 0x33333333); retVal = (retVal + (retVal >> 4)) & 0x0F0F0F0F; retVal = (retVal + (retVal >> 8)); retVal = (retVal + (retVal >> 16)) & 0x0000003F; *ret = retVal; } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE4_2 #include static inline void volk_32u_popcnt_a_sse4_2(uint32_t* ret, const uint32_t value) { *ret = _mm_popcnt_u32(value); } #endif /*LV_HAVE_SSE4_2*/ #endif /*INCLUDED_VOLK_32u_POPCNT_A16_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_x2_multiply_conjugate_16ic.h0000664000175000017500000000741612207440367026052 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8ic_x2_multiply_conjugate_16ic_a_H #define INCLUDED_volk_8ic_x2_multiply_conjugate_16ic_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Multiplys the one complex vector with the complex conjugate of the second complex vector and stores their results in the third vector \param cVector The complex vector where the results will be stored \param aVector One of the complex vectors to be multiplied \param bVector The complex vector which will be converted to complex conjugate and multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_8ic_x2_multiply_conjugate_16ic_a_sse4_1(lv_16sc_t* cVector, const lv_8sc_t* aVector, const lv_8sc_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128i x, y, realz, imagz; lv_16sc_t* c = cVector; const lv_8sc_t* a = aVector; const lv_8sc_t* b = bVector; __m128i conjugateSign = _mm_set_epi16(-1, 1, -1, 1, -1, 1, -1, 1); for(;number < quarterPoints; number++){ // Convert into 8 bit values into 16 bit values x = _mm_cvtepi8_epi16(_mm_loadl_epi64((__m128i*)a)); y = _mm_cvtepi8_epi16(_mm_loadl_epi64((__m128i*)b)); // Calculate the ar*cr - ai*(-ci) portions realz = _mm_madd_epi16(x,y); // Calculate the complex conjugate of the cr + ci j values y = _mm_sign_epi16(y, conjugateSign); // Shift the order of the cr and ci values y = _mm_shufflehi_epi16(_mm_shufflelo_epi16(y, _MM_SHUFFLE(2,3,0,1) ), _MM_SHUFFLE(2,3,0,1)); // Calculate the ar*(-ci) + cr*(ai) imagz = _mm_madd_epi16(x,y); _mm_store_si128((__m128i*)c, _mm_packs_epi32(_mm_unpacklo_epi32(realz, imagz), _mm_unpackhi_epi32(realz, imagz))); a += 4; b += 4; c += 4; } number = quarterPoints * 4; int16_t* c16Ptr = (int16_t*)&cVector[number]; int8_t* a8Ptr = (int8_t*)&aVector[number]; int8_t* b8Ptr = (int8_t*)&bVector[number]; for(; number < num_points; number++){ float aReal = (float)*a8Ptr++; float aImag = (float)*a8Ptr++; lv_32fc_t aVal = lv_cmake(aReal, aImag ); float bReal = (float)*b8Ptr++; float bImag = (float)*b8Ptr++; lv_32fc_t bVal = lv_cmake( bReal, -bImag ); lv_32fc_t temp = aVal * bVal; *c16Ptr++ = (int16_t)lv_creal(temp); *c16Ptr++ = (int16_t)lv_cimag(temp); } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplys the one complex vector with the complex conjugate of the second complex vector and stores their results in the third vector \param cVector The complex vector where the results will be stored \param aVector One of the complex vectors to be multiplied \param bVector The complex vector which will be converted to complex conjugate and multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_8ic_x2_multiply_conjugate_16ic_generic(lv_16sc_t* cVector, const lv_8sc_t* aVector, const lv_8sc_t* bVector, unsigned int num_points){ unsigned int number = 0; int16_t* c16Ptr = (int16_t*)cVector; int8_t* a8Ptr = (int8_t*)aVector; int8_t* b8Ptr = (int8_t*)bVector; for(number =0; number < num_points; number++){ float aReal = (float)*a8Ptr++; float aImag = (float)*a8Ptr++; lv_32fc_t aVal = lv_cmake(aReal, aImag ); float bReal = (float)*b8Ptr++; float bImag = (float)*b8Ptr++; lv_32fc_t bVal = lv_cmake( bReal, -bImag ); lv_32fc_t temp = aVal * bVal; *c16Ptr++ = (int16_t)lv_creal(temp); *c16Ptr++ = (int16_t)lv_cimag(temp); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_8ic_x2_multiply_conjugate_16ic_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_branch_4_state_8.h0000664000175000017500000001126212207440367023716 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_branch_4_state_8_a_H #define INCLUDED_volk_16i_branch_4_state_8_a_H #include #include #ifdef LV_HAVE_SSSE3 #include #include #include static inline void volk_16i_branch_4_state_8_a_ssse3(short* target, short* src0, char** permuters, short* cntl2, short* cntl3, short* scalars) { __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11; __m128i *p_target, *p_src0, *p_cntl2, *p_cntl3, *p_scalars; p_target = (__m128i*)target; p_src0 = (__m128i*)src0; p_cntl2 = (__m128i*)cntl2; p_cntl3 = (__m128i*)cntl3; p_scalars = (__m128i*)scalars; int i = 0; int bound = 1; xmm0 = _mm_load_si128(p_scalars); xmm1 = _mm_shufflelo_epi16(xmm0, 0); xmm2 = _mm_shufflelo_epi16(xmm0, 0x55); xmm3 = _mm_shufflelo_epi16(xmm0, 0xaa); xmm4 = _mm_shufflelo_epi16(xmm0, 0xff); xmm1 = _mm_shuffle_epi32(xmm1, 0x00); xmm2 = _mm_shuffle_epi32(xmm2, 0x00); xmm3 = _mm_shuffle_epi32(xmm3, 0x00); xmm4 = _mm_shuffle_epi32(xmm4, 0x00); xmm0 = _mm_load_si128((__m128i*)permuters[0]); xmm6 = _mm_load_si128((__m128i*)permuters[1]); xmm8 = _mm_load_si128((__m128i*)permuters[2]); xmm10 = _mm_load_si128((__m128i*)permuters[3]); for(; i < bound; ++i) { xmm5 = _mm_load_si128(p_src0); xmm0 = _mm_shuffle_epi8(xmm5, xmm0); xmm6 = _mm_shuffle_epi8(xmm5, xmm6); xmm8 = _mm_shuffle_epi8(xmm5, xmm8); xmm10 = _mm_shuffle_epi8(xmm5, xmm10); p_src0 += 4; xmm5 = _mm_add_epi16(xmm1, xmm2); xmm6 = _mm_add_epi16(xmm2, xmm6); xmm8 = _mm_add_epi16(xmm1, xmm8); xmm7 = _mm_load_si128(p_cntl2); xmm9 = _mm_load_si128(p_cntl3); xmm0 = _mm_add_epi16(xmm5, xmm0); xmm7 = _mm_and_si128(xmm7, xmm3); xmm9 = _mm_and_si128(xmm9, xmm4); xmm5 = _mm_load_si128(&p_cntl2[1]); xmm11 = _mm_load_si128(&p_cntl3[1]); xmm7 = _mm_add_epi16(xmm7, xmm9); xmm5 = _mm_and_si128(xmm5, xmm3); xmm11 = _mm_and_si128(xmm11, xmm4); xmm0 = _mm_add_epi16(xmm0, xmm7); xmm7 = _mm_load_si128(&p_cntl2[2]); xmm9 = _mm_load_si128(&p_cntl3[2]); xmm5 = _mm_add_epi16(xmm5, xmm11); xmm7 = _mm_and_si128(xmm7, xmm3); xmm9 = _mm_and_si128(xmm9, xmm4); xmm6 = _mm_add_epi16(xmm6, xmm5); xmm5 = _mm_load_si128(&p_cntl2[3]); xmm11 = _mm_load_si128(&p_cntl3[3]); xmm7 = _mm_add_epi16(xmm7, xmm9); xmm5 = _mm_and_si128(xmm5, xmm3); xmm11 = _mm_and_si128(xmm11, xmm4); xmm8 = _mm_add_epi16(xmm8, xmm7); xmm5 = _mm_add_epi16(xmm5, xmm11); _mm_store_si128(p_target, xmm0); _mm_store_si128(&p_target[1], xmm6); xmm10 = _mm_add_epi16(xmm5, xmm10); _mm_store_si128(&p_target[2], xmm8); _mm_store_si128(&p_target[3], xmm10); p_target += 3; } } #endif /*LV_HAVE_SSEs*/ #ifdef LV_HAVE_GENERIC static inline void volk_16i_branch_4_state_8_generic(short* target, short* src0, char** permuters, short* cntl2, short* cntl3, short* scalars) { int i = 0; int bound = 4; for(; i < bound; ++i) { target[i* 8] = src0[((char)permuters[i][0])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8] & scalars[2]) + (cntl3[i * 8] & scalars[3]); target[i* 8 + 1] = src0[((char)permuters[i][1 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 1] & scalars[2]) + (cntl3[i * 8 + 1] & scalars[3]); target[i* 8 + 2] = src0[((char)permuters[i][2 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 2] & scalars[2]) + (cntl3[i * 8 + 2] & scalars[3]); target[i* 8 + 3] = src0[((char)permuters[i][3 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 3] & scalars[2]) + (cntl3[i * 8 + 3] & scalars[3]); target[i* 8 + 4] = src0[((char)permuters[i][4 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 4] & scalars[2]) + (cntl3[i * 8 + 4] & scalars[3]); target[i* 8 + 5] = src0[((char)permuters[i][5 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 5] & scalars[2]) + (cntl3[i * 8 + 5] & scalars[3]); target[i* 8 + 6] = src0[((char)permuters[i][6 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 6] & scalars[2]) + (cntl3[i * 8 + 6] & scalars[3]); target[i* 8 + 7] = src0[((char)permuters[i][7 * 2])/2] + ((i + 1)%2 * scalars[0]) + (((i >> 1)^1) * scalars[1]) + (cntl2[i * 8 + 7] & scalars[2]) + (cntl3[i * 8 + 7] & scalars[3]); } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_16i_branch_4_state_8_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_conjugate_32fc.h0000664000175000017500000000737212207440367023550 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_conjugate_32fc_u_H #define INCLUDED_volk_32fc_conjugate_32fc_u_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Takes the conjugate of a complex vector. \param cVector The vector where the results will be stored \param aVector Vector to be conjugated \param num_points The number of complex values in aVector to be conjugated and stored into cVector */ static inline void volk_32fc_conjugate_32fc_u_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; __m128 conjugator = _mm_setr_ps(0, -0.f, 0, -0.f); for(;number < halfPoints; number++){ x = _mm_loadu_ps((float*)a); // Load the complex data as ar,ai,br,bi x = _mm_xor_ps(x, conjugator); // conjugate register _mm_storeu_ps((float*)c,x); // Store the results back into the C container a += 2; c += 2; } if((num_points % 2) != 0) { *c = lv_conj(*a); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_GENERIC /*! \brief Takes the conjugate of a complex vector. \param cVector The vector where the results will be stored \param aVector Vector to be conjugated \param num_points The number of complex values in aVector to be conjugated and stored into cVector */ static inline void volk_32fc_conjugate_32fc_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = lv_conj(*aPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_conjugate_32fc_u_H */ #ifndef INCLUDED_volk_32fc_conjugate_32fc_a_H #define INCLUDED_volk_32fc_conjugate_32fc_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Takes the conjugate of a complex vector. \param cVector The vector where the results will be stored \param aVector Vector to be conjugated \param num_points The number of complex values in aVector to be conjugated and stored into cVector */ static inline void volk_32fc_conjugate_32fc_a_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; __m128 conjugator = _mm_setr_ps(0, -0.f, 0, -0.f); for(;number < halfPoints; number++){ x = _mm_load_ps((float*)a); // Load the complex data as ar,ai,br,bi x = _mm_xor_ps(x, conjugator); // conjugate register _mm_store_ps((float*)c,x); // Store the results back into the C container a += 2; c += 2; } if((num_points % 2) != 0) { *c = lv_conj(*a); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_GENERIC /*! \brief Takes the conjugate of a complex vector. \param cVector The vector where the results will be stored \param aVector Vector to be conjugated \param num_points The number of complex values in aVector to be conjugated and stored into cVector */ static inline void volk_32fc_conjugate_32fc_a_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = lv_conj(*aPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_conjugate_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32f_power_spectrum_32f.h0000664000175000017500000001030112207440367025323 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32f_power_spectrum_32f_a_H #define INCLUDED_volk_32fc_s32f_power_spectrum_32f_a_H #include #include #include #ifdef LV_HAVE_SSE3 #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief Calculates the log10 power value for each input point \param logPowerOutput The 10.0 * log10(r*r + i*i) for each data point \param complexFFTInput The complex data output from the FFT point \param normalizationFactor This value is divided against all the input values before the power is calculated \param num_points The number of fft data points */ static inline void volk_32fc_s32f_power_spectrum_32f_a_sse3(float* logPowerOutput, const lv_32fc_t* complexFFTInput, const float normalizationFactor, unsigned int num_points){ const float* inputPtr = (const float*)complexFFTInput; float* destPtr = logPowerOutput; uint64_t number = 0; const float iNormalizationFactor = 1.0 / normalizationFactor; #ifdef LV_HAVE_LIB_SIMDMATH __m128 magScalar = _mm_set_ps1(10.0); magScalar = _mm_div_ps(magScalar, logf4(magScalar)); __m128 invNormalizationFactor = _mm_set_ps1(iNormalizationFactor); __m128 power; __m128 input1, input2; const uint64_t quarterPoints = num_points / 4; for(;number < quarterPoints; number++){ // Load the complex values input1 =_mm_load_ps(inputPtr); inputPtr += 4; input2 =_mm_load_ps(inputPtr); inputPtr += 4; // Apply the normalization factor input1 = _mm_mul_ps(input1, invNormalizationFactor); input2 = _mm_mul_ps(input2, invNormalizationFactor); // Multiply each value by itself // (r1*r1), (i1*i1), (r2*r2), (i2*i2) input1 = _mm_mul_ps(input1, input1); // (r3*r3), (i3*i3), (r4*r4), (i4*i4) input2 = _mm_mul_ps(input2, input2); // Horizontal add, to add (r*r) + (i*i) for each complex value // (r1*r1)+(i1*i1), (r2*r2) + (i2*i2), (r3*r3)+(i3*i3), (r4*r4)+(i4*i4) power = _mm_hadd_ps(input1, input2); // Calculate the natural log power power = logf4(power); // Convert to log10 and multiply by 10.0 power = _mm_mul_ps(power, magScalar); // Store the floating point results _mm_store_ps(destPtr, power); destPtr += 4; } number = quarterPoints*4; #endif /* LV_HAVE_LIB_SIMDMATH */ // Calculate the FFT for any remaining points for(; number < num_points; number++){ // Calculate dBm // 50 ohm load assumption // 10 * log10 (v^2 / (2 * 50.0 * .001)) = 10 * log10( v^2 * 10) // 75 ohm load assumption // 10 * log10 (v^2 / (2 * 75.0 * .001)) = 10 * log10( v^2 * 15) const float real = *inputPtr++ * iNormalizationFactor; const float imag = *inputPtr++ * iNormalizationFactor; *destPtr = 10.0*log10f(((real * real) + (imag * imag)) + 1e-20); destPtr++; } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the log10 power value for each input point \param logPowerOutput The 10.0 * log10(r*r + i*i) for each data point \param complexFFTInput The complex data output from the FFT point \param normalizationFactor This value is divided agains all the input values before the power is calculated \param num_points The number of fft data points */ static inline void volk_32fc_s32f_power_spectrum_32f_generic(float* logPowerOutput, const lv_32fc_t* complexFFTInput, const float normalizationFactor, unsigned int num_points){ // Calculate the Power of the complex point const float* inputPtr = (float*)complexFFTInput; float* realFFTDataPointsPtr = logPowerOutput; const float iNormalizationFactor = 1.0 / normalizationFactor; unsigned int point; for(point = 0; point < num_points; point++){ // Calculate dBm // 50 ohm load assumption // 10 * log10 (v^2 / (2 * 50.0 * .001)) = 10 * log10( v^2 * 10) // 75 ohm load assumption // 10 * log10 (v^2 / (2 * 75.0 * .001)) = 10 * log10( v^2 * 15) const float real = *inputPtr++ * iNormalizationFactor; const float imag = *inputPtr++ * iNormalizationFactor; *realFFTDataPointsPtr = 10.0*log10f(((real * real) + (imag * imag)) + 1e-20); realFFTDataPointsPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_s32f_power_spectrum_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_32f_multiply_32fc.h0000664000175000017500000000721512207440367024116 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_32f_multiply_32fc_a_H #define INCLUDED_volk_32fc_32f_multiply_32fc_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Multiplies the input complex vector with the input float vector and store their results in the third vector \param cVector The vector where the results will be stored \param aVector The complex vector to be multiplied \param bVector The vectors containing the float values to be multiplied against each complex value in aVector \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_32f_multiply_32fc_a_sse(lv_32fc_t* cVector, const lv_32fc_t* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; const float* bPtr= bVector; __m128 aVal1, aVal2, bVal, bVal1, bVal2, cVal; for(;number < quarterPoints; number++){ aVal1 = _mm_load_ps((const float*)aPtr); aPtr += 2; aVal2 = _mm_load_ps((const float*)aPtr); aPtr += 2; bVal = _mm_load_ps(bPtr); bPtr += 4; bVal1 = _mm_shuffle_ps(bVal, bVal, _MM_SHUFFLE(1,1,0,0)); bVal2 = _mm_shuffle_ps(bVal, bVal, _MM_SHUFFLE(3,3,2,2)); cVal = _mm_mul_ps(aVal1, bVal1); _mm_store_ps((float*)cPtr,cVal); // Store the results back into the C container cPtr += 2; cVal = _mm_mul_ps(aVal2, bVal2); _mm_store_ps((float*)cPtr,cVal); // Store the results back into the C container cPtr += 2; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr); bPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies the input complex vector with the input lv_32fc_t vector and store their results in the third vector \param cVector The vector where the results will be stored \param aVector The complex vector to be multiplied \param bVector The vectors containing the lv_32fc_t values to be multiplied against each complex value in aVector \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_32f_multiply_32fc_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const float* bVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Multiplies the input complex vector with the input lv_32fc_t vector and store their results in the third vector \param cVector The vector where the results will be stored \param aVector The complex vector to be multiplied \param bVector The vectors containing the lv_32fc_t values to be multiplied against each complex value in aVector \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ extern void volk_32fc_32f_multiply_32fc_a_orc_impl(lv_32fc_t* cVector, const lv_32fc_t* aVector, const float* bVector, unsigned int num_points); static inline void volk_32fc_32f_multiply_32fc_u_orc(lv_32fc_t* cVector, const lv_32fc_t* aVector, const float* bVector, unsigned int num_points){ volk_32fc_32f_multiply_32fc_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_32f_multiply_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_deinterleave_real_64f.h0000664000175000017500000000367212207440367025104 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_deinterleave_real_64f_a_H #define INCLUDED_volk_32fc_deinterleave_real_64f_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Deinterleaves the complex vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_real_64f_a_sse2(double* iBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; double* iBufferPtr = iBuffer; const unsigned int halfPoints = num_points / 2; __m128 cplxValue, fVal; __m128d dVal; for(;number < halfPoints; number++){ cplxValue = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i1i2 format fVal = _mm_shuffle_ps(cplxValue, cplxValue, _MM_SHUFFLE(2,0,2,0)); dVal = _mm_cvtps_pd(fVal); _mm_store_pd(iBufferPtr, dVal); iBufferPtr += 2; } number = halfPoints * 2; for(; number < num_points; number++){ *iBufferPtr++ = (double)*complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex vector into I vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_real_64f_generic(double* iBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; double* iBufferPtr = iBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (double)*complexVectorPtr++; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_deinterleave_real_64f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_32f_fm_detect_32f.h0000664000175000017500000001065712207440367024524 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_32f_fm_detect_32f_a_H #define INCLUDED_volk_32f_s32f_32f_fm_detect_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief performs the FM-detect differentiation on the input vector and stores the results in the output vector. \param outputVector The byte-aligned vector where the results will be stored. \param inputVector The byte-aligned input vector containing phase data (must be on the interval (-bound,bound] ) \param bound The interval that the input phase data is in, which is used to modulo the differentiation \param saveValue A pointer to a float which contains the phase value of the sample before the first input sample. \param num_noints The number of real values in the input vector. */ static inline void volk_32f_s32f_32f_fm_detect_32f_a_sse(float* outputVector, const float* inputVector, const float bound, float* saveValue, unsigned int num_points){ if (num_points < 1) { return; } unsigned int number = 1; unsigned int j = 0; // num_points-1 keeps Fedora 7's gcc from crashing... // num_points won't work. :( const unsigned int quarterPoints = (num_points-1) / 4; float* outPtr = outputVector; const float* inPtr = inputVector; __m128 upperBound = _mm_set_ps1(bound); __m128 lowerBound = _mm_set_ps1(-bound); __m128 next3old1; __m128 next4; __m128 boundAdjust; __m128 posBoundAdjust = _mm_set_ps1(-2*bound); // Subtract when we're above. __m128 negBoundAdjust = _mm_set_ps1(2*bound); // Add when we're below. // Do the first 4 by hand since we're going in from the saveValue: *outPtr = *inPtr - *saveValue; if (*outPtr > bound) *outPtr -= 2*bound; if (*outPtr < -bound) *outPtr += 2*bound; inPtr++; outPtr++; for (j = 1; j < ( (4 < num_points) ? 4 : num_points); j++) { *outPtr = *(inPtr) - *(inPtr-1); if (*outPtr > bound) *outPtr -= 2*bound; if (*outPtr < -bound) *outPtr += 2*bound; inPtr++; outPtr++; } for (; number < quarterPoints; number++) { // Load data next3old1 = _mm_loadu_ps((float*) (inPtr-1)); next4 = _mm_load_ps(inPtr); inPtr += 4; // Subtract and store: next3old1 = _mm_sub_ps(next4, next3old1); // Bound: boundAdjust = _mm_cmpgt_ps(next3old1, upperBound); boundAdjust = _mm_and_ps(boundAdjust, posBoundAdjust); next4 = _mm_cmplt_ps(next3old1, lowerBound); next4 = _mm_and_ps(next4, negBoundAdjust); boundAdjust = _mm_or_ps(next4, boundAdjust); // Make sure we're in the bounding interval: next3old1 = _mm_add_ps(next3old1, boundAdjust); _mm_store_ps(outPtr,next3old1); // Store the results back into the output outPtr += 4; } for (number = (4 > (quarterPoints*4) ? 4 : (4 * quarterPoints)); number < num_points; number++) { *outPtr = *(inPtr) - *(inPtr-1); if (*outPtr > bound) *outPtr -= 2*bound; if (*outPtr < -bound) *outPtr += 2*bound; inPtr++; outPtr++; } *saveValue = inputVector[num_points-1]; } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief performs the FM-detect differentiation on the input vector and stores the results in the output vector. \param outputVector The byte-aligned vector where the results will be stored. \param inputVector The byte-aligned input vector containing phase data (must be on the interval (-bound,bound] ) \param bound The interval that the input phase data is in, which is used to modulo the differentiation \param saveValue A pointer to a float which contains the phase value of the sample before the first input sample. \param num_points The number of real values in the input vector. */ static inline void volk_32f_s32f_32f_fm_detect_32f_generic(float* outputVector, const float* inputVector, const float bound, float* saveValue, unsigned int num_points){ if (num_points < 1) { return; } unsigned int number = 0; float* outPtr = outputVector; const float* inPtr = inputVector; // Do the first 1 by hand since we're going in from the saveValue: *outPtr = *inPtr - *saveValue; if (*outPtr > bound) *outPtr -= 2*bound; if (*outPtr < -bound) *outPtr += 2*bound; inPtr++; outPtr++; for (number = 1; number < num_points; number++) { *outPtr = *(inPtr) - *(inPtr-1); if (*outPtr > bound) *outPtr -= 2*bound; if (*outPtr < -bound) *outPtr += 2*bound; inPtr++; outPtr++; } *saveValue = inputVector[num_points-1]; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_32f_fm_detect_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_magnitude_squared_32f.h0000664000175000017500000002151612207440367025123 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_magnitude_squared_32f_u_H #define INCLUDED_volk_32fc_magnitude_squared_32f_u_H #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude squared of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_squared_32f_u_sse3(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values _mm_storeu_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (val1Real * val1Real) + (val1Imag * val1Imag); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude squared of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_squared_32f_u_sse(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, iValue, qValue, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_loadu_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); iValue = _mm_mul_ps(iValue, iValue); // Square the I values qValue = _mm_mul_ps(qValue, qValue); // Square the Q Values result = _mm_add_ps(iValue, qValue); // Add the I2 and Q2 values _mm_storeu_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (val1Real * val1Real) + (val1Imag * val1Imag); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude squared of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_squared_32f_generic(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (real*real) + (imag*imag); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_magnitude_32f_u_H */ #ifndef INCLUDED_volk_32fc_magnitude_squared_32f_a_H #define INCLUDED_volk_32fc_magnitude_squared_32f_a_H #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude squared of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_squared_32f_a_sse3(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values _mm_store_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (val1Real * val1Real) + (val1Imag * val1Imag); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude squared of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_squared_32f_a_sse(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 cplxValue1, cplxValue2, iValue, qValue, result; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); iValue = _mm_mul_ps(iValue, iValue); // Square the I values qValue = _mm_mul_ps(qValue, qValue); // Square the Q Values result = _mm_add_ps(iValue, qValue); // Add the I2 and Q2 values _mm_store_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (val1Real * val1Real) + (val1Imag * val1Imag); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude squared of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_magnitude_squared_32f_a_generic(float* magnitudeVector, const lv_32fc_t* complexVector, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (real*real) + (imag*imag); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_magnitude_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_deinterleave_real_16i.h0000664000175000017500000000422312207440367025023 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8ic_deinterleave_real_16i_a_H #define INCLUDED_volk_8ic_deinterleave_real_16i_a_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Deinterleaves the complex 8 bit vector into I 16 bit vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_deinterleave_real_16i_a_sse4_1(int16_t* iBuffer, const lv_8sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (int8_t*)complexVector; int16_t* iBufferPtr = iBuffer; __m128i moveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 14, 12, 10, 8, 6, 4, 2, 0); __m128i complexVal, outputVal; unsigned int eighthPoints = num_points / 8; for(number = 0; number < eighthPoints; number++){ complexVal = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal = _mm_shuffle_epi8(complexVal, moveMask); outputVal = _mm_cvtepi8_epi16(complexVal); outputVal = _mm_slli_epi16(outputVal, 7); _mm_store_si128((__m128i*)iBufferPtr, outputVal); iBufferPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = ((int16_t)*complexVectorPtr++) * 128; complexVectorPtr++; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 8 bit vector into I 16 bit vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_deinterleave_real_16i_generic(int16_t* iBuffer, const lv_8sc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (const int8_t*)complexVector; int16_t* iBufferPtr = iBuffer; for(number = 0; number < num_points; number++){ *iBufferPtr++ = ((int16_t)(*complexVectorPtr++)) * 128; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_8ic_deinterleave_real_16i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_s32f_magnitude_32f.h0000664000175000017500000001640112207440367024236 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_s32f_magnitude_32f_a_H #define INCLUDED_volk_16ic_s32f_magnitude_32f_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_16ic_s32f_magnitude_32f_a_sse3(float* magnitudeVector, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const int16_t* complexVectorPtr = (const int16_t*)complexVector; float* magnitudeVectorPtr = magnitudeVector; __m128 invScalar = _mm_set_ps1(1.0/scalar); __m128 cplxValue1, cplxValue2, result; __VOLK_ATTR_ALIGNED(16) float inputFloatBuffer[8]; for(;number < quarterPoints; number++){ inputFloatBuffer[0] = (float)(complexVectorPtr[0]); inputFloatBuffer[1] = (float)(complexVectorPtr[1]); inputFloatBuffer[2] = (float)(complexVectorPtr[2]); inputFloatBuffer[3] = (float)(complexVectorPtr[3]); inputFloatBuffer[4] = (float)(complexVectorPtr[4]); inputFloatBuffer[5] = (float)(complexVectorPtr[5]); inputFloatBuffer[6] = (float)(complexVectorPtr[6]); inputFloatBuffer[7] = (float)(complexVectorPtr[7]); cplxValue1 = _mm_load_ps(&inputFloatBuffer[0]); cplxValue2 = _mm_load_ps(&inputFloatBuffer[4]); complexVectorPtr += 8; cplxValue1 = _mm_mul_ps(cplxValue1, invScalar); cplxValue2 = _mm_mul_ps(cplxValue2, invScalar); cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); // Square root the values _mm_store_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; magnitudeVectorPtr = &magnitudeVector[number]; complexVectorPtr = (const int16_t*)&complexVector[number]; for(; number < num_points; number++){ float val1Real = (float)(*complexVectorPtr++) / scalar; float val1Imag = (float)(*complexVectorPtr++) / scalar; *magnitudeVectorPtr++ = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_16ic_s32f_magnitude_32f_a_sse(float* magnitudeVector, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const int16_t* complexVectorPtr = (const int16_t*)complexVector; float* magnitudeVectorPtr = magnitudeVector; const float iScalar = 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); __m128 cplxValue1, cplxValue2, result, re, im; __VOLK_ATTR_ALIGNED(16) float inputFloatBuffer[8]; for(;number < quarterPoints; number++){ inputFloatBuffer[0] = (float)(complexVectorPtr[0]); inputFloatBuffer[1] = (float)(complexVectorPtr[1]); inputFloatBuffer[2] = (float)(complexVectorPtr[2]); inputFloatBuffer[3] = (float)(complexVectorPtr[3]); inputFloatBuffer[4] = (float)(complexVectorPtr[4]); inputFloatBuffer[5] = (float)(complexVectorPtr[5]); inputFloatBuffer[6] = (float)(complexVectorPtr[6]); inputFloatBuffer[7] = (float)(complexVectorPtr[7]); cplxValue1 = _mm_load_ps(&inputFloatBuffer[0]); cplxValue2 = _mm_load_ps(&inputFloatBuffer[4]); re = _mm_shuffle_ps(cplxValue1, cplxValue2, 0x88); im = _mm_shuffle_ps(cplxValue1, cplxValue2, 0xdd); complexVectorPtr += 8; cplxValue1 = _mm_mul_ps(re, invScalar); cplxValue2 = _mm_mul_ps(im, invScalar); cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_add_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); // Square root the values _mm_store_ps(magnitudeVectorPtr, result); magnitudeVectorPtr += 4; } number = quarterPoints * 4; magnitudeVectorPtr = &magnitudeVector[number]; complexVectorPtr = (const int16_t*)&complexVector[number]; for(; number < num_points; number++){ float val1Real = (float)(*complexVectorPtr++) * iScalar; float val1Imag = (float)(*complexVectorPtr++) * iScalar; *magnitudeVectorPtr++ = sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_16ic_s32f_magnitude_32f_generic(float* magnitudeVector, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ const int16_t* complexVectorPtr = (const int16_t*)complexVector; float* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; const float invScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ float real = ( (float) (*complexVectorPtr++)) * invScalar; float imag = ( (float) (*complexVectorPtr++)) * invScalar; *magnitudeVectorPtr++ = sqrtf((real*real) + (imag*imag)); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC_DISABLED /*! \brief Calculates the magnitude of the complexVector and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param magnitudeVector The vector containing the real output values \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ extern void volk_16ic_s32f_magnitude_32f_a_orc_impl(float* magnitudeVector, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points); static inline void volk_16ic_s32f_magnitude_32f_u_orc(float* magnitudeVector, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ volk_16ic_s32f_magnitude_32f_a_orc_impl(magnitudeVector, complexVector, scalar, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_16ic_s32f_magnitude_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_sqrt_32f.h0000664000175000017500000000460712207440367022252 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_sqrt_32f_a_H #define INCLUDED_volk_32f_sqrt_32f_a_H #include #include #include #ifdef LV_HAVE_SSE #include /*! \brief Sqrts the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be sqrted \param num_points The number of values in aVector and bVector to be sqrted together and stored into cVector */ static inline void volk_32f_sqrt_32f_a_sse(float* cVector, const float* aVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; __m128 aVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); cVal = _mm_sqrt_ps(aVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = sqrtf(*aPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Sqrts the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be sqrted \param num_points The number of values in aVector and bVector to be sqrted together and stored into cVector */ static inline void volk_32f_sqrt_32f_generic(float* cVector, const float* aVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = sqrtf(*aPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC extern void volk_32f_sqrt_32f_a_orc_impl(float *, const float*, unsigned int); /*! \brief Sqrts the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be sqrted \param num_points The number of values in aVector and bVector to be sqrted together and stored into cVector */ static inline void volk_32f_sqrt_32f_u_orc(float* cVector, const float* aVector, unsigned int num_points){ volk_32f_sqrt_32f_a_orc_impl(cVector, aVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_sqrt_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_interleave_32fc.h0000664000175000017500000000466212207440367024174 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_interleave_32fc_a_H #define INCLUDED_volk_32f_x2_interleave_32fc_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Interleaves the I & Q vector data into the complex vector \param iBuffer The I buffer data to be interleaved \param qBuffer The Q buffer data to be interleaved \param complexVector The complex output vector \param num_points The number of complex data values to be interleaved */ static inline void volk_32f_x2_interleave_32fc_a_sse(lv_32fc_t* complexVector, const float* iBuffer, const float* qBuffer, unsigned int num_points){ unsigned int number = 0; float* complexVectorPtr = (float*)complexVector; const float* iBufferPtr = iBuffer; const float* qBufferPtr = qBuffer; const uint64_t quarterPoints = num_points / 4; __m128 iValue, qValue, cplxValue; for(;number < quarterPoints; number++){ iValue = _mm_load_ps(iBufferPtr); qValue = _mm_load_ps(qBufferPtr); // Interleaves the lower two values in the i and q variables into one buffer cplxValue = _mm_unpacklo_ps(iValue, qValue); _mm_store_ps(complexVectorPtr, cplxValue); complexVectorPtr += 4; // Interleaves the upper two values in the i and q variables into one buffer cplxValue = _mm_unpackhi_ps(iValue, qValue); _mm_store_ps(complexVectorPtr, cplxValue); complexVectorPtr += 4; iBufferPtr += 4; qBufferPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ *complexVectorPtr++ = *iBufferPtr++; *complexVectorPtr++ = *qBufferPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Interleaves the I & Q vector data into the complex vector. \param iBuffer The I buffer data to be interleaved \param qBuffer The Q buffer data to be interleaved \param complexVector The complex output vector \param num_points The number of complex data values to be interleaved */ static inline void volk_32f_x2_interleave_32fc_generic(lv_32fc_t* complexVector, const float* iBuffer, const float* qBuffer, unsigned int num_points){ float* complexVectorPtr = (float*)complexVector; const float* iBufferPtr = iBuffer; const float* qBufferPtr = qBuffer; unsigned int number; for(number = 0; number < num_points; number++){ *complexVectorPtr++ = *iBufferPtr++; *complexVectorPtr++ = *qBufferPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_x2_interleave_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_index_max_16u.h0000664000175000017500000000775112207440367023261 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_index_max_16u_a_H #define INCLUDED_volk_32f_index_max_16u_a_H #include #include #include #include #ifdef LV_HAVE_SSE4_1 #include static inline void volk_32f_index_max_16u_a_sse4_1(unsigned int* target, const float* src0, unsigned int num_points) { if(num_points > 0){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* inputPtr = (float*)src0; __m128 indexIncrementValues = _mm_set1_ps(4); __m128 currentIndexes = _mm_set_ps(-1,-2,-3,-4); float max = src0[0]; float index = 0; __m128 maxValues = _mm_set1_ps(max); __m128 maxValuesIndex = _mm_setzero_ps(); __m128 compareResults; __m128 currentValues; __VOLK_ATTR_ALIGNED(16) float maxValuesBuffer[4]; __VOLK_ATTR_ALIGNED(16) float maxIndexesBuffer[4]; for(;number < quarterPoints; number++){ currentValues = _mm_load_ps(inputPtr); inputPtr += 4; currentIndexes = _mm_add_ps(currentIndexes, indexIncrementValues); compareResults = _mm_cmpgt_ps(maxValues, currentValues); maxValuesIndex = _mm_blendv_ps(currentIndexes, maxValuesIndex, compareResults); maxValues = _mm_blendv_ps(currentValues, maxValues, compareResults); } // Calculate the largest value from the remaining 4 points _mm_store_ps(maxValuesBuffer, maxValues); _mm_store_ps(maxIndexesBuffer, maxValuesIndex); for(number = 0; number < 4; number++){ if(maxValuesBuffer[number] > max){ index = maxIndexesBuffer[number]; max = maxValuesBuffer[number]; } } number = quarterPoints * 4; for(;number < num_points; number++){ if(src0[number] > max){ index = number; max = src0[number]; } } target[0] = (unsigned int)index; } } #endif /*LV_HAVE_SSE4_1*/ #ifdef LV_HAVE_SSE #include static inline void volk_32f_index_max_16u_a_sse(unsigned int* target, const float* src0, unsigned int num_points) { if(num_points > 0){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* inputPtr = (float*)src0; __m128 indexIncrementValues = _mm_set1_ps(4); __m128 currentIndexes = _mm_set_ps(-1,-2,-3,-4); float max = src0[0]; float index = 0; __m128 maxValues = _mm_set1_ps(max); __m128 maxValuesIndex = _mm_setzero_ps(); __m128 compareResults; __m128 currentValues; __VOLK_ATTR_ALIGNED(16) float maxValuesBuffer[4]; __VOLK_ATTR_ALIGNED(16) float maxIndexesBuffer[4]; for(;number < quarterPoints; number++){ currentValues = _mm_load_ps(inputPtr); inputPtr += 4; currentIndexes = _mm_add_ps(currentIndexes, indexIncrementValues); compareResults = _mm_cmpgt_ps(maxValues, currentValues); maxValuesIndex = _mm_or_ps(_mm_and_ps(compareResults, maxValuesIndex) , _mm_andnot_ps(compareResults, currentIndexes)); maxValues = _mm_or_ps(_mm_and_ps(compareResults, maxValues) , _mm_andnot_ps(compareResults, currentValues)); } // Calculate the largest value from the remaining 4 points _mm_store_ps(maxValuesBuffer, maxValues); _mm_store_ps(maxIndexesBuffer, maxValuesIndex); for(number = 0; number < 4; number++){ if(maxValuesBuffer[number] > max){ index = maxIndexesBuffer[number]; max = maxValuesBuffer[number]; } } number = quarterPoints * 4; for(;number < num_points; number++){ if(src0[number] > max){ index = number; max = src0[number]; } } target[0] = (unsigned int)index; } } #endif /*LV_HAVE_SSE*/ #ifdef LV_HAVE_GENERIC static inline void volk_32f_index_max_16u_generic(unsigned int* target, const float* src0, unsigned int num_points) { if(num_points > 0){ float max = src0[0]; unsigned int index = 0; unsigned int i = 1; for(; i < num_points; ++i) { if(src0[i] > max){ index = i; max = src0[i]; } } target[0] = index; } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_32f_index_max_16u_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_deinterleave_32f_x2.h0000664000175000017500000000453612207440367024505 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_deinterleave_32f_x2_a_H #define INCLUDED_volk_32fc_deinterleave_32f_x2_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex vector into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_32f_x2_a_sse(float* iBuffer, float* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128 cplxValue1, cplxValue2, iValue, qValue; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); _mm_store_ps(iBufferPtr, iValue); _mm_store_ps(qBufferPtr, qValue); iBufferPtr += 4; qBufferPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex vector into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_32f_x2_generic(float* iBuffer, float* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; unsigned int number; for(number = 0; number < num_points; number++){ *iBufferPtr++ = *complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_deinterleave_32f_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_permute_and_scalar_add.h0000664000175000017500000000677112207440367025260 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_permute_and_scalar_add_a_H #define INCLUDED_volk_16i_permute_and_scalar_add_a_H #include #include #ifdef LV_HAVE_SSE2 #include #include static inline void volk_16i_permute_and_scalar_add_a_sse2(short* target, short* src0, short* permute_indexes, short* cntl0, short* cntl1, short* cntl2, short* cntl3, short* scalars, unsigned int num_points) { const unsigned int num_bytes = num_points*2; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; __m128i *p_target, *p_cntl0, *p_cntl1, *p_cntl2, *p_cntl3, *p_scalars; short* p_permute_indexes = permute_indexes; p_target = (__m128i*)target; p_cntl0 = (__m128i*)cntl0; p_cntl1 = (__m128i*)cntl1; p_cntl2 = (__m128i*)cntl2; p_cntl3 = (__m128i*)cntl3; p_scalars = (__m128i*)scalars; int i = 0; int bound = (num_bytes >> 4); int leftovers = (num_bytes >> 1) & 7; xmm0 = _mm_load_si128(p_scalars); xmm1 = _mm_shufflelo_epi16(xmm0, 0); xmm2 = _mm_shufflelo_epi16(xmm0, 0x55); xmm3 = _mm_shufflelo_epi16(xmm0, 0xaa); xmm4 = _mm_shufflelo_epi16(xmm0, 0xff); xmm1 = _mm_shuffle_epi32(xmm1, 0x00); xmm2 = _mm_shuffle_epi32(xmm2, 0x00); xmm3 = _mm_shuffle_epi32(xmm3, 0x00); xmm4 = _mm_shuffle_epi32(xmm4, 0x00); for(; i < bound; ++i) { xmm0 = _mm_setzero_si128(); xmm5 = _mm_setzero_si128(); xmm6 = _mm_setzero_si128(); xmm7 = _mm_setzero_si128(); xmm0 = _mm_insert_epi16(xmm0, src0[p_permute_indexes[0]], 0); xmm5 = _mm_insert_epi16(xmm5, src0[p_permute_indexes[1]], 1); xmm6 = _mm_insert_epi16(xmm6, src0[p_permute_indexes[2]], 2); xmm7 = _mm_insert_epi16(xmm7, src0[p_permute_indexes[3]], 3); xmm0 = _mm_insert_epi16(xmm0, src0[p_permute_indexes[4]], 4); xmm5 = _mm_insert_epi16(xmm5, src0[p_permute_indexes[5]], 5); xmm6 = _mm_insert_epi16(xmm6, src0[p_permute_indexes[6]], 6); xmm7 = _mm_insert_epi16(xmm7, src0[p_permute_indexes[7]], 7); xmm0 = _mm_add_epi16(xmm0, xmm5); xmm6 = _mm_add_epi16(xmm6, xmm7); p_permute_indexes += 8; xmm0 = _mm_add_epi16(xmm0, xmm6); xmm5 = _mm_load_si128(p_cntl0); xmm6 = _mm_load_si128(p_cntl1); xmm7 = _mm_load_si128(p_cntl2); xmm5 = _mm_and_si128(xmm5, xmm1); xmm6 = _mm_and_si128(xmm6, xmm2); xmm7 = _mm_and_si128(xmm7, xmm3); xmm0 = _mm_add_epi16(xmm0, xmm5); xmm5 = _mm_load_si128(p_cntl3); xmm6 = _mm_add_epi16(xmm6, xmm7); p_cntl0 += 1; xmm5 = _mm_and_si128(xmm5, xmm4); xmm0 = _mm_add_epi16(xmm0, xmm6); p_cntl1 += 1; p_cntl2 += 1; xmm0 = _mm_add_epi16(xmm0, xmm5); p_cntl3 += 1; _mm_store_si128(p_target, xmm0); p_target += 1; } for(i = bound * 8; i < (bound * 8) + leftovers; ++i) { target[i] = src0[permute_indexes[i]] + (cntl0[i] & scalars[0]) + (cntl1[i] & scalars[1]) + (cntl2[i] & scalars[2]) + (cntl3[i] & scalars[3]); } } #endif /*LV_HAVE_SSEs*/ #ifdef LV_HAVE_GENERIC static inline void volk_16i_permute_and_scalar_add_generic(short* target, short* src0, short* permute_indexes, short* cntl0, short* cntl1, short* cntl2, short* cntl3, short* scalars, unsigned int num_points) { const unsigned int num_bytes = num_points*2; int i = 0; int bound = num_bytes >> 1; for(i = 0; i < bound; ++i) { target[i] = src0[permute_indexes[i]] + (cntl0[i] & scalars[0]) + (cntl1[i] & scalars[1]) + (cntl2[i] & scalars[2]) + (cntl3[i] & scalars[3]); } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_16i_permute_and_scalar_add_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_s32f_convert_32f.h0000664000175000017500000002046512207440367023603 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_s32f_convert_32f_u_H #define INCLUDED_volk_16i_s32f_convert_32f_u_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 16 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_16i_s32f_convert_32f_u_sse4_1(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; float* outputVectorPtr = outputVector; __m128 invScalar = _mm_set_ps1(1.0/scalar); int16_t* inputPtr = (int16_t*)inputVector; __m128i inputVal; __m128i inputVal2; __m128 ret; for(;number < eighthPoints; number++){ // Load the 8 values inputVal = _mm_loadu_si128((__m128i*)inputPtr); // Shift the input data to the right by 64 bits ( 8 bytes ) inputVal2 = _mm_srli_si128(inputVal, 8); // Convert the lower 4 values into 32 bit words inputVal = _mm_cvtepi16_epi32(inputVal); inputVal2 = _mm_cvtepi16_epi32(inputVal2); ret = _mm_cvtepi32_ps(inputVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; ret = _mm_cvtepi32_ps(inputVal2); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ outputVector[number] =((float)(inputVector[number])) / scalar; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 16 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_16i_s32f_convert_32f_u_sse(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* outputVectorPtr = outputVector; __m128 invScalar = _mm_set_ps1(1.0/scalar); int16_t* inputPtr = (int16_t*)inputVector; __m128 ret; for(;number < quarterPoints; number++){ ret = _mm_set_ps((float)(inputPtr[3]), (float)(inputPtr[2]), (float)(inputPtr[1]), (float)(inputPtr[0])); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); inputPtr += 4; outputVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] = (float)(inputVector[number]) / scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 16 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_16i_s32f_convert_32f_generic(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){ float* outputVectorPtr = outputVector; const int16_t* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)) / scalar; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16i_s32f_convert_32f_u_H */ #ifndef INCLUDED_volk_16i_s32f_convert_32f_a_H #define INCLUDED_volk_16i_s32f_convert_32f_a_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 16 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_16i_s32f_convert_32f_a_sse4_1(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; float* outputVectorPtr = outputVector; __m128 invScalar = _mm_set_ps1(1.0/scalar); int16_t* inputPtr = (int16_t*)inputVector; __m128i inputVal; __m128i inputVal2; __m128 ret; for(;number < eighthPoints; number++){ // Load the 8 values inputVal = _mm_loadu_si128((__m128i*)inputPtr); // Shift the input data to the right by 64 bits ( 8 bytes ) inputVal2 = _mm_srli_si128(inputVal, 8); // Convert the lower 4 values into 32 bit words inputVal = _mm_cvtepi16_epi32(inputVal); inputVal2 = _mm_cvtepi16_epi32(inputVal2); ret = _mm_cvtepi32_ps(inputVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; ret = _mm_cvtepi32_ps(inputVal2); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputPtr += 8; } number = eighthPoints * 8; for(; number < num_points; number++){ outputVector[number] =((float)(inputVector[number])) / scalar; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 16 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_16i_s32f_convert_32f_a_sse(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* outputVectorPtr = outputVector; __m128 invScalar = _mm_set_ps1(1.0/scalar); int16_t* inputPtr = (int16_t*)inputVector; __m128 ret; for(;number < quarterPoints; number++){ ret = _mm_set_ps((float)(inputPtr[3]), (float)(inputPtr[2]), (float)(inputPtr[1]), (float)(inputPtr[0])); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); inputPtr += 4; outputVectorPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] = (float)(inputVector[number]) / scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 16 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_16i_s32f_convert_32f_a_generic(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){ float* outputVectorPtr = outputVector; const int16_t* inputVectorPtr = inputVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)) / scalar; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_16i_s32f_convert_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_multiply_32f.h0000664000175000017500000001652012207440367023546 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_multiply_32f_u_H #define INCLUDED_volk_32f_x2_multiply_32f_u_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Multiplys the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_x2_multiply_32f_u_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_loadu_ps(aPtr); bVal = _mm_loadu_ps(bPtr); cVal = _mm_mul_ps(aVal, bVal); _mm_storeu_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_AVX #include /*! \brief Multiplies the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_x2_multiply_32f_u_avx(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m256 aVal, bVal, cVal; for(;number < eighthPoints; number++){ aVal = _mm256_loadu_ps(aPtr); bVal = _mm256_loadu_ps(bPtr); cVal = _mm256_mul_ps(aVal, bVal); _mm256_storeu_ps(cPtr,cVal); // Store the results back into the C container aPtr += 8; bPtr += 8; cPtr += 8; } number = eighthPoints * 8; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_AVX */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplys the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_x2_multiply_32f_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_x2_multiply_32f_u_H */ #ifndef INCLUDED_volk_32f_x2_multiply_32f_a_H #define INCLUDED_volk_32f_x2_multiply_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Multiplys the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_x2_multiply_32f_a_sse(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m128 aVal, bVal, cVal; for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); bVal = _mm_load_ps(bPtr); cVal = _mm_mul_ps(aVal, bVal); _mm_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 4; bPtr += 4; cPtr += 4; } number = quarterPoints * 4; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_AVX #include /*! \brief Multiplies the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_x2_multiply_32f_a_avx(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; __m256 aVal, bVal, cVal; for(;number < eighthPoints; number++){ aVal = _mm256_load_ps(aPtr); bVal = _mm256_load_ps(bPtr); cVal = _mm256_mul_ps(aVal, bVal); _mm256_store_ps(cPtr,cVal); // Store the results back into the C container aPtr += 8; bPtr += 8; cPtr += 8; } number = eighthPoints * 8; for(;number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_AVX */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplys the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32f_x2_multiply_32f_a_generic(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ float* cPtr = cVector; const float* aPtr = aVector; const float* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Multiplys the two input vectors and store their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of values in aVector and bVector to be multiplied together and stored into cVector */ extern void volk_32f_x2_multiply_32f_a_orc_impl(float* cVector, const float* aVector, const float* bVector, unsigned int num_points); static inline void volk_32f_x2_multiply_32f_u_orc(float* cVector, const float* aVector, const float* bVector, unsigned int num_points){ volk_32f_x2_multiply_32f_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32f_x2_multiply_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_deinterleave_imag_32f.h0000664000175000017500000000374712207440367025074 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_deinterleave_imag_32f_a_H #define INCLUDED_volk_32fc_deinterleave_imag_32f_a_H #include #include #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex vector into Q vector data \param complexVector The complex input vector \param qBuffer The Q buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_imag_32f_a_sse(float* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (const float*)complexVector; float* qBufferPtr = qBuffer; __m128 cplxValue1, cplxValue2, iValue; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in q1q2q3q4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); _mm_store_ps(qBufferPtr, iValue); qBufferPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex vector into Q vector data \param complexVector The complex input vector \param qBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_deinterleave_imag_32f_generic(float* qBuffer, const lv_32fc_t* complexVector, unsigned int num_points){ unsigned int number = 0; const float* complexVectorPtr = (float*)complexVector; float* qBufferPtr = qBuffer; for(number = 0; number < num_points; number++){ complexVectorPtr++; *qBufferPtr++ = *complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_deinterleave_imag_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_s32f_deinterleave_real_32f.h0000664000175000017500000001041212207440367025650 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8ic_s32f_deinterleave_real_32f_a_H #define INCLUDED_volk_8ic_s32f_deinterleave_real_32f_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Deinterleaves the complex 8 bit vector into I float vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_s32f_deinterleave_real_32f_a_sse4_1(float* iBuffer, const lv_8sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; __m128 iFloatValue; const float iScalar= 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); __m128i complexVal, iIntVal; int8_t* complexVectorPtr = (int8_t*)complexVector; __m128i moveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 14, 12, 10, 8, 6, 4, 2, 0); for(;number < eighthPoints; number++){ complexVal = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; complexVal = _mm_shuffle_epi8(complexVal, moveMask); iIntVal = _mm_cvtepi8_epi32(complexVal); iFloatValue = _mm_cvtepi32_ps(iIntVal); iFloatValue = _mm_mul_ps(iFloatValue, invScalar); _mm_store_ps(iBufferPtr, iFloatValue); iBufferPtr += 4; complexVal = _mm_srli_si128(complexVal, 4); iIntVal = _mm_cvtepi8_epi32(complexVal); iFloatValue = _mm_cvtepi32_ps(iIntVal); iFloatValue = _mm_mul_ps(iFloatValue, invScalar); _mm_store_ps(iBufferPtr, iFloatValue); iBufferPtr += 4; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++) * iScalar; complexVectorPtr++; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex 8 bit vector into I float vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_s32f_deinterleave_real_32f_a_sse(float* iBuffer, const lv_8sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128 iValue; const float iScalar= 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); int8_t* complexVectorPtr = (int8_t*)complexVector; __VOLK_ATTR_ALIGNED(16) float floatBuffer[4]; for(;number < quarterPoints; number++){ floatBuffer[0] = (float)(*complexVectorPtr); complexVectorPtr += 2; floatBuffer[1] = (float)(*complexVectorPtr); complexVectorPtr += 2; floatBuffer[2] = (float)(*complexVectorPtr); complexVectorPtr += 2; floatBuffer[3] = (float)(*complexVectorPtr); complexVectorPtr += 2; iValue = _mm_load_ps(floatBuffer); iValue = _mm_mul_ps(iValue, invScalar); _mm_store_ps(iBufferPtr, iValue); iBufferPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++) * iScalar; complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 8 bit vector into I float vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_s32f_deinterleave_real_32f_generic(float* iBuffer, const lv_8sc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const int8_t* complexVectorPtr = (const int8_t*)complexVector; float* iBufferPtr = iBuffer; const float invScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *iBufferPtr++ = ((float)(*complexVectorPtr++)) * invScalar; complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_8ic_s32f_deinterleave_real_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32i_s32f_convert_32f.h0000664000175000017500000001172412207440367023577 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32i_s32f_convert_32f_u_H #define INCLUDED_volk_32i_s32f_convert_32f_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the input 32 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 32 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_32i_s32f_convert_32f_u_sse2(float* outputVector, const int32_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* outputVectorPtr = outputVector; const float iScalar = 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); int32_t* inputPtr = (int32_t*)inputVector; __m128i inputVal; __m128 ret; for(;number < quarterPoints; number++){ // Load the 4 values inputVal = _mm_loadu_si128((__m128i*)inputPtr); ret = _mm_cvtepi32_ps(inputVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] =((float)(inputVector[number])) * iScalar; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 32 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 32 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_32i_s32f_convert_32f_generic(float* outputVector, const int32_t* inputVector, const float scalar, unsigned int num_points){ float* outputVectorPtr = outputVector; const int32_t* inputVectorPtr = inputVector; unsigned int number = 0; const float iScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)) * iScalar; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32i_s32f_convert_32f_u_H */ #ifndef INCLUDED_volk_32i_s32f_convert_32f_a_H #define INCLUDED_volk_32i_s32f_convert_32f_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Converts the input 32 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 32 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_32i_s32f_convert_32f_a_sse2(float* outputVector, const int32_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; float* outputVectorPtr = outputVector; const float iScalar = 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); int32_t* inputPtr = (int32_t*)inputVector; __m128i inputVal; __m128 ret; for(;number < quarterPoints; number++){ // Load the 4 values inputVal = _mm_load_si128((__m128i*)inputPtr); ret = _mm_cvtepi32_ps(inputVal); ret = _mm_mul_ps(ret, invScalar); _mm_store_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputPtr += 4; } number = quarterPoints * 4; for(; number < num_points; number++){ outputVector[number] =((float)(inputVector[number])) * iScalar; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 32 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 32 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_32i_s32f_convert_32f_a_generic(float* outputVector, const int32_t* inputVector, const float scalar, unsigned int num_points){ float* outputVectorPtr = outputVector; const int32_t* inputVectorPtr = inputVector; unsigned int number = 0; const float iScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)) * iScalar; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32i_s32f_convert_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_convert_8i.h0000664000175000017500000002541312207440367023522 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_convert_8i_u_H #define INCLUDED_volk_32f_s32f_convert_8i_u_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 8 bit integer value \param inputVector The floating point input data buffer \param outputVector The 8 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_8i_u_sse2(int8_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; const float* inputVectorPtr = (const float*)inputVector; int8_t* outputVectorPtr = outputVector; float min_val = -128; float max_val = 127; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 inputVal1, inputVal2, inputVal3, inputVal4; __m128i intInputVal1, intInputVal2, intInputVal3, intInputVal4; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); for(;number < sixteenthPoints; number++){ inputVal1 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; inputVal2 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; inputVal3 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; inputVal4 = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; inputVal1 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); inputVal2 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal2, vScalar), vmax_val), vmin_val); inputVal3 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal3, vScalar), vmax_val), vmin_val); inputVal4 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal4, vScalar), vmax_val), vmin_val); intInputVal1 = _mm_cvtps_epi32(inputVal1); intInputVal2 = _mm_cvtps_epi32(inputVal2); intInputVal3 = _mm_cvtps_epi32(inputVal3); intInputVal4 = _mm_cvtps_epi32(inputVal4); intInputVal1 = _mm_packs_epi32(intInputVal1, intInputVal2); intInputVal3 = _mm_packs_epi32(intInputVal3, intInputVal4); intInputVal1 = _mm_packs_epi16(intInputVal1, intInputVal3); _mm_storeu_si128((__m128i*)outputVectorPtr, intInputVal1); outputVectorPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int16_t)(r); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 8 bit integer value \param inputVector The floating point input data buffer \param outputVector The 8 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_8i_u_sse(int8_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; int8_t* outputVectorPtr = outputVector; float min_val = -128; float max_val = 127; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 ret; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ ret = _mm_loadu_ps(inputVectorPtr); inputVectorPtr += 4; ret = _mm_max_ps(_mm_min_ps(_mm_mul_ps(ret, vScalar), vmax_val), vmin_val); _mm_store_ps(outputFloatBuffer, ret); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[0]); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[1]); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[2]); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[3]); } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int16_t)(r); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 8 bit integer value \param inputVector The floating point input data buffer \param outputVector The 8 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted \note Input buffer does NOT need to be properly aligned */ static inline void volk_32f_s32f_convert_8i_generic(int8_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ int8_t* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; float min_val = -128; float max_val = 127; float r; for(number = 0; number < num_points; number++){ r = *inputVectorPtr++ * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; *outputVectorPtr++ = (int16_t)(r); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_convert_8i_u_H */ #ifndef INCLUDED_volk_32f_s32f_convert_8i_a_H #define INCLUDED_volk_32f_s32f_convert_8i_a_H #include #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 8 bit integer value \param inputVector The floating point input data buffer \param outputVector The 8 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_8i_a_sse2(int8_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; const float* inputVectorPtr = (const float*)inputVector; int8_t* outputVectorPtr = outputVector; float min_val = -128; float max_val = 127; float r; __m128 vScalar = _mm_set_ps1(scalar); __m128 inputVal1, inputVal2, inputVal3, inputVal4; __m128i intInputVal1, intInputVal2, intInputVal3, intInputVal4; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); for(;number < sixteenthPoints; number++){ inputVal1 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; inputVal2 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; inputVal3 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; inputVal4 = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; inputVal1 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal1, vScalar), vmax_val), vmin_val); inputVal2 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal2, vScalar), vmax_val), vmin_val); inputVal3 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal3, vScalar), vmax_val), vmin_val); inputVal4 = _mm_max_ps(_mm_min_ps(_mm_mul_ps(inputVal4, vScalar), vmax_val), vmin_val); intInputVal1 = _mm_cvtps_epi32(inputVal1); intInputVal2 = _mm_cvtps_epi32(inputVal2); intInputVal3 = _mm_cvtps_epi32(inputVal3); intInputVal4 = _mm_cvtps_epi32(inputVal4); intInputVal1 = _mm_packs_epi32(intInputVal1, intInputVal2); intInputVal3 = _mm_packs_epi32(intInputVal3, intInputVal4); intInputVal1 = _mm_packs_epi16(intInputVal1, intInputVal3); _mm_store_si128((__m128i*)outputVectorPtr, intInputVal1); outputVectorPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int8_t)(r); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_SSE #include /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 8 bit integer value \param inputVector The floating point input data buffer \param outputVector The 8 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_8i_a_sse(int8_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* inputVectorPtr = (const float*)inputVector; float min_val = -128; float max_val = 127; float r; int8_t* outputVectorPtr = outputVector; __m128 vScalar = _mm_set_ps1(scalar); __m128 ret; __m128 vmin_val = _mm_set_ps1(min_val); __m128 vmax_val = _mm_set_ps1(max_val); __VOLK_ATTR_ALIGNED(16) float outputFloatBuffer[4]; for(;number < quarterPoints; number++){ ret = _mm_load_ps(inputVectorPtr); inputVectorPtr += 4; ret = _mm_max_ps(_mm_min_ps(_mm_mul_ps(ret, vScalar), vmax_val), vmin_val); _mm_store_ps(outputFloatBuffer, ret); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[0]); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[1]); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[2]); *outputVectorPtr++ = (int8_t)(outputFloatBuffer[3]); } number = quarterPoints * 4; for(; number < num_points; number++){ r = inputVector[number] * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; outputVector[number] = (int8_t)(r); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies each point in the input buffer by the scalar value, then converts the result into a 8 bit integer value \param inputVector The floating point input data buffer \param outputVector The 8 bit output data buffer \param scalar The value multiplied against each point in the input buffer \param num_points The number of data values to be converted */ static inline void volk_32f_s32f_convert_8i_a_generic(int8_t* outputVector, const float* inputVector, const float scalar, unsigned int num_points){ int8_t* outputVectorPtr = outputVector; const float* inputVectorPtr = inputVector; unsigned int number = 0; float min_val = -128; float max_val = 127; float r; for(number = 0; number < num_points; number++){ r = *inputVectorPtr++ * scalar; if(r > max_val) r = max_val; else if(r < min_val) r = min_val; *outputVectorPtr++ = (int8_t)(r); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_convert_8i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_s32f_deinterleave_32f_x2.h0000664000175000017500000001356212207440367025267 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8ic_s32f_deinterleave_32f_x2_a_H #define INCLUDED_volk_8ic_s32f_deinterleave_32f_x2_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Deinterleaves the complex 8 bit vector into I & Q floating point vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_s32f_deinterleave_32f_x2_a_sse4_1(float* iBuffer, float* qBuffer, const lv_8sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; unsigned int number = 0; const unsigned int eighthPoints = num_points / 8; __m128 iFloatValue, qFloatValue; const float iScalar= 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); __m128i complexVal, iIntVal, qIntVal, iComplexVal, qComplexVal; int8_t* complexVectorPtr = (int8_t*)complexVector; __m128i iMoveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 14, 12, 10, 8, 6, 4, 2, 0); __m128i qMoveMask = _mm_set_epi8(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 15, 13, 11, 9, 7, 5, 3, 1); for(;number < eighthPoints; number++){ complexVal = _mm_load_si128((__m128i*)complexVectorPtr); complexVectorPtr += 16; iComplexVal = _mm_shuffle_epi8(complexVal, iMoveMask); qComplexVal = _mm_shuffle_epi8(complexVal, qMoveMask); iIntVal = _mm_cvtepi8_epi32(iComplexVal); iFloatValue = _mm_cvtepi32_ps(iIntVal); iFloatValue = _mm_mul_ps(iFloatValue, invScalar); _mm_store_ps(iBufferPtr, iFloatValue); iBufferPtr += 4; iComplexVal = _mm_srli_si128(iComplexVal, 4); iIntVal = _mm_cvtepi8_epi32(iComplexVal); iFloatValue = _mm_cvtepi32_ps(iIntVal); iFloatValue = _mm_mul_ps(iFloatValue, invScalar); _mm_store_ps(iBufferPtr, iFloatValue); iBufferPtr += 4; qIntVal = _mm_cvtepi8_epi32(qComplexVal); qFloatValue = _mm_cvtepi32_ps(qIntVal); qFloatValue = _mm_mul_ps(qFloatValue, invScalar); _mm_store_ps(qBufferPtr, qFloatValue); qBufferPtr += 4; qComplexVal = _mm_srli_si128(qComplexVal, 4); qIntVal = _mm_cvtepi8_epi32(qComplexVal); qFloatValue = _mm_cvtepi32_ps(qIntVal); qFloatValue = _mm_mul_ps(qFloatValue, invScalar); _mm_store_ps(qBufferPtr, qFloatValue); qBufferPtr += 4; } number = eighthPoints * 8; for(; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++) * iScalar; *qBufferPtr++ = (float)(*complexVectorPtr++) * iScalar; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex 8 bit vector into I & Q floating point vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_s32f_deinterleave_32f_x2_a_sse(float* iBuffer, float* qBuffer, const lv_8sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128 cplxValue1, cplxValue2, iValue, qValue; __m128 invScalar = _mm_set_ps1(1.0/scalar); int8_t* complexVectorPtr = (int8_t*)complexVector; __VOLK_ATTR_ALIGNED(16) float floatBuffer[8]; for(;number < quarterPoints; number++){ floatBuffer[0] = (float)(complexVectorPtr[0]); floatBuffer[1] = (float)(complexVectorPtr[1]); floatBuffer[2] = (float)(complexVectorPtr[2]); floatBuffer[3] = (float)(complexVectorPtr[3]); floatBuffer[4] = (float)(complexVectorPtr[4]); floatBuffer[5] = (float)(complexVectorPtr[5]); floatBuffer[6] = (float)(complexVectorPtr[6]); floatBuffer[7] = (float)(complexVectorPtr[7]); cplxValue1 = _mm_load_ps(&floatBuffer[0]); cplxValue2 = _mm_load_ps(&floatBuffer[4]); complexVectorPtr += 8; cplxValue1 = _mm_mul_ps(cplxValue1, invScalar); cplxValue2 = _mm_mul_ps(cplxValue2, invScalar); // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); _mm_store_ps(iBufferPtr, iValue); _mm_store_ps(qBufferPtr, qValue); iBufferPtr += 4; qBufferPtr += 4; } number = quarterPoints * 4; complexVectorPtr = (int8_t*)&complexVector[number]; for(; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++) / scalar; *qBufferPtr++ = (float)(*complexVectorPtr++) / scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex 8 bit vector into I & Q floating point vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param scalar The scaling value being multiplied against each data point \param num_points The number of complex data values to be deinterleaved */ static inline void volk_8ic_s32f_deinterleave_32f_x2_generic(float* iBuffer, float* qBuffer, const lv_8sc_t* complexVector, const float scalar, unsigned int num_points){ const int8_t* complexVectorPtr = (const int8_t*)complexVector; float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; unsigned int number; const float invScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++)*invScalar; *qBufferPtr++ = (float)(*complexVectorPtr++)*invScalar; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_8ic_s32f_deinterleave_32f_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_x2_dot_prod_32fc.h0000664000175000017500000004036712207440367024015 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_x2_dot_prod_32fc_u_H #define INCLUDED_volk_32fc_x2_dot_prod_32fc_u_H #include #include #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32fc_x2_dot_prod_32fc_generic(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { float * res = (float*) result; float * in = (float*) input; float * tp = (float*) taps; unsigned int n_2_ccomplex_blocks = num_points/2; unsigned int isodd = num_points &1; float sum0[2] = {0,0}; float sum1[2] = {0,0}; unsigned int i = 0; for(i = 0; i < n_2_ccomplex_blocks; ++i) { sum0[0] += in[0] * tp[0] - in[1] * tp[1]; sum0[1] += in[0] * tp[1] + in[1] * tp[0]; sum1[0] += in[2] * tp[2] - in[3] * tp[3]; sum1[1] += in[2] * tp[3] + in[3] * tp[2]; in += 4; tp += 4; } res[0] = sum0[0] + sum1[0]; res[1] = sum0[1] + sum1[1]; for(i = 0; i < isodd; ++i) { *result += input[num_points - 1] * taps[num_points - 1]; } } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE3 #include static inline void volk_32fc_x2_dot_prod_32fc_u_sse3(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { lv_32fc_t dotProduct; memset(&dotProduct, 0x0, 2*sizeof(float)); unsigned int number = 0; const unsigned int halfPoints = num_points/2; __m128 x, y, yl, yh, z, tmp1, tmp2, dotProdVal; const lv_32fc_t* a = input; const lv_32fc_t* b = taps; dotProdVal = _mm_setzero_ps(); for(;number < halfPoints; number++){ x = _mm_loadu_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi y = _mm_loadu_ps((float*)b); // Load the cr + ci, dr + di as cr,ci,dr,di yl = _mm_moveldup_ps(y); // Load yl with cr,cr,dr,dr yh = _mm_movehdup_ps(y); // Load yh with ci,ci,di,di tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di dotProdVal = _mm_add_ps(dotProdVal, z); // Add the complex multiplication results together a += 2; b += 2; } __VOLK_ATTR_ALIGNED(16) lv_32fc_t dotProductVector[2]; _mm_storeu_ps((float*)dotProductVector,dotProdVal); // Store the results back into the dot product vector dotProduct += ( dotProductVector[0] + dotProductVector[1] ); if(num_points % 1 != 0) { dotProduct += (*a) * (*b); } *result = dotProduct; } #endif /*LV_HAVE_SSE3*/ #endif /*INCLUDED_volk_32fc_x2_dot_prod_32fc_u_H*/ #ifndef INCLUDED_volk_32fc_x2_dot_prod_32fc_a_H #define INCLUDED_volk_32fc_x2_dot_prod_32fc_a_H #include #include #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32fc_x2_dot_prod_32fc_a_generic(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; float * res = (float*) result; float * in = (float*) input; float * tp = (float*) taps; unsigned int n_2_ccomplex_blocks = num_bytes >> 4; unsigned int isodd = (num_bytes >> 3) &1; float sum0[2] = {0,0}; float sum1[2] = {0,0}; unsigned int i = 0; for(i = 0; i < n_2_ccomplex_blocks; ++i) { sum0[0] += in[0] * tp[0] - in[1] * tp[1]; sum0[1] += in[0] * tp[1] + in[1] * tp[0]; sum1[0] += in[2] * tp[2] - in[3] * tp[3]; sum1[1] += in[2] * tp[3] + in[3] * tp[2]; in += 4; tp += 4; } res[0] = sum0[0] + sum1[0]; res[1] = sum0[1] + sum1[1]; for(i = 0; i < isodd; ++i) { *result += input[(num_bytes >> 3) - 1] * taps[(num_bytes >> 3) - 1]; } } #endif /*LV_HAVE_GENERIC*/ #if LV_HAVE_SSE && LV_HAVE_64 static inline void volk_32fc_x2_dot_prod_32fc_a_sse_64(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; asm ( "# ccomplex_dotprod_generic (float* result, const float *input,\n\t" "# const float *taps, unsigned num_bytes)\n\t" "# float sum0 = 0;\n\t" "# float sum1 = 0;\n\t" "# float sum2 = 0;\n\t" "# float sum3 = 0;\n\t" "# do {\n\t" "# sum0 += input[0] * taps[0] - input[1] * taps[1];\n\t" "# sum1 += input[0] * taps[1] + input[1] * taps[0];\n\t" "# sum2 += input[2] * taps[2] - input[3] * taps[3];\n\t" "# sum3 += input[2] * taps[3] + input[3] * taps[2];\n\t" "# input += 4;\n\t" "# taps += 4; \n\t" "# } while (--n_2_ccomplex_blocks != 0);\n\t" "# result[0] = sum0 + sum2;\n\t" "# result[1] = sum1 + sum3;\n\t" "# TODO: prefetch and better scheduling\n\t" " xor %%r9, %%r9\n\t" " xor %%r10, %%r10\n\t" " movq %%rcx, %%rax\n\t" " movq %%rcx, %%r8\n\t" " movq %[rsi], %%r9\n\t" " movq %[rdx], %%r10\n\t" " xorps %%xmm6, %%xmm6 # zero accumulators\n\t" " movaps 0(%%r9), %%xmm0\n\t" " xorps %%xmm7, %%xmm7 # zero accumulators\n\t" " movaps 0(%%r10), %%xmm2\n\t" " shr $5, %%rax # rax = n_2_ccomplex_blocks / 2\n\t" " shr $4, %%r8\n\t" " jmp .%=L1_test\n\t" " # 4 taps / loop\n\t" " # something like ?? cycles / loop\n\t" ".%=Loop1: \n\t" "# complex prod: C += A * B, w/ temp Z & Y (or B), xmmPN=$0x8000000080000000\n\t" "# movaps (%%r9), %%xmmA\n\t" "# movaps (%%r10), %%xmmB\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# shufps $0xb1, %%xmmZ, %%xmmZ # swap internals\n\t" "# mulps %%xmmB, %%xmmA\n\t" "# mulps %%xmmZ, %%xmmB\n\t" "# # SSE replacement for: pfpnacc %%xmmB, %%xmmA\n\t" "# xorps %%xmmPN, %%xmmA\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# unpcklps %%xmmB, %%xmmA\n\t" "# unpckhps %%xmmB, %%xmmZ\n\t" "# movaps %%xmmZ, %%xmmY\n\t" "# shufps $0x44, %%xmmA, %%xmmZ # b01000100\n\t" "# shufps $0xee, %%xmmY, %%xmmA # b11101110\n\t" "# addps %%xmmZ, %%xmmA\n\t" "# addps %%xmmA, %%xmmC\n\t" "# A=xmm0, B=xmm2, Z=xmm4\n\t" "# A'=xmm1, B'=xmm3, Z'=xmm5\n\t" " movaps 16(%%r9), %%xmm1\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " movaps 16(%%r10), %%xmm3\n\t" " movaps %%xmm1, %%xmm5\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm3, %%xmm1\n\t" " shufps $0xb1, %%xmm5, %%xmm5 # swap internals\n\t" " addps %%xmm1, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " movaps 32(%%r9), %%xmm0\n\t" " addps %%xmm2, %%xmm7\n\t" " mulps %%xmm5, %%xmm3\n\t" " add $32, %%r9\n\t" " movaps 32(%%r10), %%xmm2\n\t" " addps %%xmm3, %%xmm7\n\t" " add $32, %%r10\n\t" ".%=L1_test:\n\t" " dec %%rax\n\t" " jge .%=Loop1\n\t" " # We've handled the bulk of multiplies up to here.\n\t" " # Let's sse if original n_2_ccomplex_blocks was odd.\n\t" " # If so, we've got 2 more taps to do.\n\t" " and $1, %%r8\n\t" " je .%=Leven\n\t" " # The count was odd, do 2 more taps.\n\t" " # Note that we've already got mm0/mm2 preloaded\n\t" " # from the main loop.\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " addps %%xmm2, %%xmm7\n\t" ".%=Leven:\n\t" " # neg inversor\n\t" " xorps %%xmm1, %%xmm1\n\t" " mov $0x80000000, %%r9\n\t" " movd %%r9, %%xmm1\n\t" " shufps $0x11, %%xmm1, %%xmm1 # b00010001 # 0 -0 0 -0\n\t" " # pfpnacc\n\t" " xorps %%xmm1, %%xmm6\n\t" " movaps %%xmm6, %%xmm2\n\t" " unpcklps %%xmm7, %%xmm6\n\t" " unpckhps %%xmm7, %%xmm2\n\t" " movaps %%xmm2, %%xmm3\n\t" " shufps $0x44, %%xmm6, %%xmm2 # b01000100\n\t" " shufps $0xee, %%xmm3, %%xmm6 # b11101110\n\t" " addps %%xmm2, %%xmm6\n\t" " # xmm6 = r1 i2 r3 i4\n\t" " movhlps %%xmm6, %%xmm4 # xmm4 = r3 i4 ?? ??\n\t" " addps %%xmm4, %%xmm6 # xmm6 = r1+r3 i2+i4 ?? ??\n\t" " movlps %%xmm6, (%[rdi]) # store low 2x32 bits (complex) to memory\n\t" : :[rsi] "r" (input), [rdx] "r" (taps), "c" (num_bytes), [rdi] "r" (result) :"rax", "r8", "r9", "r10" ); if(((num_bytes >> 3) & 1)) { *result += (input[(num_bytes >> 3) - 1] * taps[(num_bytes >> 3) - 1]); } return; } #endif #if LV_HAVE_SSE && LV_HAVE_32 static inline void volk_32fc_x2_dot_prod_32fc_a_sse_32(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { volk_32fc_x2_dot_prod_32fc_a_generic(result, input, taps, num_points); #if 0 const unsigned int num_bytes = num_points*8; asm volatile ( " #pushl %%ebp\n\t" " #movl %%esp, %%ebp\n\t" " movl 12(%%ebp), %%eax # input\n\t" " movl 16(%%ebp), %%edx # taps\n\t" " movl 20(%%ebp), %%ecx # n_bytes\n\t" " xorps %%xmm6, %%xmm6 # zero accumulators\n\t" " movaps 0(%%eax), %%xmm0\n\t" " xorps %%xmm7, %%xmm7 # zero accumulators\n\t" " movaps 0(%%edx), %%xmm2\n\t" " shrl $5, %%ecx # ecx = n_2_ccomplex_blocks / 2\n\t" " jmp .%=L1_test\n\t" " # 4 taps / loop\n\t" " # something like ?? cycles / loop\n\t" ".%=Loop1: \n\t" "# complex prod: C += A * B, w/ temp Z & Y (or B), xmmPN=$0x8000000080000000\n\t" "# movaps (%%eax), %%xmmA\n\t" "# movaps (%%edx), %%xmmB\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# shufps $0xb1, %%xmmZ, %%xmmZ # swap internals\n\t" "# mulps %%xmmB, %%xmmA\n\t" "# mulps %%xmmZ, %%xmmB\n\t" "# # SSE replacement for: pfpnacc %%xmmB, %%xmmA\n\t" "# xorps %%xmmPN, %%xmmA\n\t" "# movaps %%xmmA, %%xmmZ\n\t" "# unpcklps %%xmmB, %%xmmA\n\t" "# unpckhps %%xmmB, %%xmmZ\n\t" "# movaps %%xmmZ, %%xmmY\n\t" "# shufps $0x44, %%xmmA, %%xmmZ # b01000100\n\t" "# shufps $0xee, %%xmmY, %%xmmA # b11101110\n\t" "# addps %%xmmZ, %%xmmA\n\t" "# addps %%xmmA, %%xmmC\n\t" "# A=xmm0, B=xmm2, Z=xmm4\n\t" "# A'=xmm1, B'=xmm3, Z'=xmm5\n\t" " movaps 16(%%eax), %%xmm1\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " movaps 16(%%edx), %%xmm3\n\t" " movaps %%xmm1, %%xmm5\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm3, %%xmm1\n\t" " shufps $0xb1, %%xmm5, %%xmm5 # swap internals\n\t" " addps %%xmm1, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " movaps 32(%%eax), %%xmm0\n\t" " addps %%xmm2, %%xmm7\n\t" " mulps %%xmm5, %%xmm3\n\t" " addl $32, %%eax\n\t" " movaps 32(%%edx), %%xmm2\n\t" " addps %%xmm3, %%xmm7\n\t" " addl $32, %%edx\n\t" ".%=L1_test:\n\t" " decl %%ecx\n\t" " jge .%=Loop1\n\t" " # We've handled the bulk of multiplies up to here.\n\t" " # Let's sse if original n_2_ccomplex_blocks was odd.\n\t" " # If so, we've got 2 more taps to do.\n\t" " movl 20(%%ebp), %%ecx # n_2_ccomplex_blocks\n\t" " shrl $4, %%ecx\n\t" " andl $1, %%ecx\n\t" " je .%=Leven\n\t" " # The count was odd, do 2 more taps.\n\t" " # Note that we've already got mm0/mm2 preloaded\n\t" " # from the main loop.\n\t" " movaps %%xmm0, %%xmm4\n\t" " mulps %%xmm2, %%xmm0\n\t" " shufps $0xb1, %%xmm4, %%xmm4 # swap internals\n\t" " addps %%xmm0, %%xmm6\n\t" " mulps %%xmm4, %%xmm2\n\t" " addps %%xmm2, %%xmm7\n\t" ".%=Leven:\n\t" " # neg inversor\n\t" " movl 8(%%ebp), %%eax \n\t" " xorps %%xmm1, %%xmm1\n\t" " movl $0x80000000, (%%eax)\n\t" " movss (%%eax), %%xmm1\n\t" " shufps $0x11, %%xmm1, %%xmm1 # b00010001 # 0 -0 0 -0\n\t" " # pfpnacc\n\t" " xorps %%xmm1, %%xmm6\n\t" " movaps %%xmm6, %%xmm2\n\t" " unpcklps %%xmm7, %%xmm6\n\t" " unpckhps %%xmm7, %%xmm2\n\t" " movaps %%xmm2, %%xmm3\n\t" " shufps $0x44, %%xmm6, %%xmm2 # b01000100\n\t" " shufps $0xee, %%xmm3, %%xmm6 # b11101110\n\t" " addps %%xmm2, %%xmm6\n\t" " # xmm6 = r1 i2 r3 i4\n\t" " #movl 8(%%ebp), %%eax # @result\n\t" " movhlps %%xmm6, %%xmm4 # xmm4 = r3 i4 ?? ??\n\t" " addps %%xmm4, %%xmm6 # xmm6 = r1+r3 i2+i4 ?? ??\n\t" " movlps %%xmm6, (%%eax) # store low 2x32 bits (complex) to memory\n\t" " #popl %%ebp\n\t" : : : "eax", "ecx", "edx" ); int getem = num_bytes % 16; for(; getem > 0; getem -= 8) { *result += (input[(num_bytes >> 3) - 1] * taps[(num_bytes >> 3) - 1]); } return; #endif } #endif /*LV_HAVE_SSE*/ #ifdef LV_HAVE_SSE3 #include static inline void volk_32fc_x2_dot_prod_32fc_a_sse3(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; lv_32fc_t dotProduct; memset(&dotProduct, 0x0, 2*sizeof(float)); unsigned int number = 0; const unsigned int halfPoints = num_bytes >> 4; __m128 x, y, yl, yh, z, tmp1, tmp2, dotProdVal; const lv_32fc_t* a = input; const lv_32fc_t* b = taps; dotProdVal = _mm_setzero_ps(); for(;number < halfPoints; number++){ x = _mm_load_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi y = _mm_load_ps((float*)b); // Load the cr + ci, dr + di as cr,ci,dr,di yl = _mm_moveldup_ps(y); // Load yl with cr,cr,dr,dr yh = _mm_movehdup_ps(y); // Load yh with ci,ci,di,di tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di dotProdVal = _mm_add_ps(dotProdVal, z); // Add the complex multiplication results together a += 2; b += 2; } __VOLK_ATTR_ALIGNED(16) lv_32fc_t dotProductVector[2]; _mm_store_ps((float*)dotProductVector,dotProdVal); // Store the results back into the dot product vector dotProduct += ( dotProductVector[0] + dotProductVector[1] ); if(((num_bytes >> 3) & 1) != 0) { dotProduct += (*a) * (*b); } *result = dotProduct; } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_SSE4_1 #include static inline void volk_32fc_x2_dot_prod_32fc_a_sse4_1(lv_32fc_t* result, const lv_32fc_t* input, const lv_32fc_t* taps, unsigned int num_points) { const unsigned int num_bytes = num_points*8; __m128 xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, real0, real1, im0, im1; float *p_input, *p_taps; __m64 *p_result; p_result = (__m64*)result; p_input = (float*)input; p_taps = (float*)taps; static const __m128i neg = {0x000000000000000080000000}; int i = 0; int bound = (num_bytes >> 5); int leftovers = (num_bytes & 24) >> 3; real0 = _mm_sub_ps(real0, real0); real1 = _mm_sub_ps(real1, real1); im0 = _mm_sub_ps(im0, im0); im1 = _mm_sub_ps(im1, im1); for(; i < bound; ++i) { xmm0 = _mm_load_ps(p_input); xmm1 = _mm_load_ps(p_taps); p_input += 4; p_taps += 4; xmm2 = _mm_load_ps(p_input); xmm3 = _mm_load_ps(p_taps); p_input += 4; p_taps += 4; xmm4 = _mm_unpackhi_ps(xmm0, xmm2); xmm5 = _mm_unpackhi_ps(xmm1, xmm3); xmm0 = _mm_unpacklo_ps(xmm0, xmm2); xmm2 = _mm_unpacklo_ps(xmm1, xmm3); //imaginary vector from input xmm1 = _mm_unpackhi_ps(xmm0, xmm4); //real vector from input xmm3 = _mm_unpacklo_ps(xmm0, xmm4); //imaginary vector from taps xmm0 = _mm_unpackhi_ps(xmm2, xmm5); //real vector from taps xmm2 = _mm_unpacklo_ps(xmm2, xmm5); xmm4 = _mm_dp_ps(xmm3, xmm2, 0xf1); xmm5 = _mm_dp_ps(xmm1, xmm0, 0xf1); xmm6 = _mm_dp_ps(xmm3, xmm0, 0xf2); xmm7 = _mm_dp_ps(xmm1, xmm2, 0xf2); real0 = _mm_add_ps(xmm4, real0); real1 = _mm_add_ps(xmm5, real1); im0 = _mm_add_ps(xmm6, im0); im1 = _mm_add_ps(xmm7, im1); } real1 = _mm_xor_ps(real1, bit128_p(&neg)->float_vec); im0 = _mm_add_ps(im0, im1); real0 = _mm_add_ps(real0, real1); im0 = _mm_add_ps(im0, real0); _mm_storel_pi(p_result, im0); for(i = bound * 4; i < (bound * 4) + leftovers; ++i) { *result += input[i] * taps[i]; } } #endif /*LV_HAVE_SSE4_1*/ #endif /*INCLUDED_volk_32fc_x2_dot_prod_32fc_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32f_deinterleave_real_16i.h0000664000175000017500000000527412207440367025741 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32f_deinterleave_real_16i_a_H #define INCLUDED_volk_32fc_s32f_deinterleave_real_16i_a_H #include #include #include #ifdef LV_HAVE_SSE #include /*! \brief Deinterleaves the complex vector, multiply the value by the scalar, convert to 16t, and in I vector data \param complexVector The complex input vector \param scalar The value to be multiply against each of the input values \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_s32f_deinterleave_real_16i_a_sse(int16_t* iBuffer, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (float*)complexVector; int16_t* iBufferPtr = iBuffer; __m128 vScalar = _mm_set_ps1(scalar); __m128 cplxValue1, cplxValue2, iValue; __VOLK_ATTR_ALIGNED(16) float floatBuffer[4]; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); iValue = _mm_mul_ps(iValue, vScalar); _mm_store_ps(floatBuffer, iValue); *iBufferPtr++ = (int16_t)(floatBuffer[0]); *iBufferPtr++ = (int16_t)(floatBuffer[1]); *iBufferPtr++ = (int16_t)(floatBuffer[2]); *iBufferPtr++ = (int16_t)(floatBuffer[3]); } number = quarterPoints * 4; iBufferPtr = &iBuffer[number]; for(; number < num_points; number++){ *iBufferPtr++ = (int16_t)(*complexVectorPtr++ * scalar); complexVectorPtr++; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Deinterleaves the complex vector, multiply the value by the scalar, convert to 16t, and in I vector data \param complexVector The complex input vector \param scalar The value to be multiply against each of the input values \param iBuffer The I buffer output data \param num_points The number of complex data values to be deinterleaved */ static inline void volk_32fc_s32f_deinterleave_real_16i_generic(int16_t* iBuffer, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; int16_t* iBufferPtr = iBuffer; unsigned int number = 0; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (int16_t)(*complexVectorPtr++ * scalar); complexVectorPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_s32f_deinterleave_real_16i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_64f_x2_max_64f.h0000664000175000017500000000431512207440367022465 0ustar jcorganjcorgan#ifndef INCLUDED_volk_64f_x2_max_64f_a_H #define INCLUDED_volk_64f_x2_max_64f_a_H #include #include #ifdef LV_HAVE_SSE2 #include /*! \brief Selects maximum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_64f_x2_max_64f_a_sse2(double* cVector, const double* aVector, const double* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; double* cPtr = cVector; const double* aPtr = aVector; const double* bPtr= bVector; __m128d aVal, bVal, cVal; for(;number < halfPoints; number++){ aVal = _mm_load_pd(aPtr); bVal = _mm_load_pd(bPtr); cVal = _mm_max_pd(aVal, bVal); _mm_store_pd(cPtr,cVal); // Store the results back into the C container aPtr += 2; bPtr += 2; cPtr += 2; } number = halfPoints * 2; for(;number < num_points; number++){ const double a = *aPtr++; const double b = *bPtr++; *cPtr++ = ( a > b ? a : b); } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Selects maximum value from each entry between bVector and aVector and store their results in the cVector \param cVector The vector where the results will be stored \param aVector The vector to be checked \param bVector The vector to be checked \param num_points The number of values in aVector and bVector to be checked and stored into cVector */ static inline void volk_64f_x2_max_64f_generic(double* cVector, const double* aVector, const double* bVector, unsigned int num_points){ double* cPtr = cVector; const double* aPtr = aVector; const double* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const double a = *aPtr++; const double b = *bPtr++; *cPtr++ = ( a > b ? a : b); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64f_x2_max_64f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_dot_prod_16i.h0000664000175000017500000000500712207440367023504 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_dot_prod_16i_a_H #define INCLUDED_volk_32f_x2_dot_prod_16i_a_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32f_x2_dot_prod_16i_generic(int16_t* result, const float* input, const float* taps, unsigned int num_points) { float dotProduct = 0; const float* aPtr = input; const float* bPtr= taps; unsigned int number = 0; for(number = 0; number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = (int16_t)dotProduct; } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE static inline void volk_32f_x2_dot_prod_16i_a_sse(int16_t* result, const float* input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm_load_ps(aPtr); a1Val = _mm_load_ps(aPtr+4); a2Val = _mm_load_ps(aPtr+8); a3Val = _mm_load_ps(aPtr+12); b0Val = _mm_load_ps(bPtr); b1Val = _mm_load_ps(bPtr+4); b2Val = _mm_load_ps(bPtr+8); b3Val = _mm_load_ps(bPtr+12); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm_add_ps(c1Val, dotProdVal1); dotProdVal2 = _mm_add_ps(c2Val, dotProdVal2); dotProdVal3 = _mm_add_ps(c3Val, dotProdVal3); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = (short)dotProduct; } #endif /*LV_HAVE_SSE*/ #endif /*INCLUDED_volk_32f_x2_dot_prod_16i_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_16ic_s32f_deinterleave_32f_x2.h0000664000175000017500000001072712207440367025346 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16ic_s32f_deinterleave_32f_x2_a_H #define INCLUDED_volk_16ic_s32f_deinterleave_32f_x2_a_H #include #include #include #ifdef LV_HAVE_SSE #include /*! \brief Converts the complex 16 bit vector into floats,scales each data point, and deinterleaves into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_s32f_deinterleave_32f_x2_a_sse(float* iBuffer, float* qBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; uint64_t number = 0; const uint64_t quarterPoints = num_points / 4; __m128 cplxValue1, cplxValue2, iValue, qValue; __m128 invScalar = _mm_set_ps1(1.0/scalar); int16_t* complexVectorPtr = (int16_t*)complexVector; __VOLK_ATTR_ALIGNED(16) float floatBuffer[8]; for(;number < quarterPoints; number++){ floatBuffer[0] = (float)(complexVectorPtr[0]); floatBuffer[1] = (float)(complexVectorPtr[1]); floatBuffer[2] = (float)(complexVectorPtr[2]); floatBuffer[3] = (float)(complexVectorPtr[3]); floatBuffer[4] = (float)(complexVectorPtr[4]); floatBuffer[5] = (float)(complexVectorPtr[5]); floatBuffer[6] = (float)(complexVectorPtr[6]); floatBuffer[7] = (float)(complexVectorPtr[7]); cplxValue1 = _mm_load_ps(&floatBuffer[0]); cplxValue2 = _mm_load_ps(&floatBuffer[4]); complexVectorPtr += 8; cplxValue1 = _mm_mul_ps(cplxValue1, invScalar); cplxValue2 = _mm_mul_ps(cplxValue2, invScalar); // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); _mm_store_ps(iBufferPtr, iValue); _mm_store_ps(qBufferPtr, qValue); iBufferPtr += 4; qBufferPtr += 4; } number = quarterPoints * 4; complexVectorPtr = (int16_t*)&complexVector[number]; for(; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++) / scalar; *qBufferPtr++ = (float)(*complexVectorPtr++) / scalar; } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the complex 16 bit vector into floats,scales each data point, and deinterleaves into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex data values to be deinterleaved */ static inline void volk_16ic_s32f_deinterleave_32f_x2_generic(float* iBuffer, float* qBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ const int16_t* complexVectorPtr = (const int16_t*)complexVector; float* iBufferPtr = iBuffer; float* qBufferPtr = qBuffer; unsigned int number; for(number = 0; number < num_points; number++){ *iBufferPtr++ = (float)(*complexVectorPtr++) / scalar; *qBufferPtr++ = (float)(*complexVectorPtr++) / scalar; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Converts the complex 16 bit vector into floats,scales each data point, and deinterleaves into I & Q vector data \param complexVector The complex input vector \param iBuffer The I buffer output data \param qBuffer The Q buffer output data \param scalar The data value to be divided against each input data value of the input complex vector \param num_points The number of complex data values to be deinterleaved */ extern void volk_16ic_s32f_deinterleave_32f_x2_a_orc_impl(float* iBuffer, float* qBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points); static inline void volk_16ic_s32f_deinterleave_32f_x2_u_orc(float* iBuffer, float* qBuffer, const lv_16sc_t* complexVector, const float scalar, unsigned int num_points){ volk_16ic_s32f_deinterleave_32f_x2_a_orc_impl(iBuffer, qBuffer, complexVector, scalar, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_16ic_s32f_deinterleave_32f_x2_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8i_s32f_convert_32f.h0000664000175000017500000001657512207440367023533 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8i_s32f_convert_32f_u_H #define INCLUDED_volk_8i_s32f_convert_32f_u_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Converts the input 8 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 8 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_8i_s32f_convert_32f_u_sse4_1(float* outputVector, const int8_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float* outputVectorPtr = outputVector; const float iScalar = 1.0 / scalar; __m128 invScalar = _mm_set_ps1( iScalar ); const int8_t* inputVectorPtr = inputVector; __m128 ret; __m128i inputVal; __m128i interimVal; for(;number < sixteenthPoints; number++){ inputVal = _mm_loadu_si128((__m128i*)inputVectorPtr); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVal = _mm_srli_si128(inputVal, 4); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVal = _mm_srli_si128(inputVal, 4); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVal = _mm_srli_si128(inputVal, 4); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_storeu_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVectorPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ outputVector[number] = (float)(inputVector[number]) * iScalar; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 8 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 8 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted \note Output buffer does NOT need to be properly aligned */ static inline void volk_8i_s32f_convert_32f_generic(float* outputVector, const int8_t* inputVector, const float scalar, unsigned int num_points){ float* outputVectorPtr = outputVector; const int8_t* inputVectorPtr = inputVector; unsigned int number = 0; const float iScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)) * iScalar; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_VOLK_8s_CONVERT_32f_UNALIGNED8_H */ #ifndef INCLUDED_volk_8i_s32f_convert_32f_a_H #define INCLUDED_volk_8i_s32f_convert_32f_a_H #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Converts the input 8 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 8 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_8i_s32f_convert_32f_a_sse4_1(float* outputVector, const int8_t* inputVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float* outputVectorPtr = outputVector; const float iScalar = 1.0 / scalar; __m128 invScalar = _mm_set_ps1(iScalar); const int8_t* inputVectorPtr = inputVector; __m128 ret; __m128i inputVal; __m128i interimVal; for(;number < sixteenthPoints; number++){ inputVal = _mm_load_si128((__m128i*)inputVectorPtr); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_store_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVal = _mm_srli_si128(inputVal, 4); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_store_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVal = _mm_srli_si128(inputVal, 4); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_store_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVal = _mm_srli_si128(inputVal, 4); interimVal = _mm_cvtepi8_epi32(inputVal); ret = _mm_cvtepi32_ps(interimVal); ret = _mm_mul_ps(ret, invScalar); _mm_store_ps(outputVectorPtr, ret); outputVectorPtr += 4; inputVectorPtr += 16; } number = sixteenthPoints * 16; for(; number < num_points; number++){ outputVector[number] = (float)(inputVector[number]) * iScalar; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Converts the input 8 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 8 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ static inline void volk_8i_s32f_convert_32f_a_generic(float* outputVector, const int8_t* inputVector, const float scalar, unsigned int num_points){ float* outputVectorPtr = outputVector; const int8_t* inputVectorPtr = inputVector; unsigned int number = 0; const float iScalar = 1.0 / scalar; for(number = 0; number < num_points; number++){ *outputVectorPtr++ = ((float)(*inputVectorPtr++)) * iScalar; } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Converts the input 8 bit integer data into floating point data, and divides the each floating point output data point by the scalar value \param inputVector The 8 bit input data buffer \param outputVector The floating point output data buffer \param scalar The value divided against each point in the output buffer \param num_points The number of data values to be converted */ extern void volk_8i_s32f_convert_32f_a_orc_impl(float* outputVector, const int8_t* inputVector, const float scalar, unsigned int num_points); static inline void volk_8i_s32f_convert_32f_u_orc(float* outputVector, const int8_t* inputVector, const float scalar, unsigned int num_points){ float invscalar = 1.0 / scalar; volk_8i_s32f_convert_32f_a_orc_impl(outputVector, inputVector, invscalar, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_VOLK_8s_CONVERT_32f_ALIGNED8_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_x2_square_dist_32f.h0000664000175000017500000000460512207440367024356 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_x2_square_dist_32f_a_H #define INCLUDED_volk_32fc_x2_square_dist_32f_a_H #include #include #include #ifdef LV_HAVE_SSE3 #include #include static inline void volk_32fc_x2_square_dist_32f_a_sse3(float* target, lv_32fc_t* src0, lv_32fc_t* points, unsigned int num_points) { const unsigned int num_bytes = num_points*8; __m128 xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; lv_32fc_t diff; float sq_dist; int bound = num_bytes >> 5; int leftovers0 = (num_bytes >> 4) & 1; int leftovers1 = (num_bytes >> 3) & 1; int i = 0; xmm1 = _mm_setzero_ps(); xmm1 = _mm_loadl_pi(xmm1, (__m64*)src0); xmm2 = _mm_load_ps((float*)&points[0]); xmm1 = _mm_movelh_ps(xmm1, xmm1); xmm3 = _mm_load_ps((float*)&points[2]); for(; i < bound - 1; ++i) { xmm4 = _mm_sub_ps(xmm1, xmm2); xmm5 = _mm_sub_ps(xmm1, xmm3); points += 4; xmm6 = _mm_mul_ps(xmm4, xmm4); xmm7 = _mm_mul_ps(xmm5, xmm5); xmm2 = _mm_load_ps((float*)&points[0]); xmm4 = _mm_hadd_ps(xmm6, xmm7); xmm3 = _mm_load_ps((float*)&points[2]); _mm_store_ps(target, xmm4); target += 4; } xmm4 = _mm_sub_ps(xmm1, xmm2); xmm5 = _mm_sub_ps(xmm1, xmm3); points += 4; xmm6 = _mm_mul_ps(xmm4, xmm4); xmm7 = _mm_mul_ps(xmm5, xmm5); xmm4 = _mm_hadd_ps(xmm6, xmm7); _mm_store_ps(target, xmm4); target += 4; for(i = 0; i < leftovers0; ++i) { xmm2 = _mm_load_ps((float*)&points[0]); xmm4 = _mm_sub_ps(xmm1, xmm2); points += 2; xmm6 = _mm_mul_ps(xmm4, xmm4); xmm4 = _mm_hadd_ps(xmm6, xmm6); _mm_storeh_pi((__m64*)target, xmm4); target += 2; } for(i = 0; i < leftovers1; ++i) { diff = src0[0] - points[0]; sq_dist = lv_creal(diff) * lv_creal(diff) + lv_cimag(diff) * lv_cimag(diff); target[0] = sq_dist; } } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_GENERIC static inline void volk_32fc_x2_square_dist_32f_generic(float* target, lv_32fc_t* src0, lv_32fc_t* points, unsigned int num_points) { const unsigned int num_bytes = num_points*8; lv_32fc_t diff; float sq_dist; unsigned int i = 0; for(; i < num_bytes >> 3; ++i) { diff = src0[0] - points[i]; sq_dist = lv_creal(diff) * lv_creal(diff) + lv_cimag(diff) * lv_cimag(diff); target[i] = sq_dist; } } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_32fc_x2_square_dist_32f_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x3_sum_of_poly_32f.h0000664000175000017500000000701112207440367024216 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x3_sum_of_poly_32f_a_H #define INCLUDED_volk_32f_x3_sum_of_poly_32f_a_H #include #include #include #ifndef MAX #define MAX(X,Y) ((X) > (Y)?(X):(Y)) #endif #ifdef LV_HAVE_SSE3 #include #include static inline void volk_32f_x3_sum_of_poly_32f_a_sse3(float* target, float* src0, float* center_point_array, float* cutoff, unsigned int num_points) { const unsigned int num_bytes = num_points*4; float result = 0.0; float fst = 0.0; float sq = 0.0; float thrd = 0.0; float frth = 0.0; //float fith = 0.0; __m128 xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10;// xmm11, xmm12; xmm9 = _mm_setzero_ps(); xmm1 = _mm_setzero_ps(); xmm0 = _mm_load1_ps(¢er_point_array[0]); xmm6 = _mm_load1_ps(¢er_point_array[1]); xmm7 = _mm_load1_ps(¢er_point_array[2]); xmm8 = _mm_load1_ps(¢er_point_array[3]); //xmm11 = _mm_load1_ps(¢er_point_array[4]); xmm10 = _mm_load1_ps(cutoff); int bound = num_bytes >> 4; int leftovers = (num_bytes >> 2) & 3; int i = 0; for(; i < bound; ++i) { xmm2 = _mm_load_ps(src0); xmm2 = _mm_max_ps(xmm10, xmm2); xmm3 = _mm_mul_ps(xmm2, xmm2); xmm4 = _mm_mul_ps(xmm2, xmm3); xmm5 = _mm_mul_ps(xmm3, xmm3); //xmm12 = _mm_mul_ps(xmm3, xmm4); xmm2 = _mm_mul_ps(xmm2, xmm0); xmm3 = _mm_mul_ps(xmm3, xmm6); xmm4 = _mm_mul_ps(xmm4, xmm7); xmm5 = _mm_mul_ps(xmm5, xmm8); //xmm12 = _mm_mul_ps(xmm12, xmm11); xmm2 = _mm_add_ps(xmm2, xmm3); xmm3 = _mm_add_ps(xmm4, xmm5); src0 += 4; xmm9 = _mm_add_ps(xmm2, xmm9); xmm1 = _mm_add_ps(xmm3, xmm1); //xmm9 = _mm_add_ps(xmm12, xmm9); } xmm2 = _mm_hadd_ps(xmm9, xmm1); xmm3 = _mm_hadd_ps(xmm2, xmm2); xmm4 = _mm_hadd_ps(xmm3, xmm3); _mm_store_ss(&result, xmm4); for(i = 0; i < leftovers; ++i) { fst = src0[i]; fst = MAX(fst, *cutoff); sq = fst * fst; thrd = fst * sq; frth = sq * sq; //fith = sq * thrd; result += (center_point_array[0] * fst + center_point_array[1] * sq + center_point_array[2] * thrd + center_point_array[3] * frth);// + //center_point_array[4] * fith); } result += ((float)((bound * 4) + leftovers)) * center_point_array[4]; //center_point_array[5]; target[0] = result; } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_GENERIC static inline void volk_32f_x3_sum_of_poly_32f_generic(float* target, float* src0, float* center_point_array, float* cutoff, unsigned int num_points) { const unsigned int num_bytes = num_points*4; float result = 0.0; float fst = 0.0; float sq = 0.0; float thrd = 0.0; float frth = 0.0; //float fith = 0.0; unsigned int i = 0; for(; i < num_bytes >> 2; ++i) { fst = src0[i]; fst = MAX(fst, *cutoff); sq = fst * fst; thrd = fst * sq; frth = sq * sq; //fith = sq * thrd; result += (center_point_array[0] * fst + center_point_array[1] * sq + center_point_array[2] * thrd + center_point_array[3] * frth); //+ //center_point_array[4] * fith); /*printf("%f12...%d\n", (center_point_array[0] * fst + center_point_array[1] * sq + center_point_array[2] * thrd + center_point_array[3] * frth) + //center_point_array[4] * fith) + (center_point_array[4]), i); */ } result += ((float)(num_bytes >> 2)) * (center_point_array[4]);//(center_point_array[5]); *target = result; } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_32f_x3_sum_of_poly_32f_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_s32f_stddev_32f.h0000664000175000017500000001135412207440367023404 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_s32f_stddev_32f_a_H #define INCLUDED_volk_32f_s32f_stddev_32f_a_H #include #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Calculates the standard deviation of the input buffer using the supplied mean \param stddev The calculated standard deviation \param inputBuffer The buffer of points to calculate the std deviation for \param mean The mean of the input buffer \param num_points The number of values in input buffer to used in the stddev calculation */ static inline void volk_32f_s32f_stddev_32f_a_sse4_1(float* stddev, const float* inputBuffer, const float mean, unsigned int num_points){ float returnValue = 0; if(num_points > 0){ unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; const float* aPtr = inputBuffer; __VOLK_ATTR_ALIGNED(16) float squareBuffer[4]; __m128 squareAccumulator = _mm_setzero_ps(); __m128 aVal1, aVal2, aVal3, aVal4; __m128 cVal1, cVal2, cVal3, cVal4; for(;number < sixteenthPoints; number++) { aVal1 = _mm_load_ps(aPtr); aPtr += 4; cVal1 = _mm_dp_ps(aVal1, aVal1, 0xF1); aVal2 = _mm_load_ps(aPtr); aPtr += 4; cVal2 = _mm_dp_ps(aVal2, aVal2, 0xF2); aVal3 = _mm_load_ps(aPtr); aPtr += 4; cVal3 = _mm_dp_ps(aVal3, aVal3, 0xF4); aVal4 = _mm_load_ps(aPtr); aPtr += 4; cVal4 = _mm_dp_ps(aVal4, aVal4, 0xF8); cVal1 = _mm_or_ps(cVal1, cVal2); cVal3 = _mm_or_ps(cVal3, cVal4); cVal1 = _mm_or_ps(cVal1, cVal3); squareAccumulator = _mm_add_ps(squareAccumulator, cVal1); // squareAccumulator += x^2 } _mm_store_ps(squareBuffer,squareAccumulator); // Store the results back into the C container returnValue = squareBuffer[0]; returnValue += squareBuffer[1]; returnValue += squareBuffer[2]; returnValue += squareBuffer[3]; number = sixteenthPoints * 16; for(;number < num_points; number++){ returnValue += (*aPtr) * (*aPtr); aPtr++; } returnValue /= num_points; returnValue -= (mean * mean); returnValue = sqrtf(returnValue); } *stddev = returnValue; } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the standard deviation of the input buffer using the supplied mean \param stddev The calculated standard deviation \param inputBuffer The buffer of points to calculate the std deviation for \param mean The mean of the input buffer \param num_points The number of values in input buffer to used in the stddev calculation */ static inline void volk_32f_s32f_stddev_32f_a_sse(float* stddev, const float* inputBuffer, const float mean, unsigned int num_points){ float returnValue = 0; if(num_points > 0){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* aPtr = inputBuffer; __VOLK_ATTR_ALIGNED(16) float squareBuffer[4]; __m128 squareAccumulator = _mm_setzero_ps(); __m128 aVal = _mm_setzero_ps(); for(;number < quarterPoints; number++) { aVal = _mm_load_ps(aPtr); // aVal = x aVal = _mm_mul_ps(aVal, aVal); // squareAccumulator += x^2 squareAccumulator = _mm_add_ps(squareAccumulator, aVal); aPtr += 4; } _mm_store_ps(squareBuffer,squareAccumulator); // Store the results back into the C container returnValue = squareBuffer[0]; returnValue += squareBuffer[1]; returnValue += squareBuffer[2]; returnValue += squareBuffer[3]; number = quarterPoints * 4; for(;number < num_points; number++){ returnValue += (*aPtr) * (*aPtr); aPtr++; } returnValue /= num_points; returnValue -= (mean * mean); returnValue = sqrtf(returnValue); } *stddev = returnValue; } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the standard deviation of the input buffer using the supplied mean \param stddev The calculated standard deviation \param inputBuffer The buffer of points to calculate the std deviation for \param mean The mean of the input buffer \param num_points The number of values in input buffer to used in the stddev calculation */ static inline void volk_32f_s32f_stddev_32f_generic(float* stddev, const float* inputBuffer, const float mean, unsigned int num_points){ float returnValue = 0; if(num_points > 0){ const float* aPtr = inputBuffer; unsigned int number = 0; for(number = 0; number < num_points; number++){ returnValue += (*aPtr) * (*aPtr); aPtr++; } returnValue /= num_points; returnValue -= (mean * mean); returnValue = sqrtf(returnValue); } *stddev = returnValue; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_s32f_stddev_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_x2_dot_prod_32f.h0000664000175000017500000003645512207440367023512 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_x2_dot_prod_32f_u_H #define INCLUDED_volk_32f_x2_dot_prod_32f_u_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32f_x2_dot_prod_32f_generic(float * result, const float * input, const float * taps, unsigned int num_points) { float dotProduct = 0; const float* aPtr = input; const float* bPtr= taps; unsigned int number = 0; for(number = 0; number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE static inline void volk_32f_x2_dot_prod_32f_u_sse( float* result, const float* input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm_loadu_ps(aPtr); a1Val = _mm_loadu_ps(aPtr+4); a2Val = _mm_loadu_ps(aPtr+8); a3Val = _mm_loadu_ps(aPtr+12); b0Val = _mm_loadu_ps(bPtr); b1Val = _mm_loadu_ps(bPtr+4); b2Val = _mm_loadu_ps(bPtr+8); b3Val = _mm_loadu_ps(bPtr+12); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm_add_ps(c1Val, dotProdVal1); dotProdVal2 = _mm_add_ps(c2Val, dotProdVal2); dotProdVal3 = _mm_add_ps(c3Val, dotProdVal3); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_SSE*/ #ifdef LV_HAVE_SSE3 #include static inline void volk_32f_x2_dot_prod_32f_u_sse3(float * result, const float * input, const float * taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm_loadu_ps(aPtr); a1Val = _mm_loadu_ps(aPtr+4); a2Val = _mm_loadu_ps(aPtr+8); a3Val = _mm_loadu_ps(aPtr+12); b0Val = _mm_loadu_ps(bPtr); b1Val = _mm_loadu_ps(bPtr+4); b2Val = _mm_loadu_ps(bPtr+8); b3Val = _mm_loadu_ps(bPtr+12); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(dotProdVal0, c0Val); dotProdVal1 = _mm_add_ps(dotProdVal1, c1Val); dotProdVal2 = _mm_add_ps(dotProdVal2, c2Val); dotProdVal3 = _mm_add_ps(dotProdVal3, c3Val); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_SSE4_1 #include static inline void volk_32f_x2_dot_prod_32f_u_sse4_1(float * result, const float * input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 aVal1, bVal1, cVal1; __m128 aVal2, bVal2, cVal2; __m128 aVal3, bVal3, cVal3; __m128 aVal4, bVal4, cVal4; __m128 dotProdVal = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ aVal1 = _mm_loadu_ps(aPtr); aPtr += 4; aVal2 = _mm_loadu_ps(aPtr); aPtr += 4; aVal3 = _mm_loadu_ps(aPtr); aPtr += 4; aVal4 = _mm_loadu_ps(aPtr); aPtr += 4; bVal1 = _mm_loadu_ps(bPtr); bPtr += 4; bVal2 = _mm_loadu_ps(bPtr); bPtr += 4; bVal3 = _mm_loadu_ps(bPtr); bPtr += 4; bVal4 = _mm_loadu_ps(bPtr); bPtr += 4; cVal1 = _mm_dp_ps(aVal1, bVal1, 0xF1); cVal2 = _mm_dp_ps(aVal2, bVal2, 0xF2); cVal3 = _mm_dp_ps(aVal3, bVal3, 0xF4); cVal4 = _mm_dp_ps(aVal4, bVal4, 0xF8); cVal1 = _mm_or_ps(cVal1, cVal2); cVal3 = _mm_or_ps(cVal3, cVal4); cVal1 = _mm_or_ps(cVal1, cVal3); dotProdVal = _mm_add_ps(dotProdVal, cVal1); } __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector, dotProdVal); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints * 16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_SSE4_1*/ #ifdef LV_HAVE_AVX #include static inline void volk_32f_x2_dot_prod_32f_u_avx( float* result, const float* input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m256 a0Val, a1Val; __m256 b0Val, b1Val; __m256 c0Val, c1Val; __m256 dotProdVal0 = _mm256_setzero_ps(); __m256 dotProdVal1 = _mm256_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm256_loadu_ps(aPtr); a1Val = _mm256_loadu_ps(aPtr+8); b0Val = _mm256_loadu_ps(bPtr); b1Val = _mm256_loadu_ps(bPtr+8); c0Val = _mm256_mul_ps(a0Val, b0Val); c1Val = _mm256_mul_ps(a1Val, b1Val); dotProdVal0 = _mm256_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm256_add_ps(c1Val, dotProdVal1); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm256_add_ps(dotProdVal0, dotProdVal1); __VOLK_ATTR_ALIGNED(32) float dotProductVector[8]; _mm256_storeu_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; dotProduct += dotProductVector[4]; dotProduct += dotProductVector[5]; dotProduct += dotProductVector[6]; dotProduct += dotProductVector[7]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_AVX*/ #endif /*INCLUDED_volk_32f_x2_dot_prod_32f_u_H*/ #ifndef INCLUDED_volk_32f_x2_dot_prod_32f_a_H #define INCLUDED_volk_32f_x2_dot_prod_32f_a_H #include #include #ifdef LV_HAVE_GENERIC static inline void volk_32f_x2_dot_prod_32f_a_generic(float * result, const float * input, const float * taps, unsigned int num_points) { float dotProduct = 0; const float* aPtr = input; const float* bPtr= taps; unsigned int number = 0; for(number = 0; number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_GENERIC*/ #ifdef LV_HAVE_SSE static inline void volk_32f_x2_dot_prod_32f_a_sse( float* result, const float* input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm_load_ps(aPtr); a1Val = _mm_load_ps(aPtr+4); a2Val = _mm_load_ps(aPtr+8); a3Val = _mm_load_ps(aPtr+12); b0Val = _mm_load_ps(bPtr); b1Val = _mm_load_ps(bPtr+4); b2Val = _mm_load_ps(bPtr+8); b3Val = _mm_load_ps(bPtr+12); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm_add_ps(c1Val, dotProdVal1); dotProdVal2 = _mm_add_ps(c2Val, dotProdVal2); dotProdVal3 = _mm_add_ps(c3Val, dotProdVal3); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_SSE*/ #ifdef LV_HAVE_SSE3 #include static inline void volk_32f_x2_dot_prod_32f_a_sse3(float * result, const float * input, const float * taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 a0Val, a1Val, a2Val, a3Val; __m128 b0Val, b1Val, b2Val, b3Val; __m128 c0Val, c1Val, c2Val, c3Val; __m128 dotProdVal0 = _mm_setzero_ps(); __m128 dotProdVal1 = _mm_setzero_ps(); __m128 dotProdVal2 = _mm_setzero_ps(); __m128 dotProdVal3 = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm_load_ps(aPtr); a1Val = _mm_load_ps(aPtr+4); a2Val = _mm_load_ps(aPtr+8); a3Val = _mm_load_ps(aPtr+12); b0Val = _mm_load_ps(bPtr); b1Val = _mm_load_ps(bPtr+4); b2Val = _mm_load_ps(bPtr+8); b3Val = _mm_load_ps(bPtr+12); c0Val = _mm_mul_ps(a0Val, b0Val); c1Val = _mm_mul_ps(a1Val, b1Val); c2Val = _mm_mul_ps(a2Val, b2Val); c3Val = _mm_mul_ps(a3Val, b3Val); dotProdVal0 = _mm_add_ps(dotProdVal0, c0Val); dotProdVal1 = _mm_add_ps(dotProdVal1, c1Val); dotProdVal2 = _mm_add_ps(dotProdVal2, c2Val); dotProdVal3 = _mm_add_ps(dotProdVal3, c3Val); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal1); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal2); dotProdVal0 = _mm_add_ps(dotProdVal0, dotProdVal3); __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_SSE3*/ #ifdef LV_HAVE_SSE4_1 #include static inline void volk_32f_x2_dot_prod_32f_a_sse4_1(float * result, const float * input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m128 aVal1, bVal1, cVal1; __m128 aVal2, bVal2, cVal2; __m128 aVal3, bVal3, cVal3; __m128 aVal4, bVal4, cVal4; __m128 dotProdVal = _mm_setzero_ps(); for(;number < sixteenthPoints; number++){ aVal1 = _mm_load_ps(aPtr); aPtr += 4; aVal2 = _mm_load_ps(aPtr); aPtr += 4; aVal3 = _mm_load_ps(aPtr); aPtr += 4; aVal4 = _mm_load_ps(aPtr); aPtr += 4; bVal1 = _mm_load_ps(bPtr); bPtr += 4; bVal2 = _mm_load_ps(bPtr); bPtr += 4; bVal3 = _mm_load_ps(bPtr); bPtr += 4; bVal4 = _mm_load_ps(bPtr); bPtr += 4; cVal1 = _mm_dp_ps(aVal1, bVal1, 0xF1); cVal2 = _mm_dp_ps(aVal2, bVal2, 0xF2); cVal3 = _mm_dp_ps(aVal3, bVal3, 0xF4); cVal4 = _mm_dp_ps(aVal4, bVal4, 0xF8); cVal1 = _mm_or_ps(cVal1, cVal2); cVal3 = _mm_or_ps(cVal3, cVal4); cVal1 = _mm_or_ps(cVal1, cVal3); dotProdVal = _mm_add_ps(dotProdVal, cVal1); } __VOLK_ATTR_ALIGNED(16) float dotProductVector[4]; _mm_store_ps(dotProductVector, dotProdVal); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; number = sixteenthPoints * 16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_SSE4_1*/ #ifdef LV_HAVE_AVX #include static inline void volk_32f_x2_dot_prod_32f_a_avx( float* result, const float* input, const float* taps, unsigned int num_points) { unsigned int number = 0; const unsigned int sixteenthPoints = num_points / 16; float dotProduct = 0; const float* aPtr = input; const float* bPtr = taps; __m256 a0Val, a1Val; __m256 b0Val, b1Val; __m256 c0Val, c1Val; __m256 dotProdVal0 = _mm256_setzero_ps(); __m256 dotProdVal1 = _mm256_setzero_ps(); for(;number < sixteenthPoints; number++){ a0Val = _mm256_load_ps(aPtr); a1Val = _mm256_load_ps(aPtr+8); b0Val = _mm256_load_ps(bPtr); b1Val = _mm256_load_ps(bPtr+8); c0Val = _mm256_mul_ps(a0Val, b0Val); c1Val = _mm256_mul_ps(a1Val, b1Val); dotProdVal0 = _mm256_add_ps(c0Val, dotProdVal0); dotProdVal1 = _mm256_add_ps(c1Val, dotProdVal1); aPtr += 16; bPtr += 16; } dotProdVal0 = _mm256_add_ps(dotProdVal0, dotProdVal1); __VOLK_ATTR_ALIGNED(32) float dotProductVector[8]; _mm256_store_ps(dotProductVector,dotProdVal0); // Store the results back into the dot product vector dotProduct = dotProductVector[0]; dotProduct += dotProductVector[1]; dotProduct += dotProductVector[2]; dotProduct += dotProductVector[3]; dotProduct += dotProductVector[4]; dotProduct += dotProductVector[5]; dotProduct += dotProductVector[6]; dotProduct += dotProductVector[7]; number = sixteenthPoints*16; for(;number < num_points; number++){ dotProduct += ((*aPtr++) * (*bPtr++)); } *result = dotProduct; } #endif /*LV_HAVE_AVX*/ #endif /*INCLUDED_volk_32f_x2_dot_prod_32f_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_x2_multiply_conjugate_32fc.h0000664000175000017500000001342112207440367026110 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_x2_multiply_conjugate_32fc_u_H #define INCLUDED_volk_32fc_x2_multiply_conjugate_32fc_u_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Multiplies vector a by the conjugate of vector b and stores the results in the third vector \param cVector The vector where the results will be stored \param aVector First vector to be multiplied \param bVector Second vector that is conjugated before being multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_conjugate_32fc_u_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x, y, yl, yh, z, tmp1, tmp2; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; const lv_32fc_t* b = bVector; __m128 conjugator = _mm_setr_ps(0, -0.f, 0, -0.f); for(;number < halfPoints; number++){ x = _mm_loadu_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi y = _mm_loadu_ps((float*)b); // Load the cr + ci, dr + di as cr,ci,dr,di y = _mm_xor_ps(y, conjugator); // conjugate y yl = _mm_moveldup_ps(y); // Load yl with cr,cr,dr,dr yh = _mm_movehdup_ps(y); // Load yh with ci,ci,di,di tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di _mm_storeu_ps((float*)c,z); // Store the results back into the C container a += 2; b += 2; c += 2; } if((num_points % 2) != 0) { *c = (*a) * lv_conj(*b); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies vector a by the conjugate of vector b and stores the results in the third vector \param cVector The vector where the results will be stored \param aVector First vector to be multiplied \param bVector Second vector that is conjugated before being multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_conjugate_32fc_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; const lv_32fc_t* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * lv_conj(*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_x2_multiply_conjugate_32fc_u_H */ #ifndef INCLUDED_volk_32fc_x2_multiply_conjugate_32fc_a_H #define INCLUDED_volk_32fc_x2_multiply_conjugate_32fc_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Multiplies vector a by the conjugate of vector b and stores the results in the third vector \param cVector The vector where the results will be stored \param aVector First vector to be multiplied \param bVector Second vector that is conjugated before being multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_conjugate_32fc_a_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x, y, yl, yh, z, tmp1, tmp2; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; const lv_32fc_t* b = bVector; __m128 conjugator = _mm_setr_ps(0, -0.f, 0, -0.f); for(;number < halfPoints; number++){ x = _mm_load_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi y = _mm_load_ps((float*)b); // Load the cr + ci, dr + di as cr,ci,dr,di y = _mm_xor_ps(y, conjugator); // conjugate y yl = _mm_moveldup_ps(y); // Load yl with cr,cr,dr,dr yh = _mm_movehdup_ps(y); // Load yh with ci,ci,di,di tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di _mm_store_ps((float*)c,z); // Store the results back into the C container a += 2; b += 2; c += 2; } if((num_points % 2) != 0) { *c = (*a) * lv_conj(*b); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies vector a by the conjugate of vector b and stores the results in the third vector \param cVector The vector where the results will be stored \param aVector First vector to be multiplied \param bVector Second vector that is conjugated before being multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_conjugate_32fc_a_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; const lv_32fc_t* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * lv_conj(*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_x2_multiply_conjugate_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32f_x2_power_spectral_density_32f.h0000664000175000017500000001117312207440367027456 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32f_x2_power_spectral_density_32f_a_H #define INCLUDED_volk_32fc_s32f_x2_power_spectral_density_32f_a_H #include #include #include #ifdef LV_HAVE_SSE3 #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief Calculates the log10 power value divided by the RBW for each input point \param logPowerOutput The 10.0 * log10((r*r + i*i)/RBW) for each data point \param complexFFTInput The complex data output from the FFT point \param normalizationFactor This value is divided against all the input values before the power is calculated \param rbw The resolution bandwith of the fft spectrum \param num_points The number of fft data points */ static inline void volk_32fc_s32f_x2_power_spectral_density_32f_a_sse3(float* logPowerOutput, const lv_32fc_t* complexFFTInput, const float normalizationFactor, const float rbw, unsigned int num_points){ const float* inputPtr = (const float*)complexFFTInput; float* destPtr = logPowerOutput; uint64_t number = 0; const float iRBW = 1.0 / rbw; const float iNormalizationFactor = 1.0 / normalizationFactor; #ifdef LV_HAVE_LIB_SIMDMATH __m128 magScalar = _mm_set_ps1(10.0); magScalar = _mm_div_ps(magScalar, logf4(magScalar)); __m128 invRBW = _mm_set_ps1(iRBW); __m128 invNormalizationFactor = _mm_set_ps1(iNormalizationFactor); __m128 power; __m128 input1, input2; const uint64_t quarterPoints = num_points / 4; for(;number < quarterPoints; number++){ // Load the complex values input1 =_mm_load_ps(inputPtr); inputPtr += 4; input2 =_mm_load_ps(inputPtr); inputPtr += 4; // Apply the normalization factor input1 = _mm_mul_ps(input1, invNormalizationFactor); input2 = _mm_mul_ps(input2, invNormalizationFactor); // Multiply each value by itself // (r1*r1), (i1*i1), (r2*r2), (i2*i2) input1 = _mm_mul_ps(input1, input1); // (r3*r3), (i3*i3), (r4*r4), (i4*i4) input2 = _mm_mul_ps(input2, input2); // Horizontal add, to add (r*r) + (i*i) for each complex value // (r1*r1)+(i1*i1), (r2*r2) + (i2*i2), (r3*r3)+(i3*i3), (r4*r4)+(i4*i4) power = _mm_hadd_ps(input1, input2); // Divide by the rbw power = _mm_mul_ps(power, invRBW); // Calculate the natural log power power = logf4(power); // Convert to log10 and multiply by 10.0 power = _mm_mul_ps(power, magScalar); // Store the floating point results _mm_store_ps(destPtr, power); destPtr += 4; } number = quarterPoints*4; #endif /* LV_HAVE_LIB_SIMDMATH */ // Calculate the FFT for any remaining points for(; number < num_points; number++){ // Calculate dBm // 50 ohm load assumption // 10 * log10 (v^2 / (2 * 50.0 * .001)) = 10 * log10( v^2 * 10) // 75 ohm load assumption // 10 * log10 (v^2 / (2 * 75.0 * .001)) = 10 * log10( v^2 * 15) const float real = *inputPtr++ * iNormalizationFactor; const float imag = *inputPtr++ * iNormalizationFactor; *destPtr = 10.0*log10f((((real * real) + (imag * imag)) + 1e-20) * iRBW); destPtr++; } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the log10 power value divided by the RBW for each input point \param logPowerOutput The 10.0 * log10((r*r + i*i)/RBW) for each data point \param complexFFTInput The complex data output from the FFT point \param normalizationFactor This value is divided against all the input values before the power is calculated \param rbw The resolution bandwith of the fft spectrum \param num_points The number of fft data points */ static inline void volk_32fc_s32f_x2_power_spectral_density_32f_generic(float* logPowerOutput, const lv_32fc_t* complexFFTInput, const float normalizationFactor, const float rbw, unsigned int num_points){ // Calculate the Power of the complex point const float* inputPtr = (float*)complexFFTInput; float* realFFTDataPointsPtr = logPowerOutput; unsigned int point; const float invRBW = 1.0 / rbw; const float iNormalizationFactor = 1.0 / normalizationFactor; for(point = 0; point < num_points; point++){ // Calculate dBm // 50 ohm load assumption // 10 * log10 (v^2 / (2 * 50.0 * .001)) = 10 * log10( v^2 * 10) // 75 ohm load assumption // 10 * log10 (v^2 / (2 * 75.0 * .001)) = 10 * log10( v^2 * 15) const float real = *inputPtr++ * iNormalizationFactor; const float imag = *inputPtr++ * iNormalizationFactor; *realFFTDataPointsPtr = 10.0*log10f((((real * real) + (imag * imag)) + 1e-20) * invRBW); realFFTDataPointsPtr++; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_s32f_x2_power_spectral_density_32f_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32f_power_32fc.h0000664000175000017500000001006212207440367023550 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32f_power_32fc_a_H #define INCLUDED_volk_32fc_s32f_power_32fc_a_H #include #include #include //! raise a complex float to a real float power static inline lv_32fc_t __volk_s32fc_s32f_power_s32fc_a(const lv_32fc_t exp, const float power){ const float arg = power*atan2f(lv_creal(exp), lv_cimag(exp)); const float mag = powf(lv_creal(exp)*lv_creal(exp) + lv_cimag(exp)*lv_cimag(exp), power/2); return mag*lv_cmake(cosf(arg), sinf(arg)); } #ifdef LV_HAVE_SSE #include #ifdef LV_HAVE_LIB_SIMDMATH #include #endif /* LV_HAVE_LIB_SIMDMATH */ /*! \brief Takes each the input complex vector value to the specified power and stores the results in the return vector \param cVector The vector where the results will be stored \param aVector The complex vector of values to be taken to a power \param power The power value to be applied to each data point \param num_points The number of values in aVector to be taken to the specified power level and stored into cVector */ static inline void volk_32fc_s32f_power_32fc_a_sse(lv_32fc_t* cVector, const lv_32fc_t* aVector, const float power, unsigned int num_points){ unsigned int number = 0; lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; #ifdef LV_HAVE_LIB_SIMDMATH const unsigned int quarterPoints = num_points / 4; __m128 vPower = _mm_set_ps1(power); __m128 cplxValue1, cplxValue2, magnitude, phase, iValue, qValue; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps((float*)aPtr); aPtr += 2; cplxValue2 = _mm_load_ps((float*)aPtr); aPtr += 2; // Convert to polar coordinates // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); phase = atan2f4(qValue, iValue); // Calculate the Phase magnitude = _mm_sqrt_ps(_mm_add_ps(_mm_mul_ps(iValue, iValue), _mm_mul_ps(qValue, qValue))); // Calculate the magnitude by square rooting the added I2 and Q2 values // Now calculate the power of the polar coordinate data magnitude = powf4(magnitude, vPower); // Take the magnitude to the specified power phase = _mm_mul_ps(phase, vPower); // Multiply the phase by the specified power // Convert back to cartesian coordinates iValue = _mm_mul_ps( cosf4(phase), magnitude); // Multiply the cos of the phase by the magnitude qValue = _mm_mul_ps( sinf4(phase), magnitude); // Multiply the sin of the phase by the magnitude cplxValue1 = _mm_unpacklo_ps(iValue, qValue); // Interleave the lower two i & q values cplxValue2 = _mm_unpackhi_ps(iValue, qValue); // Interleave the upper two i & q values _mm_store_ps((float*)cPtr,cplxValue1); // Store the results back into the C container cPtr += 2; _mm_store_ps((float*)cPtr,cplxValue2); // Store the results back into the C container cPtr += 2; } number = quarterPoints * 4; #endif /* LV_HAVE_LIB_SIMDMATH */ for(;number < num_points; number++){ *cPtr++ = __volk_s32fc_s32f_power_s32fc_a((*aPtr++), power); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Takes each the input complex vector value to the specified power and stores the results in the return vector \param cVector The vector where the results will be stored \param aVector The complex vector of values to be taken to a power \param power The power value to be applied to each data point \param num_points The number of values in aVector to be taken to the specified power level and stored into cVector */ static inline void volk_32fc_s32f_power_32fc_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const float power, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = __volk_s32fc_s32f_power_s32fc_a((*aPtr++), power); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_s32f_power_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_s32f_magnitude_16i.h0000664000175000017500000001471412207440367024243 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_s32f_magnitude_16i_a_H #define INCLUDED_volk_32fc_s32f_magnitude_16i_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Calculates the magnitude of the complexVector, scales the resulting value and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param scalar The scale value multiplied to the magnitude of each complex vector \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_s32f_magnitude_16i_a_sse3(int16_t* magnitudeVector, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (const float*)complexVector; int16_t* magnitudeVectorPtr = magnitudeVector; __m128 vScalar = _mm_set_ps1(scalar); __m128 cplxValue1, cplxValue2, result; __VOLK_ATTR_ALIGNED(16) float floatBuffer[4]; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue1 = _mm_mul_ps(cplxValue1, cplxValue1); // Square the values cplxValue2 = _mm_mul_ps(cplxValue2, cplxValue2); // Square the Values result = _mm_hadd_ps(cplxValue1, cplxValue2); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); result = _mm_mul_ps(result, vScalar); _mm_store_ps(floatBuffer, result); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[0]); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[1]); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[2]); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[3]); } number = quarterPoints * 4; magnitudeVectorPtr = &magnitudeVector[number]; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (int16_t)(sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)) * scalar); } } #endif /* LV_HAVE_SSE3 */ #ifdef LV_HAVE_SSE #include /*! \brief Calculates the magnitude of the complexVector, scales the resulting value and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param scalar The scale value multiplied to the magnitude of each complex vector \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_s32f_magnitude_16i_a_sse(int16_t* magnitudeVector, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* complexVectorPtr = (const float*)complexVector; int16_t* magnitudeVectorPtr = magnitudeVector; __m128 vScalar = _mm_set_ps1(scalar); __m128 cplxValue1, cplxValue2, iValue, qValue, result; __VOLK_ATTR_ALIGNED(16) float floatBuffer[4]; for(;number < quarterPoints; number++){ cplxValue1 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; cplxValue2 = _mm_load_ps(complexVectorPtr); complexVectorPtr += 4; // Arrange in i1i2i3i4 format iValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(2,0,2,0)); // Arrange in q1q2q3q4 format qValue = _mm_shuffle_ps(cplxValue1, cplxValue2, _MM_SHUFFLE(3,1,3,1)); iValue = _mm_mul_ps(iValue, iValue); // Square the I values qValue = _mm_mul_ps(qValue, qValue); // Square the Q Values result = _mm_add_ps(iValue, qValue); // Add the I2 and Q2 values result = _mm_sqrt_ps(result); result = _mm_mul_ps(result, vScalar); _mm_store_ps(floatBuffer, result); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[0]); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[1]); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[2]); *magnitudeVectorPtr++ = (int16_t)(floatBuffer[3]); } number = quarterPoints * 4; magnitudeVectorPtr = &magnitudeVector[number]; for(; number < num_points; number++){ float val1Real = *complexVectorPtr++; float val1Imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (int16_t)(sqrtf((val1Real * val1Real) + (val1Imag * val1Imag)) * scalar); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Calculates the magnitude of the complexVector, scales the resulting value and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param scalar The scale value multiplied to the magnitude of each complex vector \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ static inline void volk_32fc_s32f_magnitude_16i_generic(int16_t* magnitudeVector, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points){ const float* complexVectorPtr = (float*)complexVector; int16_t* magnitudeVectorPtr = magnitudeVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ const float real = *complexVectorPtr++; const float imag = *complexVectorPtr++; *magnitudeVectorPtr++ = (int16_t)(sqrtf((real*real) + (imag*imag)) * scalar); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Calculates the magnitude of the complexVector, scales the resulting value and stores the results in the magnitudeVector \param complexVector The vector containing the complex input values \param scalar The scale value multiplied to the magnitude of each complex vector \param magnitudeVector The vector containing the real output values \param num_points The number of complex values in complexVector to be calculated and stored into cVector */ extern void volk_32fc_s32f_magnitude_16i_a_orc_impl(int16_t* magnitudeVector, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points); static inline void volk_32fc_s32f_magnitude_16i_u_orc(int16_t* magnitudeVector, const lv_32fc_t* complexVector, const float scalar, unsigned int num_points){ volk_32fc_s32f_magnitude_16i_a_orc_impl(magnitudeVector, complexVector, scalar, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32fc_s32f_magnitude_16i_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_8ic_x2_s32f_multiply_conjugate_32fc.h0000664000175000017500000001061612207440367026676 0ustar jcorganjcorgan#ifndef INCLUDED_volk_8ic_x2_s32f_multiply_conjugate_32fc_a_H #define INCLUDED_volk_8ic_x2_s32f_multiply_conjugate_32fc_a_H #include #include #include #ifdef LV_HAVE_SSE4_1 #include /*! \brief Multiplys the one complex vector with the complex conjugate of the second complex vector and stores their results in the third vector \param cVector The complex vector where the results will be stored \param aVector One of the complex vectors to be multiplied \param bVector The complex vector which will be converted to complex conjugate and multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_8ic_x2_s32f_multiply_conjugate_32fc_a_sse4_1(lv_32fc_t* cVector, const lv_8sc_t* aVector, const lv_8sc_t* bVector, const float scalar, unsigned int num_points){ unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; __m128i x, y, realz, imagz; __m128 ret; lv_32fc_t* c = cVector; const lv_8sc_t* a = aVector; const lv_8sc_t* b = bVector; __m128i conjugateSign = _mm_set_epi16(-1, 1, -1, 1, -1, 1, -1, 1); __m128 invScalar = _mm_set_ps1(1.0/scalar); for(;number < quarterPoints; number++){ // Convert into 8 bit values into 16 bit values x = _mm_cvtepi8_epi16(_mm_loadl_epi64((__m128i*)a)); y = _mm_cvtepi8_epi16(_mm_loadl_epi64((__m128i*)b)); // Calculate the ar*cr - ai*(-ci) portions realz = _mm_madd_epi16(x,y); // Calculate the complex conjugate of the cr + ci j values y = _mm_sign_epi16(y, conjugateSign); // Shift the order of the cr and ci values y = _mm_shufflehi_epi16(_mm_shufflelo_epi16(y, _MM_SHUFFLE(2,3,0,1) ), _MM_SHUFFLE(2,3,0,1)); // Calculate the ar*(-ci) + cr*(ai) imagz = _mm_madd_epi16(x,y); // Interleave real and imaginary and then convert to float values ret = _mm_cvtepi32_ps(_mm_unpacklo_epi32(realz, imagz)); // Normalize the floating point values ret = _mm_mul_ps(ret, invScalar); // Store the floating point values _mm_store_ps((float*)c, ret); c += 2; // Interleave real and imaginary and then convert to float values ret = _mm_cvtepi32_ps(_mm_unpackhi_epi32(realz, imagz)); // Normalize the floating point values ret = _mm_mul_ps(ret, invScalar); // Store the floating point values _mm_store_ps((float*)c, ret); c += 2; a += 4; b += 4; } number = quarterPoints * 4; float* cFloatPtr = (float*)&cVector[number]; int8_t* a8Ptr = (int8_t*)&aVector[number]; int8_t* b8Ptr = (int8_t*)&bVector[number]; for(; number < num_points; number++){ float aReal = (float)*a8Ptr++; float aImag = (float)*a8Ptr++; lv_32fc_t aVal = lv_cmake(aReal, aImag ); float bReal = (float)*b8Ptr++; float bImag = (float)*b8Ptr++; lv_32fc_t bVal = lv_cmake( bReal, -bImag ); lv_32fc_t temp = aVal * bVal; *cFloatPtr++ = lv_creal(temp) / scalar; *cFloatPtr++ = lv_cimag(temp) / scalar; } } #endif /* LV_HAVE_SSE4_1 */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplys the one complex vector with the complex conjugate of the second complex vector and stores their results in the third vector \param cVector The complex vector where the results will be stored \param aVector One of the complex vectors to be multiplied \param bVector The complex vector which will be converted to complex conjugate and multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_8ic_x2_s32f_multiply_conjugate_32fc_generic(lv_32fc_t* cVector, const lv_8sc_t* aVector, const lv_8sc_t* bVector, const float scalar, unsigned int num_points){ unsigned int number = 0; float* cPtr = (float*)cVector; const float invScalar = 1.0 / scalar; int8_t* a8Ptr = (int8_t*)aVector; int8_t* b8Ptr = (int8_t*)bVector; for(number = 0; number < num_points; number++){ float aReal = (float)*a8Ptr++; float aImag = (float)*a8Ptr++; lv_32fc_t aVal = lv_cmake(aReal, aImag ); float bReal = (float)*b8Ptr++; float bImag = (float)*b8Ptr++; lv_32fc_t bVal = lv_cmake( bReal, -bImag ); lv_32fc_t temp = aVal * bVal; *cPtr++ = (lv_creal(temp) * invScalar); *cPtr++ = (lv_cimag(temp) * invScalar); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_8ic_x2_s32f_multiply_conjugate_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_16i_max_star_16i.h0000664000175000017500000000366212207440367023111 0ustar jcorganjcorgan#ifndef INCLUDED_volk_16i_max_star_16i_a_H #define INCLUDED_volk_16i_max_star_16i_a_H #include #include #ifdef LV_HAVE_SSSE3 #include #include #include static inline void volk_16i_max_star_16i_a_ssse3(short* target, short* src0, unsigned int num_points) { const unsigned int num_bytes = num_points*2; short candidate = src0[0]; short cands[8]; __m128i xmm0, xmm1, xmm3, xmm4, xmm5, xmm6; __m128i *p_src0; p_src0 = (__m128i*)src0; int bound = num_bytes >> 4; int leftovers = (num_bytes >> 1) & 7; int i = 0; xmm1 = _mm_setzero_si128(); xmm0 = _mm_setzero_si128(); //_mm_insert_epi16(xmm0, candidate, 0); xmm0 = _mm_shuffle_epi8(xmm0, xmm1); for(i = 0; i < bound; ++i) { xmm1 = _mm_load_si128(p_src0); p_src0 += 1; //xmm2 = _mm_sub_epi16(xmm1, xmm0); xmm3 = _mm_cmpgt_epi16(xmm0, xmm1); xmm4 = _mm_cmpeq_epi16(xmm0, xmm1); xmm5 = _mm_cmpgt_epi16(xmm1, xmm0); xmm6 = _mm_xor_si128(xmm4, xmm5); xmm3 = _mm_and_si128(xmm3, xmm0); xmm4 = _mm_and_si128(xmm6, xmm1); xmm0 = _mm_add_epi16(xmm3, xmm4); } _mm_store_si128((__m128i*)cands, xmm0); for(i = 0; i < 8; ++i) { candidate = ((short)(candidate - cands[i]) > 0) ? candidate : cands[i]; } for(i = 0; i < leftovers; ++i) { candidate = ((short)(candidate - src0[(bound << 3) + i]) > 0) ? candidate : src0[(bound << 3) + i]; } target[0] = candidate; } #endif /*LV_HAVE_SSSE3*/ #ifdef LV_HAVE_GENERIC static inline void volk_16i_max_star_16i_generic(short* target, short* src0, unsigned int num_points) { const unsigned int num_bytes = num_points*2; int i = 0; int bound = num_bytes >> 1; short candidate = src0[0]; for(i = 1; i < bound; ++i) { candidate = ((short)(candidate - src0[i]) > 0) ? candidate : src0[i]; } target[0] = candidate; } #endif /*LV_HAVE_GENERIC*/ #endif /*INCLUDED_volk_16i_max_star_16i_a_H*/ gnuradio-3.7.2.1/volk/kernels/volk/volk_32fc_x2_multiply_32fc.h0000664000175000017500000001424512207440367024056 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32fc_x2_multiply_32fc_u_H #define INCLUDED_volk_32fc_x2_multiply_32fc_u_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_32fc_u_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x, y, yl, yh, z, tmp1, tmp2; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; const lv_32fc_t* b = bVector; for(;number < halfPoints; number++){ x = _mm_loadu_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi y = _mm_loadu_ps((float*)b); // Load the cr + ci, dr + di as cr,ci,dr,di yl = _mm_moveldup_ps(y); // Load yl with cr,cr,dr,dr yh = _mm_movehdup_ps(y); // Load yh with ci,ci,di,di tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di _mm_storeu_ps((float*)c,z); // Store the results back into the C container a += 2; b += 2; c += 2; } if((num_points % 2) != 0) { *c = (*a) * (*b); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_32fc_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; const lv_32fc_t* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32fc_x2_multiply_32fc_u_H */ #ifndef INCLUDED_volk_32fc_x2_multiply_32fc_a_H #define INCLUDED_volk_32fc_x2_multiply_32fc_a_H #include #include #include #include #ifdef LV_HAVE_SSE3 #include /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_32fc_a_sse3(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ unsigned int number = 0; const unsigned int halfPoints = num_points / 2; __m128 x, y, yl, yh, z, tmp1, tmp2; lv_32fc_t* c = cVector; const lv_32fc_t* a = aVector; const lv_32fc_t* b = bVector; for(;number < halfPoints; number++){ x = _mm_load_ps((float*)a); // Load the ar + ai, br + bi as ar,ai,br,bi y = _mm_load_ps((float*)b); // Load the cr + ci, dr + di as cr,ci,dr,di yl = _mm_moveldup_ps(y); // Load yl with cr,cr,dr,dr yh = _mm_movehdup_ps(y); // Load yh with ci,ci,di,di tmp1 = _mm_mul_ps(x,yl); // tmp1 = ar*cr,ai*cr,br*dr,bi*dr x = _mm_shuffle_ps(x,x,0xB1); // Re-arrange x to be ai,ar,bi,br tmp2 = _mm_mul_ps(x,yh); // tmp2 = ai*ci,ar*ci,bi*di,br*di z = _mm_addsub_ps(tmp1,tmp2); // ar*cr-ai*ci, ai*cr+ar*ci, br*dr-bi*di, bi*dr+br*di _mm_store_ps((float*)c,z); // Store the results back into the C container a += 2; b += 2; c += 2; } if((num_points % 2) != 0) { *c = (*a) * (*b); } } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ static inline void volk_32fc_x2_multiply_32fc_a_generic(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ lv_32fc_t* cPtr = cVector; const lv_32fc_t* aPtr = aVector; const lv_32fc_t* bPtr= bVector; unsigned int number = 0; for(number = 0; number < num_points; number++){ *cPtr++ = (*aPtr++) * (*bPtr++); } } #endif /* LV_HAVE_GENERIC */ #ifdef LV_HAVE_ORC /*! \brief Multiplies the two input complex vectors and stores their results in the third vector \param cVector The vector where the results will be stored \param aVector One of the vectors to be multiplied \param bVector One of the vectors to be multiplied \param num_points The number of complex values in aVector and bVector to be multiplied together and stored into cVector */ extern void volk_32fc_x2_multiply_32fc_a_orc_impl(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points); static inline void volk_32fc_x2_multiply_32fc_u_orc(lv_32fc_t* cVector, const lv_32fc_t* aVector, const lv_32fc_t* bVector, unsigned int num_points){ volk_32fc_x2_multiply_32fc_a_orc_impl(cVector, aVector, bVector, num_points); } #endif /* LV_HAVE_ORC */ #endif /* INCLUDED_volk_32fc_x2_multiply_32fc_a_H */ gnuradio-3.7.2.1/volk/kernels/volk/volk_32f_accumulator_s32f.h0000664000175000017500000000367312207440367023765 0ustar jcorganjcorgan#ifndef INCLUDED_volk_32f_accumulator_s32f_a_H #define INCLUDED_volk_32f_accumulator_s32f_a_H #include #include #include #ifdef LV_HAVE_SSE #include /*! \brief Accumulates the values in the input buffer \param result The accumulated result \param inputBuffer The buffer of data to be accumulated \param num_points The number of values in inputBuffer to be accumulated */ static inline void volk_32f_accumulator_s32f_a_sse(float* result, const float* inputBuffer, unsigned int num_points){ float returnValue = 0; unsigned int number = 0; const unsigned int quarterPoints = num_points / 4; const float* aPtr = inputBuffer; __VOLK_ATTR_ALIGNED(16) float tempBuffer[4]; __m128 accumulator = _mm_setzero_ps(); __m128 aVal = _mm_setzero_ps(); for(;number < quarterPoints; number++){ aVal = _mm_load_ps(aPtr); accumulator = _mm_add_ps(accumulator, aVal); aPtr += 4; } _mm_store_ps(tempBuffer,accumulator); // Store the results back into the C container returnValue = tempBuffer[0]; returnValue += tempBuffer[1]; returnValue += tempBuffer[2]; returnValue += tempBuffer[3]; number = quarterPoints * 4; for(;number < num_points; number++){ returnValue += (*aPtr++); } *result = returnValue; } #endif /* LV_HAVE_SSE */ #ifdef LV_HAVE_GENERIC /*! \brief Accumulates the values in the input buffer \param result The accumulated result \param inputBuffer The buffer of data to be accumulated \param num_points The number of values in inputBuffer to be accumulated */ static inline void volk_32f_accumulator_s32f_generic(float* result, const float* inputBuffer, unsigned int num_points){ const float* aPtr = inputBuffer; unsigned int number = 0; float returnValue = 0; for(;number < num_points; number++){ returnValue += (*aPtr++); } *result = returnValue; } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_32f_accumulator_s32f_a_H */ gnuradio-3.7.2.1/volk/kernels/README.txt0000664000175000017500000000504012207440367017444 0ustar jcorganjcorgan######################################################################## # How to create custom kernel dispatchers ######################################################################## A kernel dispatcher is kernel implementation that calls other kernel implementations. By default, a dispatcher is generated by the build system for every kernel such that: * the best aligned implemention is called when all pointer arguments are aligned, * and otherwise the best unaligned implementation is called. The author of a VOLK kernel may create a custom dispatcher, to be called in place of the automatically generated one. A custom dispatcher may be useful to handle head and tail cases, or to implement different alignment and bounds checking logic. ######################################################################## # Code for an example dispatcher w/ tail case ######################################################################## #include #ifdef LV_HAVE_DISPATCHER static inline void volk_32f_x2_add_32f_dispatcher(float* cVector, const float* aVector, const float* bVector, unsigned int num_points) { const unsigned int num_points_r = num_points%4; const unsigned int num_points_x = num_points - num_points_r; if (volk_is_aligned(VOLK_OR_PTR(cVector, VOLK_OR_PTR(aVector, bVector)))) { volk_32f_x2_add_32f_a(cVector, aVector, bVector, num_points_x); } else { volk_32f_x2_add_32f_u(cVector, aVector, bVector, num_points_x); } volk_32f_x2_add_32f_g(cVector+num_points_x, aVector+num_points_x, bVector+num_points_x, num_points_r); } #endif //LV_HAVE_DISPATCHER ######################################################################## # Code for an example dispatcher w/ tail case and accumulator ######################################################################## #include #ifdef LV_HAVE_DISPATCHER static inline void volk_32f_x2_dot_prod_32f_dispatcher(float * result, const float * input, const float * taps, unsigned int num_points) { const unsigned int num_points_r = num_points%16; const unsigned int num_points_x = num_points - num_points_r; if (volk_is_aligned(VOLK_OR_PTR(input, taps))) { volk_32f_x2_dot_prod_32f_a(result, input, taps, num_points_x); } else { volk_32f_x2_dot_prod_32f_u(result, input, taps, num_points_x); } float result_tail = 0; volk_32f_x2_dot_prod_32f_g(&result_tail, input+num_points_x, taps+num_points_x, num_points_r); *result += result_tail; } #endif //LV_HAVE_DISPATCHER gnuradio-3.7.2.1/volk/orc/0000755000175000017500000000000012243165260015061 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/orc/volk_32fc_s32fc_multiply_32fc_a_orc_impl.orc0000644000175000017500000000055611700377701025326 0ustar jcorganjcorgan.function volk_32fc_s32fc_multiply_32fc_a_orc_impl .source 8 src1 .floatparam 8 scalar .dest 8 dst .temp 8 iqprod .temp 4 real .temp 4 imag .temp 4 ac .temp 4 bd .temp 8 swapped x2 mulf iqprod, src1, scalar splitql bd, ac, iqprod subf real, ac, bd swaplq swapped, src1 x2 mulf iqprod, swapped, scalar splitql bd, ac, iqprod addf imag, ac, bd mergelq dst, real, imag gnuradio-3.7.2.1/volk/orc/volk_16u_byteswap_a_orc_impl.orc0000644000175000017500000000010211700377701023331 0ustar jcorganjcorgan.function volk_16u_byteswap_a_orc_impl .dest 2 dst swapw dst, dst gnuradio-3.7.2.1/volk/orc/volk_32i_x2_and_32i_a_orc_impl.orc0000644000175000017500000000015011700377701023310 0ustar jcorganjcorgan.function volk_32i_x2_and_32i_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 andl dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_32fc_32f_multiply_32fc_a_orc_impl.orc0000644000175000017500000000022611700377701024772 0ustar jcorganjcorgan.function volk_32fc_32f_multiply_32fc_a_orc_impl .source 8 src1 .source 4 src2 .dest 8 dst .temp 8 tmp mergelq tmp, src2, src2 x2 mulf dst, src1, tmp gnuradio-3.7.2.1/volk/orc/volk_16ic_deinterleave_16i_x2_a_orc_impl.orc0000644000175000017500000000016311700377701025370 0ustar jcorganjcorgan.function volk_16ic_deinterleave_16i_x2_a_orc_impl .dest 2 idst .dest 2 qdst .source 4 src splitlw qdst, idst, src gnuradio-3.7.2.1/volk/orc/volk_8i_convert_16i_a_orc_impl.orc0000644000175000017500000000016111706067166023553 0ustar jcorganjcorgan.function volk_8i_convert_16i_a_orc_impl .source 1 src .dest 2 dst .temp 2 tmp convsbw tmp, src shlw dst, tmp, 8 gnuradio-3.7.2.1/volk/orc/volk_32f_x2_dot_prod_32f_a_orc_impl.orc0000644000175000017500000000020211700377701024350 0ustar jcorganjcorgan.function volk_32f_x2_dot_prod_32f_a_orc_impl .source 4 src1 .source 4 src2 .dest 4 dst .accumulator 4 accum addf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_16ic_magnitude_16i_a_orc_impl.orc0000644000175000017500000000063211702117406024262 0ustar jcorganjcorgan.function volk_16ic_magnitude_16i_a_orc_impl .source 4 src .dest 2 dst .floatparam 4 scalar .temp 8 iql .temp 8 iqf .temp 8 prodiqf .temp 4 qf .temp 4 if .temp 4 sumf .temp 4 rootf .temp 4 rootl x2 convswl iql, src x2 convlf iqf, iql x2 divf iqf, iqf, scalar x2 mulf prodiqf, iqf, iqf splitql qf, if, prodiqf addf sumf, if, qf sqrtf rootf, sumf mulf rootf, rootf, scalar convfl rootl, rootf convlw dst, rootl gnuradio-3.7.2.1/volk/orc/volk_32fc_x2_multiply_32fc_a_orc_impl.orc0000644000175000017500000000054111700377701024731 0ustar jcorganjcorgan.function volk_32fc_x2_multiply_32fc_a_orc_impl .source 8 src1 .source 8 src2 .dest 8 dst .temp 8 iqprod .temp 4 real .temp 4 imag .temp 4 ac .temp 4 bd .temp 8 swapped x2 mulf iqprod, src1, src2 splitql bd, ac, iqprod subf real, ac, bd swaplq swapped, src1 x2 mulf iqprod, swapped, src2 splitql bd, ac, iqprod addf imag, ac, bd mergelq dst, real, imag gnuradio-3.7.2.1/volk/orc/volk_32f_x2_add_32f_a_orc_impl.orc0000644000175000017500000000015011700377701023270 0ustar jcorganjcorgan.function volk_32f_x2_add_32f_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 addf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_32f_s32f_multiply_32f_a_orc_impl.orc0000644000175000017500000000016711700377701024653 0ustar jcorganjcorgan.function volk_32f_s32f_multiply_32f_a_orc_impl .dest 4 dst .source 4 src1 .floatparam 4 scalar mulf dst, src1, scalar gnuradio-3.7.2.1/volk/orc/volk_32f_x2_divide_32f_a_orc_impl.orc0000644000175000017500000000015311700377701024007 0ustar jcorganjcorgan.function volk_32f_x2_divide_32f_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 divf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_16sc_magnitude_32f_aligned16_orc_impl.orc0000644000175000017500000000067211702117406025625 0ustar jcorganjcorgan.function volk_16ic_magnitude_32f_a_orc_impl .source 4 src .dest 4 dst .floatparam 4 scalar .temp 4 reall .temp 4 imagl .temp 2 reals .temp 2 imags .temp 4 realf .temp 4 imagf .temp 4 sumf splitlw reals, imags, src convswl reall, reals convswl imagl, imags convlf realf, reall convlf imagf, imagl divf realf, realf, scalar divf imagf, imagf, scalar mulf realf, realf, realf mulf imagf, imagf, imagf addf sumf, realf, imagf sqrtf dst, sumf gnuradio-3.7.2.1/volk/orc/volk_32f_x2_min_32f_a_orc_impl.orc0000644000175000017500000000015011700377701023323 0ustar jcorganjcorgan.function volk_32f_x2_min_32f_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 minf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_16ic_deinterleave_real_8i_a_orc_impl.orc0000644000175000017500000000017311700377701025704 0ustar jcorganjcorgan.function volk_16ic_deinterleave_real_8i_a_orc_impl .dest 1 dst .source 4 src .temp 2 iw select0lw iw, src convhwb dst, iw gnuradio-3.7.2.1/volk/orc/volk_32f_x2_multiply_32f_a_orc_impl.orc0000644000175000017500000000015511700377701024424 0ustar jcorganjcorgan.function volk_32f_x2_multiply_32f_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 mulf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_32fc_magnitude_32f_a_orc_impl.orc0000644000175000017500000000033311702117406024246 0ustar jcorganjcorgan.function volk_32fc_magnitude_32f_a_orc_impl .source 8 src .dest 4 dst .temp 8 iqf .temp 8 prodiqf .temp 4 qf .temp 4 if .temp 4 sumf x2 mulf prodiqf, src, src splitql qf, if, prodiqf addf sumf, if, qf sqrtf dst, sumf gnuradio-3.7.2.1/volk/orc/volk_32f_s32f_normalize_a_orc_impl.orc0000644000175000017500000000017211700377701024316 0ustar jcorganjcorgan.function volk_32f_s32f_normalize_a_orc_impl .source 4 src1 .floatparam 4 invscalar .dest 4 dst mulf dst, src1, invscalar gnuradio-3.7.2.1/volk/orc/volk_32f_x2_subtract_32f_a_orc_impl.orc0000644000175000017500000000015511700377701024374 0ustar jcorganjcorgan.function volk_32f_x2_subtract_32f_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 subf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_8i_s32f_convert_32f_a_orc_impl.orc0000644000175000017500000000032511700377701024376 0ustar jcorganjcorgan.function volk_8i_s32f_convert_32f_a_orc_impl .source 1 src .dest 4 dst .floatparam 4 scalar .temp 4 flsrc .temp 4 lsrc .temp 2 ssrc convsbw ssrc, src convswl lsrc, ssrc convlf flsrc, lsrc mulf dst, flsrc, scalar gnuradio-3.7.2.1/volk/orc/volk_32fc_s32f_magnitude_16i_a_orc_impl.orc0000644000175000017500000000067311702117406025117 0ustar jcorganjcorgan.function volk_32fc_s32f_magnitude_16i_a_orc_impl .source 8 src .dest 2 dst .floatparam 4 scalar .temp 8 iqf .temp 8 prodiqf .temp 4 qf .temp 4 if .temp 4 sumf .temp 4 rootf .temp 4 rootl #.temp 4 maskl x2 mulf prodiqf, src, src splitql qf, if, prodiqf addf sumf, if, qf sqrtf rootf, sumf mulf rootf, rootf, scalar #cmpltf maskl, 32768.0, rootf #andl maskl, maskl, 0x80000000 #orl rootf, rootf, maskl convfl rootl, rootf convsuslw dst, rootl gnuradio-3.7.2.1/volk/orc/volk_16ic_s32f_deinterleave_32f_x2_a_orc_impl.orc0000664000175000017500000000034612243165260026223 0ustar jcorganjcorgan.function volk_16ic_s32f_deinterleave_32f_x2_a_orc_impl .dest 4 idst .dest 4 qdst .source 4 src .floatparam 4 scalar .temp 8 iql .temp 8 iqf x2 convswl iql, src x2 convlf iqf, iql x2 divf iqf, iqf, scalar splitql qdst, idst, iqf gnuradio-3.7.2.1/volk/orc/volk_32f_x2_max_32f_a_orc_impl.orc0000644000175000017500000000015011700377701023325 0ustar jcorganjcorgan.function volk_32f_x2_max_32f_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 maxf dst, src1, src2 gnuradio-3.7.2.1/volk/orc/volk_32f_sqrt_32f_a_orc_impl.orc0000644000175000017500000000012011702117406023111 0ustar jcorganjcorgan.function volk_32f_sqrt_32f_a_orc_impl .source 4 src .dest 4 dst sqrtf dst, src gnuradio-3.7.2.1/volk/orc/volk_32i_x2_or_32i_a_orc_impl.orc0000644000175000017500000000014611700377701023173 0ustar jcorganjcorgan.function volk_32i_x2_or_32i_a_orc_impl .dest 4 dst .source 4 src1 .source 4 src2 orl dst, src1, src2 gnuradio-3.7.2.1/volk/python/0000775000175000017500000000000012207440367015625 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/python/volk_modtool/0000775000175000017500000000000012207440367020335 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/python/volk_modtool/CMakeLists.txt0000664000175000017500000000232512207440367023077 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install python files and apps ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py cfg.py volk_modtool_generate.py DESTINATION ${GR_PYTHON_DIR}/volk_modtool COMPONENT "volk" ) GR_PYTHON_INSTALL( PROGRAMS volk_modtool DESTINATION ${GR_RUNTIME_DIR} COMPONENT "volk" ) gnuradio-3.7.2.1/volk/python/volk_modtool/volk_modtool_generate.py0000664000175000017500000003227512207440367025302 0ustar jcorganjcorgan# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os import sys import re import glob import shutil import exceptions from sets import Set class volk_modtool: def __init__(self, cfg): self.volk = re.compile('volk'); self.remove_after_underscore = re.compile("_.*"); self.volk_run_tests = re.compile('^\s*VOLK_RUN_TESTS.*\n', re.MULTILINE); self.volk_profile = re.compile('^\s*(VOLK_PROFILE|VOLK_PUPPET_PROFILE).*\n', re.MULTILINE); self.my_dict = cfg; self.lastline = re.compile('\s*char path\[1024\];.*'); self.badassert = re.compile('^\s*assert\(toked\[0\] == "volk_.*\n', re.MULTILINE); self.goodassert = ' assert(toked[0] == "volk");\n' self.baderase = re.compile('^\s*toked.erase\(toked.begin\(\)\);.*\n', re.MULTILINE); self.gooderase = ' toked.erase(toked.begin());\n toked.erase(toked.begin());\n'; def get_basename(self, base=None): if not base: base = self.my_dict['base'] candidate = base.split('/')[-1]; if len(candidate.split('_')) == 1: return ''; else: return candidate.split('_')[-1]; def get_current_kernels(self, base=None): if not base: base = self.my_dict['base'] name = self.get_basename(); else: name = self.get_basename(base); if name == '': hdr_files = glob.glob(os.path.join(base, "kernels/volk/*.h")); begins = re.compile("(?<=volk_).*") else: hdr_files = glob.glob(os.path.join(base, "kernels/volk_" + name + "/*.h")); begins = re.compile("(?<=volk_" + name + "_).*") datatypes = []; functions = []; for line in hdr_files: subline = re.search(".*\.h.*", os.path.basename(line)) if subline: subsubline = begins.search(subline.group(0)); if subsubline: dtype = self.remove_after_underscore.sub("", subsubline.group(0)); subdtype = re.search("[0-9]+[A-z]+", dtype); if subdtype: datatypes.append(subdtype.group(0)); datatypes = set(datatypes); for line in hdr_files: for dt in datatypes: if dt in line: #subline = re.search("(?<=volk_)" + dt + ".*(?=\.h)", line); subline = re.search(begins.pattern[:-2] + dt + ".*(?=\.h)", line); if subline: functions.append(subline.group(0)); return set(functions); def make_module_skeleton(self): dest = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name']) if os.path.exists(dest): raise exceptions.IOError("Destination %s already exits!"%(dest)); if not os.path.exists(os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'kernels/volk_' + self.my_dict['name'])): os.makedirs(os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'kernels/volk_' + self.my_dict['name'])) current_kernel_names = self.get_current_kernels(); for root, dirnames, filenames in os.walk(self.my_dict['base']): for name in filenames: t_table = map(lambda a: re.search(a, name), current_kernel_names); t_table = set(t_table); if t_table == set([None]): infile = os.path.join(root, name); instring = open(infile, 'r').read(); outstring = re.sub(self.volk, 'volk_' + self.my_dict['name'], instring); newname = re.sub(self.volk, 'volk_' + self.my_dict['name'], name); relpath = os.path.relpath(infile, self.my_dict['base']); newrelpath = re.sub(self.volk, 'volk_' + self.my_dict['name'], relpath); dest = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], os.path.dirname(newrelpath), newname); if not os.path.exists(os.path.dirname(dest)): os.makedirs(os.path.dirname(dest)) open(dest, 'w+').write(outstring); infile = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'lib/testqa.cc'); instring = open(infile, 'r').read(); outstring = re.sub(self.volk_run_tests, '', instring); open(infile, 'w+').write(outstring); infile = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'apps/volk_' + self.my_dict['name'] + '_profile.cc'); instring = open(infile, 'r').read(); outstring = re.sub(self.volk_profile, '', instring); open(infile, 'w+').write(outstring); infile = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'lib/qa_utils.cc'); instring = open(infile, 'r').read(); outstring = re.sub(self.badassert, self.goodassert, instring); outstring = re.sub(self.baderase, self.gooderase, outstring); open(infile, 'w+').write(outstring); def write_default_cfg(self, cfg): outfile = open(os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'volk_modtool.cfg'), 'wb'); cfg.write(outfile); outfile.close(); def convert_kernel(self, oldvolk, name, base, inpath, top): infile = os.path.join(inpath, 'kernels/' + top[:-1] + '/' + top + name + '.h'); instring = open(infile, 'r').read(); outstring = re.sub(oldvolk, 'volk_' + self.my_dict['name'], instring); newname = 'volk_' + self.my_dict['name'] + '_' + name + '.h'; relpath = os.path.relpath(infile, base); newrelpath = re.sub(oldvolk, 'volk_' + self.my_dict['name'], relpath); dest = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], os.path.dirname(newrelpath), newname); if not os.path.exists(os.path.dirname(dest)): os.makedirs(os.path.dirname(dest)) open(dest, 'w+').write(outstring); def remove_kernel(self, name): basename = self.my_dict['name']; if len(basename) > 0: top = 'volk_' + basename + '_'; else: top = 'volk_' base = os.path.join(self.my_dict['destination'], top[:-1]) ; if not name in self.get_current_kernels(): raise exceptions.IOError("Requested kernel %s is not in module %s"%(name,base)); inpath = os.path.abspath(base); kernel = re.compile(name) search_kernels = Set([kernel]) profile = re.compile('^\s*VOLK_PROFILE') puppet = re.compile('^\s*VOLK_PUPPET') src_dest = os.path.join(inpath, 'apps/', top[:-1] + '_profile.cc'); infile = open(src_dest); otherlines = infile.readlines(); open(src_dest, 'w+').write(''); for otherline in otherlines: write_okay = True; if kernel.search(otherline): write_okay = False; if puppet.match(otherline): args = re.search("(?<=VOLK_PUPPET_PROFILE).*", otherline) m_func = args.group(0).split(',')[0]; func = re.search('(?<=' + top + ').*', m_func); search_kernels.add(re.compile(func.group(0))); if write_okay: open(src_dest, 'a').write(otherline); src_dest = os.path.join(inpath, 'lib/testqa.cc') infile = open(src_dest); otherlines = infile.readlines(); open(src_dest, 'w+').write(''); for otherline in otherlines: write_okay = True; for kernel in search_kernels: if kernel.search(otherline): write_okay = False; if write_okay: open(src_dest, 'a').write(otherline); for kernel in search_kernels: infile = os.path.join(inpath, 'kernels/' + top[:-1] + '/' + top + kernel.pattern + '.h'); print "Removing kernel %s"%(kernel.pattern) if os.path.exists(infile): os.remove(infile); def import_kernel(self, name, base): if not (base): base = self.my_dict['base']; basename = self.getbasename(); else: basename = self.get_basename(base); if not name in self.get_current_kernels(base): raise exceptions.IOError("Requested kernel %s is not in module %s"%(name,base)); inpath = os.path.abspath(base); if len(basename) > 0: top = 'volk_' + basename + '_'; else: top = 'volk_' oldvolk = re.compile(top[:-1]); self.convert_kernel(oldvolk, name, base, inpath, top); kernel = re.compile(name) search_kernels = Set([kernel]) profile = re.compile('^\s*VOLK_PROFILE') puppet = re.compile('^\s*VOLK_PUPPET') infile = open(os.path.join(inpath, 'apps/', oldvolk.pattern + '_profile.cc')); otherinfile = open(os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'apps/volk_' + self.my_dict['name'] + '_profile.cc')); dest = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'apps/volk_' + self.my_dict['name'] + '_profile.cc'); lines = infile.readlines(); otherlines = otherinfile.readlines(); open(dest, 'w+').write(''); insert = False; inserted = False for otherline in otherlines: if self.lastline.match(otherline): insert = True; if insert and not inserted: inserted = True; for line in lines: if kernel.search(line): if profile.match(line): outline = re.sub(oldvolk, 'volk_' + self.my_dict['name'], line); open(dest, 'a').write(outline); elif puppet.match(line): outline = re.sub(oldvolk, 'volk_' + self.my_dict['name'], line); open(dest, 'a').write(outline); args = re.search("(?<=VOLK_PUPPET_PROFILE).*", line) m_func = args.group(0).split(',')[0]; func = re.search('(?<=' + top + ').*', m_func); search_kernels.add(re.compile(func.group(0))); self.convert_kernel(oldvolk, func.group(0), base, inpath, top); write_okay = True; for kernel in search_kernels: if kernel.search(otherline): write_okay = False if write_okay: open(dest, 'a').write(otherline); for kernel in search_kernels: print "Adding kernel %s from module %s"%(kernel.pattern,base) infile = open(os.path.join(inpath, 'lib/testqa.cc')); otherinfile = open(os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'lib/testqa.cc')); dest = os.path.join(self.my_dict['destination'], 'volk_' + self.my_dict['name'], 'lib/testqa.cc'); lines = infile.readlines(); otherlines = otherinfile.readlines(); open(dest, 'w+').write(''); inserted = False; insert = False for otherline in otherlines: if (re.match('\s*', otherline) == None or re.match('\s*#.*', otherline) == None): insert = True; if insert and not inserted: inserted = True; for line in lines: for kernel in search_kernels: if kernel.search(line): if self.volk_run_tests.match(line): outline = re.sub(oldvolk, 'volk_' + self.my_dict['name'], line); open(dest, 'a').write(outline); write_okay = True; for kernel in search_kernels: if kernel.search(otherline): write_okay = False if write_okay: open(dest, 'a').write(otherline); gnuradio-3.7.2.1/volk/python/volk_modtool/cfg.py0000664000175000017500000000720012207440367021445 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import ConfigParser import sys import os import exceptions import re class volk_modtool_config: def key_val_sub(self, num, stuff, section): return re.sub('\$' + 'k' + str(num), stuff[num][0], (re.sub('\$' + str(num), stuff[num][1], section[1][num]))); def verify(self): for i in self.verification: self.verify_section(i) def remap(self): for i in self.remapification: self.verify_section(i) def verify_section(self, section): stuff = self.cfg.items(section[0]) for i in range(len(section[1])): eval(self.key_val_sub(i, stuff, section)) try: val = eval(self.key_val_sub(i, stuff, section)) if val == False: raise exceptions.ValueError except ValueError: raise exceptions.ValueError('Verification function returns False... key:%s, val:%s'%(stuff[i][0], stuff[i][1])) except: raise exceptions.IOError('bad configuration... key:%s, val:%s'%(stuff[i][0], stuff[i][1])) def __init__(self, cfg=None): self.config_name = 'config' self.config_defaults = ['name', 'destination', 'base'] self.config_defaults_remap = ['1', 'self.cfg.set(self.config_name, \'$k1\', os.path.realpath(os.path.expanduser(\'$1\')))', 'self.cfg.set(self.config_name, \'$k2\', os.path.realpath(os.path.expanduser(\'$2\')))'] self.config_defaults_verify = ['re.match(\'[a-zA-Z0-9]+$\', \'$0\')', 'os.path.exists(\'$1\')', 'os.path.exists(\'$2\')'] self.remapification = [(self.config_name, self.config_defaults_remap)] self.verification = [(self.config_name, self.config_defaults_verify)] default = os.path.join(os.getcwd(), 'volk_modtool.cfg') icfg = ConfigParser.RawConfigParser() if cfg: icfg.read(cfg) elif os.path.exists(default): icfg.read(default) else: print "Initializing config file..." icfg.add_section(self.config_name) for kn in self.config_defaults: rv = raw_input("%s: "%(kn)) icfg.set(self.config_name, kn, rv) self.cfg = icfg self.remap() self.verify() def read_map(self, name, inp): if self.cfg.has_section(name): self.cfg.remove_section(name) self.cfg.add_section(name) for i in inp: self.cfg.set(name, i, inp[i]) def get_map(self, name): retval = {} stuff = self.cfg.items(name) for i in stuff: retval[i[0]] = i[1] return retval gnuradio-3.7.2.1/volk/python/volk_modtool/README0000664000175000017500000001045012207440367021215 0ustar jcorganjcorganThe volk_modtool tool is installed along with VOLK as a way of helping to construct, add to, and interogate the VOLK library or companion libraries. volk_modtool is installed into $prefix/bin. VOLK modtool enables creating standalone (out-of-tree) VOLK modules and provides a few tools for sharing VOLK kernels between VOLK modules. If you need to design or work with VOLK kernels away from the canonical VOLK library, this is the tool. If you need to tailor your own VOLK library for whatever reason, this is the tool. The canonical VOLK library installs a volk.h and a libvolk.so. Your own library will install volk_$name.h and libvolk_$name.so. Ya Gronk? Good. There isn't a substantial difference between the canonical VOLK module and any other VOLK module. They're all peers. Any module created via VOLK modtool will come complete with a default volk_modtool.cfg file associating the module with the base from which it came, its distinctive $name and its destination (or path). These values (created from user input if VOLK modtool runs without a user-supplied config file or a default config file) serve as default values for some VOLK modtool actions. It's more or less intended for the user to change directories to the top level of a created VOLK module and then run volk_modtool to take advantage of the values stored in the default volk_modtool.cfg file. Apart from creating new VOLK modules, VOLK modtool allows you to list the names of kernels in other modules, list the names of kernels in the current module, add kernels from another module into the current module, and remove kernels from the current module. When moving kernels between modules, VOLK modtool does its best to keep the qa and profiling code for those kernels intact. If the base has a test or a profiling call for some kernel, those calls will follow the kernel when VOLK modtool adds that kernel. If QA or profiling requires a puppet kernel, the puppet kernel will follow the original kernel when VOLK modtool adds that original kernel. VOLK modtool respects puppets. ====================================================================== Installing a new VOLK Library: Run the command "volk_modtool -i". This will ask you three questions: name: // the name to give your VOLK library: volk_ destination: // directory new source tree is built under -- must exists. // It will create /volk_ base: // the directory containing the original VOLK source code The name provided must be alphanumeric (and cannot start with a number). No special characters including dashes and underscores are allowed. This will build a new skeleton directory in the destination provided with the name volk_. It will contain the necessary structure to build: mkdir build cd build cmake -DCMAKE_INSTALL_PREFIX=/opt/volk ../ make sudo make install Right now, the library is empty and contains no kernels. Kernels can be added from another VOLK library using the '-a' option. If not specified, the kernel will be extracted from the base VOLK directory. Using the '-b' allows us to specify another VOLK library to use for this purpose. volk_modtool -a -n 32fc_x2_conjugate_dot_prod_32fc This will put the code for the new kernel into /volk_/kernels/volk_/ Other kernels must be added by hand. See the following webpages for more information about creating VOLK kernels: http://gnuradio.org/doc/doxygen/volk_guide.html http://gnuradio.org/redmine/projects/gnuradio/wiki/Volk ====================================================================== OPTIONS Options for Adding and Removing Kernels: -a, --add_kernel Add kernel from existing VOLK module. Uses the base VOLK module unless -b is used. Use -n to specify the kernel name. Requires: -n. Optional: -b -A, --add_all_kernels Add all kernels from existing VOLK module. Uses the base VOLK module unless -b is used. Optional: -b -x, --remove_kernel Remove kernel from module. Required: -n. Optional: -b Options for Listing Kernels: -l, --list Lists all kernels available in the base VOLK module. -k, --kernels Lists all kernels in this VOLK module. -r, --remote-list Lists all kernels in another VOLK module that is specified using the -b option. gnuradio-3.7.2.1/volk/python/volk_modtool/volk_modtool0000775000175000017500000001224312207440367022775 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from volk_modtool import volk_modtool, volk_modtool_config from optparse import OptionParser, OptionGroup import exceptions import os import sys if __name__ == '__main__': parser = OptionParser(); actions = OptionGroup(parser, 'Actions'); actions.add_option('-i', '--install', action='store_true', help='Create a new volk module.') parser.add_option('-b', '--base_path', action='store', default=None, help='Base path for action. By default, volk_modtool.cfg loads this value.') parser.add_option('-n', '--kernel_name', action='store', default=None, help='Kernel name for action. No default') parser.add_option('-c', '--config', action='store', dest='config_file', default=None, help='Config file for volk_modtool. By default, volk_modtool.cfg in the local directory will be used/created.') actions.add_option('-a', '--add_kernel', action='store_true', help='Add kernel from existing volk module. Requires: -n. Optional: -b') actions.add_option('-A', '--add_all_kernels', action='store_true', help='Add all kernels from existing volk module. Optional: -b') actions.add_option('-x', '--remove_kernel', action='store_true', help='Remove kernel from module. Required: -n. Optional: -b') actions.add_option('-l', '--list', action='store_true', help='List all kernels in the base.') actions.add_option('-k', '--kernels', action='store_true', help='List all kernels in the module.') actions.add_option('-r', '--remote_list', action='store_true', help='List all available kernels in remote volk module. Requires: -b.') actions.add_option('-m', '--moo', action='store_true', help='Have you mooed today?') parser.add_option_group(actions) (options, args) = parser.parse_args(); if len(sys.argv) < 2: parser.print_help() elif options.moo: print " (__) " print " (oo) " print " /------\/ " print " / | || " print " * /\---/\ " print " ~~ ~~ " else: my_cfg = volk_modtool_config(options.config_file); my_modtool = volk_modtool(my_cfg.get_map(my_cfg.config_name)); if options.install: my_modtool.make_module_skeleton(); my_modtool.write_default_cfg(my_cfg.cfg); if options.add_kernel: if not options.kernel_name: raise exceptions.IOError("This action requires the -n option."); else: name = options.kernel_name; if options.base_path: base = options.base_path; else: base = my_cfg.cfg.get(my_cfg.config_name, 'base'); my_modtool.import_kernel(name, base); if options.remove_kernel: if not options.kernel_name: raise exceptions.IOError("This action requires the -n option."); else: name = options.kernel_name; my_modtool.remove_kernel(name); if options.add_all_kernels: if options.base_path: base = options.base_path; else: base = my_cfg.cfg.get(my_cfg.config_name, 'base'); kernelset = my_modtool.get_current_kernels(base); for i in kernelset: my_modtool.import_kernel(i, base); if options.remote_list: if not options.base_path: raise exceptions.IOError("This action requires the -b option. Try -l or -k for listing kernels in the base or the module.") else: base = options.base_path; kernelset = my_modtool.get_current_kernels(base); for i in kernelset: print i; if options.list: kernelset = my_modtool.get_current_kernels(); for i in kernelset: print i; if options.kernels: dest = my_cfg.cfg.get(my_cfg.config_name, 'destination'); name = my_cfg.cfg.get(my_cfg.config_name, 'name'); base = os.path.join(dest, 'volk_' + name); kernelset = my_modtool.get_current_kernels(base); for i in kernelset: print i; gnuradio-3.7.2.1/volk/python/volk_modtool/__init__.py0000664000175000017500000000157512207440367022456 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from cfg import volk_modtool_config from volk_modtool_generate import volk_modtool gnuradio-3.7.2.1/volk/lib/0000755000175000017500000000000012245160224015041 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/lib/qa_32f_index_max_aligned16.cc0000644000175000017500000000426111744612271022323 0ustar jcorganjcorgan#include #include #include #include #include #include #define ERR_DELTA (1e-4) #define NUM_ITERS 1000000 #define VEC_LEN 3097 static float uniform() { return 2.0 * ((float) rand() / RAND_MAX - 0.5); // uniformly (-1, 1) } static void random_floats (float *buf, unsigned n) { unsigned int i = 0; for (; i < n; i++) { buf[i] = uniform () * 32767; } } #ifndef LV_HAVE_SSE void qa_32f_index_max_aligned16::t1(){ printf("sse not available... no test performed\n"); } #else void qa_32f_index_max_aligned16::t1(){ const int vlen = VEC_LEN; volk_runtime_init(); volk_environment_init(); int ret; unsigned int* target_sse4_1; unsigned int* target_sse; unsigned int* target_generic; float* src0 ; unsigned int i_target_sse4_1; target_sse4_1 = &i_target_sse4_1; unsigned int i_target_sse; target_sse = &i_target_sse; unsigned int i_target_generic; target_generic = &i_target_generic; ret = posix_memalign((void**)&src0, 16, vlen *sizeof(float)); random_floats((float*)src0, vlen); printf("32f_index_max_aligned16\n"); clock_t start, end; double total; start = clock(); for(int k = 0; k < NUM_ITERS; ++k) { volk_32f_index_max_aligned16_manual(target_generic, src0, vlen, "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic time: %f\n", total); start = clock(); for(int k = 0; k < NUM_ITERS; ++k) { volk_32f_index_max_aligned16_manual(target_sse, src0, vlen, "sse2"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse time: %f\n", total); start = clock(); for(int k = 0; k < NUM_ITERS; ++k) { get_volk_runtime()->volk_32f_index_max_aligned16(target_sse4_1, src0, vlen); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse4.1 time: %f\n", total); printf("generic: %u, sse: %u, sse4.1: %u\n", target_generic[0], target_sse[0], target_sse4_1[0]); CPPUNIT_ASSERT_EQUAL(target_generic[0], target_sse[0]); CPPUNIT_ASSERT_EQUAL(target_generic[0], target_sse4_1[0]); free(src0); } #endif /*LV_HAVE_SSE3*/ gnuradio-3.7.2.1/volk/lib/CMakeLists.txt0000664000175000017500000003704412245160224017613 0ustar jcorganjcorgan# # Copyright 2011-2012 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # ######################################################################## # header file detection ######################################################################## include(CheckIncludeFile) CHECK_INCLUDE_FILE(cpuid.h HAVE_CPUID_H) if(HAVE_CPUID_H) add_definitions(-DHAVE_CPUID_H) endif() CHECK_INCLUDE_FILE(intrin.h HAVE_INTRIN_H) if(HAVE_INTRIN_H) add_definitions(-DHAVE_INTRIN_H) endif() CHECK_INCLUDE_FILE(fenv.h HAVE_FENV_H) if(HAVE_FENV_H) add_definitions(-DHAVE_FENV_H) endif() CHECK_INCLUDE_FILE(dlfcn.h HAVE_DLFCN_H) if(HAVE_DLFCN_H) add_definitions(-DHAVE_DLFCN_H) list(APPEND volk_libraries ${CMAKE_DL_LIBS}) endif() ######################################################################## # Setup the compiler name ######################################################################## set(COMPILER_NAME ${CMAKE_C_COMPILER_ID}) if(MSVC) #its not set otherwise set(COMPILER_NAME MSVC) endif() message(STATUS "Compiler name: ${COMPILER_NAME}") if(NOT DEFINED COMPILER_NAME) message(FATAL_ERROR "COMPILER_NAME undefined. Volk build may not support this compiler.") endif() ######################################################################## # Special clang flag so flag checks can fail ######################################################################## if(COMPILER_NAME MATCHES "GNU") include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("-Werror=unused-command-line-argument" HAVE_WERROR_UNUSED_CMD_LINE_ARG) if(HAVE_WERROR_UNUSED_CMD_LINE_ARG) set(VOLK_FLAG_CHECK_FLAGS "-Werror=unused-command-line-argument") endif() endif() ######################################################################## # detect x86 flavor of CPU ######################################################################## if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "^(i.86|x86|x86_64|amd64)$") message(STATUS "x86* CPU detected") set(CPU_IS_x86 TRUE) endif() ######################################################################## # determine passing architectures based on compile flag tests ######################################################################## execute_process( COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_SOURCE_DIR}/gen/volk_compile_utils.py --mode "arch_flags" --compiler "${COMPILER_NAME}" OUTPUT_VARIABLE arch_flag_lines OUTPUT_STRIP_TRAILING_WHITESPACE ) macro(check_arch arch_name) set(flags ${ARGN}) set(have_${arch_name} TRUE) foreach(flag ${flags}) include(CheckCXXCompilerFlag) set(have_flag have${flag}) execute_process( #make the have_flag have nice alphanum chars (just for looks/not necessary) COMMAND ${PYTHON_EXECUTABLE} -c "import re; print(re.sub('\\W', '_', '${have_flag}'))" OUTPUT_VARIABLE have_flag OUTPUT_STRIP_TRAILING_WHITESPACE ) if(VOLK_FLAG_CHECK_FLAGS) set(CMAKE_REQUIRED_FLAGS ${VOLK_FLAG_CHECK_FLAGS}) endif() CHECK_CXX_COMPILER_FLAG(${flag} ${have_flag}) unset(CMAKE_REQUIRED_FLAGS) if (NOT ${have_flag}) set(have_${arch_name} FALSE) endif() endforeach(flag) if (have_${arch_name}) list(APPEND available_archs ${arch_name}) endif() endmacro(check_arch) foreach(line ${arch_flag_lines}) string(REGEX REPLACE "," ";" arch_flags ${line}) check_arch(${arch_flags}) endforeach(line) macro(OVERRULE_ARCH arch reason) message(STATUS "${reason}, Overruled arch ${arch}") list(REMOVE_ITEM available_archs ${arch}) endmacro(OVERRULE_ARCH) ######################################################################## # eliminate AVX on if not on x86, or if the compiler does not accept # the xgetbv instruction, or {if not cross-compiling and the xgetbv # executable does not function correctly}. ######################################################################## set(HAVE_XGETBV 0) if(CPU_IS_x86) # check to see if the compiler/linker works with xgetb instruction file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/test_xgetbv.c "unsigned long long _xgetbv(unsigned int index) { unsigned int eax, edx; __asm__ __volatile__(\"xgetbv\" : \"=a\"(eax), \"=d\"(edx) : \"c\"(index)); return ((unsigned long long)edx << 32) | eax; } int main (void) { (void) _xgetbv(0); return (0); }") execute_process(COMMAND ${CMAKE_C_COMPILER} -o ${CMAKE_CURRENT_BINARY_DIR}/test_xgetbv ${CMAKE_CURRENT_BINARY_DIR}/test_xgetbv.c OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE avx_compile_result) if(NOT ${avx_compile_result} EQUAL 0) OVERRULE_ARCH(avx "Compiler or linker missing xgetbv instruction") elseif(NOT CROSSCOMPILE_MULTILIB) execute_process(COMMAND ${CMAKE_CURRENT_BINARY_DIR}/test_xgetbv OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE avx_exe_result) if(NOT ${avx_exe_result} EQUAL 0) OVERRULE_ARCH(avx "CPU missing xgetbv.") else() set(HAVE_XGETBV 1) endif() else() # cross compiling and compiler/linker seems to work; assume working set(HAVE_XGETBV 1) endif() file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/test_xgetbv ${CMAKE_CURRENT_BINARY_DIR}/test_xgetbv.c) endif() ######################################################################## # eliminate AVX if cvtpi32_ps intrinsic fails on Apple ######################################################################## if(${HAVE_XGETBV} AND APPLE) # check to see if the compiler/linker works with cvtpi32_ps instrinsic file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/test_cvtpi32_ps.c "#include \nint main (void) {__m128 __a; __m64 __b; __m128 foo = _mm_cvtpi32_ps(__a, __b); return (0); }") execute_process(COMMAND ${CMAKE_C_COMPILER} -mavx -o ${CMAKE_CURRENT_BINARY_DIR}/test_cvtpi32_ps ${CMAKE_CURRENT_BINARY_DIR}/test_cvtpi32_ps.c OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE avx_compile_result) if(NOT ${avx_compile_result} EQUAL 0) OVERRULE_ARCH(avx "Compiler missing cvtpi32_ps instrinsic") set(HAVE_XGETBV 0) endif() file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/test_cvtpi32_ps ${CMAKE_CURRENT_BINARY_DIR}/test_cvtpi32_ps.c) endif() if(${HAVE_XGETBV}) add_definitions(-DHAVE_XGETBV) endif() ######################################################################## # implement overruling in the ORC case, # since ORC always passes flag detection ######################################################################## if(NOT ORC_FOUND) OVERRULE_ARCH(orc "ORC support not found") endif() ######################################################################## # implement overruling in the non-multilib case # this makes things work when both -m32 and -m64 pass ######################################################################## if(NOT CROSSCOMPILE_MULTILIB AND CPU_IS_x86) include(CheckTypeSize) check_type_size("void*[8]" SIZEOF_CPU BUILTIN_TYPES_ONLY) if (${SIZEOF_CPU} EQUAL 64) OVERRULE_ARCH(32 "CPU width is 64 bits") endif() if (${SIZEOF_CPU} EQUAL 32) OVERRULE_ARCH(64 "CPU width is 32 bits") endif() #MSVC 64 bit does not have MMX, overrule it if (${SIZEOF_CPU} EQUAL 64 AND MSVC) OVERRULE_ARCH(mmx "No MMX for Win64") endif() endif() ######################################################################## # done overrules! print the result ######################################################################## message(STATUS "Available architectures: ${available_archs}") ######################################################################## # determine available machines given the available architectures ######################################################################## execute_process( COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_SOURCE_DIR}/gen/volk_compile_utils.py --mode "machines" --archs "${available_archs}" OUTPUT_VARIABLE available_machines OUTPUT_STRIP_TRAILING_WHITESPACE ) ######################################################################## # Implement machine overruling for redundant machines: # A machine is redundant when expansion rules occur, # and the arch superset passes configuration checks. # When this occurs, eliminate the redundant machines # to avoid unnecessary compilation of subset machines. ######################################################################## foreach(arch mmx orc 64 32) foreach(machine_name ${available_machines}) string(REPLACE "_${arch}" "" machine_name_no_arch ${machine_name}) if (${machine_name} STREQUAL ${machine_name_no_arch}) else() list(REMOVE_ITEM available_machines ${machine_name_no_arch}) endif() endforeach(machine_name) endforeach(arch) ######################################################################## # done overrules! print the result ######################################################################## message(STATUS "Available machines: ${available_machines}") ######################################################################## # Create rules to run the volk generator ######################################################################## #dependencies are all python, xml, and header implementation files file(GLOB xml_files ${CMAKE_SOURCE_DIR}/gen/*.xml) file(GLOB py_files ${CMAKE_SOURCE_DIR}/gen/*.py) file(GLOB h_files ${CMAKE_SOURCE_DIR}/kernels/volk/*.h) macro(gen_template tmpl output) list(APPEND volk_gen_sources ${output}) add_custom_command( OUTPUT ${output} DEPENDS ${xml_files} ${py_files} ${h_files} ${tmpl} COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_SOURCE_DIR}/gen/volk_tmpl_utils.py --input ${tmpl} --output ${output} ${ARGN} ) endmacro(gen_template) make_directory(${CMAKE_BINARY_DIR}/include/volk) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk.tmpl.h ${CMAKE_BINARY_DIR}/include/volk/volk.h) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk.tmpl.c ${CMAKE_BINARY_DIR}/lib/volk.c) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_typedefs.tmpl.h ${CMAKE_BINARY_DIR}/include/volk/volk_typedefs.h) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_cpu.tmpl.h ${CMAKE_BINARY_DIR}/include/volk/volk_cpu.h) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_cpu.tmpl.c ${CMAKE_BINARY_DIR}/lib/volk_cpu.c) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_config_fixed.tmpl.h ${CMAKE_BINARY_DIR}/include/volk/volk_config_fixed.h) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_machines.tmpl.h ${CMAKE_BINARY_DIR}/lib/volk_machines.h) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_machines.tmpl.c ${CMAKE_BINARY_DIR}/lib/volk_machines.c) foreach(machine_name ${available_machines}) #generate machine source set(machine_source ${CMAKE_CURRENT_BINARY_DIR}/volk_machine_${machine_name}.c) gen_template(${CMAKE_SOURCE_DIR}/tmpl/volk_machine_xxx.tmpl.c ${machine_source} ${machine_name}) #determine machine flags execute_process( COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_SOURCE_DIR}/gen/volk_compile_utils.py --mode "machine_flags" --machine "${machine_name}" --compiler "${COMPILER_NAME}" OUTPUT_VARIABLE ${machine_name}_flags OUTPUT_STRIP_TRAILING_WHITESPACE ) if(${machine_name}_flags) set_source_files_properties(${machine_source} PROPERTIES COMPILE_FLAGS "${${machine_name}_flags}") endif() #add to available machine defs string(TOUPPER LV_MACHINE_${machine_name} machine_def) list(APPEND machine_defs ${machine_def}) endforeach(machine_name) ######################################################################## # Set local include directories first ######################################################################## include_directories( ${CMAKE_BINARY_DIR}/include ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/kernels ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ) ######################################################################## # Handle orc support ######################################################################## if(ORC_FOUND) #setup orc library usage include_directories(${ORC_INCLUDE_DIRS}) link_directories(${ORC_LIBRARY_DIRS}) list(APPEND volk_libraries ${ORC_LIBRARIES}) #setup orc functions file(GLOB orc_files ${CMAKE_SOURCE_DIR}/orc/*.orc) foreach(orc_file ${orc_files}) #extract the name for the generated c source from the orc file get_filename_component(orc_file_name_we ${orc_file} NAME_WE) set(orcc_gen ${CMAKE_CURRENT_BINARY_DIR}/${orc_file_name_we}.c) #create a rule to generate the source and add to the list of sources add_custom_command( COMMAND ${ORCC_EXECUTABLE} --include math.h --implementation -o ${orcc_gen} ${orc_file} DEPENDS ${orc_file} OUTPUT ${orcc_gen} ) list(APPEND volk_sources ${orcc_gen}) endforeach(orc_file) else() message(STATUS "Did not find liborc and orcc, disabling orc support...") endif() ######################################################################## # Setup the volk sources list and library ######################################################################## if(NOT WIN32) add_definitions(-fvisibility=hidden) endif() list(APPEND volk_sources ${CMAKE_CURRENT_SOURCE_DIR}/volk_prefs.c ${CMAKE_CURRENT_SOURCE_DIR}/volk_rank_archs.c ${volk_gen_sources} ) #set the machine definitions where applicable set_source_files_properties( ${CMAKE_CURRENT_BINARY_DIR}/volk.c ${CMAKE_CURRENT_BINARY_DIR}/volk_machines.c PROPERTIES COMPILE_DEFINITIONS "${machine_defs}") if(MSVC) #add compatibility includes for stdint types include_directories(${CMAKE_SOURCE_DIR}/cmake/msvc) add_definitions(-DHAVE_CONFIG_H) #compile the sources as C++ due to the lack of complex.h under MSVC set_source_files_properties(${volk_sources} PROPERTIES LANGUAGE CXX) endif() #create the volk runtime library add_library(volk SHARED ${volk_sources}) target_link_libraries(volk ${volk_libraries}) set_target_properties(volk PROPERTIES SOVERSION ${LIBVER}) set_target_properties(volk PROPERTIES DEFINE_SYMBOL "volk_EXPORTS") install(TARGETS volk LIBRARY DESTINATION lib${LIB_SUFFIX} COMPONENT "volk_runtime" # .so file ARCHIVE DESTINATION lib${LIB_SUFFIX} COMPONENT "volk_devel" # .lib file RUNTIME DESTINATION bin COMPONENT "volk_runtime" # .dll file ) ######################################################################## # Build the QA test application ######################################################################## if(Boost_FOUND) set_source_files_properties( ${CMAKE_CURRENT_SOURCE_DIR}/testqa.cc PROPERTIES COMPILE_DEFINITIONS "BOOST_TEST_DYN_LINK;BOOST_TEST_MAIN" ) include_directories(${Boost_INCLUDE_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) add_executable(test_all ${CMAKE_CURRENT_SOURCE_DIR}/testqa.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_utils.cc ) target_link_libraries(test_all volk ${Boost_LIBRARIES}) add_test(qa_volk_test_all test_all) endif(Boost_FOUND) gnuradio-3.7.2.1/volk/lib/qa_64u_popcnt_aligned16.cc0000644000175000017500000000250111744612271021671 0ustar jcorganjcorgan#include #include #include #include #include #include //test for sse #ifndef LV_HAVE_SSE4_2 void qa_64u_popcnt_aligned16::t1() { printf("sse4.2 not available... no test performed\n"); } #else void qa_64u_popcnt_aligned16::t1() { volk_runtime_init(); volk_environment_init(); clock_t start, end; double total; const int ITERS = 10000000; __VOLK_ATTR_ALIGNED(16) uint64_t input0; __VOLK_ATTR_ALIGNED(16) uint64_t output0; __VOLK_ATTR_ALIGNED(16) uint64_t output01; input0 = ((uint64_t) (rand() - (RAND_MAX/2))); output0 = 0; output01 = 0; printf("64u_popcnt_aligned\n"); start = clock(); uint64_t ret = 0; for(int count = 0; count < ITERS; ++count) { volk_64u_popcnt_aligned16_manual(&ret, input0, "generic"); output0 += ret; } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic_time: %f\n", total); start = clock(); ret = 0; for(int count = 0; count < ITERS; ++count) { get_volk_runtime()->volk_64u_popcnt_aligned16(&ret, input0); output01 += ret; } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse4.2_time: %f\n", total); CPPUNIT_ASSERT_EQUAL(output0, output01); } #endif gnuradio-3.7.2.1/volk/lib/volk_prefs.c0000664000175000017500000000253312207440367017373 0ustar jcorganjcorgan#include #include #include #include //#if defined(_WIN32) //#include //#endif void volk_get_config_path(char *path) { const char *suffix = "/.volk/volk_config"; char *home = NULL; if (home == NULL) home = getenv("HOME"); if (home == NULL) home = getenv("APPDATA"); if (home == NULL){ path = NULL; return; } strcpy(path, home); strcat(path, suffix); } size_t volk_load_preferences(volk_arch_pref_t **prefs_res) { FILE *config_file; char path[512], line[512]; size_t n_arch_prefs = 0; volk_arch_pref_t *prefs = NULL; //get the config path volk_get_config_path(path); if (path == NULL) return n_arch_prefs; //no prefs found config_file = fopen(path, "r"); if(!config_file) return n_arch_prefs; //no prefs found //reset the file pointer and write the prefs into volk_arch_prefs while(fgets(line, sizeof(line), config_file) != NULL) { prefs = (volk_arch_pref_t *) realloc(prefs, (n_arch_prefs+1) * sizeof(*prefs)); volk_arch_pref_t *p = prefs + n_arch_prefs; if(sscanf(line, "%s %s %s", p->name, p->impl_a, p->impl_u) == 3 && !strncmp(p->name, "volk_", 5)) { n_arch_prefs++; } } fclose(config_file); *prefs_res = prefs; return n_arch_prefs; } gnuradio-3.7.2.1/volk/lib/qa_16s_quad_max_star_aligned16.h0000644000175000017500000000066211700377701023057 0ustar jcorganjcorgan#ifndef INCLUDED_QA_16S_QUAD_MAX_STAR_ALIGNED16_H #define INCLUDED_QA_16S_QUAD_MAX_STAR_ALIGNED16_H #include #include class qa_16s_quad_max_star_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_16s_quad_max_star_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_16S_QUAD_MAX_STAR_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/testqa.cc0000664000175000017500000001300512207440367016661 0ustar jcorganjcorgan#include "qa_utils.h" #include #include //VOLK_RUN_TESTS(volk_16i_x5_add_quad_16i_x4, 1e-4, 2046, 10000); //VOLK_RUN_TESTS(volk_16i_branch_4_state_8, 1e-4, 2046, 10000); VOLK_RUN_TESTS(volk_16ic_s32f_deinterleave_real_32f, 1e-5, 32768.0, 20462, 1); VOLK_RUN_TESTS(volk_16ic_deinterleave_real_8i, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_16ic_deinterleave_16i_x2, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_16ic_s32f_deinterleave_32f_x2, 1e-4, 32768.0, 20462, 1); VOLK_RUN_TESTS(volk_16ic_deinterleave_real_16i, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_16ic_magnitude_16i, 1, 0, 20462, 1); VOLK_RUN_TESTS(volk_16ic_s32f_magnitude_32f, 1e-5, 32768.0, 20462, 1); VOLK_RUN_TESTS(volk_16i_s32f_convert_32f, 1e-4, 32768.0, 20462, 1); VOLK_RUN_TESTS(volk_16i_convert_8i, 0, 0, 20462, 1); //VOLK_RUN_TESTS(volk_16i_max_star_16i, 0, 0, 20462, 10000); //VOLK_RUN_TESTS(volk_16i_max_star_horizontal_16i, 0, 0, 20462, 10000); //VOLK_RUN_TESTS(volk_16i_permute_and_scalar_add, 1e-4, 0, 2046, 1000); //VOLK_RUN_TESTS(volk_16i_x4_quad_max_star_16i, 1e-4, 0, 2046, 1000); VOLK_RUN_TESTS(volk_16u_byteswap, 0, 0, 20462, 1); //VOLK_RUN_TESTS(volk_16i_32fc_dot_prod_32fc, 1e-4, 0, 204602, 1); VOLK_RUN_TESTS(volk_32f_accumulator_s32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_add_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_32f_multiply_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_s32f_power_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_calc_spectral_noise_floor_32f, 1e-4, 20.0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_s32f_atan2_32f, 1e-4, 10.0, 20462, 1); //VOLK_RUN_TESTS(volk_32fc_x2_conjugate_dot_prod_32fc, 1e-4, 0, 2046, 10000); VOLK_RUN_TESTS(volk_32fc_x2_conjugate_dot_prod_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_deinterleave_32f_x2, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_deinterleave_64f_x2, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_s32f_deinterleave_real_16i, 0, 32768, 20462, 1); VOLK_RUN_TESTS(volk_32fc_deinterleave_real_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_deinterleave_imag_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_deinterleave_real_64f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_x2_dot_prod_32fc, 1e-4, 0, 2046002, 1); VOLK_RUN_TESTS(volk_32fc_32f_dot_prod_32fc, 1e-4, 0, 204602, 1); VOLK_RUN_TESTS(volk_32fc_index_max_16u, 3, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_s32f_magnitude_16i, 1, 32768, 20462, 1); VOLK_RUN_TESTS(volk_32fc_magnitude_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_convert_16i, 1, 32768, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_convert_32i, 1, 2<<31, 20462, 1); VOLK_RUN_TESTS(volk_32f_convert_64f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_convert_8i, 1, 128, 20462, 1); //VOLK_RUN_TESTS(volk_32fc_s32f_x2_power_spectral_density_32f, 1e-4, 2046, 10000); VOLK_RUN_TESTS(volk_32fc_s32f_power_spectrum_32f, 1e-4, 0, 2046, 1); VOLK_RUN_TESTS(volk_32fc_x2_square_dist_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_x2_s32f_square_dist_scalar_mult_32f, 1e-4, 10, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_divide_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_dot_prod_32f, 1e-4, 0, 204602, 1); VOLK_RUN_TESTS(volk_32f_x2_dot_prod_16i, 1e-4, 0, 204602, 1); //VOLK_RUN_TESTS(volk_32f_s32f_32f_fm_detect_32f, 1e-4, 2046, 10000); VOLK_RUN_TESTS(volk_32f_index_max_16u, 3, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_s32f_interleave_16ic, 1, 32767, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_interleave_32fc, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_max_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_min_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_normalize, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_power_32f, 1e-4, 4, 20462, 1); VOLK_RUN_TESTS(volk_32f_sqrt_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_stddev_32f, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_32f_stddev_and_mean_32f_x2, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_subtract_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x3_sum_of_poly_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32i_x2_and_32i, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_32i_s32f_convert_32f, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_32i_x2_or_32i, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_32u_byteswap, 0, 0, 20462, 1); //VOLK_RUN_TESTS(volk_32u_popcnt, 0, 0, 2046, 10000); VOLK_RUN_TESTS(volk_64f_convert_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_64f_x2_max_64f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_64f_x2_min_64f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_64u_byteswap, 0, 0, 20462, 1); //VOLK_RUN_TESTS(volk_64u_popcnt, 0, 0, 2046, 10000); VOLK_RUN_TESTS(volk_8ic_deinterleave_16i_x2, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_8ic_s32f_deinterleave_32f_x2, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_8ic_deinterleave_real_16i, 0, 256, 20462, 1); VOLK_RUN_TESTS(volk_8ic_s32f_deinterleave_real_32f, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_8ic_deinterleave_real_8i, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_8ic_x2_multiply_conjugate_16ic, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_8ic_x2_s32f_multiply_conjugate_32fc, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_8i_convert_16i, 0, 0, 20462, 1); VOLK_RUN_TESTS(volk_8i_s32f_convert_32f, 1e-4, 100, 20462, 1); VOLK_RUN_TESTS(volk_32fc_x2_multiply_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_x2_multiply_conjugate_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_conjugate_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_x2_multiply_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_s32fc_multiply_32fc, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32f_s32f_multiply_32f, 1e-4, 0, 20462, 1); VOLK_RUN_TESTS(volk_32fc_s32fc_rotatorpuppet_32fc, 1e-2, (lv_32fc_t)lv_cmake(0.953939201, 0.3), 20462, 1); gnuradio-3.7.2.1/volk/lib/qa_32f_fm_detect_aligned16.h0000644000175000017500000000063611700377701022143 0ustar jcorganjcorgan#ifndef INCLUDED_QA_32F_FM_DETECT_ALIGNED16_H #define INCLUDED_QA_32F_FM_DETECT_ALIGNED16_H #include #include class qa_32f_fm_detect_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_32f_fm_detect_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_32F_FM_DETECT_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_utils.cc0000664000175000017500000004707012243165260017206 0ustar jcorganjcorgan#include "qa_utils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include float uniform() { return 2.0 * ((float) rand() / RAND_MAX - 0.5); // uniformly (-1, 1) } template void random_floats (t *buf, unsigned n) { for (unsigned i = 0; i < n; i++) buf[i] = uniform (); } void load_random_data(void *data, volk_type_t type, unsigned int n) { if(type.is_complex) n *= 2; if(type.is_float) { if(type.size == 8) random_floats((double *)data, n); else random_floats((float *)data, n); } else { float int_max = float(uint64_t(2) << (type.size*8)); if(type.is_signed) int_max /= 2.0; for(unsigned int i=0; i((RAND_MAX/2))) * int_max; //man i really don't know how to do this in a more clever way, you have to cast down at some point switch(type.size) { case 8: if(type.is_signed) ((int64_t *)data)[i] = (int64_t) scaled_rand; else ((uint64_t *)data)[i] = (uint64_t) scaled_rand; break; case 4: if(type.is_signed) ((int32_t *)data)[i] = (int32_t) scaled_rand; else ((uint32_t *)data)[i] = (uint32_t) scaled_rand; break; case 2: if(type.is_signed) ((int16_t *)data)[i] = (int16_t) scaled_rand; else ((uint16_t *)data)[i] = (uint16_t) scaled_rand; break; case 1: if(type.is_signed) ((int8_t *)data)[i] = (int8_t) scaled_rand; else ((uint8_t *)data)[i] = (uint8_t) scaled_rand; break; default: throw "load_random_data: no support for data size > 8 or < 1"; //no shenanigans here } } } } static std::vector get_arch_list(volk_func_desc_t desc) { std::vector archlist; for(size_t i = 0; i < desc.n_impls; i++) { //if(!(archs[i+1] & volk_get_lvarch())) continue; //this arch isn't available on this pc archlist.push_back(std::string(desc.impl_names[i])); } return archlist; } volk_type_t volk_type_from_string(std::string name) { volk_type_t type; type.is_float = false; type.is_scalar = false; type.is_complex = false; type.is_signed = false; type.size = 0; type.str = name; if(name.size() < 2) throw std::string("name too short to be a datatype"); //is it a scalar? if(name[0] == 's') { type.is_scalar = true; name = name.substr(1, name.size()-1); } //get the data size size_t last_size_pos = name.find_last_of("0123456789"); if(last_size_pos < 0) throw std::string("no size spec in type ").append(name); //will throw if malformed int size = boost::lexical_cast(name.substr(0, last_size_pos+1)); assert(((size % 8) == 0) && (size <= 64) && (size != 0)); type.size = size/8; //in bytes for(size_t i=last_size_pos+1; i < name.size(); i++) { switch (name[i]) { case 'f': type.is_float = true; break; case 'i': type.is_signed = true; break; case 'c': type.is_complex = true; break; case 'u': type.is_signed = false; break; default: throw; } } return type; } static void get_signatures_from_name(std::vector &inputsig, std::vector &outputsig, std::string name) { boost::char_separator sep("_"); boost::tokenizer > tok(name, sep); std::vector toked; tok.assign(name); toked.assign(tok.begin(), tok.end()); assert(toked[0] == "volk"); toked.erase(toked.begin()); //ok. we're assuming a string in the form //(sig)_(multiplier-opt)_..._(name)_(sig)_(multiplier-opt)_..._(alignment) enum { SIDE_INPUT, SIDE_NAME, SIDE_OUTPUT } side = SIDE_INPUT; std::string fn_name; volk_type_t type; BOOST_FOREACH(std::string token, toked) { try { type = volk_type_from_string(token); if(side == SIDE_NAME) side = SIDE_OUTPUT; //if this is the first one after the name... if(side == SIDE_INPUT) inputsig.push_back(type); else outputsig.push_back(type); } catch (...){ if(token[0] == 'x') { //it's a multiplier if(side == SIDE_INPUT) assert(inputsig.size() > 0); else assert(outputsig.size() > 0); int multiplier = boost::lexical_cast(token.substr(1, token.size()-1)); //will throw if invalid for(int i=1; i &buffs, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], vlen, arch.c_str()); } inline void run_cast_test2(volk_fn_2arg func, std::vector &buffs, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], vlen, arch.c_str()); } inline void run_cast_test3(volk_fn_3arg func, std::vector &buffs, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], buffs[2], vlen, arch.c_str()); } inline void run_cast_test4(volk_fn_4arg func, std::vector &buffs, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], buffs[2], buffs[3], vlen, arch.c_str()); } inline void run_cast_test1_s32f(volk_fn_1arg_s32f func, std::vector &buffs, float scalar, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], scalar, vlen, arch.c_str()); } inline void run_cast_test2_s32f(volk_fn_2arg_s32f func, std::vector &buffs, float scalar, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], scalar, vlen, arch.c_str()); } inline void run_cast_test3_s32f(volk_fn_3arg_s32f func, std::vector &buffs, float scalar, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], buffs[2], scalar, vlen, arch.c_str()); } inline void run_cast_test1_s32fc(volk_fn_1arg_s32fc func, std::vector &buffs, lv_32fc_t scalar, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], scalar, vlen, arch.c_str()); } inline void run_cast_test2_s32fc(volk_fn_2arg_s32fc func, std::vector &buffs, lv_32fc_t scalar, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], scalar, vlen, arch.c_str()); } inline void run_cast_test3_s32fc(volk_fn_3arg_s32fc func, std::vector &buffs, lv_32fc_t scalar, unsigned int vlen, unsigned int iter, std::string arch) { while(iter--) func(buffs[0], buffs[1], buffs[2], scalar, vlen, arch.c_str()); } template bool fcompare(t *in1, t *in2, unsigned int vlen, float tol) { bool fail = false; int print_max_errs = 10; for(unsigned int i=0; i tol) { fail=true; if(print_max_errs-- > 0) { std::cout << "offset " << i << " in1: " << t(((t *)(in1))[i]) << " in2: " << t(((t *)(in2))[i]) << std::endl; } } } return fail; } template bool icompare(t *in1, t *in2, unsigned int vlen, unsigned int tol) { bool fail = false; int print_max_errs = 10; for(unsigned int i=0; i tol) { fail=true; if(print_max_errs-- > 0) { std::cout << "offset " << i << " in1: " << static_cast(t(((t *)(in1))[i])) << " in2: " << static_cast(t(((t *)(in2))[i])) << std::endl; } } } return fail; } class volk_qa_aligned_mem_pool{ public: void *get_new(size_t size){ size_t alignment = volk_get_alignment(); _mems.push_back(std::vector(size + alignment-1, 0)); size_t ptr = size_t(&_mems.back().front()); return (void *)((ptr + alignment-1) & ~(alignment-1)); } private: std::list > _mems; }; bool run_volk_tests(volk_func_desc_t desc, void (*manual_func)(), std::string name, float tol, lv_32fc_t scalar, int vlen, int iter, std::vector *best_arch_vector = 0, std::string puppet_master_name = "NULL" ) { std::cout << "RUN_VOLK_TESTS: " << name << std::endl; const float tol_f = tol; const unsigned int tol_i = static_cast(tol); //first let's get a list of available architectures for the test std::vector arch_list = get_arch_list(desc); if(arch_list.size() < 2) { std::cout << "no architectures to test" << std::endl; return false; } //something that can hang onto memory and cleanup when this function exits volk_qa_aligned_mem_pool mem_pool; //now we have to get a function signature by parsing the name std::vector inputsig, outputsig; get_signatures_from_name(inputsig, outputsig, name); //pull the input scalars into their own vector std::vector inputsc; for(size_t i=0; i inbuffs; BOOST_FOREACH(volk_type_t sig, inputsig) { if(!sig.is_scalar) //we don't make buffers for scalars inbuffs.push_back(mem_pool.get_new(vlen*sig.size*(sig.is_complex ? 2 : 1))); } for(size_t i=0; i > test_data; for(size_t i=0; i arch_buffs; for(size_t j=0; j both_sigs; both_sigs.insert(both_sigs.end(), outputsig.begin(), outputsig.end()); both_sigs.insert(both_sigs.end(), inputsig.begin(), inputsig.end()); //now run the test clock_t start, end; std::vector profile_times; for(size_t i = 0; i < arch_list.size(); i++) { start = clock(); switch(both_sigs.size()) { case 1: if(inputsc.size() == 0) { run_cast_test1((volk_fn_1arg)(manual_func), test_data[i], vlen, iter, arch_list[i]); } else if(inputsc.size() == 1 && inputsc[0].is_float) { if(inputsc[0].is_complex) { run_cast_test1_s32fc((volk_fn_1arg_s32fc)(manual_func), test_data[i], scalar, vlen, iter, arch_list[i]); } else { run_cast_test1_s32f((volk_fn_1arg_s32f)(manual_func), test_data[i], scalar.real(), vlen, iter, arch_list[i]); } } else throw "unsupported 1 arg function >1 scalars"; break; case 2: if(inputsc.size() == 0) { run_cast_test2((volk_fn_2arg)(manual_func), test_data[i], vlen, iter, arch_list[i]); } else if(inputsc.size() == 1 && inputsc[0].is_float) { if(inputsc[0].is_complex) { run_cast_test2_s32fc((volk_fn_2arg_s32fc)(manual_func), test_data[i], scalar, vlen, iter, arch_list[i]); } else { run_cast_test2_s32f((volk_fn_2arg_s32f)(manual_func), test_data[i], scalar.real(), vlen, iter, arch_list[i]); } } else throw "unsupported 2 arg function >1 scalars"; break; case 3: if(inputsc.size() == 0) { run_cast_test3((volk_fn_3arg)(manual_func), test_data[i], vlen, iter, arch_list[i]); } else if(inputsc.size() == 1 && inputsc[0].is_float) { if(inputsc[0].is_complex) { run_cast_test3_s32fc((volk_fn_3arg_s32fc)(manual_func), test_data[i], scalar, vlen, iter, arch_list[i]); } else { run_cast_test3_s32f((volk_fn_3arg_s32f)(manual_func), test_data[i], scalar.real(), vlen, iter, arch_list[i]); } } else throw "unsupported 3 arg function >1 scalars"; break; case 4: run_cast_test4((volk_fn_4arg)(manual_func), test_data[i], vlen, iter, arch_list[i]); break; default: throw "no function handler for this signature"; break; } end = clock(); double arch_time = (double)(end-start)/(double)CLOCKS_PER_SEC; std::cout << arch_list[i] << " completed in " << arch_time << "s" << std::endl; profile_times.push_back(arch_time); } //and now compare each output to the generic output //first we have to know which output is the generic one, they aren't in order... size_t generic_offset=0; for(size_t i=0; i arch_results; for(size_t i=0; i::max(); double best_time_u = std::numeric_limits::max(); std::string best_arch_a = "generic"; std::string best_arch_u = "generic"; for(size_t i=0; i < arch_list.size(); i++) { if((profile_times[i] < best_time_u) && arch_results[i] && desc.impl_alignment[i] == 0) { best_time_u = profile_times[i]; best_arch_u = arch_list[i]; } if((profile_times[i] < best_time_a) && arch_results[i]) { best_time_a = profile_times[i]; best_arch_a = arch_list[i]; } } std::cout << "Best aligned arch: " << best_arch_a << std::endl; std::cout << "Best unaligned arch: " << best_arch_u << std::endl; if(best_arch_vector) { if(puppet_master_name == "NULL") { best_arch_vector->push_back(name + " " + best_arch_a + " " + best_arch_u); } else { best_arch_vector->push_back(puppet_master_name + " " + best_arch_a + " " + best_arch_u); } } return fail_global; } gnuradio-3.7.2.1/volk/lib/qa_32fc_index_max_aligned16.h0000644000175000017500000000064311700377701022326 0ustar jcorganjcorgan#ifndef INCLUDED_QA_32FC_INDEX_MAX_ALIGNED16_H #define INCLUDED_QA_32FC_INDEX_MAX_ALIGNED16_H #include #include class qa_32fc_index_max_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_32fc_index_max_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_32FC_INDEX_MAX_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_16s_quad_max_star_aligned16.cc0000644000175000017500000000332711744612271023220 0ustar jcorganjcorgan#include #include #include #include #include //test for sse2 #ifndef LV_HAVE_SSE2 void qa_16s_quad_max_star_aligned16::t1() { printf("sse2 not available... no test performed\n"); } #else void qa_16s_quad_max_star_aligned16::t1() { const int vlen = 34; __VOLK_ATTR_ALIGNED(16) short input0[vlen]; __VOLK_ATTR_ALIGNED(16) short input1[vlen]; __VOLK_ATTR_ALIGNED(16) short input2[vlen]; __VOLK_ATTR_ALIGNED(16) short input3[vlen]; __VOLK_ATTR_ALIGNED(16) short output0[vlen]; __VOLK_ATTR_ALIGNED(16) short output1[vlen]; for(int i = 0; i < vlen; ++i) { short plus0 = (short) (rand() - (RAND_MAX/2)); short plus1 = (short) (rand() - (RAND_MAX/2)); short plus2 = (short) (rand() - (RAND_MAX/2)); short plus3 = (short) (rand() - (RAND_MAX/2)); short minus0 = (short) (rand() - (RAND_MAX/2)); short minus1 = (short) (rand() - (RAND_MAX/2)); short minus2 = (short) (rand() - (RAND_MAX/2)); short minus3 = (short) (rand() - (RAND_MAX/2)); input0[i] = plus0 - minus0; input1[i] = plus1 - minus1; input2[i] = plus2 - minus2; input3[i] = plus3 - minus3; } volk_16s_quad_max_star_aligned16_manual(output0, input0, input1, input2, input3, 2*vlen, "generic"); volk_16s_quad_max_star_aligned16_manual(output1, input0, input1, input2, input3, 2*vlen, "sse2"); printf("16s_quad_max_star_aligned\n"); for(int i = 0; i < vlen; ++i) { printf("generic... %d, sse2... %d, inputs: %d, %d, %d, %d\n", output0[i], output1[i], input0[i], input1[i], input2[i], input3[i]); } for(int i = 0; i < vlen; ++i) { CPPUNIT_ASSERT_EQUAL(output0[i], output1[i]); } } #endif gnuradio-3.7.2.1/volk/lib/qa_16s_branch_4_state_8_aligned16.h0000644000175000017500000000070111700377701023330 0ustar jcorganjcorgan#ifndef INCLUDED_QA_16S_BRANCH_4_STATE_8_ALIGNED16_H #define INCLUDED_QA_16S_BRANCH_4_STATE_8_ALIGNED16_H #include #include class qa_16s_branch_4_state_8_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_16s_branch_4_state_8_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_16S_BRANCH_4_STATE_8_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_32fc_index_max_aligned16.cc0000644000175000017500000000331311744612271022463 0ustar jcorganjcorgan#include #include #include #include #include #define ERR_DELTA (1e-4) #define NUM_ITERS 1000000 #define VEC_LEN 3096 static float uniform() { return 2.0 * ((float) rand() / RAND_MAX - 0.5); // uniformly (-1, 1) } static void random_floats (float *buf, unsigned n) { unsigned int i = 0; for (; i < n; i++) { buf[i] = uniform () * 32767; } } #ifndef LV_HAVE_SSE3 void qa_32fc_index_max_aligned16::t1(){ printf("sse3 not available... no test performed\n"); } #else void qa_32fc_index_max_aligned16::t1(){ const int vlen = VEC_LEN; volk_environment_init(); int ret; unsigned int* target; unsigned int* target_generic; std::complex* src0 ; unsigned int i_target; target = &i_target; unsigned int i_target_generic; target_generic = &i_target_generic; ret = posix_memalign((void**)&src0, 16, vlen << 3); random_floats((float*)src0, vlen * 2); printf("32fc_index_max_aligned16\n"); clock_t start, end; double total; start = clock(); for(int k = 0; k < NUM_ITERS; ++k) { volk_32fc_index_max_aligned16_manual(target_generic, src0, vlen << 3, "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic time: %f\n", total); start = clock(); for(int k = 0; k < NUM_ITERS; ++k) { volk_32fc_index_max_aligned16_manual(target, src0, vlen << 3, "sse3"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse3 time: %f\n", total); printf("generic: %u, sse3: %u\n", target_generic[0], target[0]); CPPUNIT_ASSERT_DOUBLES_EQUAL(target_generic[0], target[0], 1.1); free(src0); } #endif /*LV_HAVE_SSE3*/ gnuradio-3.7.2.1/volk/lib/qa_32f_index_max_aligned16.h0000644000175000017500000000063611700377701022165 0ustar jcorganjcorgan#ifndef INCLUDED_QA_32F_INDEX_MAX_ALIGNED16_H #define INCLUDED_QA_32F_INDEX_MAX_ALIGNED16_H #include #include class qa_32f_index_max_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_32f_index_max_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_32F_INDEX_MAX_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_32fc_power_spectral_density_32f_aligned16.h0000644000175000017500000000077011700377701025615 0ustar jcorganjcorgan#ifndef INCLUDED_QA_32FC_POWER_SPECTRAL_DENSITY_32F_ALIGNED16_H #define INCLUDED_QA_32FC_POWER_SPECTRAL_DENSITY_32F_ALIGNED16_H #include #include class qa_32fc_power_spectral_density_32f_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_32fc_power_spectral_density_32f_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_32FC_POWER_SPECTRAL_DENSITY_32F_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_32u_popcnt_aligned16.h0000644000175000017500000000061711700377701021532 0ustar jcorganjcorgan#ifndef INCLUDED_QA_32U_POPCNT_ALIGNED16_H #define INCLUDED_QA_32U_POPCNT_ALIGNED16_H #include #include class qa_32u_popcnt_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_32u_popcnt_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_32U_POPCNT_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_32u_popcnt_aligned16.cc0000644000175000017500000000250111744612271021664 0ustar jcorganjcorgan#include #include #include #include #include #include //test for sse #ifndef LV_HAVE_SSE4_2 void qa_32u_popcnt_aligned16::t1() { printf("sse4.2 not available... no test performed\n"); } #else void qa_32u_popcnt_aligned16::t1() { volk_runtime_init(); volk_environment_init(); clock_t start, end; double total; const int ITERS = 10000000; __VOLK_ATTR_ALIGNED(16) uint32_t input0; __VOLK_ATTR_ALIGNED(16) uint32_t output0; __VOLK_ATTR_ALIGNED(16) uint32_t output01; input0 = ((uint32_t) (rand() - (RAND_MAX/2))); output0 = 0; output01 = 0; printf("32u_popcnt_aligned\n"); start = clock(); uint32_t ret = 0; for(int count = 0; count < ITERS; ++count) { volk_32u_popcnt_aligned16_manual(&ret, input0, "generic"); output0 += ret; } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic_time: %f\n", total); start = clock(); ret = 0; for(int count = 0; count < ITERS; ++count) { get_volk_runtime()->volk_32u_popcnt_aligned16(&ret, input0); output01 += ret; } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse4.2_time: %f\n", total); CPPUNIT_ASSERT_EQUAL(output0, output01); } #endif gnuradio-3.7.2.1/volk/lib/qa_16s_permute_and_scalar_add_aligned16.h0000644000175000017500000000073711700377701024672 0ustar jcorganjcorgan#ifndef INCLUDED_QA_16S_PERMUTE_AND_SCALAR_ADD_ALIGNED16_H #define INCLUDED_QA_16S_PERMUTE_AND_SCALAR_ADD_ALIGNED16_H #include #include class qa_16s_permute_and_scalar_add_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_16s_permute_and_scalar_add_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_16S_PERMUTE_AND_SCALAR_ADD_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/volk_rank_archs.h0000664000175000017500000000321612207440367020373 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOLK_RANK_ARCHS_H #define INCLUDED_VOLK_RANK_ARCHS_H #include #include #ifdef __cplusplus extern "C" { #endif int volk_get_index( const char *impl_names[], //list of implementations by name const size_t n_impls, //number of implementations available const char *impl_name //the implementation name to find ); int volk_rank_archs( const char *kern_name, //name of the kernel to rank const char *impl_names[], //list of implementations by name const int* impl_deps, //requirement mask per implementation const bool* alignment, //alignment status of each implementation size_t n_impls, //number of implementations available const bool align //if false, filter aligned implementations ); #ifdef __cplusplus } #endif #endif /*INCLUDED_VOLK_RANK_ARCHS_H*/ gnuradio-3.7.2.1/volk/lib/qa_32f_fm_detect_aligned16.cc0000644000175000017500000000320211744612271022273 0ustar jcorganjcorgan#include #include #include #include #include //test for sse #ifndef LV_HAVE_SSE void qa_32f_fm_detect_aligned16::t1() { printf("sse not available... no test performed\n"); } #else void qa_32f_fm_detect_aligned16::t1() { volk_environment_init(); clock_t start, end; double total; const int vlen = 3201; const int ITERS = 10000; __VOLK_ATTR_ALIGNED(16) float input0[vlen]; __VOLK_ATTR_ALIGNED(16) float output0[vlen]; __VOLK_ATTR_ALIGNED(16) float output01[vlen]; for(int i = 0; i < vlen; ++i) { input0[i] = ((float) (rand() - (RAND_MAX/2))) / static_cast((RAND_MAX/2)); } printf("32f_fm_detect_aligned\n"); start = clock(); float save = 0.1; for(int count = 0; count < ITERS; ++count) { volk_32f_fm_detect_aligned16_manual(output0, input0, 1.0, &save, vlen, "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic_time: %f\n", total); start = clock(); save = 0.1; for(int count = 0; count < ITERS; ++count) { volk_32f_fm_detect_aligned16_manual(output01, input0, 1.0, &save, vlen, "sse"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse_time: %f\n", total); for(int i = 0; i < 1; ++i) { //printf("inputs: %d, %d\n", input0[i*2], input0[i*2 + 1]); //printf("generic... %d, ssse3... %d\n", output0[i], output1[i]); } for(int i = 0; i < vlen; ++i) { //printf("%d...%d\n", output0[i], output01[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(output0[i], output01[i], fabs(output0[i]) * 1e-4); } } #endif gnuradio-3.7.2.1/volk/lib/qa_32fc_x2_conjugate_dot_prod_32fc_u.cc0000644000175000017500000000655511744612271024313 0ustar jcorganjcorgan#include #include #include #include #include #define assertcomplexEqual(expected, actual, delta) \ CPPUNIT_ASSERT_DOUBLES_EQUAL (std::real(expected), std::real(actual), fabs(std::real(expected)) * delta); \ CPPUNIT_ASSERT_DOUBLES_EQUAL (std::imag(expected), std::imag(actual), fabs(std::imag(expected))* delta); #define ERR_DELTA (1e-4) //test for sse #if LV_HAVE_SSE && LV_HAVE_64 static float uniform() { return 2.0 * ((float) rand() / RAND_MAX - 0.5); // uniformly (-1, 1) } static void random_floats (float *buf, unsigned n) { for (unsigned i = 0; i < n; i++) buf[i] = uniform () * 32767; } void qa_32fc_x2_conjugate_dot_prod_32fc_u::t1() { const int vlen = 789743; volk_environment_init(); int ret; std::complex* input; std::complex* taps; std::complex* result_generic; std::complex* result; ret = posix_memalign((void**)&input, 16, vlen << 3); ret = posix_memalign((void**)&taps, 16, vlen << 3); ret = posix_memalign((void**)&result_generic, 16, 8); ret = posix_memalign((void**)&result, 16, 8); result_generic[0] = std::complex(0,0); result[0] = std::complex(0,0); random_floats((float*)input, vlen * 2); random_floats((float*)taps, vlen * 2); volk_32fc_x2_conjugate_dot_prod_32fc_u_manual(result_generic, input, taps, vlen * 8, "generic"); volk_32fc_x2_conjugate_dot_prod_32fc_u_manual(result, input, taps, vlen * 8, "sse"); printf("32fc_x2_conjugate_dot_prod_32fc_u\n"); printf("generic: %f +i%f ... sse: %f +i%f\n", std::real(result_generic[0]), std::imag(result_generic[0]), std::real(result[0]), std::imag(result[0])); assertcomplexEqual(result_generic[0], result[0], ERR_DELTA); free(input); free(taps); free(result_generic); free(result); } #elif LV_HAVE_SSE && LV_HAVE_32 static float uniform() { return 2.0 * ((float) rand() / RAND_MAX - 0.5); // uniformly (-1, 1) } static void random_floats (float *buf, unsigned n) { for (unsigned i = 0; i < n; i++) buf[i] = uniform () * 32767; } void qa_32fc_x2_conjugate_dot_prod_32fc_u::t1() { const int vlen = 789743; volk_environment_init(); int ret; std::complex* input; std::complex* taps; std::complex* result_generic; std::complex* result; ret = posix_memalign((void**)&input, 16, vlen << 3); ret = posix_memalign((void**)&taps, 16, vlen << 3); ret = posix_memalign((void**)&result_generic, 16, 8); ret = posix_memalign((void**)&result, 16, 8); result_generic[0] = std::complex(0,0); result[0] = std::complex(0,0); random_floats((float*)input, vlen * 2); random_floats((float*)taps, vlen * 2); volk_32fc_x2_conjugate_dot_prod_32fc_u_manual(result_generic, input, taps, vlen * 8, "generic"); volk_32fc_x2_conjugate_dot_prod_32fc_u_manual(result, input, taps, vlen * 8, "sse_32"); printf("32fc_x2_conjugate_dot_prod_32fc_u\n"); printf("generic: %f +i%f ... sse: %f +i%f\n", std::real(result_generic[0]), std::imag(result_generic[0]), std::real(result[0]), std::imag(result[0])); assertcomplexEqual(result_generic[0], result[0], ERR_DELTA); free(input); free(taps); free(result_generic); free(result); } #else void qa_32fc_x2_conjugate_dot_prod_32fc_u::t1() { printf("sse not available... no test performed\n"); } #endif /*LV_HAVE_SSE*/ gnuradio-3.7.2.1/volk/lib/qa_16s_branch_4_state_8_aligned16.cc0000644000175000017500000000777411744612271023511 0ustar jcorganjcorgan#include #include #include #include //test for ssse3 #ifndef LV_HAVE_SSSE3 void qa_16s_branch_4_state_8_aligned16::t1() { printf("ssse3 not available... no test performed\n"); } #else void qa_16s_branch_4_state_8_aligned16::t1() { const int num_iters = 1000000; const int vlen = 32; static char permute0[16]__attribute__((aligned(16))) = {0x0e, 0x0f, 0x0a, 0x0b, 0x04, 0x05, 0x00, 0x01, 0x0c, 0x0d, 0x08, 0x09, 0x06, 0x07, 0x02, 0x03}; static char permute1[16]__attribute__((aligned(16))) = {0x0c, 0x0d, 0x08, 0x09, 0x06, 0x07, 0x02, 0x03, 0x0e, 0x0f, 0x0a, 0x0b, 0x04, 0x05, 0x00, 0x01}; static char permute2[16]__attribute__((aligned(16))) = {0x02, 0x03, 0x06, 0x07, 0x08, 0x09, 0x0c, 0x0d, 0x00, 0x01, 0x04, 0x05, 0x0a, 0x0b, 0x0e, 0x0f}; static char permute3[16]__attribute__((aligned(16))) = {0x00, 0x01, 0x04, 0x05, 0x0a, 0x0b, 0x0e, 0x0f, 0x02, 0x03, 0x06, 0x07, 0x08, 0x09, 0x0c, 0x0d}; static char* permuters[4] = {permute0, permute1, permute2, permute3}; unsigned int num_bytes = vlen << 1; volk_environment_init(); clock_t start, end; double total; __VOLK_ATTR_ALIGNED(16) short target[vlen]; __VOLK_ATTR_ALIGNED(16) short target2[vlen]; __VOLK_ATTR_ALIGNED(16) short target3[vlen]; __VOLK_ATTR_ALIGNED(16) short src0[vlen]; __VOLK_ATTR_ALIGNED(16) short permute_indexes[vlen] = { 7, 5, 2, 0, 6, 4, 3, 1, 6, 4, 3, 1, 7, 5, 2, 0, 1, 3, 4, 6, 0, 2, 5, 7, 0, 2, 5, 7, 1, 3, 4, 6 }; __VOLK_ATTR_ALIGNED(16) short cntl0[vlen] = { 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; __VOLK_ATTR_ALIGNED(16) short cntl1[vlen] = { 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 }; __VOLK_ATTR_ALIGNED(16) short cntl2[vlen] = { 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000 }; __VOLK_ATTR_ALIGNED(16) short cntl3[vlen] = { 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0xffff, 0xffff, 0x0000, 0x0000, 0xffff, 0xffff }; __VOLK_ATTR_ALIGNED(16) short scalars[4] = {1, 2, 3, 4}; for(int i = 0; i < vlen; ++i) { src0[i] = i; } printf("16s_branch_4_state_8_aligned\n"); start = clock(); for(int i = 0; i < num_iters; ++i) { volk_16s_permute_and_scalar_add_aligned16_manual(target, src0, permute_indexes, cntl0, cntl1, cntl2, cntl3, scalars, num_bytes, "sse2"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("permute_and_scalar_add_time: %f\n", total); start = clock(); for(int i = 0; i < num_iters; ++i) { volk_16s_branch_4_state_8_aligned16_manual(target2, src0, permuters, cntl2, cntl3, scalars, "ssse3"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("branch_4_state_8_time, ssse3: %f\n", total); start = clock(); for(int i = 0; i < num_iters; ++i) { volk_16s_branch_4_state_8_aligned16_manual(target3, src0, permuters, cntl2, cntl3, scalars, "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("permute_and_scalar_add_time, generic: %f\n", total); for(int i = 0; i < vlen; ++i) { printf("psa... %d, b4s8... %d\n", target[i], target3[i]); } for(int i = 0; i < vlen; ++i) { CPPUNIT_ASSERT(target[i] == target2[i]); CPPUNIT_ASSERT(target[i] == target3[i]); } } #endif gnuradio-3.7.2.1/volk/lib/qa_16s_add_quad_aligned16.h0000644000175000017500000000063111700377701021765 0ustar jcorganjcorgan#ifndef INCLUDED_QA_16S_ADD_QUAD_ALIGNED16_H #define INCLUDED_QA_16S_ADD_QUAD_ALIGNED16_H #include #include class qa_16s_add_quad_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_16s_add_quad_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_16S_ADD_QUAD_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_utils.h0000664000175000017500000000421012207440367017041 0ustar jcorganjcorgan#ifndef VOLK_QA_UTILS_H #define VOLK_QA_UTILS_H #include #include #include #include #include struct volk_type_t { bool is_float; bool is_scalar; bool is_signed; bool is_complex; int size; std::string str; }; volk_type_t volk_type_from_string(std::string); float uniform(void); void random_floats(float *buf, unsigned n); bool run_volk_tests(volk_func_desc_t, void(*)(), std::string, float, lv_32fc_t, int, int, std::vector *, std::string); #define VOLK_RUN_TESTS(func, tol, scalar, len, iter) BOOST_AUTO_TEST_CASE(func##_test) { BOOST_CHECK_EQUAL(run_volk_tests(func##_get_func_desc(), (void (*)())func##_manual, std::string(#func), tol, scalar, len, iter, 0, "NULL"), 0); } #define VOLK_PROFILE(func, tol, scalar, len, iter, results) run_volk_tests(func##_get_func_desc(), (void (*)())func##_manual, std::string(#func), tol, scalar, len, iter, results, "NULL") #define VOLK_PUPPET_PROFILE(func, puppet_master_func, tol, scalar, len, iter, results) run_volk_tests(func##_get_func_desc(), (void (*)())func##_manual, std::string(#func), tol, scalar, len, iter, results, std::string(#puppet_master_func)) typedef void (*volk_fn_1arg)(void *, unsigned int, const char*); //one input, operate in place typedef void (*volk_fn_2arg)(void *, void *, unsigned int, const char*); typedef void (*volk_fn_3arg)(void *, void *, void *, unsigned int, const char*); typedef void (*volk_fn_4arg)(void *, void *, void *, void *, unsigned int, const char*); typedef void (*volk_fn_1arg_s32f)(void *, float, unsigned int, const char*); //one input vector, one scalar float input typedef void (*volk_fn_2arg_s32f)(void *, void *, float, unsigned int, const char*); typedef void (*volk_fn_3arg_s32f)(void *, void *, void *, float, unsigned int, const char*); typedef void (*volk_fn_1arg_s32fc)(void *, lv_32fc_t, unsigned int, const char*); //one input vector, one scalar float input typedef void (*volk_fn_2arg_s32fc)(void *, void *, lv_32fc_t, unsigned int, const char*); typedef void (*volk_fn_3arg_s32fc)(void *, void *, void *, lv_32fc_t, unsigned int, const char*); #endif //VOLK_QA_UTILS_H gnuradio-3.7.2.1/volk/lib/qa_32fc_x2_conjugate_dot_prod_32fc_u.h0000644000175000017500000000072011700377701024137 0ustar jcorganjcorgan#ifndef INCLUDED_QA_32FC_X2_CONJUGATE_DOT_PROD_32FC_U_H #define INCLUDED_QA_32FC_X2_CONJUGATE_DOT_PROD_32FC_U_H #include #include class qa_32fc_x2_conjugate_dot_prod_32fc_u : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_32fc_x2_conjugate_dot_prod_32fc_u); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_32FC_X2_CONJUGATE_DOT_PROD_32FC_U_H */ gnuradio-3.7.2.1/volk/lib/volk_rank_archs.c0000664000175000017500000000677612207440367020404 0ustar jcorganjcorgan/* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #if __GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 4 #define __popcnt __builtin_popcount #else inline unsigned __popcnt(unsigned num) { unsigned pop = 0; while(num) { if (num & 0x1) pop++; num >>= 1; } return pop; } #endif int volk_get_index( const char *impl_names[], //list of implementations by name const size_t n_impls, //number of implementations available const char *impl_name //the implementation name to find ){ unsigned int i; for (i = 0; i < n_impls; i++) { if(!strncmp(impl_names[i], impl_name, 20)) { return i; } } //TODO return -1; //something terrible should happen here printf("Volk warning: no arch found, returning generic impl\n"); return volk_get_index(impl_names, n_impls, "generic"); //but we'll fake it for now } int volk_rank_archs( const char *kern_name, //name of the kernel to rank const char *impl_names[], //list of implementations by name const int* impl_deps, //requirement mask per implementation const bool* alignment, //alignment status of each implementation size_t n_impls, //number of implementations available const bool align //if false, filter aligned implementations ){ size_t i; static volk_arch_pref_t *volk_arch_prefs; static size_t n_arch_prefs = 0; static int prefs_loaded = 0; if(!prefs_loaded) { n_arch_prefs = volk_load_preferences(&volk_arch_prefs); prefs_loaded = 1; } //now look for the function name in the prefs list for(i = 0; i < n_arch_prefs; i++) { if(!strncmp(kern_name, volk_arch_prefs[i].name, sizeof(volk_arch_prefs[i].name))) //found it { const char *impl_name = align? volk_arch_prefs[i].impl_a : volk_arch_prefs[i].impl_u; return volk_get_index(impl_names, n_impls, impl_name); } } //return the best index with the largest deps size_t best_index_a = 0; size_t best_index_u = 0; int best_value_a = -1; int best_value_u = -1; for(i = 0; i < n_impls; i++) { const signed val = __popcnt(impl_deps[i]); if (alignment[i] && val > best_value_a) { best_index_a = i; best_value_a = val; } if (!alignment[i] && val > best_value_u) { best_index_u = i; best_value_u = val; } } //when align and we found a best aligned, use it if (align && best_value_a != -1) return best_index_a; //otherwise return the best unaligned return best_index_u; } gnuradio-3.7.2.1/volk/lib/gcc_x86_cpuid.h0000644000175000017500000001277011765410647017663 0ustar jcorganjcorgan/* * Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc. * * This file is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3, or (at your option) any * later version. * * This file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * Under Section 7 of GPL version 3, you are granted additional * permissions described in the GCC Runtime Library Exception, version * 3.1, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License and * a copy of the GCC Runtime Library Exception along with this program; * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * . */ /* %ecx */ #define bit_SSE3 (1 << 0) #define bit_PCLMUL (1 << 1) #define bit_SSSE3 (1 << 9) #define bit_FMA (1 << 12) #define bit_CMPXCHG16B (1 << 13) #define bit_SSE4_1 (1 << 19) #define bit_SSE4_2 (1 << 20) #define bit_MOVBE (1 << 22) #define bit_POPCNT (1 << 23) #define bit_AES (1 << 25) #define bit_XSAVE (1 << 26) #define bit_OSXSAVE (1 << 27) #define bit_AVX (1 << 28) #define bit_F16C (1 << 29) #define bit_RDRND (1 << 30) /* %edx */ #define bit_CMPXCHG8B (1 << 8) #define bit_CMOV (1 << 15) #define bit_MMX (1 << 23) #define bit_FXSAVE (1 << 24) #define bit_SSE (1 << 25) #define bit_SSE2 (1 << 26) /* Extended Features */ /* %ecx */ #define bit_LAHF_LM (1 << 0) #define bit_ABM (1 << 5) #define bit_SSE4a (1 << 6) #define bit_XOP (1 << 11) #define bit_LWP (1 << 15) #define bit_FMA4 (1 << 16) #define bit_TBM (1 << 21) /* %edx */ #define bit_MMXEXT (1 << 22) #define bit_LM (1 << 29) #define bit_3DNOWP (1 << 30) #define bit_3DNOW (1 << 31) /* Extended Features (%eax == 7) */ #define bit_FSGSBASE (1 << 0) #define bit_BMI (1 << 3) #if defined(__i386__) && defined(__PIC__) /* %ebx may be the PIC register. */ #if __GNUC__ >= 3 #define __cpuid(level, a, b, c, d) \ __asm__ ("xchg{l}\t{%%}ebx, %1\n\t" \ "cpuid\n\t" \ "xchg{l}\t{%%}ebx, %1\n\t" \ : "=a" (a), "=r" (b), "=c" (c), "=d" (d) \ : "0" (level)) #define __cpuid_count(level, count, a, b, c, d) \ __asm__ ("xchg{l}\t{%%}ebx, %1\n\t" \ "cpuid\n\t" \ "xchg{l}\t{%%}ebx, %1\n\t" \ : "=a" (a), "=r" (b), "=c" (c), "=d" (d) \ : "0" (level), "2" (count)) #else /* Host GCCs older than 3.0 weren't supporting Intel asm syntax nor alternatives in i386 code. */ #define __cpuid(level, a, b, c, d) \ __asm__ ("xchgl\t%%ebx, %1\n\t" \ "cpuid\n\t" \ "xchgl\t%%ebx, %1\n\t" \ : "=a" (a), "=r" (b), "=c" (c), "=d" (d) \ : "0" (level)) #define __cpuid_count(level, count, a, b, c, d) \ __asm__ ("xchgl\t%%ebx, %1\n\t" \ "cpuid\n\t" \ "xchgl\t%%ebx, %1\n\t" \ : "=a" (a), "=r" (b), "=c" (c), "=d" (d) \ : "0" (level), "2" (count)) #endif #else #define __cpuid(level, a, b, c, d) \ __asm__ ("cpuid\n\t" \ : "=a" (a), "=b" (b), "=c" (c), "=d" (d) \ : "0" (level)) #define __cpuid_count(level, count, a, b, c, d) \ __asm__ ("cpuid\n\t" \ : "=a" (a), "=b" (b), "=c" (c), "=d" (d) \ : "0" (level), "2" (count)) #endif /* Return highest supported input value for cpuid instruction. ext can be either 0x0 or 0x8000000 to return highest supported value for basic or extended cpuid information. Function returns 0 if cpuid is not supported or whatever cpuid returns in eax register. If sig pointer is non-null, then first four bytes of the signature (as found in ebx register) are returned in location pointed by sig. */ static __inline unsigned int __get_cpuid_max (unsigned int __ext, unsigned int *__sig) { unsigned int __eax, __ebx, __ecx, __edx; #ifndef __x86_64__ /* See if we can use cpuid. On AMD64 we always can. */ #if __GNUC__ >= 3 __asm__ ("pushf{l|d}\n\t" "pushf{l|d}\n\t" "pop{l}\t%0\n\t" "mov{l}\t{%0, %1|%1, %0}\n\t" "xor{l}\t{%2, %0|%0, %2}\n\t" "push{l}\t%0\n\t" "popf{l|d}\n\t" "pushf{l|d}\n\t" "pop{l}\t%0\n\t" "popf{l|d}\n\t" : "=&r" (__eax), "=&r" (__ebx) : "i" (0x00200000)); #else /* Host GCCs older than 3.0 weren't supporting Intel asm syntax nor alternatives in i386 code. */ __asm__ ("pushfl\n\t" "pushfl\n\t" "popl\t%0\n\t" "movl\t%0, %1\n\t" "xorl\t%2, %0\n\t" "pushl\t%0\n\t" "popfl\n\t" "pushfl\n\t" "popl\t%0\n\t" "popfl\n\t" : "=&r" (__eax), "=&r" (__ebx) : "i" (0x00200000)); #endif if (!((__eax ^ __ebx) & 0x00200000)) return 0; #endif /* Host supports cpuid. Return highest supported cpuid input value. */ __cpuid (__ext, __eax, __ebx, __ecx, __edx); if (__sig) *__sig = __ebx; return __eax; } /* Return cpuid data for requested cpuid level, as found in returned eax, ebx, ecx and edx registers. The function checks if cpuid is supported and returns 1 for valid cpuid information or 0 for unsupported cpuid level. All pointers are required to be non-null. */ static __inline int __get_cpuid (unsigned int __level, unsigned int *__eax, unsigned int *__ebx, unsigned int *__ecx, unsigned int *__edx) { unsigned int __ext = __level & 0x80000000; if (__get_cpuid_max (__ext, 0) < __level) return 0; __cpuid (__level, *__eax, *__ebx, *__ecx, *__edx); return 1; } gnuradio-3.7.2.1/volk/lib/qa_32fc_power_spectral_density_32f_aligned16.cc0000644000175000017500000000357211744612271025760 0ustar jcorganjcorgan#include #include #include #include #include //test for sse3 #ifndef LV_HAVE_SSE3 void qa_32fc_power_spectral_density_32f_aligned16::t1() { printf("sse3 not available... no test performed\n"); } #else void qa_32fc_power_spectral_density_32f_aligned16::t1() { volk_environment_init(); clock_t start, end; double total; const int vlen = 3201; const int ITERS = 10000; __VOLK_ATTR_ALIGNED(16) std::complex input0[vlen]; __VOLK_ATTR_ALIGNED(16) float output_generic[vlen]; __VOLK_ATTR_ALIGNED(16) float output_sse3[vlen]; const float scalar = vlen; const float rbw = 1.7; float* inputLoad = (float*)input0; for(int i = 0; i < 2*vlen; ++i) { inputLoad[i] = (((float) (rand() - (RAND_MAX/2))) / static_cast((RAND_MAX/2))); } printf("32fc_power_spectral_density_32f_aligned\n"); start = clock(); for(int count = 0; count < ITERS; ++count) { volk_32fc_power_spectral_density_32f_aligned16_manual(output_generic, input0, scalar, rbw, vlen, "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic_time: %f\n", total); start = clock(); for(int count = 0; count < ITERS; ++count) { volk_32fc_power_spectral_density_32f_aligned16_manual(output_sse3, input0, scalar, rbw, vlen, "sse3"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse3_time: %f\n", total); for(int i = 0; i < 1; ++i) { //printf("inputs: %d, %d\n", input0[i*2], input0[i*2 + 1]); //printf("generic... %d, ssse3... %d\n", output0[i], output1[i]); } for(int i = 0; i < vlen; ++i) { //printf("%d...%d\n", output0[i], output01[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(output_generic[i], output_sse3[i], fabs(output_generic[i]*1e-4)); } } #endif gnuradio-3.7.2.1/volk/lib/qa_64u_popcnt_aligned16.h0000644000175000017500000000061711700377701021537 0ustar jcorganjcorgan#ifndef INCLUDED_QA_64U_POPCNT_ALIGNED16_H #define INCLUDED_QA_64U_POPCNT_ALIGNED16_H #include #include class qa_64u_popcnt_aligned16 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_64u_popcnt_aligned16); CPPUNIT_TEST (t1); CPPUNIT_TEST_SUITE_END (); private: void t1 (); }; #endif /* INCLUDED_QA_64U_POPCNT_ALIGNED16_H */ gnuradio-3.7.2.1/volk/lib/qa_16s_permute_and_scalar_add_aligned16.cc0000644000175000017500000000376711744612271025040 0ustar jcorganjcorgan#include #include #include #include #include //test for sse2 #ifndef LV_HAVE_SSE2 void qa_16s_permute_and_scalar_add_aligned16::t1() { printf("sse2 not available... no test performed\n"); } #else void qa_16s_permute_and_scalar_add_aligned16::t1() { const int vlen = 64; unsigned int num_bytes = vlen << 1; volk_environment_init(); clock_t start, end; double total; __VOLK_ATTR_ALIGNED(16) short target[vlen]; __VOLK_ATTR_ALIGNED(16) short target2[vlen]; __VOLK_ATTR_ALIGNED(16) short src0[vlen]; __VOLK_ATTR_ALIGNED(16) short permute_indexes[vlen]; __VOLK_ATTR_ALIGNED(16) short cntl0[vlen]; __VOLK_ATTR_ALIGNED(16) short cntl1[vlen]; __VOLK_ATTR_ALIGNED(16) short cntl2[vlen]; __VOLK_ATTR_ALIGNED(16) short cntl3[vlen]; __VOLK_ATTR_ALIGNED(16) short scalars[4] = {1, 2, 3, 4}; for(int i = 0; i < vlen; ++i) { src0[i] = i; permute_indexes[i] = (3 * i)%vlen; cntl0[i] = 0xff; cntl1[i] = 0xff * (i%2); cntl2[i] = 0xff * ((i>>1)%2); cntl3[i] = 0xff * ((i%4) == 3); } printf("16s_permute_and_scalar_add_aligned\n"); start = clock(); for(int i = 0; i < 100000; ++i) { volk_16s_permute_and_scalar_add_aligned16_manual(target, src0, permute_indexes, cntl0, cntl1, cntl2, cntl3, scalars, num_bytes, "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic_time: %f\n", total); start = clock(); for(int i = 0; i < 100000; ++i) { volk_16s_permute_and_scalar_add_aligned16_manual(target2, src0, permute_indexes, cntl0, cntl1, cntl2, cntl3, scalars, num_bytes, "sse2"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse2_time: %f\n", total); for(int i = 0; i < vlen; ++i) { //printf("generic... %d, sse2... %d\n", target[i], target2[i]); } for(int i = 0; i < vlen; ++i) { CPPUNIT_ASSERT(target[i] == target2[i]); } } #endif gnuradio-3.7.2.1/volk/lib/qa_16s_add_quad_aligned16.cc0000644000175000017500000000565711744612271022142 0ustar jcorganjcorgan#include #include #include #include #include //test for sse2 #ifndef LV_HAVE_SSE2 void qa_16s_add_quad_aligned16::t1() { printf("sse2 not available... no test performed\n"); } #else void qa_16s_add_quad_aligned16::t1() { volk_environment_init(); clock_t start, end; double total; const int vlen = 3200; const int ITERS = 100000; __VOLK_ATTR_ALIGNED(16) short input0[vlen]; __VOLK_ATTR_ALIGNED(16) short input1[vlen]; __VOLK_ATTR_ALIGNED(16) short input2[vlen]; __VOLK_ATTR_ALIGNED(16) short input3[vlen]; __VOLK_ATTR_ALIGNED(16) short input4[vlen]; __VOLK_ATTR_ALIGNED(16) short output0[vlen]; __VOLK_ATTR_ALIGNED(16) short output1[vlen]; __VOLK_ATTR_ALIGNED(16) short output2[vlen]; __VOLK_ATTR_ALIGNED(16) short output3[vlen]; __VOLK_ATTR_ALIGNED(16) short output01[vlen]; __VOLK_ATTR_ALIGNED(16) short output11[vlen]; __VOLK_ATTR_ALIGNED(16) short output21[vlen]; __VOLK_ATTR_ALIGNED(16) short output31[vlen]; for(int i = 0; i < vlen; ++i) { short plus0 = ((short) (rand() - (RAND_MAX/2))) >> 2; short minus0 = ((short) (rand() - (RAND_MAX/2))) >> 2; short plus1 = ((short) (rand() - (RAND_MAX/2))) >> 2; short minus1 = ((short) (rand() - (RAND_MAX/2))) >> 2; short plus2 = ((short) (rand() - (RAND_MAX/2))) >> 2; short minus2 = ((short) (rand() - (RAND_MAX/2))) >> 2; short plus3 = ((short) (rand() - (RAND_MAX/2))) >> 2; short minus3 = ((short) (rand() - (RAND_MAX/2))) >> 2; short plus4 = ((short) (rand() - (RAND_MAX/2))) >> 2; short minus4 = ((short) (rand() - (RAND_MAX/2))) >> 2; input0[i] = plus0 - minus0; input1[i] = plus1 - minus1; input2[i] = plus2 - minus2; input3[i] = plus3 - minus3; input4[i] = plus4 - minus4; } printf("16s_add_quad_aligned\n"); start = clock(); for(int count = 0; count < ITERS; ++count) { volk_16s_add_quad_aligned16_manual(output0, output1, output2, output3, input0, input1, input2, input3, input4, vlen << 1 , "generic"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("generic_time: %f\n", total); start = clock(); for(int count = 0; count < ITERS; ++count) { volk_16s_add_quad_aligned16_manual(output01, output11, output21, output31, input0, input1, input2, input3, input4, vlen << 1 , "sse2"); } end = clock(); total = (double)(end-start)/(double)CLOCKS_PER_SEC; printf("sse2_time: %f\n", total); for(int i = 0; i < 1; ++i) { //printf("inputs: %d, %d\n", input0[i*2], input0[i*2 + 1]); //printf("generic... %d, ssse3... %d\n", output0[i], output1[i]); } for(int i = 0; i < vlen; ++i) { //printf("%d...%d\n", output0[i], output01[i]); CPPUNIT_ASSERT_EQUAL(output0[i], output01[i]); CPPUNIT_ASSERT_EQUAL(output1[i], output11[i]); CPPUNIT_ASSERT_EQUAL(output2[i], output21[i]); CPPUNIT_ASSERT_EQUAL(output3[i], output31[i]); } } #endif gnuradio-3.7.2.1/volk/volk.pc.in0000644000175000017500000000040211700377701016200 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ LV_CXXFLAGS=@LV_CXXFLAGS@ Name: volk Description: VOLK: Vector Optimized Library of Kernels Requires: Version: @VERSION@ Libs: -lvolk Cflags: -I${includedir} ${LV_CXXFLAGS} gnuradio-3.7.2.1/volk/gen/0000755000175000017500000000000012223554531015050 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/gen/volk_compile_utils.py0000644000175000017500000000416511765410647021344 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import optparse import volk_arch_defs import volk_machine_defs def do_arch_flags_list(compiler): output = list() for arch in volk_arch_defs.archs: if not arch.is_supported(compiler): continue fields = [arch.name] + arch.get_flags(compiler) output.append(','.join(fields)) print ';'.join(output) def do_machines_list(arch_names): output = list() for machine in volk_machine_defs.machines: machine_arch_set = set(machine.arch_names) if set(arch_names).intersection(machine_arch_set) == machine_arch_set: output.append(machine.name) print ';'.join(output) def do_machine_flags_list(compiler, machine_name): output = list() machine = volk_machine_defs.machine_dict[machine_name] for arch in machine.archs: output.extend(arch.get_flags(compiler)) print ' '.join(output) def main(): parser = optparse.OptionParser() parser.add_option('--mode', type='string') parser.add_option('--compiler', type='string') parser.add_option('--archs', type='string') parser.add_option('--machine', type='string') (opts, args) = parser.parse_args() if opts.mode == 'arch_flags': return do_arch_flags_list(opts.compiler.lower()) if opts.mode == 'machines': return do_machines_list(opts.archs.split(';')) if opts.mode == 'machine_flags': return do_machine_flags_list(opts.compiler.lower(), opts.machine) if __name__ == '__main__': main() gnuradio-3.7.2.1/volk/gen/machines.xml0000664000175000017500000000227112207440367017370 0ustar jcorganjcorgan generic orc| generic neon orc| generic 32|64| mmx| sse sse2 orc| generic 32|64 mmx sse sse2 sse3 orc| generic 32|64 mmx sse sse2 sse3 ssse3 orc| generic 32|64 mmx sse sse2 sse3 sse4_a popcount orc| generic 32|64 mmx sse sse2 sse3 ssse3 sse4_1 orc| generic 32|64 mmx sse sse2 sse3 ssse3 sse4_1 sse4_2 popcount orc| generic 32|64| mmx| sse sse2 sse3 ssse3 sse4_1 sse4_2 popcount avx orc| generic altivec gnuradio-3.7.2.1/volk/gen/volk_arch_defs.py0000664000175000017500000000600112207440367020375 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # archs = list() arch_dict = dict() class arch_class: def __init__(self, flags, checks, **kwargs): for key, cast, failval in ( ('name', str, None), ('environment', str, None), ('include', str, None), ('alignment', int, 1) ): try: setattr(self, key, cast(kwargs[key])) except: setattr(self, key, failval) self.checks = checks assert(self.name) self._flags = flags def is_supported(self, compiler): if not self._flags.keys(): return True return compiler in self._flags.keys() def get_flags(self, compiler): try: return self._flags[compiler] except KeyError: return list() def __repr__(self): return self.name def register_arch(**kwargs): arch = arch_class(**kwargs) archs.append(arch) arch_dict[arch.name] = arch ######################################################################## # register the arches ######################################################################## #TODO skip the XML and put it here from xml.dom import minidom import os gendir = os.path.dirname(__file__) archs_xml = minidom.parse(os.path.join(gendir, 'archs.xml')).getElementsByTagName('arch') for arch_xml in archs_xml: kwargs = dict() for attr in arch_xml.attributes.keys(): kwargs[attr] = arch_xml.attributes[attr].value for node in arch_xml.childNodes: try: name = node.tagName val = arch_xml.getElementsByTagName(name)[0].firstChild.data kwargs[name] = val except: pass checks = list() for check_xml in arch_xml.getElementsByTagName("check"): name = check_xml.attributes["name"].value params = list() for param_xml in check_xml.getElementsByTagName("param"): params.append(param_xml.firstChild.data) checks.append([name, params]) flags = dict() for flag_xml in arch_xml.getElementsByTagName("flag"): name = flag_xml.attributes["compiler"].value if not flags.has_key(name): flags[name] = list() flags[name].append(flag_xml.firstChild.data) #force kwargs keys to be of type str, not unicode for py25 kwargs = dict((str(k), v) for k, v in kwargs.iteritems()) register_arch(flags=flags, checks=checks, **kwargs) if __name__ == '__main__': print archs gnuradio-3.7.2.1/volk/gen/volk_tmpl_utils.py0000644000175000017500000000452611765410647020671 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os import re import sys import optparse import volk_arch_defs import volk_machine_defs import volk_kernel_defs from Cheetah import Template def __escape_pre_processor(code): out = list() for line in code.splitlines(): m = re.match('^(\s*)#(\s*)(\w+)(.*)$', line) if m: p0, p1, fcn, stuff = m.groups() conly = fcn in ('include', 'define', 'ifdef', 'ifndef', 'endif', 'elif', 'pragma') both = fcn in ('if', 'else') istmpl = '$' in stuff if 'defined' in stuff: istmpl = False if conly or (both and not istmpl): line = '%s\\#%s%s%s'%(p0, p1, fcn, stuff) out.append(line) return '\n'.join(out) def __parse_tmpl(_tmpl, **kwargs): defs = { 'archs': volk_arch_defs.archs, 'arch_dict': volk_arch_defs.arch_dict, 'machines': volk_machine_defs.machines, 'machine_dict': volk_machine_defs.machine_dict, 'kernels': volk_kernel_defs.kernels, } defs.update(kwargs) _tmpl = __escape_pre_processor(_tmpl) _tmpl = """ /* this file was generated by volk template utils, do not edit! */ """ + _tmpl return str(Template.Template(_tmpl, defs)) def main(): parser = optparse.OptionParser() parser.add_option('--input', type='string') parser.add_option('--output', type='string') (opts, args) = parser.parse_args() output = __parse_tmpl(open(opts.input).read(), args=args) if opts.output: open(opts.output, 'w').write(output) else: print output if __name__ == '__main__': main() gnuradio-3.7.2.1/volk/gen/volk_machine_defs.py0000664000175000017500000000531512207440367021073 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # from volk_arch_defs import arch_dict machines = list() machine_dict = dict() class machine_class: def __init__(self, name, archs): self.name = name self.archs = list() self.arch_names = list() for arch_name in archs: if not arch_name: continue arch = arch_dict[arch_name] self.archs.append(arch) self.arch_names.append(arch_name) self.alignment = max(map(lambda a: a.alignment, self.archs)) def __repr__(self): return self.name def register_machine(name, archs): for i, arch_name in enumerate(archs): if '|' in arch_name: #handle special arch names with the '|' for arch_sub in arch_name.split('|'): if arch_sub: register_machine(name+'_'+arch_sub, archs[:i] + [arch_sub] + archs[i+1:]) else: register_machine(name, archs[:i] + archs[i+1:]) return machine = machine_class(name=name, archs=archs) machines.append(machine) machine_dict[machine.name] = machine ######################################################################## # register the machines ######################################################################## #TODO skip the XML and put it here from xml.dom import minidom import os gendir = os.path.dirname(__file__) machines_xml = minidom.parse(os.path.join(gendir, 'machines.xml')).getElementsByTagName('machine') for machine_xml in machines_xml: kwargs = dict() for attr in machine_xml.attributes.keys(): kwargs[attr] = machine_xml.attributes[attr].value for node in machine_xml.childNodes: try: name = node.tagName val = machine_xml.getElementsByTagName(name)[0].firstChild.data kwargs[name] = val except: pass kwargs['archs'] = kwargs['archs'].split() #force kwargs keys to be of type str, not unicode for py25 kwargs = dict((str(k), v) for k, v in kwargs.iteritems()) register_machine(**kwargs) if __name__ == '__main__': print machines gnuradio-3.7.2.1/volk/gen/volk_kernel_defs.py0000664000175000017500000001776312207440367020761 0ustar jcorganjcorgan# # Copyright 2011-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os import re import sys import glob ######################################################################## # Strip comments from a c/cpp file. # Input is code string, output is code string without comments. # http://stackoverflow.com/questions/241327/python-snippet-to-remove-c-and-c-comments ######################################################################## def comment_remover(text): def replacer(match): s = match.group(0) if s.startswith('/'): return "" else: return s pattern = re.compile( r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE ) return re.sub(pattern, replacer, text) ######################################################################## # Split code into nested sections according to ifdef preprocessor macros ######################################################################## def split_into_nested_ifdef_sections(code): sections = list() section = '' header = 'text' in_section_depth = 0 for i, line in enumerate(code.splitlines()): m = re.match('^(\s*)#(\s*)(\w+)(.*)$', line) line_is = 'normal' if m: p0, p1, fcn, stuff = m.groups() if fcn in ('if', 'ifndef', 'ifdef'): line_is = 'if' if fcn in ('else', 'elif'): line_is = 'else' if fcn in ('endif',): line_is = 'end' if line_is == 'if': in_section_depth += 1 if line_is == 'end': in_section_depth -= 1 if in_section_depth == 1 and line_is == 'if': sections.append((header, section)) section = '' header = line continue if in_section_depth == 1 and line_is == 'else': sections.append((header, section)) section = '' header = line continue if in_section_depth == 0 and line_is == 'end': sections.append((header, section)) section = '' header = 'text' continue section += line + '\n' sections.append((header, section)) #and pack remainder into sections sections = [sec for sec in sections if sec[1].strip()] #filter empty sections #recurse into non-text sections to fill subsections for i, (header, section) in enumerate(sections): if header == 'text': continue sections[i] = (header, split_into_nested_ifdef_sections(section)) return sections ######################################################################## # Recursive print of sections to test code above ######################################################################## def print_sections(sections, indent = ' '): for header, body in sections: if header == 'text': print indent, ('\n'+indent).join(body.splitlines()) continue print indent.replace(' ', '-') + '>', header print_sections(body, indent + ' ') ######################################################################## # Flatten a section to just body text ######################################################################## def flatten_section_text(sections): output = '' for hdr, bdy in sections: if hdr != 'text': output += flatten_section_text(bdy) else: output += bdy return output ######################################################################## # Extract kernel info from section, represent as an implementation ######################################################################## class impl_class: def __init__(self, kern_name, header, body): #extract LV_HAVE_* self.deps = set(map(str.lower, re.findall('LV_HAVE_(\w+)', header))) #extract function suffix and args body = flatten_section_text(body) try: fcn_matcher = re.compile('^.*(%s\\w*)\\s*\\((.*)$'%kern_name, re.DOTALL | re.MULTILINE) body = body.split('{')[0].rsplit(')', 1)[0] #get the part before the open ){ bracket m = fcn_matcher.match(body) impl_name, the_rest = m.groups() self.name = impl_name.replace(kern_name+'_', '') self.args = list() fcn_args = the_rest.split(',') for fcn_arg in fcn_args: arg_matcher = re.compile('^\s*(.*\\W)\s*(\w+)\s*$', re.DOTALL | re.MULTILINE) m = arg_matcher.match(fcn_arg) arg_type, arg_name = m.groups() self.args.append((arg_type, arg_name)) except Exception as ex: raise Exception, 'I cant parse the function prototype from: %s in %s\n%s'%(kern_name, body, ex) assert self.name self.is_aligned = self.name.startswith('a_') def __repr__(self): return self.name ######################################################################## # Get sets of LV_HAVE_* from the code ######################################################################## def extract_lv_haves(code): haves = list() for line in code.splitlines(): if not line.strip().startswith('#'): continue have_set = set(map(str.lower, re.findall('LV_HAVE_(\w+)', line))) if have_set: haves.append(have_set) return haves ######################################################################## # Represent a processing kernel, parse from file ######################################################################## class kernel_class: def __init__(self, kernel_file): self.name = os.path.splitext(os.path.basename(kernel_file))[0] self.pname = self.name.replace('volk_', 'p_') code = open(kernel_file, 'r').read() code = comment_remover(code) sections = split_into_nested_ifdef_sections(code) self._impls = list() for header, section in sections: if 'ifndef' not in header.lower(): continue for sub_hdr, body in section: if 'if' not in sub_hdr.lower(): continue if 'LV_HAVE_' not in sub_hdr: continue self._impls.append(impl_class( kern_name=self.name, header=sub_hdr, body=body, )) assert(self._impls) self.has_dispatcher = False for impl in self._impls: if impl.name == 'dispatcher': self._impls.remove(impl) self.has_dispatcher = True break self.args = self._impls[0].args self.arglist_types = ', '.join([a[0] for a in self.args]) self.arglist_full = ', '.join(['%s %s'%a for a in self.args]) self.arglist_names = ', '.join([a[1] for a in self.args]) def get_impls(self, archs): archs = set(archs) impls = list() for impl in self._impls: if impl.deps.intersection(archs) == impl.deps: impls.append(impl) return impls def __repr__(self): return self.name ######################################################################## # Extract information from the VOLK kernels ######################################################################## __file__ = os.path.abspath(__file__) srcdir = os.path.dirname(os.path.dirname(__file__)) kernel_files = glob.glob(os.path.join(srcdir, "kernels", "volk", "*.h")) kernels = map(kernel_class, kernel_files) if __name__ == '__main__': print kernels gnuradio-3.7.2.1/volk/gen/archs.xml0000664000175000017500000001162112223554531016675 0ustar jcorganjcorgan -maltivec 16 -mfpu=neon -mfloat-abi=softfp -funsafe-math-optimizations 16 -m32 0x80000001 3 0x80000001 29 -m64 -m64 3 0x80000001 31 -m3dnow -m3dnow 8 3 0x80000001 5 -msse4.2 -msse4.2 16 2 0x00000001 23 -mpopcnt -mpopcnt /arch:AVX 3 0x00000001 23 -mmmx -mmmx /arch:SSE 8 3 0x00000001 25 -msse -msse /arch:SSE _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); xmmintrin.h 16 3 0x00000001 26 -msse2 -msse2 /arch:SSE2 16 2 0x00000001 0 -msse3 -msse3 /arch:AVX _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); pmmintrin.h 16 2 0x00000001 9 -mssse3 -mssse3 /arch:AVX 16 2 0x80000001 6 -msse4a -msse4a 16 2 0x00000001 19 -msse4.1 -msse4.1 /arch:AVX 16 2 0x00000001 20 -msse4.2 -msse4.2 /arch:AVX 16 2 0x00000001 28 2 0x00000001 27 -mavx -mavx /arch:AVX 32 gnuradio-3.7.2.1/volk/apps/0000755000175000017500000000000012207440367015245 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/apps/CMakeLists.txt0000664000175000017500000000263312207440367020013 0ustar jcorganjcorgan# # Copyright 2011-2013 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # ######################################################################## # Setup profiler ######################################################################## if(Boost_FOUND) if(MSVC) include_directories(${CMAKE_SOURCE_DIR}/cmake/msvc) endif(MSVC) include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}/include ${CMAKE_BINARY_DIR}/include ${CMAKE_SOURCE_DIR}/lib ${Boost_INCLUDE_DIRS} ) add_executable(volk_profile ${CMAKE_CURRENT_SOURCE_DIR}/volk_profile.cc ${CMAKE_SOURCE_DIR}/lib/qa_utils.cc ) target_link_libraries(volk_profile volk ${Boost_LIBRARIES}) install( TARGETS volk_profile DESTINATION bin COMPONENT "volk" ) endif(Boost_FOUND) gnuradio-3.7.2.1/volk/apps/volk_profile.cc0000664000175000017500000002032612207440367020254 0ustar jcorganjcorgan#include "qa_utils.h" #include #include #include #include #include #include #include #include #include #include namespace fs = boost::filesystem; int main(int argc, char *argv[]) { std::vector results; //VOLK_PROFILE(volk_16i_x5_add_quad_16i_x4, 1e-4, 2046, 10000, &results); //VOLK_PROFILE(volk_16i_branch_4_state_8, 1e-4, 2046, 10000, &results); VOLK_PUPPET_PROFILE(volk_32fc_s32fc_rotatorpuppet_32fc, volk_32fc_s32fc_x2_rotator_32fc, 1e-2, (lv_32fc_t)lv_cmake(.95393, .3), 20462, 10000, &results); VOLK_PROFILE(volk_16ic_s32f_deinterleave_real_32f, 1e-5, 32768.0, 204602, 10000, &results); VOLK_PROFILE(volk_16ic_deinterleave_real_8i, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_16ic_deinterleave_16i_x2, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_16ic_s32f_deinterleave_32f_x2, 1e-4, 32768.0, 204602, 1000, &results); VOLK_PROFILE(volk_16ic_deinterleave_real_16i, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_16ic_magnitude_16i, 1, 0, 204602, 100, &results); VOLK_PROFILE(volk_16ic_s32f_magnitude_32f, 1e-5, 32768.0, 204602, 1000, &results); VOLK_PROFILE(volk_16i_s32f_convert_32f, 1e-4, 32768.0, 204602, 10000, &results); VOLK_PROFILE(volk_16i_convert_8i, 0, 0, 204602, 10000, &results); //VOLK_PROFILE(volk_16i_max_star_16i, 0, 0, 204602, 10000, &results); //VOLK_PROFILE(volk_16i_max_star_horizontal_16i, 0, 0, 204602, 10000, &results); //VOLK_PROFILE(volk_16i_permute_and_scalar_add, 1e-4, 0, 2046, 10000, &results); //VOLK_PROFILE(volk_16i_x4_quad_max_star_16i, 1e-4, 0, 2046, 10000, &results); VOLK_PROFILE(volk_16u_byteswap, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_16i_32fc_dot_prod_32fc, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32f_accumulator_s32f, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32f_x2_add_32f, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_32f_multiply_32fc, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_s32f_power_32fc, 1e-4, 0, 204602, 50, &results); VOLK_PROFILE(volk_32f_s32f_calc_spectral_noise_floor_32f, 1e-4, 20.0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_s32f_atan2_32f, 1e-4, 10.0, 204602, 100, &results); //VOLK_PROFILE(volk_32fc_x2_conjugate_dot_prod_32fc, 1e-4, 0, 2046, 10000, &results); VOLK_PROFILE(volk_32fc_x2_conjugate_dot_prod_32fc, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_deinterleave_32f_x2, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_deinterleave_64f_x2, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_s32f_deinterleave_real_16i, 0, 32768, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_deinterleave_imag_32f, 1e-4, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32fc_deinterleave_real_32f, 1e-4, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32fc_deinterleave_real_64f, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_x2_dot_prod_32fc, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_32f_dot_prod_32fc, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_index_max_16u, 3, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_s32f_magnitude_16i, 1, 32768, 204602, 100, &results); VOLK_PROFILE(volk_32fc_magnitude_32f, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_magnitude_squared_32f, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_x2_multiply_32fc, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_x2_multiply_conjugate_32fc, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32fc_conjugate_32fc, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32f_s32f_convert_16i, 1, 32768, 204602, 10000, &results); VOLK_PROFILE(volk_32f_s32f_convert_32i, 1, 2<<31, 204602, 10000, &results); VOLK_PROFILE(volk_32f_convert_64f, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32f_s32f_convert_8i, 1, 128, 204602, 10000, &results); //VOLK_PROFILE(volk_32fc_s32f_x2_power_spectral_density_32f, 1e-4, 2046, 10000, &results); VOLK_PROFILE(volk_32fc_s32f_power_spectrum_32f, 1e-4, 0, 20462, 100, &results); VOLK_PROFILE(volk_32fc_x2_square_dist_32f, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32fc_x2_s32f_square_dist_scalar_mult_32f, 1e-4, 10, 204602, 10000, &results); VOLK_PROFILE(volk_32f_x2_divide_32f, 1e-4, 0, 204602, 2000, &results); VOLK_PROFILE(volk_32f_x2_dot_prod_32f, 1e-4, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32f_x2_dot_prod_16i, 1e-4, 0, 204602, 5000, &results); //VOLK_PROFILE(volk_32f_s32f_32f_fm_detect_32f, 1e-4, 2046, 10000, &results); VOLK_PROFILE(volk_32f_index_max_16u, 3, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32f_x2_s32f_interleave_16ic, 1, 32768, 204602, 3000, &results); VOLK_PROFILE(volk_32f_x2_interleave_32fc, 0, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32f_x2_max_32f, 1e-4, 0, 204602, 2000, &results); VOLK_PROFILE(volk_32f_x2_min_32f, 1e-4, 0, 204602, 2000, &results); VOLK_PROFILE(volk_32f_x2_multiply_32f, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32f_s32f_normalize, 1e-4, 100, 204602, 10000, &results); VOLK_PROFILE(volk_32f_s32f_power_32f, 1e-4, 4, 204602, 100, &results); VOLK_PROFILE(volk_32f_sqrt_32f, 1e-4, 0, 204602, 100, &results); VOLK_PROFILE(volk_32f_s32f_stddev_32f, 1e-4, 100, 204602, 3000, &results); VOLK_PROFILE(volk_32f_stddev_and_mean_32f_x2, 1e-4, 0, 204602, 3000, &results); VOLK_PROFILE(volk_32f_x2_subtract_32f, 1e-4, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32f_x3_sum_of_poly_32f, 1e-4, 0, 204602, 5000, &results); VOLK_PROFILE(volk_32i_x2_and_32i, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32i_s32f_convert_32f, 1e-4, 100, 204602, 10000, &results); VOLK_PROFILE(volk_32i_x2_or_32i, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_32u_byteswap, 0, 0, 204602, 2000, &results); //VOLK_PROFILE(volk_32u_popcnt, 0, 0, 2046, 10000, &results); VOLK_PROFILE(volk_64f_convert_32f, 1e-4, 0, 204602, 10000, &results); VOLK_PROFILE(volk_64f_x2_max_64f, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_64f_x2_min_64f, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_64u_byteswap, 0, 0, 204602, 1000, &results); //VOLK_PROFILE(volk_64u_popcnt, 0, 0, 2046, 10000, &results); VOLK_PROFILE(volk_8ic_deinterleave_16i_x2, 0, 0, 204602, 3000, &results); VOLK_PROFILE(volk_8ic_s32f_deinterleave_32f_x2, 1e-4, 100, 204602, 3000, &results); VOLK_PROFILE(volk_8ic_deinterleave_real_16i, 0, 256, 204602, 3000, &results); VOLK_PROFILE(volk_8ic_s32f_deinterleave_real_32f, 1e-4, 100, 204602, 3000, &results); VOLK_PROFILE(volk_8ic_deinterleave_real_8i, 0, 0, 204602, 10000, &results); VOLK_PROFILE(volk_8ic_x2_multiply_conjugate_16ic, 0, 0, 204602, 400, &results); VOLK_PROFILE(volk_8ic_x2_s32f_multiply_conjugate_32fc, 1e-4, 100, 204602, 400, &results); VOLK_PROFILE(volk_8i_convert_16i, 0, 0, 204602, 20000, &results); VOLK_PROFILE(volk_8i_convert_16i, 0, 0, 204602, 2000, &results); VOLK_PROFILE(volk_8i_s32f_convert_32f, 1e-4, 100, 204602, 2000, &results); //VOLK_PROFILE(volk_32fc_s32fc_multiply_32fc, 1e-4, lv_32fc_t(1.0, 0.5), 204602, 1000, &results); VOLK_PROFILE(volk_32fc_s32fc_multiply_32fc, 1e-4, 0, 204602, 1000, &results); VOLK_PROFILE(volk_32f_s32f_multiply_32f, 1e-4, 1.0, 204602, 10000, &results); char path[1024]; volk_get_config_path(path); const fs::path config_path(path); if (not fs::exists(config_path.branch_path())) { std::cout << "Creating " << config_path.branch_path() << "..." << std::endl; fs::create_directories(config_path.branch_path()); } std::cout << "Writing " << config_path << "..." << std::endl; std::ofstream config(config_path.string().c_str()); if(!config.is_open()) { //either we don't have write access or we don't have the dir yet std::cout << "Error opening file " << config_path << std::endl; } config << "\ #this file is generated by volk_profile.\n\ #the function name is followed by the preferred architecture.\n\ "; BOOST_FOREACH(std::string result, results) { config << result << std::endl; } config.close(); } gnuradio-3.7.2.1/volk/spu_lib/0000755000175000017500000000000011744612271015737 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/spu_lib/spu_memset_unaligned.S0000644000175000017500000001047711744612271022303 0ustar jcorganjcorgan/* -*- asm -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "gc_spu_macs.h" .file "spu_memset_unaligned.S" /* * Computes this, only a lot faster... * * void * * libvector_memset_unaligned(void *pv, int c, size_t n) * { * unsigned char *p = (unsigned char *) pv; * size_t i; * for (i = 0; i < n; i++) * p[i] = c; * * return pv; * } */ #define p_arg arg1 // we're going to clobber arg1 w/ the return value #define c arg2 // the constant we're writing #define n arg3 // how many bytes to write #define p r13 // where we're writing #define t0 r14 #define t1 r15 #define mask r16 #define old r17 #define an r18 // aligned n (n rounded down to mod 16 boundary) #define next_p r19 #define cond1 r20 #define cond2 r21 #define m r22 #define r r23 PROC_ENTRY(libvector_memset_unaligned) // Hint the return from do_head, in case we go that way. // There's pretty much nothing to can do to hint the branch to it. hbrr do_head_br, head_complete MR(p, p_arg) // leaves p, the return value, in the correct reg (r3) BRZ_RETURN(n) MODULO(t0, p, 16) // is p%16 == 0? VSPLTB(c, c, 3) // splat byte in preferred slot of c into all slots brnz t0, do_head // no, handle it head_complete: /* * preconditions: * p%16 == 0, n > 0 */ hbrr middle_loop_br, middle_loop ROUND_DOWN(an, n, 16) // an is "aligned n" MODULO(n, n, 16) // what's left over in the last quad brz an, do_tail // no whole quad words; skip to tail clgti t0, an, 127 // an >= 128? brz t0, middle2 // nope, go handle the cases between 0 and 112 /* * 128 bytes / iteration */ .p2align 4 middle_loop: ai an, an, -128 stqd c, 0*16(p) ai next_p, p, 128 stqd c, 1*16(p) cgti cond1, an, 127 stqd c, 2*16(p) stqd c, 3*16(p) stqd c, 4*16(p) stqd c, 5*16(p) stqd c, 6*16(p) MR(p, next_p) stqd c, 7*16-128(next_p) or cond2, n, an middle_loop_br: brnz cond1, middle_loop /* * if an and n are both zero, return now */ BRZ_RETURN(cond2) /* * otherwise handle last of full quad words * * 0 <= an < 128, p%16 == 0 */ middle2: /* * if an == 0, go handle the final non-full quadword */ brz an, do_tail hbrr middle2_loop_br, middle2_loop .p2align 3 middle2_loop: ai next_p, p, 16 stqd c, 0(p) ai an, an, -16 LMR(p, next_p) middle2_loop_br: brnz an, middle2_loop /* We're done with the full quadwords. */ /* * Handle the final partial quadword. * We'll be modifying only the left hand portion of the quad. * * preconditions: * an == 0, 0 <= n < 16, p%16 == 0 */ do_tail: HINT_RETURN(do_tail_ret) il mask, -1 sfi t1, n, 16 // t1 = 16 - n lqd old, 0(p) shlqby mask, mask, t1 selb t0, old, c, mask stqd t0, 0(p) do_tail_ret: RETURN() /* * ---------------------------------------------------------------- * Handle the first partial quadword * * preconditions: * p%16 != 0 * * postconditions: * p%16 == 0 or n == 0 * * |-- m --| * +----------------+----------------+ * | //////// | | * +----------------+----------------+ * |----- r -----| * p * ---------------------------------------------------------------- */ do_head: lqd old, 0(p) MODULO_NEG(r, p, 16) il mask, -1 UMIN(m, r, n) shlqby mask, mask, m // 1's in the top, m*8 0's in the bottom MR(t1, p) sf t0, m, r // t0 = r - m a p, p, m // p += m rotqby mask, mask, t0 // rotate 0's to the right place sf n, m, n // n -= m selb t0, c, old, mask // merge stqd t0, 0(t1) BRZ_RETURN(n) do_head_br: br head_complete gnuradio-3.7.2.1/volk/spu_lib/spu_16s_cmpgt_unaligned.c0000644000175000017500000001236211744612271022627 0ustar jcorganjcorgan#include void* libvector_16s_cmpgt_unaligned(void* target, void* src, signed short val, unsigned int num_bytes){ //loop iterator i int i = 0; void* retval = target; //put the target and source addresses into qwords vector unsigned int address_counter_tgt = {(unsigned int)target, 0, 0, 0}; vector unsigned int address_counter_src = {(unsigned int)src, 0, 0 ,0}; //create shuffle masks //shuffle mask building blocks: //all from the first vector vector unsigned char oneup = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; //all from the second vector vector unsigned char second_oneup = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; //gamma: second half of the second, first half of the first, break at (unsigned int)src%16 vector unsigned char src_cmp = spu_splats((unsigned char)((unsigned int)src%16)); vector unsigned char gt_res = spu_cmpgt(oneup, src_cmp); vector unsigned char eq_res = spu_cmpeq(oneup, src_cmp); vector unsigned char cmp_res = spu_or(gt_res, eq_res); vector unsigned char sixteen_uchar = spu_splats((unsigned char)16); vector unsigned char phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_gamma = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_gamma = spu_rlqwbyte(shuffle_mask_gamma, (unsigned int)src%16); vector unsigned char tgt_second = spu_rlqwbyte(second_oneup, -((unsigned int)target%16)); vector unsigned char tgt_first = spu_rlqwbyte(oneup, -((unsigned int)target%16)); //alpha: first half of first, second half of second, break at (unsigned int)target%16 src_cmp = spu_splats((unsigned char)((unsigned int)target%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_alpha = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); //delta: first half of first, first half of second, break at (unsigned int)target%16 vector unsigned char shuffle_mask_delta = spu_shuffle(oneup, tgt_second, (vector unsigned char)shuffle_mask_alpha); //epsilon: second half of second, second half of first, break at (unsigned int)target%16 vector unsigned char shuffle_mask_epsilon = spu_shuffle(tgt_second, oneup, (vector unsigned char)shuffle_mask_alpha); //zeta: second half of second, first half of first, break at 16 - (unsigned int)target%16 vector unsigned int shuffle_mask_zeta = spu_rlqwbyte(shuffle_mask_alpha, (unsigned int)target%16); //beta: first half of first, second half of second, break at num_bytes%16 src_cmp = spu_splats((unsigned char)(num_bytes%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_beta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); qword src_past; qword src_present; qword tgt_past; qword tgt_present; qword in_temp; qword out_temp0; qword out_temp1; src_past = si_lqd((qword)address_counter_src, 0); tgt_past = si_lqd((qword)address_counter_tgt, 0); vector signed short vec_val = spu_splats(val); vector unsigned short compare; vector unsigned short ones = {1, 1, 1, 1, 1, 1, 1, 1}; vector unsigned short after_and; for(i = 0; i < num_bytes/16; ++i) { src_present = si_lqd((qword)address_counter_src, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp = spu_shuffle(src_present, src_past, (vector unsigned char)shuffle_mask_gamma); compare = spu_cmpgt((vector signed short) in_temp, vec_val); after_and = spu_and(compare, ones); out_temp0 = spu_shuffle(tgt_past, (qword)after_and, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, (qword)after_and, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); tgt_past = out_temp1; src_past = src_present; address_counter_src = spu_add(address_counter_src, 16); address_counter_tgt = spu_add(address_counter_tgt, 16); } src_present = si_lqd((qword)address_counter_src, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp = spu_shuffle(src_present, src_past,(vector unsigned char) shuffle_mask_gamma); compare = spu_cmpgt((vector signed short) in_temp, vec_val); after_and = spu_and(compare, ones); qword target_temp = spu_shuffle(tgt_present, tgt_past, (vector unsigned char) shuffle_mask_zeta); qword meld = spu_shuffle((qword)after_and, target_temp, (vector unsigned char)shuffle_mask_beta); out_temp0 = spu_shuffle(tgt_past, meld, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, meld, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); return retval; } /* int main(){ signed short pooh[48]; signed short bear[48]; int i = 0; for(i = 0; i < 48; i += 2){ bear[i] = i; bear[i + 1] = -i; } vector_gt_16bit(&pooh[0],&bear[0], 0, 48 * sizeof(signed short)); for(i = 0; i < 48; ++i) { printf("%d, ", pooh[i]); } printf("\n"); } */ gnuradio-3.7.2.1/volk/spu_lib/spu_32fc_pointwise_multiply_unaligned.c0000644000175000017500000001743711744612271025631 0ustar jcorganjcorgan#include void* libvector_pointwise_multiply_32fc_unaligned(void* target, void* src0, void* src1, unsigned int num_bytes){ //loop iterator i int i = 0; void* retval = target; //put the target and source addresses into qwords vector unsigned int address_counter_tgt = {(unsigned int)target, 0, 0, 0}; vector unsigned int address_counter_src0 = {(unsigned int)src0, 0, 0 ,0}; vector unsigned int address_counter_src1 = {(unsigned int)src1, 0, 0, 0}; //create shuffle masks //shuffle mask building blocks: //all from the first vector vector unsigned char oneup = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; //all from the second vector vector unsigned char second_oneup = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; //gamma: second half of the second, first half of the first, break at (unsigned int)src0%16 vector unsigned char src_cmp = spu_splats((unsigned char)((unsigned int)src0%16)); vector unsigned char gt_res = spu_cmpgt(oneup, src_cmp); vector unsigned char eq_res = spu_cmpeq(oneup, src_cmp); vector unsigned char cmp_res = spu_or(gt_res, eq_res); vector unsigned char sixteen_uchar = spu_splats((unsigned char)16); vector unsigned char phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_gamma = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_gamma = spu_rlqwbyte(shuffle_mask_gamma, (unsigned int)src0%16); //eta: second half of the second, first half of the first, break at (unsigned int)src1%16 src_cmp = spu_splats((unsigned char)((unsigned int)src1%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); sixteen_uchar = spu_splats((unsigned char)16); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_eta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_eta = spu_rlqwbyte(shuffle_mask_eta, (unsigned int)src1%16); vector unsigned char tgt_second = spu_rlqwbyte(second_oneup, -((unsigned int)target%16)); vector unsigned char tgt_first = spu_rlqwbyte(oneup, -((unsigned int)target%16)); //alpha: first half of first, second half of second, break at (unsigned int)target%16 src_cmp = spu_splats((unsigned char)((unsigned int)target%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_alpha = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); //delta: first half of first, first half of second, break at (unsigned int)target%16 vector unsigned char shuffle_mask_delta = spu_shuffle(oneup, tgt_second, (vector unsigned char)shuffle_mask_alpha); //epsilon: second half of second, second half of first, break at (unsigned int)target%16 vector unsigned char shuffle_mask_epsilon = spu_shuffle(tgt_second, oneup, (vector unsigned char)shuffle_mask_alpha); //zeta: second half of second, first half of first, break at 16 - (unsigned int)target%16 vector unsigned int shuffle_mask_zeta = spu_rlqwbyte(shuffle_mask_alpha, (unsigned int)target%16); //beta: first half of first, second half of second, break at num_bytes%16 src_cmp = spu_splats((unsigned char)(num_bytes%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_beta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); qword src0_past; qword src0_present; qword src1_past; qword src1_present; qword tgt_past; qword tgt_present; qword in_temp0; qword in_temp1; qword out_temp0; qword out_temp1; src0_past = si_lqd((qword)address_counter_src0, 0); src1_past = si_lqd((qword)address_counter_src1, 0); tgt_past = si_lqd((qword)address_counter_tgt, 0); vector unsigned char shuffle_mask_complexprod0 = {0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b}; vector unsigned char shuffle_mask_complexprod1 = {0x00, 0x01, 0x02, 0x03, 0x10, 0x11, 0x12, 0x13, 0x08, 0x09, 0x0a, 0x0b, 0x18, 0x19, 0x1a, 0x1b}; vector unsigned char shuffle_mask_complexprod2 = {0x04, 0x05, 0x06, 0x07, 0x14, 0x15, 0x16, 0x17, 0x0c, 0x0d, 0x0e, 0x0f, 0x1c, 0x1d, 0x1e, 0x1f}; vector unsigned char sign_changer = {0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00}; vector float prod0; qword shuf0; vector float prod1; vector float sign_change; qword summand0; qword summand1; vector float sum; for(i = 0; i < num_bytes/16; ++i) { src0_present = si_lqd((qword)address_counter_src0, 16); src1_present = si_lqd((qword)address_counter_src1, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp0 = spu_shuffle(src0_present, src0_past, (vector unsigned char)shuffle_mask_gamma); in_temp1 = spu_shuffle(src1_present, src1_past, (vector unsigned char)shuffle_mask_eta); prod0 = spu_mul((vector float)in_temp0, (vector float)in_temp1); shuf0 = spu_shuffle((qword)in_temp1, (qword)in_temp1, shuffle_mask_complexprod0); prod1 = spu_mul((vector float)in_temp0, (vector float)shuf0); sign_change = spu_xor(prod0, (vector float)sign_changer); summand0 = spu_shuffle((qword)sign_change, (qword)prod1, shuffle_mask_complexprod1); summand1 = spu_shuffle((qword)sign_change, (qword)prod1, shuffle_mask_complexprod2); sum = spu_add((vector float)summand0, (vector float)summand1); out_temp0 = spu_shuffle(tgt_past, (qword)sum, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, (qword)sum, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); tgt_past = out_temp1; src0_past = src0_present; src1_past = src1_present; address_counter_src0 = spu_add(address_counter_src0, 16); address_counter_src1 = spu_add(address_counter_src1, 16); address_counter_tgt = spu_add(address_counter_tgt, 16); } src0_present = si_lqd((qword)address_counter_src0, 16); src1_present = si_lqd((qword)address_counter_src1, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp0 = spu_shuffle(src0_present, src0_past, (vector unsigned char) shuffle_mask_gamma); in_temp1 = spu_shuffle(src1_present, src1_past, (vector unsigned char) shuffle_mask_eta); prod0 = spu_mul((vector float)in_temp0, (vector float)in_temp1); shuf0 = spu_shuffle((qword)in_temp1, (qword)in_temp1, shuffle_mask_complexprod0); prod1 = spu_mul(prod0, (vector float)shuf0); sign_change = spu_xor(prod0, (vector float)sign_changer); summand0 = spu_shuffle((qword)sign_change, (qword)prod1, shuffle_mask_complexprod1); summand1 = spu_shuffle((qword)sign_change, (qword)prod1, shuffle_mask_complexprod2); sum = spu_add((vector float)summand0, (vector float)summand1); qword target_temp = spu_shuffle(tgt_present, tgt_past, (vector unsigned char) shuffle_mask_zeta); qword meld = spu_shuffle((qword)sum, target_temp, (vector unsigned char)shuffle_mask_beta); out_temp0 = spu_shuffle(tgt_past, meld, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, meld, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); return retval; } /* int main(){ float pooh[48]; float bear[48]; float res[48]; int i = 0; for(i = 0; i < 48; ++i){ pooh[i] = (float) i; } for(i = 48; i < 96; ++i){ bear[i - 48] = (float) i; } vector_product_complex(res, pooh, bear, 48*sizeof(float)); for(i = 0; i < 48; ++i) { printf("%f, ", res[i]); } printf("\n"); } */ gnuradio-3.7.2.1/volk/spu_lib/spu_16s_vector_subtract_unaligned.c0000644000175000017500000001435111744612271024726 0ustar jcorganjcorgan#include void* libvector_16s_vector_subtract_unaligned(void* target, void* src0, void* src1, unsigned int num_bytes){ //loop iterator i int i = 0; void* retval = target; //put the target and source addresses into qwords vector unsigned int address_counter_tgt = {(unsigned int)target, 0, 0, 0}; vector unsigned int address_counter_src0 = {(unsigned int)src0, 0, 0 ,0}; vector unsigned int address_counter_src1 = {(unsigned int)src1, 0, 0, 0}; //create shuffle masks //shuffle mask building blocks: //all from the first vector vector unsigned char oneup = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; //all from the second vector vector unsigned char second_oneup = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; //gamma: second half of the second, first half of the first, break at (unsigned int)src0%16 vector unsigned char src_cmp = spu_splats((unsigned char)((unsigned int)src0%16)); vector unsigned char gt_res = spu_cmpgt(oneup, src_cmp); vector unsigned char eq_res = spu_cmpeq(oneup, src_cmp); vector unsigned char cmp_res = spu_or(gt_res, eq_res); vector unsigned char sixteen_uchar = spu_splats((unsigned char)16); vector unsigned char phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_gamma = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_gamma = spu_rlqwbyte(shuffle_mask_gamma, (unsigned int)src0%16); //eta: second half of the second, first half of the first, break at (unsigned int)src1%16 src_cmp = spu_splats((unsigned char)((unsigned int)src1%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); sixteen_uchar = spu_splats((unsigned char)16); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_eta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_eta = spu_rlqwbyte(shuffle_mask_eta, (unsigned int)src1%16); vector unsigned char tgt_second = spu_rlqwbyte(second_oneup, -((unsigned int)target%16)); vector unsigned char tgt_first = spu_rlqwbyte(oneup, -((unsigned int)target%16)); //alpha: first half of first, second half of second, break at (unsigned int)target%16 src_cmp = spu_splats((unsigned char)((unsigned int)target%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_alpha = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); //delta: first half of first, first half of second, break at (unsigned int)target%16 vector unsigned char shuffle_mask_delta = spu_shuffle(oneup, tgt_second, (vector unsigned char)shuffle_mask_alpha); //epsilon: second half of second, second half of first, break at (unsigned int)target%16 vector unsigned char shuffle_mask_epsilon = spu_shuffle(tgt_second, oneup, (vector unsigned char)shuffle_mask_alpha); //zeta: second half of second, first half of first, break at 16 - (unsigned int)target%16 vector unsigned int shuffle_mask_zeta = spu_rlqwbyte(shuffle_mask_alpha, (unsigned int)target%16); //beta: first half of first, second half of second, break at num_bytes%16 src_cmp = spu_splats((unsigned char)(num_bytes%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_beta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); qword src0_past; qword src0_present; qword src1_past; qword src1_present; qword tgt_past; qword tgt_present; qword in_temp0; qword in_temp1; qword out_temp0; qword out_temp1; vector signed short sum; src0_past = si_lqd((qword)address_counter_src0, 0); src1_past = si_lqd((qword)address_counter_src1, 0); tgt_past = si_lqd((qword)address_counter_tgt, 0); for(i = 0; i < num_bytes/16; ++i) { src0_present = si_lqd((qword)address_counter_src0, 16); src1_present = si_lqd((qword)address_counter_src1, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp0 = spu_shuffle(src0_present, src0_past, (vector unsigned char)shuffle_mask_gamma); in_temp1 = spu_shuffle(src1_present, src1_past, (vector unsigned char)shuffle_mask_eta); sum = spu_sub((vector signed short)in_temp0, (vector signed short)in_temp1); out_temp0 = spu_shuffle(tgt_past, (qword)sum, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, (qword)sum, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); tgt_past = out_temp1; src0_past = src0_present; src1_past = src1_present; address_counter_src0 = spu_add(address_counter_src0, 16); address_counter_src1 = spu_add(address_counter_src1, 16); address_counter_tgt = spu_add(address_counter_tgt, 16); } src0_present = si_lqd((qword)address_counter_src0, 16); src1_present = si_lqd((qword)address_counter_src1, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp0 = spu_shuffle(src0_present, src0_past, (vector unsigned char) shuffle_mask_gamma); in_temp1 = spu_shuffle(src1_present, src1_past, (vector unsigned char) shuffle_mask_eta); sum = spu_sub((vector signed short)in_temp0, (vector signed short)in_temp1); qword target_temp = spu_shuffle(tgt_present, tgt_past, (vector unsigned char) shuffle_mask_zeta); qword meld = spu_shuffle((qword)sum, target_temp, (vector unsigned char)shuffle_mask_beta); out_temp0 = spu_shuffle(tgt_past, meld, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, meld, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); return retval; } /* int main(){ signed short pooh[48]; signed short bear[48]; signed short res[48]; int i = 0; for(i = 0; i < 48; ++i){ pooh[i] = i; } for(i = 48; i < 96; ++i){ bear[i - 48] = i; } vector_subtract_16bit(res, &pooh[0], &bear[0], 48 * sizeof(signed short)); for(i = 0; i < 48; ++i) { printf("%d, ", res[i]); } printf("\n"); } */ gnuradio-3.7.2.1/volk/spu_lib/gc_spu_macs.h0000644000175000017500000002035411744612271020377 0ustar jcorganjcorgan/* -*- asm -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GC_SPU_MACS_H #define INCLUDED_GC_SPU_MACS_H /* * This file contains a set of macros that are generally useful when * coding in SPU assembler * * Note that the multi-instruction macros in here may overwrite * registers 77, 78, and 79 without warning. */ /* * defines for all registers */ #define r0 $0 #define r1 $1 #define r2 $2 #define r3 $3 #define r4 $4 #define r5 $5 #define r6 $6 #define r7 $7 #define r8 $8 #define r9 $9 #define r10 $10 #define r11 $11 #define r12 $12 #define r13 $13 #define r14 $14 #define r15 $15 #define r16 $16 #define r17 $17 #define r18 $18 #define r19 $19 #define r20 $20 #define r21 $21 #define r22 $22 #define r23 $23 #define r24 $24 #define r25 $25 #define r26 $26 #define r27 $27 #define r28 $28 #define r29 $29 #define r30 $30 #define r31 $31 #define r32 $32 #define r33 $33 #define r34 $34 #define r35 $35 #define r36 $36 #define r37 $37 #define r38 $38 #define r39 $39 #define r40 $40 #define r41 $41 #define r42 $42 #define r43 $43 #define r44 $44 #define r45 $45 #define r46 $46 #define r47 $47 #define r48 $48 #define r49 $49 #define r50 $50 #define r51 $51 #define r52 $52 #define r53 $53 #define r54 $54 #define r55 $55 #define r56 $56 #define r57 $57 #define r58 $58 #define r59 $59 #define r60 $60 #define r61 $61 #define r62 $62 #define r63 $63 #define r64 $64 #define r65 $65 #define r66 $66 #define r67 $67 #define r68 $68 #define r69 $69 #define r70 $70 #define r71 $71 #define r72 $72 #define r73 $73 #define r74 $74 #define r75 $75 #define r76 $76 #define r77 $77 #define r78 $78 #define r79 $79 #define r80 $80 #define r81 $81 #define r82 $82 #define r83 $83 #define r84 $84 #define r85 $85 #define r86 $86 #define r87 $87 #define r88 $88 #define r89 $89 #define r90 $90 #define r91 $91 #define r92 $92 #define r93 $93 #define r94 $94 #define r95 $95 #define r96 $96 #define r97 $97 #define r98 $98 #define r99 $99 #define r100 $100 #define r101 $101 #define r102 $102 #define r103 $103 #define r104 $104 #define r105 $105 #define r106 $106 #define r107 $107 #define r108 $108 #define r109 $109 #define r110 $110 #define r111 $111 #define r112 $112 #define r113 $113 #define r114 $114 #define r115 $115 #define r116 $116 #define r117 $117 #define r118 $118 #define r119 $119 #define r120 $120 #define r121 $121 #define r122 $122 #define r123 $123 #define r124 $124 #define r125 $125 #define r126 $126 #define r127 $127 #define lr r0 // link register #define sp r1 // stack pointer // r2 is environment pointer for langs that need it (ALGOL) #define retval r3 // return values are passed in regs starting at r3 #define arg1 r3 // args are passed in regs starting at r3 #define arg2 r4 #define arg3 r5 #define arg4 r6 #define arg5 r7 #define arg6 r8 #define arg7 r9 #define arg8 r10 #define arg9 r11 #define arg10 r12 // r3 - r74 are volatile (caller saves) // r74 - r79 are volatile (scratch regs possibly destroyed by fct prolog/epilog) // r80 - r127 are non-volatile (caller-saves) // scratch registers reserved for use by the macros in this file. #define _gc_t0 r79 #define _gc_t1 r78 #define _gc_t2 r77 /* * ---------------------------------------------------------------- * pseudo ops * ---------------------------------------------------------------- */ #define PROC_ENTRY(name) \ .text; \ .p2align 4; \ .global name; \ .type name, @function; \ name: /* * ---------------------------------------------------------------- * aliases for common operations * ---------------------------------------------------------------- */ // Move register (even pipe, 2 cycles) #define MR(rt, ra) or rt, ra, ra; // Move register (odd pipe, 4 cycles) #define LMR(rt, ra) rotqbyi rt, ra, 0; // return #define RETURN() bi lr; // hint for a return #define HINT_RETURN(ret_label) hbr ret_label, lr; // return if zero #define BRZ_RETURN(rt) biz rt, lr; // return if not zero #define BRNZ_RETURN(rt) binz rt, lr; // return if halfword zero #define BRHZ_RETURN(rt) bihz rt, lr; // return if halfword not zero #define BRHNZ_RETURN(rt) bihnz rt, lr; /* * ---------------------------------------------------------------- * modulo like things for constant moduli that are powers of 2 * ---------------------------------------------------------------- */ // rt = ra & (pow2 - 1) #define MODULO(rt, ra, pow2) \ andi rt, ra, (pow2)-1; // rt = pow2 - (ra & (pow2 - 1)) #define MODULO_NEG(rt, ra, pow2) \ andi rt, ra, (pow2)-1; \ sfi rt, rt, (pow2); // rt = ra & -(pow2) #define ROUND_DOWN(rt, ra, pow2) \ andi rt, ra, -(pow2); // rt = (ra + (pow2 - 1)) & -(pow2) #define ROUND_UP(rt, ra, pow2) \ ai rt, ra, (pow2)-1; \ andi rt, rt, -(pow2); /* * ---------------------------------------------------------------- * Splat - replicate a particular slot into all slots * Altivec analogs... * ---------------------------------------------------------------- */ // replicate byte from slot s [0,15] #define VSPLTB(rt, ra, s) \ ilh _gc_t0, (s)*0x0101; \ shufb rt, ra, ra, _gc_t0; // replicate halfword from slot s [0,7] #define VSPLTH(rt, ra, s) \ ilh _gc_t0, 2*(s)*0x0101 + 0x0001; \ shufb rt, ra, ra, _gc_t0; // replicate word from slot s [0,3] #define VSPLTW(rt, ra, s) \ iluh _gc_t0, 4*(s)*0x0101 + 0x0001; \ iohl _gc_t0, 4*(s)*0x0101 + 0x0203; \ shufb rt, ra, ra, _gc_t0; // replicate double from slot s [0,1] #define VSPLTD(rt, ra, s) \ /* sp is always 16-byte aligned */ \ cdd _gc_t0, 8(sp); /* 0x10111213 14151617 00010203 04050607 */ \ rotqbyi rt, ra, ra, (s) << 3; /* rotate double into preferred slot */ \ shufb rt, rt, rt, _gc_t0; /* * ---------------------------------------------------------------- * lots of min/max variations... * * On a slot by slot basis, compute the min or max * * U - unsigned, else signed * B,H,{} - byte, halfword, word * F float * ---------------------------------------------------------------- */ #define MIN_SELB(rt, ra, rb, rc) selb rt, ra, rb, rc; #define MAX_SELB(rt, ra, rb, rc) selb rt, rb, ra, rc; // words #define MIN(rt, ra, rb) \ cgt _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define MAX(rt, ra, rb) \ cgt _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) #define UMIN(rt, ra, rb) \ clgt _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define UMAX(rt, ra, rb) \ clgt _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) // bytes #define MINB(rt, ra, rb) \ cgtb _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define MAXB(rt, ra, rb) \ cgtb _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) #define UMINB(rt, ra, rb) \ clgtb _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define UMAXB(rt, ra, rb) \ clgtb _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) // halfwords #define MINH(rt, ra, rb) \ cgth _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define MAXH(rt, ra, rb) \ cgth _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) #define UMINH(rt, ra, rb) \ clgth _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define UMAXH(rt, ra, rb) \ clgth _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) // floats #define FMIN(rt, ra, rb) \ fcgt _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) #define FMAX(rt, ra, rb) \ fcgt _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) // Ignoring the sign, select the values with the minimum magnitude #define FMINMAG(rt, ra, rb) \ fcmgt _gc_t0, ra, rb; \ MIN_SELB(rt, ra, rb, _gc_t0) // Ignoring the sign, select the values with the maximum magnitude #define FMAXMAG(rt, ra, rb) \ fcmgt _gc_t0, ra, rb; \ MAX_SELB(rt, ra, rb, _gc_t0) #endif /* INCLUDED_GC_SPU_MACS_H */ gnuradio-3.7.2.1/volk/spu_lib/spu_16s_vector_sum_unaligned.c0000644000175000017500000001427611744612271023711 0ustar jcorganjcorgan#include void* libvector_16s_vector_sum_unaligned(void* target, void* src0, void* src1, unsigned int num_bytes){ //loop iterator i int i = 0; void* retval = target; //put the target and source addresses into qwords vector unsigned int address_counter_tgt = {(unsigned int)target, 0, 0, 0}; vector unsigned int address_counter_src0 = {(unsigned int)src0, 0, 0 ,0}; vector unsigned int address_counter_src1 = {(unsigned int)src1, 0, 0, 0}; //create shuffle masks //shuffle mask building blocks: //all from the first vector vector unsigned char oneup = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; //all from the second vector vector unsigned char second_oneup = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; //gamma: second half of the second, first half of the first, break at (unsigned int)src0%16 vector unsigned char src_cmp = spu_splats((unsigned char)((unsigned int)src0%16)); vector unsigned char gt_res = spu_cmpgt(oneup, src_cmp); vector unsigned char eq_res = spu_cmpeq(oneup, src_cmp); vector unsigned char cmp_res = spu_or(gt_res, eq_res); vector unsigned char sixteen_uchar = spu_splats((unsigned char)16); vector unsigned char phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_gamma = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_gamma = spu_rlqwbyte(shuffle_mask_gamma, (unsigned int)src0%16); //eta: second half of the second, first half of the first, break at (unsigned int)src1%16 src_cmp = spu_splats((unsigned char)((unsigned int)src1%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); sixteen_uchar = spu_splats((unsigned char)16); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_eta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_eta = spu_rlqwbyte(shuffle_mask_eta, (unsigned int)src1%16); vector unsigned char tgt_second = spu_rlqwbyte(second_oneup, -((unsigned int)target%16)); vector unsigned char tgt_first = spu_rlqwbyte(oneup, -((unsigned int)target%16)); //alpha: first half of first, second half of second, break at (unsigned int)target%16 src_cmp = spu_splats((unsigned char)((unsigned int)target%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_alpha = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); //delta: first half of first, first half of second, break at (unsigned int)target%16 vector unsigned char shuffle_mask_delta = spu_shuffle(oneup, tgt_second, (vector unsigned char)shuffle_mask_alpha); //epsilon: second half of second, second half of first, break at (unsigned int)target%16 vector unsigned char shuffle_mask_epsilon = spu_shuffle(tgt_second, oneup, (vector unsigned char)shuffle_mask_alpha); //zeta: second half of second, first half of first, break at 16 - (unsigned int)target%16 vector unsigned int shuffle_mask_zeta = spu_rlqwbyte(shuffle_mask_alpha, (unsigned int)target%16); //beta: first half of first, second half of second, break at num_bytes%16 src_cmp = spu_splats((unsigned char)(num_bytes%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_beta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); qword src0_past; qword src0_present; qword src1_past; qword src1_present; qword tgt_past; qword tgt_present; qword in_temp0; qword in_temp1; qword out_temp0; qword out_temp1; vector signed int sum; src0_past = si_lqd((qword)address_counter_src0, 0); src1_past = si_lqd((qword)address_counter_src1, 0); tgt_past = si_lqd((qword)address_counter_tgt, 0); for(i = 0; i < num_bytes/16; ++i) { src0_present = si_lqd((qword)address_counter_src0, 16); src1_present = si_lqd((qword)address_counter_src1, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp0 = spu_shuffle(src0_present, src0_past, (vector unsigned char)shuffle_mask_gamma); in_temp1 = spu_shuffle(src1_present, src1_past, (vector unsigned char)shuffle_mask_eta); sum = spu_add((vector signed int)in_temp0, (vector signed int)in_temp1); out_temp0 = spu_shuffle(tgt_past, (qword)sum, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, (qword)sum, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); tgt_past = out_temp1; src0_past = src0_present; src1_past = src1_present; address_counter_src0 = spu_add(address_counter_src0, 16); address_counter_src1 = spu_add(address_counter_src1, 16); address_counter_tgt = spu_add(address_counter_tgt, 16); } src0_present = si_lqd((qword)address_counter_src0, 16); src1_present = si_lqd((qword)address_counter_src1, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp0 = spu_shuffle(src0_present, src0_past, (vector unsigned char) shuffle_mask_gamma); in_temp1 = spu_shuffle(src1_present, src1_past, (vector unsigned char) shuffle_mask_eta); sum = spu_add((vector signed int)in_temp0, (vector signed int)in_temp1); qword target_temp = spu_shuffle(tgt_present, tgt_past, (vector unsigned char) shuffle_mask_zeta); qword meld = spu_shuffle((qword)sum, target_temp, (vector unsigned char)shuffle_mask_beta); out_temp0 = spu_shuffle(tgt_past, meld, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, meld, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); return retval; } /* int main(){ signed short pooh[48]; signed short bear[48]; signed short res[48]; int i = 0; for(i = 0; i < 48; ++i){ pooh[i] = i; } for(i = 48; i < 96; ++i){ bear[i - 48] = i; } vector_sum(&pooh[9], &pooh[9], &bear[3], 30); for(i = 0; i < 48; ++i) { printf("%d, ", pooh[i]); } printf("\n"); } */ gnuradio-3.7.2.1/volk/spu_lib/spu_memcpy_unaligned.c0000644000175000017500000002444311744612271022321 0ustar jcorganjcorgan#include void* libvector_memcpy_unaligned(void* target, void* src, unsigned int num_bytes){ //loop iterator i int i = 0; void* retval = target; //put the target and source addresses into qwords vector unsigned int address_counter_tgt = {(unsigned int)target, 0, 0, 0}; vector unsigned int address_counter_src = {(unsigned int)src, 0, 0 ,0}; //create shuffle masks //shuffle mask building blocks: //all from the first vector vector unsigned char oneup = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; //all from the second vector vector unsigned char second_oneup = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; //gamma: second half of the second, first half of the first, break at (unsigned int)src%16 vector unsigned char src_cmp = spu_splats((unsigned char)((unsigned int)src%16)); vector unsigned char gt_res = spu_cmpgt(oneup, src_cmp); vector unsigned char eq_res = spu_cmpeq(oneup, src_cmp); vector unsigned char cmp_res = spu_or(gt_res, eq_res); vector unsigned char sixteen_uchar = spu_splats((unsigned char)16); vector unsigned char phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_gamma = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_gamma = spu_rlqwbyte(shuffle_mask_gamma, (unsigned int)src%16); vector unsigned char tgt_second = spu_rlqwbyte(second_oneup, -((unsigned int)target%16)); vector unsigned char tgt_first = spu_rlqwbyte(oneup, -((unsigned int)target%16)); //alpha: first half of first, second half of second, break at (unsigned int)target%16 src_cmp = spu_splats((unsigned char)((unsigned int)target%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_alpha = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); //delta: first half of first, first half of second, break at (unsigned int)target%16 vector unsigned char shuffle_mask_delta = spu_shuffle(oneup, tgt_second, (vector unsigned char)shuffle_mask_alpha); //epsilon: second half of second, second half of first, break at (unsigned int)target%16 vector unsigned char shuffle_mask_epsilon = spu_shuffle(tgt_second, oneup, (vector unsigned char)shuffle_mask_alpha); //zeta: second half of second, first half of first, break at 16 - (unsigned int)target%16 vector unsigned int shuffle_mask_zeta = spu_rlqwbyte(shuffle_mask_alpha, (unsigned int)target%16); //beta: first half of first, second half of second, break at num_bytes%16 src_cmp = spu_splats((unsigned char)(num_bytes%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_beta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); qword src_past; qword src_present; qword tgt_past; qword tgt_present; qword in_temp; qword out_temp0; qword out_temp1; src_past = si_lqd((qword)address_counter_src, 0); tgt_past = si_lqd((qword)address_counter_tgt, 0); for(i = 0; i < num_bytes/16; ++i) { src_present = si_lqd((qword)address_counter_src, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp = spu_shuffle(src_present, src_past, (vector unsigned char)shuffle_mask_gamma); out_temp0 = spu_shuffle(tgt_past, in_temp, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, in_temp, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); tgt_past = out_temp1; src_past = src_present; address_counter_src = spu_add(address_counter_src, 16); address_counter_tgt = spu_add(address_counter_tgt, 16); } src_present = si_lqd((qword)address_counter_src, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp = spu_shuffle(src_present, src_past,(vector unsigned char) shuffle_mask_gamma); qword target_temp = spu_shuffle(tgt_present, tgt_past, (vector unsigned char) shuffle_mask_zeta); qword meld = spu_shuffle(in_temp, target_temp, (vector unsigned char)shuffle_mask_beta); out_temp0 = spu_shuffle(tgt_past, meld, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, meld, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); return retval; } /* void* mcpy(void* target, void* src, size_t num_bytes){ //loop iterator i int i = 0; void* retval = src; //put the target and source addresses into qwords vector unsigned int address_counter_tgt = {(unsigned int)target, 0, 0, 0}; vector unsigned int address_counter_src = {(unsigned int)src, 0, 0 ,0}; //create shuffle masks //shuffle mask building blocks: //all from the first vector vector unsigned char oneup = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; //all from the second vector vector unsigned char second_oneup = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}; //gamma: second half of the second, first half of the first, break at src%16 vector unsigned char src_cmp = spu_splats((unsigned char)(src%16)); vector unsigned char gt_res = spu_cmpgt(oneup, src_cmp); vector unsigned char eq_res = spu_cmpeq(oneup, src_cmp); vector unsigned char cmp_res = spu_or(gt_res, eq_res); vector unsigned char sixteen_uchar = spu_splats((unsigned char)16); vector unsigned char phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_gamma = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); shuffle_mask_gamma = spu_rlqwbyte(shuffle_mask_gamma, src%16); vector unsigned char tgt_second = spu_rlqwbyte(second_oneup, -(target%16)); vector unsigned char tgt_first = spu_rlqwbyte(oneup, -(target%16)); //alpha: first half of first, second half of second, break at target%16 src_cmp = spu_splats((unsigned char)(target%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_alpha = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); //delta: first half of first, first half of second, break at target%16 vector unsigned char shuffle_mask_delta = spu_shuffle(oneup, tgt_second, (vector unsigned char)shuffle_mask_alpha); //epsilon: second half of second, second half of first, break at target%16 vector unsigned char shuffle_mask_epsilon = spu_shuffle(tgt_second, oneup, (vector unsigned char)shuffle_mask_alpha); //zeta: second half of second, first half of first, break at 16 - target%16 vector unsigned int shuffle_mask_zeta = spu_rlqwbyte(shuffle_mask_alpha, target%16); //beta: first half of first, second half of second, break at num_bytes%16 src_cmp = spu_splats((unsigned char)(num_bytes%16)); gt_res = spu_cmpgt(oneup, src_cmp); eq_res = spu_cmpeq(oneup, src_cmp); cmp_res = spu_or(gt_res, eq_res); phase_change = spu_and(sixteen_uchar, cmp_res); vector unsigned int shuffle_mask_beta = spu_add((vector unsigned int)phase_change, (vector unsigned int)oneup); printf("num_bytesmod16 %d\n", num_bytes%16); printf("beta %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n", spu_extract((vector unsigned char) shuffle_mask_beta, 0), spu_extract((vector unsigned char) shuffle_mask_beta, 1), spu_extract((vector unsigned char) shuffle_mask_beta, 2), spu_extract((vector unsigned char) shuffle_mask_beta, 3), spu_extract((vector unsigned char) shuffle_mask_beta, 4), spu_extract((vector unsigned char) shuffle_mask_beta, 5), spu_extract((vector unsigned char) shuffle_mask_beta, 6), spu_extract((vector unsigned char) shuffle_mask_beta, 7), spu_extract((vector unsigned char) shuffle_mask_beta, 8), spu_extract((vector unsigned char) shuffle_mask_beta, 9), spu_extract((vector unsigned char) shuffle_mask_beta, 10), spu_extract((vector unsigned char) shuffle_mask_beta, 11), spu_extract((vector unsigned char) shuffle_mask_beta, 12), spu_extract((vector unsigned char) shuffle_mask_beta, 13), spu_extract((vector unsigned char) shuffle_mask_beta, 14), spu_extract((vector unsigned char) shuffle_mask_beta, 15)); qword src_past; qword src_present; qword tgt_past; qword tgt_present; qword in_temp; qword out_temp0; qword out_temp1; src_past = si_lqd((qword)address_counter_src, 0); tgt_past = si_lqd((qword)address_counter_tgt, 0); for(i = 0; i < num_bytes/16; ++i) { src_present = si_lqd((qword)address_counter_src, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp = spu_shuffle(src_present, src_past, (vector unsigned char)shuffle_mask_gamma); out_temp0 = spu_shuffle(tgt_past, in_temp, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, in_temp, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); tgt_past = out_temp1; src_past = src_present; address_counter_src = spu_add(address_counter_src, 16); address_counter_tgt = spu_add(address_counter_tgt, 16); } src_present = si_lqd((qword)address_counter_src, 16); tgt_present = si_lqd((qword)address_counter_tgt, 16); in_temp = spu_shuffle(src_present, src_past,(vector unsigned char) shuffle_mask_gamma); qword target_temp = spu_shuffle(tgt_present, tgt_past, (vector unsigned char) shuffle_mask_zeta); qword meld = spu_shuffle(in_temp, target_temp, (vector unsigned char)shuffle_mask_beta); out_temp0 = spu_shuffle(tgt_past, meld, shuffle_mask_delta); out_temp1 = spu_shuffle(tgt_present, meld, shuffle_mask_epsilon); si_stqd(out_temp0, (qword)address_counter_tgt, 0); si_stqd(out_temp1, (qword)address_counter_tgt, 16); return retval; } */ /* int main(){ unsigned char pooh[48]; unsigned char bear[48]; int i = 0; for(i = 0; i < 48; ++i){ pooh[i] = i; bear[i] = i; } spu_mcpy(&pooh[9],&bear[3], 15); for(i = 0; i < 48; ++i) { printf("%d, ", pooh[i]); } printf("\n"); } */ gnuradio-3.7.2.1/volk/cmake/0000755000175000017500000000000012207440367015362 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/cmake/GrBoost.cmake0000664000175000017500000000751512207440367017755 0ustar jcorganjcorgan# Copyright 2010-2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. if(DEFINED __INCLUDED_GR_BOOST_CMAKE) return() endif() set(__INCLUDED_GR_BOOST_CMAKE TRUE) ######################################################################## # Setup Boost and handle some system specific things ######################################################################## set(BOOST_REQUIRED_COMPONENTS filesystem system unit_test_framework ) if(UNIX AND NOT BOOST_ROOT AND EXISTS "/usr/lib64") list(APPEND BOOST_LIBRARYDIR "/usr/lib64") #fedora 64-bit fix endif(UNIX AND NOT BOOST_ROOT AND EXISTS "/usr/lib64") if(MSVC) set(BOOST_REQUIRED_COMPONENTS ${BOOST_REQUIRED_COMPONENTS} chrono) if (NOT DEFINED BOOST_ALL_DYN_LINK) set(BOOST_ALL_DYN_LINK TRUE) endif() set(BOOST_ALL_DYN_LINK "${BOOST_ALL_DYN_LINK}" CACHE BOOL "boost enable dynamic linking") if(BOOST_ALL_DYN_LINK) add_definitions(-DBOOST_ALL_DYN_LINK) #setup boost auto-linking in msvc else(BOOST_ALL_DYN_LINK) unset(BOOST_REQUIRED_COMPONENTS) #empty components list for static link endif(BOOST_ALL_DYN_LINK) endif(MSVC) find_package(Boost "1.35" COMPONENTS ${BOOST_REQUIRED_COMPONENTS}) # This does not allow us to disable specific versions. It is used # internally by cmake to know the formation newer versions. As newer # Boost version beyond what is shown here are produced, we must extend # this list. To disable Boost versions, see below. set(Boost_ADDITIONAL_VERSIONS "1.35.0" "1.35" "1.36.0" "1.36" "1.37.0" "1.37" "1.38.0" "1.38" "1.39.0" "1.39" "1.40.0" "1.40" "1.41.0" "1.41" "1.42.0" "1.42" "1.43.0" "1.43" "1.44.0" "1.44" "1.45.0" "1.45" "1.46.0" "1.46" "1.47.0" "1.47" "1.48.0" "1.48" "1.49.0" "1.49" "1.50.0" "1.50" "1.51.0" "1.51" "1.52.0" "1.52" "1.53.0" "1.53" "1.54.0" "1.54" "1.55.0" "1.55" "1.56.0" "1.56" "1.57.0" "1.57" "1.58.0" "1.58" "1.59.0" "1.59" "1.60.0" "1.60" "1.61.0" "1.61" "1.62.0" "1.62" "1.63.0" "1.63" "1.64.0" "1.64" "1.65.0" "1.65" "1.66.0" "1.66" "1.67.0" "1.67" "1.68.0" "1.68" "1.69.0" "1.69" ) # Boost 1.52 disabled, see https://svn.boost.org/trac/boost/ticket/7669 # Similar problems with Boost 1.46 and 1.47. OPTION(ENABLE_BAD_BOOST "Enable known bad versions of Boost" OFF) if(ENABLE_BAD_BOOST) MESSAGE(STATUS "Enabling use of known bad versions of Boost.") endif(ENABLE_BAD_BOOST) # For any unsuitable Boost version, add the version number below in # the following format: XXYYZZ # Where: # XX is the major version ('10' for version 1) # YY is the minor version number ('46' for 1.46) # ZZ is the patcher version number (typically just '00') set(Boost_NOGO_VERSIONS 104600 104601 104700 105200 ) foreach(ver ${Boost_NOGO_VERSIONS}) if(${Boost_VERSION} EQUAL ${ver}) if(NOT ENABLE_BAD_BOOST) MESSAGE(STATUS "WARNING: Found a known bad version of Boost (v${Boost_VERSION}). Disabling.") set(Boost_FOUND FALSE) else(NOT ENABLE_BAD_BOOST) MESSAGE(STATUS "WARNING: Found a known bad version of Boost (v${Boost_VERSION}). Continuing anyway.") set(Boost_FOUND TRUE) endif(NOT ENABLE_BAD_BOOST) endif(${Boost_VERSION} EQUAL ${ver}) endforeach(ver) gnuradio-3.7.2.1/volk/cmake/msvc/0000755000175000017500000000000012207440367016332 5ustar jcorganjcorgangnuradio-3.7.2.1/volk/cmake/msvc/config.h0000644000175000017500000000474511765410647017770 0ustar jcorganjcorgan#ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_CONFIG_H_ // [ #define _MSC_CONFIG_H_ //////////////////////////////////////////////////////////////////////// // enable inline functions for C code //////////////////////////////////////////////////////////////////////// #ifndef __cplusplus # define inline __inline #endif //////////////////////////////////////////////////////////////////////// // signed size_t //////////////////////////////////////////////////////////////////////// #include typedef ptrdiff_t ssize_t; //////////////////////////////////////////////////////////////////////// // rint functions //////////////////////////////////////////////////////////////////////// #include static inline long lrint(double x){return (long)(x > 0.0 ? x + 0.5 : x - 0.5);} static inline long lrintf(float x){return (long)(x > 0.0f ? x + 0.5f : x - 0.5f);} static inline long long llrint(double x){return (long long)(x > 0.0 ? x + 0.5 : x - 0.5);} static inline long long llrintf(float x){return (long long)(x > 0.0f ? x + 0.5f : x - 0.5f);} static inline double rint(double x){return (x > 0.0)? floor(x + 0.5) : ceil(x - 0.5);} static inline float rintf(float x){return (x > 0.0f)? floorf(x + 0.5f) : ceilf(x - 0.5f);} //////////////////////////////////////////////////////////////////////// // math constants //////////////////////////////////////////////////////////////////////// #define INFINITY HUGE_VAL # define M_E 2.7182818284590452354 /* e */ # define M_LOG2E 1.4426950408889634074 /* log_2 e */ # define M_LOG10E 0.43429448190325182765 /* log_10 e */ # define M_LN2 0.69314718055994530942 /* log_e 2 */ # define M_LN10 2.30258509299404568402 /* log_e 10 */ # define M_PI 3.14159265358979323846 /* pi */ # define M_PI_2 1.57079632679489661923 /* pi/2 */ # define M_PI_4 0.78539816339744830962 /* pi/4 */ # define M_1_PI 0.31830988618379067154 /* 1/pi */ # define M_2_PI 0.63661977236758134308 /* 2/pi */ # define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */ # define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ # define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ //////////////////////////////////////////////////////////////////////// // random and srandom //////////////////////////////////////////////////////////////////////// #include static inline long int random (void) { return rand(); } static inline void srandom (unsigned int seed) { srand(seed); } #endif // _MSC_CONFIG_H_ ] gnuradio-3.7.2.1/volk/cmake/msvc/stdint.h0000644000175000017500000001713011765410647020020 0ustar jcorganjcorgan// ISO C9x compliant stdint.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006-2008 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_STDINT_H_ // [ #define _MSC_STDINT_H_ #if _MSC_VER > 1000 #pragma once #endif #include // For Visual Studio 6 in C++ mode and for many Visual Studio versions when // compiling for ARM we should wrap include with 'extern "C++" {}' // or compiler give many errors like this: // error C2733: second C linkage of overloaded function 'wmemchr' not allowed #ifdef __cplusplus extern "C" { #endif # include #ifdef __cplusplus } #endif // Define _W64 macros to mark types changing their size, like intptr_t. #ifndef _W64 # if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 # define _W64 __w64 # else # define _W64 # endif #endif // 7.18.1 Integer types // 7.18.1.1 Exact-width integer types // Visual Studio 6 and Embedded Visual C++ 4 doesn't // realize that, e.g. char has the same size as __int8 // so we give up on __intX for them. #if (_MSC_VER < 1300) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; #else typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; #endif typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; // 7.18.1.2 Minimum-width integer types typedef int8_t int_least8_t; typedef int16_t int_least16_t; typedef int32_t int_least32_t; typedef int64_t int_least64_t; typedef uint8_t uint_least8_t; typedef uint16_t uint_least16_t; typedef uint32_t uint_least32_t; typedef uint64_t uint_least64_t; // 7.18.1.3 Fastest minimum-width integer types typedef int8_t int_fast8_t; typedef int16_t int_fast16_t; typedef int32_t int_fast32_t; typedef int64_t int_fast64_t; typedef uint8_t uint_fast8_t; typedef uint16_t uint_fast16_t; typedef uint32_t uint_fast32_t; typedef uint64_t uint_fast64_t; // 7.18.1.4 Integer types capable of holding object pointers #ifdef _WIN64 // [ typedef signed __int64 intptr_t; typedef unsigned __int64 uintptr_t; #else // _WIN64 ][ typedef _W64 signed int intptr_t; typedef _W64 unsigned int uintptr_t; #endif // _WIN64 ] // 7.18.1.5 Greatest-width integer types typedef int64_t intmax_t; typedef uint64_t uintmax_t; // 7.18.2 Limits of specified-width integer types #if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 // 7.18.2.1 Limits of exact-width integer types #define INT8_MIN ((int8_t)_I8_MIN) #define INT8_MAX _I8_MAX #define INT16_MIN ((int16_t)_I16_MIN) #define INT16_MAX _I16_MAX #define INT32_MIN ((int32_t)_I32_MIN) #define INT32_MAX _I32_MAX #define INT64_MIN ((int64_t)_I64_MIN) #define INT64_MAX _I64_MAX #define UINT8_MAX _UI8_MAX #define UINT16_MAX _UI16_MAX #define UINT32_MAX _UI32_MAX #define UINT64_MAX _UI64_MAX // 7.18.2.2 Limits of minimum-width integer types #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX // 7.18.2.3 Limits of fastest minimum-width integer types #define INT_FAST8_MIN INT8_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MIN INT16_MIN #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MIN INT32_MIN #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MIN INT64_MIN #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX // 7.18.2.4 Limits of integer types capable of holding object pointers #ifdef _WIN64 // [ # define INTPTR_MIN INT64_MIN # define INTPTR_MAX INT64_MAX # define UINTPTR_MAX UINT64_MAX #else // _WIN64 ][ # define INTPTR_MIN INT32_MIN # define INTPTR_MAX INT32_MAX # define UINTPTR_MAX UINT32_MAX #endif // _WIN64 ] // 7.18.2.5 Limits of greatest-width integer types #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX // 7.18.3 Limits of other integer types #ifdef _WIN64 // [ # define PTRDIFF_MIN _I64_MIN # define PTRDIFF_MAX _I64_MAX #else // _WIN64 ][ # define PTRDIFF_MIN _I32_MIN # define PTRDIFF_MAX _I32_MAX #endif // _WIN64 ] #define SIG_ATOMIC_MIN INT_MIN #define SIG_ATOMIC_MAX INT_MAX #ifndef SIZE_MAX // [ # ifdef _WIN64 // [ # define SIZE_MAX _UI64_MAX # else // _WIN64 ][ # define SIZE_MAX _UI32_MAX # endif // _WIN64 ] #endif // SIZE_MAX ] // WCHAR_MIN and WCHAR_MAX are also defined in #ifndef WCHAR_MIN // [ # define WCHAR_MIN 0 #endif // WCHAR_MIN ] #ifndef WCHAR_MAX // [ # define WCHAR_MAX _UI16_MAX #endif // WCHAR_MAX ] #define WINT_MIN 0 #define WINT_MAX _UI16_MAX #endif // __STDC_LIMIT_MACROS ] // 7.18.4 Limits of other integer types #if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 // 7.18.4.1 Macros for minimum-width integer constants #define INT8_C(val) val##i8 #define INT16_C(val) val##i16 #define INT32_C(val) val##i32 #define INT64_C(val) val##i64 #define UINT8_C(val) val##ui8 #define UINT16_C(val) val##ui16 #define UINT32_C(val) val##ui32 #define UINT64_C(val) val##ui64 // 7.18.4.2 Macros for greatest-width integer constants #ifndef INTMAX_C #define INTMAX_C INT64_C #endif #ifndef UINTMAX_C #define UINTMAX_C UINT64_C #endif #endif // __STDC_CONSTANT_MACROS ] #endif // _MSC_STDINT_H_ ] gnuradio-3.7.2.1/volk/cmake/msvc/stdbool.h0000664000175000017500000000241312207440367020153 0ustar jcorganjcorgan/* * Copyright (C) 2005, 2006 Apple Computer, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef STDBOOL_WIN32_H #define STDBOOL_WIN32_H #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef __cplusplus typedef unsigned char bool; #define true 1 #define false 0 #ifndef CASSERT #define CASSERT(exp, name) typedef int dummy##name [(exp) ? 1 : -1]; #endif CASSERT(sizeof(bool) == 1, bool_is_one_byte) CASSERT(true, true_is_true) CASSERT(!false, false_is_false) #endif #endif gnuradio-3.7.2.1/volk/cmake/msvc/inttypes.h0000644000175000017500000001727111765410647020400 0ustar jcorganjcorgan// ISO C9x compliant inttypes.h for Microsoft Visual Studio // Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 // // Copyright (c) 2006 Alexander Chemeris // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. The name of the author may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////// #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] #ifndef _MSC_INTTYPES_H_ // [ #define _MSC_INTTYPES_H_ #if _MSC_VER > 1000 #pragma once #endif #include // 7.8 Format conversion of integer types typedef struct { intmax_t quot; intmax_t rem; } imaxdiv_t; // 7.8.1 Macros for format specifiers // The fprintf macros for signed integers are: #define PRId8 "d" #define PRIi8 "i" #define PRIdLEAST8 "d" #define PRIiLEAST8 "i" #define PRIdFAST8 "d" #define PRIiFAST8 "i" #define PRId16 "hd" #define PRIi16 "hi" #define PRIdLEAST16 "hd" #define PRIiLEAST16 "hi" #define PRIdFAST16 "hd" #define PRIiFAST16 "hi" #define PRId32 "I32d" #define PRIi32 "I32i" #define PRIdLEAST32 "I32d" #define PRIiLEAST32 "I32i" #define PRIdFAST32 "I32d" #define PRIiFAST32 "I32i" #define PRId64 "I64d" #define PRIi64 "I64i" #define PRIdLEAST64 "I64d" #define PRIiLEAST64 "I64i" #define PRIdFAST64 "I64d" #define PRIiFAST64 "I64i" #define PRIdMAX "I64d" #define PRIiMAX "I64i" #define PRIdPTR "Id" #define PRIiPTR "Ii" // The fprintf macros for unsigned integers are: #define PRIo8 "o" #define PRIu8 "u" #define PRIx8 "x" #define PRIX8 "X" #define PRIoLEAST8 "o" #define PRIuLEAST8 "u" #define PRIxLEAST8 "x" #define PRIXLEAST8 "X" #define PRIoFAST8 "o" #define PRIuFAST8 "u" #define PRIxFAST8 "x" #define PRIXFAST8 "X" #define PRIo16 "ho" #define PRIu16 "hu" #define PRIx16 "hx" #define PRIX16 "hX" #define PRIoLEAST16 "ho" #define PRIuLEAST16 "hu" #define PRIxLEAST16 "hx" #define PRIXLEAST16 "hX" #define PRIoFAST16 "ho" #define PRIuFAST16 "hu" #define PRIxFAST16 "hx" #define PRIXFAST16 "hX" #define PRIo32 "I32o" #define PRIu32 "I32u" #define PRIx32 "I32x" #define PRIX32 "I32X" #define PRIoLEAST32 "I32o" #define PRIuLEAST32 "I32u" #define PRIxLEAST32 "I32x" #define PRIXLEAST32 "I32X" #define PRIoFAST32 "I32o" #define PRIuFAST32 "I32u" #define PRIxFAST32 "I32x" #define PRIXFAST32 "I32X" #define PRIo64 "I64o" #define PRIu64 "I64u" #define PRIx64 "I64x" #define PRIX64 "I64X" #define PRIoLEAST64 "I64o" #define PRIuLEAST64 "I64u" #define PRIxLEAST64 "I64x" #define PRIXLEAST64 "I64X" #define PRIoFAST64 "I64o" #define PRIuFAST64 "I64u" #define PRIxFAST64 "I64x" #define PRIXFAST64 "I64X" #define PRIoMAX "I64o" #define PRIuMAX "I64u" #define PRIxMAX "I64x" #define PRIXMAX "I64X" #define PRIoPTR "Io" #define PRIuPTR "Iu" #define PRIxPTR "Ix" #define PRIXPTR "IX" // The fscanf macros for signed integers are: #define SCNd8 "d" #define SCNi8 "i" #define SCNdLEAST8 "d" #define SCNiLEAST8 "i" #define SCNdFAST8 "d" #define SCNiFAST8 "i" #define SCNd16 "hd" #define SCNi16 "hi" #define SCNdLEAST16 "hd" #define SCNiLEAST16 "hi" #define SCNdFAST16 "hd" #define SCNiFAST16 "hi" #define SCNd32 "ld" #define SCNi32 "li" #define SCNdLEAST32 "ld" #define SCNiLEAST32 "li" #define SCNdFAST32 "ld" #define SCNiFAST32 "li" #define SCNd64 "I64d" #define SCNi64 "I64i" #define SCNdLEAST64 "I64d" #define SCNiLEAST64 "I64i" #define SCNdFAST64 "I64d" #define SCNiFAST64 "I64i" #define SCNdMAX "I64d" #define SCNiMAX "I64i" #ifdef _WIN64 // [ # define SCNdPTR "I64d" # define SCNiPTR "I64i" #else // _WIN64 ][ # define SCNdPTR "ld" # define SCNiPTR "li" #endif // _WIN64 ] // The fscanf macros for unsigned integers are: #define SCNo8 "o" #define SCNu8 "u" #define SCNx8 "x" #define SCNX8 "X" #define SCNoLEAST8 "o" #define SCNuLEAST8 "u" #define SCNxLEAST8 "x" #define SCNXLEAST8 "X" #define SCNoFAST8 "o" #define SCNuFAST8 "u" #define SCNxFAST8 "x" #define SCNXFAST8 "X" #define SCNo16 "ho" #define SCNu16 "hu" #define SCNx16 "hx" #define SCNX16 "hX" #define SCNoLEAST16 "ho" #define SCNuLEAST16 "hu" #define SCNxLEAST16 "hx" #define SCNXLEAST16 "hX" #define SCNoFAST16 "ho" #define SCNuFAST16 "hu" #define SCNxFAST16 "hx" #define SCNXFAST16 "hX" #define SCNo32 "lo" #define SCNu32 "lu" #define SCNx32 "lx" #define SCNX32 "lX" #define SCNoLEAST32 "lo" #define SCNuLEAST32 "lu" #define SCNxLEAST32 "lx" #define SCNXLEAST32 "lX" #define SCNoFAST32 "lo" #define SCNuFAST32 "lu" #define SCNxFAST32 "lx" #define SCNXFAST32 "lX" #define SCNo64 "I64o" #define SCNu64 "I64u" #define SCNx64 "I64x" #define SCNX64 "I64X" #define SCNoLEAST64 "I64o" #define SCNuLEAST64 "I64u" #define SCNxLEAST64 "I64x" #define SCNXLEAST64 "I64X" #define SCNoFAST64 "I64o" #define SCNuFAST64 "I64u" #define SCNxFAST64 "I64x" #define SCNXFAST64 "I64X" #define SCNoMAX "I64o" #define SCNuMAX "I64u" #define SCNxMAX "I64x" #define SCNXMAX "I64X" #ifdef _WIN64 // [ # define SCNoPTR "I64o" # define SCNuPTR "I64u" # define SCNxPTR "I64x" # define SCNXPTR "I64X" #else // _WIN64 ][ # define SCNoPTR "lo" # define SCNuPTR "lu" # define SCNxPTR "lx" # define SCNXPTR "lX" #endif // _WIN64 ] // 7.8.2 Functions for greatest-width integer types // 7.8.2.1 The imaxabs function #define imaxabs _abs64 // 7.8.2.2 The imaxdiv function // This is modified version of div() function from Microsoft's div.c found // in %MSVC.NET%\crt\src\div.c #ifdef STATIC_IMAXDIV // [ static #else // STATIC_IMAXDIV ][ _inline #endif // STATIC_IMAXDIV ] imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) { imaxdiv_t result; result.quot = numer / denom; result.rem = numer % denom; if (numer < 0 && result.rem > 0) { // did division wrong; must fix up ++result.quot; result.rem -= denom; } return result; } // 7.8.2.3 The strtoimax and strtoumax functions #define strtoimax _strtoi64 #define strtoumax _strtoui64 // 7.8.2.4 The wcstoimax and wcstoumax functions #define wcstoimax _wcstoi64 #define wcstoumax _wcstoui64 #endif // _MSC_INTTYPES_H_ ] gnuradio-3.7.2.1/volk/cmake/FindORC.cmake0000664000175000017500000000210112207440367017604 0ustar jcorganjcorganFIND_PACKAGE(PkgConfig) PKG_CHECK_MODULES(PC_ORC "orc-0.4 > 0.4.11") FIND_PROGRAM(ORCC_EXECUTABLE orcc HINTS ${PC_ORC_TOOLSDIR} PATHS ${ORC_ROOT}/bin ${CMAKE_INSTALL_PREFIX}/bin) FIND_PATH(ORC_INCLUDE_DIR NAMES orc/orc.h HINTS ${PC_ORC_INCLUDEDIR} PATHS ${ORC_ROOT}/include/orc-0.4 ${CMAKE_INSTALL_PREFIX}/include/orc-0.4) FIND_PATH(ORC_LIBRARY_DIR NAMES ${CMAKE_SHARED_LIBRARY_PREFIX}orc-0.4${CMAKE_SHARED_LIBRARY_SUFFIX} HINTS ${PC_ORC_LIBDIR} PATHS ${ORC_ROOT}/lib${LIB_SUFFIX} ${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}) FIND_LIBRARY(ORC_LIB orc-0.4 HINTS ${PC_ORC_LIBRARY_DIRS} PATHS ${ORC_ROOT}/lib${LIB_SUFFIX} ${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}) LIST(APPEND ORC_LIBRARY ${ORC_LIB} ) SET(ORC_INCLUDE_DIRS ${ORC_INCLUDE_DIR}) SET(ORC_LIBRARIES ${ORC_LIBRARY}) SET(ORC_LIBRARY_DIRS ${ORC_LIBRARY_DIR}) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(ORC "orc files" ORC_LIBRARY ORC_INCLUDE_DIR ORCC_EXECUTABLE) mark_as_advanced(ORC_INCLUDE_DIR ORC_LIBRARY ORCC_EXECUTABLE) gnuradio-3.7.2.1/volk/cmake/CMakeParseArgumentsCopy.cmake0000664000175000017500000001340312207440367023063 0ustar jcorganjcorgan# CMAKE_PARSE_ARGUMENTS( args...) # # CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions for # parsing the arguments given to that macro or function. # It processes the arguments and defines a set of variables which hold the # values of the respective options. # # The argument contains all options for the respective macro, # i.e. keywords which can be used when calling the macro without any value # following, like e.g. the OPTIONAL keyword of the install() command. # # The argument contains all keywords for this macro # which are followed by one value, like e.g. DESTINATION keyword of the # install() command. # # The argument contains all keywords for this macro # which can be followed by more than one value, like e.g. the TARGETS or # FILES keywords of the install() command. # # When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the # keywords listed in , and # a variable composed of the given # followed by "_" and the name of the respective keyword. # These variables will then hold the respective value from the argument list. # For the keywords this will be TRUE or FALSE. # # All remaining arguments are collected in a variable # _UNPARSED_ARGUMENTS, this can be checked afterwards to see whether # your macro was called with unrecognized parameters. # # As an example here a my_install() macro, which takes similar arguments as the # real install() command: # # function(MY_INSTALL) # set(options OPTIONAL FAST) # set(oneValueArgs DESTINATION RENAME) # set(multiValueArgs TARGETS CONFIGURATIONS) # cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) # ... # # Assume my_install() has been called like this: # my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub) # # After the cmake_parse_arguments() call the macro will have set the following # variables: # MY_INSTALL_OPTIONAL = TRUE # MY_INSTALL_FAST = FALSE (this option was not used when calling my_install() # MY_INSTALL_DESTINATION = "bin" # MY_INSTALL_RENAME = "" (was not used) # MY_INSTALL_TARGETS = "foo;bar" # MY_INSTALL_CONFIGURATIONS = "" (was not used) # MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL" # # You can the continue and process these variables. # # Keywords terminate lists of values, e.g. if directly after a one_value_keyword # another recognized keyword follows, this is interpreted as the beginning of # the new option. # E.g. my_install(TARGETS foo DESTINATION OPTIONAL) would result in # MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION would # be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor. #============================================================================= # Copyright 2010 Alexander Neundorf # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) if(__CMAKE_PARSE_ARGUMENTS_INCLUDED) return() endif() set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE) function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames) # first set all result variables to empty/FALSE foreach(arg_name ${_singleArgNames} ${_multiArgNames}) set(${prefix}_${arg_name}) endforeach(arg_name) foreach(option ${_optionNames}) set(${prefix}_${option} FALSE) endforeach(option) set(${prefix}_UNPARSED_ARGUMENTS) set(insideValues FALSE) set(currentArgName) # now iterate over all arguments and fill the result variables foreach(currentArg ${ARGN}) list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) if(insideValues) if("${insideValues}" STREQUAL "SINGLE") set(${prefix}_${currentArgName} ${currentArg}) set(insideValues FALSE) elseif("${insideValues}" STREQUAL "MULTI") list(APPEND ${prefix}_${currentArgName} ${currentArg}) endif() else(insideValues) list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) endif(insideValues) else() if(NOT ${optionIndex} EQUAL -1) set(${prefix}_${currentArg} TRUE) set(insideValues FALSE) elseif(NOT ${singleArgIndex} EQUAL -1) set(currentArgName ${currentArg}) set(${prefix}_${currentArgName}) set(insideValues "SINGLE") elseif(NOT ${multiArgIndex} EQUAL -1) set(currentArgName ${currentArg}) set(${prefix}_${currentArgName}) set(insideValues "MULTI") endif() endif() endforeach(currentArg) # propagate the result variables to the caller: foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) endforeach(arg_name) set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) endfunction(CMAKE_PARSE_ARGUMENTS _options _singleArgs _multiArgs) gnuradio-3.7.2.1/volk/cmake/VolkConfig.cmake0000664000175000017500000000113212207440367020424 0ustar jcorganjcorganINCLUDE(FindPkgConfig) PKG_CHECK_MODULES(PC_VOLK volk) FIND_PATH( VOLK_INCLUDE_DIRS NAMES volk/volk.h HINTS $ENV{VOLK_DIR}/include ${PC_VOLK_INCLUDEDIR} PATHS /usr/local/include /usr/include ) FIND_LIBRARY( VOLK_LIBRARIES NAMES volk HINTS $ENV{VOLK_DIR}/lib ${PC_VOLK_LIBDIR} PATHS /usr/local/lib /usr/local/lib64 /usr/lib /usr/lib64 ) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(VOLK DEFAULT_MSG VOLK_LIBRARIES VOLK_INCLUDE_DIRS) MARK_AS_ADVANCED(VOLK_LIBRARIES VOLK_INCLUDE_DIRS) gnuradio-3.7.2.1/volk/cmake/GrPython.cmake0000664000175000017500000002213312207440367020141 0ustar jcorganjcorgan# Copyright 2010-2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. if(DEFINED __INCLUDED_GR_PYTHON_CMAKE) return() endif() set(__INCLUDED_GR_PYTHON_CMAKE TRUE) ######################################################################## # Setup the python interpreter: # This allows the user to specify a specific interpreter, # or finds the interpreter via the built-in cmake module. ######################################################################## #this allows the user to override PYTHON_EXECUTABLE if(PYTHON_EXECUTABLE) set(PYTHONINTERP_FOUND TRUE) #otherwise if not set, try to automatically find it else(PYTHON_EXECUTABLE) #use the built-in find script find_package(PythonInterp 2) #and if that fails use the find program routine if(NOT PYTHONINTERP_FOUND) find_program(PYTHON_EXECUTABLE NAMES python python2 python2.7 python2.6 python2.5) if(PYTHON_EXECUTABLE) set(PYTHONINTERP_FOUND TRUE) endif(PYTHON_EXECUTABLE) endif(NOT PYTHONINTERP_FOUND) endif(PYTHON_EXECUTABLE) #make the path to the executable appear in the cmake gui set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE} CACHE FILEPATH "python interpreter") #make sure we can use -B with python (introduced in 2.6) if(PYTHON_EXECUTABLE) execute_process( COMMAND ${PYTHON_EXECUTABLE} -B -c "" OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE PYTHON_HAS_DASH_B_RESULT ) if(PYTHON_HAS_DASH_B_RESULT EQUAL 0) set(PYTHON_DASH_B "-B") endif() endif(PYTHON_EXECUTABLE) ######################################################################## # Check for the existence of a python module: # - desc a string description of the check # - mod the name of the module to import # - cmd an additional command to run # - have the result variable to set ######################################################################## macro(GR_PYTHON_CHECK_MODULE desc mod cmd have) message(STATUS "") message(STATUS "Python checking for ${desc}") execute_process( COMMAND ${PYTHON_EXECUTABLE} -c " ######################################### try: import ${mod} except: try: ${mod} except: exit(-1) try: assert ${cmd} except: exit(-1) #########################################" RESULT_VARIABLE ${have} ) if(${have} EQUAL 0) message(STATUS "Python checking for ${desc} - found") set(${have} TRUE) else(${have} EQUAL 0) message(STATUS "Python checking for ${desc} - not found") set(${have} FALSE) endif(${have} EQUAL 0) endmacro(GR_PYTHON_CHECK_MODULE) ######################################################################## # Sets the python installation directory GR_PYTHON_DIR ######################################################################## execute_process(COMMAND ${PYTHON_EXECUTABLE} -c " from distutils import sysconfig print sysconfig.get_python_lib(plat_specific=True, prefix='') " OUTPUT_VARIABLE GR_PYTHON_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) file(TO_CMAKE_PATH ${GR_PYTHON_DIR} GR_PYTHON_DIR) ######################################################################## # Create an always-built target with a unique name # Usage: GR_UNIQUE_TARGET( ) ######################################################################## function(GR_UNIQUE_TARGET desc) file(RELATIVE_PATH reldir ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}) execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import re, hashlib unique = hashlib.md5('${reldir}${ARGN}').hexdigest()[:5] print(re.sub('\\W', '_', '${desc} ${reldir} ' + unique))" OUTPUT_VARIABLE _target OUTPUT_STRIP_TRAILING_WHITESPACE) add_custom_target(${_target} ALL DEPENDS ${ARGN}) endfunction(GR_UNIQUE_TARGET) ######################################################################## # Install python sources (also builds and installs byte-compiled python) ######################################################################## function(GR_PYTHON_INSTALL) include(CMakeParseArgumentsCopy) CMAKE_PARSE_ARGUMENTS(GR_PYTHON_INSTALL "" "DESTINATION;COMPONENT" "FILES;PROGRAMS" ${ARGN}) #################################################################### if(GR_PYTHON_INSTALL_FILES) #################################################################### install(${ARGN}) #installs regular python files #create a list of all generated files unset(pysrcfiles) unset(pycfiles) unset(pyofiles) foreach(pyfile ${GR_PYTHON_INSTALL_FILES}) get_filename_component(pyfile ${pyfile} ABSOLUTE) list(APPEND pysrcfiles ${pyfile}) #determine if this file is in the source or binary directory file(RELATIVE_PATH source_rel_path ${CMAKE_CURRENT_SOURCE_DIR} ${pyfile}) string(LENGTH "${source_rel_path}" source_rel_path_len) file(RELATIVE_PATH binary_rel_path ${CMAKE_CURRENT_BINARY_DIR} ${pyfile}) string(LENGTH "${binary_rel_path}" binary_rel_path_len) #and set the generated path appropriately if(${source_rel_path_len} GREATER ${binary_rel_path_len}) set(pygenfile ${CMAKE_CURRENT_BINARY_DIR}/${binary_rel_path}) else() set(pygenfile ${CMAKE_CURRENT_BINARY_DIR}/${source_rel_path}) endif() list(APPEND pycfiles ${pygenfile}c) list(APPEND pyofiles ${pygenfile}o) #ensure generation path exists get_filename_component(pygen_path ${pygenfile} PATH) file(MAKE_DIRECTORY ${pygen_path}) endforeach(pyfile) #the command to generate the pyc files add_custom_command( DEPENDS ${pysrcfiles} OUTPUT ${pycfiles} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_BINARY_DIR}/python_compile_helper.py ${pysrcfiles} ${pycfiles} ) #the command to generate the pyo files add_custom_command( DEPENDS ${pysrcfiles} OUTPUT ${pyofiles} COMMAND ${PYTHON_EXECUTABLE} -O ${CMAKE_BINARY_DIR}/python_compile_helper.py ${pysrcfiles} ${pyofiles} ) #create install rule and add generated files to target list set(python_install_gen_targets ${pycfiles} ${pyofiles}) install(FILES ${python_install_gen_targets} DESTINATION ${GR_PYTHON_INSTALL_DESTINATION} COMPONENT ${GR_PYTHON_INSTALL_COMPONENT} ) #################################################################### elseif(GR_PYTHON_INSTALL_PROGRAMS) #################################################################### file(TO_NATIVE_PATH ${PYTHON_EXECUTABLE} pyexe_native) if (CMAKE_CROSSCOMPILING) set(pyexe_native /usr/bin/env python) endif() foreach(pyfile ${GR_PYTHON_INSTALL_PROGRAMS}) get_filename_component(pyfile_name ${pyfile} NAME) get_filename_component(pyfile ${pyfile} ABSOLUTE) string(REPLACE "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}" pyexefile "${pyfile}.exe") list(APPEND python_install_gen_targets ${pyexefile}) get_filename_component(pyexefile_path ${pyexefile} PATH) file(MAKE_DIRECTORY ${pyexefile_path}) add_custom_command( OUTPUT ${pyexefile} DEPENDS ${pyfile} COMMAND ${PYTHON_EXECUTABLE} -c \"open('${pyexefile}', 'w').write('\#!${pyexe_native}\\n'+open('${pyfile}').read())\" COMMENT "Shebangin ${pyfile_name}" ) #on windows, python files need an extension to execute get_filename_component(pyfile_ext ${pyfile} EXT) if(WIN32 AND NOT pyfile_ext) set(pyfile_name "${pyfile_name}.py") endif() install(PROGRAMS ${pyexefile} RENAME ${pyfile_name} DESTINATION ${GR_PYTHON_INSTALL_DESTINATION} COMPONENT ${GR_PYTHON_INSTALL_COMPONENT} ) endforeach(pyfile) endif() GR_UNIQUE_TARGET("pygen" ${python_install_gen_targets}) endfunction(GR_PYTHON_INSTALL) ######################################################################## # Write the python helper script that generates byte code files ######################################################################## file(WRITE ${CMAKE_BINARY_DIR}/python_compile_helper.py " import sys, py_compile files = sys.argv[1:] srcs, gens = files[:len(files)/2], files[len(files)/2:] for src, gen in zip(srcs, gens): py_compile.compile(file=src, cfile=gen, doraise=True) ") gnuradio-3.7.2.1/gr-digital/0000755000175000017500000000000012207440367015352 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/CMakeLists.txt0000664000175000017500000000726412207440367020125 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-digital" ENABLE_GR_DIGITAL Boost_FOUND ENABLE_VOLK ENABLE_GNURADIO_RUNTIME ENABLE_GR_FFT ENABLE_GR_FILTER ENABLE_GR_BLOCKS ENABLE_GR_ANALOG ENABLE_GR_BLOCKS ENABLE_GR_FILTER ) GR_SET_GLOBAL(GR_DIGITAL_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) GR_SET_GLOBAL(GR_DIGITAL_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/swig ) SET(GR_PKG_DIGITAL_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/digital) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_DIGITAL) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_DIGITAL_DESCRIPTION "GNU Radio Digital Blocks") CPACK_COMPONENT("digital_runtime" GROUP "Digital" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("digital_devel" GROUP "Digital" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("digital_python" GROUP "Digital" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime" DEPENDS "runtime_python;digital_runtime" ) CPACK_COMPONENT("digital_swig" GROUP "Digital" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;digital_python;digital_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/digital) add_subdirectory(lib) add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/digital) add_subdirectory(grc) add_subdirectory(examples) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-digital.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-digital.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-digital.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "digital_devel" ) endif(ENABLE_GR_DIGITAL) gnuradio-3.7.2.1/gr-digital/include/0000775000175000017500000000000012207440367016777 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/include/gnuradio/0000775000175000017500000000000012207440367020607 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/0000775000175000017500000000000012244272666022232 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/packet_headerparser_b.h0000664000175000017500000000464512207440367026703 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PACKET_HEADERPARSER_B_H #define INCLUDED_DIGITAL_PACKET_HEADERPARSER_B_H #include #include #include namespace gr { namespace digital { /*! * \brief Post header metadata as a PMT * \ingroup packet_operators_blk * * \details * In a sense, this is the inverse block to packet_headergenerator_bb. * The difference is, the parsed header is not output as a stream, * but as a PMT dictionary, which is published to message port with * the id "header_data". * * The dictionary consists of the tags created by the header formatter * object. You should be able to use the exact same formatter object * as used on the Tx side in the packet_headergenerator_bb. * * If only a header length is given, this block uses the default header * format. */ class DIGITAL_API packet_headerparser_b : virtual public sync_block { public: typedef boost::shared_ptr sptr; /*! * \param header_formatter Header object. This should be the same as used for * packet_headergenerator_bb. */ static sptr make(const gr::digital::packet_header_default::sptr &header_formatter); /*! * \param header_len Number of bytes per header * \param len_tag_key Length Tag Key */ static sptr make(long header_len, const std::string &len_tag_key); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_PACKET_HEADERPARSER_B_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/header_payload_demux.h0000664000175000017500000000716212207440367026546 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_HEADER_PAYLOAD_DEMUX_H #define INCLUDED_DIGITAL_HEADER_PAYLOAD_DEMUX_H #include #include namespace gr { namespace digital { /*! * \brief Header/Payload demuxer. * \ingroup packet_operators_blk * * \details * This block is designed to handle packets from a bursty transmission. * Input 0 takes a continuous transmission of samples. * If used, input 1 is a trigger signal. In this case, a 1 on input 1 * is a trigger. Otherwise, a tag with the key specified in \p trigger_tag_key * is used as a trigger (its value is irrelevant). * * Until a trigger signal is detected, all samples are dropped onto the floor. * Once a trigger is detected, a total of \p header_len items are copied to output 0. * The block then stalls until it receives a message on the message port * \p header_data. The message must be a PMT dictionary; all key/value pairs are * copied as tags to the first item of the payload (which is assumed to be the * first item after the header). * The value corresponding to the key specified in \p length_tag_key is read * and taken as the payload length. The payload, together with the header data * as tags, is then copied to output 1. * * If specified, \p guard_interval items are discarded before every symbol. * This is useful for demuxing bursts of OFDM signals. * * Any tags on the input stream are copied to the corresponding output *if* they're * on an item that is propagated. Note that a tag on the header items is copied to the * header stream; that means the header-parsing block must handle these tags if they * should go on the payload. * A special case are tags on items that make up the guard interval. These are copied * to the first item of the following symbol. */ class DIGITAL_API header_payload_demux : virtual public block { public: typedef boost::shared_ptr sptr; /*! * \param header_len Number of symbols per header * \param items_per_symbol Number of items per symbol * \param guard_interval Number of items between two consecutive symbols * \param length_tag_key Key of the frame length tag * \param trigger_tag_key Key of the trigger tag * \param output_symbols Output symbols (true) or items (false)? * \param itemsize Item size (bytes per item) */ static sptr make( int header_len, int items_per_symbol, int guard_interval=0, const std::string &length_tag_key="frame_len", const std::string &trigger_tag_key="", bool output_symbols=false, size_t itemsize=sizeof(gr_complex) ); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_HEADER_PAYLOAD_DEMUX_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/simple_correlator.h0000664000175000017500000000271512207440367026127 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SIMPLE_CORRELATOR_H #define INCLUDED_GR_SIMPLE_CORRELATOR_H #include #include namespace gr { namespace digital { /*! * \brief inverse of simple_framer (more or less) * \ingroup packet_operators_blk * \ingroup deprecated_blk */ class DIGITAL_API simple_correlator : virtual public block { public: // gr::digital::simple_correlator::sptr typedef boost::shared_ptr sptr; static sptr make(int payload_bytesize); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SIMPLE_CORRELATOR_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_frame_equalizer_vcvc.h0000664000175000017500000000571612207440367027607 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_OFDM_FRAME_EQUALIZER_VCVC_H #define INCLUDED_OFDM_FRAME_EQUALIZER_VCVC_H #include #include #include namespace gr { namespace digital { /*! * \brief OFDM frame equalizer * \ingroup ofdm_blk * * \details * Performs equalization in one or two dimensions on a tagged OFDM frame. * * This does two things: * First, it removes the coarse carrier offset. If a tag is found on the first * item with the key 'ofdm_sync_carr_offset', this is interpreted as the coarse * frequency offset in number of carriers. * Next, it performs equalization in one or two dimensions on a tagged OFDM frame. * The actual equalization is done by a ofdm_frame_equalizer object, outside of * the block. * * Note that the tag with the coarse carrier offset is not removed. Blocks * downstream from this block must not attempt to also correct this offset. * * Input: a tagged series of OFDM symbols. * Output: The same as the input, but equalized and frequency-corrected. */ class DIGITAL_API ofdm_frame_equalizer_vcvc : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /*! * \param equalizer The equalizer object that will do the actual work * \param cp_len Length of the cyclic prefix in samples (required to correct the frequency offset) * \param len_tag_key Length tag key * \param propagate_channel_state If true, the channel state after the last symbol * will be added to the first symbol as a tag * \param fixed_frame_len Set if the frame length is fixed throughout, * helps with book keeping. */ static sptr make( ofdm_equalizer_base::sptr equalizer, int cp_len, const std::string &len_tag_key = "frame_len", bool propagate_channel_state=false, int fixed_frame_len=0 ); }; } // namespace digital } // namespace gr #endif /* INCLUDED_OFDM_FRAME_EQUALIZER_VCVC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/framer_sink_1.h0000664000175000017500000000440412207440367025117 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FRAMER_SINK_1_H #define INCLUDED_GR_FRAMER_SINK_1_H #include #include #include namespace gr { namespace digital { /*! * \brief Given a stream of bits and access_code flags, assemble packets. * \ingroup packet_operators_blk * * \details * input: stream of bytes from digital_correlate_access_code_bb * output: none. Pushes assembled packet into target queue * * The framer expects a fixed length header of 2 16-bit shorts * containing the payload length, followed by the payload. If the * 2 16-bit shorts are not identical, this packet is * ignored. Better algs are welcome. * * The input data consists of bytes that have two bits used. Bit * 0, the LSB, contains the data bit. Bit 1 if set, indicates that * the corresponding bit is the the first bit of the packet. That * is, this bit is the first one after the access code. */ class DIGITAL_API framer_sink_1 : virtual public sync_block { public: // gr::digital::framer_sink_1::sptr typedef boost::shared_ptr sptr; /*! * Make a framer_sink_1 block. * * \param target_queue The message queue where frames go. */ static sptr make(msg_queue::sptr target_queue); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_FRAMER_SINK_1_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/CMakeLists.txt0000664000175000017500000001031412237515112024755 0ustar jcorganjcorgan# Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict2(name, sig, 'digital') build_utils.expand_template(d, inp) ") macro(expand_h root) #make a list of all the generated files unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the files add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #install rules for the generated h files list(APPEND generated_includes ${expanded_files_h}) endmacro(expand_h) ######################################################################## # Invoke macro to generate various sources ####################################################################### expand_h(chunks_to_symbols_XX bf bc sf sc if ic) add_custom_target(digital_generated_includes DEPENDS ${generated_includes} ) ######################################################################## # Install header files ######################################################################## install(FILES ${generated_includes} additive_scrambler_bb.h api.h binary_slicer_fb.h clock_recovery_mm_cc.h clock_recovery_mm_ff.h cma_equalizer_cc.h constellation.h constellation_decoder_cb.h constellation_receiver_cb.h constellation_soft_decoder_cf.h correlate_access_code_bb.h correlate_access_code_tag_bb.h correlate_and_sync_cc.h costas_loop_cc.h cpmmod_bc.h crc32.h crc32_bb.h descrambler_bb.h diff_decoder_bb.h diff_encoder_bb.h diff_phasor_cc.h fll_band_edge_cc.h framer_sink_1.h glfsr.h glfsr_source_b.h glfsr_source_f.h header_payload_demux.h kurtotic_equalizer_cc.h lfsr.h lms_dd_equalizer_cc.h map_bb.h metric_type.h mpsk_receiver_cc.h mpsk_snr_est.h mpsk_snr_est_cc.h ofdm_carrier_allocator_cvc.h ofdm_chanest_vcvc.h ofdm_cyclic_prefixer.h ofdm_equalizer_base.h ofdm_equalizer_simpledfe.h ofdm_equalizer_static.h ofdm_frame_acquisition.h ofdm_frame_equalizer_vcvc.h ofdm_frame_sink.h ofdm_insert_preamble.h ofdm_mapper_bcv.h ofdm_sampler.h ofdm_serializer_vcc.h ofdm_sync_sc_cfb.h packet_header_default.h packet_header_ofdm.h packet_headergenerator_bb.h packet_headerparser_b.h packet_sink.h pfb_clock_sync_ccf.h pfb_clock_sync_fff.h pn_correlator_cc.h probe_density_b.h probe_mpsk_snr_est_c.h scrambler_bb.h simple_correlator.h simple_framer.h simple_framer_sync.h header_payload_demux.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/digital COMPONENT "digital_devel" ) gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/probe_mpsk_snr_est_c.h0000664000175000017500000000650612207440367026604 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PROBE_MPSK_SNR_EST_C_H #define INCLUDED_DIGITAL_PROBE_MPSK_SNR_EST_C_H #include #include #include namespace gr { namespace digital { /*! * \brief A probe for computing SNR of a signal. * \ingroup measurement_tools_blk * * \details * This is a probe block (a sink) that can be used to monitor and * retrieve estimations of the signal SNR. This probe is designed * for use with M-PSK signals especially. The type of estimator is * specified as the \p type parameter in the constructor. The * estimators tend to trade off performance for accuracy, although * experimentation should be done to figure out the right approach * for a given implementation. Further, the current set of * estimators are designed and proven theoretically under AWGN * conditions; some amount of error should be assumed and/or * estimated for real channel conditions. */ class DIGITAL_API probe_mpsk_snr_est_c : virtual public sync_block { public: // gr::digital::probe_mpsk_snr_est_c::sptr typedef boost::shared_ptr sptr; /*! Make an MPSK SNR probe. * * Parameters: * * \param type: the type of estimator to use see * gr::digital::snr_est_type_t for details about the types. * \param msg_nsamples: [not implemented yet] after this many * samples, a message containing the SNR (key='snr') will be sent * \param alpha: the update rate of internal running average * calculations. */ static sptr make(snr_est_type_t type, int msg_nsamples=10000, double alpha=0.001); //! Return the estimated signal-to-noise ratio in decibels virtual double snr() = 0; //! Return the type of estimator in use virtual snr_est_type_t type() const = 0; //! Return how many samples between SNR messages virtual int msg_nsample() const = 0; //! Get the running-average coefficient virtual double alpha() const = 0; //! Set type of estimator to use virtual void set_type(snr_est_type_t t) = 0; //! Set the number of samples between SNR messages virtual void set_msg_nsample(int n) = 0; //! Set the running-average coefficient virtual void set_alpha(double alpha) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_PROBE_MPSK_SNR_EST_C_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/clock_recovery_mm_cc.h0000664000175000017500000000540212207440367026545 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_CC_H #define INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_CC_H #include #include namespace gr { namespace digital { /*! * \brief Mueller and Müller (M&M) based clock recovery block with complex input, complex output. * \ingroup synchronizers_blk * * \details * This implements the Mueller and Müller (M&M) discrete-time * error-tracking synchronizer. * * The complex version here is based on: Modified Mueller and * Muller clock recovery circuit: * * G. R. Danesfahani, T.G. Jeans, "Optimisation of modified Mueller * and Muller algorithm," Electronics Letters, Vol. 31, no. 13, 22 * June 1995, pp. 1032 - 1033. */ class DIGITAL_API clock_recovery_mm_cc : virtual public block { public: // gr::digital::clock_recovery_mm_cc::sptr typedef boost::shared_ptr sptr; /*! * Make a M&M clock recovery block. * * \param omega Initial estimate of samples per symbol * \param gain_omega Gain setting for omega update loop * \param mu Initial estimate of phase of sample * \param gain_mu Gain setting for mu update loop * \param omega_relative_limit limit on omega */ static sptr make(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limit); virtual float mu() const = 0; virtual float omega() const = 0; virtual float gain_mu() const = 0; virtual float gain_omega() const = 0; virtual void set_verbose(bool verbose) = 0; virtual void set_gain_mu (float gain_mu) = 0; virtual void set_gain_omega (float gain_omega) = 0; virtual void set_mu (float mu) = 0; virtual void set_omega (float omega) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_equalizer_base.h0000664000175000017500000000751312225347106026400 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_EQUALIZER_BASE_H #define INCLUDED_DIGITAL_OFDM_EQUALIZER_BASE_H #include #include #include #include namespace gr { namespace digital { /* \brief Base class for implementation details of frequency-domain OFDM equalizers. * \ingroup ofdm_blk * \ingroup equalizers_blk */ class DIGITAL_API ofdm_equalizer_base : public boost::enable_shared_from_this { protected: int d_fft_len; public: typedef boost::shared_ptr sptr; ofdm_equalizer_base(int fft_len); virtual ~ofdm_equalizer_base(); //! Reset the channel information state knowledge virtual void reset() = 0; //! Run the actual equalization virtual void equalize( gr_complex *frame, int n_sym, const std::vector &initial_taps = std::vector(), const std::vector &tags = std::vector()) = 0; //! Return the current channel state virtual void get_channel_state(std::vector &taps) = 0; int fft_len() { return d_fft_len; }; sptr base() { return shared_from_this(); }; }; /* \brief Base class for implementation details of 1-dimensional OFDM FDEs which use pilot tones. * \ingroup digital * */ class DIGITAL_API ofdm_equalizer_1d_pilots : public ofdm_equalizer_base { protected: //! If \p d_occupied_carriers[k][l] is true, symbol k, carrier l is carrying data. // (this is a different format than occupied_carriers!) std::vector d_occupied_carriers; //! If \p d_pilot_carriers[k][l] is true, symbol k, carrier l is carrying data. // (this is a different format than pilot_carriers!) std::vector > d_pilot_carriers; //! If \p d_pilot_carriers[k][l] is true, d_pilot_symbols[k][l] is its tx'd value. // (this is a different format than pilot_symbols!) std::vector > d_pilot_symbols; //! In case the frame doesn't begin with OFDM symbol 0, this is the index of the first symbol int d_symbols_skipped; //! The current position in the set of pilot symbols int d_pilot_carr_set; //! Vector of length d_fft_len saving the current channel state (on the occupied carriers) std::vector d_channel_state; public: typedef boost::shared_ptr sptr; ofdm_equalizer_1d_pilots( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, int symbols_skipped, bool input_is_shifted); ~ofdm_equalizer_1d_pilots(); void reset(); void get_channel_state(std::vector &taps); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_EQUALIZER_BASE_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/metric_type.h0000664000175000017500000000220412207440367024717 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_METRIC_TYPE_H #define INCLUDED_DIGITAL_METRIC_TYPE_H namespace gr { namespace digital { typedef enum { TRELLIS_EUCLIDEAN = 200, TRELLIS_HARD_SYMBOL, TRELLIS_HARD_BIT } trellis_metric_type_t; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_METRIC_TYPE_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/constellation.h0000664000175000017500000005405112244272666025266 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_H #define INCLUDED_DIGITAL_CONSTELLATION_H #include #include #include #include #include #include #include namespace gr { namespace digital { /************************************************************/ /* constellation */ /* */ /* Base class defining interface. */ /************************************************************/ class constellation; typedef boost::shared_ptr constellation_sptr; /*! * \brief An abstracted constellation object * \ingroup symbol_coding_blk * * \details * The constellation objects hold the necessary information to pass * around constellation information for modulators and * demodulators. These objects contain the mapping between the bits * and the constellation points used to represent them as well as * methods for slicing the symbol space. Various implementations are * possible for efficiency and ease of use. * * Standard constellations (BPSK, QPSK, QAM, etc) can be inherited * from this class and overloaded to perform optimized slicing and * constellation mappings. */ class DIGITAL_API constellation : public boost::enable_shared_from_this { public: constellation(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality); constellation(); virtual ~constellation(); //! Returns the constellation points for a symbol value void map_to_points(unsigned int value, gr_complex *points); std::vector map_to_points_v(unsigned int value); //! Returns the constellation point that matches best. virtual unsigned int decision_maker(const gr_complex *sample) = 0; //! Takes a vector rather than a pointer. Better for SWIG wrapping. unsigned int decision_maker_v(std::vector sample); //! Also calculates the phase error. unsigned int decision_maker_pe(const gr_complex *sample, float *phase_error); //! Calculates distance. //unsigned int decision_maker_e(const gr_complex *sample, float *error); //! Calculates metrics for all points in the constellation. //! For use with the viterbi algorithm. virtual void calc_metric(const gr_complex *sample, float *metric, gr::digital::trellis_metric_type_t type); virtual void calc_euclidean_metric(const gr_complex *sample, float *metric); virtual void calc_hard_symbol_metric(const gr_complex *sample, float *metric); //! Returns the set of points in this constellation. std::vector points() { return d_constellation;} //! Returns the vector of points in this constellation. //! Raise error if dimensionality is not one. std::vector s_points(); //! Returns a vector of vectors of points. std::vector > v_points(); //! Whether to apply an encoding before doing differential encoding. (e.g. gray coding) bool apply_pre_diff_code() { return d_apply_pre_diff_code;} //! Whether to apply an encoding before doing differential encoding. (e.g. gray coding) void set_pre_diff_code(bool a) { d_apply_pre_diff_code = a;} //! Returns the encoding to apply before differential encoding. std::vector pre_diff_code() { return d_pre_diff_code;} //! Returns the order of rotational symmetry. unsigned int rotational_symmetry() { return d_rotational_symmetry;} //! Returns the number of complex numbers in a single symbol. unsigned int dimensionality() {return d_dimensionality;} unsigned int bits_per_symbol() { return floor(log(double(d_constellation.size()))/d_dimensionality/log(2.0)); } unsigned int arity() { return d_arity; } constellation_sptr base() { return shared_from_this(); } pmt::pmt_t as_pmt() { return pmt::make_any(boost::any(base())); } /*! \brief Generates the soft decision LUT based on * constellation and symbol map. * * \details Generates the soft decision LUT based on * constellation and symbol map. It can be given a estimate of * the noise power in the channel as \p npwr. * * \param precision Number of bits of precision on each axis. * \param npwr Estimate of the noise power (if known). * * This is expensive to compute. */ void gen_soft_dec_lut(int precision, float npwr=1.0); /*! \brief Calculate soft decisions for the given \p sample. * * \details Calculate the soft decisions from the given \p sample * at the given noise power \p npwr. * * This is a very costly algorithm (especially for higher order * modulations) and should be used sparingly. It uses the * #gen_soft_dec_lut function to generate the LUT, which * should be done once or if a large change in the noise floor * is detected. * * Instead of using this function, generate the LUT using the * #gen_soft_dec_lut after creating the constellation object * and then use the #soft_decision_maker function to return the * answer from the LUT. * * \param sample The complex sample to get the soft decisions. * \param npwr Estimate of the noise power (if known). */ virtual std::vector calc_soft_dec(gr_complex sample, float npwr=1.0); /*! \brief Define a soft decision look-up table. * * \details Define a soft decision look-up table (LUT). Because * soft decisions can be calculated in various ways with various * levels of accuracy and complexity, this function allows * users to create a LUT in their own way. * * Setting the LUT here means that #has_soft_dec_lut will return * true. Decision vectors returned by #soft_decision_maker will * be calculated using this LUT. * * \param soft_dec_lut The soft decision LUT as a vector of * tuples (vectors in C++) of soft decisions. Each * element of the LUT is a vector of k-bit floats (where * there are k bits/sample in the constellation). * \param precision The number of bits of precision used when * generating the LUT. */ void set_soft_dec_lut(const std::vector< std::vector > &soft_dec_lut, int precision); //! Returns True if the soft decision LUT has been defined, False otherwise. bool has_soft_dec_lut(); /*! \brief Returns the soft decisions for the given \p sample. * * \details Returns the soft decisions for the given \p * sample. If a LUT is defined for the object, the decisions * will be calculated from there. Otherwise, this function will * call calc_soft_dec directly to calculate the soft decisions. * * \param sample The complex sample to get the soft decisions. */ std::vector soft_decision_maker(gr_complex sample); protected: std::vector d_constellation; std::vector d_pre_diff_code; bool d_apply_pre_diff_code; unsigned int d_rotational_symmetry; unsigned int d_dimensionality; unsigned int d_arity; //! The factor by which the user given constellation points were //! scaled by to achieve an average amplitude of 1. float d_scalefactor; float d_re_min, d_re_max, d_im_min, d_im_max; std::vector< std::vector > d_soft_dec_lut; int d_lut_precision; float d_lut_scale; float get_distance(unsigned int index, const gr_complex *sample); unsigned int get_closest_point(const gr_complex *sample); void calc_arity(); void max_min_axes(); }; /************************************************************/ /* constellation_calcdist */ /* */ /************************************************************/ /*! \brief Calculate Euclidian distance for any constellation * \ingroup digital * * \details * Constellation which calculates the distance to each point in the * constellation for decision making. Inefficient for large * constellations. */ class DIGITAL_API constellation_calcdist : public constellation { public: typedef boost::shared_ptr sptr; /*! * Make a general constellation object that calculates the Euclidean distance for hard decisions. * * \param constell List of constellation points (order of list matches pre_diff_code) * \param pre_diff_code List of alphabet symbols (before applying any differential * coding) (order of list matches constell) * \param rotational_symmetry Number of rotations around unit circle that have the same representation. * \param dimensionality Number of dimensions to the constellation. */ static sptr make(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality); unsigned int decision_maker(const gr_complex *sample); // void calc_metric(gr_complex *sample, float *metric, trellis_metric_type_t type); // void calc_euclidean_metric(gr_complex *sample, float *metric); // void calc_hard_symbol_metric(gr_complex *sample, float *metric); protected: constellation_calcdist(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality); }; /************************************************************/ /*! constellation_sector */ /************************************************************/ /*! * \brief Sectorized digital constellation * \ingroup digital * * \details * Constellation space is divided into sectors. Each sector is * associated with the nearest constellation point. */ class DIGITAL_API constellation_sector : public constellation { public: /*! * Make a sectorized constellation object. * * \param constell List of constellation points (order of list matches pre_diff_code) * \param pre_diff_code List of alphabet symbols (before applying any differential * coding) (order of list matches constell) * \param rotational_symmetry Number of rotations around unit circle that have the same representation. * \param dimensionality Number of z-axis dimensions to the constellation * \param n_sectors Number of sectors in the constellation. */ constellation_sector(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality, unsigned int n_sectors); ~constellation_sector(); unsigned int decision_maker(const gr_complex *sample); protected: virtual unsigned int get_sector(const gr_complex *sample) = 0; virtual unsigned int calc_sector_value(unsigned int sector) = 0; void find_sector_values(); unsigned int n_sectors; private: std::vector sector_values; }; /************************************************************/ /* constellation_rect */ /************************************************************/ /*! * \brief Rectangular digital constellation * \ingroup digital * * Only implemented for 1-(complex)dimensional constellation. * * Constellation space is divided into rectangular sectors. Each * sector is associated with the nearest constellation point. * * Works well for square QAM. * * Works for any generic constellation provided sectors are not * too large. */ class DIGITAL_API constellation_rect : public constellation_sector { public: typedef boost::shared_ptr sptr; /*! * Make a rectangular constellation object. * * \param constell List of constellation points (order of list matches pre_diff_code) * \param pre_diff_code List of alphabet symbols (before applying any differential * coding) (order of list matches constell) * \param rotational_symmetry Number of rotations around unit circle that have the same representation. * \param real_sectors Number of sectors the real axis is split in to. * \param imag_sectors Number of sectors the imag axis is split in to. * \param width_real_sectors width of each real sector to calculate decision boundaries. * \param width_imag_sectors width of each imag sector to calculate decision boundaries. */ static constellation_rect::sptr make(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors); ~constellation_rect(); protected: constellation_rect(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors); unsigned int get_sector(const gr_complex *sample); gr_complex calc_sector_center(unsigned int sector); unsigned int calc_sector_value(unsigned int sector); private: unsigned int n_real_sectors; unsigned int n_imag_sectors; float d_width_real_sectors; float d_width_imag_sectors; }; /************************************************************/ /* constellation_expl_rect */ /************************************************************/ /*! * \brief Rectangular digital constellation. * \ingroup digital * * \details * Only implemented for 1-(complex)dimensional constellation. * * Constellation space is divided into rectangular sectors. Each * sector is associated with the nearest constellation point. * * This class is different from constellation_rect in that the * mapping from sector to constellation point is explicitly passed * into the constructor as sector_values. Usually we do not need * this, since we want each sector to be automatically mapped to * the closest constellation point, however sometimes it's nice to * have the flexibility. */ class DIGITAL_API constellation_expl_rect : public constellation_rect { public: typedef boost::shared_ptr sptr; static sptr make(std::vector constellation, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors, std::vector sector_values); ~constellation_expl_rect(); protected: constellation_expl_rect(std::vector constellation, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors, std::vector sector_values); unsigned int calc_sector_value (unsigned int sector) { return d_sector_values[sector]; } private: std::vector d_sector_values; }; /************************************************************/ /* constellation_psk */ /************************************************************/ /*! * \brief constellation_psk * \ingroup digital * * Constellation space is divided into pie slices sectors. * * Each slice is associated with the nearest constellation point. * * Works well for PSK but nothing else. * * Assumes that there is a constellation point at 1.x */ class DIGITAL_API constellation_psk : public constellation_sector { public: typedef boost::shared_ptr sptr; // public constructor static sptr make(std::vector constell, std::vector pre_diff_code, unsigned int n_sectors); ~constellation_psk(); protected: unsigned int get_sector(const gr_complex *sample); unsigned int calc_sector_value(unsigned int sector); constellation_psk(std::vector constell, std::vector pre_diff_code, unsigned int n_sectors); }; /************************************************************/ /* constellation_bpsk */ /* */ /* Only works for BPSK. */ /* */ /************************************************************/ /*! * \brief Digital constellation for BPSK . * \ingroup digital * * \details * \verbatim 0 | 1 \endverbatim */ class DIGITAL_API constellation_bpsk : public constellation { public: typedef boost::shared_ptr sptr; // public constructor static sptr make(); ~constellation_bpsk(); unsigned int decision_maker(const gr_complex *sample); protected: constellation_bpsk(); }; /************************************************************/ /* constellation_qpsk */ /* */ /* Only works for QPSK. */ /* */ /************************************************************/ /*! * \brief Digital constellation for QPSK * \ingroup digital * * \details * \verbatim 01 | 11 ------- 00 | 10 \endverbatim */ class DIGITAL_API constellation_qpsk : public constellation { public: typedef boost::shared_ptr sptr; // public constructor static sptr make(); ~constellation_qpsk(); unsigned int decision_maker(const gr_complex *sample); protected: constellation_qpsk(); }; /************************************************************/ /* constellation_dqpsk */ /* */ /* Works with differential encoding; slower decisions. */ /* */ /************************************************************/ /*! * \brief Digital constellation for DQPSK. * \ingroup digital * * \details * \verbatim 01 | 00 ------- 11 | 10 \endverbatim */ class DIGITAL_API constellation_dqpsk : public constellation { public: typedef boost::shared_ptr sptr; // public constructor static sptr make(); ~constellation_dqpsk(); unsigned int decision_maker(const gr_complex *sample); protected: constellation_dqpsk(); }; /************************************************************/ /* constellation_8psk */ /* */ /* Only works for 8PSK. */ /* */ /************************************************************/ /*! * \brief Digital constellation for 8PSK. * \ingroup digital * * \details * \verbatim 101 | 100 001 | 000 ----------------- 011 | 010 111 | 110 \endverbatim */ class DIGITAL_API constellation_8psk : public constellation { public: typedef boost::shared_ptr sptr; // public constructor static sptr make(); ~constellation_8psk(); unsigned int decision_maker(const gr_complex *sample); protected: constellation_8psk(); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/chunks_to_symbols_XX.h.t0000664000175000017500000000477312244272666027044 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace digital { /*! * \brief Map a stream of unpacked symbol indexes to stream of * float or complex constellation points in D dimensions (D = 1 by * default) \ingroup converter_blk * * \details * \li input: stream of @I_TYPE@ * \li output: stream of @O_TYPE@ * * \li out[n D + k] = symbol_table[in[n] D + k], k=0,1,...,D-1 * * The combination of gr::blocks::packed_to_unpacked_XX followed * by gr::digital::chunks_to_symbols_XY handles the general case * of mapping from a stream of bytes or shorts into arbitrary * float or complex symbols. * * \sa gr::blocks::packed_to_unpacked_bb, gr::blocks::unpacked_to_packed_bb, * \sa gr::blocks::packed_to_unpacked_ss, gr::blocks::unpacked_to_packed_ss, * \sa gr::digital::chunks_to_symbols_bf, gr::digital::chunks_to_symbols_bc. * \sa gr::digital::chunks_to_symbols_sf, gr::digital::chunks_to_symbols_sc. */ class DIGITAL_API @NAME@ : virtual public sync_interpolator { public: // gr::digital::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; /*! * Make a chunks-to-symbols block. * * \param symbol_table: list that maps chunks to symbols. * \param D: dimension of table. */ static sptr make(const std::vector<@O_TYPE@> &symbol_table, const int D = 1); virtual int D() const = 0; virtual std::vector<@O_TYPE@> symbol_table() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/constellation_receiver_cb.h0000664000175000017500000000502012237515112027572 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_RECEIVER_CB_H #define INCLUDED_DIGITAL_CONSTELLATION_RECEIVER_CB_H #include #include #include namespace gr { namespace digital { /*! * \brief This block makes hard decisions about the received * symbols (using a constellation object) and also fine tunes * phase synchronization. * * \details * * The phase and frequency synchronization are based on a Costas * loop that finds the error of the incoming signal point compared * to its nearest constellation point. The frequency and phase of * the NCO are updated according to this error. */ class DIGITAL_API constellation_receiver_cb : virtual public block { public: // gr::digital::constellation_receiver_cb::sptr typedef boost::shared_ptr sptr; /*! * \brief Constructs a constellation receiver that (phase/fine * freq) synchronizes and decodes constellation points specified * by a constellation object. * * \param constellation constellation of points for generic modulation * \param loop_bw Loop bandwidth of the Costas Loop (~ 2pi/100) * \param fmin minimum normalized frequency value the loop can achieve * \param fmax maximum normalized frequency value the loop can achieve */ static sptr make(constellation_sptr constellation, float loop_bw, float fmin, float fmax); virtual void phase_error_tracking(float phase_error) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_RECEIVER_CB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/diff_encoder_bb.h0000664000175000017500000000325212207440367025451 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DIFF_ENCODER_BB_H #define INCLUDED_GR_DIFF_ENCODER_BB_H #include #include namespace gr { namespace digital { /*! * \brief Differential decoder: y[0] = (x[0] + y[-1]) % M * \ingroup symbol_coding_blk * * \details * Uses current and previous symbols and the alphabet modulus to * perform differential encoding. */ class DIGITAL_API diff_encoder_bb : virtual public sync_block { public: // gr::digital::diff_encoder_bb::sptr typedef boost::shared_ptr sptr; /*! * Make a differntial encoder block. * * \param modulus Modulus of code's alphabet */ static sptr make(unsigned int modulus); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DIFF_ENCODER_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_frame_acquisition.h0000664000175000017500000000620612207440367027110 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_FRAME_ACQUISITION_H #define INCLUDED_DIGITAL_OFDM_FRAME_ACQUISITION_H #include #include #include namespace gr { namespace digital { /*! * \brief take a vector of complex constellation points in from an * FFT and performs a correlation and equalization. * \ingroup ofdm_blk * * \details * This block takes the output of an FFT of a received OFDM symbol * and finds the start of a frame based on two known symbols. It * also looks at the surrounding bins in the FFT output for the * correlation in case there is a large frequency shift in the * data. This block assumes that the fine frequency shift has * already been corrected and that the samples fall in the middle * of one FFT bin. * * It then uses one of those known symbols to estimate the channel * response over all subcarriers and does a simple 1-tap * equalization on all subcarriers. This corrects for the phase * and amplitude distortion caused by the channel. */ class DIGITAL_API ofdm_frame_acquisition : virtual public block { public: // gr::digital::ofdm_frame_acquisition::sptr typedef boost::shared_ptr sptr; /*! * Make an OFDM correlator and equalizer. * * \param occupied_carriers The number of subcarriers with data in the received symbol * \param fft_length The size of the FFT vector (occupied_carriers + unused carriers) * \param cplen The length of the cycle prefix * \param known_symbol A vector of complex numbers representing a known symbol at the * start of a frame (usually a BPSK PN sequence) * \param max_fft_shift_len Set's the maximum distance you can look between bins for correlation */ static sptr make(unsigned int occupied_carriers, unsigned int fft_length, unsigned int cplen, const std::vector &known_symbol, unsigned int max_fft_shift_len=4); /*! * \brief Return an estimate of the SNR of the channel */ virtual float snr() = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_FRAME_ACQUISITION_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/diff_phasor_cc.h0000664000175000017500000000317512207440367025334 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DIFF_PHASOR_CC_H #define INCLUDED_GR_DIFF_PHASOR_CC_H #include #include namespace gr { namespace digital { /*! * \brief Differential decoding based on phase change. * \ingroup symbol_coding_blk * * \details * Uses the phase difference between two symbols to determine the * output symbol: * * out[i] = in[i] * conj(in[i-1]); */ class DIGITAL_API diff_phasor_cc : virtual public sync_block { public: // gr::digital::diff_phasor_cc::sptr typedef boost::shared_ptr sptr; /*! * Make a differential phasor decoding block. */ static sptr make(); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DIFF_PHASOR_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_carrier_allocator_cvc.h0000664000175000017500000001314612237515112027723 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_CARRIER_ALLOCATOR_CVC_H #define INCLUDED_DIGITAL_OFDM_CARRIER_ALLOCATOR_CVC_H #include #include namespace gr { namespace digital { /*! * \brief Create frequency domain OFDM symbols from complex values, add pilots. * \ingroup ofdm_blk * * \details * This block turns a stream of complex, scalar modulation symbols into vectors * which are the input for an IFFT in an OFDM transmitter. It also supports the * possibility of placing pilot symbols onto the carriers. * * The carriers can be allocated freely, if a carrier is not allocated, it is set * to zero. This allows doing OFDMA-style carrier allocations. * * Input: A tagged stream of complex scalars. The first item must have a tag * containing the number of complex symbols in this frame. * Output: A tagged stream of complex vectors of length fft_len. This can directly * be connected to an FFT block. Make sure to set this block to 'reverse' * for the IFFT. If \p output_is_shifted is true, the FFT block must activate * FFT shifting, otherwise, set shifting to false. If given, sync words are * prepended to the output. Note that sync words are prepended verbatim, * make sure they are shifted (or not). * * Carrier indexes are always such that index 0 is the DC carrier (note: you should * not allocate this carrier). The carriers below the DC carrier are either indexed * with negative numbers, or with indexes larger than \p fft_len/2. Index -1 and index * \p fft_len-1 both identify the carrier below the DC carrier. * * Tags are propagated such that a tag on an incoming complex symbol is mapped to the * corresponding OFDM symbol. There is one exception: If a tag is on the first OFDM * symbol, it is assumed that this tag should stay there, so it is moved to the front * even if a sync word is included (any other tags will never be attached to the * sync word). This allows tags to control the transmit timing to pass through in the * correct position. */ class DIGITAL_API ofdm_carrier_allocator_cvc : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; virtual std::string len_tag_key() = 0; virtual const int fft_len() = 0; virtual std::vector > occupied_carriers() = 0; /* * \param fft_len FFT length, is also the maximum width of the OFDM symbols, the * output vector size and maximum value for elements in * \p occupied_carriers and \p pilot_carriers. * \param occupied_carriers A vector of vectors of indexes. Example: if * occupied_carriers = ((1, 2, 3), (1, 2, 4)), the first * three input symbols will be mapped to carriers 1, 2 * and 3. After that, a new OFDM symbol is started. The next * three input symbols will be placed onto carriers 1, 2 * and 4 of the second OFDM symbol. The allocation then * starts from the beginning. * Order matters! The first input symbol is always mapped * onto occupied_carriers[0][0]. * \param pilot_carriers The position of the pilot symbols. Same as occupied_carriers, * but the actual symbols are taken from pilot_symbols instead * of the input stream. * \param pilot_symbols The pilot symbols which are placed onto the pilot carriers. * pilot_symbols[0][0] is placed onto the first OFDM symbol, on * carrier index pilot_carriers[0][0] etc. * \param sync_words OFDM symbols that are prepended to the OFDM frame (usually for * synchronisation purposes, e.g. OFDM symbols with every second * sub-carrier being idle). Is a vector of complex vectors of length * \p fft_len * \param len_tag_key The key of the tag identifying the length of the input packet. */ static sptr make( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, const std::vector > &sync_words, const std::string &len_tag_key = "packet_len", const bool output_is_shifted=true); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_CARRIER_ALLOCATOR_CVC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_equalizer_simpledfe.h0000664000175000017500000001350512207440367027437 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_EQUALIZER_SIMPLEDFE_H #define INCLUDED_DIGITAL_OFDM_EQUALIZER_SIMPLEDFE_H #include #include #include namespace gr { namespace digital { /* \brief Simple decision feedback equalizer for OFDM. * \ingroup ofdm_blk * \ingroup equalizers_blk * * \details * Equalizes an OFDM signal symbol by symbol using knowledge of the * complex modulations symbols. * For every symbol, the following steps are performed: * - On every sub-carrier, decode the modulation symbol * - Use the difference between the decoded symbol and the received symbol * to update the channel state on this carrier * - Whenever a pilot symbol is found, it uses the known pilot symbol to * update the channel state. * * This equalizer makes a lot of assumptions: * - The initial channel state is good enough to decode the first * symbol without error (unless the first symbol only consists of pilot * tones) * - The channel changes only very slowly, such that the channel state * from one symbol is enough to decode the next * - SNR low enough that equalization will always suffice to correctly * decode a symbol * If these assumptions are not met, the most common error is that the * channel state is estimated incorrectly during equalization; after that, * all subsequent symbols will be completely wrong. * * Note that the equalized symbols are *exact points* on the constellation. * This means soft information of the modulation symbols is lost after the * equalization, which is suboptimal for channel codes that use soft decision. * */ class DIGITAL_API ofdm_equalizer_simpledfe : public ofdm_equalizer_1d_pilots { public: typedef boost::shared_ptr sptr; ofdm_equalizer_simpledfe( int fft_len, const gr::digital::constellation_sptr &constellation, const std::vector > &occupied_carriers = std::vector >(), const std::vector > &pilot_carriers = std::vector >(), const std::vector > &pilot_symbols = std::vector >(), int symbols_skipped = 0, float alpha = 0.1, bool input_is_shifted = true); ~ofdm_equalizer_simpledfe(); void equalize(gr_complex *frame, int n_sym, const std::vector &initial_taps = std::vector(), const std::vector &tags = std::vector()); /* * \param fft_len FFT length * \param constellation The constellation object describing the modulation used * on the subcarriers (e.g. QPSK). This is used to decode * the individual symbols. * \param occupied_carriers List of occupied carriers, see ofdm_carrier_allocator * for a description. * \param pilot_carriers Position of pilot symbols, see ofdm_carrier_allocator * for a description. * \param pilot_symbols Value of pilot symbols, see ofdm_carrier_allocator * for a description. * \param alpha Averaging coefficient (in a nutshell, if \f$H_{i,k}\f$ is the channel * state for carrier i and symbol k, * \f$H_{i,k+1} = \alpha H_{i,k} + (1 - \alpha) H_{i,k+1}\f$. Make this * larger if there's more noise, but keep in mind that larger values * of alpha mean slower response to channel changes). * \param symbols_skipped Starting position within occupied_carriers and pilot_carriers. * If the first symbol of the frame was removed (e.g. to decode the * header), set this make sure the pilot symbols are correctly * identified. * \param input_is_shifted Set this to false if the input signal is not shifted, i.e. * the first input items is on the DC carrier. * Note that a lot of the OFDM receiver blocks operate on shifted * signals! */ static sptr make( int fft_len, const gr::digital::constellation_sptr &constellation, const std::vector > &occupied_carriers = std::vector >(), const std::vector > &pilot_carriers = std::vector >(), const std::vector > &pilot_symbols = std::vector >(), int symbols_skipped=0, float alpha=0.1, bool input_is_shifted=true ); private: gr::digital::constellation_sptr d_constellation; //! Averaging coefficient float d_alpha; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_EQUALIZER_SIMPLEDFE_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/packet_header_default.h0000664000175000017500000001012612237515112026652 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PACKET_HEADER_DEFAULT_H #define INCLUDED_DIGITAL_PACKET_HEADER_DEFAULT_H #include #include #include #include namespace gr { namespace digital { /*! * \brief Default header formatter for digital packet transmission. * \ingroup packet_operators_blk * * \details * For bursty/packetized digital transmission, packets are usually prepended * with a packet header, containing the number of bytes etc. * This class is not a block, but a tool to create these packet header. * * This is a default packet header (see header_formatter()) for a description * on the header format). To create other header, derive packet header creator * classes from this function. * * gr::digital::packet_headergenerator_bb uses header generators derived from * this class to create packet headers from data streams. */ class DIGITAL_API packet_header_default : public boost::enable_shared_from_this { public: typedef boost::shared_ptr sptr; packet_header_default( long header_len, const std::string &len_tag_key="packet_len", const std::string &num_tag_key="packet_num", int bits_per_byte=1); virtual ~packet_header_default(); sptr base() { return shared_from_this(); }; sptr formatter() { return shared_from_this(); }; void set_header_num(unsigned header_num) { d_header_number = header_num; }; long header_len() { return d_header_len; }; pmt::pmt_t len_tag_key() { return d_len_tag_key; }; /*! * \brief Encodes the header information in the given tags into bits and places them into \p out * * Uses the following header format: * Bits 0-11: The packet length (what was stored in the tag with key \p len_tag_key) * Bits 12-23: The header number (counts up everytime this function is called) * Bit 24-31: 8-Bit CRC * All other bits: Are set to zero * * If the header length is smaller than 32, bits are simply left out. For this * reason, they always start with the LSB. * * However, it is recommended to stay above 32 Bits, in order to have a working * CRC. */ virtual bool header_formatter( long packet_len, unsigned char *out, const std::vector &tags=std::vector() ); /*! * \brief Inverse function to header_formatter(). * * Reads the bit stream in \p header and writes a corresponding tag into \p tags. */ virtual bool header_parser( const unsigned char *header, std::vector &tags); static sptr make( long header_len, const std::string &len_tag_key="packet_len", const std::string &num_tag_key="packet_num", int bits_per_byte=1); protected: long d_header_len; pmt::pmt_t d_len_tag_key; pmt::pmt_t d_num_tag_key; int d_bits_per_byte; unsigned d_header_number; unsigned d_mask; boost::crc_optimal<8, 0x07, 0xFF, 0x00, false, false> d_crc_impl; }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_PACKET_HEADER_DEFAULT_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/simple_framer_sync.h0000664000175000017500000000404112207440367026255 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SIMPLE_FRAMER_SYNC_H #define INCLUDED_GR_SIMPLE_FRAMER_SYNC_H namespace gr { namespace digital { /*! * Here are a couple of maximum length sequences (m-sequences) * that were generated by the the "mseq" matlab/octave code * downloaded from: http://www.mathworks.com/matlabcentral/fileexchange/990 * *
     * 31-bit m-sequence:
     *	0110100100001010111011000111110
     *	0x690AEC76 (padded on right with a zero)
     *
     * 63-bit m-sequence:
     *	101011001101110110100100111000101111001010001100001000001111110
     *      0xACDDA4E2F28C20FC (padded on right with a zero)
     * 
*/ static const unsigned long long GRSF_SYNC = 0xacdda4e2f28c20fcULL; static const int GRSF_BITS_PER_BYTE = 8; static const int GRSF_SYNC_OVERHEAD = sizeof(GRSF_SYNC); static const int GRSF_PAYLOAD_OVERHEAD = 1; // 1 byte seqno static const int GRSF_TAIL_PAD = 1; // one byte trailing padding static const int GRSF_OVERHEAD = GRSF_SYNC_OVERHEAD + GRSF_PAYLOAD_OVERHEAD + GRSF_TAIL_PAD; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SIMPLE_FRAMER_SYNC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/correlate_access_code_bb.h0000664000175000017500000000514212207440367027335 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_BB_H #define INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_BB_H #include #include #include namespace gr { namespace digital { /*! * \brief Examine input for specified access code, one bit at a time. * \ingroup packet_operators_blk * \ingroup deprecated_blk * * \details * input: stream of bits, 1 bit per input byte (data in LSB) * output: stream of bits, 2 bits per output byte (data in LSB, flag in next higher bit) * * Each output byte contains two valid bits, the data bit, and the * flag bit. The LSB (bit 0) is the data bit, and is the original * input data, delayed 64 bits. Bit 1 is the flag bit and is 1 if * the corresponding data bit is the first data bit following the * access code. Otherwise the flag bit is 0. */ class DIGITAL_API correlate_access_code_bb : virtual public sync_block { public: // gr::digital::correlate_access_code_bb::sptr typedef boost::shared_ptr sptr; /*! * Make a correlate_access_code block. * * \param access_code is represented with 1 byte per bit, * e.g., "010101010111000100" * \param threshold maximum number of bits that may be wrong */ static sptr make(const std::string &access_code, int threshold); /*! * Set a new access code. * * \param access_code is represented with 1 byte per bit, * e.g., "010101010111000100" */ virtual bool set_access_code(const std::string &access_code) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/packet_header_ofdm.h0000664000175000017500000001102312237515112026150 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PACKET_HEADER_OFDM_H #define INCLUDED_DIGITAL_PACKET_HEADER_OFDM_H #include #include #include namespace gr { namespace digital { /*! * \brief Header utility for OFDM signals. * \ingroup ofdm_blk */ class DIGITAL_API packet_header_ofdm : public packet_header_default { public: typedef boost::shared_ptr sptr; packet_header_ofdm( const std::vector > &occupied_carriers, int n_syms, const std::string &len_tag_key, const std::string &frame_len_tag_key, const std::string &num_tag_key, int bits_per_header_sym, int bits_per_payload_sym, bool scramble_header); ~packet_header_ofdm(); /*! * \brief Header formatter. * * Does the same as packet_header_default::header_formatter(), but * optionally scrambles the bits (this is more important for OFDM to avoid * PAPR spikes). */ bool header_formatter( long packet_len, unsigned char *out, const std::vector &tags ); /*! * \brief Inverse function to header_formatter(). * * Does the same as packet_header_default::header_parser(), but * adds another tag that stores the number of OFDM symbols in the * packet. * Note that there is usually no linear connection between the number * of OFDM symbols and the packet length because a packet might * finish mid-OFDM-symbol. */ bool header_parser( const unsigned char *header, std::vector &tags); /*! * \param occupied_carriers See carrier allocator * \param n_syms The number of OFDM symbols the header should be (usually 1) * \param len_tag_key The tag key used for the packet length (number of bytes) * \param frame_len_tag_key The tag key used for the frame length (number of * OFDM symbols, this is the tag key required for the * frame equalizer etc.) * \param num_tag_key The tag key used for packet numbering. * \param bits_per_header_sym Bits per complex symbol in the header, e.g. 1 if * the header is BPSK modulated, 2 if it's QPSK * modulated etc. * \param bits_per_payload_sym Bits per complex symbol in the payload. This is * required to figure out how many OFDM symbols * are necessary to encode the given number of * bytes. * \param scramble_header Set this to true to scramble the bits. This is highly * recommended, as it reduces PAPR spikes. */ static sptr make( const std::vector > &occupied_carriers, int n_syms, const std::string &len_tag_key="packet_len", const std::string &frame_len_tag_key="frame_len", const std::string &num_tag_key="packet_num", int bits_per_header_sym=1, int bits_per_payload_sym=1, bool scramble_header=false ); protected: pmt::pmt_t d_frame_len_tag_key; //!< Tag key of the additional frame length tag const std::vector > d_occupied_carriers; //!< Which carriers/symbols carry data int d_syms_per_set; //!< Helper variable: Total number of elements in d_occupied_carriers int d_bits_per_payload_sym; std::vector d_scramble_mask; //!< Bits are xor'd with this before tx'ing }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_PACKET_HEADER_OFDM_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/map_bb.h0000664000175000017500000000346512207440367023625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MAP_BB_H #define INCLUDED_GR_MAP_BB_H #include #include namespace gr { namespace digital { /*! * \brief output[i] = map[input[i]] * \ingroup symbol_coding_blk * * \details * This block maps an incoming signal to the value in the map. * The block expects that the incoming signal has a maximum * value of len(map)-1. * * -> output[i] = map[input[i]] */ class DIGITAL_API map_bb : virtual public sync_block { public: // gr::digital::map_bb::sptr typedef boost::shared_ptr sptr; /*! * Make a map block. * * \param map a vector of integers that maps x to map[x]. */ static sptr make(const std::vector &map); virtual void set_map(const std::vector &map) = 0; virtual std::vector map() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_MAP_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/simple_framer.h0000664000175000017500000000342212207440367025223 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SIMPLE_FRAMER_H #define INCLUDED_GR_SIMPLE_FRAMER_H #include #include namespace gr { namespace digital { /*! * \brief add sync field, seq number and command field to payload * \ingroup packet_operators_blk * \ingroup deprecated_blk * * \details * Takes in enough samples to create a full output frame. The * frame is prepended with the GRSF_SYNC (defind in * simple_framer_sync.h) and an 8-bit sequence number. */ class DIGITAL_API simple_framer : virtual public block { public: // gr::digital::simple_framer::sptr typedef boost::shared_ptr sptr; /*! * Make a simple_framer block. * * \param payload_bytesize The size of the payload in bytes. */ static sptr make(int payload_bytesize); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SIMPLE_FRAMER_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/diff_decoder_bb.h0000664000175000017500000000326012207440367025436 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DIFF_DECODER_BB_H #define INCLUDED_GR_DIFF_DECODER_BB_H #include #include namespace gr { namespace digital { /*! * \brief Differential encoder: y[0] = (x[0] - x[-1]) % M * \ingroup symbol_coding_blk * * \details * Uses current and previous symbols and the alphabet modulus to * perform differential decoding. */ class DIGITAL_API diff_decoder_bb : virtual public sync_block { public: // gr::digital::diff_decoder_bb::sptr typedef boost::shared_ptr sptr; /*! * Make a differntial decoder block. * * \param modulus Modulus of code's alphabet */ static sptr make(unsigned int modulus); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DIFF_DECODER_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/crc32_bb.h0000664000175000017500000000355512207440367023764 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CRC32_BB_H #define INCLUDED_DIGITAL_CRC32_BB_H #include #include namespace gr { namespace digital { /*! * \brief Byte-stream CRC block * \ingroup packet_operators_blk * * \details * Input: stream of bytes, which form a packet. The first byte of the packet * has a tag with key "length" and the value being the number of bytes in the * packet. * * Output: The same bytes as incoming, but trailing a CRC32 of the packet. * The tag is re-set to the new length. */ class DIGITAL_API crc32_bb : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /*! * \param check Set to true if you want to check CRC, false to create CRC. * \param lengthtagname Length tag key */ static sptr make(bool check=false, const std::string& lengthtagname="packet_len"); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_CRC32_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/correlate_access_code_tag_bb.h0000664000175000017500000000470112207440367030170 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_TAG_BB_H #define INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_TAG_BB_H #include #include #include namespace gr { namespace digital { /*! * \brief Examine input for specified access code, one bit at a time. * \ingroup packet_operators_blk * * \details * input: stream of bits, 1 bit per input byte (data in LSB) * output: unaltered stream of bits (plus tags) * * This block annotates the input stream with tags. The tags have * key name [tag_name], specified in the constructor. Used for * searching an input data stream for preambles, etc. */ class DIGITAL_API correlate_access_code_tag_bb : virtual public sync_block { public: // gr::digital::correlate_access_code_tag_bb::sptr typedef boost::shared_ptr sptr; /*! * \param access_code is represented with 1 byte per bit, * e.g., "010101010111000100" * \param threshold maximum number of bits that may be wrong * \param tag_name key of the tag inserted into the tag stream */ static sptr make(const std::string &access_code, int threshold, const std::string &tag_name); /*! * \param access_code is represented with 1 byte per bit, * e.g., "010101010111000100" */ virtual bool set_access_code(const std::string &access_code) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_TAG_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/probe_density_b.h0000664000175000017500000000370712207440367025553 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PROBE_DENSITY_B_H #define INCLUDED_GR_PROBE_DENSITY_B_H #include #include namespace gr { namespace digital { /*! * \ingroup measurement_tools_blk * * This block maintains a running average of the input stream and * makes it available as an accessor function. The input stream is * type unsigned char. * * If you send this block a stream of unpacked bytes, it will tell * you what the bit density is. */ class DIGITAL_API probe_density_b : virtual public sync_block { public: // gr::digital::probe_density_b::sptr typedef boost::shared_ptr sptr; /*! * Make a density probe block. * * \param alpha Average filter constant * */ static sptr make(double alpha); /*! * \brief Returns the current density value */ virtual double density() const = 0; /*! * \brief Set the average filter constant */ virtual void set_alpha(double alpha) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_PROBE_DENSITY_B_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/additive_scrambler_bb.h0000664000175000017500000000553112244272666026675 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_ADDITIVE_SCRAMBLER_BB_H #define INCLUDED_DIGITAL_ADDITIVE_SCRAMBLER_BB_H #include #include namespace gr { namespace digital { /*! * \ingroup coding_blk * * \brief * Scramble an input stream using an LFSR. * * \details * This block scrambles up to 8 bits per byte of the input * data stream, starting at the LSB. * * The scrambler works by XORing the incoming bit stream by the * output of the LFSR. Optionally, after \p count bits have been * processed, the shift register is reset to the \p seed value. * This allows processing fixed length vectors of samples. * * Alternatively, the LFSR can be reset using a reset tag to * scramble variable length vectors. However, it cannot be reset * between bytes. * * For details on configuring the LFSR, see gr::digital::lfsr. */ class DIGITAL_API additive_scrambler_bb : virtual public sync_block { public: // gr::digital::additive_scrambler_bb::sptr typedef boost::shared_ptr sptr; /*! * \brief Create additive scrambler. * * \param mask Polynomial mask for LFSR * \param seed Initial shift register contents * \param len Shift register length * \param count Number of bytes after which shift register is reset, 0=never * \param bits_per_byte Number of bits per byte * \param reset_tag_key When a tag with this key is detected, the shift register is reset (when this is set, count is ignored!) */ static sptr make(int mask, int seed, int len, int count=0, int bits_per_byte=1, const std::string &reset_tag_key=""); virtual int mask() const = 0; virtual int seed() const = 0; virtual int len() const = 0; virtual int count() const = 0; virtual int bits_per_byte() = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_ADDITIVE_SCRAMBLER_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/pn_correlator_cc.h0000664000175000017500000000420012207440367025707 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PN_CORRELATOR_CC_H #define INCLUDED_GR_PN_CORRELATOR_CC_H #include #include namespace gr { namespace digital { /*! * \brief PN code sequential search correlator * \ingroup synchronizers_blk * * \details * Receives complex baseband signal, outputs complex correlation * against reference PN code, one sample per PN code period. The * PN sequence is generated using a GLFSR. */ class DIGITAL_API pn_correlator_cc : virtual public sync_decimator { public: // gr::digital::pn_correlator_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Make PN code sequential search correlator block. * * \param degree Degree of shift register must be in [1, 32]. If mask * is 0, the degree determines a default mask (see * digital_impl_glfsr.cc for the mapping). * \param mask Allows a user-defined bit mask for indexes of the shift * register to feed back. * \param seed Initial setting for values in shift register. */ static sptr make(int degree, int mask=0, int seed=1); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_PN_CORRELATOR_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/pfb_clock_sync_ccf.h0000664000175000017500000003302112237515112026157 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PFB_CLOCK_SYNC_CCF_H #define INCLUDED_DIGITAL_PFB_CLOCK_SYNC_CCF_H #include #include #include namespace gr { namespace digital { /*! * \brief Timing synchronizer using polyphase filterbanks * \ingroup synchronizers_blk * * \details * This block performs timing synchronization for PAM signals by * minimizing the derivative of the filtered signal, which in turn * maximizes the SNR and minimizes ISI. * * This approach works by setting up two filterbanks; one * filterbank contains the signal's pulse shaping matched filter * (such as a root raised cosine filter), where each branch of the * filterbank contains a different phase of the filter. The * second filterbank contains the derivatives of the filters in * the first filterbank. Thinking of this in the time domain, the * first filterbank contains filters that have a sinc shape to * them. We want to align the output signal to be sampled at * exactly the peak of the sinc shape. The derivative of the sinc * contains a zero at the maximum point of the sinc (sinc(0) = 1, * sinc(0)' = 0). Furthermore, the region around the zero point * is relatively linear. We make use of this fact to generate the * error signal. * * If the signal out of the derivative filters is d_i[n] for the * ith filter, and the output of the matched filter is x_i[n], we * calculate the error as: e[n] = (Re{x_i[n]} * Re{d_i[n]} + * Im{x_i[n]} * Im{d_i[n]}) / 2.0 This equation averages the error * in the real and imaginary parts. There are two reasons we * multiply by the signal itself. First, if the symbol could be * positive or negative going, but we want the error term to * always tell us to go in the same direction depending on which * side of the zero point we are on. The sign of x_i[n] adjusts * the error term to do this. Second, the magnitude of x_i[n] * scales the error term depending on the symbol's amplitude, so * larger signals give us a stronger error term because we have * more confidence in that symbol's value. Using the magnitude of * x_i[n] instead of just the sign is especially good for signals * with low SNR. * * The error signal, e[n], gives us a value proportional to how * far away from the zero point we are in the derivative * signal. We want to drive this value to zero, so we set up a * second order loop. We have two variables for this loop; d_k is * the filter number in the filterbank we are on and d_rate is the * rate which we travel through the filters in the steady * state. That is, due to the natural clock differences between * the transmitter and receiver, d_rate represents that difference * and would traverse the filter phase paths to keep the receiver * locked. Thinking of this as a second-order PLL, the d_rate is * the frequency and d_k is the phase. So we update d_rate and d_k * using the standard loop equations based on two error signals, * d_alpha and d_beta. We have these two values set based on each * other for a critically damped system, so in the block * constructor, we just ask for "gain," which is d_alpha while * d_beta is equal to (gain^2)/4. * * The block's parameters are: * * \li \p sps: The clock sync block needs to know the number of * samples per symbol, because it defaults to return a single * point representing the symbol. The sps can be any positive real * number and does not need to be an integer. * * \li \p loop_bw: The loop bandwidth is used to set the gain of * the inner control loop (see: * http://gnuradio.squarespace.com/blog/2011/8/13/control-loop-gain-values.html). * This should be set small (a value of around 2pi/100 is * suggested in that blog post as the step size for the number of * radians around the unit circle to move relative to the error). * * \li \p taps: One of the most important parameters for this * block is the taps of the filter. One of the benefits of this * algorithm is that you can put the matched filter in here as the * taps, so you get both the matched filter and sample timing * correction in one go. So create your normal matched filter. For * a typical digital modulation, this is a root raised cosine * filter. The number of taps of this filter is based on how long * you expect the channel to be; that is, how many symbols do you * want to combine to get the current symbols energy back (there's * probably a better way of stating that). It's usually 5 to 10 or * so. That gives you your filter, but now we need to think about * it as a filter with different phase profiles in each filter. So * take this number of taps and multiply it by the number of * filters. This is the number you would use to create your * prototype filter. When you use this in the PFB filerbank, it * segments these taps into the filterbanks in such a way that * each bank now represents the filter at different phases, * equally spaced at 2pi/N, where N is the number of filters. * * \li \p filter_size (default=32): The number of filters can also * be set and defaults to 32. With 32 filters, you get a good * enough resolution in the phase to produce very small, almost * unnoticeable, ISI. Going to 64 filters can reduce this more, * but after that there is very little gained for the extra * complexity. * * \li \p init_phase (default=0): The initial phase is another * settable parameter and refers to the filter path the algorithm * initially looks at (i.e., d_k starts at init_phase). This value * defaults to zero, but it might be useful to start at a * different phase offset, such as the mid-point of the filters. * * \li \p max_rate_deviation (default=1.5): The next parameter is * the max_rate_devitation, which defaults to 1.5. This is how far * we allow d_rate to swing, positive or negative, from * 0. Constraining the rate can help keep the algorithm from * walking too far away to lock during times when there is no * signal. * * \li \p osps (default=1): The osps is the number of output * samples per symbol. By default, the algorithm produces 1 sample * per symbol, sampled at the exact sample value. This osps value * was added to better work with equalizers, which do a better job * of modeling the channel if they have 2 samps/sym. * * Reference: * f. j. harris and M. Rice, "Multirate Digital Filters for Symbol * Timing Synchronization in Software Defined Radios", IEEE * Selected Areas in Communications, Vol. 19, No. 12, Dec., 2001. * * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.127.1757 */ class DIGITAL_API pfb_clock_sync_ccf : virtual public block { public: // gr::digital::pfb_clock_sync_ccf::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank timing synchronizer. * \param sps (double) The number of samples per symbol in the incoming signal * \param loop_bw (float) The bandwidth of the control loop; set's alpha and beta. * \param taps (vector) The filter taps. * \param filter_size (uint) The number of filters in the filterbank (default = 32). * \param init_phase (float) The initial phase to look at, or which filter to start * with (default = 0). * \param max_rate_deviation (float) Distance from 0 d_rate can get (default = 1.5). * \param osps (int) The number of output samples per symbol (default=1). */ static sptr make(double sps, float loop_bw, const std::vector &taps, unsigned int filter_size=32, float init_phase=0, float max_rate_deviation=1.5, int osps=1); /*! \brief update the system gains from omega and eta * * This function updates the system gains based on the loop * bandwidth and damping factor of the system. * These two factors can be set separately through their own * set functions. */ virtual void update_gains() = 0; /*! * Resets the filterbank's filter taps with the new prototype filter */ virtual void set_taps(const std::vector &taps, std::vector< std::vector > &ourtaps, std::vector &ourfilter) = 0; /*! * Returns all of the taps of the matched filter */ virtual std::vector< std::vector > taps() const = 0; /*! * Returns all of the taps of the derivative filter */ virtual std::vector< std::vector > diff_taps() const = 0; /*! * Returns the taps of the matched filter for a particular channel */ virtual std::vector channel_taps(int channel) const = 0; /*! * Returns the taps in the derivative filter for a particular channel */ virtual std::vector diff_channel_taps(int channel) const = 0; /*! * Return the taps as a formatted string for printing */ virtual std::string taps_as_string() const = 0; /*! * Return the derivative filter taps as a formatted string for printing */ virtual std::string diff_taps_as_string() const = 0; /******************************************************************* SET FUNCTIONS *******************************************************************/ /*! * \brief Set the loop bandwidth * * Set the loop filter's bandwidth to \p bw. This should be * between 2*pi/200 and 2*pi/100 (in rads/samp). It must also be * a positive number. * * When a new damping factor is set, the gains, alpha and beta, * of the loop are recalculated by a call to update_gains(). * * \param bw (float) new bandwidth */ virtual void set_loop_bandwidth(float bw) = 0; /*! * \brief Set the loop damping factor * * Set the loop filter's damping factor to \p df. The damping * factor should be sqrt(2)/2.0 for critically damped systems. * Set it to anything else only if you know what you are * doing. It must be a number between 0 and 1. * * When a new damping factor is set, the gains, alpha and beta, * of the loop are recalculated by a call to update_gains(). * * \param df (float) new damping factor */ virtual void set_damping_factor(float df) = 0; /*! * \brief Set the loop gain alpha * * Set's the loop filter's alpha gain parameter. * * This value should really only be set by adjusting the loop * bandwidth and damping factor. * * \param alpha (float) new alpha gain */ virtual void set_alpha(float alpha) = 0; /*! * \brief Set the loop gain beta * * Set's the loop filter's beta gain parameter. * * This value should really only be set by adjusting the loop * bandwidth and damping factor. * * \param beta (float) new beta gain */ virtual void set_beta(float beta) = 0; /*! * Set the maximum deviation from 0 d_rate can have */ virtual void set_max_rate_deviation(float m) = 0; /******************************************************************* GET FUNCTIONS *******************************************************************/ /*! * \brief Returns the loop bandwidth */ virtual float loop_bandwidth() const = 0; /*! * \brief Returns the loop damping factor */ virtual float damping_factor() const = 0; /*! * \brief Returns the loop gain alpha */ virtual float alpha() const = 0; /*! * \brief Returns the loop gain beta */ virtual float beta() const = 0; /*! * \brief Returns the current clock rate */ virtual float clock_rate() const = 0; /*! * \brief Returns the current error of the control loop. */ virtual float error() const = 0; /*! * \brief Returns the current rate of the control loop. */ virtual float rate() const = 0; /*! * \brief Returns the current phase arm of the control loop. */ virtual float phase() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_PFB_CLOCK_SYNC_CCF_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/crc32.h0000664000175000017500000000342212207440367023312 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CRC32_H #define INCLUDED_DIGITAL_CRC32_H #include #include #include namespace gr { namespace digital { /*! * \brief update running CRC-32 * \ingroup packet_operators_blk * * \details * Update a running CRC with the bytes buf[0..len-1] The CRC * should be initialized to all 1's, and the transmitted value is * the 1's complement of the final running CRC. The resulting CRC * should be transmitted in big endian order. */ DIGITAL_API unsigned int update_crc32(unsigned int crc, const unsigned char *buf, size_t len); DIGITAL_API unsigned int update_crc32(unsigned int crc, const std::string buf); DIGITAL_API unsigned int crc32(const unsigned char *buf, size_t len); DIGITAL_API unsigned int crc32(const std::string buf); } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_CRC32_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/constellation_decoder_cb.h0000664000175000017500000000365312207440367027413 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_DECODER_CB_H #define INCLUDED_DIGITAL_CONSTELLATION_DECODER_CB_H #include #include #include namespace gr { namespace digital { /*! * \brief Constellation Decoder * \ingroup symbol_coding_blk * * \details * Decode a constellation's points from a complex space to * (unpacked) bits based on the map of the \p consetllation * object. */ class DIGITAL_API constellation_decoder_cb : virtual public block { public: // gr::digital::constellation_decoder_cb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make constellation decoder block. * * \param constellation A constellation derived from class * 'constellation'. Use base() method to get a shared pointer to * this base class type. */ static sptr make(constellation_sptr constellation); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_DECODER_CB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/glfsr.h0000664000175000017500000000333412207440367023515 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_GLFSR_H #define INCLUDED_DIGITAL_GLFSR_H #include namespace gr { namespace digital { /*! * \brief Galois Linear Feedback Shift Register using specified polynomial mask * \ingroup waveform_generators_blk * * \details * Generates a maximal length pseudo-random sequence of length 2^degree-1 */ class DIGITAL_API glfsr { private: int d_shift_register; int d_mask; public: glfsr(int mask, int seed) { d_shift_register = seed; d_mask = mask; } ~glfsr(); static int glfsr_mask(int degree); unsigned char next_bit() { unsigned char bit = d_shift_register & 1; d_shift_register >>= 1; if(bit) d_shift_register ^= d_mask; return bit; } int mask() const { return d_mask; } }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_GLFSR_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/packet_sink.h0000664000175000017500000000534412207440367024676 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PACKET_SINK_H #define INCLUDED_GR_PACKET_SINK_H #include #include #include namespace gr { namespace digital { /*! * \brief process received bits looking for packet sync, header, * and process bits into packet * \ingroup packet_operators_blk * * \details * input: stream of symbols to be sliced. * * output: none. Pushes assembled packet into target queue * * The packet sink takes in a stream of binary symbols that are * sliced around 0. The bits are then checked for the \p * sync_vector to determine find and decode the packet. It then * expects a fixed length header of 2 16-bit shorts containing the * payload length, followed by the payload. If the 2 16-bit shorts * are not identical, this packet is ignored. Better algs are * welcome. * * This block is not very useful anymore as it only works with * 2-level modulations such as BPSK or GMSK. The block can * generally be replaced with a correlate access code and frame * sink blocks. */ class DIGITAL_API packet_sink : virtual public sync_block { public: // gr::digital::packet_sink::sptr typedef boost::shared_ptr sptr; /*! * Make a packet_sink block. * * \param sync_vector The synchronization vector as a vector of 1's and 0's. * \param target_queue The message queue that packets are sent to. * \param threshold Number of bits that can be incorrect in the \p sync_vector. */ static sptr make(const std::vector& sync_vector, msg_queue::sptr target_queue, int threshold=-1); //! return true if we detect carrier virtual bool carrier_sensed() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_PACKET_SINK_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_sync_sc_cfb.h0000664000175000017500000000607012207440367025660 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_SYNC_SC_CFB_H #define INCLUDED_DIGITAL_OFDM_SYNC_SC_CFB_H #include #include namespace gr { namespace digital { /*! * \brief Schmidl & Cox synchronisation for OFDM * \ingroup ofdm_blk * \ingroup synchronizers_blk * * \details * Input: complex samples. * Output 0: Fine frequency offset, scaled by the OFDM symbol duration. * This is \f$\hat{\varphi}\f$ in [1]. The normalized frequency * offset is then 2.0*output0/fft_len. * Output 1: Beginning of the first OFDM symbol after the first (doubled) OFDM * symbol. The beginning is marked with a 1 (it's 0 everywhere else). * * The evaluation of the coarse frequency offset is *not* done in this block. * Also, the initial equalizer taps are not calculated here. * * Note that we use a different normalization factor in the timing metric than * the authors do in their original work[1]. If the timing metric (8) is * \f[ * M(d) = \frac{|P(d)|^2}{(R(d))^2}, * \f] * we calculate the normalization as * \f[ * R(d) = \frac{1}{2} \sum_{k=0}^{N-1} |r_{k+d}|^2, * \f] * i.e., we estimate the energy from *both* half-symbols. This avoids spurious detects * at the end of a burst, when the energy level suddenly drops. * * [1] Schmidl, T.M. and Cox, D.C., "Robust frequency and timing synchronization for OFDM", * Communications, IEEE Transactions on, 1997. */ class DIGITAL_API ofdm_sync_sc_cfb : virtual public hier_block2 { public: typedef boost::shared_ptr sptr; /*! \param fft_len FFT length * \param cp_len Length of the guard interval (cyclic prefix) in samples * \param use_even_carriers If true, the carriers in the sync preamble are occupied such * that the even carriers are used (0, 2, 4, ...). If you use all * carriers, that would include the DC carrier, so be careful. */ static sptr make(int fft_len, int cp_len, bool use_even_carriers=false); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_SYNC_SC_CFB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_sampler.h0000664000175000017500000000346512207440367025055 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_SAMPLER_H #define INCLUDED_DIGITAL_OFDM_SAMPLER_H #include #include namespace gr { namespace digital { /*! * \brief does the rest of the OFDM stuff * \ingroup ofdm_blk */ class DIGITAL_API ofdm_sampler : virtual public block { public: // gr::digital::ofdm_sampler::sptr typedef boost::shared_ptr sptr; /*! * Make an OFDM sampler block. * * \param fft_length The size of the FFT vector (occupied_carriers + unused carriers) * \param symbol_length Length of the full symbol (fft_length + CP length) * \param timeout timeout in samples when we stop looking for a symbol after initial ack. */ static sptr make(unsigned int fft_length, unsigned int symbol_length, unsigned int timeout=1000); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_SAMPLER_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_insert_preamble.h0000664000175000017500000000544112207440367026561 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_DIGITAL_OFDM_INSERT_PREAMBLE_H #define INCLUDED_DIGITAL_OFDM_INSERT_PREAMBLE_H #include #include #include namespace gr { namespace digital { /*! * \brief insert "pre-modulated" preamble symbols before each payload. * \ingroup ofdm_blk * \ingroup synchronizers_blk * * \details *
     * input 1: stream of vectors of gr_complex [fft_length]
     *          These are the modulated symbols of the payload.
     *
     * input 2: stream of char.  The LSB indicates whether the corresponding
     *          symbol on input 1 is the first symbol of the payload or not.
     *          It's a 1 if the corresponding symbol is the first symbol,
     *          otherwise 0.
     *
     * N.B., this implies that there must be at least 1 symbol in the payload.
     *
     * output 1: stream of vectors of gr_complex [fft_length]
     *           These include the preamble symbols and the payload symbols.
     *
     * output 2: stream of char.  The LSB indicates whether the corresponding
     *           symbol on input 1 is the first symbol of a packet (i.e., the
     *           first symbol of the preamble.)   It's a 1 if the corresponding
     *           symbol is the first symbol, otherwise 0.
     * 
*/ class DIGITAL_API ofdm_insert_preamble : virtual public block { public: // gr::digital::ofdm_insert_preamble::sptr typedef boost::shared_ptr sptr; /*! * Make an OFDM preamble inserter block. * * \param fft_length length of each symbol in samples. * \param preamble vector of symbols that represent the pre-modulated preamble. */ static sptr make(int fft_length, const std::vector > &preamble); virtual void enter_preamble() = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_INSERT_PREAMBLE_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/glfsr_source_f.h0000664000175000017500000000413012207440367025375 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_GLFSR_SOURCE_F_H #define INCLUDED_GR_GLFSR_SOURCE_F_H #include #include namespace gr { namespace digital { /*! * \brief Galois LFSR pseudo-random source generating float outputs -1.0 - 1.0. * \ingroup waveform_generators_blk */ class DIGITAL_API glfsr_source_f : virtual public sync_block { public: // gr::digital::glfsr_source_f::sptr typedef boost::shared_ptr sptr; /*! * Make a Galois LFSR pseudo-random source block. * * \param degree Degree of shift register must be in [1, 32]. If mask * is 0, the degree determines a default mask (see * digital_impl_glfsr.cc for the mapping). * \param repeat Set to repeat sequence. * \param mask Allows a user-defined bit mask for indexes of the shift * register to feed back. * \param seed Initial setting for values in shift register. */ static sptr make(int degree, bool repeat=true, int mask=0, int seed=1); virtual unsigned int period() const = 0; virtual int mask() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_GLFSR_SOURCE_F_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/lfsr.h0000664000175000017500000001244112207440367023345 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_LFSR_H #define INCLUDED_DIGITAL_LFSR_H #include #include #include namespace gr { namespace digital { /*! * \brief Fibonacci Linear Feedback Shift Register using specified * polynomial mask * \ingroup misc * * \details * Generates a maximal length pseudo-random sequence of length * 2^degree-1 * * Constructor: digital::lfsr(int mask, int seed, int reg_len); * * \param mask - polynomial coefficients representing the * locations of feedback taps from a shift register * which are xor'ed together to form the new high * order bit. * * Some common masks might be: * x^4 + x^3 + x^0 = 0x19 * x^5 + x^3 + x^0 = 0x29 * x^6 + x^5 + x^0 = 0x61 * * \param seed - the initialization vector placed into the * register durring initialization. Low order bit * corresponds to x^0 coefficient -- the first to be * shifted as output. * * \param reg_len - specifies the length of the feedback shift * register to be used. Durring each iteration, the * register is rightshifted one and the new bit is * placed in bit reg_len. reg_len should generally be * at least order(mask) + 1 * * * see http://en.wikipedia.org/wiki/Linear_feedback_shift_register * for more explanation. * * next_bit() - Standard LFSR operation * * Perform one cycle of the LFSR. The output bit is taken from * the shift register LSB. The shift register MSB is assigned from * the modulo 2 sum of the masked shift register. * * next_bit_scramble(unsigned char input) - Scramble an input stream * * Perform one cycle of the LFSR. The output bit is taken from * the shift register LSB. The shift register MSB is assigned from * the modulo 2 sum of the masked shift register and the input LSB. * * next_bit_descramble(unsigned char input) - Descramble an input stream * * Perform one cycle of the LFSR. The output bit is taken from * the modulo 2 sum of the masked shift register and the input LSB. * The shift register MSB is assigned from the LSB of the input. * * See http://en.wikipedia.org/wiki/Scrambler for operation of these * last two functions (see multiplicative scrambler.) */ class lfsr { private: uint32_t d_shift_register; uint32_t d_mask; uint32_t d_seed; uint32_t d_shift_register_length; // less than 32 static uint32_t popCount(uint32_t x) { uint32_t r = x - ((x >> 1) & 033333333333) - ((x >> 2) & 011111111111); return ((r + (r >> 3)) & 030707070707) % 63; } public: lfsr(uint32_t mask, uint32_t seed, uint32_t reg_len) : d_shift_register(seed), d_mask(mask), d_seed(seed), d_shift_register_length(reg_len) { if(reg_len > 31) throw std::invalid_argument("reg_len must be <= 31"); } unsigned char next_bit() { unsigned char output = d_shift_register & 1; unsigned char newbit = popCount( d_shift_register & d_mask )%2; d_shift_register = ((d_shift_register>>1) | (newbit<>1) | (newbit<>1) | (newbit< #include #include namespace gr { namespace digital { /*! * \brief Generates a header for a tagged, streamed packet. * \ingroup packet_operators_blk * * \details * Input: A tagged stream. This is consumed entirely, it is not appended * to the output stream. * Output: An tagged stream containing the header. The details on the header * are set in a header formatter object (of type packet_header_default * or a subclass thereof). If only a number of bits is specified, a * default header is generated (see packet_header_default). */ class DIGITAL_API packet_headergenerator_bb : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /* \param header_formatter A header formatter object. * \param len_tag_key Length tag key. Note that for header generation, * it is irrelevant which tag names are set in the * formatter object, only this value is relevant! */ static sptr make( const packet_header_default::sptr &header_formatter, const std::string &len_tag_key="packet_len" ); /* \param header_len If this value is given, a packet_header_default * object is used to generate the header. This is * the number of bits per header. * \param len_tag_key Length tag key. */ static sptr make( long header_len, const std::string &len_tag_key = "packet_len"); }; } // namespace digital } // namespace gr #endif /* INCLUDED_PACKET_HEADERGENERATOR_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/binary_slicer_fb.h0000664000175000017500000000313312244272666025677 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_BINARY_SLICER_FB_H #define INCLUDED_DIGITAL_BINARY_SLICER_FB_H #include #include namespace gr { namespace digital { /*! * \brief Slice float binary symbol producing 1 bit output * \ingroup symbol_coding_blk * * \details * \li input[0][n] < 0 --> 0 * \li input[0][n] >= 0 --> 1 */ class DIGITAL_API binary_slicer_fb : virtual public sync_block { public: // gr::digital::binary_slicer_fb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make binary symbol slicer block. */ static sptr make(); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_BINARY_SLICER_FB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_cyclic_prefixer.h0000664000175000017500000000501412207440367026554 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_CYCLIC_PREFIXER_H #define INCLUDED_DIGITAL_OFDM_CYCLIC_PREFIXER_H #include #include namespace gr { namespace digital { /*! * \brief Adds a cyclic prefix and performs pulse shaping on OFDM symbols. * \ingroup ofdm_blk * * \details * Input: OFDM symbols (in the time domain, i.e. after the IFFT). Optionally, * entire frames can be processed. In this case, \p len_tag_key must be * specified which holds the key of the tag that denotes how * many OFDM symbols are in a frame. * Output: A stream of (scalar) complex symbols, which include the cyclic prefix * and the pulse shaping. * Note: If complete frames are processed, and \p rolloff_len is greater * than zero, the final OFDM symbol is followed by the delay line of * the pulse shaping. * * The pulse shape is a raised cosine in the time domain. */ class DIGITAL_API ofdm_cyclic_prefixer : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /*! * \param input_size FFT length (i.e. length of the OFDM symbols) * \param output_size FFT length + cyclic prefix length (in samples) * \param rolloff_len Length of the rolloff flank in samples * \param len_tag_key For framed processing the key of the length tag */ static sptr make( size_t input_size, size_t output_size, int rolloff_len=0, const std::string &len_tag_key="" ); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_CYCLIC_PREFIXER_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/mpsk_snr_est_cc.h0000664000175000017500000000655312207440367025562 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_MPSK_SNR_EST_CC_H #define INCLUDED_DIGITAL_MPSK_SNR_EST_CC_H #include #include #include namespace gr { namespace digital { /*! * \brief A block for computing SNR of a signal. * \ingroup measurement_tools_blk * * \details * This block can be used to monitor and retrieve estimations of * the signal SNR. It is designed to work in a flowgraph and * passes all incoming data along to its output. * * The block is designed for use with M-PSK signals * especially. The type of estimator is specified as the \p type * parameter in the constructor. The estimators tend to trade off * performance for accuracy, although experimentation should be * done to figure out the right approach for a given * implementation. Further, the current set of estimators are * designed and proven theoretically under AWGN conditions; some * amount of error should be assumed and/or estimated for real * channel conditions. */ class DIGITAL_API mpsk_snr_est_cc : virtual public sync_block { public: // gr::digital::mpsk_snr_est_cc::sptr typedef boost::shared_ptr sptr; /*! Factory function returning shared pointer of this class * * \param type: the type of estimator to use gr::digital::snr_est_type_t * "snr_est_type_t" for details about the available types * \param tag_nsamples: after this many samples, a tag containing * the SNR (key='snr') will be sent * \param alpha: the update rate of internal running average * calculations */ static sptr make(snr_est_type_t type, int tag_nsamples=10000, double alpha=0.001); //! Return the estimated signal-to-noise ratio in decibels virtual double snr() = 0; //! Return the type of estimator in use virtual snr_est_type_t type() const = 0; //! Return how many samples between SNR tags virtual int tag_nsample() const = 0; //! Get the running-average coefficient virtual double alpha() const = 0; //! Set type of estimator to use virtual void set_type(snr_est_type_t t) = 0; //! Set the number of samples between SNR tags virtual void set_tag_nsample(int n) = 0; //! Set the running-average coefficient virtual void set_alpha(double alpha) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_MPSK_SNR_EST_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_mapper_bcv.h0000664000175000017500000000433712207440367025527 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_MAPPER_BCV_H #define INCLUDED_DIGITAL_OFDM_MAPPER_BCV_H #include #include #include namespace gr { namespace digital { /*! * \brief take a stream of bytes in and map to a vector of complex * constellation points suitable for IFFT input to be used in an * ofdm modulator. * \ingroup ofdm_blk * * \details * Abstract class must be subclassed with specific mapping. */ class DIGITAL_API ofdm_mapper_bcv : virtual public sync_block { public: // gr::digital::ofdm_mapper_bcv::sptr typedef boost::shared_ptr sptr; /*! * Make an OFDM mapper block. * * \param constellation vector of OFDM carrier symbols in complex space * \param msgq_limit limit on number of messages the queue can store * \param occupied_carriers The number of subcarriers with data in the received symbol * \param fft_length The size of the FFT vector (occupied_carriers + unused carriers) */ static sptr make(const std::vector &constellation, unsigned msgq_limit, unsigned occupied_carriers, unsigned int fft_length); virtual msg_queue::sptr msgq() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_MAPPER_BCV_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/cma_equalizer_cc.h0000664000175000017500000000504312244272666025673 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CMA_EQUALIZER_CC_H #define INCLUDED_DIGITAL_CMA_EQUALIZER_CC_H #include #include namespace gr { namespace digital { /*! * \brief Implements constant modulus adaptive filter on complex stream. * \ingroup equalizers_blk * * \details * The error value and tap update equations (for p=2) can be found in: * * D. Godard, "Self-Recovering Equalization and Carrier Tracking * in Two-Dimensional Data Communication Systems," IEEE * Transactions on Communications, Vol. 28, No. 11, pp. 1867 - * 1875, 1980. */ class DIGITAL_API cma_equalizer_cc: virtual public sync_decimator { protected: virtual gr_complex error(const gr_complex &out) = 0; virtual void update_tap(gr_complex &tap, const gr_complex &in) = 0; public: // gr::digital::cma_equalizer_cc::sptr typedef boost::shared_ptr sptr; /*! * Make a CMA Equalizer block * * \param num_taps Numer of taps in the equalizer (channel size) * \param modulus Modulus of the modulated signals * \param mu Gain of the update loop * \param sps Number of samples per symbol of the input signal */ static sptr make(int num_taps, float modulus, float mu, int sps); virtual void set_taps(const std::vector &taps) = 0; virtual std::vector taps() const = 0; virtual float gain() const = 0; virtual void set_gain(float mu) = 0; virtual float modulus() const = 0; virtual void set_modulus(float mod) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CMA_EQUALIZER_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/scrambler_bb.h0000664000175000017500000000344312207440367025016 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SCRAMBLER_BB_H #define INCLUDED_GR_SCRAMBLER_BB_H #include #include namespace gr { namespace digital { /*! * \brief Scramble an input stream using an LFSR. * \ingroup coding_blk * * \details * This block works on the LSB only of the input data stream, * i.e., on an "unpacked binary" stream, and produces the same * format on its output. */ class DIGITAL_API scrambler_bb : virtual public sync_block { public: // gr::digital::scrambler_bb::sptr typedef boost::shared_ptr sptr; /*! * Make a scramber block. * * \param mask Polynomial mask for LFSR * \param seed Initial shift register contents * \param len Shift register length */ static sptr make(int mask, int seed, int len); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SCRAMBLER_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/cpmmod_bc.h0000664000175000017500000001021612207440367024320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CPMMOD_BC_H #define INCLUDED_DIGITAL_CPMMOD_BC_H #include #include #include namespace gr { namespace digital { /*! * \brief Generic CPM modulator * \ingroup modulators_blk * * \details * Examples: * - Setting h = 0.5, L = 1, type = LREC yields MSK. * - Setting h = 0.5, type = GAUSSIAN and beta = 0.3 yields GMSK * as used in GSM. * * The input of this block are symbols from an M-ary alphabet * +/-1, +/-3, ..., +/-(M-1). Usually, M = 2 and therefore, the * valid inputs are +/-1. * The modulator will silently accept any other inputs, though. * The output is the phase-modulated signal. */ class DIGITAL_API cpmmod_bc : virtual public hier_block2 { public: // gr::digital::cpmmod_bc::sptr typedef boost::shared_ptr sptr; /*! * Make CPM modulator block. * * \param type The modulation type. Can be one of LREC, LRC, LSRC, TFM * or GAUSSIAN. See gr_cpm::phase_response() for a * detailed description. * \param h The modulation index. \f$ h \cdot \pi\f$ is the maximum * phase change that can occur between two symbols, i.e., if * you only send ones, the phase will increase by \f$ h \cdot * \pi\f$ every \p samples_per_sym samples. Set this to 0.5 * for Minimum Shift Keying variants. * \param samples_per_sym Samples per symbol. * \param L The length of the phase duration in symbols. For L=1, this * yields full- response CPM symbols, for L > 1, * partial-response. * \param beta For LSRC, this is the rolloff factor. For Gaussian * pulses, this is the 3 dB time-bandwidth product. */ static sptr make(analog::cpm::cpm_type type, float h, int samples_per_sym, int L, double beta=0.3); /*! * Make GMSK modulator block. * * The type is GAUSSIAN and the modulation index for GMSK is * 0.5. This are populated automatically by this factory * function. * * \param samples_per_sym Samples per symbol. * \param L The length of the phase duration in symbols. For L=1, this * yields full- response CPM symbols, for L > 1, * partial-response. * \param beta For LSRC, this is the rolloff factor. For Gaussian * pulses, this is the 3 dB time-bandwidth product. */ static sptr make_gmskmod_bc(int samples_per_sym=2, int L=4, double beta=0.3); //! Return the phase response FIR taps virtual std::vector taps() const = 0; //! Return the type of CPM modulator virtual int type() const = 0; //! Return the modulation index of the modulator. virtual float index() const = 0; //! Return the number of samples per symbol virtual int samples_per_sym() const = 0; //! Return the length of the phase duration (in symbols) virtual int length() const = 0; //! Return the value of beta for the modulator virtual double beta() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CPMMOD_BC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_equalizer_static.h0000664000175000017500000001040612207440367026753 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_EQUALIZER_STATIC_H #define INCLUDED_DIGITAL_OFDM_EQUALIZER_STATIC_H #include #include #include namespace gr { namespace digital { /* \brief Very simple static equalizer for OFDM. * \ingroup ofdm_blk * \ingroup equalizers_blk * * \details * This is an extremely simple equalizer. It will only work for * high-SNR, very, very slowly changing channels. * * It simply divides the signal with the currently known channel * state. Whenever a pilot symbol comes around, it updates the * channel state on that particular carrier by dividing the * received symbol with the known pilot symbol. */ class DIGITAL_API ofdm_equalizer_static : public ofdm_equalizer_1d_pilots { public: typedef boost::shared_ptr sptr; ofdm_equalizer_static( int fft_len, const std::vector > &occupied_carriers = std::vector >(), const std::vector > &pilot_carriers = std::vector >(), const std::vector > &pilot_symbols = std::vector >(), int symbols_skipped = 0, bool input_is_shifted = true ); ~ofdm_equalizer_static(); /*! \brief Divide the input signal with the current channel state. * * Does the following (and nothing else): * - Divide every OFDM symbol with the current channel state * - If a pilot symbol is found, re-set the channel state by dividing the received * symbol with the known pilot symbol */ void equalize(gr_complex *frame, int n_sym, const std::vector &initial_taps = std::vector(), const std::vector &tags = std::vector()); /* * \param fft_len FFT length * \param occupied_carriers List of occupied carriers, see ofdm_carrier_allocator * for a description. * \param pilot_carriers Position of pilot symbols, see ofdm_carrier_allocator * for a description. * \param pilot_symbols Value of pilot symbols, see ofdm_carrier_allocator * for a description. * \param symbols_skipped Starting position within occupied_carriers and pilot_carriers. * If the first symbol of the frame was removed (e.g. to decode the * header), set this make sure the pilot symbols are correctly * identified. * \param input_is_shifted Set this to false if the input signal is not shifted, i.e. * the first input items is on the DC carrier. * Note that a lot of the OFDM receiver blocks operate on shifted * signals! */ static sptr make( int fft_len, const std::vector > &occupied_carriers = std::vector >(), const std::vector > &pilot_carriers = std::vector >(), const std::vector > &pilot_symbols = std::vector >(), int symbols_skipped = 0, bool input_is_shifted = true ); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_EQUALIZER_STATIC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_serializer_vcc.h0000664000175000017500000001045212207440367026410 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_SERIALIZER_VCC_H #define INCLUDED_DIGITAL_OFDM_SERIALIZER_VCC_H #include #include #include namespace gr { namespace digital { /*! * \brief Serializes complex modulations symbols from OFDM sub-carriers * \ingroup ofdm_blk * * \details * This is the inverse block to the carrier_allocator_cvc. It outputs the * complex data symbols as a tagged stream, discarding the pilot symbols. * * If given, two different tags are parsed: The first key (\p len_tag_key) * specifies the number of OFDM symbols in the frame at the input. The * second key (\p packet_len_tag_key) specifies the number of complex symbols * that are coded into this frame. If given, this second key is then used * at the output, otherwise, \p len_tag_key is used. * If both are given, the packet length specifies the maximum number of * output items, and the frame length specifies the exact number of * consumed input items. * * It is possible to correct a carrier offset in this function by passing * another tag with said offset. * * Input: Complex vectors of length \p fft_len * Output: Complex scalars, in the same order as specified in occupied_carriers. */ class DIGITAL_API ofdm_serializer_vcc : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /*! * \param fft_len FFT length * \param occupied_carriers See ofdm_carrier_allocator_cvc. * \param len_tag_key The key of the tag identifying the length of the input frame in OFDM symbols. * \param packet_len_tag_key The key of the tag identifying the number of complex symbols in this packet. * \param symbols_skipped If the first symbol is not allocated as in \p occupied_carriers[0], set this * \param carr_offset_key When this block should correct a carrier offset, specify the tag key of the offset here (not necessary if following an ofdm_frame_equalizer_vcvc) * \param input_is_shifted If the input has the DC carrier on index 0 (i.e. it is not FFT shifted), set this to false */ static sptr make( int fft_len, const std::vector > &occupied_carriers, const std::string &len_tag_key="frame_len", const std::string &packet_len_tag_key="", int symbols_skipped=0, const std::string &carr_offset_key="", bool input_is_shifted=true ); /*! * \param allocator The carrier allocator block of which this shall be the inverse * \param packet_len_tag_key The key of the tag identifying the number of complex symbols in this packet. * \param symbols_skipped If the first symbol is not allocated as in \p occupied_carriers[0], set this * \param carr_offset_key When this block should correct a carrier offset, specify the tag key of the offset here (not necessary if following an ofdm_frame_equalizer_vcvc) * \param input_is_shifted If the input has the DC carrier on index 0 (i.e. it is not FFT shifted), set this to false */ static sptr make( const gr::digital::ofdm_carrier_allocator_cvc::sptr &allocator, const std::string &packet_len_tag_key="", int symbols_skipped=0, const std::string &carr_offset_key="", bool input_is_shifted=true ); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_SERIALIZER_VCC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/glfsr_source_b.h0000664000175000017500000000406412207440367025377 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_GLFSR_SOURCE_B_H #define INCLUDED_GR_GLFSR_SOURCE_B_H #include #include namespace gr { namespace digital { /*! * \brief Galois LFSR pseudo-random source * \ingroup waveform_generators_blk */ class DIGITAL_API glfsr_source_b : virtual public sync_block { public: // gr::digital::glfsr_source_b::sptr typedef boost::shared_ptr sptr; /*! * Make a Galois LFSR pseudo-random source block. * * \param degree Degree of shift register must be in [1, 32]. If mask * is 0, the degree determines a default mask (see * digital_impl_glfsr.cc for the mapping). * \param repeat Set to repeat sequence. * \param mask Allows a user-defined bit mask for indexes of the shift * register to feed back. * \param seed Initial setting for values in shift register. */ static sptr make(int degree, bool repeat=true, int mask=0, int seed=1); virtual unsigned int period() const = 0; virtual int mask() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_GLFSR_SOURCE_B_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_frame_sink.h0000664000175000017500000000477212207440367025532 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_FRAME_SINK_H #define INCLUDED_DIGITAL_OFDM_FRAME_SINK_H #include #include #include namespace gr { namespace digital { /*! * \brief Takes an OFDM symbol in, demaps it into bits of 0's and * 1's, packs them into packets, and sends to to a message queue * sink. * \ingroup ofdm_blk * * \details * NOTE: The mod input parameter simply chooses a pre-defined * demapper/slicer. Eventually, we want to be able to pass in a * reference to an object to do the demapping and slicing for a * given modulation type. */ class DIGITAL_API ofdm_frame_sink : virtual public sync_block { public: // gr::digital::ofdm_frame_sink::sptr typedef boost::shared_ptr sptr; /*! * Make an OFDM frame sink block. * * \param sym_position vector of OFDM carrier symbols in complex space * \param sym_value_out vector of bit mapped from the complex symbol space * \param target_queue message queue for the packets to go into * \param occupied_tones The number of subcarriers with data in the received symbol * \param phase_gain gain of the phase tracking loop * \param freq_gain gain of the frequency tracking loop */ static sptr make(const std::vector &sym_position, const std::vector &sym_value_out, msg_queue::sptr target_queue, int occupied_tones, float phase_gain=0.25, float freq_gain=0.25*0.25/4); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_OFDM_FRAME_SINK_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/fll_band_edge_cc.h0000664000175000017500000001547512207440367025603 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_FLL_BAND_EDGE_CC_H #define INCLUDED_DIGITAL_FLL_BAND_EDGE_CC_H #include #include #include namespace gr { namespace digital { /*! * \brief Frequency Lock Loop using band-edge filters * \ingroup synchronizers_blk * * \details * The frequency lock loop derives a band-edge filter that covers * the upper and lower bandwidths of a digitally-modulated * signal. The bandwidth range is determined by the excess * bandwidth (e.g., rolloff factor) of the modulated signal. The * placement in frequency of the band-edges is determined by the * oversampling ratio (number of samples per symbol) and the * excess bandwidth. The size of the filters should be fairly * large so as to average over a number of symbols. * * The FLL works by filtering the upper and lower band edges into * x_u(t) and x_l(t), respectively. These are combined to form * cc(t) = x_u(t) + x_l(t) and ss(t) = x_u(t) - x_l(t). Combining * these to form the signal e(t) = Re{cc(t) \\times ss(t)^*} * (where ^* is the complex conjugate) provides an error signal at * the DC term that is directly proportional to the carrier * frequency. We then make a second-order loop using the error * signal that is the running average of e(t). * * In practice, the above equation can be simplified by just * comparing the absolute value squared of the output of both * filters: abs(x_l(t))^2 - abs(x_u(t))^2 = norm(x_l(t)) - * norm(x_u(t)). * * In theory, the band-edge filter is the derivative of the * matched filter in frequency, (H_be(f) = frac{H(f)}{df}). In * practice, this comes down to a quarter sine wave at the point * of the matched filter's rolloff (if it's a raised-cosine, the * derivative of a cosine is a sine). Extend this sine by another * quarter wave to make a half wave around the band-edges is * equivalent in time to the sum of two sinc functions. The * baseband filter fot the band edges is therefore derived from * this sum of sincs. The band edge filters are then just the * baseband signal modulated to the correct place in * frequency. All of these calculations are done in the * 'design_filter' function. * * Note: We use FIR filters here because the filters have to have * a flat phase response over the entire frequency range to allow * their comparisons to be valid. * * It is very important that the band edge filters be the * derivatives of the pulse shaping filter, and that they be * linear phase. Otherwise, the variance of the error will be very * large. */ class DIGITAL_API fll_band_edge_cc : virtual public sync_block, virtual public blocks::control_loop { public: // gr::digital::fll_band_edge_cc::sptr typedef boost::shared_ptr sptr; /*! * Make an FLL block. * * \param samps_per_sym (float) number of samples per symbol * \param rolloff (float) Rolloff (excess bandwidth) of signal filter * \param filter_size (int) number of filter taps to generate * \param bandwidth (float) Loop bandwidth */ static sptr make(float samps_per_sym, float rolloff, int filter_size, float bandwidth); /******************************************************************* SET FUNCTIONS *******************************************************************/ /*! * \brief Set the number of samples per symbol * * Set's the number of samples per symbol the system should * use. This value is uesd to calculate the filter taps and will * force a recalculation. * * \param sps (float) new samples per symbol */ virtual void set_samples_per_symbol(float sps) = 0; /*! * \brief Set the rolloff factor of the shaping filter * * This sets the rolloff factor that is used in the pulse * shaping filter and is used to calculate the filter * taps. Changing this will force a recalculation of the filter * taps. * * This should be the same value that is used in the * transmitter's pulse shaping filter. It must be between 0 and * 1 and is usually between 0.2 and 0.5 (where 0.22 and 0.35 are * commonly used values). * * \param rolloff (float) new shaping filter rolloff factor [0,1] */ virtual void set_rolloff(float rolloff) = 0; /*! * \brief Set the number of taps in the filter * * This sets the number of taps in the band-edge * filters. Setting this will force a recalculation of the * filter taps. * * This should be about the same number of taps used in the * transmitter's shaping filter and also not very large. A large * number of taps will result in a large delay between input and * frequency estimation, and so will not be as accurate. Between * 30 and 70 taps is usual. * * \param filter_size (float) number of taps in the filters */ virtual void set_filter_size(int filter_size) = 0; /******************************************************************* GET FUNCTIONS *******************************************************************/ /*! * \brief Returns the number of sampler per symbol used for the filter */ virtual float samples_per_symbol() const = 0; /*! * \brief Returns the rolloff factor used for the filter */ virtual float rolloff() const = 0; /*! * \brief Returns the number of taps of the filter */ virtual int filter_size() const = 0; /*! * Print the taps to screen. */ virtual void print_taps() = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_FLL_BAND_EDGE_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/costas_loop_cc.h0000664000175000017500000000542612244272666025404 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_COSTAS_LOOP_CC_H #define INCLUDED_DIGITAL_COSTAS_LOOP_CC_H #include #include #include namespace gr { namespace digital { /*! * \brief A Costas loop carrier recovery module. * \ingroup synchronizers_blk * * \details * The Costas loop locks to the center frequency of a signal and * downconverts it to baseband. * * \li When order=2: used for BPSK where the real part of the * output signal is the baseband BPSK signal and the imaginary * part is the error signal. * * \li When order=4: can be used for QPSK where both I and Q (real * and imaginary) are outputted. * * \li When order=8: used for 8PSK. * * More details can be found online: * * J. Feigin, "Practical Costas loop design: Designing a simple * and inexpensive BPSK Costas loop carrier recovery circuit," RF * signal processing, pp. 20-36, 2002. * * http://rfdesign.com/images/archive/0102Feigin20.pdf * * The Costas loop can have two output streams: * \li stream 1 (required) is the baseband I and Q; * \li stream 2 (optional) is the normalized frequency of the loop */ class DIGITAL_API costas_loop_cc : virtual public sync_block, virtual public blocks::control_loop { public: // gr::digital::costas_loop_cc::sptr typedef boost::shared_ptr sptr; /*! * Make a Costas loop carrier recovery block. * * \param loop_bw internal 2nd order loop bandwidth (~ 2pi/100) * \param order the loop order, either 2, 4, or 8 */ static sptr make(float loop_bw, int order); /*! * Returns the current value of the loop error. */ virtual float error() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_COSTAS_LOOP_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/clock_recovery_mm_ff.h0000664000175000017500000000523212207440367026554 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_FF_H #define INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_FF_H #include #include namespace gr { namespace digital { /*! * \brief Mueller and Müller (M&M) based clock recovery block with float input, float output. * \ingroup synchronizers_blk * * \details * This implements the Mueller and Müller (M&M) discrete-time * error-tracking synchronizer. * * See "Digital Communication Receivers: Synchronization, Channel * Estimation and Signal Processing" by Heinrich Meyr, Marc * Moeneclaey, & Stefan Fechtel. ISBN 0-471-50275-8. */ class DIGITAL_API clock_recovery_mm_ff : virtual public block { public: // gr::digital::clock_recovery_mm_ff::sptr typedef boost::shared_ptr sptr; /*! * Make a M&M clock recovery block. * * \param omega Initial estimate of samples per symbol * \param gain_omega Gain setting for omega update loop * \param mu Initial estimate of phase of sample * \param gain_mu Gain setting for mu update loop * \param omega_relative_limit limit on omega */ static sptr make(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limit); virtual float mu() const = 0; virtual float omega() const = 0; virtual float gain_mu() const = 0; virtual float gain_omega() const = 0; virtual void set_verbose(bool verbose) = 0; virtual void set_gain_mu (float gain_mu) = 0; virtual void set_gain_omega (float gain_omega) = 0; virtual void set_mu (float mu) = 0; virtual void set_omega (float omega) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_FF_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/lms_dd_equalizer_cc.h0000664000175000017500000000715412207440367026374 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_LMS_DD_EQUALIZER_CC_H #define INCLUDED_DIGITAL_LMS_DD_EQUALIZER_CC_H #include #include #include namespace gr { namespace digital { /*! * \brief Least-Mean-Square Decision Directed Equalizer (complex in/out) * \ingroup equalizers_blk * * \details * This block implements an LMS-based decision-directed equalizer. * It uses a set of weights, w, to correlate against the inputs, * u, and a decisions is then made from this output. The error in * the decision is used to update the weight vector. * * y[n] = conj(w[n]) u[n] * d[n] = decision(y[n]) * e[n] = d[n] - y[n] * w[n+1] = w[n] + mu u[n] conj(e[n]) * * Where mu is a gain value (between 0 and 1 and usualy small, * around 0.001 - 0.01. * * This block uses the digital_constellation object for making the * decision from y[n]. Create the constellation object for * whatever constellation is to be used and pass in the object. * In Python, you can use something like: * * self.constellation = digital.constellation_qpsk() * * To create a QPSK constellation (see the digital_constellation * block for more details as to what constellations are available * or how to create your own). You then pass the object to this * block as an sptr, or using "self.constellation.base()". * * The theory for this algorithm can be found in Chapter 9 of: * S. Haykin, Adaptive Filter Theory, Upper Saddle River, NJ: * Prentice Hall, 1996. */ class DIGITAL_API lms_dd_equalizer_cc : virtual public sync_decimator { protected: virtual gr_complex error(const gr_complex &out) = 0; virtual void update_tap(gr_complex &tap, const gr_complex &in) = 0; public: // gr::digital::lms_dd_equalizer_cc::sptr typedef boost::shared_ptr sptr; /*! * Make an LMS decision-directed equalizer * * \param num_taps Numer of taps in the equalizer (channel size) * \param mu Gain of the update loop * \param sps Number of samples per symbol of the input signal * \param cnst A constellation derived from class * 'constellation'. Use base() method to get a shared pointer to * this base class type. */ static sptr make(int num_taps, float mu, int sps, constellation_sptr cnst); virtual void set_taps(const std::vector &taps) = 0; virtual std::vector taps() const = 0; virtual float gain() const = 0; virtual void set_gain(float mu) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_LMS_DD_EQUALIZER_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/ofdm_chanest_vcvc.h0000664000175000017500000001121312207440367026046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_CHANEST_VCVC_H #define INCLUDED_DIGITAL_OFDM_CHANEST_VCVC_H #include #include namespace gr { namespace digital { /*! * \brief Estimate channel and coarse frequency offset for OFDM from preambles * \ingroup ofdm_blk * \ingroup syncronizers_blk * * Input: OFDM symbols (in frequency domain). The first one (or two) symbols are expected * to be synchronisation symbols, which are used to estimate the coarse freq offset * and the initial equalizer taps (these symbols are removed from the stream). * The following \p n_data_symbols are passed through unmodified (the actual equalisation * must be done elsewhere). * Output: The data symbols, without the synchronisation symbols. * The first data symbol passed through has two tags: * 'ofdm_sync_carr_offset' (integer), the coarse frequency offset as number of carriers, * and 'ofdm_sync_eq_taps' (complex vector). * Any tags attached to the synchronisation symbols are attached to the first data * symbol. All other tags are propagated as expected. * * Note: The vector on ofdm_sync_eq_taps is already frequency-corrected, whereas the rest is not. * * This block assumes the frequency offset is even (i.e. an integer multiple of 2). * * [1] Schmidl, T.M. and Cox, D.C., "Robust frequency and timing synchronization for OFDM", * Communications, IEEE Transactions on, 1997. * [2] K.D. Kammeyer, "Nachrichtenuebertragung," Chapter. 16.3.2. */ class DIGITAL_API ofdm_chanest_vcvc : virtual public block { public: typedef boost::shared_ptr sptr; /*! * \param sync_symbol1 First synchronisation symbol in the frequency domain. Its length must be * the FFT length. For Schmidl & Cox synchronisation, every second sub-carrier * has to be zero. * \param sync_symbol2 Second synchronisation symbol in the frequency domain. Must be equal to * the FFT length, or zero length if only one synchronisation symbol is used. * Using this symbol is how synchronisation is described in [1]. Leaving this * empty forces us to interpolate the equalizer taps. * If you are using an unusual sub-carrier configuration (e.g. because of OFDMA), * this sync symbol is used to identify the active sub-carriers. If you only * have one synchronisation symbol, set the active sub-carriers to a non-zero * value in here, and also set \p force_one_sync_symbol parameter to true. * \param n_data_symbols The number of data symbols following each set of synchronisation symbols. * Must be at least 1. * \param eq_noise_red_len If non-zero, noise reduction for the equalizer taps is done according * to [2]. In this case, it is the channel influence time in number of * samples. A good value is usually the length of the cyclic prefix. * \param max_carr_offset Limit the number of sub-carriers the frequency offset can maximally be. * Leave this zero to try all possibilities. * \param force_one_sync_symbol See \p sync_symbol2. */ static sptr make( const std::vector &sync_symbol1, const std::vector &sync_symbol2, int n_data_symbols, int eq_noise_red_len=0, int max_carr_offset=-1, bool force_one_sync_symbol=false ); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_CHANEST_VCVC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/pfb_clock_sync_fff.h0000664000175000017500000003225012237515112026170 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PFB_CLOCK_SYNC_FFF_H #define INCLUDED_DIGITAL_PFB_CLOCK_SYNC_FFF_H #include #include #include namespace gr { namespace digital { /*! * \brief Timing synchronizer using polyphase filterbanks * \ingroup synchronizers_blk * * \details * This block performs timing synchronization for PAM signals by * minimizing the derivative of the filtered signal, which in turn * maximizes the SNR and minimizes ISI. * * This approach works by setting up two filterbanks; one * filterbank contains the signal's pulse shaping matched filter * (such as a root raised cosine filter), where each branch of the * filterbank contains a different phase of the filter. The * second filterbank contains the derivatives of the filters in * the first filterbank. Thinking of this in the time domain, the * first filterbank contains filters that have a sinc shape to * them. We want to align the output signal to be sampled at * exactly the peak of the sinc shape. The derivative of the sinc * contains a zero at the maximum point of the sinc (sinc(0) = 1, * sinc(0)' = 0). Furthermore, the region around the zero point * is relatively linear. We make use of this fact to generate the * error signal. * * If the signal out of the derivative filters is d_i[n] for the * ith filter, and the output of the matched filter is x_i[n], we * calculate the error as: e[n] = (Re{x_i[n]} * Re{d_i[n]} + * Im{x_i[n]} * Im{d_i[n]}) / 2.0 This equation averages the error * in the real and imaginary parts. There are two reasons we * multiply by the signal itself. First, if the symbol could be * positive or negative going, but we want the error term to * always tell us to go in the same direction depending on which * side of the zero point we are on. The sign of x_i[n] adjusts * the error term to do this. Second, the magnitude of x_i[n] * scales the error term depending on the symbol's amplitude, so * larger signals give us a stronger error term because we have * more confidence in that symbol's value. Using the magnitude of * x_i[n] instead of just the sign is especially good for signals * with low SNR. * * The error signal, e[n], gives us a value proportional to how * far away from the zero point we are in the derivative * signal. We want to drive this value to zero, so we set up a * second order loop. We have two variables for this loop; d_k is * the filter number in the filterbank we are on and d_rate is the * rate which we travel through the filters in the steady * state. That is, due to the natural clock differences between * the transmitter and receiver, d_rate represents that difference * and would traverse the filter phase paths to keep the receiver * locked. Thinking of this as a second-order PLL, the d_rate is * the frequency and d_k is the phase. So we update d_rate and d_k * using the standard loop equations based on two error signals, * d_alpha and d_beta. We have these two values set based on each * other for a critically damped system, so in the block * constructor, we just ask for "gain," which is d_alpha while * d_beta is equal to (gain^2)/4. * * The block's parameters are: * * \li \p sps: The clock sync block needs to know the number of * samples per symbol, because it defaults to return a single * point representing the symbol. The sps can be any positive real * number and does not need to be an integer. * * \li \p loop_bw: The loop bandwidth is used to set the gain of * the inner control loop (see: * http://gnuradio.squarespace.com/blog/2011/8/13/control-loop-gain-values.html). * This should be set small (a value of around 2pi/100 is * suggested in that blog post as the step size for the number of * radians around the unit circle to move relative to the error). * * \li \p taps: One of the most important parameters for this * block is the taps of the filter. One of the benefits of this * algorithm is that you can put the matched filter in here as the * taps, so you get both the matched filter and sample timing * correction in one go. So create your normal matched filter. For * a typical digital modulation, this is a root raised cosine * filter. The number of taps of this filter is based on how long * you expect the channel to be; that is, how many symbols do you * want to combine to get the current symbols energy back (there's * probably a better way of stating that). It's usually 5 to 10 or * so. That gives you your filter, but now we need to think about * it as a filter with different phase profiles in each filter. So * take this number of taps and multiply it by the number of * filters. This is the number you would use to create your * prototype filter. When you use this in the PFB filerbank, it * segments these taps into the filterbanks in such a way that * each bank now represents the filter at different phases, * equally spaced at 2pi/N, where N is the number of filters. * * \li \p filter_size (default=32): The number of filters can also * be set and defaults to 32. With 32 filters, you get a good * enough resolution in the phase to produce very small, almost * unnoticeable, ISI. Going to 64 filters can reduce this more, * but after that there is very little gained for the extra * complexity. * * \li \p init_phase (default=0): The initial phase is another * settable parameter and refers to the filter path the algorithm * initially looks at (i.e., d_k starts at init_phase). This value * defaults to zero, but it might be useful to start at a * different phase offset, such as the mid-point of the filters. * * \li \p max_rate_deviation (default=1.5): The next parameter is * the max_rate_devitation, which defaults to 1.5. This is how far * we allow d_rate to swing, positive or negative, from * 0. Constraining the rate can help keep the algorithm from * walking too far away to lock during times when there is no * signal. * * \li \p osps (default=1): The osps is the number of output * samples per symbol. By default, the algorithm produces 1 sample * per symbol, sampled at the exact sample value. This osps value * was added to better work with equalizers, which do a better job * of modeling the channel if they have 2 samps/sym. * * Reference: * f. j. harris and M. Rice, "Multirate Digital Filters for Symbol * Timing Synchronization in Software Defined Radios", IEEE * Selected Areas in Communications, Vol. 19, No. 12, Dec., 2001. * * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.127.1757 */ class DIGITAL_API pfb_clock_sync_fff : virtual public block { public: // gr::digital::pfb_clock_sync_fff::sptr typedef boost::shared_ptr sptr; /*! * Build the polyphase filterbank timing synchronizer. * \param sps (double) The number of samples per second in the incoming signal * \param gain (float) The alpha gain of the control loop; beta = (gain^2)/4 by default. * \param taps (vector) The filter taps. * \param filter_size (uint) The number of filters in the filterbank (default = 32). * \param init_phase (float) The initial phase to look at, or which filter to start * with (default = 0). * \param max_rate_deviation (float) Distance from 0 d_rate can get (default = 1.5). * \param osps (int) The number of output samples per symbol (default=1). * */ static sptr make(double sps, float gain, const std::vector &taps, unsigned int filter_size=32, float init_phase=0, float max_rate_deviation=1.5, int osps=1); /*! \brief update the system gains from omega and eta * * This function updates the system gains based on the loop * bandwidth and damping factor of the system. * These two factors can be set separately through their own * set functions. */ virtual void update_gains() = 0; /*! * Resets the filterbank's filter taps with the new prototype filter */ virtual void set_taps(const std::vector &taps, std::vector< std::vector > &ourtaps, std::vector &ourfilter) = 0; /*! * Returns all of the taps of the matched filter */ virtual std::vector< std::vector > taps() const = 0; /*! * Returns all of the taps of the derivative filter */ virtual std::vector< std::vector > diff_taps() const = 0; /*! * Returns the taps of the matched filter for a particular channel */ virtual std::vector channel_taps(int channel) const = 0; /*! * Returns the taps in the derivative filter for a particular channel */ virtual std::vector diff_channel_taps(int channel) const = 0; /*! * Return the taps as a formatted string for printing */ virtual std::string taps_as_string() const = 0; /*! * Return the derivative filter taps as a formatted string for printing */ virtual std::string diff_taps_as_string() const = 0; /******************************************************************* SET FUNCTIONS *******************************************************************/ /*! * \brief Set the loop bandwidth * * Set the loop filter's bandwidth to \p bw. This should be * between 2*pi/200 and 2*pi/100 (in rads/samp). It must also be * a positive number. * * When a new damping factor is set, the gains, alpha and beta, * of the loop are recalculated by a call to update_gains(). * * \param bw (float) new bandwidth */ virtual void set_loop_bandwidth(float bw) = 0; /*! * \brief Set the loop damping factor * * Set the loop filter's damping factor to \p df. The damping * factor should be sqrt(2)/2.0 for critically damped systems. * Set it to anything else only if you know what you are * doing. It must be a number between 0 and 1. * * When a new damping factor is set, the gains, alpha and beta, * of the loop are recalculated by a call to update_gains(). * * \param df (float) new damping factor */ virtual void set_damping_factor(float df) = 0; /*! * \brief Set the loop gain alpha * * Set's the loop filter's alpha gain parameter. * * This value should really only be set by adjusting the loop * bandwidth and damping factor. * * \param alpha (float) new alpha gain */ virtual void set_alpha(float alpha) = 0; /*! * \brief Set the loop gain beta * * Set's the loop filter's beta gain parameter. * * This value should really only be set by adjusting the loop * bandwidth and damping factor. * * \param beta (float) new beta gain */ virtual void set_beta(float beta) = 0; /*! * Set the maximum deviation from 0 d_rate can have */ virtual void set_max_rate_deviation(float m) = 0; /******************************************************************* GET FUNCTIONS *******************************************************************/ /*! * \brief Returns the loop bandwidth */ virtual float loop_bandwidth() const = 0; /*! * \brief Returns the loop damping factor */ virtual float damping_factor() const = 0; /*! * \brief Returns the loop gain alpha */ virtual float alpha() const = 0; /*! * \brief Returns the loop gain beta */ virtual float beta() const = 0; /*! * \brief Returns the current clock rate */ virtual float clock_rate() const = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_PFB_CLOCK_SYNC_FFF_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/correlate_and_sync_cc.h0000664000175000017500000000645612244272666026721 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CORRELATE_AND_SYNC_CC_H #define INCLUDED_DIGITAL_CORRELATE_AND_SYNC_CC_H #include #include namespace gr { namespace digital { /*! * \brief Correlate to a preamble and send time/phase sync info * \ingroup synchronizers_blk * * \details * Input: * \li Stream of complex samples. * * Output: * \li Output stream that just passes the input complex samples * \li tag 'phase_est': estimate of phase offset * \li tag 'timing_est': estimate of symbol timing offset * \li tag 'corr_est': the correlation value of the estimates * * This block is designed to search for a preamble by correlation * and uses the results of the correlation to get a time and phase * offset estimate. These estimates are passed downstream as * stream tags for use by follow-on synchronization blocks. * * The preamble is provided as a set of symbols along with a * baseband matched filter which we use to create the filtered and * upsampled symbol that we will receive over-the-air. * * The phase_est tag is used to adjust the phase estimation of any * downstream synchronization blocks and is currently used by the * gr::digital::costas_loop_cc block. * * The time_est tag is used to adjust the sampling timing * estimation of any downstream synchronization blocks and is * currently used by the gr::digital::pfb_clock_sync_ccf block. */ class DIGITAL_API correlate_and_sync_cc : virtual public sync_block { public: typedef boost::shared_ptr sptr; /*! * Make a block that correlates against the \p symbols vector * and outputs a phase and symbol timing estimate. * * \param symbols Set of symbols to correlate against (e.g., a * preamble). * \param filter Baseband matched filter (e.g., RRC) * \param sps Samples per symbol * \param nfilts Number of filters in the internal PFB */ static sptr make(const std::vector &symbols, const std::vector &filter, unsigned int sps, unsigned int nfilts=32); virtual std::vector symbols() const = 0; virtual void set_symbols(const std::vector &symbols) = 0; }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_CORRELATE_AND_SYNC_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/mpsk_snr_est.h0000664000175000017500000002212512207440367025106 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_MPSK_SNR_EST_H #define INCLUDED_DIGITAL_MPSK_SNR_EST_H #include #include namespace gr { namespace digital { /*! * \brief A block for computing SNR of a signal. * \ingroup measurement_tools_blk * * \details * Below are some ROUGH estimates of what values of SNR each of * these types of estimators is good for. In general, these offer * a trade-off between accuracy and performance. * * \li SNR_EST_SIMPLE: Simple estimator (>= 7 dB) * \li SNR_EST_SKEW: Skewness-base est (>= 5 dB) * \li SNR_EST_M2M4: 2nd & 4th moment est (>= 1 dB) * \li SNR_EST_SVR: SVR-based est (>= 0dB) */ typedef enum { SNR_EST_SIMPLE = 0, // Simple estimator (>= 7 dB) SNR_EST_SKEW, // Skewness-base est (>= 5 dB) SNR_EST_M2M4, // 2nd & 4th moment est (>= 1 dB) SNR_EST_SVR // SVR-based est (>= 0dB) } snr_est_type_t; /*! \brief A parent class for SNR estimators, specifically for * M-PSK signals in AWGN channels. * \ingroup snr_blk */ class DIGITAL_API mpsk_snr_est { protected: double d_alpha, d_beta; public: /*! Constructor * * Parameters: * \param alpha: the update rate of internal running average * calculations. */ mpsk_snr_est(double alpha); virtual ~mpsk_snr_est(); //! Get the running-average coefficient double alpha() const; //! Set the running-average coefficient void set_alpha(double alpha); //! Update the current registers virtual int update(int noutput_items, const gr_complex *input); //! Use the register values to compute a new estimate virtual double snr(); }; //! \brief SNR Estimator using simple mean/variance estimates. /*! \ingroup snr_blk * * A very simple SNR estimator that just uses mean and variance * estimates of an M-PSK constellation. This esimator is quick * and cheap and accurate for high SNR (above 7 dB or so) but * quickly starts to overestimate the SNR at low SNR. */ class DIGITAL_API mpsk_snr_est_simple : public mpsk_snr_est { private: double d_y1, d_y2; public: /*! Constructor * * Parameters: * \param alpha: the update rate of internal running average * calculations. */ mpsk_snr_est_simple(double alpha); ~mpsk_snr_est_simple() {} int update(int noutput_items, const gr_complex *input); double snr(); }; //! \brief SNR Estimator using skewness correction. /*! \ingroup snr_blk * * This is an estimator that came from a discussion between Tom * Rondeau and fred harris with no known paper reference. The * idea is that at low SNR, the variance estimations will be * affected because of fold-over around the decision boundaries, * which results in a skewness to the samples. We estimate the * skewness and use this as a correcting term. */ class DIGITAL_API mpsk_snr_est_skew : public mpsk_snr_est { private: double d_y1, d_y2, d_y3; public: /*! Constructor * * Parameters: * \param alpha: the update rate of internal running average * calculations. */ mpsk_snr_est_skew(double alpha); ~mpsk_snr_est_skew() {} int update(int noutput_items, const gr_complex *input); double snr(); }; //! \brief SNR Estimator using 2nd and 4th-order moments. /*! \ingroup snr_blk * * An SNR estimator for M-PSK signals that uses 2nd (M2) and 4th * (M4) order moments. This estimator uses knowledge of the * kurtosis of the signal (k_a) and noise (k_w) to make its * estimation. We use Beaulieu's approximations here to M-PSK * signals and AWGN channels such that k_a=1 and k_w=2. These * approximations significantly reduce the complexity of the * calculations (and computations) required. * * Reference: * D. R. Pauluzzi and N. C. Beaulieu, "A comparison of SNR * estimation techniques for the AWGN channel," IEEE * Trans. Communications, Vol. 48, No. 10, pp. 1681-1691, 2000. */ class DIGITAL_API mpsk_snr_est_m2m4 : public mpsk_snr_est { private: double d_y1, d_y2; public: /*! Constructor * * Parameters: * \param alpha: the update rate of internal running average * calculations. */ mpsk_snr_est_m2m4(double alpha); ~mpsk_snr_est_m2m4() {} int update(int noutput_items, const gr_complex *input); double snr(); }; //! \brief SNR Estimator using 2nd and 4th-order moments. /*! \ingroup snr_blk * * An SNR estimator for M-PSK signals that uses 2nd (M2) and 4th * (M4) order moments. This estimator uses knowledge of the * kurtosis of the signal (k_a) and noise (k_w) to make its * estimation. In this case, you can set your own estimations for * k_a and k_w, the kurtosis of the signal and noise, to fit this * estimation better to your signal and channel conditions. * * A word of warning: this estimator has not been fully tested or * proved with any amount of rigor. The estimation for M4 in * particular might be ignoring effectf of when k_a and k_w are * different. Use this estimator with caution and a copy of the * reference on hand. * * The digital_mpsk_snr_est_m2m4 assumes k_a and k_w to simplify * the computations for M-PSK and AWGN channels. Use that * estimator unless you have a way to guess or estimate these * values here. * * Original paper: * R. Matzner, "An SNR estimation algorithm for complex baseband * signal using higher order statistics," Facta Universitatis * (Nis), no. 6, pp. 41-52, 1993. * * Reference used in derivation: * D. R. Pauluzzi and N. C. Beaulieu, "A comparison of SNR * estimation techniques for the AWGN channel," IEEE * Trans. Communications, Vol. 48, No. 10, pp. 1681-1691, 2000. */ class DIGITAL_API snr_est_m2m4 : public mpsk_snr_est { private: double d_y1, d_y2; double d_ka, d_kw; public: /*! Constructor * * Parameters: * \param alpha: the update rate of internal running average * calculations. * \param ka: estimate of the signal kurtosis (1 for PSK) * \param kw: estimate of the channel noise kurtosis (2 for AWGN) */ snr_est_m2m4(double alpha, double ka, double kw); ~snr_est_m2m4() {} int update(int noutput_items, const gr_complex *input); double snr(); }; //! \brief Signal-to-Variation Ratio SNR Estimator. /*! \ingroup snr_blk * * This estimator actually comes from an SNR estimator for M-PSK * signals in fading channels, but this implementation is * specifically for AWGN channels. The math was simplified to * assume a signal and noise kurtosis (k_a and k_w) for M-PSK * signals in AWGN. These approximations significantly reduce the * complexity of the calculations (and computations) required. * * Original paper: * A. L. Brandao, L. B. Lopes, and D. C. McLernon, "In-service * monitoring of multipath delay and cochannel interference for * indoor mobile communication systems," Proc. IEEE * Int. Conf. Communications, vol. 3, pp. 1458-1462, May 1994. * * Reference: * D. R. Pauluzzi and N. C. Beaulieu, "A comparison of SNR * estimation techniques for the AWGN channel," IEEE * Trans. Communications, Vol. 48, No. 10, pp. 1681-1691, 2000. */ class DIGITAL_API mpsk_snr_est_svr : public mpsk_snr_est { private: double d_y1, d_y2; public: /*! Constructor * * Parameters: * \param alpha: the update rate of internal running average * calculations. */ mpsk_snr_est_svr(double alpha); ~mpsk_snr_est_svr() {} int update(int noutput_items, const gr_complex *input); double snr(); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_MPSK_SNR_EST_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/api.h0000664000175000017500000000204512207440367023147 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_API_H #define INCLUDED_DIGITAL_API_H #include #ifdef gnuradio_digital_EXPORTS # define DIGITAL_API __GR_ATTR_EXPORT #else # define DIGITAL_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_DIGITAL_API_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/descrambler_bb.h0000664000175000017500000000354612207440367025333 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DESCRAMBLER_BB_H #define INCLUDED_GR_DESCRAMBLER_BB_H #include #include namespace gr { namespace digital { /*! * \brief Descramber an input stream using an LFSR. * \ingroup coding_blk * * \details * Descramble an input stream using an LFSR. This block works on * the LSB only of the input data stream, i.e., on an "unpacked * binary" stream, and produces the same format on its output. */ class DIGITAL_API descrambler_bb : virtual public sync_block { public: // gr::digital::descrambler_bb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a descrambler block. * * \param mask Polynomial mask for LFSR * \param seed Initial shift register contents * \param len Shift register length */ static sptr make(int mask, int seed, int len); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DESCRAMBLER_BB_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/kurtotic_equalizer_cc.h0000664000175000017500000000400412207440367026765 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_KURTOTIC_EQUALIZER_CC_H #define INCLUDED_DIGITAL_KURTOTIC_EQUALIZER_CC_H #include #include namespace gr { namespace digital { /*! * \brief Implements a kurtosis-based adaptive equalizer on complex stream * \ingroup equalizers_blk * * \details * Warning: This block does not yet work. * * "Y. Guo, J. Zhao, Y. Sun, "Sign kurtosis maximization based blind * equalization algorithm," IEEE Conf. on Control, Automation, * Robotics and Vision, Vol. 3, Dec. 2004, pp. 2052 - 2057." */ class DIGITAL_API kurtotic_equalizer_cc : virtual public sync_decimator { protected: virtual gr_complex error(const gr_complex &out) = 0; virtual void update_tap(gr_complex &tap, const gr_complex &in) = 0; public: // gr::digital::kurtotic_equalizer_cc::sptr typedef boost::shared_ptr sptr; static sptr make(int num_taps, float mu); virtual float gain() const = 0; virtual void set_gain(float mu) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_KURTOTIC_EQUALIZER_CC_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/constellation_soft_decoder_cf.h0000664000175000017500000000375412244272666030462 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_SOFT_DECODER_CF_H #define INCLUDED_DIGITAL_CONSTELLATION_SOFT_DECODER_CF_H #include #include #include namespace gr { namespace digital { /*! * \brief Constellation Decoder * \ingroup symbol_coding_blk * * \details * Decode a constellation's points from a complex space to soft * bits based on the map and soft decision LUT of the \p * consetllation object. */ class DIGITAL_API constellation_soft_decoder_cf : virtual public sync_interpolator { public: // gr::digital::constellation_soft_decoder_cf::sptr typedef boost::shared_ptr sptr; /*! * \brief Make constellation decoder block. * * \param constellation A constellation derived from class * 'constellation'. Use base() method to get a shared pointer to * this base class type. */ static sptr make(constellation_sptr constellation); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_SOFT_DECODER_CF_H */ gnuradio-3.7.2.1/gr-digital/include/gnuradio/digital/mpsk_receiver_cc.h0000664000175000017500000001277512207440367025714 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_MPSK_RECEIVER_CC_H #define INCLUDED_DIGITAL_MPSK_RECEIVER_CC_H #include #include namespace gr { namespace digital { /*! * \brief This block takes care of receiving M-PSK modulated * signals through phase, frequency, and symbol synchronization. * \ingroup synchronizers_blk * * \details * It performs carrier frequency and phase locking as well as * symbol timing recovery. It works with (D)BPSK, (D)QPSK, and * (D)8PSK as tested currently. It should also work for OQPSK and * PI/4 DQPSK. * * The phase and frequency synchronization are based on a Costas * loop that finds the error of the incoming signal point compared * to its nearest constellation point. The frequency and phase of * the NCO are updated according to this error. There are * optimized phase error detectors for BPSK and QPSK, but 8PSK is * done using a brute-force computation of the constellation * points to find the minimum. * * The symbol synchronization is done using a modified Mueller and * Muller circuit from the paper: * * "G. R. Danesfahani, T. G. Jeans, "Optimisation of modified Mueller * and Muller algorithm," Electronics Letters, Vol. 31, no. 13, 22 * June 1995, pp. 1032 - 1033." * * This circuit interpolates the downconverted sample (using the * NCO developed by the Costas loop) every mu samples, then it * finds the sampling error based on this and the past symbols and * the decision made on the samples. Like the phase error * detector, there are optimized decision algorithms for BPSK and * QPKS, but 8PSK uses another brute force computation against all * possible symbols. The modifications to the M&M used here reduce * self-noise. * */ class DIGITAL_API mpsk_receiver_cc : virtual public block { public: // gr::digital::mpsk_receiver_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a M-PSK receiver block. * * \param M modulation order of the M-PSK modulation * \param theta any constant phase rotation from the real axis of the constellation * \param loop_bw Loop bandwidth to set gains of phase/freq tracking loop * \param fmin minimum normalized frequency value the loop can achieve * \param fmax maximum normalized frequency value the loop can achieve * \param mu initial parameter for the interpolator [0,1] * \param gain_mu gain parameter of the M&M error signal to adjust mu (~0.05) * \param omega initial value for the number of symbols between samples (~number of samples/symbol) * \param gain_omega gain parameter to adjust omega based on the error (~omega^2/4) * \param omega_rel sets the maximum (omega*(1+omega_rel)) and minimum (omega*(1+omega_rel)) omega (~0.005) * * The constructor also chooses which phase detector and * decision maker to use in the work loop based on the value of * M. */ static sptr make(unsigned int M, float theta, float loop_bw, float fmin, float fmax, float mu, float gain_mu, float omega, float gain_omega, float omega_rel); //! Returns the modulation order (M) currently set virtual float modulation_order() const = 0; //! Returns current value of theta virtual float theta() const = 0; //! Returns current value of mu virtual float mu() const = 0; //! Returns current value of omega virtual float omega() const = 0; //! Returns mu gain factor virtual float gain_mu() const = 0; //! Returns omega gain factor virtual float gain_omega() const = 0; //! Returns the relative omega limit virtual float gain_omega_rel() const = 0; //! Sets the modulation order (M) currently virtual void set_modulation_order(unsigned int M) = 0; //! Sets value of theta virtual void set_theta(float theta) = 0; //! Sets value of mu virtual void set_mu(float mu) = 0; //! Sets value of omega and its min and max values virtual void set_omega(float omega) = 0; //! Sets value for mu gain factor virtual void set_gain_mu(float gain_mu) = 0; //! Sets value for omega gain factor virtual void set_gain_omega(float gain_omega) = 0; //! Sets the relative omega limit and resets omega min/max values virtual void set_gain_omega_rel(float omega_rel) = 0; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_MPSK_RECEIVER_CC_H */ gnuradio-3.7.2.1/gr-digital/grc/0000755000175000017500000000000012237515112016117 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/grc/CMakeLists.txt0000664000175000017500000000160212207440367020666 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "digital_python" ) gnuradio-3.7.2.1/gr-digital/grc/digital_binary_slicer_fb.xml0000664000175000017500000000066612207416644023653 0ustar jcorganjcorgan Binary Slicer digital_binary_slicer_fb from gnuradio import digital digital.binary_slicer_fb() in float out byte gnuradio-3.7.2.1/gr-digital/grc/digital_packet_headerparser_b.xml0000664000175000017500000000070612207440367024646 0ustar jcorganjcorgan Packet Header Parser digital_packet_headerparser_b from gnuradio import digital digital.packet_headerparser_b($header_formatter) Formatter Object header_formatter raw in byte header_data message gnuradio-3.7.2.1/gr-digital/grc/digital_dxpsk_mod.xml0000664000175000017500000000500512207440367022336 0ustar jcorganjcorgan DPSK Mod digital_dxpsk_mod from gnuradio import digital digital.$(type)_mod( samples_per_symbol=$samples_per_symbol, excess_bw=$excess_bw, mod_code=$mod_code, verbose=$verbose, log=$log) Type type enum Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real Gray Code mod_code enum Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_mpsk_receiver_cc.xml0000664000175000017500000000341712207440367023656 0ustar jcorganjcorgan MPSK Receiver digital_mpsk_receiver_cc from gnuradio import digital;import cmath digital.mpsk_receiver_cc($M, $theta, $w, $fmin, $fmax, $mu, $gain_mu, $omega, $gain_omega, $omega_relative_limit) set_loop_bandwidth($w) set_mu($mu) set_gain_mu($gain_mu) set_omega($omega) set_gain_omega($gain_omega) M M 4 int Theta theta 0 real Loop Bandwidth w cmath.pi/100.0 real Min Freq fmin -0.5 real Max Freq fmax 0.5 real Mu mu 0.25 real Gain Mu gain_mu 0.01 real Omega omega 2 real Gain Omega gain_omega 0.001 real Omega Relative Limit omega_relative_limit 0.001 real in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_clock_recovery_mm_xx.xml0000664000175000017500000000344212207440367024572 0ustar jcorganjcorgan Clock Recovery MM digital_clock_recovery_mm_xx from gnuradio import digital digital.clock_recovery_mm_$(type.fcn)($omega, $gain_omega, $mu, $gain_mu, $omega_relative_limit) set_omega($omega) set_gain_omega($gain_omega) set_mu($mu) set_gain_mu($gain_mu) Type type enum Omega omega samp_per_sym*(1+0.0) real Gain Omega gain_omega 0.25*0.175*0.175 real Mu mu 0.5 real Gain Mu gain_mu 0.175 real Omega Relative Limit omega_relative_limit 0.005 real in $type out $type gnuradio-3.7.2.1/gr-digital/grc/digital_mpsk_snr_est_cc.xml0000644000175000017500000000223311740601222023506 0ustar jcorganjcorgan MPSK SNR Estimator digital_mpsk_snr_est_cc from gnuradio import digital digital.mpsk_snr_est_cc($type, $tag_nsamples, $alpha) set_type($type) set_tag_nsamples($tag_nsamples) set_alpha($alpha) Type type enum Samples between tags tag_nsamples 10000 int Filter Alpha alpha 0.001 real in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_cyclic_prefixer.xml0000664000175000017500000000343012207440367024525 0ustar jcorganjcorgan OFDM Cyclic Prefixer digital_ofdm_cyclic_prefixer from gnuradio import digital digital.ofdm_cyclic_prefixer($input_size, $input_size+$cp_len, $rolloff, $tagname) FFT Length input_size fft_len int CP Length cp_len fft_len/4 int Rolloff rolloff 0 int #if $rolloff then 'none' else 'part'# Length Tag Key tagname "frame_len" string in complex $input_size out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_carrier_allocator_cvc.xml0000664000175000017500000000226612207440367025703 0ustar jcorganjcorgan OFDM Carrier Allocator digital_ofdm_carrier_allocator_cvc from gnuradio import digital digital.ofdm_carrier_allocator_cvc($fft_len, $occupied_carriers, $pilot_carriers, $pilot_symbols, $sync_words, $len_tag_key) FFT length fft_len fft_len int Occupied Carriers occupied_carriers raw Pilot Carriers pilot_carriers () raw Pilot Symbols pilot_symbols () raw Sync Words sync_words () raw Length tag key len_tag_key "packet_len" string in complex out complex $fft_len gnuradio-3.7.2.1/gr-digital/grc/digital_constellation_soft_decoder_cf.xml0000664000175000017500000000115212237515112026405 0ustar jcorganjcorgan Constellation Soft Decoder digital_constellation_soft_decoder_cf from gnuradio import digital digital.constellation_soft_decoder_cf($constellation) Constellation Object constellation raw in complex out float gnuradio-3.7.2.1/gr-digital/grc/digital_framer_sink_1.xml0000644000175000017500000000074511765410647023100 0ustar jcorganjcorgan Framer Sink 1 digital_framer_sink_1 from gnuradio import digital digital.framer_sink_1($target_queue) Target Message Queue target_queue raw in byte gnuradio-3.7.2.1/gr-digital/grc/digital_header_payload_demux.xml0000664000175000017500000000445712207440367024523 0ustar jcorganjcorgan Header/Payload Demux digital_header_payload_demux from gnuradio import digital digital.header_payload_demux($header_len, $items_per_symbol, $guard_interval, $length_tag_key, $trigger_tag_key, $output_symbols, $(type.itemsize)) Header Length (Symbols) header_len int Items per symbol items_per_symbol int Guard Interval (items) guard_interval 0 int #if $guard_interval then 'none' else 'part'# Length tag key length_tag_key "frame_len" string Trigger tag key trigger_tag_key "" string #if $trigger_tag_key then 'none' else 'part'# Output Format output_symbols enum IO Type type enum in $type trigger byte header_data message out_hdr $type {True: $items_per_symbol, False: 1}[$output_symbols] out_payload $type {True: $items_per_symbol, False: 1}[$output_symbols] gnuradio-3.7.2.1/gr-digital/grc/digital_constellation.xml0000664000175000017500000000410712237515112023220 0ustar jcorganjcorgan Constellation Object variable_constellation Modulators from gnuradio import digital self.$(id) = $(id) = digital.constellation_calcdist($const_points, $sym_map, $rot_sym, $dims).base() #if str($soft_dec_lut).lower() == '"auto"' or str($soft_dec_lut).lower() == "'auto'" self.$(id).gen_soft_dec_lut($precision) #else if str($soft_dec_lut) != 'None' self.$(id).set_soft_dec_lut($soft_dec_lut, $precision) #end if Ignore Me value "ok" raw all Symbol Map sym_map [0, 1, 3, 2] int_vector Constellation Points const_points [-1-1j, -1+1j, 1+1j, 1-1j] complex_vector Rotational Symmetry rot_sym 4 int Dimensionality dims 1 int Soft Decisions Precision precision 8 int part Soft Decisions LUT soft_dec_lut None raw #if str($soft_dec_lut) == 'None' then 'part' else 'none'# gnuradio-3.7.2.1/gr-digital/grc/digital_simple_framer.xml0000664000175000017500000000104512207407611023166 0ustar jcorganjcorgan Simple Framer digital_simple_framer from gnuradio import digital digital.simple_framer($payload_bytesize) Payload Byte Size payload_bytesize int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_correlate_access_code_bb.xml0000644000175000017500000000127011700377701025300 0ustar jcorganjcorgan Correlate Access Code digital_correlate_access_code_bb from gnuradio import digital digital.correlate_access_code_bb($access_code, $threshold) Access Code access_code 101010 string Threshold threshold int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_correlate_access_code_tag_bb.xml0000664000175000017500000000144612207440367026144 0ustar jcorganjcorgan Correlate Access Code - Tag digital_correlate_access_code_tag_bb from gnuradio import digital digital.correlate_access_code_tag_bb($access_code, $threshold, $tagname) Access Code access_code 101010 string Threshold threshold int Tag Name tagname string in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_diff_encoder_bb.xml0000644000175000017500000000103311765410647023421 0ustar jcorganjcorgan Differential Encoder digital_diff_encoder_bb from gnuradio import digital digital.diff_encoder_bb($modulus) Modulus modulus int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_diff_phasor_cc.xml0000644000175000017500000000070311765410647023303 0ustar jcorganjcorgan Differential Phasor digital_diff_phasor_cc from gnuradio import digital digital.diff_phasor_cc() in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_simple_correlator.xml0000664000175000017500000000106612207440367024076 0ustar jcorganjcorgan Simple Correlator digital_simple_correlator from gnuradio import digital digital.simple_correlator($payload_bytesize) Payload Byte Size payload_bytesize int in float out byte gnuradio-3.7.2.1/gr-digital/grc/digital_crc32_bb.xml0000664000175000017500000000124412207440367021726 0ustar jcorganjcorgan Stream CRC32 digital_crc32_bb from gnuradio import digital digital.crc32_bb($check, $lengthtagname) Mode check enum Length tag name lengthtagname "packet_len" string in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_packet_headerparser_b_default.xml0000664000175000017500000000113112207440367026343 0ustar jcorganjcorgan Packet Header Parser (Default) digital_packet_headerparser_b_default from gnuradio import digital digital.packet_headerparser_b($header_len, $len_tag_key) Header Length header_len int Length Tag Name len_tag_key "packet_len" string in byte out message gnuradio-3.7.2.1/gr-digital/grc/digital_cma_equalizer_cc.xml0000664000175000017500000000156612207310533023633 0ustar jcorganjcorgan CMA Equalizer digital_cma_equalizer_cc from gnuradio import digital digital.cma_equalizer_cc($num_taps, $modulus, $mu, $sps) set_gain($mu) set_modulus($modulus) Num. Taps num_taps int Modulus modulus real Gain mu real Samples per Symbol sps int in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_gfsk_demod.xml0000664000175000017500000000353212207440367022453 0ustar jcorganjcorgan GFSK Demod digital_gfsk_demod from gnuradio import digital digital.gfsk_demod( samples_per_symbol=$samples_per_symbol, sensitivity=$sensitivity, gain_mu=$gain_mu, mu=$mu, omega_relative_limit=$omega_relative_limit, freq_error=$freq_error, verbose=$verbose, log=$log, ) Samples/Symbol samples_per_symbol 2 int Sensitivity sensitivity 1.0 real Gain Mu gain_mu 0.175 real Mu mu 0.5 real Omega Relative Limit omega_relative_limit 0.005 real Freq Error freq_error 0.0 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in complex out byte gnuradio-3.7.2.1/gr-digital/grc/digital_glfsr_source_x.xml0000644000175000017500000000216111765410647023376 0ustar jcorganjcorgan GLFSR Source digital_glfsr_source_x from gnuradio import digital digital.glfsr_source_$(type.fcn)($degree, $repeat, $mask, $seed) Type type enum Degree degree int Repeat repeat enum Mask mask 0 int Seed seed 1 int out $type gnuradio-3.7.2.1/gr-digital/grc/digital_gfsk_mod.xml0000664000175000017500000000263612207440367022146 0ustar jcorganjcorgan GFSK Mod digital_gfsk_mod from gnuradio import digital digital.gfsk_mod( samples_per_symbol=$samples_per_symbol, sensitivity=$sensitivity, bt=$bt, verbose=$verbose, log=$log, ) Samples/Symbol samples_per_symbol 2 int Sensitivity sensitivity 1.0 real BT bt 0.35 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_block_tree.xml0000664000175000017500000001120712237515112022452 0ustar jcorganjcorgan Coding digital_additive_scrambler_bb digital_descrambler_bb digital_scrambler_bb Equalizers digital_cma_equalizer_cc digital_lms_dd_equalizer_cc digital_kurtotic_equalizer_cc Measurement Tools digital_mpsk_snr_est_cc digital_probe_density_b digital_probe_mpsk_snr_est_c Modulators digital_cpmmod_bc digital_dxpsk_mod digital_dxpsk_demod digital_gfsk_mod digital_gfsk_demod digital_gmskmod_bc digital_gmsk_mod digital_gmsk_demod digital_psk_mod digital_psk_demod digital_qam_mod digital_qam_demod digital_constellation_modulator digital_constellation_receiver_cb variable_constellation variable_constellation_rect Packet Operators digital_correlate_access_code_bb digital_crc32_bb digital_framer_sink_1 digital_header_payload_demux digital_packet_headergenerator_bb digital_packet_headergenerator_bb_default digital_packet_headerparser_b digital_packet_headerparser_b_default digital_packet_sink digital_simple_framer digital_simple_correlator OFDM digital_ofdm_mod digital_ofdm_mod2 digital_ofdm_demod digital_ofdm_carrier_allocator_cvc digital_ofdm_chanest_vcvc digital_ofdm_cyclic_prefixer digital_ofdm_frame_acquisition digital_ofdm_frame_equalizer_vcvc digital_ofdm_frame_sink digital_ofdm_insert_preamble digital_ofdm_rx digital_ofdm_sampler digital_ofdm_serializer_vcc digital_ofdm_sync_pn digital_ofdm_sync_sc_cfb digital_ofdm_tx Symbol Coding digital_binary_slicer_fb digital_bytes_to_syms digital_chunks_to_symbols_xx digital_constellation_decoder_cb digital_constellation_receiver_cb digital_constellation_soft_decoder_cf digital_diff_decoder_bb digital_diff_encoder_bb digital_diff_phasor_cc digital_map_bb Synchronizers digital_clock_recovery_mm_xx digital_costas_loop_cc digital_fll_band_edge_cc digital_mpsk_receiver_cc digital_pfb_clock_sync_xxx digital_pn_correlator_cc digital_correlate_and_sync_cc Waveform Generators digital_glfsr_source_x Deprecated digital_correlate_access_code_bb digital_correlate_access_code_tag_bb digital_simple_framer digital_simple_correlator gnuradio-3.7.2.1/gr-digital/grc/digital_correlate_and_sync_cc.xml0000664000175000017500000000146012237515112024644 0ustar jcorganjcorgan Correlate and Sync digital_correlate_and_sync_cc from gnuradio import digital digital.correlate_and_sync_cc($symbols, $filter, $sps) Symbols symbols [1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,-1,1,-1] complex_vector Filter filter complex_vector Samples per Symbol sps 4 int in complex out complex corr complex gnuradio-3.7.2.1/gr-digital/grc/digital_bytes_to_syms.xml0000644000175000017500000000066411765410647023263 0ustar jcorganjcorgan Bytes to Symbols digital_bytes_to_syms from gnuradio import digital digital.bytes_to_syms() in byte out float gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_frame_acquisition.xml0000644000175000017500000000371411700377701025056 0ustar jcorganjcorgan OFDM Frame Acquisition digital_ofdm_frame_acquisition from gnuradio import digital digital.ofdm_frame_acquisition($occupied_carriers, $fft_length, $cplen, $known_symbol, $max_fft_shift_len) Occupied Carriers occupied_carriers int FFT Length fft_length int CP Length cplen int Preamble known_symbol complex_vector Max FFT Shift max_fft_shift_len int in complex $fft_length flag byte $fft_length out complex $occupied_carriers flag byte gnuradio-3.7.2.1/gr-digital/grc/digital_qam_demod.xml0000644000175000017500000000654711766404361022311 0ustar jcorganjcorgan QAM Demod digital_qam_demod from gnuradio import digital digital.qam.qam_demod( constellation_points=$constellation_points, differential=$differential, samples_per_symbol=$samples_per_symbol, excess_bw=$excess_bw, freq_bw=$freq_bw, timing_bw=$timing_bw, phase_bw=$phase_bw, mod_code=$mod_code, verbose=$verbose, log=$log, ) Number of Constellation Points constellation_points 16 int Differential Encoding differential True bool Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real Frequency BW freq_bw 6.28/100.0 real Timing BW timing_bw 6.28/100.0 real Phase BW phase_bw 6.28/100.0 real Gray Code mod_code enum Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in complex out byte gnuradio-3.7.2.1/gr-digital/grc/digital_scrambler_bb.xml0000644000175000017500000000133511765410647022771 0ustar jcorganjcorgan Scrambler digital_scrambler_bb from gnuradio import digital digital.scrambler_bb($mask, $seed, $len) Mask mask 0x8A hex Seed seed 0x7F hex Length len 7 int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_frame_sink.xml0000664000175000017500000000365712207440367023504 0ustar jcorganjcorgan OFDM Frame Sink digital_ofdm_frame_sink from gnuradio import digital digital.ofdm_frame_sink($syms, $vals, $queue, $occ_tones, $ph_gain, $frq_gain) Symbol Points syms complex_vector Symbol Values vals int_vector Message Queue queue raw Occupied Tones occ_tones int Phase Gain ph_gain 0.25 real Freq. Gain frq_gain 0.015625 real in complex $occ_tones flag byte out complex $occ_tones gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_demod.xml0000644000175000017500000000604511700377701022444 0ustar jcorganjcorgan OFDM Demod digital_ofdm_demod from grc_gnuradio import blks2 as grc_blks2 from gnuradio import digital grc_blks2.packet_demod_$(type.fcn)(digital.ofdm_demod( options=grc_blks2.options( modulation="$modulation", fft_length=$fft_length, occupied_tones=$occupied_tones, cp_length=$cp_length, snr=$snr, log=None, verbose=None, ), callback=lambda ok, payload: self.$(id).recv_pkt(ok, payload), ), ) Output Type type float enum Modulation modulation enum FFT Length fft_length 512 int Occupied Tones occupied_tones 200 int Cyclic Prefix Length cp_length 128 int SNR snr 10 real in complex out $type Payload Length: 0 for automatic. gnuradio-3.7.2.1/gr-digital/grc/digital_probe_mpsk_snr_est_c.xml0000644000175000017500000000216311740601222024534 0ustar jcorganjcorgan MPSK SNR Estimator Probe digital_probe_mpsk_snr_est_c from gnuradio import digital digital.probe_mpsk_snr_est_c($type, $msg_nsamples, $alpha) set_type($type) set_msg_nsample($msg_nsamples) set_alpha($alpha) Type type enum Samples between SNR messages msg_nsamples 10000 int Filter Alpha alpha 0.001 real in complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_sampler.xml0000644000175000017500000000324611700377701023017 0ustar jcorganjcorgan OFDM Sampler digital_ofdm_sampler from gnuradio import digital digital.ofdm_sampler($fft_length, $symbol_length, $timeout) FFT Length fft_length int Symbol Length symbol_length int Timeout timeout 1000 int in complex flag byte out complex $fft_length flag byte $fft_length gnuradio-3.7.2.1/gr-digital/grc/digital_kurtotic_equalizer_cc.xml0000644000175000017500000000124011700377701024731 0ustar jcorganjcorgan Kurtotic Equalizer digital_kurtotic_equalizer_cc from gnuradio import digital digital.kurtotic_equalizer_cc($num_taps, $mu) set_gain($mu) Num. Taps num_taps int Mu mu real in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_psk_demod.xml0000644000175000017500000000652211767217515022325 0ustar jcorganjcorgan PSK Demod digital_psk_demod from gnuradio import digital digital.psk.psk_demod( constellation_points=$constellation_points, differential=$differential, samples_per_symbol=$samples_per_symbol, excess_bw=$excess_bw, phase_bw=$phase_bw, timing_bw=$timing_bw, mod_code=$mod_code, verbose=$verbose, log=$log, ) Number of Constellation Points constellation_points 8 int Differential Encoding differential True bool Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real Frequency BW freq_bw 6.28/100.0 real Timing BW timing_bw 6.28/100.0 real Phase BW phase_bw 6.28/100.0 real Gray Code mod_code enum Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in complex out byte gnuradio-3.7.2.1/gr-digital/grc/digital_constellation_receiver_cb.xml0000664000175000017500000000234612207440367025561 0ustar jcorganjcorgan Constellation Receiver digital_constellation_receiver_cb from gnuradio import digital digital.constellation_receiver_cb($constellation, $loop_bw, $fmin, $fmax) Constellation Object constellation raw Loop Bandwidth loop_bw real Minimum Freq Deviation fmin real Maximum Freq Deviation fmax real in complex out byte error float 1 phase float 1 frequency float 1 symbol complex 1 gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_rx.xml0000664000175000017500000000742212237515112022003 0ustar jcorganjcorgan OFDM Receiver digital_ofdm_rx from gnuradio import digital digital.ofdm_rx( fft_len=$fft_len, cp_len=$cp_len, frame_length_tag_key='frame_'+$packet_len_key, packet_length_tag_key=$packet_len_key, #if $occupied_carriers() occupied_carriers=$occupied_carriers, #end if #if $pilot_carriers() pilot_carriers=$pilot_carriers, #end if #if $pilot_symbols() pilot_symbols=$pilot_symbols, #end if #if $sync_word1() sync_word1=$sync_word1, #end if #if $sync_word2() sync_word2=$sync_word2, #end if bps_header=$header_mod.bps, bps_payload=$payload_mod.bps, debug_log=$log, scramble_bits=$scramble_bits ) FFT Length fft_len 64 int Cyclic Prefix Length cp_len 16 int Packet Length Tag Key packet_len_key "length" string Occupied Carriers occupied_carriers () raw #if $occupied_carriers() none #else part #end if Pilot Carriers pilot_carriers () raw #if $pilot_carriers() none #else part #end if Pilot Symbols pilot_symbols () raw #if $pilot_symbols() none #else part #end if Sync Word 1 sync_word1 () raw #if $sync_word1() none #else part #end if Sync Word 2 sync_word2 () raw #if $sync_word2() none #else part #end if Header Modulation header_mod enum Payload Modulation payload_mod enum Scramble Bits scramble_bits False enum #if $scramble_bits then 'part' else 'none'# Log Debug Info log False enum #if $log then 'none' else 'part'# $fft_len > 0 $cp_len > 0 $cp_len < $fft_len in complex out byte gnuradio-3.7.2.1/gr-digital/grc/digital_psk_mod.xml0000644000175000017500000000564611700377701022011 0ustar jcorganjcorgan PSK Mod digital_psk_mod from gnuradio import digital digital.psk.psk_mod( constellation_points=$constellation_points, mod_code=$mod_code, differential=$differential, samples_per_symbol=$samples_per_symbol, excess_bw=$excess_bw, verbose=$verbose, log=$log, ) Number of Constellation Points constellation_points 8 int Gray Code mod_code enum Differential Encoding differential True bool Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_mod.xml0000644000175000017500000000637111700377701022135 0ustar jcorganjcorgan OFDM Mod digital_ofdm_mod from grc_gnuradio import blks2 as grc_blks2 from gnuradio import digital grc_blks2.packet_mod_$(type.fcn)(digital.ofdm_mod( options=grc_blks2.options( modulation="$modulation", fft_length=$fft_length, occupied_tones=$occupied_tones, cp_length=$cp_length, pad_for_usrp=$pad_for_usrp, log=None, verbose=None, ), ), payload_length=$payload_length, ) Input Type type float enum Modulation modulation enum FFT Length fft_length 512 int Occupied Tones occupied_tones 200 int Cyclic Prefix Length cp_length 128 int Pad for USRP pad_for_usrp enum Payload Length payload_length 0 int in $type out complex Payload Length: 0 for automatic. gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_chanest_vcvc.xml0000664000175000017500000000313112207440367024017 0ustar jcorganjcorgan OFDM Channel Estimation digital_ofdm_chanest_vcvc from gnuradio import digital digital.ofdm_chanest_vcvc($sync_symbol1, $sync_symbol2, $n_data_symbols, $eq_noise_red_len, $max_carr_offset, $force_one_symbol) Synch. symbol 1 sync_symbol1 complex_vector Synch. symbol 2 sync_symbol2 () complex_vector Number of data symbols n_data_symbols 1 int Channel taps noise reduction length eq_noise_red_len 0 int all Maximum carrier offset max_carr_offset -1 int #if $max_carr_offset < 0 then 'part' else 'none'# Force One Synchronisation Symbol force_one_symbol enum #if not $force_one_symbol then 'part' else 'none'# len($sync_symbol1) len($sync_symbol2) == 0 or len($sync_symbol2) == len($sync_symbol1) in complex len($sync_symbol1) out complex len($sync_symbol1) gnuradio-3.7.2.1/gr-digital/grc/digital_diff_decoder_bb.xml0000644000175000017500000000103311765410647023407 0ustar jcorganjcorgan Differential Decoder digital_diff_decoder_bb from gnuradio import digital digital.diff_decoder_bb($modulus) Modulus modulus int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_probe_density_b.xml0000644000175000017500000000116411765410647023523 0ustar jcorganjcorgan Probe Density digital_probe_density_b from gnuradio import digital digital.probe_density_b($alpha) set_alpha($alpha) Alpha alpha 1 real Probe Rate probe_rate 10 real in byte gnuradio-3.7.2.1/gr-digital/grc/digital_fll_band_edge_cc.xml0000644000175000017500000000260011700377701023532 0ustar jcorganjcorgan FLL Band-Edge digital_fll_band_edge_cc from gnuradio import digital digital.fll_band_edge_cc($samps_per_sym, $rolloff, $filter_size, $w) set_loop_bandwidth($w) Type type enum Samples Per Symbol samps_per_sym real Filter Rolloff Factor rolloff real Prototype Filter Size filter_size int Loop Bandwidth w real in $type.input out $type.output freq float 1 phase float 1 error float 1 gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_insert_preamble.xml0000644000175000017500000000320311765410647024530 0ustar jcorganjcorgan OFDM Insert Preamble digital_ofdm_insert_preamble from gnuradio import digital digital.ofdm_insert_preamble($fft_length, $preamble) FFT Length fft_length int Preamble preamble raw in complex $fft_length flag byte 1 out complex $fft_length flag byte 1 gnuradio-3.7.2.1/gr-digital/grc/digital_constellation_modulator.xml0000664000175000017500000000526212237515112025311 0ustar jcorganjcorgan Constellation Modulator digital_constellation_modulator from gnuradio import digital digital.generic_mod( constellation=$constellation, differential=$differential, samples_per_symbol=$samples_per_symbol, pre_diff_code=True, excess_bw=$excess_bw, verbose=$verbose, log=$log, ) Constellation constellation raw Differential Encoding differential True bool Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_serializer_vcc.xml0000664000175000017500000000310512207440367024356 0ustar jcorganjcorgan OFDM Serializer digital_ofdm_serializer_vcc from gnuradio import digital digital.ofdm_serializer_vcc($fft_len, $occupied_carriers, $len_tag_key, $packet_len_tag_key, $symbols_skipped, $carr_offset_key, $input_is_shifted) FFT length fft_len fft_len int Occupied Carriers occupied_carriers raw Length Tag Key len_tag_key string Packet Length Tag Key packet_len_tag_key "" string #if $packet_len_tag_key then 'none' else 'part'# Symbols skipped symbols_skipped 0 int #if $symbols_skipped then 'none' else 'part'# Carrier Offset Key carr_offset_key "" string #if $carr_offset_key then 'none' else 'part'# Input is shifted input_is_shifted True bool #if $input_is_shifted then 'part' else 'none'# in complex $fft_len out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_mod2.xml0000664000175000017500000000266212207440367022222 0ustar jcorganjcorgan OFDM Mod 2 digital_ofdm_mod2 from gnuradio import digital digital.ofdm_mod2(fft_len=$fft_len, cp_len=$cp_len, length_tag_name=$length_tag_name, occupied_carriers=$occupied_carriers, pilot_carriers=$pilot_carriers, pilot_symbols=$pilot_symbols, sync_sequence=$sync_sequence, ) Cyclic Prefix Length cp_len 16 int FFT Length fft_len 64 int Length Tag Name length_tag_name length string Occupied Carriers occupied_carriers (range(1, 27) + range(38, 64),) raw Pilot Carriers pilot_carriers ((0,),) raw Pilot Symbols pilot_symbols ((100,),) raw Synchronization Sequence sync_sequence None raw in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_descrambler_bb.xml0000644000175000017500000000134411765410647023302 0ustar jcorganjcorgan Descrambler digital_descrambler_bb from gnuradio import digital digital.descrambler_bb($mask, $seed, $len) Mask mask 0x8A hex Seed seed 0x7F hex Length len 7 int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_packet_headergenerator_bb.xml0000664000175000017500000000070612207440367025502 0ustar jcorganjcorgan Packet Header Generator digital_packet_headergenerator_bb from gnuradio import digital digital.packet_headergenerator_bb($header_formatter) Formatter Object header_formatter raw in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_sync_pn.xml0000644000175000017500000000310711700377701023021 0ustar jcorganjcorgan OFDM Sync PN digital_ofdm_sync_pn from gnuradio import digital digital.ofdm_sync_pn($fft_length, $cp_length, $logging) FFT Length fft_length int CP Length cp_length int Logging logging False bool in complex fine freq float timing sig byte gnuradio-3.7.2.1/gr-digital/grc/digital_qam_mod.xml0000644000175000017500000000564711700377701021773 0ustar jcorganjcorgan QAM Mod digital_qam_mod from gnuradio import digital digital.qam.qam_mod( constellation_points=$constellation_points, mod_code=$mod_code, differential=$differential, samples_per_symbol=$samples_per_symbol, excess_bw=$excess_bw, verbose=$verbose, log=$log, ) Number of Constellation Points constellation_points 16 int Gray Code mod_code enum Differential Encoding differential True bool Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_gmskmod_bc.xml0000664000175000017500000000143612207440367022457 0ustar jcorganjcorgan GMSK Modulator digital_gmskmod_bc from gnuradio import digital digital.gmskmod_bc($samples_per_symbol, $L, $bt) Samples/Symbol samples_per_symbol 2 int 3 dB Time-Bandwith Product bt 0.3 real Pulse Duration (Symbols) L 4 int in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_tx.xml0000664000175000017500000000762212237515112022007 0ustar jcorganjcorgan OFDM Transmitter digital_ofdm_tx from gnuradio import digital digital.ofdm_tx( fft_len=$fft_len, cp_len=$cp_len, packet_length_tag_key=$packet_len_key, #if $occupied_carriers() occupied_carriers=$occupied_carriers, #end if #if $pilot_carriers() pilot_carriers=$pilot_carriers, #end if #if $pilot_carriers() pilot_symbols=$pilot_symbols, #end if #if $sync_word1() sync_word1=$sync_word1, #end if #if $sync_word2() sync_word2=$sync_word2, #end if bps_header=$header_mod.bps, bps_payload=$payload_mod.bps, rolloff=$rolloff, debug_log=$log, scramble_bits=$scramble_bits ) FFT Length fft_len 64 int Cyclic Prefix Length cp_len 16 int Length Tag Name packet_len_key length string Occupied Carriers occupied_carriers () raw #if $occupied_carriers() none #else part #end if Pilot Carriers pilot_carriers () raw #if $pilot_carriers() none #else part #end if Pilot Symbols pilot_symbols () raw #if $pilot_symbols() none #else part #end if Sync Word 1 sync_word1 () raw #if $sync_word1() none #else part #end if Sync Word 2 sync_word2 () raw #if $sync_word2() none #else part #end if Header Modulation header_mod enum Payload Modulation payload_mod enum Rolloff length (samples) rolloff 0 int Scramble Bits scramble_bits False enum #if $scramble_bits then 'part' else 'none'# Log Debug Info log False enum #if $log then 'none' else 'part'# $fft_len > 0 $cp_len > 0 $cp_len < $fft_len $rolloff >= 0 in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_gmsk_mod.xml0000644000175000017500000000242311700377701022143 0ustar jcorganjcorgan GMSK Mod digital_gmsk_mod from gnuradio import digital digital.gmsk_mod( samples_per_symbol=$samples_per_symbol, bt=$bt, verbose=$verbose, log=$log, ) Samples/Symbol samples_per_symbol 2 int BT bt 0.35 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_cpmmod_bc.xml0000664000175000017500000000301612207440367022271 0ustar jcorganjcorgan Continuous Phase Modulation digital_cpmmod_bc from gnuradio import gr, digital, analog digital.cpmmod_bc($type, $mod_index, $samples_per_symbol, $L, $beta) CPM Type type enum Modulation Index mod_index 0.5 real Samples/Symbol samples_per_symbol 4 int Pulse Duration (Symbols) L 4 int Phase Response Parameter (BT or Beta) beta 0.3 real in byte out complex gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_frame_equalizer_vcvc.xml0000664000175000017500000000250012207440367025544 0ustar jcorganjcorgan OFDM Frame Equalizer digital_ofdm_frame_equalizer_vcvc from gnuradio import digital digital.ofdm_frame_equalizer_vcvc($equalizer, $cp_len, $len_tag_key, $propagate_channel_state, $fixed_frame_len) FFT length fft_len fft_len int CP length cp_len fft_len/4 int Equalizer equalizer raw Length Tag Key len_tag_key string Propagate Channel State propagate_channel_state enum Fixed frame length fixed_frame_len 0 int #if $fixed_frame_len then 'none' else 'part'# in complex $fft_len out complex $fft_len gnuradio-3.7.2.1/gr-digital/grc/digital_packet_sink.xml0000664000175000017500000000130312207440367022636 0ustar jcorganjcorgan Packet Sink digital_packet_sink from gnuradio import digital digital.packet_sink($sync_vector, $target_queue, $threshold) Sync Vector sync_vector int_vector Target Message Queue target_queue raw Threshold threshold -1 int in float gnuradio-3.7.2.1/gr-digital/grc/digital_additive_scrambler_bb.xml0000664000175000017500000000155112207416644024637 0ustar jcorganjcorgan Additive Scrambler digital_additive_scrambler_bb from gnuradio import digital digital.additive_scrambler_bb($mask, $seed, $len, $count) Mask mask 0x8A hex Seed seed 0x7F hex Length len 7 int Count count 0 int in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_dxpsk_demod.xml0000664000175000017500000000643512207440367022657 0ustar jcorganjcorgan DPSK Demod digital_dxpsk_demod from gnuradio import digital digital.$(type)_demod( samples_per_symbol=$samples_per_symbol, excess_bw=$excess_bw, freq_bw=$freq_bw, phase_bw=$phase_bw, timing_bw=$timing_bw, mod_code=$mod_code, verbose=$verbose, log=$log ) clock_recov.set_loop_bandwidth($phase_bw) time_recov.set_loop_bandwidth($timing_bw) Type type enum Samples/Symbol samples_per_symbol 2 int Excess BW excess_bw 0.35 real FLL Bandwidth freq_bw 6.28/100.0 real Phase Loop Bandwidth phase_bw 6.28/100.0 real Timing Bandwidth timing_bw 6.28/100.0 real Gray Code mod_code enum Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# Sync Out sync_out False bool in complex out byte gnuradio-3.7.2.1/gr-digital/grc/digital_costas_loop_cc.xml0000644000175000017500000000140411700377701023333 0ustar jcorganjcorgan Costas Loop digital_costas_loop_cc from gnuradio import digital digital.costas_loop_cc($w, $order) set_loop_bandwidth($w) Loop Bandwidth w real Order order int in complex out complex frequency float 1 gnuradio-3.7.2.1/gr-digital/grc/digital_gmsk_demod.xml0000644000175000017500000000331711700377701022457 0ustar jcorganjcorgan GMSK Demod digital_gmsk_demod from gnuradio import digital digital.gmsk_demod( samples_per_symbol=$samples_per_symbol, gain_mu=$gain_mu, mu=$mu, omega_relative_limit=$omega_relative_limit, freq_error=$freq_error, verbose=$verbose, log=$log, ) Samples/Symbol samples_per_symbol 2 int Gain Mu gain_mu 0.175 real Mu mu 0.5 real Omega Relative Limit omega_relative_limit 0.005 real Freq Error freq_error 0.0 real Verbose verbose False bool #if str($verbose) == 'False' then 'part' else 'none'# Logging log False bool #if str($log) == 'False' then 'part' else 'none'# in complex out byte gnuradio-3.7.2.1/gr-digital/grc/digital_lms_dd_equalizer_cc.xml0000664000175000017500000000153412207310533024330 0ustar jcorganjcorgan LMS DD Equalizer digital_lms_dd_equalizer_cc from gnuradio import digital digital.lms_dd_equalizer_cc($num_taps, $mu, $sps, $cnst) set_gain($mu) Gain mu real Num. Taps num_taps int Samples per Symbol sps int Constellation Object cnst raw in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_pfb_clock_sync.xml0000664000175000017500000000375012207440367023331 0ustar jcorganjcorgan Polyphase Clock Sync digital_pfb_clock_sync_xxx from gnuradio import digital digital.pfb_clock_sync_$(type)($sps, $loop_bw, $taps, $filter_size, $init_phase, $max_dev, $osps) set_taps($taps) set_loop_bandwidth($loop_bw) Type type enum Samples/Symbol sps real Loop Bandwidth loop_bw real Taps taps real_vector Filter Size filter_size 32 int Initial Phase init_phase 16 real Maximum Rate Deviation max_dev 1.5 real Output SPS osps 1 int in $type.input out $type.output err float 1 rate float 1 phase float 1 gnuradio-3.7.2.1/gr-digital/grc/digital_packet_headergenerator_bb_default.xml0000664000175000017500000000114112207440367027200 0ustar jcorganjcorgan Packet Header Generator (Default) digital_packet_headergenerator_bb_default from gnuradio import digital digital.packet_headergenerator_bb($header_len, $len_tag_key) Header Length header_len int Length Tag Name len_tag_key "packet_len" string in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_constellation_rect.xml0000664000175000017500000000472312237515112024241 0ustar jcorganjcorgan Constellation Rect. Object variable_constellation_rect Modulators from gnuradio import digital self.$(id) = $(id) = digital.constellation_rect($const_points, $sym_map, $rot_sym, $real_sect, $imag_sect, $w_real_sect, $w_imag_sect).base() #if str($softbits_lut) != 'None' self.$(id).set_softbits($softbits_lut, $precision) #end if Ignore Me value "ok" raw all Symbol Map sym_map [0, 1, 3, 2] int_vector Constellation Points const_points [-1-1j, -1+1j, 1+1j, 1-1j] complex_vector Rotational Symmetry rot_sym 4 int Real Sectors real_sect 2 int Imaginary Sectors imag_sect 2 int Width Real Sectors w_real_sect 1 int Width Imaginary Sectors w_imag_sect 1 int Soft bits precision precision 8 int part Soft bits LUT softbits_lut None raw #if str($softbits_lut) == 'None' then 'part' else 'none'# gnuradio-3.7.2.1/gr-digital/grc/digital_ofdm_sync_sc_cfb.xml0000664000175000017500000000165312207440367023633 0ustar jcorganjcorgan Schmidl & Cox OFDM synch. digital_ofdm_sync_sc_cfb from gnuradio import digital digital.ofdm_sync_sc_cfb($fft_len, $cp_len, $use_even_carriers) FFT length fft_len int Cyclic Prefix length cp_len int Preamble Carriers use_even_carriers False enum part in complex freq_offset float detect byte gnuradio-3.7.2.1/gr-digital/grc/digital_map_bb.xml0000644000175000017500000000074211765410647021575 0ustar jcorganjcorgan Map digital_map_bb from gnuradio import digital digital.map_bb($map) Map map int_vector in byte out byte gnuradio-3.7.2.1/gr-digital/grc/digital_pn_correlator_cc.xml0000644000175000017500000000133611765410647023673 0ustar jcorganjcorgan PN Correlator digital_pn_correlator_cc from gnuradio import digital digital.pn_correlator_cc($degree, $mask, $seed) Degree degree int Mask mask 0 int Seed seed 1 int in complex out complex gnuradio-3.7.2.1/gr-digital/grc/digital_chunks_to_symbols.xml0000644000175000017500000000306211765410647024120 0ustar jcorganjcorgan Chunks to Symbols digital_chunks_to_symbols_xx from gnuradio import digital digital.chunks_to_symbols_$(in_type.fcn)$(out_type.fcn)($symbol_table, $dimension) Input Type in_type enum Output Type out_type enum Symbol Table symbol_table $out_type.table Dimension dimension 2 int Num Ports num_ports 1 int $num_ports > 0 in $in_type $num_ports out $out_type $num_ports gnuradio-3.7.2.1/gr-digital/grc/digital_constellation_decoder_cb.xml0000664000175000017500000000111312207310533025340 0ustar jcorganjcorgan Constellation Decoder digital_constellation_decoder_cb from gnuradio import digital digital.constellation_decoder_cb($constellation) Constellation Object constellation raw in complex out byte gnuradio-3.7.2.1/gr-digital/doc/0000755000175000017500000000000012237515112016111 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/doc/CMakeLists.txt0000644000175000017500000000152511700377701020660 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.digital DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-digital/doc/digital.dox0000664000175000017500000005171712237515112020257 0ustar jcorganjcorgan/*! \page page_digital Digital Modulation \section Introduction This is the gr-digital package. It contains all of the digital modulation blocks, utilities, and examples. To use the digital blocks, the Python namespaces is in gnuradio.digital, which would be normally imported as: \code from gnuradio import digital \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(digital) \endcode \section digital_constellations Constellation Objects GNU Radio supports the creation and use of Constellation objects for many of its digital communications needs. We define these constellations with a set of constellation points in complex space and the symbol mappings to those points. For a constellation that has 4 symbols, it then has log2(4) = 2 bits/symbol. We define this constellation with:
    constel_points = [c0, c1, c2, c3]
    symbols = [s0, s1, s2, s3]
In this case: \f$c_i \in C\f$ and \f$s_i \in [00, 01, 10, 11]\f$. Also, the mapping is a 1-to-1 for the items in both lists, so the symbol \f$s_0\f$ is positioned in complex space at the point \f$c_0\f$. In the code itself, the symbols are referred to as the 'pre_diff_code' since this is the mapping before the application of differential modulation, if used. The constellation object classes are defined in constellation.h. There is a hierarchy of classes for different purposes and which represent special classes of constellations. The all derive from the virtual class gr::digital::constellation. All constellations we will make are based on classes derived from this base:
gr::digital::constellation
    --> gr::digital::constellation_calcdist
    --> gr::digital::constellation_sector
        --> gr::digital::constellation_rect
            --> gr::digital::constellation_expl_rect
        --> gr::digital::constellation_psk
    --> gr::digital::constellation_bpsk
    --> gr::digital::constellation_qpsk
    --> gr::digital::constellation_dqpsk
    --> gr::digital::constellation_8psk
Each constellation class has a set of attributes and functions useful for manipulating the constellations and for converting symbols to and from complex points. One of the more important functions is the gr::digital::constellation::decision_maker function that takes in a sample in complex space and returns the symbol that it maps to. How this calculation is performed generally distinguishes the constellation classes from each other. The gr::digital::constellation_calcdist is the most generic constellation class we can create. This takes in the constellation points, symbol mapping, a rotational symmetry, and the number of dimensions. The decision_maker function takes in a complex sample x and calculates the Euclidean distance between x and each point in the constellation map of the object. The constellation point that has the minimum Euclidean distance to x is selected as the best match. The decision_maker will then return the symbol value that matches to this selected constellation point. We then have a concept of a constellation with a well-defined concept of sectors in the gr::digital::constellation_sector. This is farther refined if we know that the constellation is rectangular and can use the gr::digital::constellation_rect class. These classes have an overloaded decision_maker function that is specific to how the sectors are defined in the constructor. Essentially, the decision making math for this class is less costly than calculating the Euclidean distance for each point in the space. So if we can sectorize our constellation, using this class will be computationally cheaper. Finally, we have a set of pre-defined, hard-coded constellations for BPSK (gr::digital::constellation_bpsk), QPSK (gr::digital::constellation_qpsk), DQPSK (gr::digital::constellation_dqpsk), and 8PSK (gr::digital::constellation_8psk). These derive directly from gr::digital::constellation and specifically overload the decision_maker function. We have very simple metrics for calculating decisions for each of these constellations. For BPSK, we simply slice on the real axis. Samples are based solely on whether the real part of the complex symbol x is greater than or less than 0. Similar, simple, decision makers are defined for the others. Note that these specific constellations for the PSK modulations are defined for only one mapping of the constellation points to the symbols. Each is Gray coded, but for a specific Gray coding that is hard-coded into the class. \subsection grc_constellations Constellation Objects in GRC GRC provides two constellation representations that we can use to more easily define and interact with constellation objects. These are located in the 'Modulators' category as 'Constellation Object' and 'Constellation Rect. Object'. These allow us to easily specify the constellation points, symbol list, and other properties of the constellation objects. They return the base() of the object, so the variable's ID can be used directly with blocks that accept constellation objects. These constellation blocks also allow us to specify the soft decision LUT if using the constellation object for soft decision outputs. The input can either be 'None' (default), a list of the soft bits that were generated externally or by another function, or 'auto' where the block will automatically calculate the soft decisions based on the constellation points and symbol map. \section digital_python_helpers Python Constellation Helper Functions A series of helper functions are defined in Python to create different, common constellations. There are various functions that have various levels of complexity in their definitions. \subsection digital_python_helpers_psk PSK Python Helpers There are two modules imported directly into gnuradio.digital. The first is gr-digital/python/digital/psk.py and the second is gr-digital/python/digital/psk_constellations.py. The gr-digital/python/digital/psk.py module defines the following constellations:
    psk_constellation(m, mod_code, differential)
This function defines a PSK modulation of order 'm' (that is, there are m number of constellation points / symbols). The 'mod_code' is either mod_codes.GRAY_CODE or mode_codes.NO_CODE to set the symbol mapping up as either Gray coded or not. The 'differential' argument is either True to use differential coding or False for non-differential coding. This function creates and returns a constellation object that can then be used by any block that takes a constellation (gr::digital::constellation_decoder_cb, gr::digital::constellation_receiver_cb, gr::digital::constellation_soft_decoder_cf, or gr::digital::lms_dd_equalizer_cc). The gr-digital/python/digital/psk.py module also holds functions similar to digital.psk_constellation but that create a full modulator and demodulator chain derived from digital.generic_mod_demod.
    psk_mod(constellation_points, mod_code, differential, *args, **kwargs)
    psk_demod(constellation_points, mod_code, differential, *args, **kwargs)
The args and kwargs are parameters of the generic_mod or generic_demod passed directly to them. See \ref digital_generic_mod_demod for details of this interface. There is another Python file full of helper functions to create different constellations. This is found in the gr-digital/python/digital/psk_constellation.py file. This file provides functions that build the vectors of constellation points and symbol mappings that can be used to create a constellation object. These are particularly helpful when using the Constellation Obj. and Constellation Rect. GUI elements in GRC. The gr-digital/python/digital/psk_constellation.py file has extensive documentation that describes the naming scheme used for the different constellations that will not be repeated here. The main thing to understand is that these functions define constellations of the same order with different Gray code mappings. The function names are:
    (const_points, symbol_map) = psk_M_0xk_()
Where M is the order of the modulation (2 for BPSK, 4 for QPSK, etc.), and k and \ define a particular encoding for the Gray code mapping used. The documentation in the file explains how these two concepts define the Gray code mapping. These functions are also simply named "psk_M_n" when n is an integer from 0 to N-1 for however many mappings are defined for that modulation. Not all modulations are fully defined, and the value for n has no other meaning except as a counter. The functions return a tuple of lists. The first list in the tuple is the list of complex constellation points and the second list contains the symbols mapped to those points. These lists can then be passed to a constellation class directly to create a constellation of any Gray code mapping needed. While not all Gray code mappings of the modulations are defined, there is a generator function to automatically build any rotation of a basis constellation:
    (const_points, symbol_map) = \
        constellation_map_generator(basis_cpoints, basis_symbols, k, pi)
We provide a basis constellation map and symbol map as the fundamental rotation of the constellation points. This function uses the k and pi inputs (see the discussion in psk_constellation.py for what these mean) to return a new rotation of the constellation's symbols. If the basis symbols are Gray coded than the output symbols will also be Gray coded. Note that this algorithm specifically depends on the constellation in complex space to be square to preserve the Gray code property. \subsection digital_python_helpers_qam QAM Python Helpers Similar to defining PSK modulations, GNU Radio also has helpers for some QAM modulations, found in gr-digital/python/digital/qam.py and gr-digital/python/digital/qam_constellations.py. Similar functions to what has been described for PSK exist here:
    qam_constellation(constellation_points, differential, mod_code,
                      large_ampls_to_corners)
    qam_mod(constellation_points, differential, mod_code, *args, **kwargs)
    qam_demod(constellation_points, differential, mod_code,
              large_ampls_to_corner, *args, **kwargs)
The parameters to these functions is the same as for the PSK equivalents. The new argument 'large_ampls_to_corner' is defined in the documentation as:
    large_ampls_to_corners:  If this is set to True then when the
        constellation is making decisions, points that are far outside
        the constellation are mapped to the closest corner rather than
        the closet constellation point.  This can help with phase
        locking.
Similarly, gr-digital/python/digital/qam_constellations.py defines a of QAM constellation functions that return a tuple containing the constellation points and the symbol mappings. The naming scheme is defined in depth in the module itself and is similar to the equivalent set of PSK functions. Currently, only a subset of 16QAM symbol mappings are defined, but we can use of the constellation_map_generator function described in the previous section to define more mapping rotations for and square QAM modulation. \section digital_generic_mod_demod The Generic Modulator/Demodulator Hierarchical Blocks Since digital modulation and demodulation are complex functions, the different parts can be done by different existing GNU Radio blocks. We have combined these into a generic modulator and generic demodulator hierarchical blocks to make access and use much easier. This file can be found as gr-digital/python/digital/generic_mod_demod.py. \subsection digital_generic_mod Generic Modulator The modulator constructor looks like:
    digital.generic_mod(constellation, differential, samples_per_symbol,
                        pre_diff_code, excess_bw, verbose, log)
The 'constellation' arg is a constellation object as defined above in \ref digital_constellations and can represent any constellation mapping. The 'differential' arg is a bool to turn differential coding on/off. The block also performs pulse shaping and interpolates the pulse-shaped filter to some number of 'samples_per_symbol'. The pulse shaping is a root raised cosine filter defined by the excess bandwidth (or alpha) parameter called 'excess_bw.' We can also turn on a verbose mode to output information to the user. The 'log' parameter toggles logging data on/off. When logging is turned on, it stores every stage of the modulation to a different file so that each stage can be independently analyzed. \subsection digital_generic_demod Generic Demodulator The demodulator looks like:
    digital.generic_demod(constellation, differential, samples_per_symbol,
                          pre_diff_code, excess_bw, freq_bw, timing_bw,
                          phase_bw, verbose, log)
The additional parameters to the demodulator are the loop bandwidths for the different signal recovery loops used internally. There are separate loops for frequency acquisition, timing acquisition, and fine frequency / phase acquisition, controlled in tern by each of the three 'X_bw' arguments. Otherwise, the arguments are the same as the modulator. \subsection digital_generic_guts Guts of the Modulator and Demodulator The generic modulator looks like the following:
    blocks.packed_to_unpacked_bb: takes in packed bytes
    digital.map_bb: maps baseband symbols to the pre-differential encoding
    digital.diff_encoder_bb: differentially encode symbols
    digital.chunks_to_symbols_bc: convert symbols to complex samples
    filter.pfb_arb_resampler_ccf: perform upsampling to samps/symbol and pulse shape
The mapping and chunks-to-symbols stages are done using the information provided by the constellation object. Note that the modulator takes in packed bytes, which means that all 8 bits per byte are used and unpacked into k bits per symbol. The generic demodulator looks like the following:
    digital.fll_band_edge_cc: Performs coarse frequency correction
    digital.pfb_clock_sync_ccf: Matched filtering and timing recovery
    digital.constellation_receiver_cb: Phase tracking and decision making (hard bits)
    digital.diff_decoder_bb: Differential decoding
    digital.map_bb: Map to pre-differential symbols
    blocks.unpack_k_bits_bb: Unpack k bits/symbol to a stream of bits
This block outputs unpacked bits, so each output item represents a single bit of data. A block like 'pack_k_bits' can be used following this to convert the data back into bytes. \section digital_softbits Support for Soft Decisions To support soft decisions of the receivers instead of the current hard decisions, the constellation objects also accept a soft decision look-up table (LUT) or can be told to generate a LUT based on the constellation points and symbol map. All constellation objects can accept a new LUT using the gr::digital::constellation::set_soft_dec_lut function. This function takes in a LUT, which is a vector of floating point tuples (in C++ it is just a vector\\>) and a precision value that specifies how accurate the LUT is to a given number of bits. The constellation objects also have two functions to calculate the soft decisions from their constellation and symbol map. The gr::digital::constellation::calc_soft_dec takes a complex number (and optional noise power) and returns the soft decisions as a list of floats. This function is used internally in the gr::digital::constellation::gen_soft_dec_lut, which takes in the LUT's precision (as a number of bits) and an optional noise power estimate, if known. This function calculates the soft decisions itself. These functions are very expensive because each constellation point is taken into account during the calculation. We provide the gr::digital::constellation::set_soft_dec_lut in order to allow users to use one of the many known approximations to more quickly generate the soft decision LUT. The gr::digital::constellation::calc_soft_dec function could be used instead of drawing directly from a LUT, which is probably only important if the noise floor or channel estimates are likely to change and we want to account for this in the decisions. The basic implementation of the soft decision calculation is the full calculation based on the distance between the sample and all points in the constellation space. If using this function for real-time decisions, a new object should inherit from the gr::digital::constellation class (or whichever child class is being used) and redefine this function with a faster approximation calculation. Note: If no soft decision LUT is defined but gr::digital::constellation::soft_decision_maker is called then the full calculation from gr::digital::constellation::calc_soft_dec is used by default. The LUT is a list of tuples, where each index of the list is some quantized (to some number of bits of precision) point in the constellation space. At each index, there is a tuple of \e k soft bit values for a constellation with \e k bits/symbol. To help with this, the file gr-digital/python/digital/soft_dec_lut_gen.py can be used to create these tables. The function digital.soft_dec_table_generator(generator, precision) function generates a LUT based on some generator function and the number of bits of precision required. This file contains documentation explaining the system better. Or the digital.soft_dec_table(constel, symbols, prec, npwr=1) can be used which takes in the constellation map and symbols to do the full raw calculation of the softbits as opposed to a generator function. To further aid the LUT creation, the digital module also defines a number of functions that can be used as soft decision generators for the soft_dec_table function. These functions are found in psk_constellations.py and qam_constellations.py. These files were already mentioned as they contain a set of functions that return tuples of constellation points and Gray-mapped symbols for different modulations. But these files contain a second set of functions prefixed by 'sd_' which are soft decision LUT generator functions Each LUT generator takes in a complex value and returns the tuple of soft decisions for that point in complex space. To aid with this, soft_dec_lut_gen.py defines a 'calc_from_table' function that takes in a complex sample, the precision of the table, and the LUT itself and returns the tuple of soft decisions in the LUT that is closest to the given symbol. Each of these functions can be found directly from the 'digital' Python module. The LUTs are defined from min to max constellation points in both the real and imaginary axes. That means that signals coming in outside of these bounds are clipped to 1. So there is no added certainty for values beyond these bounds. The gr::digital::constellation_soft_decoder_cf block takes in a constellation object where a soft decision LUT is defined. It takes in complex samples and produces a stream of floats of soft decisions. The soft decision outputs are not grouped together, it is just a stream of floats. So this block acts as an interpolator that takes in 1 complex sample and return \e k float for \e k bits per symbol. \subsection soft_dec_api Review of the Soft Decision API/Functions Files of interest: \li psk_constellations.py: PSK constellations and soft decision generators \li qam_constellations.py: QAM constellations and soft decision generators \li soft_dec_lut_gen.py: Functions to build soft decision LUTs and test them \li test_soft_decisions.py: A script that generates a random complex sample and calculates the soft decisions using various methods. Plots the sample against the full constellation. Requires matplotlib installed. Functions: \li digital.sd_psk_2_*: Returns (constellation, symbol_map) lists for different rotations for BPSK. \li digital.sd_psk_4_*: Returns (constellation, symbol_map) lists for different rotations for QPSK. \li digital.sd_qam_16_*: Returns (constellation, symbol_map) lists for different rotations for 16QAM. \li digital.soft_dec_table_generator: Takes in a generator function (like the digital.sd_XXX above) and creates a LUT to a specific precision. \li digital.soft_dec_table: Takes in a constellation/symbol map and uses digital.calc_soft_dec to generate a LUT to a specific precision. \li digital.calc_soft_dec: Takes a complex sample and calculates the soft decisions for a given constellation/symbol mapping. \li digital.calc_soft_dec_from_table: Given a sample and a LUT, returns the soft decisions of the LUT for the nearest point to the sample. C++ Interface: \li gr::digital::constellation::gen_soft_dec_lut: uses calc_soft_dec to internally generate a soft decision LUT. \li gr::digital::constellation::calc_soft_dec: calculates the soft decisions for a given sample from the full constellation/symbol map. \li gr::digital::constellation::set_soft_dec_lut: Set the soft decision LUT from an externally-calculated LUT. \li gr::digital::constellation::has_soft_dec_lut: has the LUT been set/generated or not. \li gr::digital::constellation::soft_decision_maker: Used by gr::digital::constellation_soft_decoder to convert samples to soft decisions. If a LUT is defined, uses it; else, uses calc_soft_dec. */ gnuradio-3.7.2.1/gr-digital/doc/README.digital0000644000175000017500000000066711700377701020422 0ustar jcorganjcorganThis is the gr-digital package. It contains all of the digital modulation blocks, utilities, and examples. To use the digital blocks, the Python namespaces is in gnuradio.digital, which would be normally imported as: from gnuradio import digital See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(digital) gnuradio-3.7.2.1/gr-digital/python/0000775000175000017500000000000012207440367016675 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/python/digital/0000775000175000017500000000000012243426635020314 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/python/digital/ofdm.py0000664000175000017500000007136712207440367021627 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006-2008,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, fft from gnuradio import blocks import digital_swig as digital import ofdm_packet_utils from ofdm_receiver import ofdm_receiver import gnuradio.gr.gr_threading as _threading import psk, qam # ///////////////////////////////////////////////////////////////////////////// # mod/demod with packets as i/o # ///////////////////////////////////////////////////////////////////////////// class ofdm_mod(gr.hier_block2): """ Modulates an OFDM stream. Based on the options fft_length, occupied_tones, and cp_length, this block creates OFDM symbols using a specified modulation option. Send packets by calling send_pkt """ def __init__(self, options, msgq_limit=2, pad_for_usrp=True): """ Hierarchical block for sending packets Packets to be sent are enqueued by calling send_pkt. The output is the complex modulated signal at baseband. Args: options: pass modulation options from higher layers (fft length, occupied tones, etc.) msgq_limit: maximum number of messages in message queue (int) pad_for_usrp: If true, packets are padded such that they end up a multiple of 128 samples """ gr.hier_block2.__init__(self, "ofdm_mod", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._pad_for_usrp = pad_for_usrp self._modulation = options.modulation self._fft_length = options.fft_length self._occupied_tones = options.occupied_tones self._cp_length = options.cp_length win = [] #[1 for i in range(self._fft_length)] # Use freq domain to get doubled-up known symbol for correlation in time domain zeros_on_left = int(math.ceil((self._fft_length - self._occupied_tones)/2.0)) ksfreq = known_symbols_4512_3[0:self._occupied_tones] for i in range(len(ksfreq)): if((zeros_on_left + i) & 1): ksfreq[i] = 0 # hard-coded known symbols preambles = (ksfreq,) padded_preambles = list() for pre in preambles: padded = self._fft_length*[0,] padded[zeros_on_left : zeros_on_left + self._occupied_tones] = pre padded_preambles.append(padded) symbol_length = options.fft_length + options.cp_length mods = {"bpsk": 2, "qpsk": 4, "8psk": 8, "qam8": 8, "qam16": 16, "qam64": 64, "qam256": 256} arity = mods[self._modulation] rot = 1 if self._modulation == "qpsk": rot = (0.707+0.707j) # FIXME: pass the constellation objects instead of just the points if(self._modulation.find("psk") >= 0): constel = psk.psk_constellation(arity) rotated_const = map(lambda pt: pt * rot, constel.points()) elif(self._modulation.find("qam") >= 0): constel = qam.qam_constellation(arity) rotated_const = map(lambda pt: pt * rot, constel.points()) #print rotated_const self._pkt_input = digital.ofdm_mapper_bcv(rotated_const, msgq_limit, options.occupied_tones, options.fft_length) self.preambles = digital.ofdm_insert_preamble(self._fft_length, padded_preambles) self.ifft = fft.fft_vcc(self._fft_length, False, win, True) self.cp_adder = digital.ofdm_cyclic_prefixer(self._fft_length, symbol_length) self.scale = blocks.multiply_const_cc(1.0 / math.sqrt(self._fft_length)) self.connect((self._pkt_input, 0), (self.preambles, 0)) self.connect((self._pkt_input, 1), (self.preambles, 1)) self.connect(self.preambles, self.ifft, self.cp_adder, self.scale, self) if options.verbose: self._print_verbage() if options.log: self.connect(self._pkt_input, blocks.file_sink(gr.sizeof_gr_complex*options.fft_length, "ofdm_mapper_c.dat")) self.connect(self.preambles, blocks.file_sink(gr.sizeof_gr_complex*options.fft_length, "ofdm_preambles.dat")) self.connect(self.ifft, blocks.file_sink(gr.sizeof_gr_complex*options.fft_length, "ofdm_ifft_c.dat")) self.connect(self.cp_adder, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_cp_adder_c.dat")) def send_pkt(self, payload='', eof=False): """ Send the payload. Args: payload: data to send (string) """ if eof: msg = gr.message(1) # tell self._pkt_input we're not sending any more packets else: # print "original_payload =", string_to_hex_list(payload) pkt = ofdm_packet_utils.make_packet(payload, 1, 1, self._pad_for_usrp, whitening=True) #print "pkt =", string_to_hex_list(pkt) msg = gr.message_from_string(pkt) self._pkt_input.msgq().insert_tail(msg) def add_options(normal, expert): """ Adds OFDM-specific options to the Options Parser """ normal.add_option("-m", "--modulation", type="string", default="bpsk", help="set modulation type (bpsk, qpsk, 8psk, qam{16,64}) [default=%default]") expert.add_option("", "--fft-length", type="intx", default=512, help="set the number of FFT bins [default=%default]") expert.add_option("", "--occupied-tones", type="intx", default=200, help="set the number of occupied FFT bins [default=%default]") expert.add_option("", "--cp-length", type="intx", default=128, help="set the number of bits in the cyclic prefix [default=%default]") # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the OFDM modulator """ print "\nOFDM Modulator:" print "Modulation Type: %s" % (self._modulation) print "FFT length: %3d" % (self._fft_length) print "Occupied Tones: %3d" % (self._occupied_tones) print "CP length: %3d" % (self._cp_length) class ofdm_demod(gr.hier_block2): """ Demodulates a received OFDM stream. Based on the options fft_length, occupied_tones, and cp_length, this block performs synchronization, FFT, and demodulation of incoming OFDM symbols and passes packets up the a higher layer. The input is complex baseband. When packets are demodulated, they are passed to the app via the callback. """ def __init__(self, options, callback=None): """ Hierarchical block for demodulating and deframing packets. The input is the complex modulated signal at baseband. Demodulated packets are sent to the handler. Args: options: pass modulation options from higher layers (fft length, occupied tones, etc.) callback: function of two args: ok, payload (ok: bool; payload: string) """ gr.hier_block2.__init__(self, "ofdm_demod", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._rcvd_pktq = gr.msg_queue() # holds packets from the PHY self._modulation = options.modulation self._fft_length = options.fft_length self._occupied_tones = options.occupied_tones self._cp_length = options.cp_length self._snr = options.snr # Use freq domain to get doubled-up known symbol for correlation in time domain zeros_on_left = int(math.ceil((self._fft_length - self._occupied_tones)/2.0)) ksfreq = known_symbols_4512_3[0:self._occupied_tones] for i in range(len(ksfreq)): if((zeros_on_left + i) & 1): ksfreq[i] = 0 # hard-coded known symbols preambles = (ksfreq,) symbol_length = self._fft_length + self._cp_length self.ofdm_recv = ofdm_receiver(self._fft_length, self._cp_length, self._occupied_tones, self._snr, preambles, options.log) mods = {"bpsk": 2, "qpsk": 4, "8psk": 8, "qam8": 8, "qam16": 16, "qam64": 64, "qam256": 256} arity = mods[self._modulation] rot = 1 if self._modulation == "qpsk": rot = (0.707+0.707j) # FIXME: pass the constellation objects instead of just the points if(self._modulation.find("psk") >= 0): constel = psk.psk_constellation(arity) rotated_const = map(lambda pt: pt * rot, constel.points()) elif(self._modulation.find("qam") >= 0): constel = qam.qam_constellation(arity) rotated_const = map(lambda pt: pt * rot, constel.points()) #print rotated_const phgain = 0.25 frgain = phgain*phgain / 4.0 self.ofdm_demod = digital.ofdm_frame_sink(rotated_const, range(arity), self._rcvd_pktq, self._occupied_tones, phgain, frgain) self.connect(self, self.ofdm_recv) self.connect((self.ofdm_recv, 0), (self.ofdm_demod, 0)) self.connect((self.ofdm_recv, 1), (self.ofdm_demod, 1)) # added output signature to work around bug, though it might not be a bad # thing to export, anyway self.connect(self.ofdm_recv.chan_filt, self) if options.log: self.connect(self.ofdm_demod, blocks.file_sink(gr.sizeof_gr_complex*self._occupied_tones, "ofdm_frame_sink_c.dat")) else: self.connect(self.ofdm_demod, blocks.null_sink(gr.sizeof_gr_complex*self._occupied_tones)) if options.verbose: self._print_verbage() self._watcher = _queue_watcher_thread(self._rcvd_pktq, callback) def add_options(normal, expert): """ Adds OFDM-specific options to the Options Parser """ normal.add_option("-m", "--modulation", type="string", default="bpsk", help="set modulation type (bpsk or qpsk) [default=%default]") expert.add_option("", "--fft-length", type="intx", default=512, help="set the number of FFT bins [default=%default]") expert.add_option("", "--occupied-tones", type="intx", default=200, help="set the number of occupied FFT bins [default=%default]") expert.add_option("", "--cp-length", type="intx", default=128, help="set the number of bits in the cyclic prefix [default=%default]") expert.add_option("", "--snr", type="float", default=30.0, help="SNR estimate [default=%default]") # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the OFDM demodulator """ print "\nOFDM Demodulator:" print "Modulation Type: %s" % (self._modulation) print "FFT length: %3d" % (self._fft_length) print "Occupied Tones: %3d" % (self._occupied_tones) print "CP length: %3d" % (self._cp_length) class _queue_watcher_thread(_threading.Thread): def __init__(self, rcvd_pktq, callback): _threading.Thread.__init__(self) self.setDaemon(1) self.rcvd_pktq = rcvd_pktq self.callback = callback self.keep_running = True self.start() def run(self): while self.keep_running: msg = self.rcvd_pktq.delete_head() ok, payload = ofdm_packet_utils.unmake_packet(msg.to_string()) if self.callback: self.callback(ok, payload) # Generating known symbols with: # i = [2*random.randint(0,1)-1 for i in range(4512)] known_symbols_4512_3 = [-1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, -1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, 1, 1, -1, 1, -1] gnuradio-3.7.2.1/gr-digital/python/digital/generic_mod_demod.py0000664000175000017500000004141412207440367024313 0ustar jcorganjcorgan# # Copyright 2005,2006,2007,2009,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # See gnuradio-examples/python/digital for examples """ Generic modulation and demodulation. """ from gnuradio import gr from modulation_utils import extract_kwargs_from_options_for_class from utils import mod_codes import digital_swig as digital import math try: from gnuradio import blocks except ImportError: import blocks_swig as blocks try: from gnuradio import filter except ImportError: import filter_swig as filter try: from gnuradio import analog except ImportError: import analog_swig as analog # default values (used in __init__ and add_options) _def_samples_per_symbol = 2 _def_excess_bw = 0.35 _def_verbose = False _def_log = False # Frequency correction _def_freq_bw = 2*math.pi/100.0 # Symbol timing recovery _def_timing_bw = 2*math.pi/100.0 _def_timing_max_dev = 1.5 # Fine frequency / Phase correction _def_phase_bw = 2*math.pi/100.0 # Number of points in constellation _def_constellation_points = 16 # Whether differential coding is used. _def_differential = False def add_common_options(parser): """ Sets options common to both modulator and demodulator. """ parser.add_option("-p", "--constellation-points", type="int", default=_def_constellation_points, help="set the number of constellation points (must be a power of 2 for psk, power of 4 for QAM) [default=%default]") parser.add_option("", "--non-differential", action="store_false", dest="differential", help="do not use differential encoding [default=False]") parser.add_option("", "--differential", action="store_true", dest="differential", default=True, help="use differential encoding [default=%default]") parser.add_option("", "--mod-code", type="choice", choices=mod_codes.codes, default=mod_codes.NO_CODE, help="Select modulation code from: %s [default=%%default]" % (', '.join(mod_codes.codes),)) parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw, help="set RRC excess bandwith factor [default=%default]") # ///////////////////////////////////////////////////////////////////////////// # Generic modulator # ///////////////////////////////////////////////////////////////////////////// class generic_mod(gr.hier_block2): """ Hierarchical block for RRC-filtered differential generic modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation: determines the modulation type (gnuradio.digital.digital_constellation) samples_per_symbol: samples per baud >= 2 (float) differential: whether to use differential encoding (boolean) pre_diff_code: whether to use apply a pre-differential mapping (boolean) excess_bw: Root-raised cosine filter excess bandwidth (float) verbose: Print information about modulator? (boolean) log: Log modulation data to files? (boolean) """ def __init__(self, constellation, differential=_def_differential, samples_per_symbol=_def_samples_per_symbol, pre_diff_code=True, excess_bw=_def_excess_bw, verbose=_def_verbose, log=_def_log): gr.hier_block2.__init__(self, "generic_mod", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._constellation = constellation self._samples_per_symbol = samples_per_symbol self._excess_bw = excess_bw self._differential = differential # Only apply a predifferential coding if the constellation also supports it. self.pre_diff_code = pre_diff_code and self._constellation.apply_pre_diff_code() if self._samples_per_symbol < 2: raise TypeError, ("sbp must be >= 2, is %f" % self._samples_per_symbol) arity = pow(2,self.bits_per_symbol()) # turn bytes into k-bit vectors self.bytes2chunks = \ blocks.packed_to_unpacked_bb(self.bits_per_symbol(), gr.GR_MSB_FIRST) if self.pre_diff_code: self.symbol_mapper = digital.map_bb(self._constellation.pre_diff_code()) if differential: self.diffenc = digital.diff_encoder_bb(arity) self.chunks2symbols = digital.chunks_to_symbols_bc(self._constellation.points()) # pulse shaping filter nfilts = 32 ntaps = nfilts * 11 * int(self._samples_per_symbol) # make nfilts filters of ntaps each self.rrc_taps = filter.firdes.root_raised_cosine( nfilts, # gain nfilts, # sampling rate based on 32 filters in resampler 1.0, # symbol rate self._excess_bw, # excess bandwidth (roll-off factor) ntaps) self.rrc_filter = filter.pfb_arb_resampler_ccf(self._samples_per_symbol, self.rrc_taps) # Connect self._blocks = [self, self.bytes2chunks] if self.pre_diff_code: self._blocks.append(self.symbol_mapper) if differential: self._blocks.append(self.diffenc) self._blocks += [self.chunks2symbols, self.rrc_filter, self] self.connect(*self._blocks) if verbose: self._print_verbage() if log: self._setup_logging() def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self): # static method that's also callable on an instance return self._constellation.bits_per_symbol() def add_options(parser): """ Adds generic modulation options to the standard parser """ add_common_options(parser) add_options=staticmethod(add_options) def extract_kwargs_from_options(cls, options): """ Given command line options, create dictionary suitable for passing to __init__ """ return extract_kwargs_from_options_for_class(cls, options) extract_kwargs_from_options=classmethod(extract_kwargs_from_options) def _print_verbage(self): print "\nModulator:" print "bits per symbol: %d" % self.bits_per_symbol() print "RRC roll-off factor: %.2f" % self._excess_bw def _setup_logging(self): print "Modulation logging turned on." self.connect(self.bytes2chunks, blocks.file_sink(gr.sizeof_char, "tx_bytes2chunks.8b")) if self.pre_diff_code: self.connect(self.symbol_mapper, blocks.file_sink(gr.sizeof_char, "tx_symbol_mapper.8b")) if self._differential: self.connect(self.diffenc, blocks.file_sink(gr.sizeof_char, "tx_diffenc.8b")) self.connect(self.chunks2symbols, blocks.file_sink(gr.sizeof_gr_complex, "tx_chunks2symbols.32fc")) self.connect(self.rrc_filter, blocks.file_sink(gr.sizeof_gr_complex, "tx_rrc_filter.32fc")) # ///////////////////////////////////////////////////////////////////////////// # Generic demodulator # # Differentially coherent detection of differentially encoded generically # modulated signal. # ///////////////////////////////////////////////////////////////////////////// class generic_demod(gr.hier_block2): """ Hierarchical block for RRC-filtered differential generic demodulation. The input is the complex modulated signal at baseband. The output is a stream of bits packed 1 bit per byte (LSB) Args: constellation: determines the modulation type (gnuradio.digital.digital_constellation) samples_per_symbol: samples per baud >= 2 (float) differential: whether to use differential encoding (boolean) pre_diff_code: whether to use apply a pre-differential mapping (boolean) excess_bw: Root-raised cosine filter excess bandwidth (float) freq_bw: loop filter lock-in bandwidth (float) timing_bw: timing recovery loop lock-in bandwidth (float) phase_bw: phase recovery loop bandwidth (float) verbose: Print information about modulator? (boolean) log: Log modulation data to files? (boolean) """ def __init__(self, constellation, differential=_def_differential, samples_per_symbol=_def_samples_per_symbol, pre_diff_code=True, excess_bw=_def_excess_bw, freq_bw=_def_freq_bw, timing_bw=_def_timing_bw, phase_bw=_def_phase_bw, verbose=_def_verbose, log=_def_log): gr.hier_block2.__init__(self, "generic_demod", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_char)) # Output signature self._constellation = constellation self._samples_per_symbol = samples_per_symbol self._excess_bw = excess_bw self._phase_bw = phase_bw self._freq_bw = freq_bw self._timing_bw = timing_bw self._timing_max_dev= _def_timing_max_dev self._differential = differential if self._samples_per_symbol < 2: raise TypeError, ("sbp must be >= 2, is %d" % self._samples_per_symbol) # Only apply a predifferential coding if the constellation also supports it. self.pre_diff_code = pre_diff_code and self._constellation.apply_pre_diff_code() arity = pow(2,self.bits_per_symbol()) nfilts = 32 ntaps = 11 * int(self._samples_per_symbol*nfilts) # Automatic gain control self.agc = analog.agc2_cc(0.6e-1, 1e-3, 1, 1) # Frequency correction fll_ntaps = 55 self.freq_recov = digital.fll_band_edge_cc(self._samples_per_symbol, self._excess_bw, fll_ntaps, self._freq_bw) # symbol timing recovery with RRC data filter taps = filter.firdes.root_raised_cosine(nfilts, nfilts*self._samples_per_symbol, 1.0, self._excess_bw, ntaps) self.time_recov = digital.pfb_clock_sync_ccf(self._samples_per_symbol, self._timing_bw, taps, nfilts, nfilts//2, self._timing_max_dev) fmin = -0.25 fmax = 0.25 self.receiver = digital.constellation_receiver_cb( self._constellation.base(), self._phase_bw, fmin, fmax) # Do differential decoding based on phase change of symbols if differential: self.diffdec = digital.diff_decoder_bb(arity) if self.pre_diff_code: self.symbol_mapper = digital.map_bb( mod_codes.invert_code(self._constellation.pre_diff_code())) # unpack the k bit vector into a stream of bits self.unpack = blocks.unpack_k_bits_bb(self.bits_per_symbol()) if verbose: self._print_verbage() if log: self._setup_logging() # Connect and Initialize base class self._blocks = [self, self.agc, self.freq_recov, self.time_recov, self.receiver] if differential: self._blocks.append(self.diffdec) if self.pre_diff_code: self._blocks.append(self.symbol_mapper) self._blocks += [self.unpack, self] self.connect(*self._blocks) def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self): # staticmethod that's also callable on an instance return self._constellation.bits_per_symbol() def _print_verbage(self): print "\nDemodulator:" print "bits per symbol: %d" % self.bits_per_symbol() print "RRC roll-off factor: %.2f" % self._excess_bw print "FLL bandwidth: %.2e" % self._freq_bw print "Timing bandwidth: %.2e" % self._timing_bw print "Phase bandwidth: %.2e" % self._phase_bw def _setup_logging(self): print "Modulation logging turned on." self.connect(self.agc, blocks.file_sink(gr.sizeof_gr_complex, "rx_agc.32fc")) self.connect((self.freq_recov, 0), blocks.file_sink(gr.sizeof_gr_complex, "rx_freq_recov.32fc")) self.connect((self.freq_recov, 1), blocks.file_sink(gr.sizeof_float, "rx_freq_recov_freq.32f")) self.connect((self.freq_recov, 2), blocks.file_sink(gr.sizeof_float, "rx_freq_recov_phase.32f")) self.connect((self.freq_recov, 3), blocks.file_sink(gr.sizeof_float, "rx_freq_recov_error.32f")) self.connect((self.time_recov, 0), blocks.file_sink(gr.sizeof_gr_complex, "rx_time_recov.32fc")) self.connect((self.time_recov, 1), blocks.file_sink(gr.sizeof_float, "rx_time_recov_error.32f")) self.connect((self.time_recov, 2), blocks.file_sink(gr.sizeof_float, "rx_time_recov_rate.32f")) self.connect((self.time_recov, 3), blocks.file_sink(gr.sizeof_float, "rx_time_recov_phase.32f")) self.connect((self.receiver, 0), blocks.file_sink(gr.sizeof_char, "rx_receiver.8b")) self.connect((self.receiver, 1), blocks.file_sink(gr.sizeof_float, "rx_receiver_error.32f")) self.connect((self.receiver, 2), blocks.file_sink(gr.sizeof_float, "rx_receiver_phase.32f")) self.connect((self.receiver, 3), blocks.file_sink(gr.sizeof_float, "rx_receiver_freq.32f")) if self._differential: self.connect(self.diffdec, blocks.file_sink(gr.sizeof_char, "rx_diffdec.8b")) if self.pre_diff_code: self.connect(self.symbol_mapper, blocks.file_sink(gr.sizeof_char, "rx_symbol_mapper.8b")) self.connect(self.unpack, blocks.file_sink(gr.sizeof_char, "rx_unpack.8b")) def add_options(parser): """ Adds generic demodulation options to the standard parser """ # Add options shared with modulator. add_common_options(parser) # Add options specific to demodulator. parser.add_option("", "--freq-bw", type="float", default=_def_freq_bw, help="set frequency lock loop lock-in bandwidth [default=%default]") parser.add_option("", "--phase-bw", type="float", default=_def_phase_bw, help="set phase tracking loop lock-in bandwidth [default=%default]") parser.add_option("", "--timing-bw", type="float", default=_def_timing_bw, help="set timing symbol sync loop gain lock-in bandwidth [default=%default]") add_options=staticmethod(add_options) def extract_kwargs_from_options(cls, options): """ Given command line options, create dictionary suitable for passing to __init__ """ return extract_kwargs_from_options_for_class(cls, options) extract_kwargs_from_options=classmethod(extract_kwargs_from_options) shared_demod_args = """ samples_per_symbol: samples per baud >= 2 (float) excess_bw: Root-raised cosine filter excess bandwidth (float) freq_bw: loop filter lock-in bandwidth (float) timing_bw: timing recovery loop lock-in bandwidth (float) phase_bw: phase recovery loop bandwidth (float) verbose: Print information about modulator? (boolean) log: Log modulation data to files? (boolean) """ shared_mod_args = """ samples_per_symbol: samples per baud >= 2 (float) excess_bw: Root-raised cosine filter excess bandwidth (float) verbose: Print information about modulator? (boolean) log: Log modulation data to files? (boolean) """ gnuradio-3.7.2.1/gr-digital/python/digital/CMakeLists.txt0000664000175000017500000000462212237515112023050 0ustar jcorganjcorgan# Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py bpsk.py constellation_map_generator.py cpm.py crc.py generic_mod_demod.py gmsk.py gfsk.py modulation_utils.py ofdm.py ofdm_packet_utils.py ofdm_receiver.py ofdm_sync_fixed.py ofdm_sync_ml.py ofdm_sync_pnac.py ofdm_sync_pn.py ofdm_txrx.py packet_utils.py pkt.py psk.py psk_constellations.py qam.py qamlike.py qam_constellations.py qpsk.py soft_dec_lut_gen.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/digital COMPONENT "digital_python" ) GR_PYTHON_INSTALL( FILES utils/__init__.py utils/gray_code.py utils/mod_codes.py utils/alignment.py utils/tagged_streams.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/digital/utils COMPONENT "digital_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-digital/python/digital/qa_probe_density.py0000775000175000017500000000412412207440367024217 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_probe_density(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = [0, 1, 0, 1] expected_data = 1 src = blocks.vector_source_b(src_data) op = digital.probe_density_b(1) self.tb.connect(src, op) self.tb.run() result_data = op.density() self.assertEqual(expected_data, result_data) def test_002(self): src_data = [1, 1, 1, 1] expected_data = 1 src = blocks.vector_source_b(src_data) op = digital.probe_density_b(0.01) self.tb.connect(src, op) self.tb.run() result_data = op.density() self.assertEqual(expected_data, result_data) def test_003(self): src_data = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] expected_data = 0.95243 src = blocks.vector_source_b(src_data) op = digital.probe_density_b(0.01) self.tb.connect(src, op) self.tb.run() result_data = op.density() print result_data self.assertAlmostEqual(expected_data, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_probe_density, "test_probe_density.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_packet_headerparser_b.py0000775000175000017500000001646112237515112025647 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import time import random from gnuradio import gr, gr_unittest, blocks, digital from gnuradio.digital.utils import tagged_streams import pmt class qa_packet_headerparser_b (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): """ First header: Packet length 4, packet num 0 Second header: Packet 2, packet num 1 Third header: Invalid (CRC does not check) (would be len 4, num 2) """ encoded_headers = ( # | Number of bytes | Packet number | CRC 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 ) packet_len_tagname = "packet_len" random_tag = gr.tag_t() random_tag.offset = 5 random_tag.key = pmt.string_to_symbol("foo") random_tag.value = pmt.from_long(42) src = blocks.vector_source_b(encoded_headers, tags=(random_tag,)) parser = digital.packet_headerparser_b(32, packet_len_tagname) sink = blocks.message_debug() self.tb.connect(src, parser) self.tb.msg_connect(parser, "header_data", sink, "store") self.tb.start() time.sleep(1) self.tb.stop() self.tb.wait() self.assertEqual(sink.num_messages(), 3) msg1 = pmt.to_python(sink.get_message(0)) msg2 = pmt.to_python(sink.get_message(1)) msg3 = pmt.to_python(sink.get_message(2)) self.assertEqual(msg1, {'packet_len': 4, 'packet_num': 0, 'foo': 42}) self.assertEqual(msg2, {'packet_len': 2, 'packet_num': 1}) self.assertEqual(msg3, False) def test_002_pipe(self): """ Create N packets of random length, pipe them through header generator, back to header parser, make sure output is the same. """ N = 20 header_len = 32 packet_len_tagname = "packet_len" packet_lengths = [random.randint(1, 100) for x in range(N)] data, tags = tagged_streams.packets_to_vectors([range(packet_lengths[i]) for i in range(N)], packet_len_tagname) src = blocks.vector_source_b(data, False, 1, tags) header_gen = digital.packet_headergenerator_bb(header_len, packet_len_tagname) header_parser = digital.packet_headerparser_b(header_len, packet_len_tagname) sink = blocks.message_debug() self.tb.connect(src, header_gen, header_parser) self.tb.msg_connect(header_parser, "header_data", sink, "store") self.tb.start() time.sleep(1) self.tb.stop() self.tb.wait() self.assertEqual(sink.num_messages(), N) for i in xrange(N): msg = pmt.to_python(sink.get_message(i)) self.assertEqual(msg, {'packet_len': packet_lengths[i], 'packet_num': i}) def test_003_ofdm (self): """ Header 1: 193 bytes Header 2: 8 bytes 2 bits per complex symbol, 32 carriers => 64 bits = 8 bytes per OFDM symbol """ encoded_headers = ( # | Number of bytes | Packet number | CRC 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, ) packet_len_tagname = "packet_len" frame_len_tagname = "frame_len" src = blocks.vector_source_b(encoded_headers) header_formatter = digital.packet_header_ofdm( (range(32),), # 32 carriers are occupied (which doesn't matter here) 1, # 1 OFDM symbol per header (= 32 bits) packet_len_tagname, frame_len_tagname, "packet_num", 1, # 1 bit per header symbols (BPSK) 2 # 2 bits per payload symbol (QPSK) ) parser = digital.packet_headerparser_b(header_formatter.base()) sink = blocks.message_debug() self.tb.connect(src, parser) self.tb.msg_connect(parser, "header_data", sink, "store") self.tb.start() time.sleep(1) self.tb.stop() self.tb.wait() self.assertEqual(sink.num_messages(), 2) msg1 = pmt.to_python(sink.get_message(0)) msg2 = pmt.to_python(sink.get_message(1)) # Multiply with 4 because unpacked bytes have only two bits self.assertEqual(msg1, {'packet_len': 193*4, 'frame_len': 25, 'packet_num': 0}) self.assertEqual(msg2, {'packet_len': 8*4, 'frame_len': 1, 'packet_num': 1}) def test_004_ofdm_scramble(self): """ Test scrambling for OFDM header gen """ header_len = 32 packet_length = 23 packet_len_tagname = "packet_len" frame_len_tagname = "frame_len" data, tags = tagged_streams.packets_to_vectors([range(packet_length),range(packet_length),], packet_len_tagname) src = blocks.vector_source_b(data, False, 1, tags) header_formatter = digital.packet_header_ofdm( (range(32),), # 32 carriers are occupied (which doesn't matter here) 1, # 1 OFDM symbol per header (= 32 bits) packet_len_tagname, frame_len_tagname, "packet_num", 1, # 1 bit per header symbols (BPSK) 2, # 2 bits per payload symbol (QPSK) scramble_header=True ) header_gen = digital.packet_headergenerator_bb(header_formatter.base()) header_parser = digital.packet_headerparser_b(header_formatter.base()) sink = blocks.message_debug() self.tb.connect(src, header_gen, header_parser) self.tb.msg_connect(header_parser, "header_data", sink, "store") self.tb.start() time.sleep(1) self.tb.stop() self.tb.wait() msg = pmt.to_python(sink.get_message(0)) self.assertEqual(msg, {'packet_len': packet_length, 'packet_num': 0, 'frame_len': 4}) msg = pmt.to_python(sink.get_message(1)) self.assertEqual(msg, {'packet_len': packet_length, 'packet_num': 1, 'frame_len': 4}) if __name__ == '__main__': gr_unittest.run(qa_packet_headerparser_b, "qa_packet_headerparser_b.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_correlate_access_code.py0000775000175000017500000000617212207440367025651 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks default_access_code = '\xAC\xDD\xA4\xE2\xF2\x8C\x20\xFC' def string_to_1_0_list(s): r = [] for ch in s: x = ord(ch) for i in range(8): t = (x >> i) & 0x1 r.append(t) return r def to_1_0_string(L): return ''.join(map(lambda x: chr(x + ord('0')), L)) class test_correlate_access_code(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): pad = (0,) * 64 # 0 0 0 1 0 0 0 1 src_data = (1, 0, 1, 1, 1, 1, 0, 1, 1) + pad + (0,) * 7 expected_result = pad + (1, 0, 1, 1, 3, 1, 0, 1, 1, 2) + (0,) * 6 src = blocks.vector_source_b(src_data) op = digital.correlate_access_code_bb("1011", 0) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_002(self): code = tuple(string_to_1_0_list(default_access_code)) access_code = to_1_0_string(code) pad = (0,) * 64 #print code #print access_code src_data = code + (1, 0, 1, 1) + pad expected_result = pad + code + (3, 0, 1, 1) src = blocks.vector_source_b(src_data) op = digital.correlate_access_code_bb(access_code, 0) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_003(self): code = tuple(string_to_1_0_list(default_access_code)) access_code = to_1_0_string(code) pad = (0,) * 64 #print code #print access_code src_data = code + (1, 0, 1, 1) + pad expected_result = code + (1, 0, 1, 1) + pad src = blocks.vector_source_b(src_data) op = digital.correlate_access_code_tag_bb(access_code, 0, "test") dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_correlate_access_code, "test_correlate_access_code.xml") gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_sync_fixed.py0000664000175000017500000000365412207440367024034 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr from gnuradio import blocks class ofdm_sync_fixed(gr.hier_block2): def __init__(self, fft_length, cp_length, nsymbols, freq_offset, logging=False): gr.hier_block2.__init__(self, "ofdm_sync_fixed", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature2(2, 2, gr.sizeof_float, gr.sizeof_char)) # Output signature # Use a fixed trigger point instead of sync block symbol_length = fft_length + cp_length pkt_length = nsymbols*symbol_length data = (pkt_length)*[0,] data[(symbol_length)-1] = 1 self.peak_trigger = blocks.vector_source_b(data, True) # Use a pre-defined frequency offset foffset = (pkt_length)*[math.pi*freq_offset,] self.frequency_offset = blocks.vector_source_f(foffset, True) self.connect(self, blocks.null_sink(gr.sizeof_gr_complex)) self.connect(self.frequency_offset, (self,0)) self.connect(self.peak_trigger, (self,1)) if logging: self.connect(self.peak_trigger, blocks.file_sink(gr.sizeof_char, "ofdm_sync_fixed-peaks_b.dat")) gnuradio-3.7.2.1/gr-digital/python/digital/qa_constellation_soft_decoder_cf.py0000664000175000017500000001061512237515112027410 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks from math import sqrt class test_constellation_soft_decoder(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_constellation_soft_decoder_cf_bpsk(self): prec = 8 src_data = (0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, 1+1j) lut = digital.soft_dec_table_generator(digital.sd_psk_2_0x0, prec) expected_result = list() for s in src_data: expected_result += digital.calc_soft_dec_from_table(s, lut, prec, Es=2/sqrt(2)) cnst_pts, code = digital.psk_2_0x0() cnst = digital.constellation_calcdist(cnst_pts, code, 2, 1) cnst.set_soft_dec_lut(lut, int(prec)) src = blocks.vector_source_c(src_data) op = digital.constellation_soft_decoder_cf(cnst.base()) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 4) def test_constellation_soft_decoder_cf_qpsk(self): prec = 8 src_data = (0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, 1+1j) lut = digital.soft_dec_table_generator(digital.sd_psk_4_0x0_0_1, prec) expected_result = list() for s in src_data: expected_result += digital.calc_soft_dec_from_table(s, lut, prec) cnst_pts,code = digital.psk_4_0x0_0_1() cnst = digital.constellation_calcdist(cnst_pts, code, 2, 1) cnst.set_soft_dec_lut(lut, int(prec)) src = blocks.vector_source_c(src_data) op = digital.constellation_soft_decoder_cf(cnst.base()) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 5) def test_constellation_soft_decoder_cf_qam16(self): prec = 8 src_data = (0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j, 1+1j) lut = digital.soft_dec_table_generator(digital.sd_qam_16_0x0_0_1_2_3, prec) expected_result = list() for s in src_data: expected_result += digital.calc_soft_dec_from_table(s, lut, prec) cnst_pts = digital.qam_16_0x0_0_1_2_3() cnst = digital.constellation_calcdist(cnst_pts[0], cnst_pts[1], 2, 1) cnst.set_soft_dec_lut(lut, int(prec)) src = blocks.vector_source_c(src_data) op = digital.constellation_soft_decoder_cf(cnst.base()) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 5) if __name__ == '__main__': gr_unittest.run(test_constellation_soft_decoder, "test_constellation_soft_decoder.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_serializer_vcc.py0000775000175000017500000002456012207450051025357 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy from gnuradio import gr, gr_unittest, blocks, fft, analog, digital import pmt class qa_ofdm_serializer_vcc (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_simple (self): """ Standard test """ fft_len = 16 tx_symbols = (0, 1, 1j, 2, 3, 0, 0, 0, 0, 0, 0, 4, 5, 2j, 6, 0, 0, 7, 8, 3j, 9, 0, 0, 0, 0, 0, 0, 10, 4j, 11, 12, 0, 0, 13, 1j, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 2j, 0, 0) expected_result = tuple(range(1, 16)) + (0, 0, 0) occupied_carriers = ((1, 3, 4, 11, 12, 14), (1, 2, 4, 11, 13, 14),) n_syms = len(tx_symbols)/fft_len tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(n_syms) src = blocks.vector_source_c(tx_symbols, False, fft_len, (tag,)) serializer = digital.ofdm_serializer_vcc(fft_len, occupied_carriers, tag_name, "", 0, "", False) sink = blocks.vector_sink_c() self.tb.connect(src, serializer, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) self.assertEqual(len(sink.tags()), 1) result_tag = sink.tags()[0] self.assertEqual(pmt.symbol_to_string(result_tag.key), tag_name) self.assertEqual(pmt.to_long(result_tag.value), n_syms * len(occupied_carriers[0])) def test_001b_shifted (self): """ Same as before, but shifted, because that's the normal mode in OFDM Rx """ fft_len = 16 tx_symbols = ( 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 6, 1j, 7, 8, 0, 9, 10, 1j, 11, 0, 0, 0, 0, 0, 0, 0, 0, 12, 13, 14, 0, 15, 16, 17, 0, 0, 0, 0, ) expected_result = tuple(range(18)) occupied_carriers = ((13, 14, 15, 1, 2, 3), (-4, -2, -1, 1, 2, 4),) n_syms = len(tx_symbols)/fft_len tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(n_syms) src = blocks.vector_source_c(tx_symbols, False, fft_len, (tag,)) serializer = digital.ofdm_serializer_vcc(fft_len, occupied_carriers, tag_name) sink = blocks.vector_sink_c() self.tb.connect(src, serializer, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) self.assertEqual(len(sink.tags()), 1) result_tag = sink.tags()[0] self.assertEqual(pmt.symbol_to_string(result_tag.key), tag_name) self.assertEqual(pmt.to_long(result_tag.value), n_syms * len(occupied_carriers[0])) def test_002_with_offset (self): """ Standard test, carrier offset """ fft_len = 16 tx_symbols = range(1, 16); tx_symbols = (0, 0, 1, 1j, 2, 3, 0, 0, 0, 0, 0, 0, 4, 5, 2j, 6, 0, 0, 7, 8, 3j, 9, 0, 0, 0, 0, 0, 0, 10, 4j, 11, 12, 0, 0, 13, 1j, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 2j, 0) carr_offset = 1 # Compare this with tx_symbols from the previous test expected_result = tuple(range(1, 16)) + (0, 0, 0) occupied_carriers = ((1, 3, 4, 11, 12, 14), (1, 2, 4, 11, 13, 14),) n_syms = len(tx_symbols)/fft_len tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(n_syms) offsettag = gr.tag_t() offsettag.offset = 0 offsettag.key = pmt.string_to_symbol("ofdm_sync_carr_offset") offsettag.value = pmt.from_long(carr_offset) src = blocks.vector_source_c(tx_symbols, False, fft_len, (tag, offsettag)) sink = blocks.vector_sink_c() serializer = digital.ofdm_serializer_vcc( fft_len, occupied_carriers, tag_name, "", 0, "ofdm_sync_carr_offset", False ) self.tb.connect(src, serializer, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) self.assertEqual(len(sink.tags()), 2) for tag in sink.tags(): if pmt.symbol_to_string(tag.key) == tag_name: self.assertEqual(pmt.to_long(tag.value), n_syms * len(occupied_carriers[0])) def test_003_connect (self): """ Connect carrier_allocator to ofdm_serializer, make sure output==input """ fft_len = 8 n_syms = 1 occupied_carriers = ((1, 2, 6, 7),) pilot_carriers = ((3,),(5,)) pilot_symbols = ((1j,),(-1j,)) #tx_data = tuple([numpy.random.randint(0, 10) for x in range(4 * n_syms)]) tx_data = (1, 2, 3, 4) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(tx_data)) src = blocks.vector_source_c(tx_data, False, 1, (tag,)) alloc = digital.ofdm_carrier_allocator_cvc( fft_len, occupied_carriers, pilot_carriers, pilot_symbols, (), # No sync word tag_name, True # Output is shifted (default) ) serializer = digital.ofdm_serializer_vcc( alloc, "", # Len tag key 0, # Symbols skipped "", # Carrier offset key True # Input is shifted (default) ) sink = blocks.vector_sink_c() self.tb.connect(src, alloc, serializer, sink) self.tb.run () self.assertEqual(sink.data(), tx_data) def test_004_connect (self): """ Advanced test: - Allocator -> IFFT -> Frequency offset -> FFT -> Serializer - FFT does shift (moves DC to middle) - Make sure input == output - Frequency offset is -2 carriers """ fft_len = 8 n_syms = 1 carr_offset = -2 freq_offset = 1.0 / fft_len * carr_offset # Normalized frequency occupied_carriers = ((-2, -1, 1, 2),) pilot_carriers = ((-3,),(3,)) pilot_symbols = ((1j,),(-1j,)) tx_data = (1, 2, 3, 4) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(tx_data)) offsettag = gr.tag_t() offsettag.offset = 0 offsettag.key = pmt.string_to_symbol("ofdm_sync_carr_offset") offsettag.value = pmt.from_long(carr_offset) src = blocks.vector_source_c(tx_data, False, 1, (tag, offsettag)) alloc = digital.ofdm_carrier_allocator_cvc(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, (), tag_name) tx_ifft = fft.fft_vcc(fft_len, False, (1.0/fft_len,)*fft_len, True) oscillator = analog.sig_source_c(1.0, analog.GR_COS_WAVE, freq_offset, 1.0) mixer = blocks.multiply_cc() rx_fft = fft.fft_vcc(fft_len, True, (), True) sink2 = blocks.vector_sink_c(fft_len) self.tb.connect(rx_fft, sink2) serializer = digital.ofdm_serializer_vcc( alloc, "", 0, "ofdm_sync_carr_offset", True ) sink = blocks.vector_sink_c() self.tb.connect( src, alloc, tx_ifft, blocks.vector_to_stream(gr.sizeof_gr_complex, fft_len), (mixer, 0), blocks.stream_to_vector(gr.sizeof_gr_complex, fft_len), rx_fft, serializer, sink ) self.tb.connect(oscillator, (mixer, 1)) self.tb.run () self.assertComplexTuplesAlmostEqual(sink.data()[-len(occupied_carriers[0]):], tx_data, places=4) def test_005_packet_len_tag (self): """ Standard test """ fft_len = 16 tx_symbols = range(1, 16); tx_symbols = (0, 1, 1j, 2, 3, 0, 0, 0, 0, 0, 0, 4, 5, 2j, 6, 0, 0, 7, 8, 3j, 9, 0, 0, 0, 0, 0, 0, 10, 4j, 11, 12, 0, 0, 13, 1j, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 2j, 0, 0) expected_result = tuple(range(1, 16)) occupied_carriers = ((1, 3, 4, 11, 12, 14), (1, 2, 4, 11, 13, 14),) n_syms = len(tx_symbols)/fft_len tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(n_syms) tag2 = gr.tag_t() tag2.offset = 0 tag2.key = pmt.string_to_symbol("packet_len") tag2.value = pmt.from_long(len(expected_result)) src = blocks.vector_source_c(tx_symbols, False, fft_len, (tag, tag2)) serializer = digital.ofdm_serializer_vcc(fft_len, occupied_carriers, tag_name, "packet_len", 0, "", False) sink = blocks.vector_sink_c() self.tb.connect(src, serializer, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) self.assertEqual(len(sink.tags()), 1) result_tag = sink.tags()[0] self.assertEqual(pmt.symbol_to_string(result_tag.key), "packet_len") self.assertEqual(pmt.to_long(result_tag.value), len(expected_result)) def test_099 (self): """ Make sure it fails if it should """ fft_len = 16 occupied_carriers = ((1, 3, 4, 11, 12, 112),) tag_name = "len" self.assertRaises(RuntimeError, digital.ofdm_serializer_vcc, fft_len, occupied_carriers, tag_name) if __name__ == '__main__': gr_unittest.run(qa_ofdm_serializer_vcc, "qa_ofdm_serializer_vcc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/packet_utils.py0000664000175000017500000006645712237515112023367 0ustar jcorganjcorgan# # Copyright 2005,2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import struct import numpy from gnuradio import gru import crc def conv_packed_binary_string_to_1_0_string(s): """ '\xAF' --> '10101111' """ r = [] for ch in s: x = ord(ch) for i in range(7,-1,-1): t = (x >> i) & 0x1 r.append(t) return ''.join(map(lambda x: chr(x + ord('0')), r)) def conv_1_0_string_to_packed_binary_string(s): """ '10101111' -> ('\xAF', False) Basically the inverse of conv_packed_binary_string_to_1_0_string, but also returns a flag indicating if we had to pad with leading zeros to get to a multiple of 8. """ if not is_1_0_string(s): raise ValueError, "Input must be a string containing only 0's and 1's" # pad to multiple of 8 padded = False rem = len(s) % 8 if rem != 0: npad = 8 - rem s = '0' * npad + s padded = True assert len(s) % 8 == 0 r = [] i = 0 while i < len(s): t = 0 for j in range(8): t = (t << 1) | (ord(s[i + j]) - ord('0')) r.append(chr(t)) i += 8 return (''.join(r), padded) default_access_code = \ conv_packed_binary_string_to_1_0_string('\xAC\xDD\xA4\xE2\xF2\x8C\x20\xFC') default_preamble = \ conv_packed_binary_string_to_1_0_string('\xA4\xF2') def is_1_0_string(s): if not isinstance(s, str): return False for ch in s: if not ch in ('0', '1'): return False return True def string_to_hex_list(s): return map(lambda x: hex(ord(x)), s) def whiten(s, o): sa = numpy.fromstring(s, numpy.uint8) z = sa ^ random_mask_vec8[o:len(sa)+o] return z.tostring() def dewhiten(s, o): return whiten(s, o) # self inverse def make_header(payload_len, whitener_offset=0): # Upper nibble is offset, lower 12 bits is len val = ((whitener_offset & 0xf) << 12) | (payload_len & 0x0fff) #print "offset =", whitener_offset, " len =", payload_len, " val=", val return struct.pack('!HH', val, val) def make_packet(payload, samples_per_symbol, bits_per_symbol, preamble=default_preamble, access_code=default_access_code, pad_for_usrp=True, whitener_offset=0, whitening=True): """ Build a packet, given access code, payload, and whitener offset Args: payload: packet payload, len [0, 4096] samples_per_symbol: samples per symbol (needed for padding calculation) (int) bits_per_symbol: (needed for padding calculation) (int) preamble: string of ascii 0's and 1's access_code: string of ascii 0's and 1's whitener_offset: offset into whitener string to use [0-16) Packet will have access code at the beginning, followed by length, payload and finally CRC-32. """ if not is_1_0_string(preamble): raise ValueError, "preamble must be a string containing only 0's and 1's (%r)" % (preamble,) if not is_1_0_string(access_code): raise ValueError, "access_code must be a string containing only 0's and 1's (%r)" % (access_code,) if not whitener_offset >=0 and whitener_offset < 16: raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,) (packed_access_code, padded) = conv_1_0_string_to_packed_binary_string(access_code) (packed_preamble, ignore) = conv_1_0_string_to_packed_binary_string(preamble) payload_with_crc = crc.gen_and_append_crc32(payload) #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:]) L = len(payload_with_crc) MAXLEN = len(random_mask_tuple) if L > MAXLEN: raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,) if whitening: pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset), whiten(payload_with_crc, whitener_offset), '\x55')) else: pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset), (payload_with_crc), '\x55')) if pad_for_usrp: pkt = pkt + (_npadding_bytes(len(pkt), int(samples_per_symbol), bits_per_symbol) * '\x55') #print "make_packet: len(pkt) =", len(pkt) return pkt def _npadding_bytes(pkt_byte_len, samples_per_symbol, bits_per_symbol): """ Generate sufficient padding such that each packet ultimately ends up being a multiple of 512 bytes when sent across the USB. We send 4-byte samples across the USB (16-bit I and 16-bit Q), thus we want to pad so that after modulation the resulting packet is a multiple of 128 samples. Args: ptk_byte_len: len in bytes of packet, not including padding. samples_per_symbol: samples per bit (1 bit / symbolwidth GMSK) (int) bits_per_symbol: bits per symbol (log2(modulation order)) (int) Returns: number of bytes of padding to append. """ modulus = 128 byte_modulus = gru.lcm(modulus/8, samples_per_symbol) * bits_per_symbol / samples_per_symbol r = pkt_byte_len % byte_modulus if r == 0: return 0 return byte_modulus - r def unmake_packet(whitened_payload_with_crc, whitener_offset=0, dewhitening=True): """ Return (ok, payload) Args: whitened_payload_with_crc: string """ if dewhitening: payload_with_crc = dewhiten(whitened_payload_with_crc, whitener_offset) else: payload_with_crc = (whitened_payload_with_crc) ok, payload = crc.check_crc32(payload_with_crc) if 0: print "payload_with_crc =", string_to_hex_list(payload_with_crc) print "ok = %r, len(payload) = %d" % (ok, len(payload)) print "payload =", string_to_hex_list(payload) return ok, payload # FYI, this PN code is the output of a 15-bit LFSR random_mask_tuple = ( 255, 63, 0, 16, 0, 12, 0, 5, 192, 3, 16, 1, 204, 0, 85, 192, 63, 16, 16, 12, 12, 5, 197, 195, 19, 17, 205, 204, 85, 149, 255, 47, 0, 28, 0, 9, 192, 6, 208, 2, 220, 1, 153, 192, 106, 208, 47, 28, 28, 9, 201, 198, 214, 210, 222, 221, 152, 89, 170, 186, 255, 51, 0, 21, 192, 15, 16, 4, 12, 3, 69, 193, 243, 16, 69, 204, 51, 21, 213, 207, 31, 20, 8, 15, 70, 132, 50, 227, 85, 137, 255, 38, 192, 26, 208, 11, 28, 7, 73, 194, 182, 209, 182, 220, 118, 217, 230, 218, 202, 219, 23, 27, 78, 139, 116, 103, 103, 106, 170, 175, 63, 60, 16, 17, 204, 12, 85, 197, 255, 19, 0, 13, 192, 5, 144, 3, 44, 1, 221, 192, 89, 144, 58, 236, 19, 13, 205, 197, 149, 147, 47, 45, 220, 29, 153, 201, 170, 214, 255, 30, 192, 8, 80, 6, 188, 2, 241, 193, 132, 80, 99, 124, 41, 225, 222, 200, 88, 86, 186, 190, 243, 48, 69, 212, 51, 31, 85, 200, 63, 22, 144, 14, 236, 4, 77, 195, 117, 145, 231, 44, 74, 157, 247, 41, 134, 158, 226, 232, 73, 142, 182, 228, 118, 203, 102, 215, 106, 222, 175, 24, 124, 10, 161, 199, 56, 82, 146, 189, 173, 177, 189, 180, 113, 183, 100, 118, 171, 102, 255, 106, 192, 47, 16, 28, 12, 9, 197, 198, 211, 18, 221, 205, 153, 149, 170, 239, 63, 12, 16, 5, 204, 3, 21, 193, 207, 16, 84, 12, 63, 69, 208, 51, 28, 21, 201, 207, 22, 212, 14, 223, 68, 88, 51, 122, 149, 227, 47, 9, 220, 6, 217, 194, 218, 209, 155, 28, 107, 73, 239, 118, 204, 38, 213, 218, 223, 27, 24, 11, 74, 135, 119, 34, 166, 153, 186, 234, 243, 15, 5, 196, 3, 19, 65, 205, 240, 85, 132, 63, 35, 80, 25, 252, 10, 193, 199, 16, 82, 140, 61, 165, 209, 187, 28, 115, 73, 229, 246, 203, 6, 215, 66, 222, 177, 152, 116, 106, 167, 111, 58, 172, 19, 61, 205, 209, 149, 156, 111, 41, 236, 30, 205, 200, 85, 150, 191, 46, 240, 28, 68, 9, 243, 70, 197, 242, 211, 5, 157, 195, 41, 145, 222, 236, 88, 77, 250, 181, 131, 55, 33, 214, 152, 94, 234, 184, 79, 50, 180, 21, 183, 79, 54, 180, 22, 247, 78, 198, 180, 82, 247, 125, 134, 161, 162, 248, 121, 130, 162, 225, 185, 136, 114, 230, 165, 138, 251, 39, 3, 90, 129, 251, 32, 67, 88, 49, 250, 148, 67, 47, 113, 220, 36, 89, 219, 122, 219, 99, 27, 105, 203, 110, 215, 108, 94, 173, 248, 125, 130, 161, 161, 184, 120, 114, 162, 165, 185, 187, 50, 243, 85, 133, 255, 35, 0, 25, 192, 10, 208, 7, 28, 2, 137, 193, 166, 208, 122, 220, 35, 25, 217, 202, 218, 215, 27, 30, 139, 72, 103, 118, 170, 166, 255, 58, 192, 19, 16, 13, 204, 5, 149, 195, 47, 17, 220, 12, 89, 197, 250, 211, 3, 29, 193, 201, 144, 86, 236, 62, 205, 208, 85, 156, 63, 41, 208, 30, 220, 8, 89, 198, 186, 210, 243, 29, 133, 201, 163, 22, 249, 206, 194, 212, 81, 159, 124, 104, 33, 238, 152, 76, 106, 181, 239, 55, 12, 22, 133, 206, 227, 20, 73, 207, 118, 212, 38, 223, 90, 216, 59, 26, 147, 75, 45, 247, 93, 134, 185, 162, 242, 249, 133, 130, 227, 33, 137, 216, 102, 218, 170, 219, 63, 27, 80, 11, 124, 7, 97, 194, 168, 81, 190, 188, 112, 113, 228, 36, 75, 91, 119, 123, 102, 163, 106, 249, 239, 2, 204, 1, 149, 192, 111, 16, 44, 12, 29, 197, 201, 147, 22, 237, 206, 205, 148, 85, 175, 127, 60, 32, 17, 216, 12, 90, 133, 251, 35, 3, 89, 193, 250, 208, 67, 28, 49, 201, 212, 86, 223, 126, 216, 32, 90, 152, 59, 42, 147, 95, 45, 248, 29, 130, 137, 161, 166, 248, 122, 194, 163, 17, 185, 204, 114, 213, 229, 159, 11, 40, 7, 94, 130, 184, 97, 178, 168, 117, 190, 167, 48, 122, 148, 35, 47, 89, 220, 58, 217, 211, 26, 221, 203, 25, 151, 74, 238, 183, 12, 118, 133, 230, 227, 10, 201, 199, 22, 210, 142, 221, 164, 89, 187, 122, 243, 99, 5, 233, 195, 14, 209, 196, 92, 83, 121, 253, 226, 193, 137, 144, 102, 236, 42, 205, 223, 21, 152, 15, 42, 132, 31, 35, 72, 25, 246, 138, 198, 231, 18, 202, 141, 151, 37, 174, 155, 60, 107, 81, 239, 124, 76, 33, 245, 216, 71, 26, 178, 139, 53, 167, 87, 58, 190, 147, 48, 109, 212, 45, 159, 93, 168, 57, 190, 146, 240, 109, 132, 45, 163, 93, 185, 249, 178, 194, 245, 145, 135, 44, 98, 157, 233, 169, 142, 254, 228, 64, 75, 112, 55, 100, 22, 171, 78, 255, 116, 64, 39, 112, 26, 164, 11, 59, 71, 83, 114, 189, 229, 177, 139, 52, 103, 87, 106, 190, 175, 48, 124, 20, 33, 207, 88, 84, 58, 191, 83, 48, 61, 212, 17, 159, 76, 104, 53, 238, 151, 12, 110, 133, 236, 99, 13, 233, 197, 142, 211, 36, 93, 219, 121, 155, 98, 235, 105, 143, 110, 228, 44, 75, 93, 247, 121, 134, 162, 226, 249, 137, 130, 230, 225, 138, 200, 103, 22, 170, 142, 255, 36, 64, 27, 112, 11, 100, 7, 107, 66, 175, 113, 188, 36, 113, 219, 100, 91, 107, 123, 111, 99, 108, 41, 237, 222, 205, 152, 85, 170, 191, 63, 48, 16, 20, 12, 15, 69, 196, 51, 19, 85, 205, 255, 21, 128, 15, 32, 4, 24, 3, 74, 129, 247, 32, 70, 152, 50, 234, 149, 143, 47, 36, 28, 27, 73, 203, 118, 215, 102, 222, 170, 216, 127, 26, 160, 11, 56, 7, 82, 130, 189, 161, 177, 184, 116, 114, 167, 101, 186, 171, 51, 63, 85, 208, 63, 28, 16, 9, 204, 6, 213, 194, 223, 17, 152, 12, 106, 133, 239, 35, 12, 25, 197, 202, 211, 23, 29, 206, 137, 148, 102, 239, 106, 204, 47, 21, 220, 15, 25, 196, 10, 211, 71, 29, 242, 137, 133, 166, 227, 58, 201, 211, 22, 221, 206, 217, 148, 90, 239, 123, 12, 35, 69, 217, 243, 26, 197, 203, 19, 23, 77, 206, 181, 148, 119, 47, 102, 156, 42, 233, 223, 14, 216, 4, 90, 131, 123, 33, 227, 88, 73, 250, 182, 195, 54, 209, 214, 220, 94, 217, 248, 90, 194, 187, 17, 179, 76, 117, 245, 231, 7, 10, 130, 135, 33, 162, 152, 121, 170, 162, 255, 57, 128, 18, 224, 13, 136, 5, 166, 131, 58, 225, 211, 8, 93, 198, 185, 146, 242, 237, 133, 141, 163, 37, 185, 219, 50, 219, 85, 155, 127, 43, 96, 31, 104, 8, 46, 134, 156, 98, 233, 233, 142, 206, 228, 84, 75, 127, 119, 96, 38, 168, 26, 254, 139, 0, 103, 64, 42, 176, 31, 52, 8, 23, 70, 142, 178, 228, 117, 139, 103, 39, 106, 154, 175, 43, 60, 31, 81, 200, 60, 86, 145, 254, 236, 64, 77, 240, 53, 132, 23, 35, 78, 153, 244, 106, 199, 111, 18, 172, 13, 189, 197, 177, 147, 52, 109, 215, 109, 158, 173, 168, 125, 190, 161, 176, 120, 116, 34, 167, 89, 186, 186, 243, 51, 5, 213, 195, 31, 17, 200, 12, 86, 133, 254, 227, 0, 73, 192, 54, 208, 22, 220, 14, 217, 196, 90, 211, 123, 29, 227, 73, 137, 246, 230, 198, 202, 210, 215, 29, 158, 137, 168, 102, 254, 170, 192, 127, 16, 32, 12, 24, 5, 202, 131, 23, 33, 206, 152, 84, 106, 191, 111, 48, 44, 20, 29, 207, 73, 148, 54, 239, 86, 204, 62, 213, 208, 95, 28, 56, 9, 210, 134, 221, 162, 217, 185, 154, 242, 235, 5, 143, 67, 36, 49, 219, 84, 91, 127, 123, 96, 35, 104, 25, 238, 138, 204, 103, 21, 234, 143, 15, 36, 4, 27, 67, 75, 113, 247, 100, 70, 171, 114, 255, 101, 128, 43, 32, 31, 88, 8, 58, 134, 147, 34, 237, 217, 141, 154, 229, 171, 11, 63, 71, 80, 50, 188, 21, 177, 207, 52, 84, 23, 127, 78, 160, 52, 120, 23, 98, 142, 169, 164, 126, 251, 96, 67, 104, 49, 238, 148, 76, 111, 117, 236, 39, 13, 218, 133, 155, 35, 43, 89, 223, 122, 216, 35, 26, 153, 203, 42, 215, 95, 30, 184, 8, 114, 134, 165, 162, 251, 57, 131, 82, 225, 253, 136, 65, 166, 176, 122, 244, 35, 7, 89, 194, 186, 209, 179, 28, 117, 201, 231, 22, 202, 142, 215, 36, 94, 155, 120, 107, 98, 175, 105, 188, 46, 241, 220, 68, 89, 243, 122, 197, 227, 19, 9, 205, 198, 213, 146, 223, 45, 152, 29, 170, 137, 191, 38, 240, 26, 196, 11, 19, 71, 77, 242, 181, 133, 183, 35, 54, 153, 214, 234, 222, 207, 24, 84, 10, 191, 71, 48, 50, 148, 21, 175, 79, 60, 52, 17, 215, 76, 94, 181, 248, 119, 2, 166, 129, 186, 224, 115, 8, 37, 198, 155, 18, 235, 77, 143, 117, 164, 39, 59, 90, 147, 123, 45, 227, 93, 137, 249, 166, 194, 250, 209, 131, 28, 97, 201, 232, 86, 206, 190, 212, 112, 95, 100, 56, 43, 82, 159, 125, 168, 33, 190, 152, 112, 106, 164, 47, 59, 92, 19, 121, 205, 226, 213, 137, 159, 38, 232, 26, 206, 139, 20, 103, 79, 106, 180, 47, 55, 92, 22, 185, 206, 242, 212, 69, 159, 115, 40, 37, 222, 155, 24, 107, 74, 175, 119, 60, 38, 145, 218, 236, 91, 13, 251, 69, 131, 115, 33, 229, 216, 75, 26, 183, 75, 54, 183, 86, 246, 190, 198, 240, 82, 196, 61, 147, 81, 173, 252, 125, 129, 225, 160, 72, 120, 54, 162, 150, 249, 174, 194, 252, 81, 129, 252, 96, 65, 232, 48, 78, 148, 52, 111, 87, 108, 62, 173, 208, 125, 156, 33, 169, 216, 126, 218, 160, 91, 56, 59, 82, 147, 125, 173, 225, 189, 136, 113, 166, 164, 122, 251, 99, 3, 105, 193, 238, 208, 76, 92, 53, 249, 215, 2, 222, 129, 152, 96, 106, 168, 47, 62, 156, 16, 105, 204, 46, 213, 220, 95, 25, 248, 10, 194, 135, 17, 162, 140, 121, 165, 226, 251, 9, 131, 70, 225, 242, 200, 69, 150, 179, 46, 245, 220, 71, 25, 242, 138, 197, 167, 19, 58, 141, 211, 37, 157, 219, 41, 155, 94, 235, 120, 79, 98, 180, 41, 183, 94, 246, 184, 70, 242, 178, 197, 181, 147, 55, 45, 214, 157, 158, 233, 168, 78, 254, 180, 64, 119, 112, 38, 164, 26, 251, 75, 3, 119, 65, 230, 176, 74, 244, 55, 7, 86, 130, 190, 225, 176, 72, 116, 54, 167, 86, 250, 190, 195, 48, 81, 212, 60, 95, 81, 248, 60, 66, 145, 241, 172, 68, 125, 243, 97, 133, 232, 99, 14, 169, 196, 126, 211, 96, 93, 232, 57, 142, 146, 228, 109, 139, 109, 167, 109, 186, 173, 179, 61, 181, 209, 183, 28, 118, 137, 230, 230, 202, 202, 215, 23, 30, 142, 136, 100, 102, 171, 106, 255, 111, 0, 44, 0, 29, 192, 9, 144, 6, 236, 2, 205, 193, 149, 144, 111, 44, 44, 29, 221, 201, 153, 150, 234, 238, 207, 12, 84, 5, 255, 67, 0, 49, 192, 20, 80, 15, 124, 4, 33, 195, 88, 81, 250, 188, 67, 49, 241, 212, 68, 95, 115, 120, 37, 226, 155, 9, 171, 70, 255, 114, 192, 37, 144, 27, 44, 11, 93, 199, 121, 146, 162, 237, 185, 141, 178, 229, 181, 139, 55, 39, 86, 154, 190, 235, 48, 79, 84, 52, 63, 87, 80, 62, 188, 16, 113, 204, 36, 85, 219, 127, 27, 96, 11, 104, 7, 110, 130, 172, 97, 189, 232, 113, 142, 164, 100, 123, 107, 99, 111, 105, 236, 46, 205, 220, 85, 153, 255, 42, 192, 31, 16, 8, 12, 6, 133, 194, 227, 17, 137, 204, 102, 213, 234, 223, 15, 24, 4, 10, 131, 71, 33, 242, 152, 69, 170, 179, 63, 53, 208, 23, 28, 14, 137, 196, 102, 211, 106, 221, 239, 25, 140, 10, 229, 199, 11, 18, 135, 77, 162, 181, 185, 183, 50, 246, 149, 134, 239, 34, 204, 25, 149, 202, 239, 23, 12, 14, 133, 196, 99, 19, 105, 205, 238, 213, 140, 95, 37, 248, 27, 2, 139, 65, 167, 112, 122, 164, 35, 59, 89, 211, 122, 221, 227, 25, 137, 202, 230, 215, 10, 222, 135, 24, 98, 138, 169, 167, 62, 250, 144, 67, 44, 49, 221, 212, 89, 159, 122, 232, 35, 14, 153, 196, 106, 211, 111, 29, 236, 9, 141, 198, 229, 146, 203, 45, 151, 93, 174, 185, 188, 114, 241, 229, 132, 75, 35, 119, 89, 230, 186, 202, 243, 23, 5, 206, 131, 20, 97, 207, 104, 84, 46, 191, 92, 112, 57, 228, 18, 203, 77, 151, 117, 174, 167, 60, 122, 145, 227, 44, 73, 221, 246, 217, 134, 218, 226, 219, 9, 155, 70, 235, 114, 207, 101, 148, 43, 47, 95, 92, 56, 57, 210, 146, 221, 173, 153, 189, 170, 241, 191, 4, 112, 3, 100, 1, 235, 64, 79, 112, 52, 36, 23, 91, 78, 187, 116, 115, 103, 101, 234, 171, 15, 63, 68, 16, 51, 76, 21, 245, 207, 7, 20, 2, 143, 65, 164, 48, 123, 84, 35, 127, 89, 224, 58, 200, 19, 22, 141, 206, 229, 148, 75, 47, 119, 92, 38, 185, 218, 242, 219, 5, 155, 67, 43, 113, 223, 100, 88, 43, 122, 159, 99, 40, 41, 222, 158, 216, 104, 90, 174, 187, 60, 115, 81, 229, 252, 75, 1, 247, 64, 70, 176, 50, 244, 21, 135, 79, 34, 180, 25, 183, 74, 246, 183, 6, 246, 130, 198, 225, 146, 200, 109, 150, 173, 174, 253, 188, 65, 177, 240, 116, 68, 39, 115, 90, 165, 251, 59, 3, 83, 65, 253, 240, 65, 132, 48, 99, 84, 41, 255, 94, 192, 56, 80, 18, 188, 13, 177, 197, 180, 83, 55, 125, 214, 161, 158, 248, 104, 66, 174, 177, 188, 116, 113, 231, 100, 74, 171, 119, 63, 102, 144, 42, 236, 31, 13, 200, 5, 150, 131, 46, 225, 220, 72, 89, 246, 186, 198, 243, 18, 197, 205, 147, 21, 173, 207, 61, 148, 17, 175, 76, 124, 53, 225, 215, 8, 94, 134, 184, 98, 242, 169, 133, 190, 227, 48, 73, 212, 54, 223, 86, 216, 62, 218, 144, 91, 44, 59, 93, 211, 121, 157, 226, 233, 137, 142, 230, 228, 74, 203, 119, 23, 102, 142, 170, 228, 127, 11, 96, 7, 104, 2, 174, 129, 188, 96, 113, 232, 36, 78, 155, 116, 107, 103, 111, 106, 172, 47, 61, 220, 17, 153, 204, 106, 213, 239, 31, 12, 8, 5, 198, 131, 18, 225, 205, 136, 85, 166, 191, 58, 240, 19, 4, 13, 195, 69, 145, 243, 44, 69, 221, 243, 25, 133, 202, 227, 23, 9, 206, 134, 212, 98, 223, 105, 152, 46, 234, 156, 79, 41, 244, 30, 199, 72, 82, 182, 189, 182, 241, 182, 196, 118, 211, 102, 221, 234, 217, 143, 26, 228, 11, 11, 71, 71, 114, 178, 165, 181, 187, 55, 51, 86, 149, 254, 239, 0, 76, 0, 53, 192, 23, 16, 14, 140, 4, 101, 195, 107, 17, 239, 76, 76, 53, 245, 215, 7, 30, 130, 136, 97, 166, 168, 122, 254, 163, 0, 121, 192, 34, 208, 25, 156, 10, 233, 199, 14, 210, 132, 93, 163, 121, 185, 226, 242, 201, 133, 150, 227, 46, 201, 220, 86, 217, 254, 218, 192, 91, 16, 59, 76, 19, 117, 205, 231, 21, 138, 143, 39, 36, 26, 155, 75, 43, 119, 95, 102, 184, 42, 242, 159, 5, 168, 3, 62, 129, 208, 96, 92, 40, 57, 222, 146, 216, 109, 154, 173, 171, 61, 191, 81, 176, 60, 116, 17, 231, 76, 74, 181, 247, 55, 6, 150, 130, 238, 225, 140, 72, 101, 246, 171, 6, 255, 66, 192, 49, 144, 20, 108, 15, 109, 196, 45, 147, 93, 173, 249, 189, 130, 241, 161, 132, 120, 99, 98, 169, 233, 190, 206, 240, 84, 68, 63, 115, 80, 37, 252, 27, 1, 203, 64, 87, 112, 62, 164, 16, 123, 76, 35, 117, 217, 231, 26, 202, 139, 23, 39, 78, 154, 180, 107, 55, 111, 86, 172, 62, 253, 208, 65, 156, 48, 105, 212, 46, 223, 92, 88, 57, 250, 146, 195, 45, 145, 221, 172, 89, 189, 250, 241, 131, 4, 97, 195, 104, 81, 238, 188, 76, 113, 245, 228, 71, 11, 114, 135, 101, 162, 171, 57, 191, 82, 240, 61, 132, 17, 163, 76, 121, 245, 226, 199, 9, 146, 134, 237, 162, 205, 185, 149, 178, 239, 53, 140, 23, 37, 206, 155, 20, 107, 79, 111, 116, 44, 39, 93, 218, 185, 155, 50, 235, 85, 143, 127, 36, 32, 27, 88, 11, 122, 135, 99, 34, 169, 217, 190, 218, 240, 91, 4, 59, 67, 83, 113, 253, 228, 65, 139, 112, 103, 100, 42, 171, 95, 63, 120, 16, 34, 140, 25, 165, 202, 251, 23, 3, 78, 129, 244, 96, 71, 104, 50, 174, 149, 188, 111, 49, 236, 20, 77, 207, 117, 148, 39, 47, 90, 156, 59, 41, 211, 94, 221, 248, 89, 130, 186, 225, 179, 8, 117, 198, 167, 18, 250, 141, 131, 37, 161, 219, 56, 91, 82, 187, 125, 179, 97, 181, 232, 119, 14, 166, 132, 122, 227, 99, 9, 233, 198, 206, 210, 212, 93, 159, 121, 168, 34, 254, 153, 128, 106, 224, 47, 8, 28, 6, 137, 194, 230, 209, 138, 220, 103, 25, 234, 138, 207, 39, 20, 26, 143, 75, 36, 55, 91, 86, 187, 126, 243, 96, 69, 232, 51, 14, 149, 196, 111, 19, 108, 13, 237, 197, 141, 147, 37, 173, 219, 61, 155, 81, 171, 124, 127, 97, 224, 40, 72, 30, 182, 136, 118, 230, 166, 202, 250, 215, 3, 30, 129, 200, 96, 86, 168, 62, 254, 144, 64, 108, 48, 45, 212, 29, 159, 73, 168, 54, 254, 150, 192, 110, 208, 44, 92, 29, 249, 201, 130, 214, 225, 158, 200, 104, 86, 174, 190, 252, 112, 65, 228, 48, 75, 84, 55, 127, 86, 160, 62, 248, 16, 66, 140, 49, 165, 212, 123, 31, 99, 72, 41, 246, 158, 198, 232, 82, 206, 189, 148, 113, 175, 100, 124, 43, 97, 223, 104, 88, 46, 186, 156, 115, 41, 229, 222, 203, 24, 87, 74, 190, 183, 48, 118, 148, 38, 239, 90, 204, 59, 21, 211, 79, 29, 244, 9, 135, 70, 226, 178, 201, 181, 150, 247, 46, 198, 156, 82, 233, 253, 142, 193, 164, 80, 123, 124, 35, 97, 217, 232, 90, 206, 187, 20, 115, 79, 101, 244, 43, 7, 95, 66, 184, 49, 178, 148, 117, 175, 103, 60, 42, 145, 223, 44, 88, 29, 250, 137, 131, 38, 225, 218, 200, 91, 22, 187, 78, 243, 116, 69, 231, 115, 10, 165, 199, 59, 18, 147, 77, 173, 245, 189, 135, 49, 162, 148, 121, 175, 98, 252, 41, 129, 222, 224, 88, 72, 58, 182, 147, 54, 237, 214, 205, 158, 213, 168, 95, 62, 184, 16, 114, 140, 37, 165, 219, 59, 27, 83, 75, 125, 247, 97, 134, 168, 98, 254, 169, 128, 126, 224, 32, 72, 24, 54, 138, 150, 231, 46, 202, 156, 87, 41, 254, 158, 192, 104, 80, 46, 188, 28, 113, 201, 228, 86, 203, 126, 215, 96, 94, 168, 56, 126, 146, 160, 109, 184, 45, 178, 157, 181, 169, 183, 62, 246, 144, 70, 236, 50, 205, 213, 149, 159, 47, 40, 28, 30, 137, 200, 102, 214, 170, 222, 255, 24, 64, 10, 176, 7, 52, 2, 151, 65, 174, 176, 124, 116, 33, 231, 88, 74, 186, 183, 51, 54, 149, 214, 239, 30, 204, 8, 85, 198, 191, 18, 240, 13, 132, 5, 163, 67, 57, 241, 210, 196, 93, 147, 121, 173, 226, 253, 137, 129, 166, 224, 122, 200, 35, 22, 153, 206, 234, 212, 79, 31, 116, 8, 39, 70, 154, 178, 235, 53, 143, 87, 36, 62, 155, 80, 107, 124, 47, 97, 220, 40, 89, 222, 186, 216, 115, 26, 165, 203, 59, 23, 83, 78, 189, 244, 113, 135, 100, 98, 171, 105, 191, 110, 240, 44, 68, 29, 243, 73, 133, 246, 227, 6, 201, 194, 214, 209, 158, 220, 104, 89, 238, 186, 204, 115, 21, 229, 207, 11, 20, 7, 79, 66, 180, 49, 183, 84, 118, 191, 102, 240, 42, 196, 31, 19, 72, 13, 246, 133, 134, 227, 34, 201, 217, 150, 218, 238, 219, 12, 91, 69, 251, 115, 3, 101, 193, 235, 16, 79, 76, 52, 53, 215, 87, 30, 190, 136, 112, 102, 164, 42, 251, 95, 3, 120, 1, 226, 128, 73, 160, 54, 248, 22, 194, 142, 209, 164, 92, 123, 121, 227, 98, 201, 233, 150, 206, 238, 212, 76, 95, 117, 248, 39, 2, 154, 129, 171, 32, 127, 88, 32, 58, 152, 19, 42, 141, 223, 37, 152, 27, 42, 139, 95, 39, 120, 26, 162, 139, 57, 167, 82, 250, 189, 131, 49, 161, 212, 120, 95, 98, 184, 41, 178, 158, 245, 168, 71, 62, 178, 144, 117, 172, 39, 61, 218, 145, 155, 44, 107, 93, 239, 121, 140, 34, 229, 217, 139, 26, 231, 75, 10, 183, 71, 54, 178, 150, 245, 174, 199, 60, 82, 145, 253, 172, 65, 189, 240, 113, 132, 36, 99, 91, 105, 251, 110, 195, 108, 81, 237, 252, 77, 129, 245, 160, 71, 56, 50, 146, 149, 173, 175, 61, 188, 17, 177, 204, 116, 85, 231, 127, 10, 160, 7, 56, 2, 146, 129, 173, 160, 125, 184, 33, 178, 152, 117, 170, 167, 63, 58, 144, 19, 44, 13, 221, 197, 153, 147, 42, 237, 223, 13, 152, 5, 170, 131, 63, 33, 208, 24, 92, 10, 185, 199, 50, 210, 149, 157, 175, 41, 188, 30, 241, 200, 68, 86, 179, 126, 245, 224, 71, 8, 50, 134, 149, 162, 239, 57, 140, 18, 229, 205, 139, 21, 167, 79, 58, 180, 19, 55, 77, 214, 181, 158, 247, 40, 70, 158, 178, 232, 117, 142, 167, 36, 122, 155, 99, 43, 105, 223, 110, 216, 44, 90, 157, 251, 41, 131, 94, 225, 248, 72, 66, 182, 177, 182, 244, 118, 199, 102, 210, 170, 221, 191, 25, 176, 10, 244, 7, 7, 66, 130, 177, 161, 180, 120, 119, 98, 166, 169, 186, 254, 243, 0, 69, 192, 51, 16, 21, 204, 15, 21, 196, 15, 19, 68, 13, 243, 69, 133, 243, 35, 5, 217, 195, 26, 209, 203, 28, 87, 73, 254, 182, 192, 118, 208, 38, 220, 26, 217, 203, 26, 215, 75, 30, 183, 72, 118, 182, 166, 246, 250, 198, 195, 18, 209, 205, 156, 85, 169, 255, 62, 192, 16, 80, 12, 60, 5, 209, 195, 28, 81, 201, 252, 86, 193, 254, 208, 64, 92, 48, 57, 212, 18, 223, 77, 152, 53, 170, 151, 63, 46, 144, 28, 108, 9, 237, 198, 205, 146, 213, 173, 159, 61, 168, 17, 190, 140, 112, 101, 228, 43, 11, 95, 71, 120, 50, 162, 149, 185, 175, 50, 252, 21, 129, 207, 32, 84, 24, 63, 74, 144, 55, 44, 22, 157, 206, 233, 148, 78, 239, 116, 76, 39, 117, 218, 167, 27, 58, 139, 83, 39, 125, 218, 161, 155, 56, 107, 82, 175, 125, 188, 33, 177, 216, 116, 90, 167, 123, 58, 163, 83, 57, 253, 210, 193, 157, 144, 105, 172, 46, 253, 220, 65, 153, 240, 106, 196, 47, 19, 92, 13, 249, 197, 130, 211, 33, 157, 216, 105, 154, 174, 235, 60, 79, 81, 244, 60, 71, 81, 242, 188, 69, 177, 243, 52, 69, 215, 115, 30, 165, 200, 123, 22, 163, 78, 249, 244, 66, 199, 113, 146, 164, 109, 187, 109, 179, 109, 181, 237, 183, 13, 182, 133, 182, 227, 54, 201, 214, 214, 222, 222, 216, 88, 90, 186, 187, 51, 51, 255, 63 ) random_mask_vec8 = numpy.array(random_mask_tuple, numpy.uint8) gnuradio-3.7.2.1/gr-digital/python/digital/soft_dec_lut_gen.py0000664000175000017500000002172512237515112024170 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy def soft_dec_table_generator(soft_dec_gen, prec, Es=1): ''' Builds a LUT that is a list of tuples. The tuple represents the soft decisions for the constellation/bit mapping at any given point in the complex space, (x,y). The table is built to a precision specified by the 'prec' argument. There are (2x2)^prec samples in the sample space, so we get the precision of 2^prec samples in both the real and imaginary axes. The space is represented where index 0 is the bottom left corner and the maximum index is the upper left. The table index for a surface space with 4 bits of precision looks like the following: 240 241 242 243 244 245 246 247 | 248 249 250 251 252 253 254 255 224 225 226 227 228 229 230 231 | 232 233 234 235 236 237 238 239 208 209 210 211 212 213 214 215 | 216 217 218 219 220 221 222 223 192 193 194 195 196 197 198 199 | 200 201 202 203 204 205 206 207 176 177 178 179 180 181 182 183 | 184 185 186 187 188 189 190 191 160 161 162 163 164 165 166 167 | 168 169 170 171 172 173 174 175 144 145 146 147 148 149 150 151 | 152 153 154 155 156 157 158 159 128 129 130 131 132 133 134 135 | 136 137 138 139 140 141 142 143 ----------------------------------------------------------------- 112 113 114 115 116 117 118 119 | 120 121 122 123 124 125 126 127 96 97 98 99 100 101 102 103 | 104 105 106 107 108 109 110 111 80 81 82 83 84 85 86 87 | 88 89 90 91 92 93 94 95 64 65 66 67 68 69 70 71 | 72 73 74 75 76 77 78 79 48 49 50 51 52 53 54 55 | 56 57 58 59 60 61 62 63 32 33 34 35 36 37 38 39 | 40 41 42 43 44 45 46 47 16 17 18 19 20 21 22 23 | 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 15 We then calculate coordinates from -1 to 1 with 2^prec points for both the x and y axes. We then sample starting at (-1, -1) and move left to right on the x-axis and then move up a row on the y-axis. For every point in this sampled space, we calculate the soft decisions for the given constellation/mapping. This is done by passing in the function 'soft_dec_gen' as an argument to this function. This takes in the x/y coordinates and outputs the soft decisions. These soft decisions are stored into the list at the index from the above table as a tuple. The function 'calc_from_table' takes in a point and reverses this operation. It converts the point from the coordinates (-1,-1) to (1,1) into an index value in the table and returns the tuple of soft decisions at that index. Es is the energy per symbol. This is passed to the function to provide the bounds when calling the generator function since they don't know how the constellation was normalized. Using the (maximum) energy per symbol for constellation allows us to provide any scaling of the constellation (normalized to sum to 1, normalized so the outside points sit on +/-1, etc.) but still calculate the soft decisions as we would given the full constellation. ''' npts = 2.0**prec maxd = Es*numpy.sqrt(2)/2 yrng = numpy.linspace(-maxd, maxd, npts) xrng = numpy.linspace(-maxd, maxd, npts) table = [] for y in yrng: for x in xrng: pt = complex(x, y) decs = soft_dec_gen(pt, Es) table.append(decs) return table def soft_dec_table(constel, symbols, prec, npwr=1): ''' Similar in nature to soft_dec_table_generator above. Instead, this takes in the constellation and symbol points along with the noise power estimate and uses calc_soft_dec (below) to generate the LUT. Instead of assuming that the constellation is normalied (e.g., all points are between -1 and 1), this function calculates the min/max of both the real and imaginary axes and uses those when constructing the LUT. So when using this version of the LUT, the samples and the constellations must be working on the same magnitudes. Because this uses the calc_soft_dec function, it can be quite a bit more expensive to generate the LUT, though it should be one-time work. ''' re_min = min(numpy.array(constel).real) im_min = min(numpy.array(constel).imag) re_max = max(numpy.array(constel).real) im_max = max(numpy.array(constel).imag) npts = 2.0**prec yrng = numpy.linspace(im_min, im_max, npts) xrng = numpy.linspace(re_min, re_max, npts) table = [] for y in yrng: for x in xrng: pt = complex(x, y) decs = calc_soft_dec(pt, constel, symbols, npwr) table.append(decs) return table def calc_soft_dec_from_table(sample, table, prec, Es=1): ''' Takes in a complex sample and converts it from the coordinates (-1,-1) to (1,1) into an index value. The index value points to a location in the provided LUT 'table' and returns the soft decisions tuple at that index. sample: the complex sample to calculate the soft decisions from. table: the LUT. prec: the precision used when generating the LUT. Es: the energy per symbol. This is passed to the function to provide the bounds when calling the generator function since they don't know how the constellation was normalized. Using the (maximum) energy per symbol for constellation allows us to provide any scaling of the constellation (normalized to sum to 1, normalized so the outside points sit on +/-1, etc.) but still calculate the soft decisions as we would given the full constellation. ''' lut_scale = 2**prec maxd = Es*numpy.sqrt(2)/2 step = 2*maxd / lut_scale scale = (lut_scale) / (2*maxd) - step xre = sample.real xim = sample.imag xre = int((maxd + min(maxd, max(-maxd, xre))) * scale) xim = int((maxd + min(maxd, max(-maxd, xim))) * scale) index = int(xre + lut_scale*xim) max_index = lut_scale**2 if(index > max_index): return table[0]; if(index < 0): raise RuntimeError("calc_from_table: input sample out of range.") return table[index] def calc_soft_dec(sample, constel, symbols, npwr=1): ''' This function takes in any consteallation and symbol symbol set (where symbols[i] is the set of bits at constellation point constel[i] and an estimate of the noise power and produces the soft decisions for the given sample. If known, the noise power of the received sample may be passed in to this function as npwr. This is an incredibly costly algorthm because it must calculate the Euclidean distance between the sample and all points in the constellation to build up its probability calculations. Conversely, it should work for any given constellation/symbol map. The function returns a vector of k soft decisions. Decisions less than 0 are more likely to indicate a '0' bit and decisions greater than 0 are more likely to indicate a '1' bit. ''' M = len(constel) k = int(numpy.log2(M)) tmp = 2*k*[0,] s = k*[0,] # Find a scaling factor for the constellation, however it was normalized. constel = numpy.array(constel) scale = min(min(abs(constel.real)), min(abs(constel.imag))) for i in range(M): # Calculate the distance between the sample and the current # constellation point. dist = abs(sample - constel[i])**2 # Calculate the probability factor from the distance and the # scaled noise power. d = numpy.exp(-dist/(2*npwr*scale**2)) for j in range(k): # Get the bit at the jth index mask = 1<> j # If the bit is a 0, add to the probability of a zero if(bit == 0): tmp[2*j+0] += d # else, add to the probability of a one else: tmp[2*j+1] += d # Calculate the log-likelihood ratio for all bits based on the # probability of ones (tmp[2*i+1]) over the probability of a zero # (tmp[2*i+0]). for i in range(k): s[k-1-i] = (numpy.log(tmp[2*i+1]) - numpy.log(tmp[2*i+0])) * scale**2 return s gnuradio-3.7.2.1/gr-digital/python/digital/qpsk.py0000664000175000017500000001637512207440367021656 0ustar jcorganjcorgan# # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ QPSK modulation. Demodulation is not included since the generic_mod_demod """ from gnuradio import gr from gnuradio.digital.generic_mod_demod import generic_mod, generic_demod from gnuradio.digital.generic_mod_demod import shared_mod_args, shared_demod_args from utils import mod_codes import digital_swig as digital import modulation_utils # The default encoding (e.g. gray-code, set-partition) _def_mod_code = mod_codes.GRAY_CODE # ///////////////////////////////////////////////////////////////////////////// # QPSK constellation # ///////////////////////////////////////////////////////////////////////////// def qpsk_constellation(mod_code=_def_mod_code): """ Creates a QPSK constellation. """ if mod_code != mod_codes.GRAY_CODE: raise ValueError("This QPSK mod/demod works only for gray-coded constellations.") return digital.constellation_qpsk() # ///////////////////////////////////////////////////////////////////////////// # QPSK modulator # ///////////////////////////////////////////////////////////////////////////// class qpsk_mod(generic_mod): """ Hierarchical block for RRC-filtered QPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). differential: Whether to use differential encoding (boolean). """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, mod_code=_def_mod_code, differential=False, *args, **kwargs): pre_diff_code = True if not differential: constellation = digital.constellation_qpsk() if mod_code != mod_codes.GRAY_CODE: raise ValueError("This QPSK mod/demod works only for gray-coded constellations.") else: constellation = digital.constellation_dqpsk() if mod_code not in set([mod_codes.GRAY_CODE, mod_codes.NO_CODE]): raise ValueError("That mod_code is not supported for DQPSK mod/demod.") if mod_code == mod_codes.NO_CODE: pre_diff_code = False super(qpsk_mod, self).__init__(constellation=constellation, pre_diff_code=pre_diff_code, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # QPSK demodulator # # ///////////////////////////////////////////////////////////////////////////// class qpsk_demod(generic_demod): """ Hierarchical block for RRC-filtered QPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). differential: Whether to use differential encoding (boolean). """ # See generic_mod for additional arguments __doc__ += shared_demod_args def __init__(self, mod_code=_def_mod_code, differential=False, *args, **kwargs): pre_diff_code = True if not differential: constellation = digital.constellation_qpsk() if mod_code != mod_codes.GRAY_CODE: raise ValueError("This QPSK mod/demod works only for gray-coded constellations.") else: constellation = digital.constellation_dqpsk() if mod_code not in set([mod_codes.GRAY_CODE, mod_codes.NO_CODE]): raise ValueError("That mod_code is not supported for DQPSK mod/demod.") if mod_code == mod_codes.NO_CODE: pre_diff_code = False super(qpsk_demod, self).__init__(constellation=constellation, pre_diff_code=pre_diff_code, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # DQPSK constellation # ///////////////////////////////////////////////////////////////////////////// def dqpsk_constellation(mod_code=_def_mod_code): if mod_code != mod_codes.GRAY_CODE: raise ValueError("The DQPSK constellation is only generated for gray_coding. But it can be used for non-grayed coded modulation if one doesn't use the pre-differential code.") return digital.constellation_dqpsk() # ///////////////////////////////////////////////////////////////////////////// # DQPSK modulator # ///////////////////////////////////////////////////////////////////////////// class dqpsk_mod(qpsk_mod): """ Hierarchical block for RRC-filtered DQPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, mod_code=_def_mod_code, *args, **kwargs): super(dqpsk_mod, self).__init__(mod_code, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # DQPSK demodulator # # ///////////////////////////////////////////////////////////////////////////// class dqpsk_demod(qpsk_demod): """ Hierarchical block for RRC-filtered DQPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). """ # See generic_mod for additional arguments __doc__ += shared_demod_args def __init__(self, mod_code=_def_mod_code, *args, **kwargs): super(dqpsk_demod, self).__init__(mod_code, *args, **kwargs) # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('qpsk', qpsk_mod) modulation_utils.add_type_1_demod('qpsk', qpsk_demod) modulation_utils.add_type_1_constellation('qpsk', qpsk_constellation) modulation_utils.add_type_1_mod('dqpsk', dqpsk_mod) modulation_utils.add_type_1_demod('dqpsk', dqpsk_demod) modulation_utils.add_type_1_constellation('dqpsk', dqpsk_constellation) gnuradio-3.7.2.1/gr-digital/python/digital/qa_clock_recovery_mm.py0000775000175000017500000001256112207440367025057 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import cmath from gnuradio import gr, gr_unittest, digital, blocks class test_clock_recovery_mm(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): # Test complex/complex version omega = 2 gain_omega = 0.001 mu = 0.5 gain_mu = 0.01 omega_rel_lim = 0.001 self.test = digital.clock_recovery_mm_cc(omega, gain_omega, mu, gain_mu, omega_rel_lim) data = 100*[complex(1, 1),] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() expected_result = 100*[complex(0.99972, 0.99972)] # doesn't quite get to 1.0 dst_data = self.snk.data() # Only compare last Ncmp samples Ncmp = 30 len_e = len(expected_result) len_d = len(dst_data) expected_result = expected_result[len_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #print expected_result #print dst_data self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) def test02(self): # Test float/float version omega = 2 gain_omega = 0.01 mu = 0.5 gain_mu = 0.01 omega_rel_lim = 0.001 self.test = digital.clock_recovery_mm_ff(omega, gain_omega, mu, gain_mu, omega_rel_lim) data = 100*[1,] self.src = blocks.vector_source_f(data, False) self.snk = blocks.vector_sink_f() self.tb.connect(self.src, self.test, self.snk) self.tb.run() expected_result = 100*[0.99972, ] # doesn't quite get to 1.0 dst_data = self.snk.data() # Only compare last Ncmp samples Ncmp = 30 len_e = len(expected_result) len_d = len(dst_data) expected_result = expected_result[len_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #print expected_result #print dst_data self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) def test03(self): # Test complex/complex version with varying input omega = 2 gain_omega = 0.01 mu = 0.25 gain_mu = 0.1 omega_rel_lim = 0.0001 self.test = digital.clock_recovery_mm_cc(omega, gain_omega, mu, gain_mu, omega_rel_lim) data = 1000*[complex(1, 1), complex(1, 1), complex(-1, -1), complex(-1, -1)] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() expected_result = 1000*[complex(-1.2, -1.2), complex(1.2, 1.2)] dst_data = self.snk.data() # Only compare last Ncmp samples Ncmp = 100 len_e = len(expected_result) len_d = len(dst_data) expected_result = expected_result[len_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #print expected_result #print dst_data self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 1) def test04(self): # Test float/float version omega = 2 gain_omega = 0.01 mu = 0.25 gain_mu = 0.1 omega_rel_lim = 0.001 self.test = digital.clock_recovery_mm_ff(omega, gain_omega, mu, gain_mu, omega_rel_lim) data = 1000*[1, 1, -1, -1] self.src = blocks.vector_source_f(data, False) self.snk = blocks.vector_sink_f() self.tb.connect(self.src, self.test, self.snk) self.tb.run() expected_result = 1000*[-1.31, 1.31] dst_data = self.snk.data() # Only compare last Ncmp samples Ncmp = 100 len_e = len(expected_result) len_d = len(dst_data) expected_result = expected_result[len_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #print expected_result #print dst_data self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 1) if __name__ == '__main__': gr_unittest.run(test_clock_recovery_mm, "test_clock_recovery_mm.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_chanest_vcvc.py0000775000175000017500000003276312207440367025036 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys import numpy import random import numpy from gnuradio import gr, gr_unittest, blocks, analog, digital import pmt def shift_tuple(vec, N): """ Shifts a vector by N elements. Fills up with zeros. """ if N > 0: return (0,) * N + tuple(vec[0:-N]) else: N = -N return tuple(vec[N:]) + (0,) * N def rand_range(min_val, max_val): """ Returns a random value (uniform) from the interval min_val, max_val """ return random.random() * (max_val - min_val) + min_val class qa_ofdm_sync_eqinit_vcvc (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_offset_2sym (self): """ Add a frequency offset, check if it's correctly detected. Also add some random tags and see if they come out at the correct position. """ fft_len = 16 carr_offset = -2 sync_symbol1 = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0) sync_symbol2 = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) data_symbol = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) tx_data = shift_tuple(sync_symbol1, carr_offset) + \ shift_tuple(sync_symbol2, carr_offset) + \ shift_tuple(data_symbol, carr_offset) tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol("test_tag_1") tag1.value = pmt.from_long(23) tag2 = gr.tag_t() tag2.offset = 2 tag2.key = pmt.string_to_symbol("test_tag_2") tag2.value = pmt.from_long(42) src = blocks.vector_source_c(tx_data, False, fft_len, (tag1, tag2)) chanest = digital.ofdm_chanest_vcvc(sync_symbol1, sync_symbol2, 1) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, chanest, sink) self.tb.run() self.assertEqual(shift_tuple(sink.data(), -carr_offset), data_symbol) tags = sink.tags() ptags = {} for tag in tags: ptag = gr.tag_to_python(tag) ptags[ptag.key] = (ptag.value, ptag.offset) if ptag.key == 'ofdm_sync_chan_taps': ptags[ptag.key] = (None, ptag.offset) expected_tags = { 'ofdm_sync_carr_offset': (-2, 0), 'ofdm_sync_chan_taps': (None, 0), 'test_tag_1': (23, 0), 'test_tag_2': (42, 0), } self.assertEqual(ptags, expected_tags) def test_002_offset_1sym (self): """ Add a frequency offset, check if it's correctly detected. Difference to previous test is, it only uses one synchronisation symbol. """ fft_len = 16 carr_offset = -2 # This will not correct for +2 because it thinks carrier 14 is used # (because of interpolation) sync_symbol = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0) data_symbol = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) tx_data = shift_tuple(sync_symbol, carr_offset) + \ shift_tuple(data_symbol, carr_offset) src = blocks.vector_source_c(tx_data, False, fft_len) # 17 is out of bounds! chanest = digital.ofdm_chanest_vcvc(sync_symbol, (), 1, 0, 17) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, chanest, sink) self.tb.run() self.assertEqual(shift_tuple(sink.data(), -carr_offset), data_symbol) tags = sink.tags() for tag in tags: if pmt.symbol_to_string(tag.key) == 'ofdm_sync_carr_offset': carr_offset_hat = pmt.to_long(tag.value) self.assertEqual(pmt.to_long(tag.value), carr_offset) def test_003_channel_no_carroffset (self): """ Add a channel, check if it's correctly estimated """ fft_len = 16 carr_offset = 0 sync_symbol1 = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0) sync_symbol2 = (0, 0, 0, 1j, -1, 1, -1j, 1j, 0, 1, -1j, -1, -1j, 1, 0, 0) data_symbol = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) tx_data = sync_symbol1 + sync_symbol2 + data_symbol channel = (0, 0, 0, 2, -2, 2, 3j, 2, 0, 2, 2, 2, 2, 3, 0, 0) src = blocks.vector_source_c(tx_data, False, fft_len) chan = blocks.multiply_const_vcc(channel) chanest = digital.ofdm_chanest_vcvc(sync_symbol1, sync_symbol2, 1) sink = blocks.vector_sink_c(fft_len) sink_chanest = blocks.vector_sink_c(fft_len) self.tb.connect(src, chan, chanest, sink) self.tb.connect((chanest, 1), sink_chanest) self.tb.run() tags = sink.tags() self.assertEqual(shift_tuple(sink.data(), -carr_offset), tuple(numpy.multiply(data_symbol, channel))) for tag in tags: if pmt.symbol_to_string(tag.key) == 'ofdm_sync_carr_offset': self.assertEqual(pmt.to_long(tag.value), carr_offset) if pmt.symbol_to_string(tag.key) == 'ofdm_sync_chan_taps': self.assertEqual(pmt.c32vector_elements(tag.value), channel) self.assertEqual(sink_chanest.data(), channel) def test_004_channel_no_carroffset_1sym (self): """ Add a channel, check if it's correctly estimated. Only uses 1 synchronisation symbol. """ fft_len = 16 carr_offset = 0 sync_symbol = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0) data_symbol = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) tx_data = sync_symbol + data_symbol channel = (0, 0, 0, 2, 2, 2, 2, 3, 3, 2.5, 2.5, -3, -3, 1j, 1j, 0) #channel = (0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0) src = blocks.vector_source_c(tx_data, False, fft_len) chan = blocks.multiply_const_vcc(channel) chanest = digital.ofdm_chanest_vcvc(sync_symbol, (), 1) sink = blocks.vector_sink_c(fft_len) sink_chanest = blocks.vector_sink_c(fft_len) self.tb.connect(src, chan, chanest, sink) self.tb.connect((chanest, 1), sink_chanest) self.tb.run() self.assertEqual(sink_chanest.data(), channel) tags = sink.tags() for tag in tags: if pmt.symbol_to_string(tag.key) == 'ofdm_sync_carr_offset': self.assertEqual(pmt.to_long(tag.value), carr_offset) if pmt.symbol_to_string(tag.key) == 'ofdm_sync_chan_taps': self.assertEqual(pmt.c32vector_elements(tag.value), channel) def test_005_both_1sym_force (self): """ Add a channel, check if it's correctly estimated. Only uses 1 synchronisation symbol. """ fft_len = 16 carr_offset = 0 sync_symbol = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0) ref_symbol = (0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0) data_symbol = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) tx_data = sync_symbol + data_symbol channel = (0, 0, 0, 2, 2, 2, 2.5, 3, 2.5, 2, 2.5, 3, 2, 1, 1, 0) src = blocks.vector_source_c(tx_data, False, fft_len) chan = blocks.multiply_const_vcc(channel) chanest = digital.ofdm_chanest_vcvc(sync_symbol, ref_symbol, 1) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, chan, chanest, sink) self.tb.run() tags = sink.tags() for tag in tags: if pmt.symbol_to_string(tag.key) == 'ofdm_sync_carr_offset': self.assertEqual(pmt.to_long(tag.value), carr_offset) if pmt.symbol_to_string(tag.key) == 'ofdm_sync_chan_taps': self.assertEqual(pmt.c32vector_elements(tag.value), channel) def test_006_channel_and_carroffset (self): """ Add a channel, check if it's correctly estimated """ fft_len = 16 carr_offset = 2 # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 sync_symbol1 = (0, 0, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 0) sync_symbol2 = (0, 0, 0, 1j, -1, 1, -1j, 1j, 0, 1, -1j, -1, -1j, 1, 0, 0) data_symbol = (0, 0, 0, 1, -1, 1, -1, 1, 0, 1, -1, -1, -1, 1, 0, 0) # Channel 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # Shifted (0, 0, 0, 0, 0, 1j, -1, 1, -1j, 1j, 0, 1, -1j, -1, -1j, 1) chanest_exp = (0, 0, 0, 5, 6, 7, 8, 9, 0, 11, 12, 13, 14, 15, 0, 0) tx_data = shift_tuple(sync_symbol1, carr_offset) + \ shift_tuple(sync_symbol2, carr_offset) + \ shift_tuple(data_symbol, carr_offset) channel = range(fft_len) src = blocks.vector_source_c(tx_data, False, fft_len) chan = blocks.multiply_const_vcc(channel) chanest = digital.ofdm_chanest_vcvc(sync_symbol1, sync_symbol2, 1) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, chan, chanest, sink) self.tb.run() tags = sink.tags() chan_est = None for tag in tags: if pmt.symbol_to_string(tag.key) == 'ofdm_sync_carr_offset': self.assertEqual(pmt.to_long(tag.value), carr_offset) if pmt.symbol_to_string(tag.key) == 'ofdm_sync_chan_taps': chan_est = pmt.c32vector_elements(tag.value) self.assertEqual(chan_est, chanest_exp) self.assertEqual(sink.data(), tuple(numpy.multiply(shift_tuple(data_symbol, carr_offset), channel))) def test_999_all_at_once(self): """docstring for test_999_all_at_once""" fft_len = 32 # 6 carriers empty, 10 carriers full, 1 DC carrier, 10 carriers full, 5 carriers empty syncsym_mask = (0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0) carrier_mask = (0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0) max_offset = 4 wgn_amplitude = 0.05 min_chan_ampl = 0.1 max_chan_ampl = 5 n_iter = 20 # The more the accurater def run_flow_graph(sync_sym1, sync_sym2, data_sym): top_block = gr.top_block() carr_offset = random.randint(-max_offset/2, max_offset/2) * 2 tx_data = shift_tuple(sync_sym1, carr_offset) + \ shift_tuple(sync_sym2, carr_offset) + \ shift_tuple(data_sym, carr_offset) channel = [rand_range(min_chan_ampl, max_chan_ampl) * numpy.exp(1j * rand_range(0, 2 * numpy.pi)) for x in range(fft_len)] src = blocks.vector_source_c(tx_data, False, fft_len) chan = blocks.multiply_const_vcc(channel) noise = analog.noise_source_c(analog.GR_GAUSSIAN, wgn_amplitude) add = blocks.add_cc(fft_len) chanest = digital.ofdm_chanest_vcvc(sync_sym1, sync_sym2, 1) sink = blocks.vector_sink_c(fft_len) top_block.connect(src, chan, (add, 0), chanest, sink) top_block.connect(noise, blocks.stream_to_vector(gr.sizeof_gr_complex, fft_len), (add, 1)) top_block.run() channel_est = None carr_offset_hat = 0 rx_sym_est = [0,] * fft_len tags = sink.tags() for tag in tags: if pmt.symbol_to_string(tag.key) == 'ofdm_sync_carr_offset': carr_offset_hat = pmt.to_long(tag.value) self.assertEqual(carr_offset, carr_offset_hat) if pmt.symbol_to_string(tag.key) == 'ofdm_sync_chan_taps': channel_est = shift_tuple(pmt.c32vector_elements(tag.value), carr_offset) shifted_carrier_mask = shift_tuple(carrier_mask, carr_offset) for i in range(fft_len): if shifted_carrier_mask[i] and channel_est[i]: self.assertAlmostEqual(channel[i], channel_est[i], places=0) rx_sym_est[i] = (sink.data()[i] / channel_est[i]).real return (carr_offset, list(shift_tuple(rx_sym_est, -carr_offset_hat))) bit_errors = 0 for k in xrange(n_iter): sync_sym = [(random.randint(0, 1) * 2 - 1) * syncsym_mask[i] for i in range(fft_len)] ref_sym = [(random.randint(0, 1) * 2 - 1) * carrier_mask[i] for i in range(fft_len)] data_sym = [(random.randint(0, 1) * 2 - 1) * carrier_mask[i] for i in range(fft_len)] data_sym[26] = 1 (carr_offset, rx_sym) = run_flow_graph(sync_sym, ref_sym, data_sym) rx_sym_est = [0,] * fft_len for i in xrange(fft_len): if carrier_mask[i] == 0: continue rx_sym_est[i] = {True: 1, False: -1}[rx_sym[i] > 0] if rx_sym_est[i] != data_sym[i]: bit_errors += 1 # This is much more than we could allow self.assertTrue(bit_errors < n_iter) if __name__ == '__main__': gr_unittest.run(qa_ofdm_sync_eqinit_vcvc, "qa_ofdm_sync_eqinit_vcvc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_sync_sc_cfb.py0000775000175000017500000001573612207440367024644 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy import random from gnuradio import gr, gr_unittest, blocks, analog, channels from gnuradio import digital from gnuradio.digital.utils import tagged_streams from gnuradio.digital.ofdm_txrx import ofdm_tx class qa_ofdm_sync_sc_cfb (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_detect (self): """ Send two bursts, with zeros in between, and check they are both detected at the correct position and no false alarms occur """ n_zeros = 15 fft_len = 32 cp_len = 4 sig_len = (fft_len + cp_len) * 10 sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2 tx_signal = [0,] * n_zeros + \ sync_symbol[-cp_len:] + \ sync_symbol + \ [(random.randint(0, 1)*2)-1 for x in range(sig_len)] tx_signal = tx_signal * 2 add = blocks.add_cc() sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len) sink_freq = blocks.vector_sink_f() sink_detect = blocks.vector_sink_b() self.tb.connect(blocks.vector_source_c(tx_signal), (add, 0)) self.tb.connect(analog.noise_source_c(analog.GR_GAUSSIAN, .01), (add, 1)) self.tb.connect(add, sync) self.tb.connect((sync, 0), sink_freq) self.tb.connect((sync, 1), sink_detect) self.tb.run() sig1_detect = sink_detect.data()[0:len(tx_signal)/2] sig2_detect = sink_detect.data()[len(tx_signal)/2:] self.assertTrue(abs(sig1_detect.index(1) - (n_zeros + fft_len + cp_len)) < cp_len) self.assertTrue(abs(sig2_detect.index(1) - (n_zeros + fft_len + cp_len)) < cp_len) self.assertEqual(numpy.sum(sig1_detect), 1) self.assertEqual(numpy.sum(sig2_detect), 1) def test_002_freq (self): """ Add a fine frequency offset and see if that get's detected properly """ fft_len = 32 cp_len = 4 # This frequency offset is normalized to rads, i.e. \pi == f_s/2 max_freq_offset = 2*numpy.pi/fft_len # Otherwise, it's coarse freq_offset = ((2 * random.random()) - 1) * max_freq_offset sig_len = (fft_len + cp_len) * 10 sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2 tx_signal = sync_symbol[-cp_len:] + \ sync_symbol + \ [(random.randint(0, 1)*2)-1 for x in range(sig_len)] sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len, True) sink_freq = blocks.vector_sink_f() sink_detect = blocks.vector_sink_b() channel = channels.channel_model(0.005, freq_offset / 2.0 / numpy.pi) self.tb.connect(blocks.vector_source_c(tx_signal), channel, sync) self.tb.connect((sync, 0), sink_freq) self.tb.connect((sync, 1), sink_detect) self.tb.run() phi_hat = sink_freq.data()[sink_detect.data().index(1)] est_freq_offset = 2 * phi_hat / fft_len self.assertAlmostEqual(est_freq_offset, freq_offset, places=2) def test_003_multiburst (self): """ Send several bursts, see if the number of detects is correct. Burst lengths and content are random. """ n_bursts = 42 fft_len = 32 cp_len = 4 tx_signal = [] for i in xrange(n_bursts): sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2 tx_signal += [0,] * random.randint(0, 2*fft_len) + \ sync_symbol[-cp_len:] + \ sync_symbol + \ [(random.randint(0, 1)*2)-1 for x in range(fft_len * random.randint(5,23))] add = blocks.add_cc() sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len) sink_freq = blocks.vector_sink_f() sink_detect = blocks.vector_sink_b() channel = channels.channel_model(0.005) self.tb.connect(blocks.vector_source_c(tx_signal), channel, sync) self.tb.connect((sync, 0), sink_freq) self.tb.connect((sync, 1), sink_detect) self.tb.run() n_bursts_detected = numpy.sum(sink_detect.data()) # We allow for one false alarm or missed burst self.assertTrue(abs(n_bursts_detected - n_bursts) <= 1, msg="""Because of statistics, it is possible (though unlikely) that the number of detected bursts differs slightly. If the number of detects is off by one or two, run the test again and see what happen. Detection error was: %d """ % (numpy.sum(sink_detect.data()) - n_bursts) ) def test_004_ofdm_packets (self): """ Send several bursts using ofdm_tx, see if the number of detects is correct. Burst lengths and content are random. """ n_bursts = 42 fft_len = 64 cp_len = 16 # Here, coarse freq offset is allowed max_freq_offset = 2*numpy.pi/fft_len * 4 freq_offset = ((2 * random.random()) - 1) * max_freq_offset tx_signal = [] packets = [] tagname = "packet_length" min_packet_length = 10 max_packet_length = 50 sync_sequence = [random.randint(0, 1)*2-1 for x in range(fft_len/2)] for i in xrange(n_bursts): packet_length = random.randint(min_packet_length, max_packet_length+1) packet = [random.randint(0, 255) for i in range(packet_length)] packets.append(packet) data, tags = tagged_streams.packets_to_vectors(packets, tagname, vlen=1) total_length = len(data) src = blocks.vector_source_b(data, False, 1, tags) mod = ofdm_tx(packet_length_tag_key=tagname) sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len) sink_freq = blocks.vector_sink_f() sink_detect = blocks.vector_sink_b() noise_level = 0.005 channel = channels.channel_model(noise_level, freq_offset / 2 / numpy.pi) self.tb.connect(src, mod, channel, sync, sink_freq) self.tb.connect((sync, 1), sink_detect) self.tb.run() self.assertEqual(numpy.sum(sink_detect.data()), n_bursts) if __name__ == '__main__': gr_unittest.run(qa_ofdm_sync_sc_cfb, "qa_ofdm_sync_sc_cfb.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_simple_framer.py0000775000175000017500000000400512207440367024174 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_simple_framer(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_simple_framer_001(self): src_data = (0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff) expected_result = ( 0xac, 0xdd, 0xa4, 0xe2, 0xf2, 0x8c, 0x20, 0xfc, 0x00, 0x00, 0x11, 0x22, 0x33, 0x55, 0xac, 0xdd, 0xa4, 0xe2, 0xf2, 0x8c, 0x20, 0xfc, 0x01, 0x44, 0x55, 0x66, 0x77, 0x55, 0xac, 0xdd, 0xa4, 0xe2, 0xf2, 0x8c, 0x20, 0xfc, 0x02, 0x88, 0x99, 0xaa, 0xbb, 0x55, 0xac, 0xdd, 0xa4, 0xe2, 0xf2, 0x8c, 0x20, 0xfc, 0x03, 0xcc, 0xdd, 0xee, 0xff, 0x55) src = blocks.vector_source_b(src_data) op = digital.simple_framer(4) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_simple_framer, "test_simple_framer.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_insert_preamble.py0000775000175000017500000001304112207440367025527 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from pprint import pprint from gnuradio import gr, gr_unittest, digital, blocks class test_ofdm_insert_preamble(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def helper(self, v0, v1, fft_length, preamble): tb = self.tb src0 = blocks.vector_source_c(v0) src1 = blocks.vector_source_b(v1) s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, fft_length) # print "len(v) = %d" % (len(v)) op = digital.ofdm_insert_preamble(fft_length, preamble) v2s = blocks.vector_to_stream(gr.sizeof_gr_complex, fft_length) dst0 = blocks.vector_sink_c() dst1 = blocks.vector_sink_b() tb.connect(src0, s2v, (op, 0)) tb.connect(src1, (op, 1)) tb.connect((op, 0), v2s, dst0) tb.connect((op, 1), dst1) tb.run() r0 = dst0.data() r0v = [] for i in range(len(r0)//fft_length): r0v.append(r0[i*fft_length:(i+1)*fft_length]) r1 = dst1.data() self.assertEqual(len(r0v), len(r1)) return (r1, r0v) def check_match(self, actual, expected_list): lst = [] map(lambda x: lst.append(x), expected_list) self.assertEqual(actual, lst) # ---------------------------------------------------------------- def test_000(self): # no preamble, 1 symbol payloads preamble = () fft_length = 8 npayloads = 8 v = [] p = [] for i in range(npayloads): t = fft_length*[(i + i*1j)] p.append(tuple(t)) v += t p = tuple(p) r = self.helper(v, npayloads*[1], fft_length, preamble) # pprint(r) self.assertEqual(r[0], tuple(npayloads*[1])) self.check_match(r[1], (p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7])) def test_001(self): # 1 symbol preamble, 1 symbol payloads preamble = ((100, 101, 102, 103, 104, 105, 106, 107),) p0 = preamble[0] fft_length = 8 npayloads = 8 v = [] p = [] for i in range(npayloads): t = fft_length*[(i + i*1j)] p.append(tuple(t)) v += t r = self.helper(v, npayloads*[1], fft_length, preamble) self.assertEqual(r[0], tuple(npayloads*[1, 0])) self.check_match(r[1], (p0, p[0], p0, p[1], p0, p[2], p0, p[3], p0, p[4], p0, p[5], p0, p[6], p0, p[7])) def test_002(self): # 2 symbol preamble, 1 symbol payloads preamble = ((100, 101, 102, 103, 104, 105, 106, 107), (200, 201, 202, 203, 204, 205, 206, 207)) p0 = preamble[0] p1 = preamble[1] fft_length = 8 npayloads = 8 v = [] p = [] for i in range(npayloads): t = fft_length*[(i + i*1j)] p.append(tuple(t)) v += t r = self.helper(v, npayloads*[1], fft_length, preamble) self.assertEqual(r[0], tuple(npayloads*[1, 0, 0])) self.check_match(r[1], (p0, p1, p[0], p0, p1, p[1], p0, p1, p[2], p0, p1, p[3], p0, p1, p[4], p0, p1, p[5], p0, p1, p[6], p0, p1, p[7])) def xtest_003_preamble(self): # 2 symbol preamble, 2 symbol payloads preamble = ((100, 101, 102, 103, 104, 105, 106, 107), (200, 201, 202, 203, 204, 205, 206, 207)) p0 = preamble[0] p1 = preamble[1] fft_length = 8 npayloads = 8 v = [] p = [] for i in range(npayloads * 2): t = fft_length*[(i + i*1j)] p.append(tuple(t)) v += t r = self.helper(v, npayloads*[1, 0], fft_length, preamble) self.assertEqual(r[0], tuple(npayloads*[1, 0, 0, 0])) self.check_match(r[1], (p0, p1, p[0], p[1], p0, p1, p[2], p[3], p0, p1, p[4], p[5], p0, p1, p[6], p[7], p0, p1, p[8], p[9], p0, p1, p[10], p[11], p0, p1, p[12], p[13], p0, p1, p[14], p[15])) if __name__ == '__main__': gr_unittest.run(test_ofdm_insert_preamble, "test_ofdm_insert_preamble.xml") gnuradio-3.7.2.1/gr-digital/python/digital/psk_constellations.py0000775000175000017500000001543112237515112024603 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy from constellation_map_generator import * ''' Note on the naming scheme. Each constellation is named using a prefix for the type of constellation, the order of the constellation, and a distinguishing feature, which comes in three modes: - No extra feature: the basic Gray-coded constellation map; others will be derived from this type. - A single number: an indexed number to uniquely identify different constellation maps. - 0xN_x0_x1..._xM: A permutation of the base constellation, explained below. For rectangular constellations (BPSK, QPSK, QAM), we can define a hyperspace and look for all symmetries. This is also known as the automorphism group of the hypercube, aka the hyperoctahedral group. What this means is that we can easily define all possible rotations in terms of the first base mapping by creating the mapping: f(x) = k XOR pi(x) The x is the bit string for the symbol we are altering. Then k is a bit string of n bits where n is the number of bits per symbol in the constellation (e.g., 2 for QPSK or 6 for QAM64). The pi is a permutation function specified as pi_0, pi_1..., pi_n-1. This permutes the bits from the base constellation symbol to a new code, which is then xor'd by k. The value of k is from 0 to 2^n-1 and pi is a list of all bit positions. The total number of Gray coded modulations is (2^n)*(n!). We create aliases for all possible naming schemes for the constellations. So if a hyperoctahedral group is defined, we also set this function equal to a function name using a unique ID number, and we always select one rotation as our basic rotation that the other rotations are based off of. ''' # BPSK Constellation Mappings def psk_2_0x0(): ''' 0 | 1 ''' const_points = [-1, 1] symbols = [0, 1] return (const_points, symbols) psk_2 = psk_2_0x0 # Basic BPSK rotation psk_2_0 = psk_2 # First ID for BPSK rotations def psk_2_0x1(): ''' 1 | 0 ''' const_points = [-1, 1] symbols = [1, 0] return (const_points, symbols) psk_2_1 = psk_2_0x1 ############################################################ # BPSK Soft bit LUT generators ############################################################ def sd_psk_2_0x0(x, Es=1): ''' 0 | 1 ''' x_re = x.real dist = Es*numpy.sqrt(2) return [dist*x_re,] sd_psk_2 = sd_psk_2_0x0 # Basic BPSK rotation sd_psk_2_0 = sd_psk_2 # First ID for BPSK rotations def sd_psk_2_0x1(x, Es=1): ''' 1 | 0 ''' x_re = [x.real,] dist = Es*numpy.sqrt(2) return -dist*x_re sd_psk_2_1 = sd_psk_2_0x1 ############################################################ # QPSK Constellation Mappings ############################################################ def psk_4_0x0_0_1(): ''' 10 | 11 ------- 00 | 01 ''' const_points = [-1-1j, 1-1j, -1+1j, 1+1j] symbols = [0, 1, 2, 3] return (const_points, symbols) psk_4 = psk_4_0x0_0_1 psk_4_0 = psk_4 def psk_4_0x1_0_1(): ''' 11 | 10 ------- 01 | 00 ''' k = 0x1 pi = [0, 1] return constellation_map_generator(psk_4, k, pi) psk_4_1 = psk_4_0x1_0_1 def psk_4_0x2_0_1(): ''' 00 | 01 ------- 10 | 11 ''' k = 0x2 pi = [0, 1] return constellation_map_generator(psk_4, k, pi) psk_4_2 = psk_4_0x2_0_1 def psk_4_0x3_0_1(): ''' 01 | 00 ------- 11 | 10 ''' k = 0x3 pi = [0, 1] return constellation_map_generator(psk_4, k, pi) psk_4_3 = psk_4_0x3_0_1 def psk_4_0x0_1_0(): ''' 01 | 11 ------- 00 | 10 ''' k = 0x0 pi = [1, 0] return constellation_map_generator(psk_4, k, pi) psk_4_4 = psk_4_0x0_1_0 def psk_4_0x1_1_0(): ''' 00 | 10 ------- 01 | 11 ''' k = 0x1 pi = [1, 0] return constellation_map_generator(psk_4, k, pi) psk_4_5 = psk_4_0x1_1_0 def psk_4_0x2_1_0(): ''' 11 | 01 ------- 10 | 00 ''' k = 0x2 pi = [1, 0] return constellation_map_generator(psk_4, k, pi) psk_4_6 = psk_4_0x2_1_0 def psk_4_0x3_1_0(): ''' 10 | 00 ------- 11 | 01 ''' k = 0x3 pi = [1, 0] return constellation_map_generator(psk_4, k, pi) psk_4_7 = psk_4_0x3_1_0 ############################################################ # QPSK Constellation Softbit LUT generators ############################################################ def sd_psk_4_0x0_0_1(x, Es=1): ''' 10 | 11 ------- 00 | 01 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [dist*x_im, dist*x_re] sd_psk_4 = sd_psk_4_0x0_0_1 sd_psk_4_0 = sd_psk_4 def sd_psk_4_0x1_0_1(x, Es=1): ''' 11 | 10 ------- 01 | 00 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [dist*x_im, -dist*x_re] sd_psk_4_1 = sd_psk_4_0x1_0_1 def sd_psk_4_0x2_0_1(x, Es=1): ''' 00 | 01 ------- 10 | 11 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [-dist*x_im, dist*x_re] sd_psk_4_2 = sd_psk_4_0x2_0_1 def sd_psk_4_0x3_0_1(x, Es=1): ''' 01 | 00 ------- 11 | 10 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [-dist*x_im, -dist*x_re] sd_psk_4_3 = sd_psk_4_0x3_0_1 def sd_psk_4_0x0_1_0(x, Es=1): ''' 01 | 11 ------- 00 | 10 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [dist*x_re, dist*x_im] sd_psk_4_4 = sd_psk_4_0x0_1_0 def sd_psk_4_0x1_1_0(x, Es=1): ''' 00 | 10 ------- 01 | 11 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [dist*x_re, -dist*x_im] sd_psk_4_5 = sd_psk_4_0x1_1_0 def sd_psk_4_0x2_1_0(x, Es=1): ''' 11 | 01 ------- 10 | 00 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [-dist*x_re, dist*x_im] sd_psk_4_6 = sd_psk_4_0x2_1_0 def sd_psk_4_0x3_1_0(x, Es=1): ''' 10 | 00 ------- 11 | 01 ''' x_re = x.real x_im = x.imag dist = Es*numpy.sqrt(2) return [-dist*x_re, -dist*x_im] sd_psk_4_7 = sd_psk_4_0x3_1_0 gnuradio-3.7.2.1/gr-digital/python/digital/qa_constellation.py0000664000175000017500000003101012237515112024210 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random from cmath import exp, pi, log, sqrt from gnuradio import gr, gr_unittest, digital, blocks from gnuradio.digital.utils import mod_codes from gnuradio.digital import psk, qam, qamlike tested_mod_codes = (mod_codes.NO_CODE, mod_codes.GRAY_CODE) # A list of the constellations to test. # Each constellation is given by a 3-tuple. # First item is a function to generate the constellation # Second item is a dictionary of arguments for function with lists of # possible values. # Third item is whether differential encoding should be tested. # Fourth item is the name of the argument to constructor that specifices # whether differential encoding is used. def twod_constell(): """ """ points = ((1+0j), (0+1j), (-1+0j), (0-1j)) rot_sym = 2 dim = 2 return digital.constellation_calcdist(points, [], rot_sym, dim) def threed_constell(): oned_points = ((1+0j), (0+1j), (-1+0j), (0-1j)) points = [] r4 = range(0, 4) for ia in r4: for ib in r4: for ic in r4: points += [oned_points[ia], oned_points[ib], oned_points[ic]] rot_sym = 4 dim = 3 return digital.constellation_calcdist(points, [], rot_sym, dim) # A list of tuples for constellation testing. The contents of the # tuples are (constructor, poss_args, differential, diff_argname). # These constellations should lock on well. easy_constellation_info = ( (psk.psk_constellation, {'m': (2, 4, 8, 16, ), 'mod_code': tested_mod_codes, }, True, None), (psk.psk_constellation, {'m': (2, 4, 8, 16, 32, 64), 'mod_code': tested_mod_codes, 'differential': (False,)}, False, None), (qam.qam_constellation, {'constellation_points': (4,), 'mod_code': tested_mod_codes, 'large_ampls_to_corners': [False],}, True, None), (qam.qam_constellation, {'constellation_points': (4, 16, 64), 'mod_code': tested_mod_codes, 'differential': (False,)}, False, None), (digital.constellation_bpsk, {}, True, None), (digital.constellation_qpsk, {}, False, None), (digital.constellation_dqpsk, {}, True, None), (digital.constellation_8psk, {}, False, None), (twod_constell, {}, True, None), (threed_constell, {}, True, None), ) # These constellations don't work nicely. # We have a lower required error rate. medium_constellation_info = ( (psk.psk_constellation, {'m': (32, 64), 'mod_code': tested_mod_codes, }, True, None), (qam.qam_constellation, {'constellation_points': (16 ,), 'mod_code': tested_mod_codes, 'large_ampls_to_corners': [False, True],}, True, None), (qamlike.qam32_holeinside_constellation, {'large_ampls_to_corners': [True]}, True, None), ) # These constellation are basically broken in our test difficult_constellation_info = ( (qam.qam_constellation, {'constellation_points': (64,), 'mod_code': tested_mod_codes, 'large_ampls_to_corners': [False, True],}, True, None), ) def tested_constellations(easy=True, medium=True, difficult=True): """ Generator to produce (constellation, differential) tuples for testing purposes. """ constellation_info = [] if easy: constellation_info += easy_constellation_info if medium: constellation_info += medium_constellation_info if difficult: constellation_info += difficult_constellation_info for constructor, poss_args, differential, diff_argname in constellation_info: if differential: diff_poss = (True, False) else: diff_poss = (False,) poss_args = [[argname, argvalues, 0] for argname, argvalues in poss_args.items()] for current_diff in diff_poss: # Add an index into args to keep track of current position in argvalues while True: current_args = dict([(argname, argvalues[argindex]) for argname, argvalues, argindex in poss_args]) if diff_argname is not None: current_args[diff_argname] = current_diff constellation = constructor(**current_args) yield (constellation, current_diff) for this_poss_arg in poss_args: argname, argvalues, argindex = this_poss_arg if argindex < len(argvalues) - 1: this_poss_arg[2] += 1 break else: this_poss_arg[2] = 0 if sum([argindex for argname, argvalues, argindex in poss_args]) == 0: break class test_constellation(gr_unittest.TestCase): src_length = 256 def setUp(self): # Generate a list of random bits. self.src_data = tuple([random.randint(0,1) for i in range(0, self.src_length)]) def tearDown(self): pass def test_hard_decision(self): for constellation, differential in tested_constellations(): if differential: rs = constellation.rotational_symmetry() rotations = [exp(i*2*pi*(0+1j)/rs) for i in range(0, rs)] else: rotations = [None] for rotation in rotations: src = blocks.vector_source_b(self.src_data) content = mod_demod(constellation, differential, rotation) dst = blocks.vector_sink_b() self.tb = gr.top_block() self.tb.connect(src, content, dst) self.tb.run() data = dst.data() # Don't worry about cut off data for now. first = constellation.bits_per_symbol() self.assertEqual(self.src_data[first:len(data)], data[first:]) def test_soft_qpsk_gen(self): prec = 8 constel, code = digital.psk_4_0() rot_sym = 1 side = 2 width = 2 c = digital.constellation_rect(constel, code, rot_sym, side, side, width, width) # Get max energy/symbol in constellation constel = c.points() Es = max([abs(constel_i) for constel_i in constel]) table = digital.soft_dec_table_generator(digital.sd_psk_4_0, prec, Es) c.set_soft_dec_lut(table, prec) x = sqrt(2.0)/2.0 step = (x.real+x.real) / (2**prec - 1) samples = [ -x-x*1j, -x+x*1j, x+x*1j, x-x*1j, (-x+128*step)+(-x+128*step)*1j, (-x+64*step) +(-x+64*step)*1j, (-x+64*step) +(-x+192*step)*1j, (-x+192*step)+(-x+192*step)*1j, (-x+192*step)+(-x+64*step)*1j,] y_python_raw_calc = [] y_python_gen_calc = [] y_python_table = [] y_cpp_raw_calc = [] y_cpp_table = [] for sample in samples: y_python_raw_calc += digital.calc_soft_dec(sample, constel, code) y_python_gen_calc += digital.sd_psk_4_0(sample, Es) y_python_table += digital.calc_soft_dec_from_table(sample, table, prec, Es) y_cpp_raw_calc += c.calc_soft_dec(sample) y_cpp_table += c.soft_decision_maker(sample) self.assertFloatTuplesAlmostEqual(y_python_raw_calc, y_python_gen_calc, 4) self.assertFloatTuplesAlmostEqual(y_python_raw_calc, y_python_table, 2) self.assertFloatTuplesAlmostEqual(y_cpp_raw_calc, y_cpp_table, 4) def test_soft_qpsk_calc(self): prec = 8 constel, code = digital.psk_4_0() rot_sym = 1 side = 2 width = 2 c = digital.constellation_rect(constel, code, rot_sym, side, side, width, width) # Get max energy/symbol in constellation constel = c.points() Es = max([abs(constel_i) for constel_i in constel]) table = digital.soft_dec_table(constel, code, prec) c.gen_soft_dec_lut(prec) x = sqrt(2.0)/2.0 step = (x.real+x.real) / (2**prec - 1) samples = [ -x-x*1j, -x+x*1j, x+x*1j, x-x*1j, (-x+128*step)+(-x+128*step)*1j, (-x+64*step) +(-x+64*step)*1j, (-x+64*step) +(-x+192*step)*1j, (-x+192*step)+(-x+192*step)*1j, (-x+192*step)+(-x+64*step)*1j,] y_python_raw_calc = [] y_python_table = [] y_cpp_raw_calc = [] y_cpp_table = [] for sample in samples: y_python_raw_calc += digital.calc_soft_dec(sample, constel, code) y_python_table += digital.calc_soft_dec_from_table(sample, table, prec, Es) y_cpp_raw_calc += c.calc_soft_dec(sample) y_cpp_table += c.soft_decision_maker(sample) self.assertFloatTuplesAlmostEqual(y_python_raw_calc, y_python_table, 4) self.assertFloatTuplesAlmostEqual(y_cpp_raw_calc, y_cpp_table, 4) class mod_demod(gr.hier_block2): def __init__(self, constellation, differential, rotation): if constellation.arity() > 256: # If this becomes limiting some of the blocks should be generalised so # that they can work with shorts and ints as well as chars. raise ValueError("Constellation cannot contain more than 256 points.") gr.hier_block2.__init__(self, "mod_demod", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_char)) # Output signature arity = constellation.arity() # TX self.constellation = constellation self.differential = differential import weakref self.blocks = [weakref.proxy(self)] # We expect a stream of unpacked bits. # First step is to pack them. self.blocks.append(blocks.unpacked_to_packed_bb(1, gr.GR_MSB_FIRST)) # Second step we unpack them such that we have k bits in each byte where # each constellation symbol hold k bits. self.blocks.append( blocks.packed_to_unpacked_bb(self.constellation.bits_per_symbol(), gr.GR_MSB_FIRST)) # Apply any pre-differential coding # Gray-coding is done here if we're also using differential coding. if self.constellation.apply_pre_diff_code(): self.blocks.append(digital.map_bb(self.constellation.pre_diff_code())) # Differential encoding. if self.differential: self.blocks.append(digital.diff_encoder_bb(arity)) # Convert to constellation symbols. self.blocks.append(digital.chunks_to_symbols_bc(self.constellation.points(), self.constellation.dimensionality())) # CHANNEL # Channel just consists of a rotation to check differential coding. if rotation is not None: self.blocks.append(blocks.multiply_const_cc(rotation)) # RX # Convert the constellation symbols back to binary values. self.blocks.append(digital.constellation_decoder_cb(self.constellation.base())) # Differential decoding. if self.differential: self.blocks.append(digital.diff_decoder_bb(arity)) # Decode any pre-differential coding. if self.constellation.apply_pre_diff_code(): self.blocks.append(digital.map_bb( mod_codes.invert_code(self.constellation.pre_diff_code()))) # unpack the k bit vector into a stream of bits self.blocks.append(blocks.unpack_k_bits_bb( self.constellation.bits_per_symbol())) # connect to block output check_index = len(self.blocks) self.blocks = self.blocks[:check_index] self.blocks.append(weakref.proxy(self)) self.connect(*self.blocks) if __name__ == '__main__': gr_unittest.run(test_constellation, "test_constellation.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_mpsk_snr_est.py0000775000175000017500000001003112207440367024052 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random from gnuradio import gr, gr_unittest, digital, blocks def get_cplx(): return complex(2*random.randint(0,1) - 1, 0) def get_n_cplx(): return complex(random.random()-0.5, random.random()-0.5) class test_mpsk_snr_est(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() random.seed(0) # make repeatable N = 10000 self._noise = [get_n_cplx() for i in xrange(N)] self._bits = [get_cplx() for i in xrange(N)] def tearDown(self): self.tb = None def mpsk_snr_est_setup(self, op): result = [] for i in xrange(1,6): src_data = [b+(i*n) for b,n in zip(self._bits, self._noise)] src = blocks.vector_source_c(src_data) dst = blocks.null_sink(gr.sizeof_gr_complex) tb = gr.top_block() tb.connect(src, op) tb.connect(op, dst) tb.run() # run the graph and wait for it to finish result.append(op.snr()) return result def test_mpsk_snr_est_simple(self): expected_result = [11.48, 5.91, 3.30, 2.08, 1.46] N = 10000 alpha = 0.001 op = digital.mpsk_snr_est_cc(digital.SNR_EST_SIMPLE, N, alpha) actual_result = self.mpsk_snr_est_setup(op) self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 2) def test_mpsk_snr_est_skew(self): expected_result = [11.48, 5.91, 3.30, 2.08, 1.46] N = 10000 alpha = 0.001 op = digital.mpsk_snr_est_cc(digital.SNR_EST_SKEW, N, alpha) actual_result = self.mpsk_snr_est_setup(op) self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 2) def test_mpsk_snr_est_m2m4(self): expected_result = [11.02, 6.20, 4.98, 5.16, 5.66] N = 10000 alpha = 0.001 op = digital.mpsk_snr_est_cc(digital.SNR_EST_M2M4, N, alpha) actual_result = self.mpsk_snr_est_setup(op) self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 2) def test_mpsk_snr_est_svn(self): expected_result = [10.92, 6.02, 4.78, 4.98, 5.51] N = 10000 alpha = 0.001 op = digital.mpsk_snr_est_cc(digital.SNR_EST_SVR, N, alpha) actual_result = self.mpsk_snr_est_setup(op) self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 2) def test_probe_mpsk_snr_est_m2m4(self): expected_result = [11.02, 6.20, 4.98, 5.16, 5.66] actual_result = [] for i in xrange(1,6): src_data = [b+(i*n) for b,n in zip(self._bits, self._noise)] src = blocks.vector_source_c(src_data) N = 10000 alpha = 0.001 op = digital.probe_mpsk_snr_est_c(digital.SNR_EST_M2M4, N, alpha) tb = gr.top_block() tb.connect(src, op) tb.run() # run the graph and wait for it to finish actual_result.append(op.snr()) self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 2) if __name__ == '__main__': # Test various SNR estimators; we're not using a Gaussian # noise source, so these estimates have no real meaning; # just a sanity check. gr_unittest.run(test_mpsk_snr_est, "test_mpsk_snr_est.xml") gnuradio-3.7.2.1/gr-digital/python/digital/cpm.py0000664000175000017500000002073312207440367021450 0ustar jcorganjcorgan# # CPM modulation and demodulation. # # # Copyright 2005-2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # See gnuradio-examples/python/digital for examples from gnuradio import gr, filter from gnuradio import analog from gnuradio import blocks from math import pi import numpy import digital_swig import modulation_utils # default values (used in __init__ and add_options) _def_samples_per_symbol = 2 _def_bits_per_symbol = 1 _def_h_numerator = 1 _def_h_denominator = 2 _def_cpm_type = 0 # 0=CPFSK, 1=GMSK, 2=RC, 3=GENERAL _def_bt = 0.35 _def_symbols_per_pulse = 1 _def_generic_taps = numpy.empty(1) _def_verbose = False _def_log = False # ///////////////////////////////////////////////////////////////////////////// # CPM modulator # ///////////////////////////////////////////////////////////////////////////// class cpm_mod(gr.hier_block2): """ Hierarchical block for Continuous Phase modulation. The input is a byte stream (unsigned char) representing packed bits and the output is the complex modulated signal at baseband. See Proakis for definition of generic CPM signals: s(t)=exp(j phi(t)) phi(t)= 2 pi h int_0^t f(t') dt' f(t)=sum_k a_k g(t-kT) (normalizing assumption: int_0^infty g(t) dt = 1/2) Args: samples_per_symbol: samples per baud >= 2 (integer) bits_per_symbol: bits per symbol (integer) h_numerator: numerator of modulation index (integer) h_denominator: denominator of modulation index (numerator and denominator must be relative primes) (integer) cpm_type: supported types are: 0=CPFSK, 1=GMSK, 2=RC, 3=GENERAL (integer) bt: bandwidth symbol time product for GMSK (float) symbols_per_pulse: shaping pulse duration in symbols (integer) generic_taps: define a generic CPM pulse shape (sum = samples_per_symbol/2) (list/array of floats) verbose: Print information about modulator? (boolean) debug: Print modulation data to files? (boolean) """ def __init__(self, samples_per_symbol=_def_samples_per_symbol, bits_per_symbol=_def_bits_per_symbol, h_numerator=_def_h_numerator, h_denominator=_def_h_denominator, cpm_type=_def_cpm_type, bt=_def_bt, symbols_per_pulse=_def_symbols_per_pulse, generic_taps=_def_generic_taps, verbose=_def_verbose, log=_def_log): gr.hier_block2.__init__(self, "cpm_mod", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._samples_per_symbol = samples_per_symbol self._bits_per_symbol = bits_per_symbol self._h_numerator = h_numerator self._h_denominator = h_denominator self._cpm_type = cpm_type self._bt=bt if cpm_type == 0 or cpm_type == 2 or cpm_type == 3: # CPFSK, RC, Generic self._symbols_per_pulse = symbols_per_pulse elif cpm_type == 1: # GMSK self._symbols_per_pulse = 4 else: raise TypeError, ("cpm_type must be an integer in {0,1,2,3}, is %r" % (cpm_type,)) self._generic_taps=numpy.array(generic_taps) if samples_per_symbol < 2: raise TypeError, ("samples_per_symbol must be >= 2, is %r" % (samples_per_symbol,)) self.nsymbols = 2**bits_per_symbol self.sym_alphabet = numpy.arange(-(self.nsymbols-1),self.nsymbols,2).tolist() self.ntaps = int(self._symbols_per_pulse * samples_per_symbol) sensitivity = 2 * pi * h_numerator / h_denominator / samples_per_symbol # Unpack Bytes into bits_per_symbol groups self.B2s = blocks.packed_to_unpacked_bb(bits_per_symbol,gr.GR_MSB_FIRST) # Turn it into symmetric PAM data. self.pam = digital_swig.chunks_to_symbols_bf(self.sym_alphabet,1) # Generate pulse (sum of taps = samples_per_symbol/2) if cpm_type == 0: # CPFSK self.taps= (1.0/self._symbols_per_pulse/2,) * self.ntaps elif cpm_type == 1: # GMSK gaussian_taps = filter.firdes.gaussian( 1.0/2, # gain samples_per_symbol, # symbol_rate bt, # bandwidth * symbol time self.ntaps # number of taps ) sqwave = (1,) * samples_per_symbol # rectangular window self.taps = numpy.convolve(numpy.array(gaussian_taps),numpy.array(sqwave)) elif cpm_type == 2: # Raised Cosine # generalize it for arbitrary roll-off factor self.taps = (1-numpy.cos(2*pi*numpy.arange(0,self.ntaps)/samples_per_symbol/self._symbols_per_pulse))/(2*self._symbols_per_pulse) elif cpm_type == 3: # Generic CPM self.taps = generic_taps else: raise TypeError, ("cpm_type must be an integer in {0,1,2,3}, is %r" % (cpm_type,)) self.filter = filter.pfb.arb_resampler_fff(samples_per_symbol, self.taps) # FM modulation self.fmmod = analog.frequency_modulator_fc(sensitivity) if verbose: self._print_verbage() if log: self._setup_logging() # Connect self.connect(self, self.B2s, self.pam, self.filter, self.fmmod, self) def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self): return self._bits_per_symbol def h_numerator(self): return self._h_numerator def h_denominator(self): return self._h_denominator def cpm_type(self): return self._cpm_type def bt(self): return self._bt def symbols_per_pulse(self): return self._symbols_per_pulse def _print_verbage(self): print "Samples per symbol = %d" % self._samples_per_symbol print "Bits per symbol = %d" % self._bits_per_symbol print "h = " , self._h_numerator , " / " , self._h_denominator print "Symbol alphabet = " , self.sym_alphabet print "Symbols per pulse = %d" % self._symbols_per_pulse print "taps = " , self.taps print "CPM type = %d" % self._cpm_type if self._cpm_type == 1: print "Gaussian filter BT = %.2f" % self._bt def _setup_logging(self): print "Modulation logging turned on." self.connect(self.B2s, blocks.file_sink(gr.sizeof_float, "symbols.dat")) self.connect(self.pam, blocks.file_sink(gr.sizeof_float, "pam.dat")) self.connect(self.filter, blocks.file_sink(gr.sizeof_float, "filter.dat")) self.connect(self.fmmod, blocks.file_sink(gr.sizeof_gr_complex, "fmmod.dat")) def add_options(parser): """ Adds CPM modulation-specific options to the standard parser """ parser.add_option("", "--bt", type="float", default=_def_bt, help="set bandwidth-time product [default=%default] (GMSK)") add_options=staticmethod(add_options) def extract_kwargs_from_options(options): """ Given command line options, create dictionary suitable for passing to __init__ """ return modulation_utils.extract_kwargs_from_options(cpm_mod.__init__, ('self',), options) extract_kwargs_from_options=staticmethod(extract_kwargs_from_options) # ///////////////////////////////////////////////////////////////////////////// # CPM demodulator # ///////////////////////////////////////////////////////////////////////////// # # Not yet implemented # # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('cpm', cpm_mod) #modulation_utils.add_type_1_demod('cpm', cpm_demod) gnuradio-3.7.2.1/gr-digital/python/digital/bpsk.py0000664000175000017500000001271712207440367021633 0ustar jcorganjcorgan# # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ BPSK modulation and demodulation. """ from math import pi, log from cmath import exp from gnuradio import gr from gnuradio.digital.generic_mod_demod import generic_mod, generic_demod from gnuradio.digital.generic_mod_demod import shared_mod_args, shared_demod_args import digital_swig import modulation_utils # ///////////////////////////////////////////////////////////////////////////// # BPSK constellation # ///////////////////////////////////////////////////////////////////////////// def bpsk_constellation(): return digital_swig.constellation_bpsk() # ///////////////////////////////////////////////////////////////////////////// # BPSK modulator # ///////////////////////////////////////////////////////////////////////////// class bpsk_mod(generic_mod): """ Hierarchical block for RRC-filtered BPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Argument is not used. It exists purely to simplify generation of the block in grc. differential: Whether to use differential encoding (boolean). """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, mod_code=None, differential=False, *args, **kwargs): constellation = digital_swig.constellation_bpsk() super(bpsk_mod, self).__init__(constellation=constellation, differential=differential, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # BPSK demodulator # # ///////////////////////////////////////////////////////////////////////////// class bpsk_demod(generic_demod): """ Hierarchical block for RRC-filtered BPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Argument is not used. It exists purely to simplify generation of the block in grc. differential: whether to use differential encoding (boolean) """ # See generic_demod for additional arguments __doc__ += shared_demod_args def __init__(self, mod_code=None, differential=False, *args, **kwargs): constellation = digital_swig.constellation_bpsk() super(bpsk_demod, self).__init__(constellation=constellation, differential=differential, *args, **kwargs) #bpsk_demod.__doc__ += shared_demod_args # ///////////////////////////////////////////////////////////////////////////// # DBPSK constellation # ///////////////////////////////////////////////////////////////////////////// def dbpsk_constellation(): return digital_swig.constellation_dbpsk() # ///////////////////////////////////////////////////////////////////////////// # DBPSK modulator # ///////////////////////////////////////////////////////////////////////////// class dbpsk_mod(bpsk_mod): """ Hierarchical block for RRC-filtered DBPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Argument is not used. It exists purely to simplify generation of the block in grc. """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, mod_code=None, *args, **kwargs): super(dbpsk_mod, self).__init__(*args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # DBPSK demodulator # # ///////////////////////////////////////////////////////////////////////////// class dbpsk_demod(bpsk_demod): """ Hierarchical block for RRC-filtered DBPSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: mod_code: Argument is not used. It exists purely to simplify generation of the block in grc. """ # See generic_demod for additional arguments __doc__ += shared_demod_args def __init__(self, mod_code=None, *args, **kwargs): super(dbpsk_demod, self).__init__(*args, **kwargs) # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('bpsk', bpsk_mod) modulation_utils.add_type_1_demod('bpsk', bpsk_demod) modulation_utils.add_type_1_constellation('bpsk', bpsk_constellation) modulation_utils.add_type_1_mod('dbpsk', dbpsk_mod) modulation_utils.add_type_1_demod('dbpsk', dbpsk_demod) modulation_utils.add_type_1_constellation('dbpsk', dbpsk_constellation) gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_sync_pn.py0000664000175000017500000001252212207440367023344 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from numpy import fft from gnuradio import gr try: from gnuradio import filter except ImportError: import filter_swig as filter try: from gnuradio import blocks except ImportError: import blocks_swig as blocks class ofdm_sync_pn(gr.hier_block2): def __init__(self, fft_length, cp_length, logging=False): """ OFDM synchronization using PN Correlation: T. M. Schmidl and D. C. Cox, "Robust Frequency and Timing Synchonization for OFDM," IEEE Trans. Communications, vol. 45, no. 12, 1997. """ gr.hier_block2.__init__(self, "ofdm_sync_pn", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature2(2, 2, gr.sizeof_float, gr.sizeof_char)) # Output signature self.input = blocks.add_const_cc(0) # PN Sync # Create a delay line self.delay = blocks.delay(gr.sizeof_gr_complex, fft_length/2) # Correlation from ML Sync self.conjg = blocks.conjugate_cc(); self.corr = blocks.multiply_cc(); # Create a moving sum filter for the corr output if 1: moving_sum_taps = [1.0 for i in range(fft_length//2)] self.moving_sum_filter = filter.fir_filter_ccf(1,moving_sum_taps) else: moving_sum_taps = [complex(1.0,0.0) for i in range(fft_length//2)] self.moving_sum_filter = filter.fft_filter_ccc(1,moving_sum_taps) # Create a moving sum filter for the input self.inputmag2 = blocks.complex_to_mag_squared() movingsum2_taps = [1.0 for i in range(fft_length//2)] if 1: self.inputmovingsum = filter.fir_filter_fff(1,movingsum2_taps) else: self.inputmovingsum = filter.fft_filter_fff(1,movingsum2_taps) self.square = blocks.multiply_ff() self.normalize = blocks.divide_ff() # Get magnitude (peaks) and angle (phase/freq error) self.c2mag = blocks.complex_to_mag_squared() self.angle = blocks.complex_to_arg() self.sample_and_hold = blocks.sample_and_hold_ff() #ML measurements input to sampler block and detect self.sub1 = blocks.add_const_ff(-1) self.pk_detect = blocks.peak_detector_fb(0.20, 0.20, 30, 0.001) #self.pk_detect = blocks.peak_detector2_fb(9) self.connect(self, self.input) # Calculate the frequency offset from the correlation of the preamble self.connect(self.input, self.delay) self.connect(self.input, (self.corr,0)) self.connect(self.delay, self.conjg) self.connect(self.conjg, (self.corr,1)) self.connect(self.corr, self.moving_sum_filter) self.connect(self.moving_sum_filter, self.c2mag) self.connect(self.moving_sum_filter, self.angle) self.connect(self.angle, (self.sample_and_hold,0)) # Get the power of the input signal to normalize the output of the correlation self.connect(self.input, self.inputmag2, self.inputmovingsum) self.connect(self.inputmovingsum, (self.square,0)) self.connect(self.inputmovingsum, (self.square,1)) self.connect(self.square, (self.normalize,1)) self.connect(self.c2mag, (self.normalize,0)) # Create a moving sum filter for the corr output matched_filter_taps = [1.0/cp_length for i in range(cp_length)] self.matched_filter = filter.fir_filter_fff(1,matched_filter_taps) self.connect(self.normalize, self.matched_filter) self.connect(self.matched_filter, self.sub1, self.pk_detect) #self.connect(self.matched_filter, self.pk_detect) self.connect(self.pk_detect, (self.sample_and_hold,1)) # Set output signals # Output 0: fine frequency correction value # Output 1: timing signal self.connect(self.sample_and_hold, (self,0)) self.connect(self.pk_detect, (self,1)) if logging: self.connect(self.matched_filter, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pn-mf_f.dat")) self.connect(self.normalize, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pn-theta_f.dat")) self.connect(self.angle, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pn-epsilon_f.dat")) self.connect(self.pk_detect, blocks.file_sink(gr.sizeof_char, "ofdm_sync_pn-peaks_b.dat")) self.connect(self.sample_and_hold, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pn-sample_and_hold_f.dat")) self.connect(self.input, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_sync_pn-input_c.dat")) gnuradio-3.7.2.1/gr-digital/python/digital/qa_chunks_to_symbols.py0000775000175000017500000001415112237515112025111 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import pmt from gnuradio import gr, gr_unittest, digital, blocks class test_chunks_to_symbols(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_bc_001(self): const = [ 1+0j, 0+1j, -1+0j, 0-1j] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (1+0j, 0+1j, -1+0j, 0-1j, 0-1j, -1+0j, 0+1j, 1+0j) src = blocks.vector_source_b(src_data) op = digital.chunks_to_symbols_bc(const) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_bf_002(self): const = [-3, -1, 1, 3] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (-3, -1, 1, 3, 3, 1, -1, -3) src = blocks.vector_source_b(src_data) op = digital.chunks_to_symbols_bf(const) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_ic_003(self): const = [ 1+0j, 0+1j, -1+0j, 0-1j] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (1+0j, 0+1j, -1+0j, 0-1j, 0-1j, -1+0j, 0+1j, 1+0j) src = blocks.vector_source_i(src_data) op = digital.chunks_to_symbols_ic(const) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_if_004(self): const = [-3, -1, 1, 3] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (-3, -1, 1, 3, 3, 1, -1, -3) src = blocks.vector_source_i(src_data) op = digital.chunks_to_symbols_if(const) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_sc_005(self): const = [ 1+0j, 0+1j, -1+0j, 0-1j] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (1+0j, 0+1j, -1+0j, 0-1j, 0-1j, -1+0j, 0+1j, 1+0j) src = blocks.vector_source_s(src_data) op = digital.chunks_to_symbols_sc(const) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_sf_006(self): const = [-3, -1, 1, 3] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (-3, -1, 1, 3, 3, 1, -1, -3) src = blocks.vector_source_s(src_data) op = digital.chunks_to_symbols_sf(const) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_sf_tag(self): constA = [-3.0, -1.0, 1.0, 3] constB = [12.0, -12.0, 6.0, -6] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (-3, -1, 1, 3, -6, 6, -12, 12) first_tag = gr.tag_t() first_tag.key = pmt.intern("set_symbol_table") first_tag.value = pmt.init_f32vector(len(constA), constA) first_tag.offset = 0 second_tag = gr.tag_t() second_tag.key = pmt.intern("set_symbol_table") second_tag.value = pmt.init_f32vector(len(constB), constB) second_tag.offset = 4 src = blocks.vector_source_s(src_data, False, 1, [first_tag, second_tag]) op = digital.chunks_to_symbols_sf(constB) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) def test_sc_tag(self): constA = [-3.0+1j, -1.0-1j, 1.0+1j, 3-1j] constB = [12.0+1j, -12.0-1j, 6.0+1j, -6-1j] src_data = (0, 1, 2, 3, 3, 2, 1, 0) expected_result = (-3+1j, -1-1j, 1+1j, 3-1j, -6-1j, 6+1j, -12-1j, 12+1j) first_tag = gr.tag_t() first_tag.key = pmt.intern("set_symbol_table") first_tag.value = pmt.init_c32vector(len(constA), constA) first_tag.offset = 0 second_tag = gr.tag_t() second_tag.key = pmt.intern("set_symbol_table") second_tag.value = pmt.init_c32vector(len(constB), constB) second_tag.offset = 4 src = blocks.vector_source_s(src_data, False, 1, [first_tag, second_tag]) op = digital.chunks_to_symbols_sc(constB) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() self.assertEqual(expected_result, actual_result) if __name__ == '__main__': gr_unittest.run(test_chunks_to_symbols, "test_chunks_to_symbols.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_pfb_clock_sync.py0000775000175000017500000001122712237515112024323 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import cmath from gnuradio import gr, gr_unittest, filter, digital, blocks class test_pfb_clock_sync(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): # Test BPSK sync excess_bw = 0.35 sps = 4 loop_bw = cmath.pi/100.0 nfilts = 32 init_phase = nfilts/2 max_rate_deviation = 0.5 osps = 1 ntaps = 11 * int(sps*nfilts) taps = filter.firdes.root_raised_cosine(nfilts, nfilts*sps, 1.0, excess_bw, ntaps) self.test = digital.pfb_clock_sync_ccf(sps, loop_bw, taps, nfilts, init_phase, max_rate_deviation, osps) data = 10000*[complex(1,0), complex(-1,0)] self.src = blocks.vector_source_c(data, False) # pulse shaping interpolation filter rrc_taps = filter.firdes.root_raised_cosine( nfilts, # gain nfilts, # sampling rate based on 32 filters in resampler 1.0, # symbol rate excess_bw, # excess bandwidth (roll-off factor) ntaps) self.rrc_filter = filter.pfb_arb_resampler_ccf(sps, rrc_taps) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.rrc_filter, self.test, self.snk) self.tb.run() expected_result = 10000*[complex(1,0), complex(-1,0)] dst_data = self.snk.data() # Only compare last Ncmp samples Ncmp = 1000 len_e = len(expected_result) len_d = len(dst_data) expected_result = expected_result[len_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #for e,d in zip(expected_result, dst_data): # print e, d self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 1) def test02(self): # Test real BPSK sync excess_bw = 0.35 sps = 4 loop_bw = cmath.pi/100.0 nfilts = 32 init_phase = nfilts/2 max_rate_deviation = 0.5 osps = 1 ntaps = 11 * int(sps*nfilts) taps = filter.firdes.root_raised_cosine(nfilts, nfilts*sps, 1.0, excess_bw, ntaps) self.test = digital.pfb_clock_sync_fff(sps, loop_bw, taps, nfilts, init_phase, max_rate_deviation, osps) data = 10000*[1, -1] self.src = blocks.vector_source_f(data, False) # pulse shaping interpolation filter rrc_taps = filter.firdes.root_raised_cosine( nfilts, # gain nfilts, # sampling rate based on 32 filters in resampler 1.0, # symbol rate excess_bw, # excess bandwidth (roll-off factor) ntaps) self.rrc_filter = filter.pfb_arb_resampler_fff(sps, rrc_taps) self.snk = blocks.vector_sink_f() self.tb.connect(self.src, self.rrc_filter, self.test, self.snk) self.tb.run() expected_result = 10000*[1, -1] dst_data = self.snk.data() # Only compare last Ncmp samples Ncmp = 1000 len_e = len(expected_result) len_d = len(dst_data) expected_result = expected_result[len_e - Ncmp:] dst_data = dst_data[len_d - Ncmp:] #for e,d in zip(expected_result, dst_data): # print e, d self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 1) if __name__ == '__main__': gr_unittest.run(test_pfb_clock_sync, "test_pfb_clock_sync.xml") gnuradio-3.7.2.1/gr-digital/python/digital/gmsk.py0000664000175000017500000002533412207440367021634 0ustar jcorganjcorgan# # GMSK modulation and demodulation. # # # Copyright 2005-2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # See gnuradio-examples/python/digital for examples from math import pi from pprint import pprint import inspect import numpy from gnuradio import gr, blocks, analog, filter import modulation_utils import digital_swig as digital # default values (used in __init__ and add_options) _def_samples_per_symbol = 2 _def_bt = 0.35 _def_verbose = False _def_log = False _def_gain_mu = None _def_mu = 0.5 _def_freq_error = 0.0 _def_omega_relative_limit = 0.005 # FIXME: Figure out how to make GMSK work with pfb_arb_resampler_fff for both # transmit and receive so we don't require integer samples per symbol. # ///////////////////////////////////////////////////////////////////////////// # GMSK modulator # ///////////////////////////////////////////////////////////////////////////// class gmsk_mod(gr.hier_block2): """ Hierarchical block for Gaussian Minimum Shift Key (GMSK) modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: samples_per_symbol: samples per baud >= 2 (integer) bt: Gaussian filter bandwidth * symbol time (float) verbose: Print information about modulator? (boolean) debug: Print modulation data to files? (boolean) """ def __init__(self, samples_per_symbol=_def_samples_per_symbol, bt=_def_bt, verbose=_def_verbose, log=_def_log): gr.hier_block2.__init__(self, "gmsk_mod", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature samples_per_symbol = int(samples_per_symbol) self._samples_per_symbol = samples_per_symbol self._bt = bt self._differential = False if not isinstance(samples_per_symbol, int) or samples_per_symbol < 2: raise TypeError, ("samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,)) ntaps = 4 * samples_per_symbol # up to 3 bits in filter at once sensitivity = (pi / 2) / samples_per_symbol # phase change per bit = pi / 2 # Turn it into NRZ data. #self.nrz = digital.bytes_to_syms() self.unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST) self.nrz = digital.chunks_to_symbols_bf([-1, 1], 1) # Form Gaussian filter # Generate Gaussian response (Needs to be convolved with window below). self.gaussian_taps = filter.firdes.gaussian( 1, # gain samples_per_symbol, # symbol_rate bt, # bandwidth * symbol time ntaps # number of taps ) self.sqwave = (1,) * samples_per_symbol # rectangular window self.taps = numpy.convolve(numpy.array(self.gaussian_taps),numpy.array(self.sqwave)) self.gaussian_filter = filter.interp_fir_filter_fff(samples_per_symbol, self.taps) # FM modulation self.fmmod = analog.frequency_modulator_fc(sensitivity) if verbose: self._print_verbage() if log: self._setup_logging() # Connect & Initialize base class self.connect(self, self.unpack, self.nrz, self.gaussian_filter, self.fmmod, self) def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self=None): # staticmethod that's also callable on an instance return 1 bits_per_symbol = staticmethod(bits_per_symbol) # make it a static method. def _print_verbage(self): print "bits per symbol = %d" % self.bits_per_symbol() print "Gaussian filter bt = %.2f" % self._bt def _setup_logging(self): print "Modulation logging turned on." self.connect(self.nrz, blocks.file_sink(gr.sizeof_float, "nrz.dat")) self.connect(self.gaussian_filter, blocks.file_sink(gr.sizeof_float, "gaussian_filter.dat")) self.connect(self.fmmod, blocks.file_sink(gr.sizeof_gr_complex, "fmmod.dat")) def add_options(parser): """ Adds GMSK modulation-specific options to the standard parser """ parser.add_option("", "--bt", type="float", default=_def_bt, help="set bandwidth-time product [default=%default] (GMSK)") add_options=staticmethod(add_options) def extract_kwargs_from_options(options): """ Given command line options, create dictionary suitable for passing to __init__ """ return modulation_utils.extract_kwargs_from_options(gmsk_mod.__init__, ('self',), options) extract_kwargs_from_options=staticmethod(extract_kwargs_from_options) # ///////////////////////////////////////////////////////////////////////////// # GMSK demodulator # ///////////////////////////////////////////////////////////////////////////// class gmsk_demod(gr.hier_block2): """ Hierarchical block for Gaussian Minimum Shift Key (GMSK) demodulation. The input is the complex modulated signal at baseband. The output is a stream of bits packed 1 bit per byte (the LSB) Args: samples_per_symbol: samples per baud (integer) verbose: Print information about modulator? (boolean) log: Print modualtion data to files? (boolean) gain_mu: controls rate of mu adjustment (float) mu: fractional delay [0.0, 1.0] (float) omega_relative_limit: sets max variation in omega (float) freq_error: bit rate error as a fraction (float) """ def __init__(self, samples_per_symbol=_def_samples_per_symbol, gain_mu=_def_gain_mu, mu=_def_mu, omega_relative_limit=_def_omega_relative_limit, freq_error=_def_freq_error, verbose=_def_verbose, log=_def_log): gr.hier_block2.__init__(self, "gmsk_demod", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_char)) # Output signature self._samples_per_symbol = samples_per_symbol self._gain_mu = gain_mu self._mu = mu self._omega_relative_limit = omega_relative_limit self._freq_error = freq_error self._differential = False if samples_per_symbol < 2: raise TypeError, "samples_per_symbol >= 2, is %f" % samples_per_symbol self._omega = samples_per_symbol*(1+self._freq_error) if not self._gain_mu: self._gain_mu = 0.175 self._gain_omega = .25 * self._gain_mu * self._gain_mu # critically damped # Demodulate FM sensitivity = (pi / 2) / samples_per_symbol self.fmdemod = analog.quadrature_demod_cf(1.0 / sensitivity) # the clock recovery block tracks the symbol clock and resamples as needed. # the output of the block is a stream of soft symbols (float) self.clock_recovery = digital.clock_recovery_mm_ff(self._omega, self._gain_omega, self._mu, self._gain_mu, self._omega_relative_limit) # slice the floats at 0, outputting 1 bit (the LSB of the output byte) per sample self.slicer = digital.binary_slicer_fb() if verbose: self._print_verbage() if log: self._setup_logging() # Connect & Initialize base class self.connect(self, self.fmdemod, self.clock_recovery, self.slicer, self) def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self=None): # staticmethod that's also callable on an instance return 1 bits_per_symbol = staticmethod(bits_per_symbol) # make it a static method. def _print_verbage(self): print "bits per symbol = %d" % self.bits_per_symbol() print "M&M clock recovery omega = %f" % self._omega print "M&M clock recovery gain mu = %f" % self._gain_mu print "M&M clock recovery mu = %f" % self._mu print "M&M clock recovery omega rel. limit = %f" % self._omega_relative_limit print "frequency error = %f" % self._freq_error def _setup_logging(self): print "Demodulation logging turned on." self.connect(self.fmdemod, blocks.file_sink(gr.sizeof_float, "fmdemod.dat")) self.connect(self.clock_recovery, blocks.file_sink(gr.sizeof_float, "clock_recovery.dat")) self.connect(self.slicer, blocks.file_sink(gr.sizeof_char, "slicer.dat")) def add_options(parser): """ Adds GMSK demodulation-specific options to the standard parser """ parser.add_option("", "--gain-mu", type="float", default=_def_gain_mu, help="M&M clock recovery gain mu [default=%default] (GMSK/PSK)") parser.add_option("", "--mu", type="float", default=_def_mu, help="M&M clock recovery mu [default=%default] (GMSK/PSK)") parser.add_option("", "--omega-relative-limit", type="float", default=_def_omega_relative_limit, help="M&M clock recovery omega relative limit [default=%default] (GMSK/PSK)") parser.add_option("", "--freq-error", type="float", default=_def_freq_error, help="M&M clock recovery frequency error [default=%default] (GMSK)") add_options=staticmethod(add_options) def extract_kwargs_from_options(options): """ Given command line options, create dictionary suitable for passing to __init__ """ return modulation_utils.extract_kwargs_from_options(gmsk_demod.__init__, ('self',), options) extract_kwargs_from_options=staticmethod(extract_kwargs_from_options) # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('gmsk', gmsk_mod) modulation_utils.add_type_1_demod('gmsk', gmsk_demod) gnuradio-3.7.2.1/gr-digital/python/digital/qa_map.py0000775000175000017500000000336212207440367022131 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_map(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def helper(self, symbols): src_data = [0, 1, 2, 3, 0, 1, 2, 3] expected_data = map(lambda x: symbols[x], src_data) src = blocks.vector_source_b(src_data) op = digital.map_bb(symbols) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() result_data = list(dst.data()) self.assertEqual(expected_data, result_data) def test_001(self): symbols = [0, 0, 0, 0] self.helper(symbols) def test_002(self): symbols = [3, 2, 1, 0] self.helper(symbols) def test_003(self): symbols = [8-1, 32-1, 128, 256-1] self.helper(symbols) if __name__ == '__main__': gr_unittest.run(test_map, "test_map.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_cyclic_prefixer.py0000775000175000017500000000671012207440367025533 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks import pmt class test_ofdm_cyclic_prefixer (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_wo_tags_no_rolloff(self): " The easiest test: make sure the CP is added correctly. " fft_len = 8 cp_len = 2 expected_result = (6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7) src = blocks.vector_source_c(range(fft_len) * 2, False, fft_len) cp = digital.ofdm_cyclic_prefixer(fft_len, fft_len + cp_len) sink = blocks.vector_sink_c() self.tb.connect(src, cp, sink) self.tb.run() self.assertEqual(sink.data(), expected_result) def test_wo_tags_2s_rolloff(self): " No tags, but have a 2-sample rolloff " fft_len = 8 cp_len = 2 rolloff = 2 expected_result = (7.0/2, 8, 1, 2, 3, 4, 5, 6, 7, 8, # 1.0/2 7.0/2+1.0/2, 8, 1, 2, 3, 4, 5, 6, 7, 8) src = blocks.vector_source_c(range(1, fft_len+1) * 2, False, fft_len) cp = digital.ofdm_cyclic_prefixer(fft_len, fft_len + cp_len, rolloff) sink = blocks.vector_sink_c() self.tb.connect(src, cp, sink) self.tb.run() self.assertEqual(sink.data(), expected_result) def test_with_tags_2s_rolloff(self): " With tags and a 2-sample rolloff " fft_len = 8 cp_len = 2 tag_name = "length" expected_result = (7.0/2, 8, 1, 2, 3, 4, 5, 6, 7, 8, # 1.0/2 7.0/2+1.0/2, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1.0/2) tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(2) tag2 = gr.tag_t() tag2.offset = 1 tag2.key = pmt.string_to_symbol("random_tag") tag2.value = pmt.from_long(42) src = blocks.vector_source_c(range(1, fft_len+1) * 2, False, fft_len, (tag, tag2)) cp = digital.ofdm_cyclic_prefixer(fft_len, fft_len + cp_len, 2, tag_name) sink = blocks.vector_sink_c() self.tb.connect(src, cp, sink) self.tb.run() self.assertEqual(sink.data(), expected_result) tags = [gr.tag_to_python(x) for x in sink.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) expected_tags = [ (0, tag_name, len(expected_result)), (fft_len+cp_len, "random_tag", 42) ] self.assertEqual(tags, expected_tags) if __name__ == '__main__': gr_unittest.run(test_ofdm_cyclic_prefixer, "test_ofdm_cyclic_prefixer.xml") gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_receiver.py0000664000175000017500000001745412207440367023510 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006-2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from numpy import fft from gnuradio import fft as gr_fft from gnuradio import gr from gnuradio import analog from gnuradio import blocks from gnuradio import filter import digital_swig as digital from ofdm_sync_pn import ofdm_sync_pn from ofdm_sync_fixed import ofdm_sync_fixed from ofdm_sync_pnac import ofdm_sync_pnac from ofdm_sync_ml import ofdm_sync_ml try: from gnuradio import filter except ImportError: import filter_swig as filter class ofdm_receiver(gr.hier_block2): """ Performs receiver synchronization on OFDM symbols. The receiver performs channel filtering as well as symbol, frequency, and phase synchronization. The synchronization routines are available in three flavors: preamble correlator (Schmidl and Cox), modifid preamble correlator with autocorrelation (not yet working), and cyclic prefix correlator (Van de Beeks). """ def __init__(self, fft_length, cp_length, occupied_tones, snr, ks, logging=False): """ Hierarchical block for receiving OFDM symbols. The input is the complex modulated signal at baseband. Synchronized packets are sent back to the demodulator. Args: fft_length: total number of subcarriers (int) cp_length: length of cyclic prefix as specified in subcarriers (<= fft_length) (int) occupied_tones: number of subcarriers used for data (int) snr: estimated signal to noise ratio used to guide cyclic prefix synchronizer (float) ks: known symbols used as preambles to each packet (list of lists) logging: turn file logging on or off (bool) """ gr.hier_block2.__init__(self, "ofdm_receiver", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature2(2, 2, gr.sizeof_gr_complex*occupied_tones, gr.sizeof_char)) # Output signature bw = (float(occupied_tones) / float(fft_length)) / 2.0 tb = bw*0.08 chan_coeffs = filter.firdes.low_pass (1.0, # gain 1.0, # sampling rate bw+tb, # midpoint of trans. band tb, # width of trans. band filter.firdes.WIN_HAMMING) # filter type self.chan_filt = filter.fft_filter_ccc(1, chan_coeffs) win = [1 for i in range(fft_length)] zeros_on_left = int(math.ceil((fft_length - occupied_tones)/2.0)) ks0 = fft_length*[0,] ks0[zeros_on_left : zeros_on_left + occupied_tones] = ks[0] ks0 = fft.ifftshift(ks0) ks0time = fft.ifft(ks0) # ADD SCALING FACTOR ks0time = ks0time.tolist() SYNC = "pn" if SYNC == "ml": nco_sensitivity = -1.0/fft_length # correct for fine frequency self.ofdm_sync = ofdm_sync_ml(fft_length, cp_length, snr, ks0time, logging) elif SYNC == "pn": nco_sensitivity = -2.0/fft_length # correct for fine frequency self.ofdm_sync = ofdm_sync_pn(fft_length, cp_length, logging) elif SYNC == "pnac": nco_sensitivity = -2.0/fft_length # correct for fine frequency self.ofdm_sync = ofdm_sync_pnac(fft_length, cp_length, ks0time, logging) # for testing only; do not user over the air # remove filter and filter delay for this elif SYNC == "fixed": self.chan_filt = blocks.multiply_const_cc(1.0) nsymbols = 18 # enter the number of symbols per packet freq_offset = 0.0 # if you use a frequency offset, enter it here nco_sensitivity = -2.0/fft_length # correct for fine frequency self.ofdm_sync = ofdm_sync_fixed(fft_length, cp_length, nsymbols, freq_offset, logging) # Set up blocks self.nco = analog.frequency_modulator_fc(nco_sensitivity) # generate a signal proportional to frequency error of sync block self.sigmix = blocks.multiply_cc() self.sampler = digital.ofdm_sampler(fft_length, fft_length+cp_length) self.fft_demod = gr_fft.fft_vcc(fft_length, True, win, True) self.ofdm_frame_acq = digital.ofdm_frame_acquisition(occupied_tones, fft_length, cp_length, ks[0]) self.connect(self, self.chan_filt) # filter the input channel self.connect(self.chan_filt, self.ofdm_sync) # into the synchronization alg. self.connect((self.ofdm_sync,0), self.nco, (self.sigmix,1)) # use sync freq. offset output to derotate input signal self.connect(self.chan_filt, (self.sigmix,0)) # signal to be derotated self.connect(self.sigmix, (self.sampler,0)) # sample off timing signal detected in sync alg self.connect((self.ofdm_sync,1), (self.sampler,1)) # timing signal to sample at self.connect((self.sampler,0), self.fft_demod) # send derotated sampled signal to FFT self.connect(self.fft_demod, (self.ofdm_frame_acq,0)) # find frame start and equalize signal self.connect((self.sampler,1), (self.ofdm_frame_acq,1)) # send timing signal to signal frame start self.connect((self.ofdm_frame_acq,0), (self,0)) # finished with fine/coarse freq correction, self.connect((self.ofdm_frame_acq,1), (self,1)) # frame and symbol timing, and equalization if logging: self.connect(self.chan_filt, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_receiver-chan_filt_c.dat")) self.connect(self.fft_demod, blocks.file_sink(gr.sizeof_gr_complex*fft_length, "ofdm_receiver-fft_out_c.dat")) self.connect(self.ofdm_frame_acq, blocks.file_sink(gr.sizeof_gr_complex*occupied_tones, "ofdm_receiver-frame_acq_c.dat")) self.connect((self.ofdm_frame_acq,1), blocks.file_sink(1, "ofdm_receiver-found_corr_b.dat")) self.connect(self.sampler, blocks.file_sink(gr.sizeof_gr_complex*fft_length, "ofdm_receiver-sampler_c.dat")) self.connect(self.sigmix, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_receiver-sigmix_c.dat")) self.connect(self.nco, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_receiver-nco_c.dat")) gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_carrier_allocator_cvc.py0000775000175000017500000002157212237515112026700 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks import pmt class qa_digital_carrier_allocator_cvc (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): """ pretty simple (the carrier allocation is not a practical OFDM configuration!) """ fft_len = 6 tx_symbols = (1, 2, 3) # ^ this gets mapped to the DC carrier because occupied_carriers[0][0] == 0 pilot_symbols = ((1j,),) occupied_carriers = ((0, 1, 2),) pilot_carriers = ((3,),) sync_word = (range(fft_len),) expected_result = tuple(sync_word[0] + [1j, 0, 0, 1, 2, 3]) # ^ DC carrier tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(tx_symbols)) src = blocks.vector_source_c(tx_symbols, False, 1, (tag,)) alloc = digital.ofdm_carrier_allocator_cvc(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, sync_word, tag_name) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, alloc, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) def test_001_t2 (self): """ pretty simple (same as before, but odd fft len) """ fft_len = 5 tx_symbols = (1, 2, 3) # ^ this gets mapped to the DC carrier because occupied_carriers[0][0] == 0 occupied_carriers = ((0, 1, 2),) pilot_carriers = ((-2,),) pilot_symbols = ((1j,),) expected_result = (1j, 0, 1, 2, 3) # ^ DC carrier tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(tx_symbols)) src = blocks.vector_source_c(tx_symbols, False, 1, (tag,)) alloc = digital.ofdm_carrier_allocator_cvc(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, (), tag_name) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, alloc, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) def test_002_t (self): """ same, but using negative carrier indices """ fft_len = 6 tx_symbols = (1, 2, 3) pilot_symbols = ((1j,),) occupied_carriers = ((-1, 1, 2),) pilot_carriers = ((3,),) expected_result = (1j, 0, 1, 0, 2, 3) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(tx_symbols)) src = blocks.vector_source_c(tx_symbols, False, 1, (tag,)) alloc = digital.ofdm_carrier_allocator_cvc(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, (), tag_name) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, alloc, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) def test_002_t (self): """ once again, but this time add a sync word """ fft_len = 6 sync_word = (0,) * fft_len tx_symbols = (1, 2, 3, 4, 5, 6) pilot_symbols = ((1j,),) occupied_carriers = ((-1, 1, 2),) pilot_carriers = ((3,),) expected_result = sync_word + (1j, 0, 1, 0, 2, 3) + (1j, 0, 4, 0, 5, 6) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(tx_symbols)) special_tag1 = gr.tag_t() special_tag1.offset = 0 special_tag1.key = pmt.string_to_symbol("spam") special_tag1.value = pmt.to_pmt(23) special_tag2 = gr.tag_t() special_tag2.offset = 4 special_tag2.key = pmt.string_to_symbol("eggs") special_tag2.value = pmt.to_pmt(42) src = blocks.vector_source_c( tx_symbols, False, 1, (tag, special_tag1, special_tag2) ) alloc = digital.ofdm_carrier_allocator_cvc( fft_len, occupied_carriers, pilot_carriers, pilot_symbols, sync_words=(sync_word,), len_tag_key=tag_name ) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, alloc, sink) self.tb.run () self.assertEqual(sink.data(), expected_result) tags = [gr.tag_to_python(x) for x in sink.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) tags_expected = [ (0, 'len', 3), (0, 'spam', 23), (2, 'eggs', 42), ] self.assertEqual(tags, tags_expected) def test_003_t (self): """ more advanced: - 6 symbols per carrier - 2 pilots per carrier - have enough data for nearly 3 OFDM symbols - send that twice - add some random tags - don't shift """ tx_symbols = range(1, 16); # 15 symbols pilot_symbols = ((1j, 2j), (3j, 4j)) occupied_carriers = ((1, 3, 4, 11, 12, 14), (1, 2, 4, 11, 13, 14),) pilot_carriers = ((2, 13), (3, 12)) expected_result = (0, 1, 1j, 2, 3, 0, 0, 0, 0, 0, 0, 4, 5, 2j, 6, 0, 0, 7, 8, 3j, 9, 0, 0, 0, 0, 0, 0, 10, 4j, 11, 12, 0, 0, 13, 1j, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 2j, 0, 0) fft_len = 16 tag_name = "len" tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol(tag_name) tag1.value = pmt.from_long(len(tx_symbols)) tag2 = gr.tag_t() tag2.offset = len(tx_symbols) tag2.key = pmt.string_to_symbol(tag_name) tag2.value = pmt.from_long(len(tx_symbols)) testtag1 = gr.tag_t() testtag1.offset = 0 testtag1.key = pmt.string_to_symbol('tag1') testtag1.value = pmt.from_long(0) testtag2 = gr.tag_t() testtag2.offset = 7 # On the 2nd OFDM symbol testtag2.key = pmt.string_to_symbol('tag2') testtag2.value = pmt.from_long(0) testtag3 = gr.tag_t() testtag3.offset = len(tx_symbols)+1 # First OFDM symbol of packet 2 testtag3.key = pmt.string_to_symbol('tag3') testtag3.value = pmt.from_long(0) testtag4 = gr.tag_t() testtag4.offset = 2*len(tx_symbols)-1 # Last OFDM symbol of packet 2 testtag4.key = pmt.string_to_symbol('tag4') testtag4.value = pmt.from_long(0) src = blocks.vector_source_c(tx_symbols * 2, False, 1, (tag1, tag2, testtag1, testtag2, testtag3, testtag4)) alloc = digital.ofdm_carrier_allocator_cvc(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, (), tag_name, False) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, alloc, sink) self.tb.run () self.assertEqual(sink.data(), expected_result * 2) tags_found = {'tag1': False, 'tag2': False, 'tag3': False, 'tag4': False} correct_offsets = {'tag1': 0, 'tag2': 1, 'tag3': 3, 'tag4': 5} for tag in sink.tags(): key = pmt.symbol_to_string(tag.key) if key in tags_found.keys(): tags_found[key] = True self.assertEqual(correct_offsets[key], tag.offset) if key == tag_name: self.assertTrue(tag.offset == 0 or tag.offset == 3) self.assertTrue(pmt.to_long(tag.value) == 3) self.assertTrue(all(tags_found.values())) if __name__ == '__main__': gr_unittest.run(qa_digital_carrier_allocator_cvc, "qa_digital_carrier_allocator_cvc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/crc.py0000664000175000017500000000240512207440367021434 0ustar jcorganjcorgan# # Copyright 2005,2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gru import digital_swig as digital import struct def gen_and_append_crc32(s): crc = digital.crc32(s) return s + struct.pack(">I", gru.hexint(crc) & 0xFFFFFFFF) def check_crc32(s): if len(s) < 4: return (False, '') msg = s[:-4] #print "msg = '%s'" % (msg,) actual = digital.crc32(msg) (expected,) = struct.unpack(">I", s[-4:]) # print "actual =", hex(actual), "expected =", hex(expected) return (actual == expected, msg) gnuradio-3.7.2.1/gr-digital/python/digital/psk.py0000664000175000017500000001255012207440367021464 0ustar jcorganjcorgan# # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ PSK modulation and demodulation. """ from math import pi, log from cmath import exp import digital_swig import modulation_utils from utils import mod_codes, gray_code from generic_mod_demod import generic_mod, generic_demod from generic_mod_demod import shared_mod_args, shared_demod_args # Default number of points in constellation. _def_constellation_points = 4 # The default encoding (e.g. gray-code, set-partition) _def_mod_code = mod_codes.GRAY_CODE # Default use of differential encoding _def_differential = True def create_encodings(mod_code, arity, differential): post_diff_code = None if mod_code not in mod_codes.codes: raise ValueError('That modulation code does not exist.') if mod_code == mod_codes.GRAY_CODE: if differential: pre_diff_code = gray_code.gray_code(arity) post_diff_code = None else: pre_diff_code = [] post_diff_code = gray_code.gray_code(arity) elif mod_code == mod_codes.NO_CODE: pre_diff_code = [] post_diff_code = None else: raise ValueError('That modulation code is not implemented for this constellation.') return (pre_diff_code, post_diff_code) # ///////////////////////////////////////////////////////////////////////////// # PSK constellation # ///////////////////////////////////////////////////////////////////////////// def psk_constellation(m=_def_constellation_points, mod_code=_def_mod_code, differential=_def_differential): """ Creates a PSK constellation object. """ k = log(m) / log(2.0) if (k != int(k)): raise StandardError('Number of constellation points must be a power of two.') points = [exp(2*pi*(0+1j)*i/m) for i in range(0,m)] pre_diff_code, post_diff_code = create_encodings(mod_code, m, differential) if post_diff_code is not None: inverse_post_diff_code = mod_codes.invert_code(post_diff_code) points = [points[x] for x in inverse_post_diff_code] constellation = digital_swig.constellation_psk(points, pre_diff_code, m) return constellation # ///////////////////////////////////////////////////////////////////////////// # PSK modulator # ///////////////////////////////////////////////////////////////////////////// class psk_mod(generic_mod): """ Hierarchical block for RRC-filtered PSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation_points: Number of constellation points (must be a power of two) (integer). mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). differential: Whether to use differential encoding (boolean). """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, constellation_points=_def_constellation_points, mod_code=_def_mod_code, differential=_def_differential, *args, **kwargs): constellation = psk_constellation(constellation_points, mod_code, differential) super(psk_mod, self).__init__(constellation, differential, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # PSK demodulator # # ///////////////////////////////////////////////////////////////////////////// class psk_demod(generic_demod): """ Hierarchical block for RRC-filtered PSK modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation_points: Number of constellation points (must be a power of two) (integer). mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). differential: Whether to use differential encoding (boolean). """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, constellation_points=_def_constellation_points, mod_code=_def_mod_code, differential=_def_differential, *args, **kwargs): constellation = psk_constellation(constellation_points, mod_code, differential) super(psk_demod, self).__init__(constellation, differential, *args, **kwargs) # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('psk', psk_mod) modulation_utils.add_type_1_demod('psk', psk_demod) modulation_utils.add_type_1_constellation('psk', psk_constellation) gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_sync_pnac.py0000664000175000017500000001374012207440367023653 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from numpy import fft from gnuradio import gr try: from gnuradio import filter except ImportError: import filter_swig as filter try: from gnuradio import blocks except ImportError: import blocks_swig as blocks class ofdm_sync_pnac(gr.hier_block2): def __init__(self, fft_length, cp_length, kstime, logging=False): """ OFDM synchronization using PN Correlation and initial cross-correlation: F. Tufvesson, O. Edfors, and M. Faulkner, "Time and Frequency Synchronization for OFDM using PN-Sequency Preambles," IEEE Proc. VTC, 1999, pp. 2203-2207. This implementation is meant to be a more robust version of the Schmidl and Cox receiver design. By correlating against the preamble and using that as the input to the time-delayed correlation, this circuit produces a very clean timing signal at the end of the preamble. The timing is more accurate and does not have the problem associated with determining the timing from the plateau structure in the Schmidl and Cox. This implementation appears to require that the signal is received with a normalized power or signal scalling factor to reduce ambiguities intorduced from partial correlation of the cyclic prefix and the peak detection. A better peak detection block might fix this. Also, the cross-correlation falls apart as the frequency offset gets larger and completely fails when an integer offset is introduced. Another thing to look at. """ gr.hier_block2.__init__(self, "ofdm_sync_pnac", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature2(2, 2, gr.sizeof_float, gr.sizeof_char)) # Output signature self.input = blocks.add_const_cc(0) symbol_length = fft_length + cp_length # PN Sync with cross-correlation input # cross-correlate with the known symbol kstime = [k.conjugate() for k in kstime[0:fft_length//2]] kstime.reverse() self.crosscorr_filter = filter.fir_filter_ccc(1, kstime) # Create a delay line self.delay = blocks.delay(gr.sizeof_gr_complex, fft_length/2) # Correlation from ML Sync self.conjg = blocks.conjugate_cc(); self.corr = blocks.multiply_cc(); # Create a moving sum filter for the input self.mag = blocks.complex_to_mag_squared() movingsum_taps = (fft_length//1)*[1.0,] self.power = filter.fir_filter_fff(1,movingsum_taps) # Get magnitude (peaks) and angle (phase/freq error) self.c2mag = blocks.complex_to_mag_squared() self.angle = blocks.complex_to_arg() self.compare = blocks.sub_ff() self.sample_and_hold = blocks.sample_and_hold_ff() #ML measurements input to sampler block and detect self.threshold = blocks.threshold_ff(0,0,0) # threshold detection might need to be tweaked self.peaks = blocksx.float_to_char() self.connect(self, self.input) # Cross-correlate input signal with known preamble self.connect(self.input, self.crosscorr_filter) # use the output of the cross-correlation as input time-shifted correlation self.connect(self.crosscorr_filter, self.delay) self.connect(self.crosscorr_filter, (self.corr,0)) self.connect(self.delay, self.conjg) self.connect(self.conjg, (self.corr,1)) self.connect(self.corr, self.c2mag) self.connect(self.corr, self.angle) self.connect(self.angle, (self.sample_and_hold,0)) # Get the power of the input signal to compare against the correlation self.connect(self.crosscorr_filter, self.mag, self.power) # Compare the power to the correlator output to determine timing peak # When the peak occurs, it peaks above zero, so the thresholder detects this self.connect(self.c2mag, (self.compare,0)) self.connect(self.power, (self.compare,1)) self.connect(self.compare, self.threshold) self.connect(self.threshold, self.peaks, (self.sample_and_hold,1)) # Set output signals # Output 0: fine frequency correction value # Output 1: timing signal self.connect(self.sample_and_hold, (self,0)) self.connect(self.peaks, (self,1)) if logging: self.connect(self.compare, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pnac-compare_f.dat")) self.connect(self.c2mag, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pnac-theta_f.dat")) self.connect(self.power, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pnac-inputpower_f.dat")) self.connect(self.angle, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pnac-epsilon_f.dat")) self.connect(self.threshold, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pnac-threshold_f.dat")) self.connect(self.peaks, blocks.file_sink(gr.sizeof_char, "ofdm_sync_pnac-peaks_b.dat")) self.connect(self.sample_and_hold, blocks.file_sink(gr.sizeof_float, "ofdm_sync_pnac-sample_and_hold_f.dat")) self.connect(self.input, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_sync_pnac-input_c.dat")) gnuradio-3.7.2.1/gr-digital/python/digital/pkt.py0000664000175000017500000001540312237515112021457 0ustar jcorganjcorgan# # Copyright 2005, 2006, 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from math import pi from gnuradio import gr import gnuradio.gr.gr_threading as _threading import packet_utils import digital_swig as digital try: from gnuradio import blocks except ImportError: import blocks_swig as blocks # ///////////////////////////////////////////////////////////////////////////// # mod/demod with packets as i/o # ///////////////////////////////////////////////////////////////////////////// class mod_pkts(gr.hier_block2): """ Wrap an arbitrary digital modulator in our packet handling framework. Send packets by calling send_pkt """ def __init__(self, modulator, preamble=None, access_code=None, msgq_limit=2, pad_for_usrp=True, use_whitener_offset=False, modulate=True): """ Hierarchical block for sending packets Packets to be sent are enqueued by calling send_pkt. The output is the complex modulated signal at baseband. Args: modulator: instance of modulator class (gr_block or hier_block2) (complex baseband out) access_code: AKA sync vector (string of 1's and 0's between 1 and 64 long) msgq_limit: maximum number of messages in message queue (int) pad_for_usrp: If true, packets are padded such that they end up a multiple of 128 samples use_whitener_offset: If true, start of whitener XOR string is incremented each packet See gmsk_mod for remaining parameters """ gr.hier_block2.__init__(self, "mod_pkts", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._modulator = modulator self._pad_for_usrp = pad_for_usrp self._use_whitener_offset = use_whitener_offset self._whitener_offset = 0 if access_code is None: access_code = packet_utils.default_access_code if not packet_utils.is_1_0_string(access_code): raise ValueError, "Invalid access_code %r. Must be string of 1's and 0's" % (access_code,) self._access_code = access_code if preamble is None: preamble = packet_utils.default_preamble if not packet_utils.is_1_0_string(preamble): raise ValueError, "Invalid preamble %r. Must be string of 1's and 0's" % (preamble,) self._preamble = preamble # accepts messages from the outside world self._pkt_input = blocks.message_source(gr.sizeof_char, msgq_limit) self.connect(self._pkt_input, self._modulator, self) def send_pkt(self, payload='', eof=False): """ Send the payload. Args: payload: data to send (string) """ if eof: msg = gr.message(1) # tell self._pkt_input we're not sending any more packets else: # print "original_payload =", string_to_hex_list(payload) pkt = packet_utils.make_packet(payload, self._modulator.samples_per_symbol(), self._modulator.bits_per_symbol(), self._preamble, self._access_code, self._pad_for_usrp, self._whitener_offset) #print "pkt =", string_to_hex_list(pkt) msg = gr.message_from_string(pkt) if self._use_whitener_offset is True: self._whitener_offset = (self._whitener_offset + 1) % 16 self._pkt_input.msgq().insert_tail(msg) class demod_pkts(gr.hier_block2): """ Wrap an arbitrary digital demodulator in our packet handling framework. The input is complex baseband. When packets are demodulated, they are passed to the app via the callback. """ def __init__(self, demodulator, access_code=None, callback=None, threshold=-1): """ Hierarchical block for demodulating and deframing packets. The input is the complex modulated signal at baseband. Demodulated packets are sent to the handler. Args: demodulator: instance of demodulator class (gr_block or hier_block2) (complex baseband in) access_code: AKA sync vector (string of 1's and 0's) callback: function of two args: ok, payload (ok: bool; payload: string) threshold: detect access_code with up to threshold bits wrong (-1 -> use default) (int) """ gr.hier_block2.__init__(self, "demod_pkts", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(0, 0, 0)) # Output signature self._demodulator = demodulator if access_code is None: access_code = packet_utils.default_access_code if not packet_utils.is_1_0_string(access_code): raise ValueError, "Invalid access_code %r. Must be string of 1's and 0's" % (access_code,) self._access_code = access_code if threshold == -1: threshold = 12 # FIXME raise exception self._rcvd_pktq = gr.msg_queue() # holds packets from the PHY self.correlator = digital.correlate_access_code_bb(access_code, threshold) self.framer_sink = digital.framer_sink_1(self._rcvd_pktq) self.connect(self, self._demodulator, self.correlator, self.framer_sink) self._watcher = _queue_watcher_thread(self._rcvd_pktq, callback) class _queue_watcher_thread(_threading.Thread): def __init__(self, rcvd_pktq, callback): _threading.Thread.__init__(self) self.setDaemon(1) self.rcvd_pktq = rcvd_pktq self.callback = callback self.keep_running = True self.start() def run(self): while self.keep_running: msg = self.rcvd_pktq.delete_head() ok, payload = packet_utils.unmake_packet(msg.to_string(), int(msg.arg1())) if self.callback: self.callback(ok, payload) gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_frame_equalizer_vcvc.py0000775000175000017500000004055312207440367026560 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy from gnuradio import gr, gr_unittest, digital, blocks import pmt class qa_ofdm_frame_equalizer_vcvc (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_simple (self): """ Very simple functionality testing: - static equalizer - init channel state with all ones - transmit all ones - make sure we rx all ones - Tag check: put in frame length tag and one other random tag, make sure they're propagated """ fft_len = 8 equalizer = digital.ofdm_equalizer_static(fft_len) n_syms = 3 len_tag_key = "frame_len" tx_data = (1,) * fft_len * n_syms len_tag = gr.tag_t() len_tag.offset = 0 len_tag.key = pmt.string_to_symbol(len_tag_key) len_tag.value = pmt.from_long(n_syms) chan_tag = gr.tag_t() chan_tag.offset = 0 chan_tag.key = pmt.string_to_symbol("ofdm_sync_chan_taps") chan_tag.value = pmt.init_c32vector(fft_len, (1,) * fft_len) random_tag = gr.tag_t() random_tag.offset = 1 random_tag.key = pmt.string_to_symbol("foo") random_tag.value = pmt.from_long(42) src = blocks.vector_source_c(tx_data, False, fft_len, (len_tag, chan_tag, random_tag)) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), 0, len_tag_key) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, eq, sink) self.tb.run () # Check data self.assertEqual(tx_data, sink.data()) # Check tags tag_dict = dict() for tag in sink.tags(): ptag = gr.tag_to_python(tag) tag_dict[ptag.key] = ptag.value expected_dict = { 'frame_len': n_syms, 'foo': 42 } self.assertEqual(tag_dict, expected_dict) def test_001b_simple_skip_nothing (self): """ Same as before, but put a skip-header in there """ fft_len = 8 equalizer = digital.ofdm_equalizer_static(fft_len, symbols_skipped=1) n_syms = 3 len_tag_key = "frame_len" tx_data = (1,) * fft_len * n_syms len_tag = gr.tag_t() len_tag.offset = 0 len_tag.key = pmt.string_to_symbol(len_tag_key) len_tag.value = pmt.from_long(n_syms) chan_tag = gr.tag_t() chan_tag.offset = 0 chan_tag.key = pmt.string_to_symbol("ofdm_sync_chan_taps") chan_tag.value = pmt.init_c32vector(fft_len, (1,) * fft_len) src = blocks.vector_source_c(tx_data, False, fft_len, (len_tag, chan_tag)) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), 0, len_tag_key) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, eq, sink) self.tb.run () # Check data self.assertEqual(tx_data, sink.data()) def test_001c_carrier_offset_no_cp (self): """ Same as before, but put a carrier offset in there """ fft_len = 8 cp_len = 0 n_syms = 1 carr_offset = 1 occupied_carriers = ((-2, -1, 1, 2),) tx_data = ( 0, 0, 0, -1j, -1j, 0, -1j, -1j, ) # The rx'd signal is shifted rx_expected = (0, 0, 1, 1, 0, 1, 1, 0) * n_syms equalizer = digital.ofdm_equalizer_static(fft_len, occupied_carriers) len_tag_key = "frame_len" len_tag = gr.tag_t() len_tag.offset = 0 len_tag.key = pmt.string_to_symbol(len_tag_key) len_tag.value = pmt.from_long(n_syms) chan_tag = gr.tag_t() chan_tag.offset = 0 chan_tag.key = pmt.string_to_symbol("ofdm_sync_chan_taps") # Note: this is shifted to the correct position! chan_tag.value = pmt.init_c32vector(fft_len, (0, 0, -1j, -1j, 0, -1j, -1j, 0)) offset_tag = gr.tag_t() offset_tag.offset = 0 offset_tag.key = pmt.string_to_symbol("ofdm_sync_carr_offset") offset_tag.value = pmt.from_long(carr_offset) src = blocks.vector_source_c(tx_data, False, fft_len, (len_tag, chan_tag, offset_tag)) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), cp_len, len_tag_key) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, eq, sink) self.tb.run () # Check data self.assertComplexTuplesAlmostEqual(rx_expected, sink.data(), places=4) def test_001c_carrier_offset_cp (self): """ Same as before, but put a carrier offset in there and a CP """ fft_len = 8 cp_len = 2 n_syms = 3 # cp_len/fft_len == 1/4, therefore, the phase is rotated by # carr_offset * \pi/2 in every symbol occupied_carriers = ((-2, -1, 1, 2),) carr_offset = -1 tx_data = ( 0,-1j,-1j, 0,-1j,-1j, 0, 0, 0, -1, -1, 0, -1, -1, 0, 0, 0, 1j, 1j, 0, 1j, 1j, 0, 0, ) # Rx'd signal is corrected rx_expected = (0, 0, 1, 1, 0, 1, 1, 0) * n_syms equalizer = digital.ofdm_equalizer_static(fft_len, occupied_carriers) len_tag_key = "frame_len" len_tag = gr.tag_t() len_tag.offset = 0 len_tag.key = pmt.string_to_symbol(len_tag_key) len_tag.value = pmt.from_long(n_syms) chan_tag = gr.tag_t() chan_tag.offset = 0 chan_tag.key = pmt.string_to_symbol("ofdm_sync_chan_taps") chan_tag.value = pmt.init_c32vector(fft_len, (0, 0, 1, 1, 0, 1, 1, 0)) offset_tag = gr.tag_t() offset_tag.offset = 0 offset_tag.key = pmt.string_to_symbol("ofdm_sync_carr_offset") offset_tag.value = pmt.from_long(carr_offset) src = blocks.vector_source_c(tx_data, False, fft_len, (len_tag, chan_tag, offset_tag)) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), cp_len, len_tag_key) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, eq, sink) self.tb.run () # Check data self.assertComplexTuplesAlmostEqual(rx_expected, sink.data(), places=4) def test_002_static (self): """ - Add a simple channel - Make symbols QPSK """ fft_len = 8 # 4 5 6 7 0 1 2 3 tx_data = [-1, -1, 1, 2, -1, 3, 0, -1, # 0 -1, -1, 0, 2, -1, 2, 0, -1, # 8 -1, -1, 3, 0, -1, 1, 0, -1, # 16 (Pilot symbols) -1, -1, 1, 1, -1, 0, 2, -1] # 24 cnst = digital.constellation_qpsk() tx_signal = [cnst.map_to_points_v(x)[0] if x != -1 else 0 for x in tx_data] occupied_carriers = ((1, 2, 6, 7),) pilot_carriers = ((), (), (1, 2, 6, 7), ()) pilot_symbols = ( [], [], [cnst.map_to_points_v(x)[0] for x in (1, 0, 3, 0)], [] ) equalizer = digital.ofdm_equalizer_static(fft_len, occupied_carriers, pilot_carriers, pilot_symbols) channel = [ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, # These coefficients will be rotated slightly (but less than \pi/2) 0, 0, 1j, 1j, 0, 1j, 1j, 0, # Go crazy here! 0, 0, 1j, 1j, 0, 1j, 1j, 0 ] channel = [ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, # These coefficients will be rotated slightly (but less than \pi/2) 0, 0, 1j, 1j, 0, 1j, 1j, 0, # Go crazy here! 0, 0, 1j, 1j, 0, 1j, 1j, 0 ] for idx in range(fft_len, 2*fft_len): channel[idx] = channel[idx-fft_len] * numpy.exp(1j * .1 * numpy.pi * (numpy.random.rand()-.5)) len_tag_key = "frame_len" len_tag = gr.tag_t() len_tag.offset = 0 len_tag.key = pmt.string_to_symbol(len_tag_key) len_tag.value = pmt.from_long(4) chan_tag = gr.tag_t() chan_tag.offset = 0 chan_tag.key = pmt.string_to_symbol("ofdm_sync_chan_taps") chan_tag.value = pmt.init_c32vector(fft_len, channel[:fft_len]) src = blocks.vector_source_c(numpy.multiply(tx_signal, channel), False, fft_len, (len_tag, chan_tag)) sink = blocks.vector_sink_c(fft_len) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), 0, len_tag_key, True) self.tb.connect(src, eq, sink) self.tb.run () rx_data = [cnst.decision_maker_v((x,)) if x != 0 else -1 for x in sink.data()] # Check data self.assertEqual(tx_data, rx_data) # Check tags tag_dict = dict() for tag in sink.tags(): ptag = gr.tag_to_python(tag) tag_dict[ptag.key] = ptag.value if ptag.key == 'ofdm_sync_chan_taps': tag_dict[ptag.key] = list(pmt.c32vector_elements(tag.value)) else: tag_dict[ptag.key] = pmt.to_python(tag.value) expected_dict = { 'frame_len': 4, 'ofdm_sync_chan_taps': channel[-fft_len:] } self.assertEqual(tag_dict, expected_dict) def test_002_static_wo_tags (self): """ Same as before, but the input stream has no tag. We specify the frame size in the constructor. We also specify a tag key, so the output stream *should* have a length tag. """ fft_len = 8 n_syms = 4 # 4 5 6 7 0 1 2 3 tx_data = [-1, -1, 1, 2, -1, 3, 0, -1, # 0 -1, -1, 0, 2, -1, 2, 0, -1, # 8 -1, -1, 3, 0, -1, 1, 0, -1, # 16 (Pilot symbols) -1, -1, 1, 1, -1, 0, 2, -1] # 24 cnst = digital.constellation_qpsk() tx_signal = [cnst.map_to_points_v(x)[0] if x != -1 else 0 for x in tx_data] occupied_carriers = ((1, 2, 6, 7),) pilot_carriers = ((), (), (1, 2, 6, 7), ()) pilot_symbols = ( [], [], [cnst.map_to_points_v(x)[0] for x in (1, 0, 3, 0)], [] ) equalizer = digital.ofdm_equalizer_static(fft_len, occupied_carriers, pilot_carriers, pilot_symbols) channel = [ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, # These coefficients will be rotated slightly (below)... 0, 0, 1j, 1j, 0, 1j, 1j, 0, # Go crazy here! 0, 0, 1j, 1j, 0, 1j, 1j, 0 # ...and again here. ] for idx in range(fft_len, 2*fft_len): channel[idx] = channel[idx-fft_len] * numpy.exp(1j * .1 * numpy.pi * (numpy.random.rand()-.5)) idx2 = idx+2*fft_len channel[idx2] = channel[idx2] * numpy.exp(1j * 0 * numpy.pi * (numpy.random.rand()-.5)) src = gr.vector_source_c(numpy.multiply(tx_signal, channel), False, fft_len) # We do specify a length tag, it should then appear at the output eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), 0, "frame_len", False, n_syms) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, eq, sink) self.tb.run () rx_data = [cnst.decision_maker_v((x,)) if x != 0 else -1 for x in sink.data()] self.assertEqual(tx_data, rx_data) # Check len tag tags = sink.tags() len_tag = dict() for tag in tags: ptag = gr.tag_to_python(tag) if ptag.key == 'frame_len': len_tag[ptag.key] = ptag.value self.assertEqual(len_tag, {'frame_len': 4}) def test_002_static_wo_tags (self): fft_len = 8 # 4 5 6 7 0 1 2 3 tx_data = [-1, -1, 1, 2, -1, 3, 0, -1, # 0 -1, -1, 0, 2, -1, 2, 0, -1, # 8 -1, -1, 3, 0, -1, 1, 0, -1, # 16 (Pilot symbols) -1, -1, 1, 1, -1, 0, 2, -1] # 24 cnst = digital.constellation_qpsk() tx_signal = [cnst.map_to_points_v(x)[0] if x != -1 else 0 for x in tx_data] occupied_carriers = ((1, 2, 6, 7),) pilot_carriers = ((), (), (1, 2, 6, 7), ()) pilot_symbols = ( [], [], [cnst.map_to_points_v(x)[0] for x in (1, 0, 3, 0)], [] ) equalizer = digital.ofdm_equalizer_static(fft_len, occupied_carriers, pilot_carriers, pilot_symbols) channel = [ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, # These coefficients will be rotated slightly... 0, 0, 1j, 1j, 0, 1j, 1j, 0, # Go crazy here! 0, 0, 1j, 1j, 0, 1j, 1j, 0 # ...and again here. ] for idx in range(fft_len, 2*fft_len): channel[idx] = channel[idx-fft_len] * numpy.exp(1j * .1 * numpy.pi * (numpy.random.rand()-.5)) idx2 = idx+2*fft_len channel[idx2] = channel[idx2] * numpy.exp(1j * 0 * numpy.pi * (numpy.random.rand()-.5)) src = blocks.vector_source_c(numpy.multiply(tx_signal, channel), False, fft_len) sink = blocks.vector_sink_c(fft_len) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), 0, "", False, 4) self.tb.connect(src, eq, sink) self.tb.run () rx_data = [cnst.decision_maker_v((x,)) if x != 0 else -1 for x in sink.data()] self.assertEqual(tx_data, rx_data) def test_002_simpledfe (self): """ Use the simple DFE equalizer. """ fft_len = 8 # 4 5 6 7 0 1 2 3 tx_data = [-1, -1, 1, 2, -1, 3, 0, -1, # 0 -1, -1, 0, 2, -1, 2, 0, -1, # 8 -1, -1, 3, 0, -1, 1, 0, -1, # 16 (Pilot symbols) -1, -1, 1, 1, -1, 0, 2, -1] # 24 cnst = digital.constellation_qpsk() tx_signal = [cnst.map_to_points_v(x)[0] if x != -1 else 0 for x in tx_data] occupied_carriers = ((1, 2, 6, 7),) pilot_carriers = ((), (), (1, 2, 6, 7), ()) pilot_symbols = ( [], [], [cnst.map_to_points_v(x)[0] for x in (1, 0, 3, 0)], [] ) equalizer = digital.ofdm_equalizer_simpledfe( fft_len, cnst.base(), occupied_carriers, pilot_carriers, pilot_symbols, 0, 0.01 ) channel = [ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, # These coefficients will be rotated slightly... 0, 0, 1j, 1j, 0, 1j, 1j, 0, # Go crazy here! 0, 0, 1j, 1j, 0, 1j, 1j, 0 # ...and again here. ] for idx in range(fft_len, 2*fft_len): channel[idx] = channel[idx-fft_len] * numpy.exp(1j * .1 * numpy.pi * (numpy.random.rand()-.5)) idx2 = idx+2*fft_len channel[idx2] = channel[idx2] * numpy.exp(1j * 0 * numpy.pi * (numpy.random.rand()-.5)) len_tag_key = "frame_len" len_tag = gr.tag_t() len_tag.offset = 0 len_tag.key = pmt.string_to_symbol(len_tag_key) len_tag.value = pmt.from_long(4) chan_tag = gr.tag_t() chan_tag.offset = 0 chan_tag.key = pmt.string_to_symbol("ofdm_sync_chan_taps") chan_tag.value = pmt.init_c32vector(fft_len, channel[:fft_len]) src = blocks.vector_source_c(numpy.multiply(tx_signal, channel), False, fft_len, (len_tag, chan_tag)) eq = digital.ofdm_frame_equalizer_vcvc(equalizer.base(), 0, len_tag_key, True) sink = blocks.vector_sink_c(fft_len) self.tb.connect(src, eq, sink) self.tb.run () rx_data = [cnst.decision_maker_v((x,)) if x != 0 else -1 for x in sink.data()] self.assertEqual(tx_data, rx_data) for tag in sink.tags(): if pmt.symbol_to_string(tag.key) == len_tag_key: self.assertEqual(pmt.to_long(tag.value), 4) if pmt.symbol_to_string(tag.key) == "ofdm_sync_chan_taps": self.assertComplexTuplesAlmostEqual(list(pmt.c32vector_elements(tag.value)), channel[-fft_len:], places=1) if __name__ == '__main__': gr_unittest.run(qa_ofdm_frame_equalizer_vcvc, "qa_ofdm_frame_equalizer_vcvc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qam_constellations.py0000775000175000017500000002621312237515112024564 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy from constellation_map_generator import * ''' Note on the naming scheme. Each constellation is named using a prefix for the type of constellation, the order of the constellation, and a distinguishing feature, which comes in three modes: - No extra feature: the basic Gray-coded constellation map; others will be derived from this type. - A single number: an indexed number to uniquely identify different constellation maps. - 0xN_x0_x1..._xM: A permutation of the base constellation, explained below. For rectangular constellations (BPSK, QPSK, QAM), we can define a hyperspace and look for all symmetries. This is also known as the automorphism group of the hypercube, aka the hyperoctahedral group. What this means is that we can easily define all possible rotations in terms of the first base mapping by creating the mapping: f(x) = k XOR pi(x) The x is the bit string for the symbol we are altering. Then k is a bit string of n bits where n is the number of bits per symbol in the constellation (e.g., 2 for QPSK or 6 for QAM64). The pi is a permutation function specified as pi_0, pi_1..., pi_n-1. This permutes the bits from the base constellation symbol to a new code, which is then xor'd by k. The value of k is from 0 to 2^n-1 and pi is a list of all bit positions. The permutation are given for b0_b1_b2_... for the total number of bits. In the constellation diagrams shown in the comments, the bit ordering is shown as [b3b2b1b0]. Bit values returned from the soft bit LUTs are in the order [b3, b2, b1, b0]. The total number of Gray coded modulations is (2^n)*(n!). We create aliases for all possible naming schemes for the constellations. So if a hyperoctahedral group is defined, we also set this function equal to a function name using a unique ID number, and we always select one rotation as our basic rotation that the other rotations are based off of. For 16QAM: - n = 4 - (2^n)*(n!) = 384 - k \in [0x0, 0xF] - pi = 0, 1, 2, 3 0, 1, 3, 2 0, 2, 1, 3 0, 2, 3, 1 0, 3, 1, 2 0, 3, 2, 1 1, 0, 2, 3 1, 0, 3, 2 1, 2, 0, 3 1, 2, 3, 0 1, 3, 0, 2 1, 3, 2, 0 2, 0, 1, 3 2, 0, 3, 1 2, 1, 0, 3 2, 1, 3, 0 2, 3, 0, 1 2, 3, 1, 0 3, 0, 1, 2 3, 0, 2, 1 3, 1, 0, 2 3, 1, 2, 0 3, 2, 0, 1 3, 2, 1, 0 ''' def qam_16_0x0_0_1_2_3(): ''' 0010 0110 | 1110 1010 0011 0111 | 1111 1011 ----------------------- 0001 0101 | 1101 1001 0000 0100 | 1100 1000 ''' const_points = [-3-3j, -1-3j, 1-3j, 3-3j, -3-1j, -1-1j, 1-1j, 3-1j, -3+1j, -1+1j, 1+1j, 3+1j, -3+3j, -1+3j, 1+3j, 3+3j] symbols = [0x0, 0x4, 0xC, 0x8, 0x1, 0x5, 0xD, 0x9, 0x3, 0x7, 0xF, 0xB, 0x2, 0x6, 0xE, 0xA] return (const_points, symbols) qam_16 = qam_16_0x0_0_1_2_3 qam_16_0 = qam_16 def qam_16_0x1_0_1_2_3(): ''' 0011 0111 | 1111 1011 0010 0110 | 1110 1010 ----------------------- 0000 0100 | 1100 1000 0001 0101 | 1101 1001 ''' k = 0x1 pi = [0, 1, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_1 = qam_16_0x1_0_1_2_3 def qam_16_0x2_0_1_2_3(): ''' 0000 0100 | 1100 1000 0001 0101 | 1101 1001 ----------------------- 0011 0111 | 1111 1011 0010 0110 | 1110 1010 ''' k = 0x2 pi = [0, 1, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_2 = qam_16_0x2_0_1_2_3 def qam_16_0x3_0_1_2_3(): ''' 0001 0101 | 1101 1001 0000 0100 | 1100 1000 ----------------------- 0010 0110 | 1110 1010 0011 0111 | 1111 1011 ''' k = 0x3 pi = [0, 1, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_3 = qam_16_0x3_0_1_2_3 def qam_16_0x0_1_0_2_3(): ''' 0001 0101 | 1101 1001 0011 0111 | 1111 1011 ----------------------- 0010 0110 | 1110 1010 0000 0100 | 1100 1000 ''' k = 0x0 pi = [1, 0, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_4 = qam_16_0x0_1_0_2_3 def qam_16_0x1_1_0_2_3(): ''' 0000 0100 | 1100 1000 0010 0110 | 1110 1010 ----------------------- 0011 0111 | 1111 1011 0001 0101 | 1101 1001 ''' k = 0x1 pi = [1, 0, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_5 = qam_16_0x1_1_0_2_3 def qam_16_0x2_1_0_2_3(): ''' 0011 0111 | 1111 1011 0001 0101 | 1101 1001 ----------------------- 0000 0100 | 1100 1000 0010 0110 | 1110 1010 ''' k = 0x2 pi = [1, 0, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_6 = qam_16_0x2_1_0_2_3 def qam_16_0x3_1_0_2_3(): ''' 0010 0110 | 1110 1010 0000 0100 | 1100 1000 ----------------------- 0001 0101 | 1101 1001 0011 0111 | 1111 1011 ''' k = 0x3 pi = [1, 0, 2, 3] return constellation_map_generator(qam_16, k, pi) qam_16_7 = qam_16_0x3_1_0_2_3 # Soft bit LUT generators def sd_qam_16_0x0_0_1_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0010 0110 | 1110 1010 0011 0111 | 1111 1011 ----------------------- 0001 0101 | 1101 1001 0000 0100 | 1100 1000 ''' dist = Es*numpy.sqrt(2) boundary = dist/3.0 dist0 = dist/6.0 # print "Sample: ", x # print "Es: ", Es # print "Distance: ", dist # print "Boundary: ", boundary # print "1st Bound: ", dist0 x_re = x.real x_im = x.imag if x_re < -boundary: b3 = boundary*(x_re + dist0) elif x_re < boundary: b3 = x_re else: b3 = boundary*(x_re - dist0) if x_im < -boundary: b1 = boundary*(x_im + dist0) elif x_im < boundary: b1 = x_im else: b1 = boundary*(x_im - dist0) b2 = -abs(x_re) + boundary b0 = -abs(x_im) + boundary return [(Es/2)*b3, (Es/2)*b2, (Es/2)*b1, (Es/2)*b0] sd_qam_16 = sd_qam_16_0x0_0_1_2_3 sd_qam_16_0 = sd_qam_16 def sd_qam_16_0x1_0_1_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0011 0111 | 1111 1011 0010 0110 | 1110 1010 ----------------------- 0000 0100 | 1100 1000 0001 0101 | 1101 1001 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b1 = 2*(x_im + 1) elif x_im < 2: b1 = x_im else: b1 = 2*(x_im - 1) b2 = -abs(x_re) + 2 b0 = +abs(x_im) - 2 return [b3, b2, b1, b0] sd_qam_16_1 = sd_qam_16_0x1_0_1_2_3 def sd_qam_16_0x2_0_1_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0000 0100 | 1100 1000 0001 0101 | 1101 1001 ----------------------- 0011 0111 | 1111 1011 0010 0110 | 1110 1010 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b1 = -2*(x_im + 1) elif x_im < 2: b1 = -x_im else: b1 = -2*(x_im - 1) b2 = -abs(x_re) + 2 b0 = -abs(x_im) + 2 return [b3, b2, b1, b0] sd_qam_16_2 = sd_qam_16_0x2_0_1_2_3 def sd_qam_16_0x3_0_1_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0001 0101 | 1101 1001 0000 0100 | 1100 1000 ----------------------- 0010 0110 | 1110 1010 0011 0111 | 1111 1011 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b1 = -2*(x_im + 1) elif x_im < 2: b1 = -x_im else: b1 = -2*(x_im - 1) b2 = -abs(x_re) + 2 b0 = +abs(x_im) - 2 return [b3, b2, b1, b0] sd_qam_16_3 = sd_qam_16_0x3_0_1_2_3 def sd_qam_16_0x0_1_0_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0001 0101 | 1101 1001 0011 0111 | 1111 1011 ----------------------- 0010 0110 | 1110 1010 0000 0100 | 1100 1000 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b0 = 2*(x_im + 1) elif x_im < 2: b0 = x_im else: b0 = 2*(x_im - 1) b2 = -abs(x_re) + 2 b1 = -abs(x_im) + 2 return [b3, b2, b1, b0] sd_qam_16_4 = sd_qam_16_0x0_1_0_2_3 def sd_qam_16_0x1_1_0_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0000 0100 | 1100 1000 0010 0110 | 1110 1010 ----------------------- 0011 0111 | 1111 1011 0001 0101 | 1101 1001 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b0 = -2*(x_im + 1) elif x_im < 2: b0 = -x_im else: b0 = -2*(x_im - 1) b2 = -abs(x_re) + 2 b1 = -abs(x_im) + 2 return [b3, b2, b1, b0] sd_qam_16_5 = sd_qam_16_0x1_1_0_2_3 def sd_qam_16_0x2_1_0_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0011 0111 | 1111 1011 0001 0101 | 1101 1001 ----------------------- 0000 0100 | 1100 1000 0010 0110 | 1110 1010 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b0 = 2*(x_im + 1) elif x_im < 2: b0 = x_im else: b0 = 2*(x_im - 1) b2 = -abs(x_re) + 2 b1 = +abs(x_im) - 2 return [b3, b2, b1, b0] sd_qam_16_6 = sd_qam_16_0x2_1_0_2_3 def sd_qam_16_0x3_1_0_2_3(x, Es=1): ''' Soft bit LUT generator for constellation: 0010 0110 | 1110 1010 0000 0100 | 1100 1000 ----------------------- 0001 0101 | 1101 1001 0011 0111 | 1111 1011 ''' x_re = 3*x.real x_im = 3*x.imag if x_re < -2: b3 = 2*(x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2*(x_re - 1) if x_im < -2: b0 = -2*(x_im + 1) elif x_im < 2: b0 = -x_im else: b0 = -2*(x_im - 1) b2 = -abs(x_re) + 2 b1 = +abs(x_im) - 2 return [b3, b2, b1, b0] sd_qam_16_7 = sd_qam_16_0x3_1_0_2_3 gnuradio-3.7.2.1/gr-digital/python/digital/constellation_map_generator.py0000664000175000017500000000371012237515112026440 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # def constellation_map_generator(basis_cpoints, basis_symbols, k, pi): ''' Uses the a basis constellation provided (e.g., from psk_constellation.psk_4()) and the the k and permutation index (pi) to generate a new Gray-coded symbol map to the constellation points provided in the basis. The basis_cpoints are the constellation points of the basis constellation, and basis_symbols are the symbols that correspond to the constellation points. The selection of k and pi will provide an automorphism the hyperoctahedral group of the basis constellation. This function returns a tuple of (constellation_points, symbol_map). The constellation_points is a list of the constellation points in complex space and the symbol_map is a list of the log2(M)-bit symbols for the constellation points (i.e., symbol_map[i] are the bits associated with constellation_points[i]). ''' const_points, s = basis() symbols = list() for s_i in s: tmp = 0 for i,p in enumerate(pi): bit = (s_i >> i) & 0x1 tmp |= bit << p symbols.append(tmp ^ k) return (const_points, symbols) gnuradio-3.7.2.1/gr-digital/python/digital/qa_mpsk_receiver.py0000775000175000017500000001147612243426635024221 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import cmath import time from gnuradio import gr, gr_unittest, digital, filter, blocks class test_mpsk_receiver(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): # Test BPSK sync M = 2 theta = 0 loop_bw = cmath.pi/100.0 fmin = -0.5 fmax = 0.5 mu = 0.5 gain_mu = 0.01 omega = 2 gain_omega = 0.001 omega_rel = 0.001 self.test = digital.mpsk_receiver_cc(M, theta, loop_bw, fmin, fmax, mu, gain_mu, omega, gain_omega, omega_rel) data = 10000*[complex(1,0), complex(-1,0)] #data = [2*random.randint(0,1)-1 for x in xrange(10000)] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() # pulse shaping interpolation filter nfilts = 32 excess_bw = 0.35 ntaps = 11 * int(omega*nfilts) rrc_taps0 = filter.firdes.root_raised_cosine( nfilts, nfilts, 1.0, excess_bw, ntaps) rrc_taps1 = filter.firdes.root_raised_cosine( 1, omega, 1.0, excess_bw, 11*omega) self.rrc0 = filter.pfb_arb_resampler_ccf(omega, rrc_taps0) self.rrc1 = filter.fir_filter_ccf(1, rrc_taps1) self.tb.connect(self.src, self.rrc0, self.rrc1, self.test, self.snk) self.tb.run() expected_result = [-0.5*d for d in data] dst_data = self.snk.data() # Only Ncmp samples after Nstrt samples Nstrt = 9000 Ncmp = 1000 expected_result = expected_result[Nstrt:Nstrt+Ncmp] dst_data = dst_data[Nstrt:Nstrt+Ncmp] #for e,d in zip(expected_result, dst_data): # print "{0:+.02f} {1:+.02f}".format(e, d) self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 1) def test02(self): # Test QPSK sync M = 4 theta = 0 loop_bw = cmath.pi/100.0 fmin = -0.5 fmax = 0.5 mu = 0.5 gain_mu = 0.01 omega = 2 gain_omega = 0.001 omega_rel = 0.001 self.test = digital.mpsk_receiver_cc(M, theta, loop_bw, fmin, fmax, mu, gain_mu, omega, gain_omega, omega_rel) data = 10000*[complex( 0.707, 0.707), complex(-0.707, 0.707), complex(-0.707, -0.707), complex( 0.707, -0.707)] data = [0.5*d for d in data] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() # pulse shaping interpolation filter nfilts = 32 excess_bw = 0.35 ntaps = 11 * int(omega*nfilts) rrc_taps0 = filter.firdes.root_raised_cosine( nfilts, nfilts, 1.0, excess_bw, ntaps) rrc_taps1 = filter.firdes.root_raised_cosine( 1, omega, 1.0, excess_bw, 11*omega) self.rrc0 = filter.pfb_arb_resampler_ccf(omega, rrc_taps0) self.rrc1 = filter.fir_filter_ccf(1, rrc_taps1) self.tb.connect(self.src, self.rrc0, self.rrc1, self.test, self.snk) self.tb.run() expected_result = 10000*[complex(-0.5, +0.0), complex(+0.0, -0.5), complex(+0.5, +0.0), complex(+0.0, +0.5)] dst_data = self.snk.data() # Only Ncmp samples after Nstrt samples Nstrt = 9000 Ncmp = 1000 expected_result = expected_result[Nstrt:Nstrt+Ncmp] dst_data = dst_data[Nstrt:Nstrt+Ncmp] #for e,d in zip(expected_result, dst_data): # print "{0:+.02f} {1:+.02f}".format(e, d) self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 1) if __name__ == '__main__': gr_unittest.run(test_mpsk_receiver, "test_mpsk_receiver.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_lms_equalizer.py0000775000175000017500000000334112207440367024225 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_lms_dd_equalizer(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def transform(self, src_data, gain, const): SRC = blocks.vector_source_c(src_data, False) EQU = digital.lms_dd_equalizer_cc(4, gain, 1, const.base()) DST = blocks.vector_sink_c() self.tb.connect(SRC, EQU, DST) self.tb.run() return DST.data() def test_001_identity(self): # Constant modulus signal so no adjustments const = digital.constellation_qpsk() src_data = const.points()*1000 N = 100 # settling time expected_data = src_data[N:] result = self.transform(src_data, 0.1, const)[N:] N = -500 self.assertComplexTuplesAlmostEqual(expected_data[N:], result[N:], 5) if __name__ == "__main__": gr_unittest.run(test_lms_dd_equalizer, "test_lms_dd_equalizer.xml") gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_sync_ml.py0000664000175000017500000001675712207440367023355 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr try: from gnuradio import filter except ImportError: import filter_swig as filter try: from gnuradio import blocks except ImportError: import blocks_swig as blocks class ofdm_sync_ml(gr.hier_block2): def __init__(self, fft_length, cp_length, snr, kstime, logging): ''' Maximum Likelihood OFDM synchronizer: J. van de Beek, M. Sandell, and P. O. Borjesson, "ML Estimation of Time and Frequency Offset in OFDM Systems," IEEE Trans. Signal Processing, vol. 45, no. 7, pp. 1800-1805, 1997. ''' gr.hier_block2.__init__(self, "ofdm_sync_ml", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature2(2, 2, gr.sizeof_float, gr.sizeof_char)) # Output signature self.input = blocks.add_const_cc(0) SNR = 10.0**(snr/10.0) rho = SNR / (SNR + 1.0) symbol_length = fft_length + cp_length # ML Sync # Energy Detection from ML Sync self.connect(self, self.input) # Create a delay line self.delay = blocks.delay(gr.sizeof_gr_complex, fft_length) self.connect(self.input, self.delay) # magnitude squared blocks self.magsqrd1 = blocks.complex_to_mag_squared() self.magsqrd2 = blocks.complex_to_mag_squared() self.adder = blocks.add_ff() moving_sum_taps = [rho/2 for i in range(cp_length)] self.moving_sum_filter = filter.fir_filter_fff(1,moving_sum_taps) self.connect(self.input,self.magsqrd1) self.connect(self.delay,self.magsqrd2) self.connect(self.magsqrd1,(self.adder,0)) self.connect(self.magsqrd2,(self.adder,1)) self.connect(self.adder,self.moving_sum_filter) # Correlation from ML Sync self.conjg = blocks.conjugate_cc(); self.mixer = blocks.multiply_cc(); movingsum2_taps = [1.0 for i in range(cp_length)] self.movingsum2 = filter.fir_filter_ccf(1,movingsum2_taps) # Correlator data handler self.c2mag = blocks.complex_to_mag() self.angle = blocks.complex_to_arg() self.connect(self.input,(self.mixer,1)) self.connect(self.delay,self.conjg,(self.mixer,0)) self.connect(self.mixer,self.movingsum2,self.c2mag) self.connect(self.movingsum2,self.angle) # ML Sync output arg, need to find maximum point of this self.diff = blocks.sub_ff() self.connect(self.c2mag,(self.diff,0)) self.connect(self.moving_sum_filter,(self.diff,1)) #ML measurements input to sampler block and detect self.f2c = blocks.float_to_complex() self.pk_detect = blocks.peak_detector_fb(0.2, 0.25, 30, 0.0005) self.sample_and_hold = blocks.sample_and_hold_ff() # use the sync loop values to set the sampler and the NCO # self.diff = theta # self.angle = epsilon self.connect(self.diff, self.pk_detect) # The DPLL corrects for timing differences between CP correlations use_dpll = 0 if use_dpll: self.dpll = gr.dpll_bb(float(symbol_length),0.01) self.connect(self.pk_detect, self.dpll) self.connect(self.dpll, (self.sample_and_hold,1)) else: self.connect(self.pk_detect, (self.sample_and_hold,1)) self.connect(self.angle, (self.sample_and_hold,0)) ################################ # correlate against known symbol # This gives us the same timing signal as the PN sync block only on the preamble # we don't use the signal generated from the CP correlation because we don't want # to readjust the timing in the middle of the packet or we ruin the equalizer settings. kstime = [k.conjugate() for k in kstime] kstime.reverse() self.kscorr = filter.fir_filter_ccc(1, kstime) self.corrmag = blocks.complex_to_mag_squared() self.div = blocks.divide_ff() # The output signature of the correlation has a few spikes because the rest of the # system uses the repeated preamble symbol. It needs to work that generically if # anyone wants to use this against a WiMAX-like signal since it, too, repeats. # The output theta of the correlator above is multiplied with this correlation to # identify the proper peak and remove other products in this cross-correlation self.threshold_factor = 0.1 self.slice = blocks.threshold_ff(self.threshold_factor, self.threshold_factor, 0) self.f2b = blocks.float_to_char() self.b2f = blocks.char_to_float() self.mul = blocks.multiply_ff() # Normalize the power of the corr output by the energy. This is not really needed # and could be removed for performance, but it makes for a cleaner signal. # if this is removed, the threshold value needs adjustment. self.connect(self.input, self.kscorr, self.corrmag, (self.div,0)) self.connect(self.moving_sum_filter, (self.div,1)) self.connect(self.div, (self.mul,0)) self.connect(self.pk_detect, self.b2f, (self.mul,1)) self.connect(self.mul, self.slice) # Set output signals # Output 0: fine frequency correction value # Output 1: timing signal self.connect(self.sample_and_hold, (self,0)) self.connect(self.slice, self.f2b, (self,1)) if logging: self.connect(self.moving_sum_filter, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-energy_f.dat")) self.connect(self.diff, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-theta_f.dat")) self.connect(self.angle, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-epsilon_f.dat")) self.connect(self.corrmag, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-corrmag_f.dat")) self.connect(self.kscorr, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_sync_ml-kscorr_c.dat")) self.connect(self.div, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-div_f.dat")) self.connect(self.mul, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-mul_f.dat")) self.connect(self.slice, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-slice_f.dat")) self.connect(self.pk_detect, blocks.file_sink(gr.sizeof_char, "ofdm_sync_ml-peaks_b.dat")) if use_dpll: self.connect(self.dpll, blocks.file_sink(gr.sizeof_char, "ofdm_sync_ml-dpll_b.dat")) self.connect(self.sample_and_hold, blocks.file_sink(gr.sizeof_float, "ofdm_sync_ml-sample_and_hold_f.dat")) self.connect(self.input, blocks.file_sink(gr.sizeof_gr_complex, "ofdm_sync_ml-input_c.dat")) gnuradio-3.7.2.1/gr-digital/python/digital/qa_diff_phasor_cc.py0000775000175000017500000000323212207440367024301 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_diff_phasor(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_diff_phasor_cc(self): src_data = (0+0j, 1+0j, -1+0j, 3+4j, -3-4j, -3+4j) expected_result = (0+0j, 0+0j, -1+0j, -3-4j, -25+0j, -7-24j) src = blocks.vector_source_c(src_data) op = digital.diff_phasor_cc() dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink self.assertComplexTuplesAlmostEqual(expected_result, actual_result) if __name__ == '__main__': gr_unittest.run(test_diff_phasor, "test_diff_phasor.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_ofdm_txrx.py0000775000175000017500000001557412237515112023370 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import numpy import pmt from gnuradio import gr, gr_unittest from gnuradio import digital from gnuradio import blocks from gnuradio import channels from gnuradio.digital.ofdm_txrx import ofdm_tx, ofdm_rx from gnuradio.digital.utils import tagged_streams # Set this to true if you need to write out data LOG_DEBUG_INFO=False class ofdm_tx_fg (gr.top_block): def __init__(self, data, len_tag_key, scramble_bits=False, additional_tags=[]): gr.top_block.__init__(self, "ofdm_tx") tx_data, tags = tagged_streams.packets_to_vectors((data,), len_tag_key) src = blocks.vector_source_b(data, False, 1, tags + additional_tags) self.tx = ofdm_tx(packet_length_tag_key=len_tag_key, debug_log=LOG_DEBUG_INFO, scramble_bits=scramble_bits) self.sink = blocks.vector_sink_c() self.connect(src, self.tx, self.sink) def get_tx_samples(self): return self.sink.data() class ofdm_rx_fg (gr.top_block): def __init__(self, samples, len_tag_key, channel=None, prepend_zeros=100, scramble_bits=False): gr.top_block.__init__(self, "ofdm_rx") if prepend_zeros: samples = (0,) * prepend_zeros + tuple(samples) src = blocks.vector_source_c(tuple(samples) + (0,) * 1000) self.rx = ofdm_rx(frame_length_tag_key=len_tag_key, debug_log=LOG_DEBUG_INFO, scramble_bits=scramble_bits) if channel is not None: self.connect(src, channel, self.rx) else: self.connect(src, self.rx) self.sink = blocks.vector_sink_b() self.connect(self.rx, self.sink) def get_rx_bytes(self): return self.sink.data() class test_ofdm_txrx (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_tx (self): """ Just make sure the Tx works in general """ # This tag gets put onto the first item of the transmit data, # it should be transmitted first, too timing_tag = gr.tag_t() timing_tag.offset = 0 timing_tag.key = pmt.string_to_symbol('tx_timing') timing_tag.value = pmt.to_pmt('now') len_tag_key = 'frame_len' n_bytes = 52 n_samples_expected = (numpy.ceil(1.0 * (n_bytes + 4) / 6) + 3) * 80 test_data = [random.randint(0, 255) for x in range(n_bytes)] tx_fg = ofdm_tx_fg(test_data, len_tag_key, additional_tags=[timing_tag,]) tx_fg.run() self.assertEqual(len(tx_fg.get_tx_samples()), n_samples_expected) tags_rx = [gr.tag_to_python(x) for x in tx_fg.sink.tags()] tags_rx = sorted([(x.offset, x.key, x.value) for x in tags_rx]) tags_expected = [ (0, 'frame_len', n_samples_expected), (0, 'tx_timing', 'now'), ] self.assertEqual(tags_rx, tags_expected) def test_002_rx_only_noise(self): """ Run the RX with only noise, check it doesn't crash or return a burst. """ len_tag_key = 'frame_len' samples = (0,) * 1000 channel = channels.channel_model(0.1) rx_fg = ofdm_rx_fg(samples, len_tag_key, channel) rx_fg.run() self.assertEqual(len(rx_fg.get_rx_bytes()), 0) def test_003_tx1packet(self): """ Transmit one packet, with slight AWGN and slight frequency + timing offset. Check packet is received and no bit errors have occurred. """ len_tag_key = 'frame_len' n_bytes = 21 fft_len = 64 test_data = tuple([random.randint(0, 255) for x in range(n_bytes)]) # 1.0/fft_len is one sub-carrier, a fine freq offset stays below that freq_offset = 1.0 / fft_len * 0.7 #channel = channels.channel_model(0.01, freq_offset) channel = None # Tx tx_fg = ofdm_tx_fg(test_data, len_tag_key) tx_fg.run() tx_samples = tx_fg.get_tx_samples() # Rx rx_fg = ofdm_rx_fg(tx_samples, len_tag_key, channel, prepend_zeros=100) rx_fg.run() rx_data = rx_fg.get_rx_bytes() self.assertEqual(tuple(tx_fg.tx.sync_word1), tuple(rx_fg.rx.sync_word1)) self.assertEqual(tuple(tx_fg.tx.sync_word2), tuple(rx_fg.rx.sync_word2)) self.assertEqual(test_data, rx_data) def test_003_tx1packet_scramble(self): """ Same as before, use scrambler. """ len_tag_key = 'frame_len' n_bytes = 21 fft_len = 64 test_data = tuple([random.randint(0, 255) for x in range(n_bytes)]) # 1.0/fft_len is one sub-carrier, a fine freq offset stays below that freq_offset = 1.0 / fft_len * 0.7 #channel = channels.channel_model(0.01, freq_offset) channel = None # Tx tx_fg = ofdm_tx_fg(test_data, len_tag_key, scramble_bits=True) tx_fg.run() tx_samples = tx_fg.get_tx_samples() # Rx rx_fg = ofdm_rx_fg(tx_samples, len_tag_key, channel, prepend_zeros=100, scramble_bits=True) rx_fg.run() rx_data = rx_fg.get_rx_bytes() self.assertEqual(tuple(tx_fg.tx.sync_word1), tuple(rx_fg.rx.sync_word1)) self.assertEqual(tuple(tx_fg.tx.sync_word2), tuple(rx_fg.rx.sync_word2)) self.assertEqual(test_data, rx_data) def test_004_tx1packet_large_fO(self): """ Transmit one packet, with slight AWGN and large frequency offset. Check packet is received and no bit errors have occurred. """ fft_len = 64 len_tag_key = 'frame_len' n_bytes = 21 test_data = tuple([random.randint(0, 255) for x in range(n_bytes)]) #test_data = tuple([255 for x in range(n_bytes)]) # 1.0/fft_len is one sub-carrier frequency_offset = 1.0 / fft_len * 2.5 channel = channels.channel_model(0.00001, frequency_offset) # Tx tx_fg = ofdm_tx_fg(test_data, len_tag_key) tx_fg.run() tx_samples = tx_fg.get_tx_samples() # Rx rx_fg = ofdm_rx_fg(tx_samples, len_tag_key, channel, prepend_zeros=100) rx_fg.run() rx_data = rx_fg.get_rx_bytes() self.assertEqual(test_data, rx_data) if __name__ == '__main__': gr_unittest.run(test_ofdm_txrx, "test_ofdm_txrx.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qam.py0000664000175000017500000003302612207440367021446 0ustar jcorganjcorgan# # Copyright 2005,2006,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ QAM modulation and demodulation. """ from math import pi, sqrt, log from gnuradio import gr from generic_mod_demod import generic_mod, generic_demod from generic_mod_demod import shared_mod_args, shared_demod_args from utils.gray_code import gray_code from utils import mod_codes import modulation_utils import digital_swig as digital # Default number of points in constellation. _def_constellation_points = 16 # Whether the quadrant bits are coded differentially. _def_differential = True # Whether gray coding is used. If differential is True then gray # coding is used within but not between each quadrant. _def_mod_code = mod_codes.NO_CODE def is_power_of_four(x): v = log(x)/log(4) return int(v) == v def get_bit(x, n): """ Get the n'th bit of integer x (from little end).""" return (x&(0x01 << n)) >> n def get_bits(x, n, k): """ Get the k bits of integer x starting at bit n(from little end).""" # Remove the n smallest bits v = x >> n # Remove all bits bigger than n+k-1 return v % pow(2, k) def make_differential_constellation(m, gray_coded): """ Create a constellation with m possible symbols where m must be a power of 4. Points are laid out in a square grid. Bits referring to the quadrant are differentilly encoded, remaining bits are gray coded. """ sqrtm = pow(m, 0.5) if (not isinstance(m, int) or m < 4 or not is_power_of_four(m)): raise ValueError("m must be a power of 4 integer.") # Each symbol holds k bits. k = int(log(m) / log(2.0)) # First create a constellation for one quadrant containing m/4 points. # The quadrant has 'side' points along each side of a quadrant. side = int(sqrtm/2) if gray_coded: # Number rows and columns using gray codes. gcs = gray_code(side) # Get inverse gray codes. i_gcs = dict([(v, key) for key, v in enumerate(gcs)]) else: i_gcs = dict([(i, i) for i in range(0, side)]) # The distance between points is found. step = 1/(side-0.5) gc_to_x = [(i_gcs[gc]+0.5)*step for gc in range(0, side)] # Takes the (x, y) location of the point with the quadrant along # with the quadrant number. (x, y) are integers referring to which # point within the quadrant it is. # A complex number representing this location of this point is returned. def get_c(gc_x, gc_y, quad): if quad == 0: return complex(gc_to_x[gc_x], gc_to_x[gc_y]) if quad == 1: return complex(-gc_to_x[gc_y], gc_to_x[gc_x]) if quad == 2: return complex(-gc_to_x[gc_x], -gc_to_x[gc_y]) if quad == 3: return complex(gc_to_x[gc_y], -gc_to_x[gc_x]) raise StandardError("Impossible!") # First two bits determine quadrant. # Next (k-2)/2 bits determine x position. # Following (k-2)/2 bits determine y position. # How x and y relate to real and imag depends on quadrant (see get_c function). const_map = [] for i in range(m): y = get_bits(i, 0, (k-2)/2) x = get_bits(i, (k-2)/2, (k-2)/2) quad = get_bits(i, k-2, 2) const_map.append(get_c(x, y, quad)) return const_map def make_non_differential_constellation(m, gray_coded): side = int(pow(m, 0.5)) if (not isinstance(m, int) or m < 4 or not is_power_of_four(m)): raise ValueError("m must be a power of 4 integer.") # Each symbol holds k bits. k = int(log(m) / log(2.0)) if gray_coded: # Number rows and columns using gray codes. gcs = gray_code(side) # Get inverse gray codes. i_gcs = mod_codes.invert_code(gcs) else: i_gcs = range(0, side) # The distance between points is found. step = 2.0/(side-1) gc_to_x = [-1 + i_gcs[gc]*step for gc in range(0, side)] # First k/2 bits determine x position. # Following k/2 bits determine y position. const_map = [] for i in range(m): y = gc_to_x[get_bits(i, 0, k/2)] x = gc_to_x[get_bits(i, k/2, k/2)] const_map.append(complex(x,y)) return const_map # ///////////////////////////////////////////////////////////////////////////// # QAM constellation # ///////////////////////////////////////////////////////////////////////////// def qam_constellation(constellation_points=_def_constellation_points, differential=_def_differential, mod_code=_def_mod_code, large_ampls_to_corners=False): """ Creates a QAM constellation object. If large_ampls_to_corners=True then sectors that are probably occupied due to a phase offset, are not mapped to the closest constellation point. Rather we take into account the fact that a phase offset is probably the problem and map them to the closest corner point. It's a bit hackish but it seems to improve frequency locking. """ if mod_code == mod_codes.GRAY_CODE: gray_coded = True elif mod_code == mod_codes.NO_CODE: gray_coded = False else: raise ValueError("Mod code is not implemented for QAM") if differential: points = make_differential_constellation(constellation_points, gray_coded=False) else: points = make_non_differential_constellation(constellation_points, gray_coded) side = int(sqrt(constellation_points)) width = 2.0/(side-1) # No pre-diff code # Should add one so that we can gray-code the quadrant bits too. pre_diff_code = [] if not large_ampls_to_corners: constellation = digital.constellation_rect(points, pre_diff_code, 4, side, side, width, width) else: sector_values = large_ampls_to_corners_mapping(side, points, width) constellation = digital.constellation_expl_rect( points, pre_diff_code, 4, side, side, width, width, sector_values) return constellation def find_closest_point(p, qs): """ Return in index of the closest point in 'qs' to 'p'. """ min_dist = None min_i = None for i, q in enumerate(qs): dist = abs(q-p) if min_dist is None or dist < min_dist: min_dist = dist min_i = i return min_i def large_ampls_to_corners_mapping(side, points, width): """ We have a grid that we use for decision making. One additional row/column is placed on each side of the grid. Points in these additional rows/columns are mapped to the corners rather than the closest constellation points. Args: side: The number of rows/columns in the grid that we use to do decision making. points: The list of constellation points. width: The width of the rows/columns. Returns: sector_values maps the sector index to the constellation point index. """ # First find the indices of the corner points. # Assume the corner points are the 4 points with the largest magnitudes. corner_indices = [] corner_points = [] max_mag = 0 for i, p in enumerate(points): if abs(p) > max_mag: corner_indices = [i] corner_points = [p] max_mag = abs(p) elif abs(p) == max_mag: corner_indices.append(i) corner_points.append(p) if len(corner_indices) != 4: raise ValueError("Found {0} corner indices. Expected 4." .format(len(corner_indices))) # We want an additional layer around the constellation # Value in this extra layer will be mapped to the closest corner rather # than the closest constellation point. extra_layers = 1 side = side + extra_layers*2 # Calculate sector values sector_values = [] for real_x in range(side): for imag_x in range(side): sector = real_x * side + imag_x # If this sector is a normal constellation sector then # use the center point. c = ((real_x-side/2.0+0.5)*width + (imag_x-side/2.0+0.5)*width*1j) if (real_x >= extra_layers and real_x < side-extra_layers and imag_x >= extra_layers and imag_x < side-extra_layers): # This is not an edge row/column. Find closest point. index = find_closest_point(c, points) else: # This is an edge. Find closest corner point. index = corner_indices[find_closest_point(c, corner_points)] sector_values.append(index) return sector_values # ///////////////////////////////////////////////////////////////////////////// # QAM modulator # ///////////////////////////////////////////////////////////////////////////// class qam_mod(generic_mod): """ Hierarchical block for RRC-filtered QAM modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation_points: Number of constellation points (must be a power of four) (integer). mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). differential: Whether to use differential encoding (boolean). """ # See generic_mod for additional arguments __doc__ += shared_mod_args def __init__(self, constellation_points=_def_constellation_points, differential=_def_differential, mod_code=_def_mod_code, *args, **kwargs): """ Hierarchical block for RRC-filtered QAM modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation_points: Number of constellation points. Must be a power of 4. mod_code: Specifies an encoding to use (typically used to indicated if we want gray coding, see digital.utils.mod_codes) See generic_mod block for list of additional parameters. """ constellation = qam_constellation(constellation_points, differential, mod_code) # We take care of the gray coding in the constellation # generation so it doesn't need to be done in the block. super(qam_mod, self).__init__(constellation, differential=differential, *args, **kwargs) # ///////////////////////////////////////////////////////////////////////////// # QAM demodulator # # ///////////////////////////////////////////////////////////////////////////// class qam_demod(generic_demod): """ Hierarchical block for RRC-filtered QAM modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation_points: Number of constellation points (must be a power of four) (integer). mod_code: Whether to use a gray_code (digital.mod_codes.GRAY_CODE) or not (digital.mod_codes.NO_CODE). differential: Whether to use differential encoding (boolean). """ # See generic_demod for additional arguments __doc__ += shared_mod_args def __init__(self, constellation_points=_def_constellation_points, differential=_def_differential, mod_code=_def_mod_code, large_ampls_to_corner = False, *args, **kwargs): """ Hierarchical block for RRC-filtered QAM modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: constellation_points: Number of constellation points. Must be a power of 4. mod_code: Specifies an encoding to use (typically used to indicated if we want gray coding, see digital.utils.mod_codes) large_ampls_to_corners: If this is set to True then when the constellation is making decisions, points that are far outside the constellation are mapped to the closest corner rather than the closet constellation point. This can help with phase locking. See generic_demod block for list of additional parameters. """ constellation = qam_constellation(constellation_points, differential, mod_code) # We take care of the gray coding in the constellation # generation so it doesn't need to be done in the block. super(qam_demod, self).__init__(constellation, differential=differential, *args, **kwargs) # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('qam', qam_mod) modulation_utils.add_type_1_demod('qam', qam_demod) modulation_utils.add_type_1_constellation('qam', qam_constellation) gnuradio-3.7.2.1/gr-digital/python/digital/qa_costas_loop_cc.py0000775000175000017500000001154712207440367024352 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import cmath from gnuradio import gr, gr_unittest, digital, blocks from gnuradio.digital import psk class test_costas_loop_cc(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): # test basic functionality by setting all gains to 0 natfreq = 0.0 order = 2 self.test = digital.costas_loop_cc(natfreq, order) data = 100*[complex(1,0),] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() expected_result = data dst_data = self.snk.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) def test02(self): # Make sure it doesn't diverge given perfect data natfreq = 0.25 order = 2 self.test = digital.costas_loop_cc(natfreq, order) data = [complex(2*random.randint(0,1)-1, 0) for i in xrange(100)] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() expected_result = data dst_data = self.snk.data() self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 5) def test03(self): # BPSK Convergence test with static rotation natfreq = 0.25 order = 2 self.test = digital.costas_loop_cc(natfreq, order) rot = cmath.exp(0.2j) # some small rotation data = [complex(2*random.randint(0,1)-1, 0) for i in xrange(100)] N = 40 # settling time expected_result = data[N:] data = [rot*d for d in data] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() dst_data = self.snk.data()[N:] # generously compare results; the loop will converge near to, but # not exactly on, the target data self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 2) def test04(self): # QPSK Convergence test with static rotation natfreq = 0.25 order = 4 self.test = digital.costas_loop_cc(natfreq, order) rot = cmath.exp(0.2j) # some small rotation data = [complex(2*random.randint(0,1)-1, 2*random.randint(0,1)-1) for i in xrange(100)] N = 40 # settling time expected_result = data[N:] data = [rot*d for d in data] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() dst_data = self.snk.data()[N:] # generously compare results; the loop will converge near to, but # not exactly on, the target data self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 2) def test05(self): # 8PSK Convergence test with static rotation natfreq = 0.25 order = 8 self.test = digital.costas_loop_cc(natfreq, order) rot = cmath.exp(-cmath.pi/8.0j) # rotate to match Costas rotation const = psk.psk_constellation(order) data = [random.randint(0,7) for i in xrange(100)] data = [2*rot*const.points()[d] for d in data] N = 40 # settling time expected_result = data[N:] rot = cmath.exp(0.1j) # some small rotation data = [rot*d for d in data] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() dst_data = self.snk.data()[N:] # generously compare results; the loop will converge near to, but # not exactly on, the target data self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 2) if __name__ == '__main__': gr_unittest.run(test_costas_loop_cc, "test_costas_loop_cc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_simple_correlator.py0000775000175000017500000000414712207440367025103 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks, filter, digital class test_simple_correlator(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_00(self): expected_result = ( 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff) # Filter taps to expand the data to oversample by 8 # Just using a RRC for some basic filter shape taps = filter.firdes.root_raised_cosine(8, 8, 1.0, 0.5, 21) src = blocks.vector_source_b(expected_result) frame = digital.simple_framer(4) unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST) expand = filter.interp_fir_filter_fff(8, taps) b2f = blocks.char_to_float() mult2 = blocks.multiply_const_ff(2) sub1 = blocks.add_const_ff(-1) op = digital.simple_correlator(4) dst = blocks.vector_sink_b() self.tb.connect(src, frame, unpack, b2f, mult2, sub1, expand) self.tb.connect(expand, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_simple_correlator, "test_simple_correlator.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_digital.py0000775000175000017500000000207412207440367022770 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital class test_digital(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None if __name__ == '__main__': gr_unittest.run(test_digital, "test_digital.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_correlate_and_sync.py0000664000175000017500000000731212237515112025200 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math import pmt from gnuradio import gr, gr_unittest, digital, blocks, filter def make_parabolic_pulse_shape(sps, N=1, scale=1): # Make L taps on each side. L = int(float(N)/2 * sps) n_taps = 2 * L + 1 taps = [] for tap_i in xrange(n_taps): x = float(tap_i - L)/sps/N if abs(x) > 1: taps.append(0) else: taps.append(1-x*x) return [tap*scale for tap in taps] class test_correlate_and_sync(gr_unittest.TestCase): def test_001(self): # We're using a really simple preamble so that the correlation # is straight forward. preamble = [0, 0, 0, 1, 0, 0, 0] # Our pulse shape has this width (in units of symbols). pulse_width = 1.5 # The number of filters to use for resampling. n_filters = 12 sps = 3 data = [0]*10 + preamble + [0]*40 src = blocks.vector_source_c(data) # We want to generate taps with a sampling rate of sps=n_filters for resampling # purposes. pulse_shape = make_parabolic_pulse_shape(sps=n_filters, N=0.5, scale=35) # Create our resampling filter to generate the data for the correlator. shape = filter.pfb_arb_resampler_ccf(sps, pulse_shape, n_filters) # Generate the correlator block itself. correlator = digital.correlate_and_sync_cc(preamble, pulse_shape, sps, n_filters) # Connect it all up and go. snk = blocks.vector_sink_c() null = blocks.null_sink(gr.sizeof_gr_complex) tb = gr.top_block() tb.connect(src, shape, correlator, snk) tb.connect((correlator, 1), null) tb.run() # Look at the tags. Retrieve the timing offset. data = snk.data() offset = None timing_error = None for tag in snk.tags(): key = pmt.symbol_to_string(tag.key) if key == "time_est": offset = tag.offset timing_error = pmt.to_double(tag.value) if offset is None: raise ValueError("No tags found.") # Detect where the middle of the preamble is. # Assume we have only one peak and that it is symmetric. sum_id = 0 sum_d = 0 for i, d in enumerate(data): sum_id += i*abs(d) sum_d += abs(d) data_i = sum_id/sum_d if offset is not None: diff = data_i-offset remainder = -(diff%sps) if remainder < -sps/2.0: remainder += sps tol = 0.2 difference = timing_error - remainder difference = difference % sps if abs(difference) >= tol: print("Tag gives timing estimate of {0}. QA calculates it as {1}. Tolerance is {2}".format(timing_error, remainder, tol)) self.assertTrue(abs(difference) < tol) if __name__ == '__main__': gr_unittest.run(test_correlate_and_sync, "test_correlate_and_sync.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_framer_sink.py0000775000175000017500000000576412207440367023664 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks default_access_code = '\xAC\xDD\xA4\xE2\xF2\x8C\x20\xFC' def string_to_1_0_list(s): r = [] for ch in s: x = ord(ch) for i in range(8): t = (x >> i) & 0x1 r.append(t) return r def to_1_0_string(L): return ''.join(map(lambda x: chr(x + ord('0')), L)) class test_framker_sink(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): code = (1, 1, 0, 1) access_code = to_1_0_string(code) header = tuple(2*[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]) # len=1 pad = (0,) * 100 src_data = code + header + (0,1,0,0,0,0,0,1) + pad expected_data = 'A' rcvd_pktq = gr.msg_queue() src = blocks.vector_source_b(src_data) correlator = digital.correlate_access_code_bb(access_code, 0) framer_sink = digital.framer_sink_1(rcvd_pktq) vsnk = blocks.vector_sink_b() self.tb.connect(src, correlator, framer_sink) self.tb.connect(correlator, vsnk) self.tb.run() result_data = rcvd_pktq.delete_head() result_data = result_data.to_string() self.assertEqual(expected_data, result_data) def test_002(self): code = tuple(string_to_1_0_list(default_access_code)) access_code = to_1_0_string(code) header = tuple(2*[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]) # len=2 pad = (0,) * 100 src_data = code + header + (0,1,0,0,1,0,0,0) + (0,1,0,0,1,0,0,1) + pad expected_data = 'HI' rcvd_pktq = gr.msg_queue() src = blocks.vector_source_b(src_data) correlator = digital.correlate_access_code_bb(access_code, 0) framer_sink = digital.framer_sink_1(rcvd_pktq) vsnk = blocks.vector_sink_b() self.tb.connect(src, correlator, framer_sink) self.tb.connect(correlator, vsnk) self.tb.run() result_data = rcvd_pktq.delete_head() result_data = result_data.to_string() self.assertEqual(expected_data, result_data) if __name__ == '__main__': gr_unittest.run(test_framker_sink, "test_framker_sink.xml") gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_packet_utils.py0000664000175000017500000006516412207440367024374 0ustar jcorganjcorgan# # Copyright 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import struct import numpy from gnuradio import gru import crc def conv_packed_binary_string_to_1_0_string(s): """ '\xAF' --> '10101111' """ r = [] for ch in s: x = ord(ch) for i in range(7,-1,-1): t = (x >> i) & 0x1 r.append(t) return ''.join(map(lambda x: chr(x + ord('0')), r)) def conv_1_0_string_to_packed_binary_string(s): """ '10101111' -> ('\xAF', False) Basically the inverse of conv_packed_binary_string_to_1_0_string, but also returns a flag indicating if we had to pad with leading zeros to get to a multiple of 8. """ if not is_1_0_string(s): raise ValueError, "Input must be a string containing only 0's and 1's" # pad to multiple of 8 padded = False rem = len(s) % 8 if rem != 0: npad = 8 - rem s = '0' * npad + s padded = True assert len(s) % 8 == 0 r = [] i = 0 while i < len(s): t = 0 for j in range(8): t = (t << 1) | (ord(s[i + j]) - ord('0')) r.append(chr(t)) i += 8 return (''.join(r), padded) def is_1_0_string(s): if not isinstance(s, str): return False for ch in s: if not ch in ('0', '1'): return False return True def string_to_hex_list(s): return map(lambda x: hex(ord(x)), s) def whiten(s, o): sa = numpy.fromstring(s, numpy.uint8) z = sa ^ random_mask_vec8[o:len(sa)+o] return z.tostring() def dewhiten(s, o): return whiten(s, o) # self inverse def make_header(payload_len, whitener_offset=0): # Upper nibble is offset, lower 12 bits is len val = ((whitener_offset & 0xf) << 12) | (payload_len & 0x0fff) #print "offset =", whitener_offset, " len =", payload_len, " val=", val return struct.pack('!HH', val, val) def make_packet(payload, samples_per_symbol, bits_per_symbol, pad_for_usrp=True, whitener_offset=0, whitening=True): """ Build a packet, given access code, payload, and whitener offset Args: payload: packet payload, len [0, 4096] samples_per_symbol: samples per symbol (needed for padding calculation) (int) bits_per_symbol: (needed for padding calculation) (int) whitener_offset: offset into whitener string to use [0-16) whitening: Turn whitener on or off (bool) Packet will have access code at the beginning, followed by length, payload and finally CRC-32. """ if not whitener_offset >=0 and whitener_offset < 16: raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,) payload_with_crc = crc.gen_and_append_crc32(payload) #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:]) L = len(payload_with_crc) MAXLEN = len(random_mask_tuple) if L > MAXLEN: raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,) pkt_hd = make_header(L, whitener_offset) pkt_dt = ''.join((payload_with_crc, '\x55')) packet_length = len(pkt_hd) + len(pkt_dt) if pad_for_usrp: usrp_packing = _npadding_bytes(packet_length, samples_per_symbol, bits_per_symbol) * '\x55' pkt_dt = pkt_dt + usrp_packing if(whitening): pkt = pkt_hd + whiten(pkt_dt, whitener_offset) else: pkt = pkt_hd + pkt_dt #print "make_packet: len(pkt) =", len(pkt) return pkt def _npadding_bytes(pkt_byte_len, samples_per_symbol, bits_per_symbol): """ Generate sufficient padding such that each packet ultimately ends up being a multiple of 512 bytes when sent across the USB. We send 4-byte samples across the USB (16-bit I and 16-bit Q), thus we want to pad so that after modulation the resulting packet is a multiple of 128 samples. Args: ptk_byte_len: len in bytes of packet, not including padding. samples_per_symbol: samples per bit (1 bit / symbolwidth GMSK) (int) bits_per_symbol: bits per symbol (log2(modulation order)) (int) Returns: number of bytes of padding to append. """ modulus = 128 byte_modulus = gru.lcm(modulus/8, samples_per_symbol) * bits_per_symbol / samples_per_symbol r = pkt_byte_len % byte_modulus if r == 0: return 0 return byte_modulus - r def unmake_packet(whitened_payload_with_crc, whitener_offset=0, dewhitening=1): """ Return (ok, payload) Args: whitened_payload_with_crc: string whitener_offset: offset into whitener string to use [0-16) dewhitening: Turn whitener on or off (bool) """ if dewhitening: payload_with_crc = dewhiten(whitened_payload_with_crc, whitener_offset) else: payload_with_crc = whitened_payload_with_crc ok, payload = crc.check_crc32(payload_with_crc) if 0: print "payload_with_crc =", string_to_hex_list(payload_with_crc) print "ok = %r, len(payload) = %d" % (ok, len(payload)) print "payload =", string_to_hex_list(payload) return ok, payload # FYI, this PN code is the output of a 15-bit LFSR random_mask_tuple = ( 255, 63, 0, 16, 0, 12, 0, 5, 192, 3, 16, 1, 204, 0, 85, 192, 63, 16, 16, 12, 12, 5, 197, 195, 19, 17, 205, 204, 85, 149, 255, 47, 0, 28, 0, 9, 192, 6, 208, 2, 220, 1, 153, 192, 106, 208, 47, 28, 28, 9, 201, 198, 214, 210, 222, 221, 152, 89, 170, 186, 255, 51, 0, 21, 192, 15, 16, 4, 12, 3, 69, 193, 243, 16, 69, 204, 51, 21, 213, 207, 31, 20, 8, 15, 70, 132, 50, 227, 85, 137, 255, 38, 192, 26, 208, 11, 28, 7, 73, 194, 182, 209, 182, 220, 118, 217, 230, 218, 202, 219, 23, 27, 78, 139, 116, 103, 103, 106, 170, 175, 63, 60, 16, 17, 204, 12, 85, 197, 255, 19, 0, 13, 192, 5, 144, 3, 44, 1, 221, 192, 89, 144, 58, 236, 19, 13, 205, 197, 149, 147, 47, 45, 220, 29, 153, 201, 170, 214, 255, 30, 192, 8, 80, 6, 188, 2, 241, 193, 132, 80, 99, 124, 41, 225, 222, 200, 88, 86, 186, 190, 243, 48, 69, 212, 51, 31, 85, 200, 63, 22, 144, 14, 236, 4, 77, 195, 117, 145, 231, 44, 74, 157, 247, 41, 134, 158, 226, 232, 73, 142, 182, 228, 118, 203, 102, 215, 106, 222, 175, 24, 124, 10, 161, 199, 56, 82, 146, 189, 173, 177, 189, 180, 113, 183, 100, 118, 171, 102, 255, 106, 192, 47, 16, 28, 12, 9, 197, 198, 211, 18, 221, 205, 153, 149, 170, 239, 63, 12, 16, 5, 204, 3, 21, 193, 207, 16, 84, 12, 63, 69, 208, 51, 28, 21, 201, 207, 22, 212, 14, 223, 68, 88, 51, 122, 149, 227, 47, 9, 220, 6, 217, 194, 218, 209, 155, 28, 107, 73, 239, 118, 204, 38, 213, 218, 223, 27, 24, 11, 74, 135, 119, 34, 166, 153, 186, 234, 243, 15, 5, 196, 3, 19, 65, 205, 240, 85, 132, 63, 35, 80, 25, 252, 10, 193, 199, 16, 82, 140, 61, 165, 209, 187, 28, 115, 73, 229, 246, 203, 6, 215, 66, 222, 177, 152, 116, 106, 167, 111, 58, 172, 19, 61, 205, 209, 149, 156, 111, 41, 236, 30, 205, 200, 85, 150, 191, 46, 240, 28, 68, 9, 243, 70, 197, 242, 211, 5, 157, 195, 41, 145, 222, 236, 88, 77, 250, 181, 131, 55, 33, 214, 152, 94, 234, 184, 79, 50, 180, 21, 183, 79, 54, 180, 22, 247, 78, 198, 180, 82, 247, 125, 134, 161, 162, 248, 121, 130, 162, 225, 185, 136, 114, 230, 165, 138, 251, 39, 3, 90, 129, 251, 32, 67, 88, 49, 250, 148, 67, 47, 113, 220, 36, 89, 219, 122, 219, 99, 27, 105, 203, 110, 215, 108, 94, 173, 248, 125, 130, 161, 161, 184, 120, 114, 162, 165, 185, 187, 50, 243, 85, 133, 255, 35, 0, 25, 192, 10, 208, 7, 28, 2, 137, 193, 166, 208, 122, 220, 35, 25, 217, 202, 218, 215, 27, 30, 139, 72, 103, 118, 170, 166, 255, 58, 192, 19, 16, 13, 204, 5, 149, 195, 47, 17, 220, 12, 89, 197, 250, 211, 3, 29, 193, 201, 144, 86, 236, 62, 205, 208, 85, 156, 63, 41, 208, 30, 220, 8, 89, 198, 186, 210, 243, 29, 133, 201, 163, 22, 249, 206, 194, 212, 81, 159, 124, 104, 33, 238, 152, 76, 106, 181, 239, 55, 12, 22, 133, 206, 227, 20, 73, 207, 118, 212, 38, 223, 90, 216, 59, 26, 147, 75, 45, 247, 93, 134, 185, 162, 242, 249, 133, 130, 227, 33, 137, 216, 102, 218, 170, 219, 63, 27, 80, 11, 124, 7, 97, 194, 168, 81, 190, 188, 112, 113, 228, 36, 75, 91, 119, 123, 102, 163, 106, 249, 239, 2, 204, 1, 149, 192, 111, 16, 44, 12, 29, 197, 201, 147, 22, 237, 206, 205, 148, 85, 175, 127, 60, 32, 17, 216, 12, 90, 133, 251, 35, 3, 89, 193, 250, 208, 67, 28, 49, 201, 212, 86, 223, 126, 216, 32, 90, 152, 59, 42, 147, 95, 45, 248, 29, 130, 137, 161, 166, 248, 122, 194, 163, 17, 185, 204, 114, 213, 229, 159, 11, 40, 7, 94, 130, 184, 97, 178, 168, 117, 190, 167, 48, 122, 148, 35, 47, 89, 220, 58, 217, 211, 26, 221, 203, 25, 151, 74, 238, 183, 12, 118, 133, 230, 227, 10, 201, 199, 22, 210, 142, 221, 164, 89, 187, 122, 243, 99, 5, 233, 195, 14, 209, 196, 92, 83, 121, 253, 226, 193, 137, 144, 102, 236, 42, 205, 223, 21, 152, 15, 42, 132, 31, 35, 72, 25, 246, 138, 198, 231, 18, 202, 141, 151, 37, 174, 155, 60, 107, 81, 239, 124, 76, 33, 245, 216, 71, 26, 178, 139, 53, 167, 87, 58, 190, 147, 48, 109, 212, 45, 159, 93, 168, 57, 190, 146, 240, 109, 132, 45, 163, 93, 185, 249, 178, 194, 245, 145, 135, 44, 98, 157, 233, 169, 142, 254, 228, 64, 75, 112, 55, 100, 22, 171, 78, 255, 116, 64, 39, 112, 26, 164, 11, 59, 71, 83, 114, 189, 229, 177, 139, 52, 103, 87, 106, 190, 175, 48, 124, 20, 33, 207, 88, 84, 58, 191, 83, 48, 61, 212, 17, 159, 76, 104, 53, 238, 151, 12, 110, 133, 236, 99, 13, 233, 197, 142, 211, 36, 93, 219, 121, 155, 98, 235, 105, 143, 110, 228, 44, 75, 93, 247, 121, 134, 162, 226, 249, 137, 130, 230, 225, 138, 200, 103, 22, 170, 142, 255, 36, 64, 27, 112, 11, 100, 7, 107, 66, 175, 113, 188, 36, 113, 219, 100, 91, 107, 123, 111, 99, 108, 41, 237, 222, 205, 152, 85, 170, 191, 63, 48, 16, 20, 12, 15, 69, 196, 51, 19, 85, 205, 255, 21, 128, 15, 32, 4, 24, 3, 74, 129, 247, 32, 70, 152, 50, 234, 149, 143, 47, 36, 28, 27, 73, 203, 118, 215, 102, 222, 170, 216, 127, 26, 160, 11, 56, 7, 82, 130, 189, 161, 177, 184, 116, 114, 167, 101, 186, 171, 51, 63, 85, 208, 63, 28, 16, 9, 204, 6, 213, 194, 223, 17, 152, 12, 106, 133, 239, 35, 12, 25, 197, 202, 211, 23, 29, 206, 137, 148, 102, 239, 106, 204, 47, 21, 220, 15, 25, 196, 10, 211, 71, 29, 242, 137, 133, 166, 227, 58, 201, 211, 22, 221, 206, 217, 148, 90, 239, 123, 12, 35, 69, 217, 243, 26, 197, 203, 19, 23, 77, 206, 181, 148, 119, 47, 102, 156, 42, 233, 223, 14, 216, 4, 90, 131, 123, 33, 227, 88, 73, 250, 182, 195, 54, 209, 214, 220, 94, 217, 248, 90, 194, 187, 17, 179, 76, 117, 245, 231, 7, 10, 130, 135, 33, 162, 152, 121, 170, 162, 255, 57, 128, 18, 224, 13, 136, 5, 166, 131, 58, 225, 211, 8, 93, 198, 185, 146, 242, 237, 133, 141, 163, 37, 185, 219, 50, 219, 85, 155, 127, 43, 96, 31, 104, 8, 46, 134, 156, 98, 233, 233, 142, 206, 228, 84, 75, 127, 119, 96, 38, 168, 26, 254, 139, 0, 103, 64, 42, 176, 31, 52, 8, 23, 70, 142, 178, 228, 117, 139, 103, 39, 106, 154, 175, 43, 60, 31, 81, 200, 60, 86, 145, 254, 236, 64, 77, 240, 53, 132, 23, 35, 78, 153, 244, 106, 199, 111, 18, 172, 13, 189, 197, 177, 147, 52, 109, 215, 109, 158, 173, 168, 125, 190, 161, 176, 120, 116, 34, 167, 89, 186, 186, 243, 51, 5, 213, 195, 31, 17, 200, 12, 86, 133, 254, 227, 0, 73, 192, 54, 208, 22, 220, 14, 217, 196, 90, 211, 123, 29, 227, 73, 137, 246, 230, 198, 202, 210, 215, 29, 158, 137, 168, 102, 254, 170, 192, 127, 16, 32, 12, 24, 5, 202, 131, 23, 33, 206, 152, 84, 106, 191, 111, 48, 44, 20, 29, 207, 73, 148, 54, 239, 86, 204, 62, 213, 208, 95, 28, 56, 9, 210, 134, 221, 162, 217, 185, 154, 242, 235, 5, 143, 67, 36, 49, 219, 84, 91, 127, 123, 96, 35, 104, 25, 238, 138, 204, 103, 21, 234, 143, 15, 36, 4, 27, 67, 75, 113, 247, 100, 70, 171, 114, 255, 101, 128, 43, 32, 31, 88, 8, 58, 134, 147, 34, 237, 217, 141, 154, 229, 171, 11, 63, 71, 80, 50, 188, 21, 177, 207, 52, 84, 23, 127, 78, 160, 52, 120, 23, 98, 142, 169, 164, 126, 251, 96, 67, 104, 49, 238, 148, 76, 111, 117, 236, 39, 13, 218, 133, 155, 35, 43, 89, 223, 122, 216, 35, 26, 153, 203, 42, 215, 95, 30, 184, 8, 114, 134, 165, 162, 251, 57, 131, 82, 225, 253, 136, 65, 166, 176, 122, 244, 35, 7, 89, 194, 186, 209, 179, 28, 117, 201, 231, 22, 202, 142, 215, 36, 94, 155, 120, 107, 98, 175, 105, 188, 46, 241, 220, 68, 89, 243, 122, 197, 227, 19, 9, 205, 198, 213, 146, 223, 45, 152, 29, 170, 137, 191, 38, 240, 26, 196, 11, 19, 71, 77, 242, 181, 133, 183, 35, 54, 153, 214, 234, 222, 207, 24, 84, 10, 191, 71, 48, 50, 148, 21, 175, 79, 60, 52, 17, 215, 76, 94, 181, 248, 119, 2, 166, 129, 186, 224, 115, 8, 37, 198, 155, 18, 235, 77, 143, 117, 164, 39, 59, 90, 147, 123, 45, 227, 93, 137, 249, 166, 194, 250, 209, 131, 28, 97, 201, 232, 86, 206, 190, 212, 112, 95, 100, 56, 43, 82, 159, 125, 168, 33, 190, 152, 112, 106, 164, 47, 59, 92, 19, 121, 205, 226, 213, 137, 159, 38, 232, 26, 206, 139, 20, 103, 79, 106, 180, 47, 55, 92, 22, 185, 206, 242, 212, 69, 159, 115, 40, 37, 222, 155, 24, 107, 74, 175, 119, 60, 38, 145, 218, 236, 91, 13, 251, 69, 131, 115, 33, 229, 216, 75, 26, 183, 75, 54, 183, 86, 246, 190, 198, 240, 82, 196, 61, 147, 81, 173, 252, 125, 129, 225, 160, 72, 120, 54, 162, 150, 249, 174, 194, 252, 81, 129, 252, 96, 65, 232, 48, 78, 148, 52, 111, 87, 108, 62, 173, 208, 125, 156, 33, 169, 216, 126, 218, 160, 91, 56, 59, 82, 147, 125, 173, 225, 189, 136, 113, 166, 164, 122, 251, 99, 3, 105, 193, 238, 208, 76, 92, 53, 249, 215, 2, 222, 129, 152, 96, 106, 168, 47, 62, 156, 16, 105, 204, 46, 213, 220, 95, 25, 248, 10, 194, 135, 17, 162, 140, 121, 165, 226, 251, 9, 131, 70, 225, 242, 200, 69, 150, 179, 46, 245, 220, 71, 25, 242, 138, 197, 167, 19, 58, 141, 211, 37, 157, 219, 41, 155, 94, 235, 120, 79, 98, 180, 41, 183, 94, 246, 184, 70, 242, 178, 197, 181, 147, 55, 45, 214, 157, 158, 233, 168, 78, 254, 180, 64, 119, 112, 38, 164, 26, 251, 75, 3, 119, 65, 230, 176, 74, 244, 55, 7, 86, 130, 190, 225, 176, 72, 116, 54, 167, 86, 250, 190, 195, 48, 81, 212, 60, 95, 81, 248, 60, 66, 145, 241, 172, 68, 125, 243, 97, 133, 232, 99, 14, 169, 196, 126, 211, 96, 93, 232, 57, 142, 146, 228, 109, 139, 109, 167, 109, 186, 173, 179, 61, 181, 209, 183, 28, 118, 137, 230, 230, 202, 202, 215, 23, 30, 142, 136, 100, 102, 171, 106, 255, 111, 0, 44, 0, 29, 192, 9, 144, 6, 236, 2, 205, 193, 149, 144, 111, 44, 44, 29, 221, 201, 153, 150, 234, 238, 207, 12, 84, 5, 255, 67, 0, 49, 192, 20, 80, 15, 124, 4, 33, 195, 88, 81, 250, 188, 67, 49, 241, 212, 68, 95, 115, 120, 37, 226, 155, 9, 171, 70, 255, 114, 192, 37, 144, 27, 44, 11, 93, 199, 121, 146, 162, 237, 185, 141, 178, 229, 181, 139, 55, 39, 86, 154, 190, 235, 48, 79, 84, 52, 63, 87, 80, 62, 188, 16, 113, 204, 36, 85, 219, 127, 27, 96, 11, 104, 7, 110, 130, 172, 97, 189, 232, 113, 142, 164, 100, 123, 107, 99, 111, 105, 236, 46, 205, 220, 85, 153, 255, 42, 192, 31, 16, 8, 12, 6, 133, 194, 227, 17, 137, 204, 102, 213, 234, 223, 15, 24, 4, 10, 131, 71, 33, 242, 152, 69, 170, 179, 63, 53, 208, 23, 28, 14, 137, 196, 102, 211, 106, 221, 239, 25, 140, 10, 229, 199, 11, 18, 135, 77, 162, 181, 185, 183, 50, 246, 149, 134, 239, 34, 204, 25, 149, 202, 239, 23, 12, 14, 133, 196, 99, 19, 105, 205, 238, 213, 140, 95, 37, 248, 27, 2, 139, 65, 167, 112, 122, 164, 35, 59, 89, 211, 122, 221, 227, 25, 137, 202, 230, 215, 10, 222, 135, 24, 98, 138, 169, 167, 62, 250, 144, 67, 44, 49, 221, 212, 89, 159, 122, 232, 35, 14, 153, 196, 106, 211, 111, 29, 236, 9, 141, 198, 229, 146, 203, 45, 151, 93, 174, 185, 188, 114, 241, 229, 132, 75, 35, 119, 89, 230, 186, 202, 243, 23, 5, 206, 131, 20, 97, 207, 104, 84, 46, 191, 92, 112, 57, 228, 18, 203, 77, 151, 117, 174, 167, 60, 122, 145, 227, 44, 73, 221, 246, 217, 134, 218, 226, 219, 9, 155, 70, 235, 114, 207, 101, 148, 43, 47, 95, 92, 56, 57, 210, 146, 221, 173, 153, 189, 170, 241, 191, 4, 112, 3, 100, 1, 235, 64, 79, 112, 52, 36, 23, 91, 78, 187, 116, 115, 103, 101, 234, 171, 15, 63, 68, 16, 51, 76, 21, 245, 207, 7, 20, 2, 143, 65, 164, 48, 123, 84, 35, 127, 89, 224, 58, 200, 19, 22, 141, 206, 229, 148, 75, 47, 119, 92, 38, 185, 218, 242, 219, 5, 155, 67, 43, 113, 223, 100, 88, 43, 122, 159, 99, 40, 41, 222, 158, 216, 104, 90, 174, 187, 60, 115, 81, 229, 252, 75, 1, 247, 64, 70, 176, 50, 244, 21, 135, 79, 34, 180, 25, 183, 74, 246, 183, 6, 246, 130, 198, 225, 146, 200, 109, 150, 173, 174, 253, 188, 65, 177, 240, 116, 68, 39, 115, 90, 165, 251, 59, 3, 83, 65, 253, 240, 65, 132, 48, 99, 84, 41, 255, 94, 192, 56, 80, 18, 188, 13, 177, 197, 180, 83, 55, 125, 214, 161, 158, 248, 104, 66, 174, 177, 188, 116, 113, 231, 100, 74, 171, 119, 63, 102, 144, 42, 236, 31, 13, 200, 5, 150, 131, 46, 225, 220, 72, 89, 246, 186, 198, 243, 18, 197, 205, 147, 21, 173, 207, 61, 148, 17, 175, 76, 124, 53, 225, 215, 8, 94, 134, 184, 98, 242, 169, 133, 190, 227, 48, 73, 212, 54, 223, 86, 216, 62, 218, 144, 91, 44, 59, 93, 211, 121, 157, 226, 233, 137, 142, 230, 228, 74, 203, 119, 23, 102, 142, 170, 228, 127, 11, 96, 7, 104, 2, 174, 129, 188, 96, 113, 232, 36, 78, 155, 116, 107, 103, 111, 106, 172, 47, 61, 220, 17, 153, 204, 106, 213, 239, 31, 12, 8, 5, 198, 131, 18, 225, 205, 136, 85, 166, 191, 58, 240, 19, 4, 13, 195, 69, 145, 243, 44, 69, 221, 243, 25, 133, 202, 227, 23, 9, 206, 134, 212, 98, 223, 105, 152, 46, 234, 156, 79, 41, 244, 30, 199, 72, 82, 182, 189, 182, 241, 182, 196, 118, 211, 102, 221, 234, 217, 143, 26, 228, 11, 11, 71, 71, 114, 178, 165, 181, 187, 55, 51, 86, 149, 254, 239, 0, 76, 0, 53, 192, 23, 16, 14, 140, 4, 101, 195, 107, 17, 239, 76, 76, 53, 245, 215, 7, 30, 130, 136, 97, 166, 168, 122, 254, 163, 0, 121, 192, 34, 208, 25, 156, 10, 233, 199, 14, 210, 132, 93, 163, 121, 185, 226, 242, 201, 133, 150, 227, 46, 201, 220, 86, 217, 254, 218, 192, 91, 16, 59, 76, 19, 117, 205, 231, 21, 138, 143, 39, 36, 26, 155, 75, 43, 119, 95, 102, 184, 42, 242, 159, 5, 168, 3, 62, 129, 208, 96, 92, 40, 57, 222, 146, 216, 109, 154, 173, 171, 61, 191, 81, 176, 60, 116, 17, 231, 76, 74, 181, 247, 55, 6, 150, 130, 238, 225, 140, 72, 101, 246, 171, 6, 255, 66, 192, 49, 144, 20, 108, 15, 109, 196, 45, 147, 93, 173, 249, 189, 130, 241, 161, 132, 120, 99, 98, 169, 233, 190, 206, 240, 84, 68, 63, 115, 80, 37, 252, 27, 1, 203, 64, 87, 112, 62, 164, 16, 123, 76, 35, 117, 217, 231, 26, 202, 139, 23, 39, 78, 154, 180, 107, 55, 111, 86, 172, 62, 253, 208, 65, 156, 48, 105, 212, 46, 223, 92, 88, 57, 250, 146, 195, 45, 145, 221, 172, 89, 189, 250, 241, 131, 4, 97, 195, 104, 81, 238, 188, 76, 113, 245, 228, 71, 11, 114, 135, 101, 162, 171, 57, 191, 82, 240, 61, 132, 17, 163, 76, 121, 245, 226, 199, 9, 146, 134, 237, 162, 205, 185, 149, 178, 239, 53, 140, 23, 37, 206, 155, 20, 107, 79, 111, 116, 44, 39, 93, 218, 185, 155, 50, 235, 85, 143, 127, 36, 32, 27, 88, 11, 122, 135, 99, 34, 169, 217, 190, 218, 240, 91, 4, 59, 67, 83, 113, 253, 228, 65, 139, 112, 103, 100, 42, 171, 95, 63, 120, 16, 34, 140, 25, 165, 202, 251, 23, 3, 78, 129, 244, 96, 71, 104, 50, 174, 149, 188, 111, 49, 236, 20, 77, 207, 117, 148, 39, 47, 90, 156, 59, 41, 211, 94, 221, 248, 89, 130, 186, 225, 179, 8, 117, 198, 167, 18, 250, 141, 131, 37, 161, 219, 56, 91, 82, 187, 125, 179, 97, 181, 232, 119, 14, 166, 132, 122, 227, 99, 9, 233, 198, 206, 210, 212, 93, 159, 121, 168, 34, 254, 153, 128, 106, 224, 47, 8, 28, 6, 137, 194, 230, 209, 138, 220, 103, 25, 234, 138, 207, 39, 20, 26, 143, 75, 36, 55, 91, 86, 187, 126, 243, 96, 69, 232, 51, 14, 149, 196, 111, 19, 108, 13, 237, 197, 141, 147, 37, 173, 219, 61, 155, 81, 171, 124, 127, 97, 224, 40, 72, 30, 182, 136, 118, 230, 166, 202, 250, 215, 3, 30, 129, 200, 96, 86, 168, 62, 254, 144, 64, 108, 48, 45, 212, 29, 159, 73, 168, 54, 254, 150, 192, 110, 208, 44, 92, 29, 249, 201, 130, 214, 225, 158, 200, 104, 86, 174, 190, 252, 112, 65, 228, 48, 75, 84, 55, 127, 86, 160, 62, 248, 16, 66, 140, 49, 165, 212, 123, 31, 99, 72, 41, 246, 158, 198, 232, 82, 206, 189, 148, 113, 175, 100, 124, 43, 97, 223, 104, 88, 46, 186, 156, 115, 41, 229, 222, 203, 24, 87, 74, 190, 183, 48, 118, 148, 38, 239, 90, 204, 59, 21, 211, 79, 29, 244, 9, 135, 70, 226, 178, 201, 181, 150, 247, 46, 198, 156, 82, 233, 253, 142, 193, 164, 80, 123, 124, 35, 97, 217, 232, 90, 206, 187, 20, 115, 79, 101, 244, 43, 7, 95, 66, 184, 49, 178, 148, 117, 175, 103, 60, 42, 145, 223, 44, 88, 29, 250, 137, 131, 38, 225, 218, 200, 91, 22, 187, 78, 243, 116, 69, 231, 115, 10, 165, 199, 59, 18, 147, 77, 173, 245, 189, 135, 49, 162, 148, 121, 175, 98, 252, 41, 129, 222, 224, 88, 72, 58, 182, 147, 54, 237, 214, 205, 158, 213, 168, 95, 62, 184, 16, 114, 140, 37, 165, 219, 59, 27, 83, 75, 125, 247, 97, 134, 168, 98, 254, 169, 128, 126, 224, 32, 72, 24, 54, 138, 150, 231, 46, 202, 156, 87, 41, 254, 158, 192, 104, 80, 46, 188, 28, 113, 201, 228, 86, 203, 126, 215, 96, 94, 168, 56, 126, 146, 160, 109, 184, 45, 178, 157, 181, 169, 183, 62, 246, 144, 70, 236, 50, 205, 213, 149, 159, 47, 40, 28, 30, 137, 200, 102, 214, 170, 222, 255, 24, 64, 10, 176, 7, 52, 2, 151, 65, 174, 176, 124, 116, 33, 231, 88, 74, 186, 183, 51, 54, 149, 214, 239, 30, 204, 8, 85, 198, 191, 18, 240, 13, 132, 5, 163, 67, 57, 241, 210, 196, 93, 147, 121, 173, 226, 253, 137, 129, 166, 224, 122, 200, 35, 22, 153, 206, 234, 212, 79, 31, 116, 8, 39, 70, 154, 178, 235, 53, 143, 87, 36, 62, 155, 80, 107, 124, 47, 97, 220, 40, 89, 222, 186, 216, 115, 26, 165, 203, 59, 23, 83, 78, 189, 244, 113, 135, 100, 98, 171, 105, 191, 110, 240, 44, 68, 29, 243, 73, 133, 246, 227, 6, 201, 194, 214, 209, 158, 220, 104, 89, 238, 186, 204, 115, 21, 229, 207, 11, 20, 7, 79, 66, 180, 49, 183, 84, 118, 191, 102, 240, 42, 196, 31, 19, 72, 13, 246, 133, 134, 227, 34, 201, 217, 150, 218, 238, 219, 12, 91, 69, 251, 115, 3, 101, 193, 235, 16, 79, 76, 52, 53, 215, 87, 30, 190, 136, 112, 102, 164, 42, 251, 95, 3, 120, 1, 226, 128, 73, 160, 54, 248, 22, 194, 142, 209, 164, 92, 123, 121, 227, 98, 201, 233, 150, 206, 238, 212, 76, 95, 117, 248, 39, 2, 154, 129, 171, 32, 127, 88, 32, 58, 152, 19, 42, 141, 223, 37, 152, 27, 42, 139, 95, 39, 120, 26, 162, 139, 57, 167, 82, 250, 189, 131, 49, 161, 212, 120, 95, 98, 184, 41, 178, 158, 245, 168, 71, 62, 178, 144, 117, 172, 39, 61, 218, 145, 155, 44, 107, 93, 239, 121, 140, 34, 229, 217, 139, 26, 231, 75, 10, 183, 71, 54, 178, 150, 245, 174, 199, 60, 82, 145, 253, 172, 65, 189, 240, 113, 132, 36, 99, 91, 105, 251, 110, 195, 108, 81, 237, 252, 77, 129, 245, 160, 71, 56, 50, 146, 149, 173, 175, 61, 188, 17, 177, 204, 116, 85, 231, 127, 10, 160, 7, 56, 2, 146, 129, 173, 160, 125, 184, 33, 178, 152, 117, 170, 167, 63, 58, 144, 19, 44, 13, 221, 197, 153, 147, 42, 237, 223, 13, 152, 5, 170, 131, 63, 33, 208, 24, 92, 10, 185, 199, 50, 210, 149, 157, 175, 41, 188, 30, 241, 200, 68, 86, 179, 126, 245, 224, 71, 8, 50, 134, 149, 162, 239, 57, 140, 18, 229, 205, 139, 21, 167, 79, 58, 180, 19, 55, 77, 214, 181, 158, 247, 40, 70, 158, 178, 232, 117, 142, 167, 36, 122, 155, 99, 43, 105, 223, 110, 216, 44, 90, 157, 251, 41, 131, 94, 225, 248, 72, 66, 182, 177, 182, 244, 118, 199, 102, 210, 170, 221, 191, 25, 176, 10, 244, 7, 7, 66, 130, 177, 161, 180, 120, 119, 98, 166, 169, 186, 254, 243, 0, 69, 192, 51, 16, 21, 204, 15, 21, 196, 15, 19, 68, 13, 243, 69, 133, 243, 35, 5, 217, 195, 26, 209, 203, 28, 87, 73, 254, 182, 192, 118, 208, 38, 220, 26, 217, 203, 26, 215, 75, 30, 183, 72, 118, 182, 166, 246, 250, 198, 195, 18, 209, 205, 156, 85, 169, 255, 62, 192, 16, 80, 12, 60, 5, 209, 195, 28, 81, 201, 252, 86, 193, 254, 208, 64, 92, 48, 57, 212, 18, 223, 77, 152, 53, 170, 151, 63, 46, 144, 28, 108, 9, 237, 198, 205, 146, 213, 173, 159, 61, 168, 17, 190, 140, 112, 101, 228, 43, 11, 95, 71, 120, 50, 162, 149, 185, 175, 50, 252, 21, 129, 207, 32, 84, 24, 63, 74, 144, 55, 44, 22, 157, 206, 233, 148, 78, 239, 116, 76, 39, 117, 218, 167, 27, 58, 139, 83, 39, 125, 218, 161, 155, 56, 107, 82, 175, 125, 188, 33, 177, 216, 116, 90, 167, 123, 58, 163, 83, 57, 253, 210, 193, 157, 144, 105, 172, 46, 253, 220, 65, 153, 240, 106, 196, 47, 19, 92, 13, 249, 197, 130, 211, 33, 157, 216, 105, 154, 174, 235, 60, 79, 81, 244, 60, 71, 81, 242, 188, 69, 177, 243, 52, 69, 215, 115, 30, 165, 200, 123, 22, 163, 78, 249, 244, 66, 199, 113, 146, 164, 109, 187, 109, 179, 109, 181, 237, 183, 13, 182, 133, 182, 227, 54, 201, 214, 214, 222, 222, 216, 88, 90, 186, 187, 51, 51, 255, 63 ) random_mask_vec8 = numpy.array(random_mask_tuple, numpy.uint8) gnuradio-3.7.2.1/gr-digital/python/digital/qa_lfsr.py0000775000175000017500000000254112207440367022320 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, digital class test_lfsr(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_lfsr_001(self): reglen = 8 l = digital.lfsr(1, 1, reglen) result_data = [] for i in xrange(4*(reglen+1)): result_data.append(l.next_bit()) expected_result = 4*([1,] + reglen*[0,]) self.assertFloatTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_lfsr, "test_lfsr.xml") gnuradio-3.7.2.1/gr-digital/python/digital/utils/0000775000175000017500000000000012207440367021452 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/python/digital/utils/alignment.py0000664000175000017500000001153312207440367024005 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ This module contains functions for aligning sequences. >>> import random >>> rndm = random.Random() >>> rndm.seed(1234) >>> ran_seq = [rndm.randint(0,1) for i in range(0, 100)] >>> offset_seq = [0] * 20 + ran_seq >>> correct, overlap, offset = align_sequences(ran_seq, offset_seq) >>> print(correct, overlap, offset) (1.0, 100, -20) >>> offset_err_seq = [] >>> for bit in offset_seq: ... if rndm.randint(0,4) == 4: ... offset_err_seq.append(rndm.randint(0,1)) ... else: ... offset_err_seq.append(bit) >>> correct, overlap, offset = align_sequences(ran_seq, offset_err_seq) >>> print(overlap, offset) (100, -20) """ import random # DEFAULT PARAMETERS # If the fraction of matching bits between two sequences is greater than # this the sequences are assumed to be aligned. def_correct_cutoff = 0.9 # The maximum offset to test during sequence alignment. def_max_offset = 500 # The maximum number of samples to take from two sequences to check alignment. def_num_samples = 1000 def compare_sequences(d1, d2, offset, sample_indices=None): """ Takes two binary sequences and an offset and returns the number of matching entries and the number of compared entries. d1 & d2 -- sequences offset -- offset of d2 relative to d1 sample_indices -- a list of indices to use for the comparison """ max_index = min(len(d1), len(d2)+offset) if sample_indices is None: sample_indices = range(0, max_index) correct = 0 total = 0 for i in sample_indices: if i >= max_index: break if d1[i] == d2[i-offset]: correct += 1 total += 1 return (correct, total) def random_sample(size, num_samples=def_num_samples, seed=None): """ Returns a set of random integers between 0 and (size-1). The set contains no more than num_samples integers. """ rndm = random.Random() rndm.seed(seed) if num_samples > size: indices = set(range(0, size)) else: if num_samples > size/2: num_samples = num_samples/2 indices = set([]) while len(indices) < num_samples: index = rndm.randint(0, size-1) indices.add(index) indices = list(indices) indices.sort() return indices def align_sequences(d1, d2, num_samples=def_num_samples, max_offset=def_max_offset, correct_cutoff=def_correct_cutoff, seed=None, indices=None): """ Takes two sequences and finds the offset and which the two sequences best match. It returns the fraction correct, the number of entries compared, the offset. d1 & d2 -- sequences to compare num_samples -- the maximum number of entries to compare max_offset -- the maximum offset between the sequences that is checked correct_cutoff -- If the fraction of bits correct is greater than this then the offset is assumed to optimum. seed -- a random number seed indices -- an explicit list of the indices used to compare the two sequences """ max_overlap = max(len(d1), len(d2)) if indices is None: indices = random_sample(max_overlap, num_samples, seed) max_frac_correct = 0 best_offset = None best_compared = None best_correct = None pos_range = range(0, min(len(d1), max_offset)) neg_range = range(-1, -min(len(d2), max_offset), -1) # Interleave the positive and negative offsets. int_range = [item for items in zip(pos_range, neg_range) for item in items] for offset in int_range: correct, compared = compare_sequences(d1, d2, offset, indices) frac_correct = 1.0*correct/compared if frac_correct > max_frac_correct: max_frac_correct = frac_correct best_offset = offset best_compared = compared best_correct = correct if frac_correct > correct_cutoff: break return max_frac_correct, best_compared, best_offset, indices if __name__ == "__main__": import doctest doctest.testmod() gnuradio-3.7.2.1/gr-digital/python/digital/utils/mod_codes.py0000664000175000017500000000212712207440367023762 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # Constants used to represent what coding to use. GRAY_CODE = 'gray' SET_PARTITION_CODE = 'set-partition' NO_CODE = 'none' codes = (GRAY_CODE, SET_PARTITION_CODE, NO_CODE) def invert_code(code): c = enumerate(code) ic = [(b, a) for (a, b) in c] ic.sort() return [a for (b, a) in ic] gnuradio-3.7.2.1/gr-digital/python/digital/utils/gray_code.py0000664000175000017500000000416312207440367023764 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # class GrayCodeGenerator(object): """ Generates and caches gray codes. """ def __init__(self): self.gcs = [0, 1] # The last power of two passed through. self.lp2 = 2 # The next power of two that will be passed through. self.np2 = 4 # Curent index self.i = 2 def get_gray_code(self, length): """ Returns a list of gray code of given length. """ if len(self.gcs) < length: self.generate_new_gray_code(length) return self.gcs[:length] def generate_new_gray_code(self, length): """ Generates new gray code and places into cache. """ while len(self.gcs) < length: if self.i == self.lp2: # if i is a power of two then gray number is of form 1100000... result = self.i + self.i/2 else: # if not we take advantage of the symmetry of all but the last bit # around a power of two. result = self.gcs[2*self.lp2-1-self.i] + self.lp2 self.gcs.append(result) self.i += 1 if self.i == self.np2: self.lp2 = self.i self.np2 = self.i*2 _gray_code_generator = GrayCodeGenerator() gray_code = _gray_code_generator.get_gray_code gnuradio-3.7.2.1/gr-digital/python/digital/utils/tagged_streams.py0000664000175000017500000001074312207440367025022 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import pmt def make_lengthtags(lengths, offsets, tagname='length', vlen=1): tags = [] assert(len(offsets) == len(lengths)) for offset, length in zip(offsets, lengths): tag = gr.tag_t() tag.offset = offset/vlen tag.key = pmt.string_to_symbol(tagname) tag.value = pmt.from_long(length/vlen) tags.append(tag) return tags def string_to_vector(string): v = [] for s in string: v.append(ord(s)) return v def strings_to_vectors(strings, lengthtagname): vs = [string_to_vector(string) for string in strings] return packets_to_vectors(vs, lengthtagname) def vector_to_string(v): s = [] for d in v: s.append(chr(d)) return ''.join(s) def vectors_to_strings(data, tags, lengthtagname): packets = vectors_to_packets(data, tags, lengthtagname) return [vector_to_string(packet) for packet in packets] def count_bursts(data, tags, lengthtagname, vlen=1): lengthtags = [t for t in tags if pmt.symbol_to_string(t.key) == lengthtagname] lengths = {} for tag in lengthtags: if tag.offset in lengths: raise ValueError( "More than one tags with key {0} with the same offset={1}." .format(lengthtagname, tag.offset)) lengths[tag.offset] = pmt.to_long(tag.value)*vlen in_burst = False in_packet = False packet_length = None packet_pos = None burst_count = 0 for pos in range(len(data)): if pos in lengths: if in_packet: print("Got tag at pos {0} current packet_pos is {1}".format(pos, packet_pos)) raise StandardError("Received packet tag while in packet.") packet_pos = -1 packet_length = lengths[pos] in_packet = True if not in_burst: burst_count += 1 in_burst = True elif not in_packet: in_burst = False if in_packet: packet_pos += 1 if packet_pos == packet_length-1: in_packet = False packet_pos = None return burst_count def vectors_to_packets(data, tags, lengthtagname, vlen=1): lengthtags = [t for t in tags if pmt.symbol_to_string(t.key) == lengthtagname] lengths = {} for tag in lengthtags: if tag.offset in lengths: raise ValueError( "More than one tags with key {0} with the same offset={1}." .format(lengthtagname, tag.offset)) lengths[tag.offset] = pmt.to_long(tag.value)*vlen if 0 not in lengths: raise ValueError("There is no tag with key {0} and an offset of 0" .format(lengthtagname)) pos = 0 packets = [] while pos < len(data): if pos not in lengths: raise ValueError("There is no tag with key {0} and an offset of {1}." "We were expecting one." .format(lengthtagname, pos)) length = lengths[pos] if length == 0: raise ValueError("Packets cannot have zero length.") if pos+length > len(data): raise ValueError("The final packet is incomplete.") packets.append(data[pos: pos+length]) pos += length return packets def packets_to_vectors(packets, lengthtagname, vlen=1): tags = [] data = [] offset = 0 for packet in packets: data.extend(packet) tag = gr.tag_t() tag.offset = offset/vlen tag.key = pmt.string_to_symbol(lengthtagname) tag.value = pmt.from_long(len(packet)/vlen) tags.append(tag) offset = offset + len(packet) return data, tags gnuradio-3.7.2.1/gr-digital/python/digital/utils/__init__.py0000664000175000017500000000145112207440367023564 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # gnuradio-3.7.2.1/gr-digital/python/digital/qa_diff_encoder.py0000775000175000017500000000603312207440367023761 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random from gnuradio import gr, gr_unittest, digital, blocks def make_random_int_tuple(L, min, max): result = [] for x in range(L): result.append(random.randint(min, max)) return tuple(result) class test_diff_encoder(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_diff_encdec_000(self): random.seed(0) modulus = 2 src_data = make_random_int_tuple(1000, 0, modulus-1) expected_result = src_data src = blocks.vector_source_b(src_data) enc = digital.diff_encoder_bb(modulus) dec = digital.diff_decoder_bb(modulus) dst = blocks.vector_sink_b() self.tb.connect(src, enc, dec, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink self.assertEqual(expected_result, actual_result) def test_diff_encdec_001(self): random.seed(0) modulus = 4 src_data = make_random_int_tuple(1000, 0, modulus-1) expected_result = src_data src = blocks.vector_source_b(src_data) enc = digital.diff_encoder_bb(modulus) dec = digital.diff_decoder_bb(modulus) dst = blocks.vector_sink_b() self.tb.connect(src, enc, dec, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink self.assertEqual(expected_result, actual_result) def test_diff_encdec_002(self): random.seed(0) modulus = 8 src_data = make_random_int_tuple(40000, 0, modulus-1) expected_result = src_data src = blocks.vector_source_b(src_data) enc = digital.diff_encoder_bb(modulus) dec = digital.diff_decoder_bb(modulus) dst = blocks.vector_sink_b() self.tb.connect(src, enc, dec, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink self.assertEqual(expected_result, actual_result) if __name__ == '__main__': gr_unittest.run(test_diff_encoder, "test_diff_encoder.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_constellation_receiver.py0000775000175000017500000002006112237515112026103 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import math import pmt from gnuradio import gr, gr_unittest, filter, analog, blocks, digital from gnuradio.digital.utils import mod_codes, alignment from gnuradio.digital import packet_utils from gnuradio.digital.generic_mod_demod import generic_mod, generic_demod from qa_constellation import tested_constellations, twod_constell # Set a seed so that if errors turn up they are reproducible. SEED = 1239 # TESTING PARAMETERS # The number of symbols to test with. # We need this many to let the frequency recovery block converge. DATA_LENGTH = 1000 # Test fails if fraction of output that is correct is less than this. EASY_REQ_CORRECT = 0.9 # For constellations that aren't expected to work so well. MEDIUM_REQ_CORRECT = 0.8 # CHANNEL PARAMETERS NOISE_VOLTAGE = 0.01 FREQUENCY_OFFSET = 0.01 TIMING_OFFSET = 1.0 # RECEIVER PARAMETERS FREQ_BW = 2*math.pi/100.0 PHASE_BW = 2*math.pi/100.0 class channel_model(gr.hier_block2): def __init__(self, noise_voltage, freq, timing): gr.hier_block2.__init__(self, "channel_model", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_gr_complex)) timing_offset = filter.fractional_resampler_cc(0, timing) noise_adder = blocks.add_cc() noise = analog.noise_source_c(analog.GR_GAUSSIAN, noise_voltage, 0) freq_offset = analog.sig_source_c(1, analog.GR_SIN_WAVE, freq, 1.0, 0.0) mixer_offset = blocks.multiply_cc(); self.connect(self, timing_offset) self.connect(timing_offset, (mixer_offset,0)) self.connect(freq_offset, (mixer_offset,1)) self.connect(mixer_offset, (noise_adder,1)) self.connect(noise, (noise_adder,0)) self.connect(noise_adder, self) class test_constellation_receiver(gr_unittest.TestCase): # We ignore the first half of the output data since often it takes # a while for the receiver to lock on. ignore_fraction = 0.8 max_data_length = DATA_LENGTH * 6 max_num_samples = 1000 def test_basic(self): """ Tests a bunch of different constellations by using generic modulation, a channel, and generic demodulation. The generic demodulation uses constellation_receiver which is what we're really trying to test. """ rndm = random.Random() rndm.seed(SEED) # Assumes not more than 64 points in a constellation # Generates some random input data to use. self.src_data = tuple( [rndm.randint(0,1) for i in range(0, self.max_data_length)]) # Generates some random indices to use for comparing input and # output data (a full comparison is too slow in python). self.indices = alignment.random_sample( self.max_data_length, self.max_num_samples, SEED) requirements = ( (EASY_REQ_CORRECT, tested_constellations(easy=True, medium=False, difficult=False)), (MEDIUM_REQ_CORRECT, tested_constellations(easy=False, medium=True, difficult=False)), ) for req_correct, tcs in requirements: for constellation, differential in tcs: # The constellation_receiver doesn't work for constellations # of multple dimensions (i.e. multiple complex numbers to a # single symbol). # That is not implemented since the receiver has no way of # knowing where the beginning of a symbol is. # It also doesn't work for non-differential modulation. if constellation.dimensionality() != 1 or not differential: continue data_length = DATA_LENGTH * constellation.bits_per_symbol() tb = rec_test_tb(constellation, differential, src_data=self.src_data[:data_length]) tb.run() data = tb.dst.data() d1 = tb.src_data[:int(len(tb.src_data)*self.ignore_fraction)] d2 = data[:int(len(data)*self.ignore_fraction)] correct, overlap, offset, indices = alignment.align_sequences( d1, d2, indices=self.indices) if correct <= req_correct: print("Constellation is {0}. Differential is {1}. Required correct is {2}. Correct is {3}. FAIL.". format(constellation, differential, req_correct, correct)) self.assertTrue(correct > req_correct) def test_tag(self): # Send data through bpsk receiver # followed by qpsk receiver data = [0.9+0j, 0.1+0.9j, -1-0.1j, -0.1-0.6j]*2 bpsk_data = [1, 1, 0, 0] qpsk_data = [1, 3, 0, 0] first_tag = gr.tag_t() first_tag.key = pmt.intern("set_constellation") first_tag.value = digital.bpsk_constellation().as_pmt() first_tag.offset = 0 second_tag = gr.tag_t() second_tag.key = pmt.intern("set_constellation") second_tag.value = digital.qpsk_constellation().as_pmt() second_tag.offset = 4 src = blocks.vector_source_c(data, False, 1, [first_tag, second_tag]) decoder = digital.constellation_receiver_cb( digital.bpsk_constellation().base(), 0, 0, 0) snk = blocks.vector_sink_b() tb = gr.top_block() tb.connect(src, decoder, snk) tb.run() self.assertEqual(list(snk.data()), bpsk_data+qpsk_data) class rec_test_tb(gr.top_block): """ Takes a constellation an runs a generic modulation, channel, and generic demodulation. """ def __init__(self, constellation, differential, data_length=None, src_data=None, freq_offset=True): """ Args: constellation: a constellation object differential: whether differential encoding is used data_length: the number of bits of data to use src_data: a list of the bits to use freq_offset: whether to use a frequency offset in the channel """ super(rec_test_tb, self).__init__() # Transmission Blocks if src_data is None: self.src_data = tuple([rndm.randint(0,1) for i in range(0, data_length)]) else: self.src_data = src_data packer = blocks.unpacked_to_packed_bb(1, gr.GR_MSB_FIRST) src = blocks.vector_source_b(self.src_data) mod = generic_mod(constellation, differential=differential) # Channel if freq_offset: channel = channel_model(NOISE_VOLTAGE, FREQUENCY_OFFSET, TIMING_OFFSET) else: channel = channel_model(NOISE_VOLTAGE, 0, TIMING_OFFSET) # Receiver Blocks if freq_offset: demod = generic_demod(constellation, differential=differential, freq_bw=FREQ_BW, phase_bw=PHASE_BW) else: demod = generic_demod(constellation, differential=differential, freq_bw=0, phase_bw=0) self.dst = blocks.vector_sink_b() self.connect(src, packer, mod, channel, demod, self.dst) if __name__ == '__main__': gr_unittest.run(test_constellation_receiver, "test_constellation_receiver.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_glfsr_source.py0000775000175000017500000000671312207440367024054 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_glfsr_source(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000_make_b(self): src = digital.glfsr_source_b(16) self.assertEquals(src.mask(), 0x8016) self.assertEquals(src.period(), 2**16-1) def test_001_degree_b(self): self.assertRaises(RuntimeError, lambda: digital.glfsr_source_b(0)) self.assertRaises(RuntimeError, lambda: digital.glfsr_source_b(33)) def test_002_correlation_b(self): for degree in range(1,11): # Higher degrees take too long to correlate src = digital.glfsr_source_b(degree, False) b2f = digital.chunks_to_symbols_bf((-1.0,1.0), 1) dst = blocks.vector_sink_f() del self.tb # Discard existing top block self.tb = gr.top_block() self.tb.connect(src, b2f, dst) self.tb.run() self.tb.disconnect_all() actual_result = dst.data() R = auto_correlate(actual_result) self.assertEqual(R[0], float(len(R))) # Auto-correlation peak at origin for i in range(len(R)-1): self.assertEqual(R[i+1], -1.0) # Auto-correlation minimum everywhere else def test_003_make_f(self): src = digital.glfsr_source_f(16) self.assertEquals(src.mask(), 0x8016) self.assertEquals(src.period(), 2**16-1) def test_004_degree_f(self): self.assertRaises(RuntimeError, lambda: digital.glfsr_source_f(0)) self.assertRaises(RuntimeError, lambda: digital.glfsr_source_f(33)) def test_005_correlation_f(self): for degree in range(1,11): # Higher degrees take too long to correlate src = digital.glfsr_source_f(degree, False) dst = blocks.vector_sink_f() del self.tb # Discard existing top block self.tb = gr.top_block() self.tb.connect(src, dst) self.tb.run() actual_result = dst.data() R = auto_correlate(actual_result) self.assertEqual(R[0], float(len(R))) # Auto-correlation peak at origin for i in range(len(R)-1): self.assertEqual(R[i+1], -1.0) # Auto-correlation minimum everywhere else def auto_correlate(data): l = len(data) R = [0,]*l for lag in range(l): for i in range(l): R[lag] += data[i]*data[i-lag] return R if __name__ == '__main__': gr_unittest.run(test_glfsr_source, "test_glfsr_source.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_scrambler.py0000775000175000017500000001012312237515112023311 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks import pmt class test_scrambler(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_scrambler_descrambler(self): src_data = (1,)*1000 src = blocks.vector_source_b(src_data, False) scrambler = digital.scrambler_bb(0x8a, 0x7F, 7) # CCSDS 7-bit scrambler descrambler = digital.descrambler_bb(0x8a, 0x7F, 7) dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler, dst) self.tb.run() self.assertEqual(tuple(src_data[:-8]), dst.data()[8:]) # skip garbage during synchronization def test_additive_scrambler(self): src_data = (1,)*1000 src = blocks.vector_source_b(src_data, False) scrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7) descrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7) dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler, dst) self.tb.run() self.assertEqual(src_data, dst.data()) def test_additive_scrambler_reset(self): src_data = (1,)*1000 src = blocks.vector_source_b(src_data, False) scrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100) descrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100) dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler, dst) self.tb.run() self.assertEqual(src_data, dst.data()) def test_additive_scrambler_reset_3bpb(self): src_data = (5,)*2000 src = blocks.vector_source_b(src_data, False) scrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100, 3) descrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100, 3) dst = blocks.vector_sink_b() dst2 = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler, dst) self.tb.connect(scrambler, dst2) self.tb.run() if not (src_data == dst.data()): self.fail('Not equal.') self.assertEqual(src_data, src_data) def test_additive_scrambler_tags(self): src_data = (1,)*1000 src = blocks.vector_source_b(src_data, False) scrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100) descrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100) reset_tag_key = 'reset_lfsr' reset_tag1 = gr.tag_t() reset_tag1.key = pmt.string_to_symbol(reset_tag_key) reset_tag1.offset = 17 reset_tag2 = gr.tag_t() reset_tag2.key = pmt.string_to_symbol(reset_tag_key) reset_tag2.offset = 110 reset_tag3 = gr.tag_t() reset_tag3.key = pmt.string_to_symbol(reset_tag_key) reset_tag3.offset = 523 src = blocks.vector_source_b(src_data, False, 1, (reset_tag1, reset_tag2, reset_tag3)) scrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100, 1, reset_tag_key) descrambler = digital.additive_scrambler_bb(0x8a, 0x7f, 7, 100, 1, reset_tag_key) dst = blocks.vector_sink_b() self.tb.connect(src, scrambler, descrambler, dst) self.tb.run() self.assertEqual(src_data, dst.data()) if __name__ == '__main__': gr_unittest.run(test_scrambler, "test_scrambler.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_cma_equalizer.py0000775000175000017500000000316612207440367024177 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_cma_equalizer_fir(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def transform(self, src_data): SRC = blocks.vector_source_c(src_data, False) EQU = digital.cma_equalizer_cc(4, 1.0, .001, 1) DST = blocks.vector_sink_c() self.tb.connect(SRC, EQU, DST) self.tb.run() return DST.data() def test_001_identity(self): # Constant modulus signal so no adjustments src_data = (1+0j, 0+1j, -1+0j, 0-1j)*1000 expected_data = src_data result = self.transform(src_data) N = -500 self.assertComplexTuplesAlmostEqual(expected_data[N:], result[N:]) if __name__ == "__main__": gr_unittest.run(test_cma_equalizer_fir, "test_cma_equalizer_fir.xml") gnuradio-3.7.2.1/gr-digital/python/digital/ofdm_txrx.py0000664000175000017500000005066712237515112022706 0ustar jcorganjcorgan# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ OFDM Transmitter / Receiver hier blocks. For simple configurations, no need to connect all the relevant OFDM blocks to form an OFDM Tx/Rx--simply use these. """ # Reminder: All frequency-domain stuff is in shifted form, i.e. DC carrier # in the middle! import numpy from gnuradio import gr import digital_swig as digital from utils import tagged_streams try: # This will work when feature #505 is added. from gnuradio import fft from gnuradio import blocks from gnuradio import analog except ImportError: # Until then this will work. import fft_swig as fft import blocks_swig as blocks import analog_swig as analog _def_fft_len = 64 _def_cp_len = 16 _def_frame_length_tag_key = "frame_length" _def_packet_length_tag_key = "packet_length" _def_packet_num_tag_key = "packet_num" # Data and pilot carriers are same as in 802.11a _def_occupied_carriers = (range(-26, -21) + range(-20, -7) + range(-6, 0) + range(1, 7) + range(8, 21) + range(22, 27),) _def_pilot_carriers=((-21, -7, 7, 21,),) _pilot_sym_scramble_seq = ( 1,1,1,1, -1,-1,-1,1, -1,-1,-1,-1, 1,1,-1,1, -1,-1,1,1, -1,1,1,-1, 1,1,1,1, 1,1,-1,1, 1,1,-1,1, 1,-1,-1,1, 1,1,-1,1, -1,-1,-1,1, -1,1,-1,-1, 1,-1,-1,1, 1,1,1,1, -1,-1,1,1, -1,-1,1,-1, 1,-1,1,1, -1,-1,-1,1, 1,-1,-1,-1, -1,1,-1,-1, 1,-1,1,1, 1,1,-1,1, -1,1,-1,1, -1,-1,-1,-1, -1,1,-1,1, 1,-1,1,-1, 1,1,1,-1, -1,1,-1,-1, -1,1,1,1, -1,-1,-1,-1, -1,-1,-1 ) _def_pilot_symbols= tuple([(x, x, x, -x) for x in _pilot_sym_scramble_seq]) _seq_seed = 42 def _get_active_carriers(fft_len, occupied_carriers, pilot_carriers): """ Returns a list of all carriers that at some point carry data or pilots. """ active_carriers = list() for carrier in list(occupied_carriers[0]) + list(pilot_carriers[0]): if carrier < 0: carrier += fft_len active_carriers.append(carrier) return active_carriers def _make_sync_word1(fft_len, occupied_carriers, pilot_carriers): """ Creates a random sync sequence for fine frequency offset and timing estimation. This is the first of typically two sync preamble symbols for the Schmidl & Cox sync algorithm. The relevant feature of this symbols is that every second sub-carrier is zero. In the time domain, this results in two identical halves of the OFDM symbols. Symbols are always BPSK symbols. Carriers are scaled by sqrt(2) to keep total energy constant. Carrier 0 (DC carrier) is always zero. If used, carrier 1 is non-zero. This means the sync algorithm has to check on odd carriers! """ active_carriers = _get_active_carriers(fft_len, occupied_carriers, pilot_carriers) numpy.random.seed(_seq_seed) bpsk = {0: numpy.sqrt(2), 1: -numpy.sqrt(2)} sw1 = [bpsk[numpy.random.randint(2)] if x in active_carriers and x % 2 else 0 for x in range(fft_len)] return numpy.fft.fftshift(sw1) def _make_sync_word2(fft_len, occupied_carriers, pilot_carriers): """ Creates a random sync sequence for coarse frequency offset and channel estimation. This is the second of typically two sync preamble symbols for the Schmidl & Cox sync algorithm. Symbols are always BPSK symbols. """ active_carriers = _get_active_carriers(fft_len, occupied_carriers, pilot_carriers) numpy.random.seed(_seq_seed) bpsk = {0: 1, 1: -1} sw2 = [bpsk[numpy.random.randint(2)] if x in active_carriers else 0 for x in range(fft_len)] sw2[0] = 0j return numpy.fft.fftshift(sw2) def _get_constellation(bps): """ Returns a modulator block for a given number of bits per symbol """ constellation = { 1: digital.constellation_bpsk(), 2: digital.constellation_qpsk(), 3: digital.constellation_8psk() } try: return constellation[bps] except KeyError: print 'Modulation not supported.' exit(1) class ofdm_tx(gr.hier_block2): """ Hierarchical block for OFDM modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: fft_len: The length of FFT (integer). cp_len: The length of cyclic prefix in total samples (integer). packet_length_tag_key: The name of the tag giving packet length at the input. occupied_carriers: A vector of vectors describing which OFDM carriers are occupied. pilot_carriers: A vector of vectors describing which OFDM carriers are occupied with pilot symbols. pilot_symbols: The pilot symbols. bps_header: Bits per symbol (header). bps_payload: Bits per symbol (payload). sync_word1: The first sync preamble symbol. This has to be with zeros on alternating carriers. Used for fine and coarse frequency offset and timing estimation. sync_word2: The second sync preamble symbol. This has to be filled entirely. Also used for coarse frequency offset and channel estimation. rolloff: The rolloff length in samples. Must be smaller than the CP. debug_log: Write output into log files (Warning: creates lots of data!) scramble_bits: Activates the scramblers (set this to True unless debugging) """ def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, packet_length_tag_key=_def_packet_length_tag_key, occupied_carriers=_def_occupied_carriers, pilot_carriers=_def_pilot_carriers, pilot_symbols=_def_pilot_symbols, bps_header=1, bps_payload=1, sync_word1=None, sync_word2=None, rolloff=0, debug_log=False, scramble_bits=False ): gr.hier_block2.__init__(self, "ofdm_tx", gr.io_signature(1, 1, gr.sizeof_char), gr.io_signature(1, 1, gr.sizeof_gr_complex)) ### Param init / sanity check ######################################## self.fft_len = fft_len self.cp_len = cp_len self.packet_length_tag_key = packet_length_tag_key self.occupied_carriers = occupied_carriers self.pilot_carriers = pilot_carriers self.pilot_symbols = pilot_symbols self.bps_header = bps_header self.bps_payload = bps_payload self.sync_word1 = sync_word1 if sync_word1 is None: self.sync_word1 = _make_sync_word1(fft_len, occupied_carriers, pilot_carriers) else: if len(sync_word1) != self.fft_len: raise ValueError("Length of sync sequence(s) must be FFT length.") self.sync_words = [self.sync_word1,] if sync_word2 is None: self.sync_word2 = _make_sync_word2(fft_len, occupied_carriers, pilot_carriers) else: self.sync_word2 = sync_word2 if len(self.sync_word2): if len(self.sync_word2) != fft_len: raise ValueError("Length of sync sequence(s) must be FFT length.") self.sync_word2 = list(self.sync_word2) self.sync_words.append(self.sync_word2) if scramble_bits: self.scramble_seed = 0x7f else: self.scramble_seed = 0x00 # We deactivate the scrambler by init'ing it with zeros ### Header modulation ################################################ crc = digital.crc32_bb(False, self.packet_length_tag_key) header_constellation = _get_constellation(bps_header) header_mod = digital.chunks_to_symbols_bc(header_constellation.points()) formatter_object = digital.packet_header_ofdm( occupied_carriers=occupied_carriers, n_syms=1, bits_per_header_sym=self.bps_header, bits_per_payload_sym=self.bps_payload, scramble_header=scramble_bits ) header_gen = digital.packet_headergenerator_bb(formatter_object.base(), self.packet_length_tag_key) header_payload_mux = blocks.tagged_stream_mux( itemsize=gr.sizeof_gr_complex*1, lengthtagname=self.packet_length_tag_key, tag_preserve_head_pos=1 # Head tags on the payload stream stay on the head ) self.connect( self, crc, header_gen, header_mod, (header_payload_mux, 0) ) if debug_log: self.connect(header_gen, blocks.file_sink(1, 'tx-hdr.dat')) ### Payload modulation ############################################### payload_constellation = _get_constellation(bps_payload) payload_mod = digital.chunks_to_symbols_bc(payload_constellation.points()) payload_scrambler = digital.additive_scrambler_bb( 0x8a, self.scramble_seed, 7, 0, # Don't reset after fixed length (let the reset tag do that) bits_per_byte=8, # This is before unpacking reset_tag_key=self.packet_length_tag_key ) payload_unpack = blocks.repack_bits_bb( 8, # Unpack 8 bits per byte bps_payload, self.packet_length_tag_key ) self.connect( crc, payload_scrambler, payload_unpack, payload_mod, (header_payload_mux, 1) ) ### Create OFDM frame ################################################ allocator = digital.ofdm_carrier_allocator_cvc( self.fft_len, occupied_carriers=self.occupied_carriers, pilot_carriers=self.pilot_carriers, pilot_symbols=self.pilot_symbols, sync_words=self.sync_words, len_tag_key=self.packet_length_tag_key ) ffter = fft.fft_vcc( self.fft_len, False, # Inverse FFT (), # No window True # Shift ) cyclic_prefixer = digital.ofdm_cyclic_prefixer( self.fft_len, self.fft_len+self.cp_len, rolloff, self.packet_length_tag_key ) self.connect(header_payload_mux, allocator, ffter, cyclic_prefixer, self) if debug_log: self.connect(allocator, blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'tx-post-allocator.dat')) self.connect(cyclic_prefixer, blocks.file_sink(gr.sizeof_gr_complex, 'tx-signal.dat')) class ofdm_rx(gr.hier_block2): """ Hierarchical block for OFDM demodulation. The input is a complex baseband signal (e.g. from a UHD source). The detected packets are output as a stream of packed bits on the output. Args: fft_len: The length of FFT (integer). cp_len: The length of cyclic prefix in total samples (integer). frame_length_tag_key: Used internally to tag the length of the OFDM frame. packet_length_tag_key: The name of the tag giving packet length at the input. occupied_carriers: A vector of vectors describing which OFDM carriers are occupied. pilot_carriers: A vector of vectors describing which OFDM carriers are occupied with pilot symbols. pilot_symbols: The pilot symbols. bps_header: Bits per symbol (header). bps_payload: Bits per symbol (payload). sync_word1: The first sync preamble symbol. This has to be with zeros on alternating carriers. Used for fine and coarse frequency offset and timing estimation. sync_word2: The second sync preamble symbol. This has to be filled entirely. Also used for coarse frequency offset and channel estimation. """ def __init__(self, fft_len=_def_fft_len, cp_len=_def_cp_len, frame_length_tag_key=_def_frame_length_tag_key, packet_length_tag_key=_def_packet_length_tag_key, packet_num_tag_key=_def_packet_num_tag_key, occupied_carriers=_def_occupied_carriers, pilot_carriers=_def_pilot_carriers, pilot_symbols=_def_pilot_symbols, bps_header=1, bps_payload=1, sync_word1=None, sync_word2=None, debug_log=False, scramble_bits=False ): gr.hier_block2.__init__(self, "ofdm_rx", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_char)) ### Param init / sanity check ######################################## self.fft_len = fft_len self.cp_len = cp_len self.frame_length_tag_key = frame_length_tag_key self.packet_length_tag_key = packet_length_tag_key self.occupied_carriers = occupied_carriers self.bps_header = bps_header self.bps_payload = bps_payload n_sync_words = 1 if sync_word1 is None: self.sync_word1 = _make_sync_word1(fft_len, occupied_carriers, pilot_carriers) else: if len(sync_word1) != self.fft_len: raise ValueError("Length of sync sequence(s) must be FFT length.") self.sync_word1 = sync_word1 self.sync_word2 = () if sync_word2 is None: self.sync_word2 = _make_sync_word2(fft_len, occupied_carriers, pilot_carriers) n_sync_words = 2 elif len(sync_word2): if len(sync_word2) != fft_len: raise ValueError("Length of sync sequence(s) must be FFT length.") self.sync_word2 = sync_word2 n_sync_words = 2 if scramble_bits: self.scramble_seed = 0x7f else: self.scramble_seed = 0x00 # We deactivate the scrambler by init'ing it with zeros ### Sync ############################################################ sync_detect = digital.ofdm_sync_sc_cfb(fft_len, cp_len) delay = blocks.delay(gr.sizeof_gr_complex, fft_len+cp_len) oscillator = analog.frequency_modulator_fc(-2.0 / fft_len) mixer = blocks.multiply_cc() hpd = digital.header_payload_demux( n_sync_words+1, # Number of OFDM symbols before payload (sync + 1 sym header) fft_len, cp_len, # FFT length, guard interval frame_length_tag_key, # Frame length tag key "", # We're not using trigger tags True # One output item is one OFDM symbol (False would output complex scalars) ) self.connect(self, sync_detect) self.connect(self, delay, (mixer, 0), (hpd, 0)) self.connect((sync_detect, 0), oscillator, (mixer, 1)) self.connect((sync_detect, 1), (hpd, 1)) if debug_log: self.connect((sync_detect, 0), blocks.file_sink(gr.sizeof_float, 'freq-offset.dat')) self.connect((sync_detect, 1), blocks.file_sink(gr.sizeof_char, 'sync-detect.dat')) ### Header demodulation ############################################## header_fft = fft.fft_vcc(self.fft_len, True, (), True) chanest = digital.ofdm_chanest_vcvc(self.sync_word1, self.sync_word2, 1) header_constellation = _get_constellation(bps_header) header_equalizer = digital.ofdm_equalizer_simpledfe( fft_len, header_constellation.base(), occupied_carriers, pilot_carriers, pilot_symbols, symbols_skipped=0, ) header_eq = digital.ofdm_frame_equalizer_vcvc( header_equalizer.base(), cp_len, self.frame_length_tag_key, True, 1 # Header is 1 symbol long ) header_serializer = digital.ofdm_serializer_vcc( fft_len, occupied_carriers, self.frame_length_tag_key ) header_demod = digital.constellation_decoder_cb(header_constellation.base()) header_formatter = digital.packet_header_ofdm( occupied_carriers, 1, packet_length_tag_key, frame_length_tag_key, packet_num_tag_key, bps_header, bps_payload, scramble_header=scramble_bits ) header_parser = digital.packet_headerparser_b(header_formatter.formatter()) self.connect( (hpd, 0), header_fft, chanest, header_eq, header_serializer, header_demod, header_parser ) self.msg_connect(header_parser, "header_data", hpd, "header_data") if debug_log: self.connect((chanest, 1), blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'channel-estimate.dat')) self.connect((chanest, 0), blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'post-hdr-chanest.dat')) self.connect((chanest, 0), blocks.tag_debug(gr.sizeof_gr_complex * fft_len, 'post-hdr-chanest')) self.connect(header_eq, blocks.file_sink(gr.sizeof_gr_complex * fft_len, 'post-hdr-eq.dat')) self.connect(header_serializer, blocks.file_sink(gr.sizeof_gr_complex, 'post-hdr-serializer.dat')) self.connect(header_descrambler, blocks.file_sink(1, 'post-hdr-demod.dat')) ### Payload demod #################################################### payload_fft = fft.fft_vcc(self.fft_len, True, (), True) payload_constellation = _get_constellation(bps_payload) payload_equalizer = digital.ofdm_equalizer_simpledfe( fft_len, payload_constellation.base(), occupied_carriers, pilot_carriers, pilot_symbols, symbols_skipped=1, # (that was already in the header) alpha=0.1 ) payload_eq = digital.ofdm_frame_equalizer_vcvc( payload_equalizer.base(), cp_len, self.frame_length_tag_key ) payload_serializer = digital.ofdm_serializer_vcc( fft_len, occupied_carriers, self.frame_length_tag_key, self.packet_length_tag_key, 1 # Skip 1 symbol (that was already in the header) ) payload_demod = digital.constellation_decoder_cb(payload_constellation.base()) self.payload_descrambler = digital.additive_scrambler_bb( 0x8a, self.scramble_seed, 7, 0, # Don't reset after fixed length bits_per_byte=8, # This is after packing reset_tag_key=self.packet_length_tag_key ) payload_pack = blocks.repack_bits_bb(bps_payload, 8, self.packet_length_tag_key, True) self.crc = digital.crc32_bb(True, self.packet_length_tag_key) self.connect( (hpd, 1), payload_fft, payload_eq, payload_serializer, payload_demod, payload_pack, self.payload_descrambler, self.crc, self ) if debug_log: self.connect((hpd, 1), blocks.tag_debug(gr.sizeof_gr_complex*fft_len, 'post-hpd')) self.connect(payload_fft, blocks.file_sink(gr.sizeof_gr_complex*fft_len, 'post-payload-fft.dat')) self.connect(payload_eq, blocks.file_sink(gr.sizeof_gr_complex*fft_len, 'post-payload-eq.dat')) self.connect(payload_serializer, blocks.file_sink(gr.sizeof_gr_complex, 'post-payload-serializer.dat')) self.connect(payload_demod, blocks.file_sink(1, 'post-payload-demod.dat')) self.connect(payload_pack, blocks.file_sink(1, 'post-payload-pack.dat')) self.connect(crc, blocks.file_sink(1, 'post-payload-crc.dat')) gnuradio-3.7.2.1/gr-digital/python/digital/qa_fll_band_edge.py0000775000175000017500000000567312207440367024110 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import math from gnuradio import gr, gr_unittest, digital, filter, blocks, analog class test_fll_band_edge_cc(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): sps = 4 rolloff = 0.35 bw = 2*math.pi/100.0 ntaps = 45 # Create pulse shape filter rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) # The frequency offset to correct foffset = 0.2 / (2.0*math.pi) # Create a set of 1's and -1's, pulse shape and interpolate to sps random.seed(0) data = [2.0*random.randint(0, 2) - 1.0 for i in xrange(200)] self.src = blocks.vector_source_c(data, False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) # Mix symbols with a complex sinusoid to spin them self.nco = analog.sig_source_c(1, analog.GR_SIN_WAVE, foffset, 1) self.mix = blocks.multiply_cc() # FLL will despin the symbols to an arbitrary phase self.fll = digital.fll_band_edge_cc(sps, rolloff, ntaps, bw) # Create sinks for all outputs of the FLL # we will only care about the freq and error outputs self.vsnk_frq = blocks.vector_sink_f() self.nsnk_fll = blocks.null_sink(gr.sizeof_gr_complex) self.nsnk_phs = blocks.null_sink(gr.sizeof_float) self.nsnk_err = blocks.null_sink(gr.sizeof_float) # Connect the blocks self.tb.connect(self.nco, (self.mix,1)) self.tb.connect(self.src, self.rrc, (self.mix,0)) self.tb.connect(self.mix, self.fll, self.nsnk_fll) self.tb.connect((self.fll,1), self.vsnk_frq) self.tb.connect((self.fll,2), self.nsnk_phs) self.tb.connect((self.fll,3), self.nsnk_err) self.tb.run() N = 700 dst_data = self.vsnk_frq.data()[N:] expected_result = len(dst_data)* [-0.20,] self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 4) if __name__ == '__main__': gr_unittest.run(test_fll_band_edge_cc, "test_fll_band_edge_cc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/__init__.py0000664000175000017500000000334312237515112022420 0ustar jcorganjcorgan# Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks and utilities for digital modulation and demodulation. ''' # The presence of this file turns this directory into a Python package import os try: from digital_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from digital_swig import * from psk import * from qam import * from qamlike import * from bpsk import * from qpsk import * from gmsk import * from gfsk import * from cpm import * from pkt import * from crc import * from modulation_utils import * from ofdm import * from ofdm_receiver import * from ofdm_sync_fixed import * from ofdm_sync_ml import * from ofdm_sync_pnac import * from ofdm_sync_pn import * from ofdm_txrx import ofdm_tx, ofdm_rx from soft_dec_lut_gen import * from psk_constellations import * from qam_constellations import * from constellation_map_generator import * import packet_utils import ofdm_packet_utils gnuradio-3.7.2.1/gr-digital/python/digital/qa_crc32.py0000775000175000017500000000327412207440367022272 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random import cmath from gnuradio import gr, gr_unittest, digital class test_crc32(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test01(self): data = 100*"0" expected_result = 2943744955 result = digital.crc32(data) #print hex(result) self.assertEqual(expected_result, result) def test02(self): data = 100*"1" expected_result = 2326594156 result = digital.crc32(data) #print hex(result) self.assertEqual(expected_result, result) def test03(self): data = 10*"0123456789" expected_result = 3774345973 result = digital.crc32(data) #print hex(result) self.assertEqual(expected_result, result) if __name__ == '__main__': gr_unittest.run(test_crc32, "test_crc32.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_packet_headergenerator_bb.py0000775000175000017500000001357712237515112026510 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks import pmt class qa_packet_headergenerator_bb (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_12bits (self): # 3 PDUs: | | | data = (1, 2, 3, 4, 1, 2) + tuple(range(25)) tagname = "packet_len" tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol(tagname) tag1.value = pmt.from_long(4) tag2 = gr.tag_t() tag2.offset = 4 tag2.key = pmt.string_to_symbol(tagname) tag2.value = pmt.from_long(2) tag3 = gr.tag_t() tag3.offset = 6 tag3.key = pmt.string_to_symbol(tagname) tag3.value = pmt.from_long(25) src = blocks.vector_source_b(data, False, 1, (tag1, tag2, tag3)) header = digital.packet_headergenerator_bb(12, tagname) sink = blocks.vector_sink_b() self.tb.connect(src, header, sink) self.tb.run() expected_data = ( 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 ) self.assertEqual(sink.data(), expected_data) def test_002_32bits (self): # 3 PDUs: | | | | data = (1, 2, 3, 4, 1, 2, 1, 2, 3, 4) tagname = "packet_len" tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol(tagname) tag1.value = pmt.from_long(4) tag2 = gr.tag_t() tag2.offset = 4 tag2.key = pmt.string_to_symbol(tagname) tag2.value = pmt.from_long(2) tag3 = gr.tag_t() tag3.offset = 6 tag3.key = pmt.string_to_symbol(tagname) tag3.value = pmt.from_long(4) src = blocks.vector_source_b(data, False, 1, (tag1, tag2, tag3)) header = digital.packet_headergenerator_bb(32, tagname) sink = blocks.vector_sink_b() self.tb.connect(src, header, sink) self.tb.run() expected_data = ( # | Number of symbols | Packet number | CRC 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1 ) self.assertEqual(sink.data(), expected_data) def test_003_12bits_formatter_object (self): # 3 PDUs: | | | | data = (1, 2, 3, 4, 1, 2, 1, 2, 3, 4) tagname = "packet_len" tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol(tagname) tag1.value = pmt.from_long(4) tag2 = gr.tag_t() tag2.offset = 4 tag2.key = pmt.string_to_symbol(tagname) tag2.value = pmt.from_long(2) tag3 = gr.tag_t() tag3.offset = 6 tag3.key = pmt.string_to_symbol(tagname) tag3.value = pmt.from_long(4) src = blocks.vector_source_b(data, False, 1, (tag1, tag2, tag3)) formatter_object = digital.packet_header_default(12, tagname) header = digital.packet_headergenerator_bb(formatter_object.formatter(), tagname) sink = blocks.vector_sink_b() self.tb.connect(src, header, sink) self.tb.run() expected_data = ( 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) self.assertEqual(sink.data(), expected_data) def test_004_8bits_formatter_ofdm (self): occupied_carriers = ((1, 2, 3, 5, 6, 7),) # 3 PDUs: | | | | data = (1, 2, 3, 4, 1, 2, 1, 2, 3, 4) tagname = "packet_len" tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol(tagname) tag1.value = pmt.from_long(4) tag2 = gr.tag_t() tag2.offset = 4 tag2.key = pmt.string_to_symbol(tagname) tag2.value = pmt.from_long(2) tag3 = gr.tag_t() tag3.offset = 6 tag3.key = pmt.string_to_symbol(tagname) tag3.value = pmt.from_long(4) src = blocks.vector_source_b(data, False, 1, (tag1, tag2, tag3)) formatter_object = digital.packet_header_ofdm(occupied_carriers, 1, tagname) self.assertEqual(formatter_object.header_len(), 6) self.assertEqual(pmt.symbol_to_string(formatter_object.len_tag_key()), tagname) header = digital.packet_headergenerator_bb(formatter_object.formatter(), tagname) sink = blocks.vector_sink_b() self.tb.connect(src, header, sink) self.tb.run() expected_data = ( 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ) self.assertEqual(sink.data(), expected_data) if __name__ == '__main__': gr_unittest.run(qa_packet_headergenerator_bb, "qa_packet_headergenerator_bb.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_constellation_decoder_cb.py0000775000175000017500000000555312207440367026367 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_constellation_decoder(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_constellation_decoder_cb_bpsk(self): cnst = digital.constellation_bpsk() src_data = (0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j) expected_result = ( 1, 1, 0, 0, 1, 0, 1) src = blocks.vector_source_c(src_data) op = digital.constellation_decoder_cb(cnst.base()) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) def _test_constellation_decoder_cb_qpsk(self): cnst = digital.constellation_qpsk() src_data = (0.5 + 0.5j, 0.1 - 1.2j, -0.8 - 0.1j, -0.45 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 - 1.2j) expected_result = ( 3, 1, 0, 2, 3, 2, 1) src = blocks.vector_source_c(src_data) op = digital_swig.constellation_decoder_cb(cnst.base()) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) if __name__ == '__main__': gr_unittest.run(test_constellation_decoder, "test_constellation_decoder.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_crc32_bb.py0000775000175000017500000001324112207440367022730 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks, digital import pmt class qa_crc32_bb (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_crc_len (self): """ Make sure the output of a CRC set is 4 bytes longer than the input. """ data = range(16) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(data)) src = blocks.vector_source_b(data, False, 1, (tag,)) crc = digital.crc32_bb(False, tag_name) sink = blocks.vector_sink_b() self.tb.connect(src, crc, sink) self.tb.run() # Check that the packets before crc_check are 4 bytes longer that the input. self.assertEqual(len(data)+4, len(sink.data())) def test_002_crc_equal (self): """ Go through CRC set / CRC check and make sure the output is the same as the input. """ data = (0, 1, 2, 3, 4, 5, 6, 7, 8) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(data)) src = blocks.vector_source_b(data, False, 1, (tag,)) crc = digital.crc32_bb(False, tag_name) crc_check = digital.crc32_bb(True, tag_name) sink = blocks.vector_sink_b() self.tb.connect(src, crc, crc_check, sink) self.tb.run() # Check that the packets after crc_check are the same as input. self.assertEqual(data, sink.data()) def test_003_crc_correct_lentag (self): tag_name = "length" pack_len = 8 packets = range(pack_len*2) tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.string_to_symbol(tag_name) tag1.value = pmt.from_long(pack_len) tag2 = gr.tag_t() tag2.offset = pack_len tag2.key = pmt.string_to_symbol(tag_name) tag2.value = pmt.from_long(pack_len) testtag1 = gr.tag_t() testtag1.offset = 1 testtag1.key = pmt.string_to_symbol("tag1") testtag1.value = pmt.from_long(0) testtag2 = gr.tag_t() testtag2.offset = pack_len testtag2.key = pmt.string_to_symbol("tag2") testtag2.value = pmt.from_long(0) testtag3 = gr.tag_t() testtag3.offset = len(packets)-1 testtag3.key = pmt.string_to_symbol("tag3") testtag3.value = pmt.from_long(0) src = blocks.vector_source_b(packets, False, 1, (tag1, tag2, testtag1, testtag2, testtag3)) crc = digital.crc32_bb(False, tag_name) sink = blocks.vector_sink_b() self.tb.connect(src, crc, sink) self.tb.run() self.assertEqual(len(sink.data()), 2*(pack_len+4)) correct_offsets = {'tag1': 1, 'tag2': 12, 'tag3': 19} tags_found = {'tag1': False, 'tag2': False, 'tag3': False} for tag in sink.tags(): key = pmt.symbol_to_string(tag.key) if key in correct_offsets.keys(): tags_found[key] = True self.assertEqual(correct_offsets[key], tag.offset) if key == tag_name: self.assertTrue(tag.offset == 0 or tag.offset == pack_len+4) self.assertTrue(all(tags_found.values())) def test_004_fail (self): """ Corrupt the data and make sure it fails CRC test. """ data = (0, 1, 2, 3, 4, 5, 6, 7) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(data)) src = blocks.vector_source_b(data, False, 1, (tag,)) crc = digital.crc32_bb(False, tag_name) crc_check = digital.crc32_bb(True, tag_name) corruptor = blocks.add_const_bb(1) sink = blocks.vector_sink_b() self.tb.connect(src, crc, corruptor, crc_check, sink) self.tb.run() # crc_check will drop invalid packets self.assertEqual(len(sink.data()), 0) def test_005_tag_propagation (self): """ Make sure tags on the CRC aren't lost. """ data = (0, 1, 2, 3, 4, 5, 6, 7, 8, 2, 67, 225, 188) tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(data)) testtag = gr.tag_t() testtag.offset = len(data)-1 testtag.key = pmt.string_to_symbol('tag1') testtag.value = pmt.from_long(0) src = blocks.vector_source_b(data, False, 1, (tag, testtag)) crc_check = digital.crc32_bb(True, tag_name) sink = blocks.vector_sink_b() self.tb.connect(src, crc_check, sink) self.tb.run() self.assertEqual([len(data)-5,], [tag.offset for tag in sink.tags() if pmt.symbol_to_string(tag.key) == 'tag1']) if __name__ == '__main__': gr_unittest.run(qa_crc32_bb, "qa_crc32_bb.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_pn_correlator_cc.py0000775000175000017500000000317112207440367024670 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks class test_pn_correlator_cc(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000_make(self): c = digital.pn_correlator_cc(10) def test_001_correlate(self): degree = 10 length = 2**degree-1 src = digital.glfsr_source_f(degree) head = blocks.head(gr.sizeof_float, length*length) f2c = blocks.float_to_complex() corr = digital.pn_correlator_cc(degree) dst = blocks.vector_sink_c() self.tb.connect(src, head, f2c, corr, dst) self.tb.run() data = dst.data() self.assertEqual(data[-1], (1.0+0j)) if __name__ == '__main__': gr_unittest.run(test_pn_correlator_cc, "test_pn_correlator_cc.xml") gnuradio-3.7.2.1/gr-digital/python/digital/gfsk.py0000664000175000017500000002631512207440367021625 0ustar jcorganjcorgan# # GFSK modulation and demodulation. # # # Copyright 2005-2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # See gnuradio-examples/python/digital for examples from gnuradio import gr from gnuradio import analog from gnuradio import blocks import modulation_utils import digital_swig as digital from math import pi import numpy from pprint import pprint import inspect try: from gnuradio import filter except ImportError: import filter_swig as filter # default values (used in __init__ and add_options) _def_samples_per_symbol = 2 _def_sensitivity = 1 _def_bt = 0.35 _def_verbose = False _def_log = False _def_gain_mu = None _def_mu = 0.5 _def_freq_error = 0.0 _def_omega_relative_limit = 0.005 # FIXME: Figure out how to make GFSK work with pfb_arb_resampler_fff for both # transmit and receive so we don't require integer samples per symbol. # ///////////////////////////////////////////////////////////////////////////// # GFSK modulator # ///////////////////////////////////////////////////////////////////////////// class gfsk_mod(gr.hier_block2): def __init__(self, samples_per_symbol=_def_samples_per_symbol, sensitivity=_def_sensitivity, bt=_def_bt, verbose=_def_verbose, log=_def_log): """ Hierarchical block for Gaussian Frequency Shift Key (GFSK) modulation. The input is a byte stream (unsigned char) and the output is the complex modulated signal at baseband. Args: samples_per_symbol: samples per baud >= 2 (integer) bt: Gaussian filter bandwidth * symbol time (float) verbose: Print information about modulator? (bool) debug: Print modualtion data to files? (bool) """ gr.hier_block2.__init__(self, "gfsk_mod", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature samples_per_symbol = int(samples_per_symbol) self._samples_per_symbol = samples_per_symbol self._bt = bt self._differential = False if not isinstance(samples_per_symbol, int) or samples_per_symbol < 2: raise TypeError, ("samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,)) ntaps = 4 * samples_per_symbol # up to 3 bits in filter at once #sensitivity = (pi / 2) / samples_per_symbol # phase change per bit = pi / 2 # Turn it into NRZ data. #self.nrz = digital.bytes_to_syms() self.unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST) self.nrz = digital.chunks_to_symbols_bf([-1, 1]) # Form Gaussian filter # Generate Gaussian response (Needs to be convolved with window below). self.gaussian_taps = filter.firdes.gaussian( 1.0, # gain samples_per_symbol, # symbol_rate bt, # bandwidth * symbol time ntaps # number of taps ) self.sqwave = (1,) * samples_per_symbol # rectangular window self.taps = numpy.convolve(numpy.array(self.gaussian_taps),numpy.array(self.sqwave)) self.gaussian_filter = filter.interp_fir_filter_fff(samples_per_symbol, self.taps) # FM modulation self.fmmod = analog.frequency_modulator_fc(sensitivity) # small amount of output attenuation to prevent clipping USRP sink self.amp = blocks.multiply_const_cc(0.999) if verbose: self._print_verbage() if log: self._setup_logging() # Connect & Initialize base class self.connect(self, self.unpack, self.nrz, self.gaussian_filter, self.fmmod, self.amp, self) def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self=None): # staticmethod that's also callable on an instance return 1 bits_per_symbol = staticmethod(bits_per_symbol) # make it a static method. def _print_verbage(self): print "bits per symbol = %d" % self.bits_per_symbol() print "Gaussian filter bt = %.2f" % self._bt def _setup_logging(self): print "Modulation logging turned on." self.connect(self.nrz, blocks.file_sink(gr.sizeof_float, "nrz.dat")) self.connect(self.gaussian_filter, blocks.file_sink(gr.sizeof_float, "gaussian_filter.dat")) self.connect(self.fmmod, blocks.file_sink(gr.sizeof_gr_complex, "fmmod.dat")) def add_options(parser): """ Adds GFSK modulation-specific options to the standard parser """ parser.add_option("", "--bt", type="float", default=_def_bt, help="set bandwidth-time product [default=%default] (GFSK)") add_options=staticmethod(add_options) def extract_kwargs_from_options(options): """ Given command line options, create dictionary suitable for passing to __init__ """ return modulation_utils.extract_kwargs_from_options(gfsk_mod.__init__, ('self',), options) extract_kwargs_from_options=staticmethod(extract_kwargs_from_options) # ///////////////////////////////////////////////////////////////////////////// # GFSK demodulator # ///////////////////////////////////////////////////////////////////////////// class gfsk_demod(gr.hier_block2): def __init__(self, samples_per_symbol=_def_samples_per_symbol, sensitivity=_def_sensitivity, gain_mu=_def_gain_mu, mu=_def_mu, omega_relative_limit=_def_omega_relative_limit, freq_error=_def_freq_error, verbose=_def_verbose, log=_def_log): """ Hierarchical block for Gaussian Minimum Shift Key (GFSK) demodulation. The input is the complex modulated signal at baseband. The output is a stream of bits packed 1 bit per byte (the LSB) Args: samples_per_symbol: samples per baud (integer) verbose: Print information about modulator? (bool) log: Print modualtion data to files? (bool) Clock recovery parameters. These all have reasonble defaults. Args: gain_mu: controls rate of mu adjustment (float) mu: fractional delay [0.0, 1.0] (float) omega_relative_limit: sets max variation in omega (float, typically 0.000200 (200 ppm)) freq_error: bit rate error as a fraction float: """ gr.hier_block2.__init__(self, "gfsk_demod", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_char)) # Output signature self._samples_per_symbol = samples_per_symbol self._gain_mu = gain_mu self._mu = mu self._omega_relative_limit = omega_relative_limit self._freq_error = freq_error self._differential = False if samples_per_symbol < 2: raise TypeError, "samples_per_symbol >= 2, is %f" % samples_per_symbol self._omega = samples_per_symbol*(1+self._freq_error) if not self._gain_mu: self._gain_mu = 0.175 self._gain_omega = .25 * self._gain_mu * self._gain_mu # critically damped # Demodulate FM #sensitivity = (pi / 2) / samples_per_symbol self.fmdemod = analog.quadrature_demod_cf(1.0 / sensitivity) # the clock recovery block tracks the symbol clock and resamples as needed. # the output of the block is a stream of soft symbols (float) self.clock_recovery = digital.clock_recovery_mm_ff(self._omega, self._gain_omega, self._mu, self._gain_mu, self._omega_relative_limit) # slice the floats at 0, outputting 1 bit (the LSB of the output byte) per sample self.slicer = digital.binary_slicer_fb() if verbose: self._print_verbage() if log: self._setup_logging() # Connect & Initialize base class self.connect(self, self.fmdemod, self.clock_recovery, self.slicer, self) def samples_per_symbol(self): return self._samples_per_symbol def bits_per_symbol(self=None): # staticmethod that's also callable on an instance return 1 bits_per_symbol = staticmethod(bits_per_symbol) # make it a static method. def _print_verbage(self): print "bits per symbol = %d" % self.bits_per_symbol() print "M&M clock recovery omega = %f" % self._omega print "M&M clock recovery gain mu = %f" % self._gain_mu print "M&M clock recovery mu = %f" % self._mu print "M&M clock recovery omega rel. limit = %f" % self._omega_relative_limit print "frequency error = %f" % self._freq_error def _setup_logging(self): print "Demodulation logging turned on." self.connect(self.fmdemod, blocks.file_sink(gr.sizeof_float, "fmdemod.dat")) self.connect(self.clock_recovery, blocks.file_sink(gr.sizeof_float, "clock_recovery.dat")) self.connect(self.slicer, blocks.file_sink(gr.sizeof_char, "slicer.dat")) def add_options(parser): """ Adds GFSK demodulation-specific options to the standard parser """ parser.add_option("", "--gain-mu", type="float", default=_def_gain_mu, help="M&M clock recovery gain mu [default=%default] (GFSK/PSK)") parser.add_option("", "--mu", type="float", default=_def_mu, help="M&M clock recovery mu [default=%default] (GFSK/PSK)") parser.add_option("", "--omega-relative-limit", type="float", default=_def_omega_relative_limit, help="M&M clock recovery omega relative limit [default=%default] (GFSK/PSK)") parser.add_option("", "--freq-error", type="float", default=_def_freq_error, help="M&M clock recovery frequency error [default=%default] (GFSK)") add_options=staticmethod(add_options) def extract_kwargs_from_options(options): """ Given command line options, create dictionary suitable for passing to __init__ """ return modulation_utils.extract_kwargs_from_options(gfsk_demod.__init__, ('self',), options) extract_kwargs_from_options=staticmethod(extract_kwargs_from_options) # # Add these to the mod/demod registry # modulation_utils.add_type_1_mod('gfsk', gfsk_mod) modulation_utils.add_type_1_demod('gfsk', gfsk_demod) gnuradio-3.7.2.1/gr-digital/python/digital/qa_header_payload_demux.py0000775000175000017500000002401112207440367025511 0ustar jcorganjcorgan#!/usr/bin/env python # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import time from gnuradio import gr, gr_unittest, digital, blocks import pmt class qa_header_payload_demux (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): """ Simplest possible test: put in zeros, then header, then payload, trigger signal, try to demux. The return signal from the header parser is faked via _post() Add in some tags for fun. """ n_zeros = 1 header = (1, 2, 3) payload = tuple(range(5, 20)) data_signal = (0,) * n_zeros + header + payload trigger_signal = [0,] * len(data_signal) trigger_signal[n_zeros] = 1 # This is dropped: testtag1 = gr.tag_t() testtag1.offset = 0 testtag1.key = pmt.string_to_symbol('tag1') testtag1.value = pmt.from_long(0) # This goes on output 0, item 0: testtag2 = gr.tag_t() testtag2.offset = n_zeros testtag2.key = pmt.string_to_symbol('tag2') testtag2.value = pmt.from_long(23) # This goes on output 0, item 2: testtag3 = gr.tag_t() testtag3.offset = n_zeros + len(header) - 1 testtag3.key = pmt.string_to_symbol('tag3') testtag3.value = pmt.from_long(42) # This goes on output 1, item 3: testtag4 = gr.tag_t() testtag4.offset = n_zeros + len(header) + 3 testtag4.key = pmt.string_to_symbol('tag4') testtag4.value = pmt.from_long(314) data_src = blocks.vector_source_f(data_signal, False, tags=(testtag1, testtag2, testtag3, testtag4)) trigger_src = blocks.vector_source_b(trigger_signal, False) hpd = digital.header_payload_demux( len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float ) self.assertEqual(pmt.length(hpd.message_ports_in()), 1) header_sink = blocks.vector_sink_f() payload_sink = blocks.vector_sink_f() self.tb.connect(data_src, (hpd, 0)) self.tb.connect(trigger_src, (hpd, 1)) self.tb.connect((hpd, 0), header_sink) self.tb.connect((hpd, 1), payload_sink) self.tb.start() time.sleep(.2) # Need this, otherwise, the next message is ignored hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.from_long(len(payload)) ) while len(payload_sink.data()) < len(payload): time.sleep(.2) self.tb.stop() self.tb.wait() self.assertEqual(header_sink.data(), header) self.assertEqual(payload_sink.data(), payload) ptags_header = [] for tag in header_sink.tags(): ptag = gr.tag_to_python(tag) ptags_header.append({'key': ptag.key, 'offset': ptag.offset}) expected_tags_header = [ {'key': 'tag2', 'offset': 0}, {'key': 'tag3', 'offset': 2}, ] self.assertEqual(expected_tags_header, ptags_header) ptags_payload = [] for tag in payload_sink.tags(): ptag = gr.tag_to_python(tag) ptags_payload.append({'key': ptag.key, 'offset': ptag.offset}) expected_tags_payload = [ {'key': 'frame_len', 'offset': 0}, {'key': 'tag4', 'offset': 3}, ] self.assertEqual(expected_tags_payload, ptags_payload) def test_002_symbols (self): """ Same as before, but operate on symbols """ n_zeros = 1 items_per_symbol = 3 gi = 1 n_symbols = 4 header = (1, 2, 3) payload = (1, 2, 3) data_signal = (0,) * n_zeros + (0,) + header + ((0,) + payload) * n_symbols trigger_signal = [0,] * len(data_signal) trigger_signal[n_zeros] = 1 # This is dropped: testtag1 = gr.tag_t() testtag1.offset = 0 testtag1.key = pmt.string_to_symbol('tag1') testtag1.value = pmt.from_long(0) # This goes on output 0, item 0 (from the GI) testtag2 = gr.tag_t() testtag2.offset = n_zeros testtag2.key = pmt.string_to_symbol('tag2') testtag2.value = pmt.from_long(23) # This goes on output 0, item 0 (middle of the header symbol) testtag3 = gr.tag_t() testtag3.offset = n_zeros + gi + 1 testtag3.key = pmt.string_to_symbol('tag3') testtag3.value = pmt.from_long(42) # This goes on output 1, item 1 (middle of the first payload symbol) testtag4 = gr.tag_t() testtag4.offset = n_zeros + (gi + items_per_symbol) * 2 + 1 testtag4.key = pmt.string_to_symbol('tag4') testtag4.value = pmt.from_long(314) data_src = blocks.vector_source_f(data_signal, False, tags=(testtag1, testtag2, testtag3, testtag4)) trigger_src = blocks.vector_source_b(trigger_signal, False) hpd = digital.header_payload_demux( len(header) / items_per_symbol, # Header length (in symbols) items_per_symbol, # Items per symbols gi, # Items per guard time "frame_len", # Frame length tag key "detect", # Trigger tag key True, # Output symbols (not items) gr.sizeof_float # Bytes per item ) self.assertEqual(pmt.length(hpd.message_ports_in()), 1) header_sink = blocks.vector_sink_f(items_per_symbol) payload_sink = blocks.vector_sink_f(items_per_symbol) self.tb.connect(data_src, (hpd, 0)) self.tb.connect(trigger_src, (hpd, 1)) self.tb.connect((hpd, 0), header_sink) self.tb.connect((hpd, 1), payload_sink) self.tb.start() time.sleep(.2) # Need this, otherwise, the next message is ignored hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.from_long(n_symbols) ) while len(payload_sink.data()) < len(payload) * n_symbols: time.sleep(.2) self.tb.stop() self.tb.wait() self.assertEqual(header_sink.data(), header) self.assertEqual(payload_sink.data(), payload * n_symbols) ptags_header = [] for tag in header_sink.tags(): ptag = gr.tag_to_python(tag) ptags_header.append({'key': ptag.key, 'offset': ptag.offset}) expected_tags_header = [ {'key': 'tag2', 'offset': 0}, {'key': 'tag3', 'offset': 0}, ] self.assertEqual(expected_tags_header, ptags_header) ptags_payload = [] for tag in payload_sink.tags(): ptag = gr.tag_to_python(tag) ptags_payload.append({'key': ptag.key, 'offset': ptag.offset}) expected_tags_payload = [ {'key': 'frame_len', 'offset': 0}, {'key': 'tag4', 'offset': 1}, ] self.assertEqual(expected_tags_payload, ptags_payload) def test_003_t (self): """ Like test 1, but twice, plus one fail """ n_zeros = 5 header = (1, 2, 3) header_fail = (-1, -2, -4) # Contents don't really matter payload1 = tuple(range(5, 20)) payload2 = (42,) data_signal = (0,) * n_zeros + header + payload1 trigger_signal = [0,] * len(data_signal) * 2 trigger_signal[n_zeros] = 1 trigger_signal[len(data_signal)] = 1 trigger_signal[len(data_signal)+len(header_fail)+n_zeros] = 1 tx_signal = data_signal + header_fail + (0,) * n_zeros + header + payload2 + (0,) * 1000 data_src = blocks.vector_source_f(tx_signal, False) trigger_src = blocks.vector_source_b(trigger_signal, False) hpd = digital.header_payload_demux( len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float ) self.assertEqual(pmt.length(hpd.message_ports_in()), 1) header_sink = blocks.vector_sink_f() payload_sink = blocks.vector_sink_f() self.tb.connect(data_src, (hpd, 0)) self.tb.connect(trigger_src, (hpd, 1)) self.tb.connect((hpd, 0), header_sink) self.tb.connect((hpd, 1), payload_sink) self.tb.start() time.sleep(.2) # Need this, otherwise, the next message is ignored hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.from_long(len(payload1)) ) while len(payload_sink.data()) < len(payload1): time.sleep(.2) hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.PMT_F ) # This next command is a bit of a showstopper, but there's no condition to check upon # to see if the previous msg handling is finished time.sleep(.7) hpd.to_basic_block()._post( pmt.intern('header_data'), pmt.from_long(len(payload2)) ) while len(payload_sink.data()) < len(payload1) + len(payload2): time.sleep(.2) self.tb.stop() self.tb.wait() self.assertEqual(header_sink.data(), header + header_fail + header) self.assertEqual(payload_sink.data(), payload1 + payload2) if __name__ == '__main__': gr_unittest.run(qa_header_payload_demux, "qa_header_payload_demux.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qa_binary_slicer_fb.py0000775000175000017500000000357212207440367024653 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random from gnuradio import gr, gr_unittest, digital, blocks class test_binary_slicer_fb(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_binary_slicer_fb(self): expected_result = ( 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1) src_data = (-1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1) src_data = [s + (1 - random.random()) for s in src_data] # add some noise src = blocks.vector_source_f(src_data) op = digital.binary_slicer_fb() dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() # run the graph and wait for it to finish actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result) if __name__ == '__main__': gr_unittest.run(test_binary_slicer_fb, "test_binary_slicer_fb.xml") gnuradio-3.7.2.1/gr-digital/python/digital/qamlike.py0000664000175000017500000000501212207440367022305 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ This file contains constellations that are similar to QAM, but are not perfect squares. """ import digital_swig from qam import large_ampls_to_corners_mapping def qam32_holeinside_constellation(large_ampls_to_corners=False): # First make constellation for one quadrant. # 0 1 2 # 2 - 010 111 110 # 1 - 011 101 100 # 0 - 000 001 # Have put hole in the side rather than corner. # Corner point is helpful for frequency locking. # It has an attempt at some gray-coding, but not # a very good one. # Indices are (horizontal, vertical). indices_and_numbers = ( ((0, 0), 0b000), ((0, 1), 0b011), ((0, 2), 0b010), ((1, 0), 0b001), ((1, 1), 0b101), ((1, 2), 0b111), ((2, 1), 0b100), ((2, 2), 0b110), ) points = [None]*32 for indices, number in indices_and_numbers: p_in_quadrant = 0.5+indices[0] + 1j*(0.5+indices[1]) for quadrant in range(4): index = number + 8 * quadrant rotation = pow(1j, quadrant) p = p_in_quadrant * rotation points[index] = p side = 6 width = 1 # Double number of boxes on side # This is so that points in the 'hole' get assigned correctly. side = 12 width = 0.5 pre_diff_code = [] if not large_ampls_to_corners: constellation = digital_swig.constellation_rect(points, pre_diff_code, 4, side, side, width, width) else: sector_values = large_ampls_to_corners_mapping(side, points, width) constellation = digital_swig.constellation_expl_rect( points, pre_diff_code, 4, side, side, width, width, sector_values) return constellation gnuradio-3.7.2.1/gr-digital/python/digital/modulation_utils.py0000664000175000017500000000730612207440367024265 0ustar jcorganjcorgan# # Copyright 2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Miscellaneous utilities for managing mods and demods, as well as other items useful in dealing with generalized handling of different modulations and demods. """ import inspect # Type 1 modulators accept a stream of bytes on their input and produce complex baseband output _type_1_modulators = {} def type_1_mods(): return _type_1_modulators def add_type_1_mod(name, mod_class): _type_1_modulators[name] = mod_class # Type 1 demodulators accept complex baseband input and produce a stream of bits, packed # 1 bit / byte as their output. Their output is completely unambiguous. There is no need # to resolve phase or polarity ambiguities. _type_1_demodulators = {} def type_1_demods(): return _type_1_demodulators def add_type_1_demod(name, demod_class): _type_1_demodulators[name] = demod_class # Also record the constellation making functions of the modulations _type_1_constellations = {} def type_1_constellations(): return _type_1_constellations def add_type_1_constellation(name, constellation): _type_1_constellations[name] = constellation def extract_kwargs_from_options(function, excluded_args, options): """ Given a function, a list of excluded arguments and the result of parsing command line options, create a dictionary of key word arguments suitable for passing to the function. The dictionary will be populated with key/value pairs where the keys are those that are common to the function's argument list (minus the excluded_args) and the attributes in options. The values are the corresponding values from options unless that value is None. In that case, the corresponding dictionary entry is not populated. (This allows different modulations that have the same parameter names, but different default values to coexist. The downside is that --help in the option parser will list the default as None, but in that case the default provided in the __init__ argument list will be used since there is no kwargs entry.) Args: function: the function whose parameter list will be examined excluded_args: function arguments that are NOT to be added to the dictionary (sequence of strings) options: result of command argument parsing (optparse.Values) """ # Try this in C++ ;) args, varargs, varkw, defaults = inspect.getargspec(function) d = {} for kw in [a for a in args if a not in excluded_args]: if hasattr(options, kw): if getattr(options, kw) is not None: d[kw] = getattr(options, kw) return d def extract_kwargs_from_options_for_class(cls, options): """ Given command line options, create dictionary suitable for passing to __init__ """ d = extract_kwargs_from_options( cls.__init__, ('self',), options) for base in cls.__bases__: if hasattr(base, 'extract_kwargs_from_options'): d.update(base.extract_kwargs_from_options(options)) return d gnuradio-3.7.2.1/gr-digital/python/digital/test_soft_decisions.py0000775000175000017500000001107512237515112024737 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy, pylab, sys from gnuradio import digital from soft_dec_lut_gen import * from psk_constellations import * from qam_constellations import * def test_qpsk(i, sample, prec): qpsk_const_list = [psk_4_0, psk_4_1, psk_4_2, psk_4_3, psk_4_4, psk_4_5, psk_4_6, psk_4_7] qpsk_lut_gen_list = [sd_psk_4_0, sd_psk_4_1, sd_psk_4_2, sd_psk_4_3, sd_psk_4_4, sd_psk_4_5, sd_psk_4_6, sd_psk_4_7] constel, code = qpsk_const_list[i]() qpsk_lut_gen = qpsk_lut_gen_list[i] rot_sym = 1 side = 2 width = 2 c = digital.constellation_rect(constel, code, rot_sym, side, side, width, width) # Get max energy/symbol in constellation constel = c.points() Es = max([numpy.sqrt(constel_i.real**2 + constel_i.imag**2) for constel_i in constel]) #table = soft_dec_table_generator(qpsk_lut_gen, prec, Es) table = soft_dec_table(constel, code, prec) c.gen_soft_dec_lut(prec) #c.set_soft_dec_lut(table, prec) y_python_gen_calc = qpsk_lut_gen(sample, Es) y_python_table = calc_soft_dec_from_table(sample, table, prec, Es) y_python_raw_calc = calc_soft_dec(sample, constel, code) y_cpp_table = c.soft_decision_maker(sample) y_cpp_raw_calc = c.calc_soft_dec(sample) return (y_python_gen_calc, y_python_table, y_python_raw_calc, y_cpp_table, y_cpp_raw_calc, constel, code, c) def test_qam16(i, sample, prec): sample = sample/1 qam_const_list = [qam_16_0, ] qam_lut_gen_list = [sd_qam_16_0, ] constel, code = qam_const_list[i]() qam_lut_gen = qam_lut_gen_list[i] rot_sym = 4 side = 2 width = 2 c = digital.constellation_rect(constel, code, rot_sym, side, side, width, width) # Get max energy/symbol in constellation constel = c.points() Es = max([abs(constel_i) for constel_i in constel]) #table = soft_dec_table_generator(qam_lut_gen, prec, Es) table = soft_dec_table(constel, code, prec, 1) #c.gen_soft_dec_lut(prec) c.set_soft_dec_lut(table, prec) y_python_gen_calc = qam_lut_gen(sample, Es) y_python_table = calc_soft_dec_from_table(sample, table, prec, Es) y_python_raw_calc = calc_soft_dec(sample, constel, code, 1) y_cpp_table = c.soft_decision_maker(sample) y_cpp_raw_calc = c.calc_soft_dec(sample) return (y_python_gen_calc, y_python_table, y_python_raw_calc, y_cpp_table, y_cpp_raw_calc, constel, code, c) if __name__ == "__main__": index = 0 prec = 8 x_re = 2*numpy.random.random()-1 x_im = 2*numpy.random.random()-1 x = x_re + x_im*1j #x = -1 + -0.j if 1: y_python_gen_calc, y_python_table, y_python_raw_calc, \ y_cpp_table, y_cpp_raw_calc, constel, code, c \ = test_qpsk(index, x, prec) else: y_python_gen_calc, y_python_table, y_python_raw_calc, \ y_cpp_table, y_cpp_raw_calc, constel, code, c \ = test_qam16(index, x, prec) k = numpy.log2(len(constel)) print "Sample: ", x print "Python Generator Calculated: ", (y_python_gen_calc) print "Python Generator Table: ", (y_python_table) print "Python Raw calc: ", (y_python_raw_calc) print "C++ Table calc: ", (y_cpp_table) print "C++ Raw calc: ", (y_cpp_raw_calc) fig = pylab.figure(1) sp1 = fig.add_subplot(1,1,1) sp1.plot([c.real for c in constel], [c.imag for c in constel], 'bo') sp1.plot(x.real, x.imag, 'ro') sp1.set_xlim([-1.5, 1.5]) sp1.set_ylim([-1.5, 1.5]) fill = int(numpy.log2(len(constel))) for i,c in enumerate(constel): sp1.text(1.2*c.real, 1.2*c.imag, bin(code[i])[2:].zfill(fill), ha='center', va='center', size=18) pylab.show() gnuradio-3.7.2.1/gr-digital/python/digital/digital_voice.py.real0000664000175000017500000000641512207440367024416 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Digital voice Tx and Rx using GSM 13kbit vocoder and GMSK. Runs channel at 32kbit/sec. """ from gnuradio import gr, gru from gnuradio import blocks from gnuradio.blksimpl.gmsk import gmsk_mod, gmsk_demod from gnuradio.vocoder import gsm_full_rate # Size of gsm full rate speech encoder output packet in bytes GSM_FRAME_SIZE = 33 # Size of packet in bytes that we send to GMSK modulator: # # Target: 256kS/sec air rate. # # 256kS 1 sym 1 bit 1 byte 0.020 sec 80 bytes # ---- * ----- * ----- * ------ * --------- = -------- # sec 8 S 1 sym 8 bits frame frame # # gr_simple_framer add 10 bytes of overhead. AIR_FRAME_SIZE = 70 class digital_voice_tx(gr.hier_block): """ Hierarchical block for digital voice tranmission. The input is 8kS/sec floating point audio in the range [-1,+1] The output is 256kS/sec GMSK modulated complex baseband signal in the range [-1,+1]. """ def __init__(self, fg): samples_per_symbol = 8 symbol_rate = 32000 bt = 0.3 # Gaussian filter bandwidth * symbol time src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() voice_coder = gsm_full_rate.encode_sp() channel_coder = gr.multiply_const_b(1) p2s = gr.parallel_to_serial(gr.sizeof_char, AIR_FRAME_SIZE) mod = gmsk_mod(fg, sps=samples_per_symbol, symbol_rate=symbol_rate, bt=bt, p_size=AIR_FRAME_SIZE) fg.connect(src_scale, f2s, voice_coder, channel_coder, p2s, mod) gr.hier_block.__init__(self, fg, src_scale, mod) class digital_voice_rx(gr.hier_block): """ Hierarchical block for digital voice reception. The input is 256kS/sec GMSK modulated complex baseband signal. The output is 8kS/sec floating point audio in the range [-1,+1] """ def __init__(self, fg): samples_per_symbol = 8 symbol_rate = 32000 demod = gmsk_demod(fg, sps=samples_per_symbol, symbol_rate=symbol_rate, p_size=AIR_FRAME_SIZE) s2p = gr.serial_to_parallel(gr.sizeof_char, AIR_FRAME_SIZE) channel_decoder = gr.multiply_const_b(1) voice_decoder = gsm_full_rate.decode_ps() s2f = blocks.short_to_float () sink_scale = blocks.multiply_const_ff(1.0/32767.) fg.connect(demod, s2p, channel_decoder, voice_decoder, s2f, sink_scale) gr.hier_block.__init__(self, fg, demod, sink_scale) gnuradio-3.7.2.1/gr-digital/python/digital/qa_cpm.py0000775000175000017500000000613512207440367022134 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy from gnuradio import gr, gr_unittest, digital, analog, blocks class test_cpm(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def do_check_phase_shift(self, type, name): sps = 2 L = 1 in_bits = (1,) * 20 src = blocks.vector_source_b(in_bits, False) cpm = digital.cpmmod_bc(type, 0.5, sps, L) arg = blocks.complex_to_arg() sink = blocks.vector_sink_f() self.tb.connect(src, cpm, arg, sink) self.tb.run() symbol_phases = numpy.array(sink.data()[sps*L-1::sps]) phase_diff = numpy.mod(numpy.subtract(symbol_phases[1:], symbol_phases[:-1]), (2*numpy.pi,) * (len(symbol_phases)-1)) self.assertFloatTuplesAlmostEqual(tuple(phase_diff), (0.5 * numpy.pi,) * len(phase_diff), 5, msg="Phase shift was not correct for CPM method " + name) def test_001_lrec(self): self.do_check_phase_shift(analog.cpm.LRC, 'LREC') def test_001_lrc(self): self.do_check_phase_shift(analog.cpm.LRC, 'LRC') def test_001_lsrc(self): self.do_check_phase_shift(analog.cpm.LSRC, 'LSRC') def test_001_ltfm(self): self.do_check_phase_shift(analog.cpm.TFM, 'TFM') def test_001_lgmsk(self): sps = 2 L = 5 bt = 0.3 in_bits = (1,) * 20 src = blocks.vector_source_b(in_bits, False) gmsk = digital.gmskmod_bc(sps, L, bt) arg = blocks.complex_to_arg() sink = blocks.vector_sink_f() self.tb.connect(src, gmsk, arg, sink) self.tb.run() symbol_phases = numpy.array(sink.data()[sps*L-1::sps]) phase_diff = numpy.mod(numpy.subtract(symbol_phases[1:], symbol_phases[:-1]), (2*numpy.pi,) * (len(symbol_phases)-1)) self.assertFloatTuplesAlmostEqual(tuple(phase_diff), (0.5 * numpy.pi,) * len(phase_diff), 5, msg="Phase shift was not correct for GMSK") def test_phase_response(self): phase_response = analog.cpm.phase_response(analog.cpm.LREC, 2, 4) self.assertAlmostEqual(numpy.sum(phase_response), 1) if __name__ == '__main__': gr_unittest.run(test_cpm, "test_cpm.xml") gnuradio-3.7.2.1/gr-digital/lib/0000755000175000017500000000000012244272666016126 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/lib/correlate_access_code_tag_bb_impl.h0000664000175000017500000000441212207440367025106 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_TAG_BB_IMPL_H #define INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_TAG_BB_IMPL_H #include namespace gr { namespace digital { class correlate_access_code_tag_bb_impl : public correlate_access_code_tag_bb { private: unsigned long long d_access_code; // access code to locate start of packet // access code is left justified in the word unsigned long long d_data_reg; // used to look for access_code unsigned long long d_mask; // masks access_code bits (top N bits are set where // N is the number of bits in the access code) unsigned int d_threshold; // how many bits may be wrong in sync vector unsigned int d_len; // the length of the access code pmt::pmt_t d_key, d_me; //d_key is the tag name, d_me is the block name + unique ID public: correlate_access_code_tag_bb_impl(const std::string &access_code, int threshold, const std::string &tag_name); ~correlate_access_code_tag_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); bool set_access_code(const std::string &access_code); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_TAG_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/fll_band_edge_cc_impl.h0000664000175000017500000000526212207440367022513 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_FLL_BAND_EDGE_CC_IMPL_H #define INCLUDED_DIGITAL_FLL_BAND_EDGE_CC_IMPL_H #include #include #include namespace gr { namespace digital { class fll_band_edge_cc_impl : public fll_band_edge_cc { private: float d_sps; float d_rolloff; int d_filter_size; std::vector d_taps_lower; std::vector d_taps_upper; bool d_updated; std::vector d_output_hist; std::vector d_fllbuffer; gr::filter::kernel::fir_filter_ccc* d_filter_lower; gr::filter::kernel::fir_filter_ccc* d_filter_upper; /*! * Design the band-edge filter based on the number of samples * per symbol, filter rolloff factor, and the filter size * * \param samps_per_sym (float) Number of samples per symbol of signal * \param rolloff (float) Rolloff factor of signal * \param filter_size (int) Size (in taps) of the filter */ void design_filter(float samps_per_sym, float rolloff, int filter_size); public: fll_band_edge_cc_impl(float samps_per_sym, float rolloff, int filter_size, float bandwidth); ~fll_band_edge_cc_impl(); void set_samples_per_symbol(float sps); void set_rolloff(float rolloff); void set_filter_size(int filter_size); float samples_per_symbol() const; float rolloff() const; int filter_size() const; void print_taps(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_FLL_BAND_EDGE_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/cpmmod_bc_impl.h0000664000175000017500000000370712207440367021246 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CPMMOD_BC_IMPL_H #define INCLUDED_DIGITAL_CPMMOD_BC_IMPL_H #include #include #include #include namespace gr { namespace digital { class cpmmod_bc_impl : public cpmmod_bc { private: int d_type; float d_index; int d_sps; int d_length; double d_beta; protected: std::vector d_taps; gr::blocks::char_to_float::sptr d_char_to_float; gr::filter::interp_fir_filter_fff::sptr d_pulse_shaper; analog::frequency_modulator_fc::sptr d_fm; public: cpmmod_bc_impl(const std::string &name, analog::cpm::cpm_type type, float h, int samples_per_sym, int L, double beta=0.3); ~cpmmod_bc_impl(); std::vector taps() const; int type() const; float index() const; int samples_per_sym() const; int length() const; double beta() const; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CPMMOD_BC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/pn_correlator_cc_impl.h0000664000175000017500000000277212207440367022642 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PN_CORRELATOR_CC_IMPL_H #define INCLUDED_GR_PN_CORRELATOR_CC_IMPL_H #include #include namespace gr { namespace digital { class pn_correlator_cc_impl : public pn_correlator_cc { private: int d_len; float d_pn; glfsr *d_reference; public: pn_correlator_cc_impl(int degree, int mask=0, int seed=1); ~pn_correlator_cc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_PN_CORRELATOR_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/CMakeLists.txt0000664000175000017500000001503512237515112020660 0ustar jcorganjcorgan# Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_DIGITAL_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GR_ANALOG_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${LOG4CPP_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) link_directories(${LOG4CPP_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_impl_dict2(name, sig, 'digital') build_utils.expand_template(d, inp) ") macro(expand_cc root) #make a list of all the generated files unset(expanded_files_cc) unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_cc ${CMAKE_CURRENT_BINARY_DIR}/${name}.cc) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the source files add_custom_command( OUTPUT ${expanded_files_cc} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.cc.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.cc.t ${ARGN} ) #create a command to generate the header file add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #make source files depends on headers to force generation set_source_files_properties(${expanded_files_cc} PROPERTIES OBJECT_DEPENDS "${expanded_files_h}" ) #install rules for the generated cc files list(APPEND generated_sources ${expanded_files_cc}) list(APPEND generated_headers ${expanded_files_h}) endmacro(expand_cc) ######################################################################## # Invoke macro to generate various sources ######################################################################## expand_cc(chunks_to_symbols_XX_impl bf bc sf sc if ic) ######################################################################## # Setup library ######################################################################## list(APPEND digital_sources ${generated_sources} additive_scrambler_bb_impl.cc binary_slicer_fb_impl.cc clock_recovery_mm_cc_impl.cc clock_recovery_mm_ff_impl.cc cma_equalizer_cc_impl.cc constellation.cc constellation_decoder_cb_impl.cc constellation_receiver_cb_impl.cc constellation_soft_decoder_cf_impl.cc correlate_access_code_bb_impl.cc correlate_access_code_tag_bb_impl.cc correlate_and_sync_cc_impl.cc costas_loop_cc_impl.cc cpmmod_bc_impl.cc crc32.cc crc32_bb_impl.cc descrambler_bb_impl.cc diff_decoder_bb_impl.cc diff_encoder_bb_impl.cc diff_phasor_cc_impl.cc fll_band_edge_cc_impl.cc framer_sink_1_impl.cc glfsr.cc glfsr_source_b_impl.cc glfsr_source_f_impl.cc header_payload_demux_impl.cc kurtotic_equalizer_cc_impl.cc lms_dd_equalizer_cc_impl.cc map_bb_impl.cc mpsk_receiver_cc_impl.cc mpsk_snr_est.cc mpsk_snr_est_cc_impl.cc ofdm_carrier_allocator_cvc_impl.cc ofdm_chanest_vcvc_impl.cc ofdm_cyclic_prefixer_impl.cc ofdm_equalizer_base.cc ofdm_equalizer_simpledfe.cc ofdm_equalizer_static.cc ofdm_frame_acquisition_impl.cc ofdm_frame_equalizer_vcvc_impl.cc ofdm_frame_sink_impl.cc ofdm_insert_preamble_impl.cc ofdm_mapper_bcv_impl.cc ofdm_sampler_impl.cc ofdm_serializer_vcc_impl.cc ofdm_sync_sc_cfb_impl.cc packet_header_default.cc packet_header_ofdm.cc packet_headergenerator_bb_impl.cc packet_headerparser_b_impl.cc packet_sink_impl.cc pfb_clock_sync_ccf_impl.cc pfb_clock_sync_fff_impl.cc pn_correlator_cc_impl.cc probe_density_b_impl.cc probe_mpsk_snr_est_c_impl.cc scrambler_bb_impl.cc simple_correlator_impl.cc simple_framer_impl.cc header_payload_demux_impl.cc ) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-digital.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-digital.rc @ONLY) list(APPEND gr_digital_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-digital.rc ) ENDIF(MSVC) list(APPEND digital_libs volk gnuradio-runtime gnuradio-filter gnuradio-blocks gnuradio-analog ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_library(gnuradio-digital SHARED ${digital_sources}) target_link_libraries(gnuradio-digital ${digital_libs}) GR_LIBRARY_FOO(gnuradio-digital RUNTIME_COMPONENT "digital_runtime" DEVEL_COMPONENT "digital_devel") add_dependencies( gnuradio-digital digital_generated_includes digital_generated_swigs gnuradio-runtime gnuradio-filter gnuradio-analog gnuradio-blocks ) gnuradio-3.7.2.1/gr-digital/lib/clock_recovery_mm_ff_impl.h0000664000175000017500000000561212236015245023470 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_FF_IMPL_H #define INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_FF_IMPL_H #include #include namespace gr { namespace digital { class clock_recovery_mm_ff_impl : public clock_recovery_mm_ff { public: clock_recovery_mm_ff_impl(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limi); ~clock_recovery_mm_ff_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const { return d_mu;} float omega() const { return d_omega;} float gain_mu() const { return d_gain_mu;} float gain_omega() const { return d_gain_omega;} void set_verbose (bool verbose) { d_verbose = verbose; } void set_gain_mu (float gain_mu) { d_gain_mu = gain_mu; } void set_gain_omega (float gain_omega) { d_gain_omega = gain_omega; } void set_mu (float mu) { d_mu = mu; } void set_omega (float omega){ d_omega = omega; d_min_omega = omega*(1.0 - d_omega_relative_limit); d_max_omega = omega*(1.0 + d_omega_relative_limit); d_omega_mid = 0.5*(d_min_omega+d_max_omega); } private: float d_mu; // fractional sample position [0.0, 1.0] float d_gain_mu; // gain for adjusting mu float d_omega; // nominal frequency float d_gain_omega; // gain for adjusting omega float d_min_omega; // minimum allowed omega float d_max_omega; // maximum allowed omeg float d_omega_relative_limit; // used to compute min and max omega float d_omega_mid; // average omega float d_last_sample; filter::mmse_fir_interpolator_ff *d_interp; bool d_verbose; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_FF_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/packet_sink_impl.cc0000664000175000017500000001265212207440367021753 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "packet_sink_impl.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace digital { #define VERBOSE 0 // detect access code with up to DEFAULT_THRESHOLD bits wrong static const int DEFAULT_THRESHOLD = 12; inline void packet_sink_impl::enter_search() { if(VERBOSE) fprintf(stderr, "@ enter_search\n"); d_state = STATE_SYNC_SEARCH; d_shift_reg = 0; } inline void packet_sink_impl::enter_have_sync() { if(VERBOSE) fprintf(stderr, "@ enter_have_sync\n"); d_state = STATE_HAVE_SYNC; d_header = 0; d_headerbitlen_cnt = 0; } inline void packet_sink_impl::enter_have_header(int payload_len) { if(VERBOSE) fprintf(stderr, "@ enter_have_header (payload_len = %d)\n", payload_len); d_state = STATE_HAVE_HEADER; d_packetlen = payload_len; d_packetlen_cnt = 0; d_packet_byte = 0; d_packet_byte_index = 0; } packet_sink::sptr packet_sink::make(const std::vector& sync_vector, msg_queue::sptr target_queue, int threshold) { return gnuradio::get_initial_sptr (new packet_sink_impl(sync_vector, target_queue, threshold)); } packet_sink_impl::packet_sink_impl(const std::vector& sync_vector, msg_queue::sptr target_queue, int threshold) : sync_block("packet_sink", io_signature::make(1, 1, sizeof(float)), io_signature::make(0, 0, 0)), d_target_queue(target_queue), d_threshold(threshold == -1 ? DEFAULT_THRESHOLD : threshold) { d_sync_vector = 0; for(int i=0;i<8;i++){ d_sync_vector <<= 8; d_sync_vector |= sync_vector[i]; } enter_search(); } packet_sink_impl::~packet_sink_impl() { } int packet_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *inbuf = (float*)input_items[0]; int count=0; if(VERBOSE) fprintf(stderr, ">>> Entering state machine\n"), fflush(stderr); while(countmsg(), d_packet, d_packetlen_cnt); d_target_queue->insert_tail(msg); // send it msg.reset(); // free it up enter_search(); break; } } } break; default: assert(0); } // switch } // while return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/crc32_bb_impl.cc0000664000175000017500000000642112225347244021034 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "crc32_bb_impl.h" namespace gr { namespace digital { crc32_bb::sptr crc32_bb::make(bool check, const std::string& lengthtagname) { return gnuradio::get_initial_sptr (new crc32_bb_impl(check, lengthtagname)); } crc32_bb_impl::crc32_bb_impl(bool check, const std::string& lengthtagname) : tagged_stream_block("crc32_bb", io_signature::make(1, 1, sizeof (char)), io_signature::make(1, 1, sizeof (char)), lengthtagname), d_check(check), d_npass(0), d_nfail(0) { set_tag_propagation_policy(TPP_DONT); } crc32_bb_impl::~crc32_bb_impl() { } int crc32_bb_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { if (d_check) { return ninput_items[0] - 4; } else { return ninput_items[0] + 4; } } int crc32_bb_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; long packet_length = ninput_items[0]; int packet_size_diff = d_check ? -4 : 4; unsigned int crc; if (d_check) { d_crc_impl.reset(); d_crc_impl.process_bytes(in, packet_length-4); crc = d_crc_impl(); if (crc != *(unsigned int *)(in+packet_length-4)) { // Drop package d_nfail++; return 0; } d_npass++; memcpy((void *) out, (const void *) in, packet_length-4); } else { d_crc_impl.reset(); d_crc_impl.process_bytes(in, packet_length); crc = d_crc_impl(); memcpy((void *) out, (const void *) in, packet_length); memcpy((void *) (out + packet_length), &crc, 4); // FIXME big-endian/little-endian, this might be wrong } std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+packet_length); for (size_t i = 0; i < tags.size(); i++) { tags[i].offset -= nitems_read(0); if (d_check && tags[i].offset > (unsigned int)(packet_length+packet_size_diff)) { tags[i].offset = packet_length-5; } add_item_tag(0, nitems_written(0) + tags[i].offset, tags[i].key, tags[i].value); } return packet_length + packet_size_diff; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/mpsk_receiver_cc_impl.h0000664000175000017500000002075112207440367022624 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_MPSK_RECEIVER_CC_IMPL_H #define INCLUDED_DIGITAL_MPSK_RECEIVER_CC_IMPL_H #include #include #include #include #include #include namespace gr { namespace digital { class mpsk_receiver_cc_impl : public mpsk_receiver_cc, public blocks::control_loop { public: mpsk_receiver_cc_impl(unsigned int M, float theta, float loop_bw, float fmin, float fmax, float mu, float gain_mu, float omega, float gain_omega, float omega_rel); ~mpsk_receiver_cc_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); //! Returns the modulation order (M) currently set float modulation_order() const { return d_M; } //! Returns current value of theta float theta() const { return d_theta; } //! Returns current value of mu float mu() const { return d_mu; } //! Returns current value of omega float omega() const { return d_omega; } //! Returns mu gain factor float gain_mu() const { return d_gain_mu; } //! Returns omega gain factor float gain_omega() const { return d_gain_omega; } //! Returns the relative omega limit float gain_omega_rel() const {return d_omega_rel; } //! Sets the modulation order (M) currently void set_modulation_order(unsigned int M); //! Sets value of theta void set_theta(float theta) { d_theta = theta; } //! Sets value of mu void set_mu(float mu) { d_mu = mu; } //! Sets value of omega and its min and max values void set_omega(float omega) { d_omega = omega; d_min_omega = omega*(1.0 - d_omega_rel); d_max_omega = omega*(1.0 + d_omega_rel); d_omega_mid = 0.5*(d_min_omega+d_max_omega); } //! Sets value for mu gain factor void set_gain_mu(float gain_mu) { d_gain_mu = gain_mu; } //! Sets value for omega gain factor void set_gain_omega(float gain_omega) { d_gain_omega = gain_omega; } //! Sets the relative omega limit and resets omega min/max values void set_gain_omega_rel(float omega_rel); protected: void make_constellation(); void mm_sampler(const gr_complex symbol); void mm_error_tracking(gr_complex sample); void phase_error_tracking(gr_complex sample); /*! * \brief Phase error detector for MPSK modulations. * * \param sample the I&Q sample from which to determine the phase error * * This function determines the phase error for any MPSK signal * by creating a set of PSK constellation points and doing a * brute-force search to see which point minimizes the Euclidean * distance. This point is then used to derotate the sample to * the real-axis and a atan (using the fast approximation * function) to determine the phase difference between the * incoming sample and the real constellation point * * This should be cleaned up and made more efficient. * * \returns the approximated phase error. */ float phase_error_detector_generic(gr_complex sample) const; /*! * \brief Phase error detector for BPSK modulation. * * \param sample the I&Q sample from which to determine the phase error * * This function determines the phase error using a simple BPSK * phase error detector by multiplying the real and imaginary (the * error signal) components together. As the imaginary part goes to * 0, so does this error. * * \returns the approximated phase error. */ float phase_error_detector_bpsk(gr_complex sample) const; /*! * \brief Phase error detector for QPSK modulation. * * \param sample the I&Q sample from which to determine the phase error * * This function determines the phase error using the limiter * approach in a standard 4th order Costas loop * * \returns the approximated phase error. */ float phase_error_detector_qpsk(gr_complex sample) const; /*! * \brief Decision maker for a generic MPSK constellation. * * \param sample the baseband I&Q sample from which to make the decision * * This decision maker is a generic implementation that does a * brute-force search for the constellation point that minimizes * the error between it and the incoming signal. * * \returns the index to d_constellation that minimizes the error/ */ unsigned int decision_generic(gr_complex sample) const; /*! * \brief Decision maker for BPSK constellation. * * \param sample the baseband I&Q sample from which to make the decision * * This decision maker is a simple slicer function that makes a * decision on the symbol based on its placement on the real * axis of greater than 0 or less than 0; the quadrature * component is always 0. * * \returns the index to d_constellation that minimizes the error/ */ unsigned int decision_bpsk(gr_complex sample) const; /*! * \brief Decision maker for QPSK constellation. * * \param sample the baseband I&Q sample from which to make the decision * * This decision maker is a simple slicer function that makes a * decision on the symbol based on its placement versus both * axes and returns which quadrant the symbol is in. * * \returns the index to d_constellation that minimizes the error/ */ unsigned int decision_qpsk(gr_complex sample) const; private: unsigned int d_M; float d_theta; /*! * \brief Decision maker function pointer * * \param sample the baseband I&Q sample from which to make the decision * * This is a function pointer that is set in the constructor to * point to the proper decision function for the specified * constellation order. * * \return index into d_constellation point that is the closest to the recieved sample */ unsigned int (mpsk_receiver_cc_impl::*d_decision)(gr_complex sample) const; std::vector d_constellation; unsigned int d_current_const_point; // Members related to symbol timing float d_mu, d_gain_mu; float d_omega, d_gain_omega, d_omega_rel, d_max_omega, d_min_omega, d_omega_mid; gr_complex d_p_2T, d_p_1T, d_p_0T; gr_complex d_c_2T, d_c_1T, d_c_0T; /*! * \brief Phase error detector function pointer * * \param sample the I&Q sample from which to determine the phase error * * This is a function pointer that is set in the constructor to * point to the proper phase error detector function for the * specified constellation order. */ float (mpsk_receiver_cc_impl::*d_phase_error_detector)(gr_complex sample) const; //! get interpolated value gr::filter::mmse_fir_interpolator_cc *d_interp; //! delay line length. static const unsigned int DLLEN = 8; //! delay line plus some length for overflow protection __GR_ATTR_ALIGNED(8) gr_complex d_dl[2*DLLEN]; //! index to delay line unsigned int d_dl_idx; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_MPSK_RECEIVER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/simple_correlator_impl.cc0000664000175000017500000001525612207440367023210 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "simple_correlator_impl.h" #include #include #include #include #include #include #include namespace gr { namespace digital { static const int THRESHOLD = 3; simple_correlator::sptr simple_correlator::make(int payload_bytesize) { return gnuradio::get_initial_sptr (new simple_correlator_impl(payload_bytesize)); } simple_correlator_impl::simple_correlator_impl(int payload_bytesize) : block("simple_correlator", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(unsigned char))), d_payload_bytesize(payload_bytesize), d_state(ST_LOOKING), d_osi(0), d_bblen((payload_bytesize + GRSF_PAYLOAD_OVERHEAD) * GRSF_BITS_PER_BYTE), d_bitbuf(new unsigned char[d_bblen]), d_pktbuf(new unsigned char[d_bblen/GRSF_BITS_PER_BYTE]), d_bbi(0) { d_avbi = 0; d_accum = 0.0; d_avg = 0.0; for(int i = 0; i < AVG_PERIOD; i++) d_avgbuf[i] = 0.0; #ifdef DEBUG_SIMPLE_CORRELATOR d_debug_fp = fopen("corr.log", "w"); #endif enter_looking(); } simple_correlator_impl::~simple_correlator_impl() { #ifdef DEBUG_SIMPLE_CORRELATOR fclose(d_debug_fp); #endif delete [] d_bitbuf; delete [] d_pktbuf; } void simple_correlator_impl::enter_looking() { fflush(stdout); // fprintf(stderr, ">>> enter_looking\n"); d_state = ST_LOOKING; for(int i = 0; i < OVERSAMPLE; i++) d_shift_reg[i] = 0; d_osi = 0; d_avbi = 0; d_avg = d_avg * 0.5; d_accum = 0; for(int i = 0; i < AVG_PERIOD; i++) d_avgbuf[i] = 0.0; } void simple_correlator_impl::enter_under_threshold() { fflush(stdout); // fprintf(stderr, ">>> enter_under_threshold\n"); d_state = ST_UNDER_THRESHOLD; d_transition_osi = d_osi; } void simple_correlator_impl::enter_locked() { d_state = ST_LOCKED; int delta = sub_index(d_osi, d_transition_osi); d_center_osi = add_index(d_transition_osi, delta/2); //d_center_osi = add_index(d_center_osi, 3); // FIXME d_bbi = 0; fflush(stdout); // fprintf(stderr, ">>> enter_locked d_center_osi = %d\n", d_center_osi); d_avg = std::max(-1.0, std::min(1.0, d_accum * (1.0/AVG_PERIOD))); // fprintf(stderr, ">>> enter_locked d_avg = %g\n", d_avg); } static void packit(unsigned char *pktbuf, const unsigned char *bitbuf, int bitcount) { for(int i = 0; i < bitcount; i += 8) { int t = bitbuf[i+0] & 0x1; t = (t << 1) | (bitbuf[i+1] & 0x1); t = (t << 1) | (bitbuf[i+2] & 0x1); t = (t << 1) | (bitbuf[i+3] & 0x1); t = (t << 1) | (bitbuf[i+4] & 0x1); t = (t << 1) | (bitbuf[i+5] & 0x1); t = (t << 1) | (bitbuf[i+6] & 0x1); t = (t << 1) | (bitbuf[i+7] & 0x1); *pktbuf++ = t; } } void simple_correlator_impl::update_avg(float x) { d_accum -= d_avgbuf[d_avbi]; d_avgbuf[d_avbi] = x; d_accum += x; d_avbi = (d_avbi + 1) & (AVG_PERIOD-1); } int simple_correlator_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; int n = 0; int nin = ninput_items[0]; int decision; int hamming_dist; #ifdef DEBUG_SIMPLE_CORRELATOR struct debug_data { float raw_data; float sampled; float enter_locked; } debug_data; #endif while(n < nin) { #ifdef DEBUG_SIMPLE_CORRELATOR debug_data.raw_data = in[n]; debug_data.sampled = 0.0; debug_data.enter_locked = 0.0; #endif switch(d_state) { case ST_LOCKED: if(d_osi == d_center_osi) { #ifdef DEBUG_SIMPLE_CORRELATOR debug_data.sampled = 1.0; #endif decision = slice(in[n]); d_bitbuf[d_bbi] = decision; d_bbi++; if(d_bbi >= d_bblen) { // printf("got whole packet\n"); packit(d_pktbuf, d_bitbuf, d_bbi); //printf("seqno %3d\n", d_pktbuf[0]); memcpy(out, &d_pktbuf[GRSF_PAYLOAD_OVERHEAD], d_payload_bytesize); enter_looking(); consume_each(n + 1); return d_payload_bytesize; } } break; case ST_LOOKING: case ST_UNDER_THRESHOLD: update_avg(in[n]); decision = slice(in[n]); d_shift_reg[d_osi] = (d_shift_reg[d_osi] << 1) | decision; hamming_dist = gr::blocks::count_bits64(d_shift_reg[d_osi] ^ GRSF_SYNC); // printf("%2d %d\n", hamming_dist, d_osi); if(d_state == ST_LOOKING && hamming_dist <= THRESHOLD) { // We're seeing a good PN code, remember location enter_under_threshold(); } else if(d_state == ST_UNDER_THRESHOLD && hamming_dist > THRESHOLD) { // no longer seeing good PN code, compute center of goodness enter_locked(); #ifdef DEBUG_SIMPLE_CORRELATOR debug_data.enter_locked = 1.0; #endif } break; default: assert(0); } #ifdef DEBUG_SIMPLE_CORRELATOR fwrite(&debug_data, sizeof(debug_data), 1, d_debug_fp); #endif d_osi = add_index(d_osi, 1); n++; } consume_each(n); return 0; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/pfb_clock_sync_ccf_impl.cc0000664000175000017500000003603112237515112023240 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include "pfb_clock_sync_ccf_impl.h" #include #include #include #include namespace gr { namespace digital { pfb_clock_sync_ccf::sptr pfb_clock_sync_ccf::make(double sps, float loop_bw, const std::vector &taps, unsigned int filter_size, float init_phase, float max_rate_deviation, int osps) { return gnuradio::get_initial_sptr (new pfb_clock_sync_ccf_impl(sps, loop_bw, taps, filter_size, init_phase, max_rate_deviation, osps)); } static int ios[] = {sizeof(gr_complex), sizeof(float), sizeof(float), sizeof(float)}; static std::vector iosig(ios, ios+sizeof(ios)/sizeof(int)); pfb_clock_sync_ccf_impl::pfb_clock_sync_ccf_impl(double sps, float loop_bw, const std::vector &taps, unsigned int filter_size, float init_phase, float max_rate_deviation, int osps) : block("pfb_clock_sync_ccf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::makev(1, 4, iosig)), d_updated(false), d_nfilters(filter_size), d_max_dev(max_rate_deviation), d_osps(osps), d_error(0), d_out_idx(0) { // Let scheduler adjust our relative_rate. enable_update_rate(true); d_nfilters = filter_size; d_sps = floor(sps); // Set the damping factor for a critically damped system d_damping = 2*d_nfilters; // Set the bandwidth, which will then call update_gains() set_loop_bandwidth(loop_bw); // Store the last filter between calls to work // The accumulator keeps track of overflow to increment the stride correctly. // set it here to the fractional difference based on the initial phaes d_k = init_phase; d_rate = (sps-floor(sps))*(double)d_nfilters; d_rate_i = (int)floor(d_rate); d_rate_f = d_rate - (float)d_rate_i; d_filtnum = (int)floor(d_k); d_filters = std::vector(d_nfilters); d_diff_filters = std::vector(d_nfilters); // Create an FIR filter for each channel and zero out the taps std::vector vtaps(1,0); for(int i = 0; i < d_nfilters; i++) { d_filters[i] = new kernel::fir_filter_ccf(1, vtaps); d_diff_filters[i] = new kernel::fir_filter_ccf(1, vtaps); } // Now, actually set the filters' taps std::vector dtaps; create_diff_taps(taps, dtaps); set_taps(taps, d_taps, d_filters); set_taps(dtaps, d_dtaps, d_diff_filters); set_relative_rate((float)d_osps/(float)d_sps); } pfb_clock_sync_ccf_impl::~pfb_clock_sync_ccf_impl() { for(int i = 0; i < d_nfilters; i++) { delete d_filters[i]; delete d_diff_filters[i]; } } bool pfb_clock_sync_ccf_impl::check_topology(int ninputs, int noutputs) { return noutputs == 1 || noutputs == 4; } void pfb_clock_sync_ccf_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size (); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = (noutput_items + history()) * (d_sps/d_osps); } /******************************************************************* SET FUNCTIONS *******************************************************************/ void pfb_clock_sync_ccf_impl::set_loop_bandwidth(float bw) { if(bw < 0) { throw std::out_of_range("pfb_clock_sync_ccf: invalid bandwidth. Must be >= 0."); } d_loop_bw = bw; update_gains(); } void pfb_clock_sync_ccf_impl::set_damping_factor(float df) { if(df < 0 || df > 1.0) { throw std::out_of_range("pfb_clock_sync_ccf: invalid damping factor. Must be in [0,1]."); } d_damping = df; update_gains(); } void pfb_clock_sync_ccf_impl::set_alpha(float alpha) { if(alpha < 0 || alpha > 1.0) { throw std::out_of_range("pfb_clock_sync_ccf: invalid alpha. Must be in [0,1]."); } d_alpha = alpha; } void pfb_clock_sync_ccf_impl::set_beta(float beta) { if(beta < 0 || beta > 1.0) { throw std::out_of_range("pfb_clock_sync_ccf: invalid beta. Must be in [0,1]."); } d_beta = beta; } /******************************************************************* GET FUNCTIONS *******************************************************************/ float pfb_clock_sync_ccf_impl::loop_bandwidth() const { return d_loop_bw; } float pfb_clock_sync_ccf_impl::damping_factor() const { return d_damping; } float pfb_clock_sync_ccf_impl::alpha() const { return d_alpha; } float pfb_clock_sync_ccf_impl::beta() const { return d_beta; } float pfb_clock_sync_ccf_impl::clock_rate() const { return d_rate_f; } float pfb_clock_sync_ccf_impl::error() const { return d_error; } float pfb_clock_sync_ccf_impl::rate() const { return d_rate_f; } float pfb_clock_sync_ccf_impl::phase() const { return d_k; } /******************************************************************* *******************************************************************/ void pfb_clock_sync_ccf_impl::update_gains() { float denom = (1.0 + 2.0*d_damping*d_loop_bw + d_loop_bw*d_loop_bw); d_alpha = (4*d_damping*d_loop_bw) / denom; d_beta = (4*d_loop_bw*d_loop_bw) / denom; } void pfb_clock_sync_ccf_impl::set_taps(const std::vector &newtaps, std::vector< std::vector > &ourtaps, std::vector &ourfilter) { int i,j; unsigned int ntaps = newtaps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_nfilters); // Create d_numchan vectors to store each channel's taps ourtaps.resize(d_nfilters); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = newtaps; while((float)(tmp_taps.size()) < d_nfilters*d_taps_per_filter) { tmp_taps.push_back(0.0); } // Partition the filter for(i = 0; i < d_nfilters; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out ourtaps[i] = std::vector(d_taps_per_filter, 0); for(j = 0; j < d_taps_per_filter; j++) { ourtaps[i][j] = tmp_taps[i + j*d_nfilters]; } // Build a filter for each channel and add it's taps to it ourfilter[i]->set_taps(ourtaps[i]); } // Set the history to ensure enough input items for each filter set_history(d_taps_per_filter + d_sps + d_sps); // Make sure there is enough output space for d_osps outputs/input. set_output_multiple(d_osps); d_updated = true; } void pfb_clock_sync_ccf_impl::create_diff_taps(const std::vector &newtaps, std::vector &difftaps) { std::vector diff_filter(3); diff_filter[0] = -1; diff_filter[1] = 0; diff_filter[2] = 1; float pwr = 0; difftaps.clear(); difftaps.push_back(0); for(unsigned int i = 0; i < newtaps.size()-2; i++) { float tap = 0; for(unsigned int j = 0; j < diff_filter.size(); j++) { tap += diff_filter[j]*newtaps[i+j]; } difftaps.push_back(tap); pwr += fabsf(tap); } difftaps.push_back(0); // Normalize the taps for(unsigned int i = 0; i < difftaps.size(); i++) { difftaps[i] *= d_nfilters/pwr; } } std::string pfb_clock_sync_ccf_impl::taps_as_string() const { int i, j; std::stringstream str; str.precision(4); str.setf(std::ios::scientific); str << "[ "; for(i = 0; i < d_nfilters; i++) { str << "[" << d_taps[i][0] << ", "; for(j = 1; j < d_taps_per_filter-1; j++) { str << d_taps[i][j] << ", "; } str << d_taps[i][j] << "],"; } str << " ]" << std::endl; return str.str(); } std::string pfb_clock_sync_ccf_impl::diff_taps_as_string() const { int i, j; std::stringstream str; str.precision(4); str.setf(std::ios::scientific); str << "[ "; for(i = 0; i < d_nfilters; i++) { str << "[" << d_dtaps[i][0] << ", "; for(j = 1; j < d_taps_per_filter-1; j++) { str << d_dtaps[i][j] << ", "; } str << d_dtaps[i][j] << "],"; } str << " ]" << std::endl; return str.str(); } std::vector< std::vector > pfb_clock_sync_ccf_impl::taps() const { return d_taps; } std::vector< std::vector > pfb_clock_sync_ccf_impl::diff_taps() const { return d_dtaps; } std::vector pfb_clock_sync_ccf_impl::channel_taps(int channel) const { std::vector taps; for(int i = 0; i < d_taps_per_filter; i++) { taps.push_back(d_taps[channel][i]); } return taps; } std::vector pfb_clock_sync_ccf_impl::diff_channel_taps(int channel) const { std::vector taps; for(int i = 0; i < d_taps_per_filter; i++) { taps.push_back(d_dtaps[channel][i]); } return taps; } int pfb_clock_sync_ccf_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; float *err = NULL, *outrate = NULL, *outk = NULL; if(output_items.size() == 4) { err = (float *) output_items[1]; outrate = (float*)output_items[2]; outk = (float*)output_items[3]; } if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+d_sps*noutput_items, pmt::intern("time_est")); int i = 0, count = 0; float error_r, error_i; // produce output as long as we can and there are enough input samples while(i < noutput_items) { if(tags.size() > 0) { size_t offset = tags[0].offset-nitems_read(0); if((offset >= (size_t)count) && (offset < (size_t)(count + d_sps))) { float center = (float)pmt::to_double(tags[0].value); d_k = (offset-count - d_sps/2.0) * d_nfilters + (M_PI*center*d_nfilters); tags.erase(tags.begin()); } } while(d_out_idx < d_osps) { d_filtnum = (int)floor(d_k); // Keep the current filter number in [0, d_nfilters] // If we've run beyond the last filter, wrap around and go to next sample // If we've gone below 0, wrap around and go to previous sample while(d_filtnum >= d_nfilters) { d_k -= d_nfilters; d_filtnum -= d_nfilters; count += 1; } while(d_filtnum < 0) { d_k += d_nfilters; d_filtnum += d_nfilters; count -= 1; } out[i+d_out_idx] = d_filters[d_filtnum]->filter(&in[count+d_out_idx]); d_k = d_k + d_rate_i + d_rate_f; // update phase d_out_idx++; if(output_items.size() == 4) { err[i] = d_error; outrate[i] = d_rate_f; outk[i] = d_k; } // We've run out of output items we can create; return now. if(i+d_out_idx >= noutput_items) { consume_each(count); return i; } } // reset here; if we didn't complete a full osps samples last time, // the early return would take care of it. d_out_idx = 0; // Update the phase and rate estimates for this symbol gr_complex diff = d_diff_filters[d_filtnum]->filter(&in[count]); error_r = out[i].real() * diff.real(); error_i = out[i].imag() * diff.imag(); d_error = (error_i + error_r) / 2.0; // average error from I&Q channel // Run the control loop to update the current phase (k) and // tracking rate estimates based on the error value // Interpolating here to update rates for ever sps. for(int s = 0; s < d_sps; s++) { d_rate_f = d_rate_f + d_beta*d_error; d_k = d_k + d_rate_f + d_alpha*d_error; } // Keep our rate within a good range d_rate_f = gr::branchless_clip(d_rate_f, d_max_dev); i+=d_osps; count += (int)floor(d_sps); } consume_each(count); return i; } void pfb_clock_sync_ccf_impl::setup_rpc() { #ifdef GR_CTRLPORT // Getters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "error", &pfb_clock_sync_ccf::error, pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Error signal of loop", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "rate", &pfb_clock_sync_ccf::rate, pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Rate change of phase", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "phase", &pfb_clock_sync_ccf::phase, pmt::mp(0), pmt::mp((int)d_nfilters), pmt::mp(0), "", "Current filter phase arm", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "loop bw", &pfb_clock_sync_ccf::loop_bandwidth, pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f), "", "Loop bandwidth", RPC_PRIVLVL_MIN, DISPNULL))); // Setters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "loop bw", &pfb_clock_sync_ccf::set_loop_bandwidth, pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f), "", "Loop bandwidth", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/packet_header_default.cc0000664000175000017500000001036012237515112022706 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { namespace digital { packet_header_default::sptr packet_header_default::make( long header_len, const std::string &len_tag_key, const std::string &num_tag_key, int bits_per_byte) { return packet_header_default::sptr(new packet_header_default(header_len, len_tag_key, num_tag_key, bits_per_byte)); } const unsigned MASK_LUT[9] = {0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x2F, 0x7F, 0xFF}; packet_header_default::packet_header_default( long header_len, const std::string &len_tag_key, const std::string &num_tag_key, int bits_per_byte) : d_header_len(header_len), d_len_tag_key(pmt::string_to_symbol(len_tag_key)), d_num_tag_key(num_tag_key.empty() ? pmt::PMT_NIL : pmt::string_to_symbol(num_tag_key)), d_bits_per_byte(bits_per_byte), d_header_number(0) { if (d_bits_per_byte < 1 || d_bits_per_byte > 8) { throw std::invalid_argument("bits_per_byte must be in [1, 8]"); } d_mask = MASK_LUT[d_bits_per_byte]; } packet_header_default::~packet_header_default() { } bool packet_header_default::header_formatter( long packet_len, unsigned char *out, const std::vector &tags ) { packet_len &= 0x0FFF; d_crc_impl.reset(); d_crc_impl.process_bytes((void const *) &packet_len, 2); d_crc_impl.process_bytes((void const *) &d_header_number, 2); unsigned char crc = d_crc_impl(); memset(out, 0x00, d_header_len); int k = 0; // Position in out for (int i = 0; i < 12 && k < d_header_len; i += d_bits_per_byte, k++) { out[k] = (unsigned char) ((packet_len >> i) & d_mask); } for (int i = 0; i < 12 && k < d_header_len; i += d_bits_per_byte, k++) { out[k] = (unsigned char) ((d_header_number >> i) & d_mask); } for (int i = 0; i < 8 && k < d_header_len; i += d_bits_per_byte, k++) { out[k] = (unsigned char) ((crc >> i) & d_mask); } d_header_number++; d_header_number &= 0x0FFF; return true; } bool packet_header_default::header_parser( const unsigned char *in, std::vector &tags) { unsigned header_len = 0; unsigned header_num = 0; tag_t tag; int k = 0; // Position in "in" for (int i = 0; i < 12 && k < d_header_len; i += d_bits_per_byte, k++) { header_len |= (((int) in[k]) & d_mask) << i; } tag.key = d_len_tag_key; tag.value = pmt::from_long(header_len); tags.push_back(tag); if (k >= d_header_len) { return true; } if (d_num_tag_key == pmt::PMT_NIL) { k += 12; } else { for (int i = 0; i < 12 && k < d_header_len; i += d_bits_per_byte, k++) { header_num |= (((int) in[k]) & d_mask) << i; } tag.key = d_num_tag_key; tag.value = pmt::from_long(header_num); tags.push_back(tag); } if (k >= d_header_len) { return true; } d_crc_impl.reset(); d_crc_impl.process_bytes((void const *) &header_len, 2); d_crc_impl.process_bytes((void const *) &header_num, 2); unsigned char crc_calcd = d_crc_impl(); for (int i = 0; i < 8 && k < d_header_len; i += d_bits_per_byte, k++) { if ( (((int) in[k]) & d_mask) != (((int) crc_calcd >> i) & d_mask) ) { return false; } } return true; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/pfb_clock_sync_fff_impl.h0000664000175000017500000000666712237515112023124 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PFB_CLOCK_SYNC_FFF_IMPL_H #define INCLUDED_DIGITAL_PFB_CLOCK_SYNC_FFF_IMPL_H #include using namespace gr::filter; namespace gr { namespace digital { class pfb_clock_sync_fff_impl : public pfb_clock_sync_fff { private: bool d_updated; double d_sps; double d_sample_num; float d_loop_bw; float d_damping; float d_alpha; float d_beta; int d_nfilters; int d_taps_per_filter; std::vector d_filters; std::vector d_diff_filters; std::vector< std::vector > d_taps; std::vector< std::vector > d_dtaps; float d_k; float d_rate; float d_rate_i; float d_rate_f; float d_max_dev; int d_filtnum; int d_osps; float d_error; int d_out_idx; void create_diff_taps(const std::vector &newtaps, std::vector &difftaps); public: pfb_clock_sync_fff_impl(double sps, float gain, const std::vector &taps, unsigned int filter_size=32, float init_phase=0, float max_rate_deviation=1.5, int osps=1); ~pfb_clock_sync_fff_impl(); void update_gains(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); void set_taps(const std::vector &taps, std::vector< std::vector > &ourtaps, std::vector &ourfilter); std::vector< std::vector > taps() const; std::vector< std::vector > diff_taps() const; std::vector channel_taps(int channel) const; std::vector diff_channel_taps(int channel) const; std::string taps_as_string() const; std::string diff_taps_as_string() const; void set_loop_bandwidth(float bw); void set_damping_factor(float df); void set_alpha(float alpha); void set_beta(float beta); void set_max_rate_deviation(float m) { d_max_dev = m; } float loop_bandwidth() const; float damping_factor() const; float alpha() const; float beta() const; float clock_rate() const; bool check_topology(int ninputs, int noutputs); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_PFB_CLOCK_SYNC_FFF_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/constellation_receiver_cb_impl.h0000664000175000017500000000501612243706713024524 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_RECEIVER_CB_IMPL_H #define INCLUDED_DIGITAL_CONSTELLATION_RECEIVER_CB_IMPL_H #include #include #include #include namespace gr { namespace digital { class constellation_receiver_cb_impl : public constellation_receiver_cb, blocks::control_loop { public: constellation_receiver_cb_impl(constellation_sptr constell, float loop_bw, float fmin, float fmax); ~constellation_receiver_cb_impl(); void setup_rpc(); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); protected: void phase_error_tracking(float phase_error); private: constellation_sptr d_constellation; unsigned int d_current_const_point; //! Set the phase and the frequency. //! Typically used when we receive a tag with values for these. void set_phase_freq(float phase, float freq); void handle_set_constellation(pmt::pmt_t constellation_pmt); //! Set the constellation used. //! Typically used when we receive a tag with a value for this. void set_constellation(constellation_sptr constellation); //! delay line length. static const unsigned int DLLEN = 8; //! delay line plus some length for overflow protection __GR_ATTR_ALIGNED(8) gr_complex d_dl[2*DLLEN]; //! index to delay line unsigned int d_dl_idx; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_RECEIVER_CB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/packet_headergenerator_bb_impl.cc0000664000175000017500000000606212207440367024607 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "packet_headergenerator_bb_impl.h" namespace gr { namespace digital { packet_headergenerator_bb::sptr packet_headergenerator_bb::make( const packet_header_default::sptr &header_formatter, const std::string &len_tag_key ) { return gnuradio::get_initial_sptr (new packet_headergenerator_bb_impl(header_formatter, len_tag_key)); } packet_headergenerator_bb::sptr packet_headergenerator_bb::make( long header_len, const std::string &len_tag_key ) { const packet_header_default::sptr header_formatter( new packet_header_default(header_len, len_tag_key) ); return gnuradio::get_initial_sptr (new packet_headergenerator_bb_impl(header_formatter, len_tag_key)); } packet_headergenerator_bb_impl::packet_headergenerator_bb_impl( const gr::digital::packet_header_default::sptr &header_formatter, const std::string &len_tag_key ) : tagged_stream_block("packet_headergenerator_bb_impl", io_signature::make(1, 1, sizeof (char)), io_signature::make(1, 1, sizeof (char)), len_tag_key), d_formatter(header_formatter) { set_output_multiple(d_formatter->header_len()); // This is the worst case rate, because we don't know the true value, of course set_relative_rate(d_formatter->header_len()); set_tag_propagation_policy(TPP_DONT); } packet_headergenerator_bb_impl::~packet_headergenerator_bb_impl() { } int packet_headergenerator_bb_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned char *out = (unsigned char *) output_items[0]; if (!d_formatter->header_formatter(ninput_items[0], out)) { GR_LOG_FATAL(d_logger, boost::format("header_formatter() returned false (this shouldn't happen). Offending header started at %1%") % nitems_read(0)); throw std::runtime_error("header formatter returned false."); } return d_formatter->header_len(); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/cpmmod_bc_impl.cc0000664000175000017500000000617412207440367021405 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cpmmod_bc_impl.h" #include namespace gr { namespace digital { cpmmod_bc::sptr cpmmod_bc::make(analog::cpm::cpm_type type, float h, int samples_per_sym, int L, double beta) { return gnuradio::get_initial_sptr (new cpmmod_bc_impl("cpmmod_bc", (analog::cpm::cpm_type)type, h, samples_per_sym, L, beta)); } cpmmod_bc::sptr cpmmod_bc::make_gmskmod_bc(int samples_per_sym, int L, double beta) { return gnuradio::get_initial_sptr (new cpmmod_bc_impl("gmskmod_bc", analog::cpm::GAUSSIAN, 0.5, samples_per_sym, L, beta)); } cpmmod_bc_impl::cpmmod_bc_impl(const std::string &name, analog::cpm::cpm_type type, float h, int samples_per_sym, int L, double beta) : hier_block2(name, io_signature::make(1, 1, sizeof(char)), io_signature::make2(1, 1, sizeof(gr_complex), sizeof(float))), d_type(type), d_index(h), d_sps(samples_per_sym), d_length(L), d_beta(beta), d_taps(analog::cpm::phase_response(type, samples_per_sym, L, beta)), d_char_to_float(blocks::char_to_float::make()), d_pulse_shaper(filter::interp_fir_filter_fff::make(samples_per_sym, d_taps)), d_fm(analog::frequency_modulator_fc::make(M_PI * h)) { switch(type) { case analog::cpm::LRC: case analog::cpm::LSRC: case analog::cpm::LREC: case analog::cpm::TFM: case analog::cpm::GAUSSIAN: break; default: throw std::invalid_argument("cpmmod_bc_impl: invalid CPM type"); } connect(self(), 0, d_char_to_float, 0); connect(d_char_to_float, 0, d_pulse_shaper, 0); connect(d_pulse_shaper, 0, d_fm, 0); connect(d_fm, 0, self(), 0); } cpmmod_bc_impl::~cpmmod_bc_impl() { } std::vector cpmmod_bc_impl::taps() const { return d_taps; } int cpmmod_bc_impl::type() const { return d_type; } float cpmmod_bc_impl::index() const { return d_index; } int cpmmod_bc_impl::samples_per_sym() const { return d_sps; } int cpmmod_bc_impl::length() const { return d_length; } double cpmmod_bc_impl::beta() const { return d_beta; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_cyclic_prefixer_impl.h0000664000175000017500000000424212207440367023475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_CYCLIC_PREFIXER_IMPL_H #define INCLUDED_DIGITAL_OFDM_CYCLIC_PREFIXER_IMPL_H #include namespace gr { namespace digital { class ofdm_cyclic_prefixer_impl : public ofdm_cyclic_prefixer { private: size_t d_fft_len; //! FFT length + CP length in samples size_t d_output_size; //! Length of the cyclic prefix in samples int d_cp_size; //! Length of pulse rolloff in samples int d_rolloff_len; //! Buffers the up-flank (at the beginning of the cyclic prefix) std::vector d_up_flank; //! Buffers the down-flank (which trails the symbol) std::vector d_down_flank; std::vector d_delay_line; // We do this explicitly to avoid outputting zeroes (i.e. no history!) protected: int calculate_output_stream_length(const gr_vector_int &ninput_items); public: ofdm_cyclic_prefixer_impl(size_t input_size, size_t output_size, int rolloff_len, const std::string &len_tag_key); ~ofdm_cyclic_prefixer_impl(); int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_CYCLIC_PREFIXER_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/cma_equalizer_cc_impl.cc0000664000175000017500000000665312207440367022752 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cma_equalizer_cc_impl.h" #include namespace gr { namespace digital { using namespace filter::kernel; cma_equalizer_cc::sptr cma_equalizer_cc::make(int num_taps, float modulus, float mu, int sps) { return gnuradio::get_initial_sptr (new cma_equalizer_cc_impl(num_taps, modulus, mu, sps)); } cma_equalizer_cc_impl::cma_equalizer_cc_impl(int num_taps, float modulus, float mu, int sps) : sync_decimator("cma_equalizer_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), sps), fir_filter_ccc(sps, std::vector(num_taps, gr_complex(0,0))), d_new_taps(num_taps, gr_complex(0,0)), d_updated(false), d_error(gr_complex(0,0)) { set_modulus(modulus); set_gain(mu); if(num_taps > 0) d_new_taps[0] = 1.0; fir_filter_ccc::set_taps(d_new_taps); set_history(num_taps); } cma_equalizer_cc_impl::~cma_equalizer_cc_impl() { } void cma_equalizer_cc_impl::set_taps(const std::vector &taps) { d_new_taps = taps; d_updated = true; } std::vector cma_equalizer_cc_impl::taps() const { return d_taps; } gr_complex cma_equalizer_cc_impl::error(const gr_complex &out) { gr_complex error = out*(norm(out) - d_modulus); float re = gr::clip(error.real(), 1.0); float im = gr::clip(error.imag(), 1.0); return gr_complex(re, im); } void cma_equalizer_cc_impl::update_tap(gr_complex &tap, const gr_complex &in) { // Hn+1 = Hn - mu*conj(Xn)*zn*(|zn|^2 - 1) tap -= d_mu*conj(in)*d_error; } int cma_equalizer_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; if(d_updated) { d_taps = d_new_taps; set_history(d_taps.size()); d_updated = false; return 0; // history requirements may have changed. } int j = 0; size_t k, l = d_taps.size(); for(int i = 0; i < noutput_items; i++) { out[i] = filter(&in[j]); // Adjust taps d_error = error(out[i]); for(k = 0; k < l; k++) { // Update tap locally from error. update_tap(d_taps[k], in[j+k]); // Update aligned taps in filter object. fir_filter_ccc::update_tap(d_taps[k], k); } j += decimation(); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_mapper_bcv_impl.h0000664000175000017500000000415512207440367022444 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_MAPPER_BCV_IMPL_H #define INCLUDED_DIGITAL_OFDM_MAPPER_BCV_IMPL_H #include #include #include namespace gr { namespace digital { class ofdm_mapper_bcv_impl : public ofdm_mapper_bcv { private: std::vector d_constellation; msg_queue::sptr d_msgq; message::sptr d_msg; unsigned d_msg_offset; bool d_eof; unsigned int d_occupied_carriers; unsigned int d_fft_length; unsigned int d_bit_offset; int d_pending_flag; unsigned long d_nbits; unsigned char d_msgbytes; unsigned char d_resid; unsigned int d_nresid; std::vector d_subcarrier_map; int randsym(); public: ofdm_mapper_bcv_impl(const std::vector &constellation, unsigned msgq_limit, unsigned occupied_carriers, unsigned int fft_length); ~ofdm_mapper_bcv_impl(void); msg_queue::sptr msgq() const { return d_msgq; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_MAPPER_BCV_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/descrambler_bb_impl.h0000664000175000017500000000266712207440367022255 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DESCRAMBLER_BB_IMPL_H #define INCLUDED_GR_DESCRAMBLER_BB_IMPL_H #include #include namespace gr { namespace digital { class descrambler_bb_impl : public descrambler_bb { private: digital::lfsr d_lfsr; public: descrambler_bb_impl(int mask, int seed, int len); ~descrambler_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DESCRAMBLER_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/probe_density_b_impl.cc0000664000175000017500000000363512207440367022630 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "probe_density_b_impl.h" #include #include namespace gr { namespace digital { probe_density_b::sptr probe_density_b::make(double alpha) { return gnuradio::get_initial_sptr (new probe_density_b_impl(alpha)); } probe_density_b_impl::probe_density_b_impl(double alpha) : sync_block("density_b", io_signature::make(1, 1, sizeof(char)), io_signature::make(0, 0, 0)) { set_alpha(alpha); d_density = 1.0; } probe_density_b_impl::~probe_density_b_impl() { } void probe_density_b_impl::set_alpha(double alpha) { d_alpha = alpha; d_beta = 1.0-d_alpha; } int probe_density_b_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char *)input_items[0]; for(int i = 0; i < noutput_items; i++) d_density = d_alpha*(double)in[i] + d_beta*d_density; return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/crc32.cc0000664000175000017500000001174612207440367017356 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * See also ISO 3309 [ISO-3309] or ITU-T V.42 [ITU-V42] for a formal specification. */ #ifdef HAVE_CONFIG_H #include #endif #include namespace gr { namespace digital { // Automatically generated CRC function // polynomial: 0x104C11DB7 unsigned int update_crc32(unsigned int crc, const unsigned char *data, size_t len) { static const unsigned int table[256] = { 0x00000000U,0x04C11DB7U,0x09823B6EU,0x0D4326D9U, 0x130476DCU,0x17C56B6BU,0x1A864DB2U,0x1E475005U, 0x2608EDB8U,0x22C9F00FU,0x2F8AD6D6U,0x2B4BCB61U, 0x350C9B64U,0x31CD86D3U,0x3C8EA00AU,0x384FBDBDU, 0x4C11DB70U,0x48D0C6C7U,0x4593E01EU,0x4152FDA9U, 0x5F15ADACU,0x5BD4B01BU,0x569796C2U,0x52568B75U, 0x6A1936C8U,0x6ED82B7FU,0x639B0DA6U,0x675A1011U, 0x791D4014U,0x7DDC5DA3U,0x709F7B7AU,0x745E66CDU, 0x9823B6E0U,0x9CE2AB57U,0x91A18D8EU,0x95609039U, 0x8B27C03CU,0x8FE6DD8BU,0x82A5FB52U,0x8664E6E5U, 0xBE2B5B58U,0xBAEA46EFU,0xB7A96036U,0xB3687D81U, 0xAD2F2D84U,0xA9EE3033U,0xA4AD16EAU,0xA06C0B5DU, 0xD4326D90U,0xD0F37027U,0xDDB056FEU,0xD9714B49U, 0xC7361B4CU,0xC3F706FBU,0xCEB42022U,0xCA753D95U, 0xF23A8028U,0xF6FB9D9FU,0xFBB8BB46U,0xFF79A6F1U, 0xE13EF6F4U,0xE5FFEB43U,0xE8BCCD9AU,0xEC7DD02DU, 0x34867077U,0x30476DC0U,0x3D044B19U,0x39C556AEU, 0x278206ABU,0x23431B1CU,0x2E003DC5U,0x2AC12072U, 0x128E9DCFU,0x164F8078U,0x1B0CA6A1U,0x1FCDBB16U, 0x018AEB13U,0x054BF6A4U,0x0808D07DU,0x0CC9CDCAU, 0x7897AB07U,0x7C56B6B0U,0x71159069U,0x75D48DDEU, 0x6B93DDDBU,0x6F52C06CU,0x6211E6B5U,0x66D0FB02U, 0x5E9F46BFU,0x5A5E5B08U,0x571D7DD1U,0x53DC6066U, 0x4D9B3063U,0x495A2DD4U,0x44190B0DU,0x40D816BAU, 0xACA5C697U,0xA864DB20U,0xA527FDF9U,0xA1E6E04EU, 0xBFA1B04BU,0xBB60ADFCU,0xB6238B25U,0xB2E29692U, 0x8AAD2B2FU,0x8E6C3698U,0x832F1041U,0x87EE0DF6U, 0x99A95DF3U,0x9D684044U,0x902B669DU,0x94EA7B2AU, 0xE0B41DE7U,0xE4750050U,0xE9362689U,0xEDF73B3EU, 0xF3B06B3BU,0xF771768CU,0xFA325055U,0xFEF34DE2U, 0xC6BCF05FU,0xC27DEDE8U,0xCF3ECB31U,0xCBFFD686U, 0xD5B88683U,0xD1799B34U,0xDC3ABDEDU,0xD8FBA05AU, 0x690CE0EEU,0x6DCDFD59U,0x608EDB80U,0x644FC637U, 0x7A089632U,0x7EC98B85U,0x738AAD5CU,0x774BB0EBU, 0x4F040D56U,0x4BC510E1U,0x46863638U,0x42472B8FU, 0x5C007B8AU,0x58C1663DU,0x558240E4U,0x51435D53U, 0x251D3B9EU,0x21DC2629U,0x2C9F00F0U,0x285E1D47U, 0x36194D42U,0x32D850F5U,0x3F9B762CU,0x3B5A6B9BU, 0x0315D626U,0x07D4CB91U,0x0A97ED48U,0x0E56F0FFU, 0x1011A0FAU,0x14D0BD4DU,0x19939B94U,0x1D528623U, 0xF12F560EU,0xF5EE4BB9U,0xF8AD6D60U,0xFC6C70D7U, 0xE22B20D2U,0xE6EA3D65U,0xEBA91BBCU,0xEF68060BU, 0xD727BBB6U,0xD3E6A601U,0xDEA580D8U,0xDA649D6FU, 0xC423CD6AU,0xC0E2D0DDU,0xCDA1F604U,0xC960EBB3U, 0xBD3E8D7EU,0xB9FF90C9U,0xB4BCB610U,0xB07DABA7U, 0xAE3AFBA2U,0xAAFBE615U,0xA7B8C0CCU,0xA379DD7BU, 0x9B3660C6U,0x9FF77D71U,0x92B45BA8U,0x9675461FU, 0x8832161AU,0x8CF30BADU,0x81B02D74U,0x857130C3U, 0x5D8A9099U,0x594B8D2EU,0x5408ABF7U,0x50C9B640U, 0x4E8EE645U,0x4A4FFBF2U,0x470CDD2BU,0x43CDC09CU, 0x7B827D21U,0x7F436096U,0x7200464FU,0x76C15BF8U, 0x68860BFDU,0x6C47164AU,0x61043093U,0x65C52D24U, 0x119B4BE9U,0x155A565EU,0x18197087U,0x1CD86D30U, 0x029F3D35U,0x065E2082U,0x0B1D065BU,0x0FDC1BECU, 0x3793A651U,0x3352BBE6U,0x3E119D3FU,0x3AD08088U, 0x2497D08DU,0x2056CD3AU,0x2D15EBE3U,0x29D4F654U, 0xC5A92679U,0xC1683BCEU,0xCC2B1D17U,0xC8EA00A0U, 0xD6AD50A5U,0xD26C4D12U,0xDF2F6BCBU,0xDBEE767CU, 0xE3A1CBC1U,0xE760D676U,0xEA23F0AFU,0xEEE2ED18U, 0xF0A5BD1DU,0xF464A0AAU,0xF9278673U,0xFDE69BC4U, 0x89B8FD09U,0x8D79E0BEU,0x803AC667U,0x84FBDBD0U, 0x9ABC8BD5U,0x9E7D9662U,0x933EB0BBU,0x97FFAD0CU, 0xAFB010B1U,0xAB710D06U,0xA6322BDFU,0xA2F33668U, 0xBCB4666DU,0xB8757BDAU,0xB5365D03U,0xB1F740B4U, }; while(len > 0) { crc = table[*data ^ ((crc >> 24) & 0xff)] ^ (crc << 8); data++; len--; } return crc; } unsigned int update_crc32(unsigned int crc, const std::string s) { return update_crc32(crc, (const unsigned char *)s.data(), s.size()); } unsigned int crc32(const unsigned char *buf, size_t len) { return update_crc32(0xffffffff, buf, len) ^ 0xffffffff; } unsigned int crc32(const std::string s) { return crc32((const unsigned char *) s.data(), s.size()); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/lms_dd_equalizer_cc_impl.cc0000664000175000017500000000712012207440367023442 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "lms_dd_equalizer_cc_impl.h" #include #include #include namespace gr { namespace digital { using namespace filter::kernel; lms_dd_equalizer_cc::sptr lms_dd_equalizer_cc::make(int num_taps, float mu, int sps, constellation_sptr cnst) { return gnuradio::get_initial_sptr (new lms_dd_equalizer_cc_impl(num_taps, mu, sps, cnst)); } lms_dd_equalizer_cc_impl::lms_dd_equalizer_cc_impl(int num_taps, float mu, int sps, constellation_sptr cnst) : sync_decimator("lms_dd_equalizer_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), sps), fir_filter_ccc(sps, std::vector(num_taps, gr_complex(0,0))), d_new_taps(num_taps, gr_complex(0,0)), d_updated(false), d_cnst(cnst) { set_gain(mu); if(num_taps > 0) d_new_taps[0] = 1.0; fir_filter_ccc::set_taps(d_new_taps); const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); set_history(num_taps); } lms_dd_equalizer_cc_impl::~lms_dd_equalizer_cc_impl() { } void lms_dd_equalizer_cc_impl::set_taps(const std::vector &taps) { d_new_taps = taps; d_updated = true; } std::vector lms_dd_equalizer_cc_impl::taps() const { return d_taps; } gr_complex lms_dd_equalizer_cc_impl::error(const gr_complex &out) { gr_complex decision, error; d_cnst->map_to_points(d_cnst->decision_maker(&out), &decision); error = decision - out; return error; } void lms_dd_equalizer_cc_impl::update_tap(gr_complex &tap, const gr_complex &in) { tap += d_mu*conj(in)*d_error; } int lms_dd_equalizer_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; if(d_updated) { d_taps = d_new_taps; set_history(d_taps.size()); d_updated = false; return 0; // history requirements may have changed. } int j = 0; size_t k, l = d_taps.size(); for(int i = 0; i < noutput_items; i++) { out[i] = filter(&in[j]); // Adjust taps d_error = error(out[i]); for(k = 0; k < l; k++) { // Update tap locally from error. update_tap(d_taps[k], in[j+k]); // Update aligned taps in filter object. fir_filter_ccc::update_tap(d_taps[k], k); } j += decimation(); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_equalizer_static.cc0000664000175000017500000000541112207440367023007 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { namespace digital { ofdm_equalizer_static::sptr ofdm_equalizer_static::make( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, int symbols_skipped, bool input_is_shifted) { return ofdm_equalizer_static::sptr( new ofdm_equalizer_static( fft_len, occupied_carriers, pilot_carriers, pilot_symbols, symbols_skipped, input_is_shifted ) ); } ofdm_equalizer_static::ofdm_equalizer_static( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, int symbols_skipped, bool input_is_shifted) : ofdm_equalizer_1d_pilots(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, symbols_skipped, input_is_shifted) { } ofdm_equalizer_static::~ofdm_equalizer_static() { } void ofdm_equalizer_static::equalize(gr_complex *frame, int n_sym, const std::vector &initial_taps, const std::vector &tags) { d_channel_state = initial_taps; for (int i = 0; i < n_sym; i++) { for (int k = 0; k < d_fft_len; k++) { if (!d_occupied_carriers[k]) { continue; } if (!d_pilot_carriers.empty() && d_pilot_carriers[d_pilot_carr_set][k]) { d_channel_state[k] = frame[i*d_fft_len + k] / d_pilot_symbols[d_pilot_carr_set][k]; frame[i*d_fft_len+k] = d_pilot_symbols[d_pilot_carr_set][k]; } else { frame[i*d_fft_len+k] /= d_channel_state[k]; } } if (!d_pilot_carriers.empty()) { d_pilot_carr_set = (d_pilot_carr_set + 1) % d_pilot_carriers.size(); } } } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/simple_framer_impl.h0000664000175000017500000000315612207440367022146 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SIMPLE_FRAMER_IMPL_H #define INCLUDED_GR_SIMPLE_FRAMER_IMPL_H #include namespace gr { namespace digital { class simple_framer_impl : public simple_framer { private: int d_seqno; int d_payload_bytesize; int d_input_block_size; // bytes int d_output_block_size; // bytes public: simple_framer_impl(int payload_bytesize); ~simple_framer_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SIMPLE_FRAMER_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/mpsk_receiver_cc_impl.cc0000664000175000017500000002371612207440367022766 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2007,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "mpsk_receiver_cc_impl.h" #include #include #include #include namespace gr { namespace digital { #define M_TWOPI (2*M_PI) #define VERBOSE_MM 0 // Used for debugging symbol timing loop #define VERBOSE_COSTAS 0 // Used for debugging phase and frequency tracking mpsk_receiver_cc::sptr mpsk_receiver_cc::make(unsigned int M, float theta, float loop_bw, float fmin, float fmax, float mu, float gain_mu, float omega, float gain_omega, float omega_rel) { return gnuradio::get_initial_sptr (new mpsk_receiver_cc_impl(M, theta, loop_bw, fmin, fmax, mu, gain_mu, omega, gain_omega, omega_rel)); } mpsk_receiver_cc_impl::mpsk_receiver_cc_impl(unsigned int M, float theta, float loop_bw, float fmin, float fmax, float mu, float gain_mu, float omega, float gain_omega, float omega_rel) : block("mpsk_receiver_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), blocks::control_loop(loop_bw, fmax, fmin), d_M(M), d_theta(theta), d_current_const_point(0), d_mu(mu), d_gain_mu(gain_mu), d_gain_omega(gain_omega), d_omega_rel(omega_rel), d_max_omega(0), d_min_omega(0), d_p_2T(0), d_p_1T(0), d_p_0T(0), d_c_2T(0), d_c_1T(0), d_c_0T(0) { d_interp = new gr::filter::mmse_fir_interpolator_cc(); d_dl_idx = 0; set_omega(omega); if(omega <= 0.0) throw std::out_of_range("clock rate must be > 0"); if(gain_mu < 0 || gain_omega < 0) throw std::out_of_range("Gains must be non-negative"); assert(d_interp->ntaps() <= DLLEN); // zero double length delay line. for(unsigned int i = 0; i < 2 * DLLEN; i++) d_dl[i] = gr_complex(0.0,0.0); set_modulation_order(d_M); } mpsk_receiver_cc_impl::~mpsk_receiver_cc_impl() { delete d_interp; } void mpsk_receiver_cc_impl::set_modulation_order(unsigned int M) { // build the constellation vector from M make_constellation(); // Select a phase detector and a decision maker for the modulation order switch(d_M) { case 2: // optimized algorithms for BPSK d_phase_error_detector = &mpsk_receiver_cc_impl::phase_error_detector_bpsk; //bpsk; d_decision = &mpsk_receiver_cc_impl::decision_bpsk; break; case 4: // optimized algorithms for QPSK d_phase_error_detector = &mpsk_receiver_cc_impl::phase_error_detector_qpsk; //qpsk; d_decision = &mpsk_receiver_cc_impl::decision_qpsk; break; default: // generic algorithms for any M (power of 2?) but not pretty d_phase_error_detector = &mpsk_receiver_cc_impl::phase_error_detector_generic; d_decision = &mpsk_receiver_cc_impl::decision_generic; break; } } void mpsk_receiver_cc_impl::set_gain_omega_rel(float omega_rel) { d_omega_rel = omega_rel; set_omega(d_omega); } void mpsk_receiver_cc_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) ninput_items_required[i] = (int) ceil((noutput_items * d_omega) + d_interp->ntaps()); } // FIXME add these back in an test difference in performance float mpsk_receiver_cc_impl::phase_error_detector_qpsk(gr_complex sample) const { float phase_error = 0; if(fabsf(sample.real()) > fabsf(sample.imag())) { if(sample.real() > 0) phase_error = -sample.imag(); else phase_error = sample.imag(); } else { if(sample.imag() > 0) phase_error = sample.real(); else phase_error = -sample.real(); } return phase_error; } float mpsk_receiver_cc_impl::phase_error_detector_bpsk(gr_complex sample) const { return -(sample.real()*sample.imag()); } float mpsk_receiver_cc_impl::phase_error_detector_generic(gr_complex sample) const { //return gr::fast_atan2f(sample*conj(d_constellation[d_current_const_point])); return -arg(sample*conj(d_constellation[d_current_const_point])); } unsigned int mpsk_receiver_cc_impl::decision_bpsk(gr_complex sample) const { return (gr::branchless_binary_slicer(sample.real()) ^ 1); //return gr_binary_slicer(sample.real()) ^ 1; } unsigned int mpsk_receiver_cc_impl::decision_qpsk(gr_complex sample) const { unsigned int index; //index = gr::branchless_quad_0deg_slicer(sample); index = gr::quad_0deg_slicer(sample); return index; } unsigned int mpsk_receiver_cc_impl::decision_generic(gr_complex sample) const { unsigned int min_m = 0; float min_s = 65535; // Develop all possible constellation points and find the one that minimizes // the Euclidean distance (error) with the sample for(unsigned int m = 0; m < d_M; m++) { gr_complex diff = norm(d_constellation[m] - sample); if(fabs(diff.real()) < min_s) { min_s = fabs(diff.real()); min_m = m; } } // Return the index of the constellation point that minimizes the error return min_m; } void mpsk_receiver_cc_impl::make_constellation() { for(unsigned int m = 0; m < d_M; m++) { d_constellation.push_back(gr_expj((M_TWOPI/d_M)*m)); } } void mpsk_receiver_cc_impl::mm_sampler(const gr_complex symbol) { gr_complex sample, nco; d_mu--; // skip a number of symbols between sampling d_phase += d_freq; // increment the phase based on the frequency of the rotation // Keep phase clamped and not walk to infinity while(d_phase > M_TWOPI) d_phase -= M_TWOPI; while(d_phase < -M_TWOPI) d_phase += M_TWOPI; nco = gr_expj(d_phase+d_theta); // get the NCO value for derotating the current sample sample = nco*symbol; // get the downconverted symbol // Fill up the delay line for the interpolator d_dl[d_dl_idx] = sample; d_dl[(d_dl_idx + DLLEN)] = sample; // put this in the second half of the buffer for overflows d_dl_idx = (d_dl_idx+1) % DLLEN; // Keep the delay line index in bounds } void mpsk_receiver_cc_impl::mm_error_tracking(gr_complex sample) { gr_complex u, x, y; float mm_error = 0; // Make sample timing corrections // set the delayed samples d_p_2T = d_p_1T; d_p_1T = d_p_0T; d_p_0T = sample; d_c_2T = d_c_1T; d_c_1T = d_c_0T; d_current_const_point = (*this.*d_decision)(d_p_0T); // make a decision on the sample value d_c_0T = d_constellation[d_current_const_point]; x = (d_c_0T - d_c_2T) * conj(d_p_1T); y = (d_p_0T - d_p_2T) * conj(d_c_1T); u = y - x; mm_error = u.real(); // the error signal is in the real part mm_error = gr::branchless_clip(mm_error, 1.0); // limit mm_val d_omega = d_omega + d_gain_omega * mm_error; // update omega based on loop error d_omega = d_omega_mid + gr::branchless_clip(d_omega-d_omega_mid, d_omega_rel); // make sure we don't walk away d_mu += d_omega + d_gain_mu * mm_error; // update mu based on loop error #if VERBOSE_MM printf("mm: mu: %f omega: %f mm_error: %f sample: %f+j%f constellation: %f+j%f\n", d_mu, d_omega, mm_error, sample.real(), sample.imag(), d_constellation[d_current_const_point].real(), d_constellation[d_current_const_point].imag()); #endif } void mpsk_receiver_cc_impl::phase_error_tracking(gr_complex sample) { float phase_error = 0; // Make phase and frequency corrections based on sampled value phase_error = (*this.*d_phase_error_detector)(sample); advance_loop(phase_error); phase_wrap(); frequency_limit(); #if VERBOSE_COSTAS printf("cl: phase_error: %f phase: %f freq: %f sample: %f+j%f constellation: %f+j%f\n", phase_error, d_phase, d_freq, sample.real(), sample.imag(), d_constellation[d_current_const_point].real(), d_constellation[d_current_const_point].imag()); #endif } int mpsk_receiver_cc_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; int i=0, o=0; while((o < noutput_items) && (i < ninput_items[0])) { while((d_mu > 1) && (i < ninput_items[0])) { mm_sampler(in[i]); // puts symbols into a buffer and adjusts d_mu i++; } if(i < ninput_items[0]) { gr_complex interp_sample = d_interp->interpolate(&d_dl[d_dl_idx], d_mu); mm_error_tracking(interp_sample); // corrects M&M sample time phase_error_tracking(interp_sample); // corrects phase and frequency offsets out[o++] = interp_sample; } } #if 0 printf("ninput_items: %d noutput_items: %d consuming: %d returning: %d\n", ninput_items[0], noutput_items, i, o); #endif consume_each(i); return o; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/packet_header_ofdm.cc0000664000175000017500000001114312237515112022207 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { namespace digital { int _get_header_len_from_occupied_carriers(const std::vector > &occupied_carriers, int n_syms) { int header_len = 0; for (int i = 0; i < n_syms; i++) { header_len += occupied_carriers[i].size(); } return header_len; } packet_header_ofdm::sptr packet_header_ofdm::make( const std::vector > &occupied_carriers, int n_syms, const std::string &len_tag_key, const std::string &frame_len_tag_key, const std::string &num_tag_key, int bits_per_header_sym, int bits_per_payload_sym, bool scramble_header) { return packet_header_ofdm::sptr( new packet_header_ofdm( occupied_carriers, n_syms, len_tag_key, frame_len_tag_key, num_tag_key, bits_per_header_sym, bits_per_payload_sym, scramble_header ) ); } packet_header_ofdm::packet_header_ofdm( const std::vector > &occupied_carriers, int n_syms, const std::string &len_tag_key, const std::string &frame_len_tag_key, const std::string &num_tag_key, int bits_per_header_sym, int bits_per_payload_sym, bool scramble_header ) : packet_header_default( _get_header_len_from_occupied_carriers(occupied_carriers, n_syms), len_tag_key, num_tag_key, bits_per_header_sym), d_frame_len_tag_key(pmt::string_to_symbol(frame_len_tag_key)), d_occupied_carriers(occupied_carriers), d_syms_per_set(0), d_bits_per_payload_sym(bits_per_payload_sym), d_scramble_mask(d_header_len, 0) { for (unsigned i = 0; i < d_occupied_carriers.size(); i++) { d_syms_per_set += d_occupied_carriers[i].size(); } // Init scrambler mask if (scramble_header) { // These are just random values which already have OK PAPR: gr::digital::lfsr shift_reg(0x8a, 0x6f, 7); for (int i = 0; i < d_header_len; i++) { for (int k = 0; k < bits_per_header_sym; k++) { d_scramble_mask[i] ^= shift_reg.next_bit() << k; } } } } packet_header_ofdm::~packet_header_ofdm() { } bool packet_header_ofdm::header_formatter(long packet_len, unsigned char *out, const std::vector &tags) { bool ret_val = packet_header_default::header_formatter(packet_len, out, tags); for (int i = 0; i < d_header_len; i++) { out[i] ^= d_scramble_mask[i]; } return ret_val; } bool packet_header_ofdm::header_parser( const unsigned char *in, std::vector &tags) { std::vector in_descrambled(d_header_len, 0); for (int i = 0; i < d_header_len; i++) { in_descrambled[i] = in[i] ^ d_scramble_mask[i]; } if (!packet_header_default::header_parser(&in_descrambled[0], tags)) { return false; } int packet_len = 0; // # of bytes in this frame for (unsigned i = 0; i < tags.size(); i++) { if (pmt::equal(tags[i].key, d_len_tag_key)) { // Convert bytes to complex symbols: packet_len = pmt::to_long(tags[i].value) * 8 / d_bits_per_payload_sym; if (pmt::to_long(tags[i].value) * 8 % d_bits_per_payload_sym) { packet_len++; } tags[i].value = pmt::from_long(packet_len); break; } } // frame_len == # of OFDM symbols in this frame int frame_len = packet_len / d_syms_per_set; int k = 0; int i = frame_len * d_syms_per_set; while (i < packet_len) { frame_len++; i += d_occupied_carriers[k].size(); } tag_t tag; tag.key = d_frame_len_tag_key; tag.value = pmt::from_long(frame_len); tags.push_back(tag); return true; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_frame_sink_impl.cc0000664000175000017500000002754612207440367022613 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2008,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ofdm_frame_sink_impl.h" #include #include #include #include #include #include #include #include namespace gr { namespace digital { #define VERBOSE 0 inline void ofdm_frame_sink_impl::enter_search() { if(VERBOSE) fprintf(stderr, "@ enter_search\n"); d_state = STATE_SYNC_SEARCH; } inline void ofdm_frame_sink_impl::enter_have_sync() { if(VERBOSE) fprintf(stderr, "@ enter_have_sync\n"); d_state = STATE_HAVE_SYNC; // clear state of demapper d_byte_offset = 0; d_partial_byte = 0; d_header = 0; d_headerbytelen_cnt = 0; // Resetting PLL d_freq = 0.0; d_phase = 0.0; fill(d_dfe.begin(), d_dfe.end(), gr_complex(1.0,0.0)); } inline void ofdm_frame_sink_impl::enter_have_header() { d_state = STATE_HAVE_HEADER; // header consists of two 16-bit shorts in network byte order // payload length is lower 12 bits // whitener offset is upper 4 bits d_packetlen = (d_header >> 16) & 0x0fff; d_packet_whitener_offset = (d_header >> 28) & 0x000f; d_packetlen_cnt = 0; if(VERBOSE) fprintf(stderr, "@ enter_have_header (payload_len = %d) (offset = %d)\n", d_packetlen, d_packet_whitener_offset); } char ofdm_frame_sink_impl::slicer(const gr_complex x) { unsigned int table_size = d_sym_value_out.size(); unsigned int min_index = 0; float min_euclid_dist = norm(x - d_sym_position[0]); float euclid_dist = 0; for(unsigned int j = 1; j < table_size; j++){ euclid_dist = norm(x - d_sym_position[j]); if(euclid_dist < min_euclid_dist){ min_euclid_dist = euclid_dist; min_index = j; } } return d_sym_value_out[min_index]; } unsigned int ofdm_frame_sink_impl::demapper(const gr_complex *in, char *out) { unsigned int i=0, bytes_produced=0; gr_complex carrier; carrier = gr_expj(d_phase); gr_complex accum_error = 0.0; //while(i < d_occupied_carriers) { while(i < d_subcarrier_map.size()) { if(d_nresid > 0) { d_partial_byte |= d_resid; d_byte_offset += d_nresid; d_nresid = 0; d_resid = 0; } //while((d_byte_offset < 8) && (i < d_occupied_carriers)) { while((d_byte_offset < 8) && (i < d_subcarrier_map.size())) { //gr_complex sigrot = in[i]*carrier*d_dfe[i]; gr_complex sigrot = in[d_subcarrier_map[i]]*carrier*d_dfe[i]; if(d_derotated_output != NULL){ d_derotated_output[i] = sigrot; } char bits = slicer(sigrot); gr_complex closest_sym = d_sym_position[bits]; accum_error += sigrot * conj(closest_sym); // FIX THE FOLLOWING STATEMENT if(norm(sigrot)> 0.001) d_dfe[i] += d_eq_gain*(closest_sym/sigrot-d_dfe[i]); i++; if((8 - d_byte_offset) >= d_nbits) { d_partial_byte |= bits << (d_byte_offset); d_byte_offset += d_nbits; } else { d_nresid = d_nbits-(8-d_byte_offset); int mask = ((1<<(8-d_byte_offset))-1); d_partial_byte |= (bits & mask) << d_byte_offset; d_resid = bits >> (8-d_byte_offset); d_byte_offset += (d_nbits - d_nresid); } //printf("demod symbol: %.4f + j%.4f bits: %x partial_byte: %x byte_offset: %d resid: %x nresid: %d\n", // in[i-1].real(), in[i-1].imag(), bits, d_partial_byte, d_byte_offset, d_resid, d_nresid); } if(d_byte_offset == 8) { //printf("demod byte: %x \n\n", d_partial_byte); out[bytes_produced++] = d_partial_byte; d_byte_offset = 0; d_partial_byte = 0; } } //std::cerr << "accum_error " << accum_error << std::endl; float angle = arg(accum_error); d_freq = d_freq - d_freq_gain*angle; d_phase = d_phase + d_freq - d_phase_gain*angle; if(d_phase >= 2*M_PI) d_phase -= 2*M_PI; if(d_phase <0) d_phase += 2*M_PI; //if(VERBOSE) // std::cerr << angle << "\t" << d_freq << "\t" << d_phase << "\t" << std::endl; return bytes_produced; } ofdm_frame_sink::sptr ofdm_frame_sink::make(const std::vector &sym_position, const std::vector &sym_value_out, msg_queue::sptr target_queue, int occupied_carriers, float phase_gain, float freq_gain) { return gnuradio::get_initial_sptr (new ofdm_frame_sink_impl(sym_position, sym_value_out, target_queue, occupied_carriers, phase_gain, freq_gain)); } ofdm_frame_sink_impl::ofdm_frame_sink_impl(const std::vector &sym_position, const std::vector &sym_value_out, msg_queue::sptr target_queue, int occupied_carriers, float phase_gain, float freq_gain) : sync_block("ofdm_frame_sink", io_signature::make2(2, 2, sizeof(gr_complex)*occupied_carriers, sizeof(char)), io_signature::make(1, 1, sizeof(gr_complex)*occupied_carriers)), d_target_queue(target_queue), d_occupied_carriers(occupied_carriers), d_byte_offset(0), d_partial_byte(0), d_resid(0), d_nresid(0),d_phase(0),d_freq(0), d_phase_gain(phase_gain),d_freq_gain(freq_gain), d_eq_gain(0.05) { std::string carriers = "FE7F"; // A bit hacky to fill out carriers to occupied_carriers length int diff = (d_occupied_carriers - 4*carriers.length()); while(diff > 7) { carriers.insert(0, "f"); carriers.insert(carriers.length(), "f"); diff -= 8; } // if there's extras left to be processed // divide remaining to put on either side of current map // all of this is done to stick with the concept of a carrier map string that // can be later passed by the user, even though it'd be cleaner to just do this // on the carrier map itself int diff_left=0; int diff_right=0; // dictionary to convert from integers to ascii hex representation char abc[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; if(diff > 0) { char c[2] = {0,0}; diff_left = (int)ceil((float)diff/2.0f); // number of carriers to put on the left side c[0] = abc[(1 << diff_left) - 1]; // convert to bits and move to ASCI integer carriers.insert(0, c); diff_right = diff - diff_left; // number of carriers to put on the right side c[0] = abc[0xF^((1 << diff_right) - 1)]; // convert to bits and move to ASCI integer carriers.insert(carriers.length(), c); } // It seemed like such a good idea at the time... // because we are only dealing with the occupied_carriers // at this point, the diff_left in the following compensates // for any offset from the 0th carrier introduced int i; unsigned int j,k; for(i = 0; i < (d_occupied_carriers/4)+diff_left; i++) { char c = carriers[i]; for(j = 0; j < 4; j++) { k = (strtol(&c, NULL, 16) >> (3-j)) & 0x1; if(k) { d_subcarrier_map.push_back(4*i + j - diff_left); } } } // make sure we stay in the limit currently imposed by the occupied_carriers if(d_subcarrier_map.size() > (size_t)d_occupied_carriers) { throw std::invalid_argument("ofdm_frame_sink_impl: subcarriers allocated exceeds size of occupied carriers"); } d_bytes_out = new char[d_occupied_carriers]; d_dfe.resize(occupied_carriers); fill(d_dfe.begin(), d_dfe.end(), gr_complex(1.0,0.0)); set_sym_value_out(sym_position, sym_value_out); enter_search(); } ofdm_frame_sink_impl::~ofdm_frame_sink_impl() { delete [] d_bytes_out; } bool ofdm_frame_sink_impl::set_sym_value_out(const std::vector &sym_position, const std::vector &sym_value_out) { if(sym_position.size() != sym_value_out.size()) return false; if(sym_position.size()<1) return false; d_sym_position = sym_position; d_sym_value_out = sym_value_out; d_nbits = (unsigned long)ceil(log10(float(d_sym_value_out.size())) / log10(2.0)); return true; } int ofdm_frame_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; const char *sig = (const char*)input_items[1]; unsigned int j = 0; unsigned int bytes=0; // If the output is connected, send it the derotated symbols if(output_items.size() >= 1) d_derotated_output = (gr_complex *)output_items[0]; else d_derotated_output = NULL; if(VERBOSE) fprintf(stderr,">>> Entering state machine\n"); switch(d_state) { case STATE_SYNC_SEARCH: // Look for flag indicating beginning of pkt if(VERBOSE) fprintf(stderr,"SYNC Search, noutput=%d\n", noutput_items); if(sig[0]) { // Found it, set up for header decode enter_have_sync(); } break; case STATE_HAVE_SYNC: // only demod after getting the preamble signal; otherwise, the // equalizer taps will screw with the PLL performance bytes = demapper(&in[0], d_bytes_out); if(VERBOSE) { if(sig[0]) printf("ERROR -- Found SYNC in HAVE_SYNC\n"); fprintf(stderr,"Header Search bitcnt=%d, header=0x%08x\n", d_headerbytelen_cnt, d_header); } j = 0; while(j < bytes) { d_header = (d_header << 8) | (d_bytes_out[j] & 0xFF); j++; if(++d_headerbytelen_cnt == HEADERBYTELEN) { if(VERBOSE) fprintf(stderr, "got header: 0x%08x\n", d_header); // we have a full header, check to see if it has been received properly if(header_ok()) { enter_have_header(); if(VERBOSE) printf("\nPacket Length: %d\n", d_packetlen); while((j < bytes) && (d_packetlen_cnt < d_packetlen)) { d_packet[d_packetlen_cnt++] = d_bytes_out[j++]; } if(d_packetlen_cnt == d_packetlen) { message::sptr msg = message::make(0, d_packet_whitener_offset, 0, d_packetlen); memcpy(msg->msg(), d_packet, d_packetlen_cnt); d_target_queue->insert_tail(msg); // send it msg.reset(); // free it up enter_search(); } } else { enter_search(); // bad header } } } break; case STATE_HAVE_HEADER: bytes = demapper(&in[0], d_bytes_out); if(VERBOSE) { if(sig[0]) printf("ERROR -- Found SYNC in HAVE_HEADER at %d, length of %d\n", d_packetlen_cnt, d_packetlen); fprintf(stderr,"Packet Build\n"); } j = 0; while(j < bytes) { d_packet[d_packetlen_cnt++] = d_bytes_out[j++]; if (d_packetlen_cnt == d_packetlen){ // packet is filled // build a message // NOTE: passing header field as arg1 is not scalable message::sptr msg = message::make(0, d_packet_whitener_offset, 0, d_packetlen_cnt); memcpy(msg->msg(), d_packet, d_packetlen_cnt); d_target_queue->insert_tail(msg); // send it msg.reset(); // free it up enter_search(); break; } } break; default: assert(0); } // switch return 1; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/correlate_and_sync_cc_impl.cc0000664000175000017500000001305312237515112023751 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "correlate_and_sync_cc_impl.h" #include #include #include #include #include namespace gr { namespace digital { correlate_and_sync_cc::sptr correlate_and_sync_cc::make(const std::vector &symbols, const std::vector &filter, unsigned int sps, unsigned int nfilts) { return gnuradio::get_initial_sptr (new correlate_and_sync_cc_impl(symbols, filter, sps, nfilts)); } correlate_and_sync_cc_impl::correlate_and_sync_cc_impl(const std::vector &symbols, const std::vector &filter, unsigned int sps, unsigned int nfilts) : sync_block("correlate_and_sync_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(2, 2, sizeof(gr_complex))) { d_last_index = 0; d_sps = sps; // We want to add padding to the beginning of the symbols so we // can do the convolution of the symbols with the pulse shape. std::vector padding((1+filter.size()/nfilts)/2, 0); std::vector padded_symbols = symbols; padded_symbols.insert(padded_symbols.begin(), padding.begin(), padding.end()); d_symbols.resize(d_sps*symbols.size(), 0); filter::kernel::pfb_arb_resampler_ccf resamp(d_sps, filter, nfilts); int nread; resamp.filter(&d_symbols[0], &padded_symbols[0], symbols.size(), nread); std::reverse(d_symbols.begin(), d_symbols.end()); float corr = 0; for(size_t i=0; i < d_symbols.size(); i++) corr += abs(d_symbols[i]*conj(d_symbols[i])); d_thresh = 0.9*corr*corr; d_center_first_symbol = (padding.size() + 0.5) * d_sps; //d_filter = new kernel::fft_filter_ccc(1, d_symbols); d_filter = new kernel::fir_filter_ccc(1, d_symbols); set_history(d_filter->ntaps()); const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); } correlate_and_sync_cc_impl::~correlate_and_sync_cc_impl() { delete d_filter; } std::vector correlate_and_sync_cc_impl::symbols() const { return d_symbols; } void correlate_and_sync_cc_impl::set_symbols(const std::vector &symbols) { gr::thread::scoped_lock lock(d_setlock); d_symbols = symbols; d_filter->set_taps(symbols); set_history(d_filter->ntaps()); } int correlate_and_sync_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock lock(d_setlock); const gr_complex *in = (gr_complex *)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; gr_complex *corr = (gr_complex*)output_items[1]; memcpy(out, in, sizeof(gr_complex)*noutput_items); // Calculate the correlation with the known symbol //d_filter->filter(noutput_items, in, corr); d_filter->filterN(corr, in, noutput_items); // Find the magnitude squared of the correlation std::vector corr_mag(noutput_items); volk_32fc_magnitude_squared_32f(&corr_mag[0], corr, noutput_items); int i = d_sps; while(i < noutput_items) { if((corr_mag[i] - corr_mag[i-d_sps]) > d_thresh) { while(corr_mag[i] < corr_mag[i+1]) i++; double nom = 0, den = 0; for(int s = 0; s < 3; s++) { nom += (s+1)*corr_mag[i+s-1]; den += corr_mag[i+s-1]; } double center = nom / den; center = (center - 2.0); int index = i; float phase = fast_atan2f(corr[index].imag(), corr[index].real()); add_item_tag(0, nitems_written(0) + index, pmt::intern("phase_est"), pmt::from_double(phase), pmt::intern(alias())); add_item_tag(0, nitems_written(0) + index, pmt::intern("time_est"), pmt::from_double(center), pmt::intern(alias())); add_item_tag(0, nitems_written(0) + index, pmt::intern("corr_est"), pmt::from_double(corr_mag[index]), pmt::intern(alias())); i += d_sps; } else i++; } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/glfsr.cc0000664000175000017500000000513112207440367017546 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include namespace gr { namespace digital { static int s_polynomial_masks[] = { 0x00000000, 0x00000001, // x^1 + 1 0x00000003, // x^2 + x^1 + 1 0x00000005, // x^3 + x^1 + 1 0x00000009, // x^4 + x^1 + 1 0x00000012, // x^5 + x^2 + 1 0x00000021, // x^6 + x^1 + 1 0x00000041, // x^7 + x^1 + 1 0x0000008E, // x^8 + x^4 + x^3 + x^2 + 1 0x00000108, // x^9 + x^4 + 1 0x00000204, // x^10 + x^4 + 1 0x00000402, // x^11 + x^2 + 1 0x00000829, // x^12 + x^6 + x^4 + x^1 + 1 0x0000100D, // x^13 + x^4 + x^3 + x^1 + 1 0x00002015, // x^14 + x^5 + x^3 + x^1 + 1 0x00004001, // x^15 + x^1 + 1 0x00008016, // x^16 + x^5 + x^3 + x^2 + 1 0x00010004, // x^17 + x^3 + 1 0x00020013, // x^18 + x^5 + x^2 + x^1 + 1 0x00040013, // x^19 + x^5 + x^2 + x^1 + 1 0x00080004, // x^20 + x^3 + 1 0x00100002, // x^21 + x^2 + 1 0x00200001, // x^22 + x^1 + 1 0x00400010, // x^23 + x^5 + 1 0x0080000D, // x^24 + x^4 + x^3 + x^1 + 1 0x01000004, // x^25 + x^3 + 1 0x02000023, // x^26 + x^6 + x^2 + x^1 + 1 0x04000013, // x^27 + x^5 + x^2 + x^1 + 1 0x08000004, // x^28 + x^3 + 1 0x10000002, // x^29 + x^2 + 1 0x20000029, // x^30 + x^4 + x^1 + 1 0x40000004, // x^31 + x^3 + 1 0x80000057 // x^32 + x^7 + x^5 + x^3 + x^2 + x^1 + 1 }; glfsr::~glfsr() { } int glfsr::glfsr_mask(int degree) { if(degree < 1 || degree > 32) throw std::runtime_error("glfsr::glfsr_mask(): degree must be between 1 and 32 inclusive"); return s_polynomial_masks[degree]; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/header_payload_demux_impl.h0000664000175000017500000000667512207440367023475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_HEADER_PAYLOAD_DEMUX_IMPL_H #define INCLUDED_DIGITAL_HEADER_PAYLOAD_DEMUX_IMPL_H #include namespace gr { namespace digital { class header_payload_demux_impl : public header_payload_demux { private: int d_header_len; //!< Number of bytes per header int d_items_per_symbol; //!< Bytes per symbol int d_gi; //!< Bytes per guard interval pmt::pmt_t d_len_tag_key; //!< Key of length tag pmt::pmt_t d_trigger_tag_key; //!< Key of trigger tag (if used) bool d_output_symbols; //!< If true, output is symbols, not items size_t d_itemsize; //!< Bytes per item bool d_uses_trigger_tag; //!< If a trigger tag is used int d_state; //!< Current read state int d_curr_payload_len; //!< Length of the next payload (symbols) std::vector d_payload_tag_keys; //!< Temporary buffer for PMTs that go on the payload (keys) std::vector d_payload_tag_values; //!< Temporary buffer for PMTs that go on the payload (values) // Helpers to make the state machine more readable //! Checks if there are enough items on the inputs and enough space on the output buffers to copy \p n_symbols symbols inline bool check_items_available(int n_symbols, gr_vector_int &ninput_items, int noutput_items, int nread); //! Message handler: Reads the result from the header demod and sets length tag (and other tags) void parse_header_data_msg(pmt::pmt_t header_data); //! Helper function that returns true if a trigger signal is detected. // Searches input 1 (if active), then the tags. Returns the offset in the input buffer // (or -1 if none is found) int find_trigger_signal( int nread, int noutput_items, gr_vector_const_void_star &input_items); //! Copies n symbols from in to out, makes sure tags are propagated properly void copy_n_symbols( const unsigned char *in, unsigned char *out, int port, int n_symbols ); public: header_payload_demux_impl( int header_len, int items_per_symbol, int guard_interval, const std::string &length_tag_key, const std::string &trigger_tag_key, bool output_symbols, size_t itemsize); ~header_payload_demux_impl(); void forecast (int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_HEADER_PAYLOAD_DEMUX_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/diff_decoder_bb_impl.h0000664000175000017500000000267012207440367022361 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DIFF_DECODER_BB_IMPL_H #define INCLUDED_GR_DIFF_DECODER_BB_IMPL_H #include #include namespace gr { namespace digital { class diff_decoder_bb_impl : public diff_decoder_bb { public: diff_decoder_bb_impl(unsigned int modulus); ~diff_decoder_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); private: unsigned int d_modulus; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DIFF_DECODER_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/glfsr_source_f_impl.cc0000664000175000017500000000465712207440367022470 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "glfsr_source_f_impl.h" #include #include namespace gr { namespace digital { glfsr_source_f::sptr glfsr_source_f::make(int degree, bool repeat, int mask, int seed) { return gnuradio::get_initial_sptr (new glfsr_source_f_impl(degree, repeat, mask, seed)); } glfsr_source_f_impl::glfsr_source_f_impl(int degree, bool repeat, int mask, int seed) : sync_block("glfsr_source_f", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(float))), d_repeat(repeat), d_index(0) { if(degree < 1 || degree > 32) throw std::runtime_error("glfsr_source_f_impl: degree must be between 1 and 32 inclusive"); d_length = (unsigned int)((1ULL << degree)-1); if(mask == 0) mask = glfsr::glfsr_mask(degree); d_glfsr = new glfsr(mask, seed); } glfsr_source_f_impl::~glfsr_source_f_impl() { delete d_glfsr; } int glfsr_source_f_impl::mask() const { return d_glfsr->mask(); } int glfsr_source_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *out = (float *) output_items[0]; if((d_index > d_length) && d_repeat == false) return -1; /* once through the sequence */ int i; for(i = 0; i < noutput_items; i++) { out[i] = (float)d_glfsr->next_bit()*2.0-1.0; d_index++; if(d_index > d_length && d_repeat == false) break; } return i; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/binary_slicer_fb_impl.cc0000664000175000017500000000352512207440367022753 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "binary_slicer_fb_impl.h" #include #include namespace gr { namespace digital { binary_slicer_fb::sptr binary_slicer_fb::make() { return gnuradio::get_initial_sptr(new binary_slicer_fb_impl()); } binary_slicer_fb_impl::binary_slicer_fb_impl() : sync_block("binary_slicer_fb", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(unsigned char))) { } binary_slicer_fb_impl::~binary_slicer_fb_impl() { } int binary_slicer_fb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = gr::binary_slicer(in[i]); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/mpsk_snr_est.cc0000664000175000017500000001306012207440367021140 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include namespace gr { namespace digital { mpsk_snr_est::mpsk_snr_est(double alpha) { set_alpha(alpha); } mpsk_snr_est::~mpsk_snr_est() {} void mpsk_snr_est::set_alpha(double alpha) { d_alpha = alpha; d_beta = 1.0-alpha; } double mpsk_snr_est::alpha() const { return d_alpha; } int mpsk_snr_est::update(int noutput_items, const gr_complex *input) { throw std::runtime_error("mpsk_snr_est: Unimplemented"); } double mpsk_snr_est::snr() { throw std::runtime_error("mpsk_snr_est: Unimplemented"); } /*****************************************************************/ mpsk_snr_est_simple::mpsk_snr_est_simple(double alpha) : mpsk_snr_est(alpha) { d_y1 = 0; d_y2 = 0; } int mpsk_snr_est_simple::update(int noutput_items, const gr_complex *input) { for(int i = 0; i < noutput_items; i++) { double y1 = abs(input[i]); d_y1 = d_alpha*y1 + d_beta*d_y1; double y2 = real(input[i]*input[i]); d_y2 = d_alpha*y2 + d_beta*d_y2; } return noutput_items; } double mpsk_snr_est_simple::snr() { double y1_2 = d_y1*d_y1; double y3 = y1_2 - d_y2 + 1e-20; return 10.0*log10(y1_2/y3); } /*****************************************************************/ mpsk_snr_est_skew::mpsk_snr_est_skew(double alpha) : mpsk_snr_est(alpha) { d_y1 = 0; d_y2 = 0; d_y3 = 0; } int mpsk_snr_est_skew::update(int noutput_items, const gr_complex *input) { for(int i = 0; i < noutput_items; i++) { double y1 = abs(input[i]); d_y1 = d_alpha*y1 + d_beta*d_y1; double y2 = real(input[i]*input[i]); d_y2 = d_alpha*y2 + d_beta*d_y2; // online algorithm for calculating skewness // See: // http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics double d = abs(input[i]) - d_y1; double d_i = d / (i+1); double y3 = (d*d_i*i)*d_i*(i-1) - 3.0*d_i*d_y2; d_y3 = d_alpha*y3 + d_beta*d_y3; } return noutput_items; } double mpsk_snr_est_skew::snr() { double y3 = d_y3*d_y3 / (d_y2*d_y2*d_y2); double y1_2 = d_y1*d_y1; double x = y1_2 - d_y2; return 10.0*log10(y1_2 / (x + y3*y1_2)); } /*****************************************************************/ mpsk_snr_est_m2m4::mpsk_snr_est_m2m4(double alpha) : mpsk_snr_est(alpha) { d_y1 = 0; d_y2 = 0; } int mpsk_snr_est_m2m4::update(int noutput_items, const gr_complex *input) { for(int i = 0; i < noutput_items; i++) { double y1 = abs(input[i])*abs(input[i]); d_y1 = d_alpha*y1 + d_beta*d_y1; double y2 = abs(input[i])*abs(input[i])*abs(input[i])*abs(input[i]); d_y2 = d_alpha*y2 + d_beta*d_y2; } return noutput_items; } double mpsk_snr_est_m2m4::snr() { double y1_2 = d_y1*d_y1; return 10.0*log10(2.0*sqrt(2*y1_2 - d_y2) / (d_y1 - sqrt(2*y1_2 - d_y2))); } /*****************************************************************/ snr_est_m2m4::snr_est_m2m4(double alpha, double ka, double kw) : mpsk_snr_est(alpha) { d_y1 = 0; d_y2 = 0; d_ka = ka; d_kw = kw; } int snr_est_m2m4::update(int noutput_items, const gr_complex *input) { for(int i = 0; i < noutput_items; i++) { double y1 = abs(input[i])*abs(input[i]); d_y1 = d_alpha*y1 + d_beta*d_y1; double y2 = abs(input[i])*abs(input[i])*abs(input[i])*abs(input[i]); d_y2 = d_alpha*y2 + d_beta*d_y2; } return noutput_items; } double snr_est_m2m4::snr() { double M2 = d_y1; double M4 = d_y2; double s = M2*(d_kw - 2) + sqrt((4.0-d_ka*d_kw)*M2*M2 + M4*(d_ka+d_kw-4.0)) / (d_ka + d_kw - 4.0); double n = M2 - s; return 10.0*log10(s / n); } /*****************************************************************/ mpsk_snr_est_svr::mpsk_snr_est_svr(double alpha) : mpsk_snr_est(alpha) { d_y1 = 0; d_y2 = 0; } int mpsk_snr_est_svr::update(int noutput_items, const gr_complex *input) { for(int i = 0; i < noutput_items; i++) { double x = abs(input[i+1]); double x1 = abs(input[i]); double y1 = (x*x)*(x1*x1); d_y1 = d_alpha*y1 + d_beta*d_y1; double y2 = x*x*x*x; d_y2 = d_alpha*y2 + d_beta*d_y2; } return noutput_items; } double mpsk_snr_est_svr::snr() { double x = d_y1 / (d_y2 - d_y1); return 10.0*log10(2.*((x-1) + sqrt(x*(x-1)))); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_insert_preamble_impl.h0000664000175000017500000000373212207440367023501 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_DIGITAL_OFDM_INSERT_PREAMBLE_IMPL_H #define INCLUDED_DIGITAL_OFDM_INSERT_PREAMBLE_IMPL_H #include namespace gr { namespace digital { class ofdm_insert_preamble_impl : public ofdm_insert_preamble { private: enum state_t { ST_IDLE, ST_PREAMBLE, ST_FIRST_PAYLOAD, ST_PAYLOAD }; int d_fft_length; state_t d_state; int d_nsymbols_output; int d_pending_flag; const std::vector > d_preamble; void enter_idle(); void enter_first_payload(); void enter_payload(); public: ofdm_insert_preamble_impl(int fft_length, const std::vector > &preamble); ~ofdm_insert_preamble_impl(); void enter_preamble(); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void forecast(int noutput_items, gr_vector_int &ninput_items_required); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_INSERT_PREAMBLE_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/descrambler_bb_impl.cc0000664000175000017500000000365212207440367022406 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "descrambler_bb_impl.h" #include namespace gr { namespace digital { descrambler_bb::sptr descrambler_bb::make(int mask, int seed, int len) { return gnuradio::get_initial_sptr (new descrambler_bb_impl(mask, seed, len)); } descrambler_bb_impl::descrambler_bb_impl(int mask, int seed, int len) : sync_block("descrambler_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))), d_lfsr(mask, seed, len) { } descrambler_bb_impl::~descrambler_bb_impl() { } int descrambler_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = d_lfsr.next_bit_descramble(in[i]); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_mapper_bcv_impl.cc0000664000175000017500000002043112207440367022575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2008,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ofdm_mapper_bcv_impl.h" #include #include #include namespace gr { namespace digital { ofdm_mapper_bcv::sptr ofdm_mapper_bcv::make(const std::vector &constellation, unsigned int msgq_limit, unsigned int occupied_carriers, unsigned int fft_length) { return gnuradio::get_initial_sptr (new ofdm_mapper_bcv_impl(constellation, msgq_limit, occupied_carriers, fft_length)); } // Consumes 1 packet and produces as many OFDM symbols of // fft_length to hold the full packet ofdm_mapper_bcv_impl::ofdm_mapper_bcv_impl(const std::vector &constellation, unsigned int msgq_limit, unsigned int occupied_carriers, unsigned int fft_length) : sync_block("ofdm_mapper_bcv", io_signature::make(0, 0, 0), io_signature::make2(1, 2, sizeof(gr_complex)*fft_length, sizeof(char))), d_constellation(constellation), d_msgq(msg_queue::make(msgq_limit)), d_msg_offset(0), d_eof(false), d_occupied_carriers(occupied_carriers), d_fft_length(fft_length), d_bit_offset(0), d_pending_flag(0), d_resid(0), d_nresid(0) { if(!(d_occupied_carriers <= d_fft_length)) throw std::invalid_argument("ofdm_mapper_bcv_impl: occupied carriers must be <= fft_length"); // this is not the final form of this solution since we still // use the occupied_tones concept, which would get us into // trouble if the number of carriers we seek is greater than the // occupied carriers. // Eventually, we will get rid of the occupied_carriers concept. std::string carriers = "FE7F"; // A bit hacky to fill out carriers to occupied_carriers length int diff = (d_occupied_carriers - 4*carriers.length()); while(diff > 7) { carriers.insert(0, "f"); carriers.insert(carriers.length(), "f"); diff -= 8; } // if there's extras left to be processed divide remaining to // put on either side of current map all of this is done to // stick with the concept of a carrier map string that can be // later passed by the user, even though it'd be cleaner to just // do this on the carrier map itself int diff_left=0; int diff_right=0; // dictionary to convert from integers to ascii hex representation char abc[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; if(diff > 0) { char c[2] = {0,0}; diff_left = (int)ceil((float)diff/2.0f); // number of carriers to put on the left side c[0] = abc[(1 << diff_left) - 1]; // convert to bits and move to ASCI integer carriers.insert(0, c); diff_right = diff - diff_left; // number of carriers to put on the right side c[0] = abc[0xF^((1 << diff_right) - 1)]; // convert to bits and move to ASCI integer carriers.insert(carriers.length(), c); } // find out how many zeros to pad on the sides; the difference between the fft length and the subcarrier // mapping size in chunks of four. This is the number to pack on the left and this number plus any // residual nulls (if odd) will be packed on the right. diff = (d_fft_length/4 - carriers.length())/2; unsigned int i,j,k; for(i = 0; i < carriers.length(); i++) { char c = carriers[i]; // get the current hex character from the string for(j = 0; j < 4; j++) { // walk through all four bits k = (strtol(&c, NULL, 16) >> (3-j)) & 0x1; // convert to int and extract next bit if(k) { // if bit is a 1, d_subcarrier_map.push_back(4*(i+diff) + j); // use this subcarrier } } } // make sure we stay in the limit currently imposed by the occupied_carriers if(d_subcarrier_map.size() > d_occupied_carriers) { throw std::invalid_argument("ofdm_mapper_bcv_impl: subcarriers allocated exceeds size of occupied carriers"); } d_nbits = (unsigned long)ceil(log10(float(d_constellation.size())) / log10(2.0)); } ofdm_mapper_bcv_impl::~ofdm_mapper_bcv_impl() { } int ofdm_mapper_bcv_impl::randsym() { return (rand() % d_constellation.size()); } int ofdm_mapper_bcv_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *out = (gr_complex *)output_items[0]; unsigned int i=0; //printf("OFDM BPSK Mapper: ninput_items: %d noutput_items: %d\n", ninput_items[0], noutput_items); if(d_eof) { return -1; } if(!d_msg) { d_msg = d_msgq->delete_head(); // block, waiting for a message d_msg_offset = 0; d_bit_offset = 0; d_pending_flag = 1; // new packet, write start of packet flag if((d_msg->length() == 0) && (d_msg->type() == 1)) { d_msg.reset(); return -1; // We're done; no more messages coming. } } char *out_flag = 0; if(output_items.size() == 2) out_flag = (char *) output_items[1]; // Build a single symbol: // Initialize all bins to 0 to set unused carriers memset(out, 0, d_fft_length*sizeof(gr_complex)); i = 0; unsigned char bits = 0; //while((d_msg_offset < d_msg->length()) && (i < d_occupied_carriers)) { while((d_msg_offset < d_msg->length()) && (i < d_subcarrier_map.size())) { // need new data to process if(d_bit_offset == 0) { d_msgbytes = d_msg->msg()[d_msg_offset]; //printf("mod message byte: %x\n", d_msgbytes); } if(d_nresid > 0) { // take the residual bits, fill out nbits with info from the new byte, and put them in the symbol d_resid |= (((1 << d_nresid)-1) & d_msgbytes) << (d_nbits - d_nresid); bits = d_resid; out[d_subcarrier_map[i]] = d_constellation[bits]; i++; d_bit_offset += d_nresid; d_nresid = 0; d_resid = 0; //printf("mod bit(r): %x resid: %x nresid: %d bit_offset: %d\n", // bits, d_resid, d_nresid, d_bit_offset); } else { if((8 - d_bit_offset) >= d_nbits) { // test to make sure we can fit nbits // take the nbits number of bits at a time from the byte to add to the symbol bits = ((1 << d_nbits)-1) & (d_msgbytes >> d_bit_offset); d_bit_offset += d_nbits; out[d_subcarrier_map[i]] = d_constellation[bits]; i++; } else { // if we can't fit nbits, store them for the next // saves d_nresid bits of this message where d_nresid < d_nbits unsigned int extra = 8-d_bit_offset; d_resid = ((1 << extra)-1) & (d_msgbytes >> d_bit_offset); d_bit_offset += extra; d_nresid = d_nbits - extra; } } if(d_bit_offset == 8) { d_bit_offset = 0; d_msg_offset++; } } // Ran out of data to put in symbol if (d_msg_offset == d_msg->length()) { if(d_nresid > 0) { d_resid |= 0x00; bits = d_resid; d_nresid = 0; d_resid = 0; } //while(i < d_occupied_carriers) { // finish filling out the symbol while(i < d_subcarrier_map.size()) { // finish filling out the symbol out[d_subcarrier_map[i]] = d_constellation[randsym()]; i++; } if(d_msg->type() == 1) // type == 1 sets EOF d_eof = true; d_msg.reset(); // finished packet, free message assert(d_bit_offset == 0); } if(out_flag) out_flag[0] = d_pending_flag; d_pending_flag = 0; return 1; // produced symbol } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/constellation_soft_decoder_cf_impl.h0000664000175000017500000000314612237515112025360 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_SOFT_DECODER_CF_IMPL_H #define INCLUDED_DIGITAL_CONSTELLATION_SOFT_DECODER_CF_IMPL_H #include namespace gr { namespace digital { class constellation_soft_decoder_cf_impl : public constellation_soft_decoder_cf { private: constellation_sptr d_constellation; unsigned int d_dim; int d_bps; public: constellation_soft_decoder_cf_impl(constellation_sptr constellation); ~constellation_soft_decoder_cf_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_SOFT_DECODER_CF_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_frame_acquisition_impl.cc0000664000175000017500000001605612207440367024171 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2008,2010,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ofdm_frame_acquisition_impl.h" #include #include #include #include namespace gr { namespace digital { #define VERBOSE 0 #define M_TWOPI (2*M_PI) #define MAX_NUM_SYMBOLS 1000 ofdm_frame_acquisition::sptr ofdm_frame_acquisition::make(unsigned int occupied_carriers, unsigned int fft_length, unsigned int cplen, const std::vector &known_symbol, unsigned int max_fft_shift_len) { return gnuradio::get_initial_sptr (new ofdm_frame_acquisition_impl(occupied_carriers, fft_length, cplen, known_symbol, max_fft_shift_len)); } ofdm_frame_acquisition_impl::ofdm_frame_acquisition_impl(unsigned occupied_carriers, unsigned int fft_length, unsigned int cplen, const std::vector &known_symbol, unsigned int max_fft_shift_len) : block("ofdm_frame_acquisition", io_signature::make2(2, 2, sizeof(gr_complex)*fft_length, sizeof(char)*fft_length), io_signature::make2(2, 2, sizeof(gr_complex)*occupied_carriers, sizeof(char))), d_occupied_carriers(occupied_carriers), d_fft_length(fft_length), d_cplen(cplen), d_freq_shift_len(max_fft_shift_len), d_known_symbol(known_symbol), d_coarse_freq(0), d_phase_count(0) { d_symbol_phase_diff.resize(d_fft_length); d_known_phase_diff.resize(d_occupied_carriers); d_hestimate.resize(d_occupied_carriers); unsigned int i = 0, j = 0; std::fill(d_known_phase_diff.begin(), d_known_phase_diff.end(), 0); for(i = 0; i < d_known_symbol.size()-2; i+=2) { d_known_phase_diff[i] = norm(d_known_symbol[i] - d_known_symbol[i+2]); } d_phase_lut = new gr_complex[(2*d_freq_shift_len+1) * MAX_NUM_SYMBOLS]; for(i = 0; i <= 2*d_freq_shift_len; i++) { for(j = 0; j < MAX_NUM_SYMBOLS; j++) { d_phase_lut[j + i*MAX_NUM_SYMBOLS] = gr_expj(-M_TWOPI*d_cplen/d_fft_length*(i-d_freq_shift_len)*j); } } } ofdm_frame_acquisition_impl::~ofdm_frame_acquisition_impl() { delete [] d_phase_lut; } void ofdm_frame_acquisition_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = 1; } gr_complex ofdm_frame_acquisition_impl::coarse_freq_comp(int freq_delta, int symbol_count) { // return gr_complex(cos(-M_TWOPI*freq_delta*d_cplen/d_fft_length*symbol_count), // sin(-M_TWOPI*freq_delta*d_cplen/d_fft_length*symbol_count)); return gr_expj(-M_TWOPI*freq_delta*d_cplen/d_fft_length*symbol_count); //return d_phase_lut[MAX_NUM_SYMBOLS * (d_freq_shift_len + freq_delta) + symbol_count]; } void ofdm_frame_acquisition_impl::correlate(const gr_complex *symbol, int zeros_on_left) { unsigned int i,j; std::fill(d_symbol_phase_diff.begin(), d_symbol_phase_diff.end(), 0); for(i = 0; i < d_fft_length-2; i++) { d_symbol_phase_diff[i] = norm(symbol[i] - symbol[i+2]); } // sweep through all possible/allowed frequency offsets and select the best int index = 0; float max = 0, sum=0; for(i = zeros_on_left - d_freq_shift_len; i < zeros_on_left + d_freq_shift_len; i++) { sum = 0; for(j = 0; j < d_occupied_carriers; j++) { sum += (d_known_phase_diff[j] * d_symbol_phase_diff[i+j]); } if(sum > max) { max = sum; index = i; } } // set the coarse frequency offset relative to the edge of the occupied tones d_coarse_freq = index - zeros_on_left; } void ofdm_frame_acquisition_impl::calculate_equalizer(const gr_complex *symbol, int zeros_on_left) { unsigned int i=0; // Set first tap of equalizer d_hestimate[0] = d_known_symbol[0] / (coarse_freq_comp(d_coarse_freq,1)*symbol[zeros_on_left+d_coarse_freq]); // set every even tap based on known symbol // linearly interpolate between set carriers to set zero-filled carriers // FIXME: is this the best way to set this? for(i = 2; i < d_occupied_carriers; i+=2) { d_hestimate[i] = d_known_symbol[i] / (coarse_freq_comp(d_coarse_freq,1)*(symbol[i+zeros_on_left+d_coarse_freq])); d_hestimate[i-1] = (d_hestimate[i] + d_hestimate[i-2]) / gr_complex(2.0, 0.0); } // with even number of carriers; last equalizer tap is wrong if(!(d_occupied_carriers & 1)) { d_hestimate[d_occupied_carriers-1] = d_hestimate[d_occupied_carriers-2]; } if(VERBOSE) { fprintf(stderr, "Equalizer setting:\n"); for(i = 0; i < d_occupied_carriers; i++) { gr_complex sym = coarse_freq_comp(d_coarse_freq,1)*symbol[i+zeros_on_left+d_coarse_freq]; gr_complex output = sym * d_hestimate[i]; fprintf(stderr, "sym: %+.4f + j%+.4f ks: %+.4f + j%+.4f eq: %+.4f + j%+.4f ==> %+.4f + j%+.4f\n", sym .real(), sym.imag(), d_known_symbol[i].real(), d_known_symbol[i].imag(), d_hestimate[i].real(), d_hestimate[i].imag(), output.real(), output.imag()); } fprintf(stderr, "\n"); } } int ofdm_frame_acquisition_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *symbol = (const gr_complex *)input_items[0]; const char *signal_in = (const char *)input_items[1]; gr_complex *out = (gr_complex *) output_items[0]; char *signal_out = (char *) output_items[1]; int unoccupied_carriers = d_fft_length - d_occupied_carriers; int zeros_on_left = (int)ceil(unoccupied_carriers/2.0); if(signal_in[0]) { d_phase_count = 1; correlate(symbol, zeros_on_left); calculate_equalizer(symbol, zeros_on_left); signal_out[0] = 1; } else { signal_out[0] = 0; } for(unsigned int i = 0; i < d_occupied_carriers; i++) { out[i] = d_hestimate[i]*coarse_freq_comp(d_coarse_freq,d_phase_count) *symbol[i+zeros_on_left+d_coarse_freq]; } d_phase_count++; if(d_phase_count == MAX_NUM_SYMBOLS) { d_phase_count = 1; } consume_each(1); return 1; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/glfsr_source_b_impl.h0000664000175000017500000000315712207440367022320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_GLFSR_SOURCE_B_IMPL_H #define INCLUDED_GR_GLFSR_SOURCE_B_IMPL_H #include #include namespace gr { namespace digital { class glfsr_source_b_impl : public glfsr_source_b { private: glfsr *d_glfsr; bool d_repeat; unsigned int d_index; unsigned int d_length; public: glfsr_source_b_impl(int degree, bool repeat=true, int mask=0, int seed=1); ~glfsr_source_b_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int period() const { return d_length; } int mask() const; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_GLFSR_SOURCE_B_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/mpsk_snr_est_cc_impl.h0000664000175000017500000000444312207440367022475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_MPSK_SNR_EST_CC_IMPL_H #define INCLUDED_DIGITAL_MPSK_SNR_EST_CC_IMPL_H #include #include #include namespace gr { namespace digital { class mpsk_snr_est_cc_impl : public mpsk_snr_est_cc { private: snr_est_type_t d_type; int d_nsamples, d_count; double d_alpha; mpsk_snr_est *d_snr_est; //d_key is the tag name, 'snr', d_me is the block name + unique ID pmt::pmt_t d_key, d_me; public: mpsk_snr_est_cc_impl(snr_est_type_t type, int tag_nsamples=10000, double alpha=0.001); ~mpsk_snr_est_cc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); //! Return the estimated signal-to-noise ratio in decibels double snr(); //! Return the type of estimator in use snr_est_type_t type() const; //! Return how many samples between SNR tags int tag_nsample() const; //! Get the running-average coefficient double alpha() const; //! Set type of estimator to use void set_type(snr_est_type_t t); //! Set the number of samples between SNR tags void set_tag_nsample(int n); //! Set the running-average coefficient void set_alpha(double alpha); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_MPSK_SNR_EST_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/chunks_to_symbols_XX_impl.cc.t0000664000175000017500000001004212237515112024067 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include #include namespace gr { namespace digital { @BASE_NAME@::sptr @BASE_NAME@::make(const std::vector<@O_TYPE@> &symbol_table, const int D) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(symbol_table, D)); } @IMPL_NAME@::@IMPL_NAME@(const std::vector<@O_TYPE@> &symbol_table, const int D) : sync_interpolator("@BASE_NAME@", io_signature::make(1, -1, sizeof(@I_TYPE@)), io_signature::make(1, -1, sizeof(@O_TYPE@)), D), d_D(D), d_symbol_table(symbol_table) { message_port_register_in(pmt::mp("set_symbol_table")); set_msg_handler( pmt::mp("set_symbol_table"), boost::bind(&@IMPL_NAME@::handle_set_symbol_table, this, _1)); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_vector_from_pmt(std::vector &symbol_table, pmt::pmt_t &symbol_table_pmt) { symbol_table.resize(0); for (unsigned int i=0; i &symbol_table, pmt::pmt_t &symbol_table_pmt) { symbol_table.resize(0); for (unsigned int i=0; i symbol_table; set_vector_from_pmt(symbol_table, symbol_table_pmt); set_symbol_table(symbol_table); } void @IMPL_NAME@::set_symbol_table(std::vector<@O_TYPE@> &symbol_table) { d_symbol_table.resize(0); for (unsigned int i=0; i tags; get_tags_in_range(tags, m, nitems_read(m), nitems_read(m)+noutput_items/d_D); tag_checker tchecker(tags); // per stream processing for(int i = 0; i < noutput_items / d_D; i++) { std::vector tags_now; tchecker.get_tags(tags_now, i+nitems_read(m)); for (unsigned int j=0; j namespace gr { namespace digital { pn_correlator_cc::sptr pn_correlator_cc::make(int degree, int mask, int seed) { return gnuradio::get_initial_sptr (new pn_correlator_cc_impl(degree, mask, seed)); } pn_correlator_cc_impl::pn_correlator_cc_impl(int degree, int mask, int seed) : sync_decimator("pn_correlator_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), (unsigned int)((1ULL << degree)-1)) // PN code length { d_len = (unsigned int)((1ULL << degree)-1); if(mask == 0) mask = glfsr::glfsr_mask(degree); d_reference = new glfsr(mask, seed); for(int i = 0; i < d_len; i++) // initialize to last value in sequence d_pn = 2.0*d_reference->next_bit()-1.0; } pn_correlator_cc_impl::~pn_correlator_cc_impl() { delete d_reference; } int pn_correlator_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; gr_complex sum; for(int i = 0; i < noutput_items; i++) { sum = 0.0; for(int j = 0; j < d_len; j++) { if(j != 0) // retard PN generator one sample per period d_pn = 2.0*d_reference->next_bit()-1.0; // no conditionals sum += *in++ * d_pn; } *out++ = sum*gr_complex(1.0/d_len, 0.0); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_sync_sc_cfb_impl.cc0000664000175000017500000001155512207440367022741 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "ofdm_sync_sc_cfb_impl.h" #include #include #include #include #include #include #include #include #include #include #include namespace gr { namespace digital { ofdm_sync_sc_cfb::sptr ofdm_sync_sc_cfb::make(int fft_len, int cp_len, bool use_even_carriers) { return gnuradio::get_initial_sptr (new ofdm_sync_sc_cfb_impl(fft_len, cp_len, use_even_carriers)); } ofdm_sync_sc_cfb_impl::ofdm_sync_sc_cfb_impl(int fft_len, int cp_len, bool use_even_carriers) : hier_block2 ("ofdm_sync_sc_cfb", io_signature::make(1, 1, sizeof (gr_complex)), #ifndef SYNC_ADD_DEBUG_OUTPUT io_signature::make2(2, 2, sizeof (float), sizeof (unsigned char))) #else io_signature::make3(3, 3, sizeof (float), sizeof (unsigned char), sizeof (float))) #endif { std::vector ma_taps(fft_len/2, 1.0); gr::blocks::delay::sptr delay(gr::blocks::delay::make(sizeof(gr_complex), fft_len/2)); gr::blocks::conjugate_cc::sptr delay_conjugate(gr::blocks::conjugate_cc::make()); gr::blocks::multiply_cc::sptr delay_corr(gr::blocks::multiply_cc::make()); gr::filter::fir_filter_ccf::sptr delay_ma(gr::filter::fir_filter_ccf::make(1, std::vector(fft_len/2, use_even_carriers ? 1.0 : -1.0))); gr::blocks::complex_to_mag_squared::sptr delay_magsquare(gr::blocks::complex_to_mag_squared::make()); gr::blocks::divide_ff::sptr delay_normalize(gr::blocks::divide_ff::make()); gr::blocks::complex_to_mag_squared::sptr normalizer_magsquare(gr::blocks::complex_to_mag_squared::make()); gr::filter::fir_filter_fff::sptr normalizer_ma(gr::filter::fir_filter_fff::make(1, std::vector(fft_len, 0.5))); gr::blocks::multiply_ff::sptr normalizer_square(gr::blocks::multiply_ff::make()); gr::blocks::complex_to_arg::sptr peak_to_angle(gr::blocks::complex_to_arg::make()); gr::blocks::sample_and_hold_ff::sptr sample_and_hold(gr::blocks::sample_and_hold_ff::make()); gr::blocks::plateau_detector_fb::sptr plateau_detector(gr::blocks::plateau_detector_fb::make(cp_len)); // Delay Path connect(self(), 0, delay, 0); connect(delay, 0, delay_conjugate, 0); connect(delay_conjugate, 0, delay_corr, 1); connect(self(), 0, delay_corr, 0); connect(delay_corr, 0, delay_ma, 0); connect(delay_ma, 0, delay_magsquare, 0); connect(delay_magsquare, 0, delay_normalize, 0); // Energy Path connect(self(), 0, normalizer_magsquare, 0); connect(normalizer_magsquare, 0, normalizer_ma, 0); connect(normalizer_ma, 0, normalizer_square, 0); connect(normalizer_ma, 0, normalizer_square, 1); connect(normalizer_square, 0, delay_normalize, 1); // Fine frequency estimate (output 0) connect(delay_ma, 0, peak_to_angle, 0); connect(peak_to_angle, 0, sample_and_hold, 0); connect(sample_and_hold, 0, self(), 0); // Peak detect (output 1) connect(delay_normalize, 0, plateau_detector, 0); connect(plateau_detector, 0, sample_and_hold, 1); connect(plateau_detector, 0, self(), 1); #ifdef SYNC_ADD_DEBUG_OUTPUT // Debugging: timing metric (output 2) connect(delay_normalize, 0, self(), 2); #endif } ofdm_sync_sc_cfb_impl::~ofdm_sync_sc_cfb_impl() { } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/clock_recovery_mm_cc_impl.h0000664000175000017500000000612612207440367023470 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_CC_IMPL_H #define INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_CC_IMPL_H #include #include namespace gr { namespace digital { class clock_recovery_mm_cc_impl : public clock_recovery_mm_cc { public: clock_recovery_mm_cc_impl(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limi); ~clock_recovery_mm_cc_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const { return d_mu;} float omega() const { return d_omega;} float gain_mu() const { return d_gain_mu;} float gain_omega() const { return d_gain_omega;} void set_verbose (bool verbose) { d_verbose = verbose; } void set_gain_mu (float gain_mu) { d_gain_mu = gain_mu; } void set_gain_omega (float gain_omega) { d_gain_omega = gain_omega; } void set_mu (float mu) { d_mu = mu; } void set_omega (float omega) { d_omega = omega; d_min_omega = omega*(1.0 - d_omega_relative_limit); d_max_omega = omega*(1.0 + d_omega_relative_limit); d_omega_mid = 0.5*(d_min_omega+d_max_omega); } private: float d_mu; // fractional sample position [0.0, 1.0] float d_omega; // nominal frequency float d_gain_omega; // gain for adjusting omega float d_min_omega; // minimum allowed omega float d_max_omega; // maximum allowed omeg float d_omega_relative_limit; // used to compute min and max omega float d_omega_mid; // average omega float d_gain_mu; // gain for adjusting mu gr_complex d_last_sample; filter::mmse_fir_interpolator_cc *d_interp; bool d_verbose; gr_complex d_p_2T, d_p_1T, d_p_0T; gr_complex d_c_2T, d_c_1T, d_c_0T; gr_complex slicer_0deg(gr_complex sample); gr_complex slicer_45deg(gr_complex sample); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CLOCK_RECOVERY_MM_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/cma_equalizer_cc_impl.h0000664000175000017500000000455412207440367022612 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CMA_EQUALIZER_CC_IMPL_H #define INCLUDED_DIGITAL_CMA_EQUALIZER_CC_IMPL_H #include #include #include #include namespace gr { namespace digital { class cma_equalizer_cc_impl : public cma_equalizer_cc, filter::kernel::fir_filter_ccc { private: std::vector d_new_taps; bool d_updated; gr_complex d_error; float d_modulus; float d_mu; protected: gr_complex error(const gr_complex &out); void update_tap(gr_complex &tap, const gr_complex &in); public: cma_equalizer_cc_impl(int num_taps, float modulus, float mu, int sps); ~cma_equalizer_cc_impl(); void set_taps(const std::vector &taps); std::vector taps() const; float gain() const { return d_mu; } void set_gain(float mu) { if(mu < 0.0f || mu > 1.0f) { throw std::out_of_range("cma_equalizer::set_gain: Gain value must be in [0,1]"); } d_mu = mu; } float modulus() const { return d_modulus; } void set_modulus(float mod) { if(mod < 0) throw std::out_of_range("cma_equalizer::set_modulus: Modulus value must be >= 0"); d_modulus = mod; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CMA_EQUALIZER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/pfb_clock_sync_ccf_impl.h0000664000175000017500000000730212237515112023101 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PFB_CLOCK_SYNC_CCF_IMPL_H #define INCLUDED_DIGITAL_PFB_CLOCK_SYNC_CCF_IMPL_H #include using namespace gr::filter; namespace gr { namespace digital { class pfb_clock_sync_ccf_impl : public pfb_clock_sync_ccf { private: bool d_updated; double d_sps; double d_sample_num; float d_loop_bw; float d_damping; float d_alpha; float d_beta; int d_nfilters; int d_taps_per_filter; std::vector d_filters; std::vector d_diff_filters; std::vector< std::vector > d_taps; std::vector< std::vector > d_dtaps; float d_k; float d_rate; float d_rate_i; float d_rate_f; float d_max_dev; int d_filtnum; int d_osps; float d_error; int d_out_idx; void create_diff_taps(const std::vector &newtaps, std::vector &difftaps); public: pfb_clock_sync_ccf_impl(double sps, float loop_bw, const std::vector &taps, unsigned int filter_size=32, float init_phase=0, float max_rate_deviation=1.5, int osps=1); ~pfb_clock_sync_ccf_impl(); void setup_rpc(); void update_gains(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); void set_taps(const std::vector &taps, std::vector< std::vector > &ourtaps, std::vector &ourfilter); std::vector< std::vector > taps() const; std::vector< std::vector > diff_taps() const; std::vector channel_taps(int channel) const; std::vector diff_channel_taps(int channel) const; std::string taps_as_string() const; std::string diff_taps_as_string() const; void set_loop_bandwidth(float bw); void set_damping_factor(float df); void set_alpha(float alpha); void set_beta(float beta); void set_max_rate_deviation(float m) { d_max_dev = m; } float loop_bandwidth() const; float damping_factor() const; float alpha() const; float beta() const; float clock_rate() const; float error() const; float rate() const; float phase() const; /******************************************************************* *******************************************************************/ bool check_topology(int ninputs, int noutputs); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_PFB_CLOCK_SYNC_CCF_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/diff_phasor_cc_impl.h0000664000175000017500000000256012207440367022250 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DIFF_PHASOR_CC_IMPL_H #define INCLUDED_GR_DIFF_PHASOR_CC_IMPL_H #include #include namespace gr { namespace digital { class diff_phasor_cc_impl : public diff_phasor_cc { public: diff_phasor_cc_impl(); ~diff_phasor_cc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DIFF_PHASOR_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/clock_recovery_mm_cc_impl.cc0000664000175000017500000001412212207440367023621 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "clock_recovery_mm_cc_impl.h" #include #include #include #include #include namespace gr { namespace digital { static const int FUDGE = 16; clock_recovery_mm_cc::sptr clock_recovery_mm_cc::make(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limit) { return gnuradio::get_initial_sptr (new clock_recovery_mm_cc_impl(omega, gain_omega, mu, gain_mu, omega_relative_limit)); } clock_recovery_mm_cc_impl::clock_recovery_mm_cc_impl(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limit) : block("clock_recovery_mm_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make2(1, 2, sizeof(gr_complex), sizeof(float))), d_mu(mu), d_omega(omega), d_gain_omega(gain_omega), d_omega_relative_limit(omega_relative_limit), d_gain_mu(gain_mu), d_last_sample(0), d_interp(new filter::mmse_fir_interpolator_cc()), d_verbose(prefs::singleton()->get_bool("clock_recovery_mm_cc", "verbose", false)), d_p_2T(0), d_p_1T(0), d_p_0T(0), d_c_2T(0), d_c_1T(0), d_c_0T(0) { if(omega <= 0.0) throw std::out_of_range("clock rate must be > 0"); if(gain_mu < 0 || gain_omega < 0) throw std::out_of_range("Gains must be non-negative"); set_omega(omega); // also sets min and max omega set_relative_rate(1.0 / omega); set_history(3); // ensure 2 extra input samples are available } clock_recovery_mm_cc_impl::~clock_recovery_mm_cc_impl() { delete d_interp; } void clock_recovery_mm_cc_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) ninput_items_required[i] = (int)ceil((noutput_items * d_omega) + d_interp->ntaps()) + FUDGE; } gr_complex clock_recovery_mm_cc_impl::slicer_0deg(gr_complex sample) { float real=0, imag=0; if(sample.real() > 0) real = 1; if(sample.imag() > 0) imag = 1; return gr_complex(real,imag); } gr_complex clock_recovery_mm_cc_impl::slicer_45deg(gr_complex sample) { float real= -1, imag = -1; if(sample.real() > 0) real=1; if(sample.imag() > 0) imag = 1; return gr_complex(real,imag); } int clock_recovery_mm_cc_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; float *foptr = (float *)output_items[1]; bool write_foptr = output_items.size() >= 2; int ii = 0; // input index int oo = 0; // output index int ni = ninput_items[0] - d_interp->ntaps() - FUDGE; // don't use more input than this assert(d_mu >= 0.0); assert(d_mu <= 1.0); float mm_val = 0; gr_complex u, x, y; // This loop writes the error to the second output, if it exists if(write_foptr) { while(oo < noutput_items && ii < ni) { d_p_2T = d_p_1T; d_p_1T = d_p_0T; d_p_0T = d_interp->interpolate(&in[ii], d_mu); d_c_2T = d_c_1T; d_c_1T = d_c_0T; d_c_0T = slicer_0deg(d_p_0T); x = (d_c_0T - d_c_2T) * conj(d_p_1T); y = (d_p_0T - d_p_2T) * conj(d_c_1T); u = y - x; mm_val = u.real(); out[oo++] = d_p_0T; // limit mm_val mm_val = gr::branchless_clip(mm_val,4.0); d_omega = d_omega + d_gain_omega * mm_val; d_omega = d_omega_mid + gr::branchless_clip(d_omega-d_omega_mid, d_omega_relative_limit); d_mu = d_mu + d_omega + d_gain_mu * mm_val; ii += (int)floor(d_mu); d_mu -= floor(d_mu); // write the error signal to the second output foptr[oo-1] = mm_val; if(ii < 0) // clamp it. This should only happen with bogus input ii = 0; } } // This loop does not write to the second output (ugly, but faster) else { while(oo < noutput_items && ii < ni) { d_p_2T = d_p_1T; d_p_1T = d_p_0T; d_p_0T = d_interp->interpolate(&in[ii], d_mu); d_c_2T = d_c_1T; d_c_1T = d_c_0T; d_c_0T = slicer_0deg(d_p_0T); x = (d_c_0T - d_c_2T) * conj(d_p_1T); y = (d_p_0T - d_p_2T) * conj(d_c_1T); u = y - x; mm_val = u.real(); out[oo++] = d_p_0T; // limit mm_val mm_val = gr::branchless_clip(mm_val,1.0); d_omega = d_omega + d_gain_omega * mm_val; d_omega = d_omega_mid + gr::branchless_clip(d_omega-d_omega_mid, d_omega_relative_limit); d_mu = d_mu + d_omega + d_gain_mu * mm_val; ii += (int)floor(d_mu); d_mu -= floor(d_mu); if(d_verbose) { std::cout << d_omega << "\t" << d_mu << std::endl; } if(ii < 0) // clamp it. This should only happen with bogus input ii = 0; } } if(ii > 0) { if(ii > ninput_items[0]) { std::cerr << "clock_recovery_mm_cc: ii > ninput_items[0] (" << ii << " > " << ninput_items[0] << std::endl; assert(0); } consume_each(ii); } return oo; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/chunks_to_symbols_XX_impl.h.t0000664000175000017500000000363612237515112023744 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* @WARNING@ */ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace digital { class @IMPL_NAME@ : public @BASE_NAME@ { private: int d_D; std::vector<@O_TYPE@> d_symbol_table; public: @IMPL_NAME@(const std::vector<@O_TYPE@> &symbol_table, const int D = 1); ~@IMPL_NAME@(); void set_vector_from_pmt(std::vector &symbol_table, pmt::pmt_t &symbol_table_pmt); void set_vector_from_pmt(std::vector &symbol_table, pmt::pmt_t &symbol_table_pmt); void handle_set_symbol_table(pmt::pmt_t symbol_table_pmt); void set_symbol_table(std::vector<@O_TYPE@> &symbol_table); int D() const { return d_D; } std::vector<@O_TYPE@> symbol_table() const { return d_symbol_table; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); bool check_topology(int ninputs, int noutputs) { return ninputs == noutputs; } }; } /* namespace digital */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-digital/lib/header_payload_demux_impl.cc0000664000175000017500000002603212243470567023625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include "header_payload_demux_impl.h" namespace gr { namespace digital { enum demux_states_t { STATE_FIND_TRIGGER, // "Idle" state (waiting for burst) STATE_HEADER, // Copy header STATE_WAIT_FOR_MSG, // Null state (wait until msg from header demod) STATE_HEADER_RX_SUCCESS, // Header processing STATE_HEADER_RX_FAIL, // " STATE_PAYLOAD // Copy payload }; #define msg_port_id pmt::mp("header_data") header_payload_demux::sptr header_payload_demux::make( int header_len, int items_per_symbol, int guard_interval, const std::string &length_tag_key, const std::string &trigger_tag_key, bool output_symbols, size_t itemsize) { return gnuradio::get_initial_sptr ( new header_payload_demux_impl( header_len, items_per_symbol, guard_interval, length_tag_key, trigger_tag_key, output_symbols, itemsize ) ); } header_payload_demux_impl::header_payload_demux_impl( int header_len, int items_per_symbol, int guard_interval, const std::string &length_tag_key, const std::string &trigger_tag_key, bool output_symbols, size_t itemsize ) : block("header_payload_demux", io_signature::make2(1, 2, itemsize, sizeof(char)), io_signature::make(2, 2, (output_symbols ? itemsize * items_per_symbol : itemsize))), d_header_len(header_len), d_items_per_symbol(items_per_symbol), d_gi(guard_interval), d_len_tag_key(pmt::string_to_symbol(length_tag_key)), d_trigger_tag_key(pmt::string_to_symbol(trigger_tag_key)), d_output_symbols(output_symbols), d_itemsize(itemsize), d_uses_trigger_tag(!trigger_tag_key.empty()), d_state(STATE_FIND_TRIGGER), d_curr_payload_len(0), d_payload_tag_keys(0), d_payload_tag_values(0) { if (d_header_len < 1) { throw std::invalid_argument("Header length must be at least 1 symbol."); } if (d_items_per_symbol < 1 || d_gi < 0 || d_itemsize < 1) { throw std::invalid_argument("Items and symbol sizes must be at least 1."); } if (d_output_symbols) { set_relative_rate(1.0 / (d_items_per_symbol + d_gi)); } else { set_relative_rate((double)d_items_per_symbol / (d_items_per_symbol + d_gi)); set_output_multiple(d_items_per_symbol); } set_tag_propagation_policy(TPP_DONT); message_port_register_in(msg_port_id); set_msg_handler(msg_port_id, boost::bind(&header_payload_demux_impl::parse_header_data_msg, this, _1)); } header_payload_demux_impl::~header_payload_demux_impl() { } void header_payload_demux_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) { int n_items_reqd = 0; if (d_state == STATE_HEADER) { n_items_reqd = d_header_len * (d_items_per_symbol + d_gi); } else if (d_state == STATE_PAYLOAD) { n_items_reqd = d_curr_payload_len * (d_items_per_symbol + d_gi); } else { n_items_reqd = noutput_items * (d_items_per_symbol + d_gi); if (!d_output_symbols) { // here, noutput_items is an integer multiple of d_items_per_symbol! n_items_reqd /= d_items_per_symbol; } } for (unsigned i = 0; i < ninput_items_required.size(); i++) { ninput_items_required[i] = n_items_reqd; } } inline bool header_payload_demux_impl::check_items_available( int n_symbols, gr_vector_int &ninput_items, int noutput_items, int nread ) { // Check there's enough items on the input if ((n_symbols * (d_items_per_symbol + d_gi)) > (ninput_items[0]-nread) || (ninput_items.size() == 2 && ((n_symbols * (d_items_per_symbol + d_gi)) > (ninput_items[1]-nread)))) { return false; } // Check there's enough space on the output buffer if (d_output_symbols) { if (noutput_items < n_symbols) { return false; } } else { if (noutput_items < n_symbols * d_items_per_symbol) { return false; } } return true; } int header_payload_demux_impl::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out_header = (unsigned char *) output_items[0]; unsigned char *out_payload = (unsigned char *) output_items[1]; int nread = 0; int trigger_offset = 0; switch (d_state) { case STATE_WAIT_FOR_MSG: // In an ideal world, this would never be called return 0; case STATE_HEADER_RX_FAIL: consume_each (1); in += d_itemsize; nread++; d_state = STATE_FIND_TRIGGER; // Fall through case STATE_FIND_TRIGGER: trigger_offset = find_trigger_signal(nread, noutput_items, input_items); if (trigger_offset == -1) { consume_each(noutput_items - nread); break; } consume_each (trigger_offset); in += trigger_offset * d_itemsize; d_state = STATE_HEADER; // Fall through case STATE_HEADER: if (check_items_available(d_header_len, ninput_items, noutput_items, nread)) { copy_n_symbols(in, out_header, 0, d_header_len); d_state = STATE_WAIT_FOR_MSG; produce(0, d_header_len * (d_output_symbols ? 1 : d_items_per_symbol)); } break; case STATE_HEADER_RX_SUCCESS: for (unsigned i = 0; i < d_payload_tag_keys.size(); i++) { add_item_tag(1, nitems_written(1), d_payload_tag_keys[i], d_payload_tag_values[i]); } consume_each (d_header_len * (d_items_per_symbol + d_gi)); in += d_header_len * (d_items_per_symbol + d_gi) * d_itemsize; nread += d_header_len * (d_items_per_symbol + d_gi); d_state = STATE_PAYLOAD; // Fall through case STATE_PAYLOAD: if (check_items_available(d_curr_payload_len, ninput_items, noutput_items, nread)) { copy_n_symbols(in, out_payload, 1, d_curr_payload_len); produce(1, d_curr_payload_len * (d_output_symbols ? 1 : d_items_per_symbol)); consume_each (d_curr_payload_len * (d_items_per_symbol + d_gi)); d_state = STATE_FIND_TRIGGER; set_min_noutput_items(d_output_symbols ? 1 : (d_items_per_symbol + d_gi)); } break; default: throw std::runtime_error("invalid state"); } /* switch */ return WORK_CALLED_PRODUCE; } /* general_work() */ int header_payload_demux_impl::find_trigger_signal( int nread, int noutput_items, gr_vector_const_void_star &input_items) { if (input_items.size() == 2) { unsigned char *in_trigger = (unsigned char *) input_items[1]; in_trigger += nread; for (int i = 0; i < noutput_items-nread; i++) { if (in_trigger[i]) { return i; } } } if (d_uses_trigger_tag) { std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+noutput_items); uint64_t min_offset = ULLONG_MAX; int tag_index = -1; for (unsigned i = 0; i < tags.size(); i++) { if (tags[i].key == d_trigger_tag_key && tags[i].offset < min_offset) { tag_index = (int) i; min_offset = tags[i].offset; } } if (tag_index != -1) { remove_item_tag(0, tags[tag_index]); return min_offset - nitems_read(0); } } return -1; } void header_payload_demux_impl::parse_header_data_msg(pmt::pmt_t header_data) { d_payload_tag_keys.clear(); d_payload_tag_values.clear(); d_state = STATE_HEADER_RX_FAIL; if (pmt::is_integer(header_data)) { d_curr_payload_len = pmt::to_long(header_data); d_payload_tag_keys.push_back(d_len_tag_key); d_payload_tag_values.push_back(header_data); d_state = STATE_HEADER_RX_SUCCESS; } else if (pmt::is_dict(header_data)) { pmt::pmt_t dict_items(pmt::dict_items(header_data)); while (!pmt::is_null(dict_items)) { pmt::pmt_t this_item(pmt::car(dict_items)); d_payload_tag_keys.push_back(pmt::car(this_item)); d_payload_tag_values.push_back(pmt::cdr(this_item)); if (pmt::equal(pmt::car(this_item), d_len_tag_key)) { d_curr_payload_len = pmt::to_long(pmt::cdr(this_item)); d_state = STATE_HEADER_RX_SUCCESS; } dict_items = pmt::cdr(dict_items); } if (d_state == STATE_HEADER_RX_FAIL) { GR_LOG_CRIT(d_logger, "no length tag passed from header data"); } } else if (header_data == pmt::PMT_F || pmt::is_null(header_data)) { GR_LOG_INFO(d_logger, boost::format("Parser returned %1%") % pmt::write_string(header_data)); } else { GR_LOG_ALERT(d_logger, boost::format("Received illegal header data (%1%)") % pmt::write_string(header_data)); } if (d_state == STATE_HEADER_RX_SUCCESS) { if ((d_curr_payload_len * (d_output_symbols ? 1 : d_items_per_symbol)) > max_output_buffer(1)/2) { d_state = STATE_HEADER_RX_FAIL; GR_LOG_INFO(d_logger, boost::format("Detected a packet larger than max frame size (%1% symbols)") % d_curr_payload_len); } else { set_min_noutput_items(d_curr_payload_len * (d_output_symbols ? 1 : d_items_per_symbol)); } } } void header_payload_demux_impl::copy_n_symbols( const unsigned char *in, unsigned char *out, int port, int n_symbols ) { // Copy samples if (d_gi) { for (int i = 0; i < n_symbols; i++) { memcpy((void *) out, (void *) (in + d_gi * d_itemsize), d_items_per_symbol * d_itemsize); in += d_itemsize * (d_items_per_symbol + d_gi); out += d_itemsize * d_items_per_symbol; } } else { memcpy( (void *) out, (void *) in, n_symbols * d_items_per_symbol * d_itemsize ); } // Copy tags std::vector tags; get_tags_in_range( tags, 0, nitems_read(0), nitems_read(0) + n_symbols * (d_items_per_symbol + d_gi) ); for (unsigned t = 0; t < tags.size(); t++) { int new_offset = tags[t].offset - nitems_read(0); if (d_output_symbols) { new_offset /= (d_items_per_symbol + d_gi); } else if (d_gi) { int pos_on_symbol = (new_offset % (d_items_per_symbol + d_gi)) - d_gi; if (pos_on_symbol < 0) { pos_on_symbol = 0; } new_offset = (new_offset / (d_items_per_symbol + d_gi)) + pos_on_symbol; } add_item_tag(port, nitems_written(port) + new_offset, tags[t].key, tags[t].value ); } } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/probe_mpsk_snr_est_c_impl.h0000664000175000017500000000434412207440367023521 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PROBE_MPSK_SNR_EST_C_IMPL_H #define INCLUDED_DIGITAL_PROBE_MPSK_SNR_EST_C_IMPL_H #include namespace gr { namespace digital { class probe_mpsk_snr_est_c_impl : public probe_mpsk_snr_est_c { private: snr_est_type_t d_type; int d_nsamples, d_count; double d_alpha; mpsk_snr_est *d_snr_est; //d_key is the message name, 'snr' pmt::pmt_t d_key; public: probe_mpsk_snr_est_c_impl(snr_est_type_t type, int msg_nsamples=10000, double alpha=0.001); ~probe_mpsk_snr_est_c_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); //! Return the estimated signal-to-noise ratio in decibels double snr(); //! Return the type of estimator in use snr_est_type_t type() const; //! Return how many samples between SNR messages int msg_nsample() const; //! Get the running-average coefficient double alpha() const; //! Set type of estimator to use void set_type(snr_est_type_t t); //! Set the number of samples between SNR messages void set_msg_nsample(int n); //! Set the running-average coefficient void set_alpha(double alpha); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_PROBE_MPSK_SNR_EST_C_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_frame_sink_impl.h0000664000175000017500000000664612207440367022453 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_FRAME_SINK_IMPL_H #define INCLUDED_DIGITAL_OFDM_FRAME_SINK_IMPL_H #include namespace gr { namespace digital { class ofdm_frame_sink_impl : public ofdm_frame_sink { private: enum state_t {STATE_SYNC_SEARCH, STATE_HAVE_SYNC, STATE_HAVE_HEADER}; static const int MAX_PKT_LEN = 4096; static const int HEADERBYTELEN = 4; msg_queue::sptr d_target_queue; // where to send the packet when received state_t d_state; unsigned int d_header; // header bits int d_headerbytelen_cnt; // how many so far char *d_bytes_out; // hold the current bytes produced by the demapper int d_occupied_carriers; unsigned int d_byte_offset; unsigned int d_partial_byte; char d_packet[MAX_PKT_LEN]; // assembled payload int d_packetlen; // length of packet int d_packet_whitener_offset; // offset into whitener string to use int d_packetlen_cnt; // how many so far gr_complex * d_derotated_output; // Pointer to output stream to send deroated symbols out std::vector d_sym_position; std::vector d_sym_value_out; std::vector d_dfe; unsigned int d_nbits; char d_resid; unsigned int d_nresid; float d_phase; float d_freq; float d_phase_gain; float d_freq_gain; float d_eq_gain; std::vector d_subcarrier_map; protected: void enter_search(); void enter_have_sync(); void enter_have_header(); bool header_ok() { // confirm that two copies of header info are identical return ((d_header >> 16) ^ (d_header & 0xffff)) == 0; } char slicer(const gr_complex x); unsigned int demapper(const gr_complex *in, char *out); bool set_sym_value_out(const std::vector &sym_position, const std::vector &sym_value_out); public: ofdm_frame_sink_impl(const std::vector &sym_position, const std::vector &sym_value_out, msg_queue::sptr target_queue, int occupied_tones, float phase_gain=0.25, float freq_gain=0.25*0.25/4); ~ofdm_frame_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_OFDM_FRAME_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/mpsk_snr_est_cc_impl.cc0000664000175000017500000001133512207440367022631 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "mpsk_snr_est_cc_impl.h" #include #include namespace gr { namespace digital { mpsk_snr_est_cc::sptr mpsk_snr_est_cc::make(snr_est_type_t type, int tag_nsamples, double alpha) { return gnuradio::get_initial_sptr (new mpsk_snr_est_cc_impl(type, tag_nsamples, alpha)); } mpsk_snr_est_cc_impl::mpsk_snr_est_cc_impl(snr_est_type_t type, int tag_nsamples, double alpha) : sync_block("mpsk_snr_est_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))) { d_snr_est = NULL; d_type = type; d_nsamples = tag_nsamples; d_count = 0; set_alpha(alpha); set_type(type); // at least 1 estimator has to look back set_history(2); std::stringstream str; str << name() << unique_id(); d_me = pmt::string_to_symbol(str.str()); d_key = pmt::string_to_symbol("snr"); } mpsk_snr_est_cc_impl::~mpsk_snr_est_cc_impl() { if(d_snr_est) delete d_snr_est; } int mpsk_snr_est_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // This is a pass-through block; copy input to output memcpy(output_items[0], input_items[0], noutput_items * sizeof(gr_complex)); const gr_complex *in = (const gr_complex*)input_items[0]; // Update, calculate, and issue an SNR tag every d_nsamples int index = 0, x = 0; int64_t nwritten = nitems_written(0); while(index + (d_nsamples-d_count) < noutput_items) { x = d_nsamples - d_count; nwritten += x; // Update the SNR estimate registers from the current input d_snr_est->update(x, &in[index]); // Issue a tag with the SNR data pmt::pmt_t pmt_snr = pmt::from_double(d_snr_est->snr()); add_item_tag(0, // stream ID nwritten, // tag's sample number d_key, // snr key pmt_snr, // SNR d_me); // block src id index += x; d_count = 0; } // Keep track of remaining items and update estimators x = noutput_items - index; d_count += x; d_snr_est->update(x, &in[index]); return noutput_items; } double mpsk_snr_est_cc_impl::snr() { if(d_snr_est) return d_snr_est->snr(); else throw std::runtime_error("mpsk_snr_est_cc_impl:: No SNR estimator defined.\n"); } snr_est_type_t mpsk_snr_est_cc_impl::type() const { return d_type; } int mpsk_snr_est_cc_impl::tag_nsample() const { return d_nsamples; } double mpsk_snr_est_cc_impl::alpha() const { return d_alpha; } void mpsk_snr_est_cc_impl::set_type(snr_est_type_t t) { d_type = t; if(d_snr_est) delete d_snr_est; switch(d_type) { case(SNR_EST_SIMPLE): d_snr_est = new mpsk_snr_est_simple(d_alpha); break; case(SNR_EST_SKEW): d_snr_est = new mpsk_snr_est_skew(d_alpha); break; case(SNR_EST_M2M4): d_snr_est = new mpsk_snr_est_m2m4(d_alpha); break; case(SNR_EST_SVR): d_snr_est = new mpsk_snr_est_svr(d_alpha); break; default: throw std::invalid_argument("mpsk_snr_est_cc_impl: unknown type specified.\n"); } } void mpsk_snr_est_cc_impl::set_tag_nsample(int n) { if(n > 0) { d_nsamples = n; d_count = 0; // reset state } else throw std::invalid_argument("mpsk_snr_est_cc_impl: tag_nsamples can't be <= 0\n"); } void mpsk_snr_est_cc_impl::set_alpha(double alpha) { if((alpha >= 0) && (alpha <= 1.0)) { d_alpha = alpha; if(d_snr_est) d_snr_est->set_alpha(d_alpha); } else throw std::invalid_argument("mpsk_snr_est_cc_impl: alpha must be in [0,1]\n"); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_serializer_vcc_impl.cc0000664000175000017500000001535412241760655023476 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "ofdm_serializer_vcc_impl.h" namespace gr { namespace digital { ofdm_serializer_vcc::sptr ofdm_serializer_vcc::make( int fft_len, const std::vector > &occupied_carriers, const std::string &len_tag_key, const std::string &packet_len_tag_key, int symbols_skipped, const std::string &carr_offset_key, bool input_is_shifted ) { return gnuradio::get_initial_sptr ( new ofdm_serializer_vcc_impl( fft_len, occupied_carriers, len_tag_key, packet_len_tag_key, symbols_skipped, carr_offset_key, input_is_shifted ) ); } ofdm_serializer_vcc::sptr ofdm_serializer_vcc::make( const gr::digital::ofdm_carrier_allocator_cvc::sptr &allocator, const std::string &packet_len_tag_key, int symbols_skipped, const std::string &carr_offset_key, bool input_is_shifted ) { return gnuradio::get_initial_sptr( new ofdm_serializer_vcc_impl( allocator->fft_len(), allocator->occupied_carriers(), allocator->len_tag_key(), packet_len_tag_key, symbols_skipped, carr_offset_key, !input_is_shifted ) ); } ofdm_serializer_vcc_impl::ofdm_serializer_vcc_impl ( int fft_len, const std::vector > &occupied_carriers, const std::string &len_tag_key, const std::string &packet_len_tag_key, int symbols_skipped, const std::string &carr_offset_key, bool input_is_shifted) : tagged_stream_block ("ofdm_serializer_vcc", io_signature::make(1, 1, sizeof (gr_complex) * fft_len), io_signature::make(1, 1, sizeof (gr_complex)), len_tag_key), d_fft_len(fft_len), d_occupied_carriers(occupied_carriers), d_packet_len_tag_key(pmt::string_to_symbol(packet_len_tag_key)), d_out_len_tag_key(pmt::string_to_symbol((packet_len_tag_key.empty() ? len_tag_key : packet_len_tag_key))), d_symbols_skipped(symbols_skipped % occupied_carriers.size()), d_carr_offset_key(pmt::string_to_symbol(carr_offset_key)), d_curr_set(symbols_skipped % occupied_carriers.size()), d_symbols_per_set(0) { for (unsigned i = 0; i < d_occupied_carriers.size(); i++) { for (unsigned k = 0; k < d_occupied_carriers[i].size(); k++) { if (input_is_shifted) { d_occupied_carriers[i][k] += fft_len/2; if (d_occupied_carriers[i][k] > fft_len) { d_occupied_carriers[i][k] -= fft_len; } } else { if (d_occupied_carriers[i][k] < 0) { d_occupied_carriers[i][k] += fft_len; } } if (d_occupied_carriers[i][k] >= fft_len || d_occupied_carriers[i][k] < 0) { throw std::invalid_argument("ofdm_serializer_vcc: trying to occupy a carrier outside the fft length."); } } } for (unsigned i = 0; i < d_occupied_carriers.size(); i++) { d_symbols_per_set += d_occupied_carriers[i].size(); } set_relative_rate((double) d_symbols_per_set / d_occupied_carriers.size()); set_tag_propagation_policy(TPP_DONT); } ofdm_serializer_vcc_impl::~ofdm_serializer_vcc_impl() { } int ofdm_serializer_vcc_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { int nout = (ninput_items[0] / d_occupied_carriers.size()) * d_symbols_per_set; for (unsigned i = 0; i < ninput_items[0] % d_occupied_carriers.size(); i++) { nout += d_occupied_carriers[(i + d_curr_set) % d_occupied_carriers.size()].size(); } return nout; } void ofdm_serializer_vcc_impl::update_length_tags(int n_produced, int n_ports) { add_item_tag(0, nitems_written(0), d_out_len_tag_key, pmt::from_long(n_produced) ); } int ofdm_serializer_vcc_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; long frame_length = ninput_items[0]; // Input frame long packet_length = 0; // Output frame int carr_offset = 0; std::vector tags; // Packet mode if (!d_length_tag_key_str.empty()) { get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+1); for (unsigned i = 0; i < tags.size(); i++) { if (tags[i].key == d_carr_offset_key) { carr_offset = pmt::to_long(tags[i].value); } if (tags[i].key == d_packet_len_tag_key) { packet_length = pmt::to_long(tags[i].value); remove_item_tag(0, tags[i]); } } } else { // recalc frame length from noutput_items frame_length = 0; int sym_per_frame = 0; while ((sym_per_frame + d_occupied_carriers[(frame_length + 1) % d_occupied_carriers.size()].size()) < (size_t)noutput_items) { frame_length++; sym_per_frame += d_occupied_carriers[(frame_length + 1) % d_occupied_carriers.size()].size(); } } // Copy symbols int n_out_symbols = 0; for (int i = 0; i < frame_length; i++) { // Copy all tags associated with this input OFDM symbol onto the first output symbol get_tags_in_range(tags, 0, nitems_read(0)+i, nitems_read(0)+i+1 ); for (unsigned t = 0; t < tags.size(); t++) { add_item_tag(0, nitems_written(0)+n_out_symbols, tags[t].key, tags[t].value ); } for (unsigned k = 0; k < d_occupied_carriers[d_curr_set].size(); k++) { out[n_out_symbols++] = in[i * d_fft_len + d_occupied_carriers[d_curr_set][k] + carr_offset]; } if (packet_length && n_out_symbols > packet_length) { n_out_symbols = packet_length; break; } d_curr_set = (d_curr_set + 1) % d_occupied_carriers.size(); } // Housekeeping if (d_length_tag_key_str.empty()) { consume_each(frame_length); } else { d_curr_set = d_symbols_skipped; } return n_out_symbols; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/correlate_access_code_tag_bb_impl.cc0000664000175000017500000000756512207440367025260 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "correlate_access_code_tag_bb_impl.h" #include #include #include #include #include namespace gr { namespace digital { #define VERBOSE 0 correlate_access_code_tag_bb::sptr correlate_access_code_tag_bb::make(const std::string &access_code, int threshold, const std::string &tag_name) { return gnuradio::get_initial_sptr (new correlate_access_code_tag_bb_impl(access_code, threshold, tag_name)); } correlate_access_code_tag_bb_impl::correlate_access_code_tag_bb_impl( const std::string &access_code, int threshold, const std::string &tag_name) : sync_block("correlate_access_code_tag_bb", io_signature::make(1, 1, sizeof(char)), io_signature::make(1, 1, sizeof(char))), d_data_reg(0), d_mask(0), d_threshold(threshold), d_len(0) { if(!set_access_code(access_code)) { throw std::out_of_range ("access_code is > 64 bits"); } std::stringstream str; str << name() << unique_id(); d_me = pmt::string_to_symbol(str.str()); d_key = pmt::string_to_symbol(tag_name); } correlate_access_code_tag_bb_impl::~correlate_access_code_tag_bb_impl() { } bool correlate_access_code_tag_bb_impl::set_access_code( const std::string &access_code) { d_len = access_code.length(); // # of bytes in string if(d_len > 64) return false; // set len top bits to 1. d_mask = ((~0ULL) >> (64 - d_len)) << (64 - d_len); d_access_code = 0; for(unsigned i=0; i < 64; i++){ d_access_code <<= 1; if(i < d_len) d_access_code |= access_code[i] & 1; // look at LSB only } return true; } int correlate_access_code_tag_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; uint64_t abs_out_sample_cnt = nitems_written(0); for(int i = 0; i < noutput_items; i++) { out[i] = in[i]; // compute hamming distance between desired access code and current data unsigned long long wrong_bits = 0; unsigned int nwrong = d_threshold+1; int new_flag = 0; wrong_bits = (d_data_reg ^ d_access_code) & d_mask; nwrong = gr::blocks::count_bits64(wrong_bits); // test for access code with up to threshold errors new_flag = (nwrong <= d_threshold); // shift in new data and new flag d_data_reg = (d_data_reg << 1) | (in[i] & 0x1); if(new_flag) { if(VERBOSE) std::cerr << "writing tag at sample " << abs_out_sample_cnt + i << std::endl; add_item_tag(0, //stream ID abs_out_sample_cnt + i - 64 + d_len, //sample d_key, //frame info pmt::pmt_t(), //data (unused) d_me //block src id ); } } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/kurtotic_equalizer_cc_impl.h0000664000175000017500000000565712243706713023723 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_KURTOTIC_EQUALIZER_CC_IMPL_H #define INCLUDED_DIGITAL_KURTOTIC_EQUALIZER_CC_IMPL_H #include #include #include #include namespace gr { namespace digital { class kurtotic_equalizer_cc_impl : public kurtotic_equalizer_cc, filter::kernel::fir_filter_ccc { private: std::vector d_new_taps; gr_complex d_error; float d_mu; float d_p, d_m; gr_complex d_q, d_u; float d_alpha_p, d_alpha_q, d_alpha_m; gr_complex sign(gr_complex x) { float re = (float)(x.real() >= 0.0f); float im = (float)(x.imag() >= 0.0f); return gr_complex(re, im); } protected: virtual gr_complex error(const gr_complex &out) { // p = E[|z|^2] // q = E[z^2] // m = E[|z|^4] // u = E[kurtosis(z)] float nrm = norm(out); gr_complex cnj = conj(out); float epsilon_f = 1e-12; gr_complex epsilon_c = gr_complex(1e-12, 1e-12); d_p = (1-d_alpha_p)*d_p + (d_alpha_p)*nrm + epsilon_f; d_q = (1-d_alpha_q)*d_q + (d_alpha_q)*out*out + epsilon_c; d_m = (1-d_alpha_m)*d_m + (d_alpha_m)*nrm*nrm + epsilon_f; d_u = d_m - 2.0f*(d_p*d_p) - d_q*d_q; gr_complex F = (1.0f / (d_p*d_p*d_p)) * (sign(d_u) * (nrm*cnj - 2.0f*d_p*cnj - conj(d_q)*out) - abs(d_u)*cnj); float re = gr::clip(F.real(), 1.0); float im = gr::clip(F.imag(), 1.0); return gr_complex(re, im); } virtual void update_tap(gr_complex &tap, const gr_complex &in) { tap += d_mu*in*d_error; } public: kurtotic_equalizer_cc_impl(int num_taps, float mu); ~kurtotic_equalizer_cc_impl(); float gain() const { return d_mu; } void set_gain(float mu) { if(mu < 0) throw std::out_of_range("kurtotic_equalizer_cc_impl::set_gain: Gain value must be >= 0"); d_mu = mu; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_KURTOTIC_EQUALIZER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_sampler_impl.cc0000664000175000017500000001117012207440367022122 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2008,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ofdm_sampler_impl.h" #include #include #include namespace gr { namespace digital { ofdm_sampler::sptr ofdm_sampler::make(unsigned int fft_length, unsigned int symbol_length, unsigned int timeout) { return gnuradio::get_initial_sptr (new ofdm_sampler_impl(fft_length, symbol_length, timeout)); } ofdm_sampler_impl::ofdm_sampler_impl(unsigned int fft_length, unsigned int symbol_length, unsigned int timeout) : block("ofdm_sampler", io_signature::make2(2, 2, sizeof(gr_complex), sizeof(char)), io_signature::make2(2, 2, sizeof(gr_complex)*fft_length, sizeof(char)*fft_length)), d_state(STATE_NO_SIG), d_timeout_max(timeout), d_fft_length(fft_length), d_symbol_length(symbol_length) { set_relative_rate(1.0/(double) fft_length); // buffer allocator hint } ofdm_sampler_impl::~ofdm_sampler_impl() { } void ofdm_sampler_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // FIXME do we need more //int nreqd = (noutput_items-1) * d_symbol_length + d_fft_length; int nreqd = d_symbol_length + d_fft_length; unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = nreqd; } int ofdm_sampler_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *iptr = (const gr_complex*)input_items[0]; const char *trigger = (const char*)input_items[1]; gr_complex *optr = (gr_complex*)output_items[0]; char *outsig = (char*)output_items[1]; //FIXME: we only process a single OFDM symbol at a time; after the preamble, we can // process a few at a time as long as we always look out for the next preamble. unsigned int index = d_fft_length; // start one fft length into the input so we can always look back this far outsig[0] = 0; // set output to no signal by default // Search for a preamble trigger signal during the next symbol length while((d_state != STATE_PREAMBLE) && (index <= (d_symbol_length+d_fft_length))) { if(trigger[index]) { outsig[0] = 1; // tell the next block there is a preamble coming d_state = STATE_PREAMBLE; } else index++; } unsigned int i, pos, ret; switch(d_state) { case(STATE_PREAMBLE): // When we found a preamble trigger, get it and set the symbol boundary here for(i = (index - d_fft_length + 1); i <= index; i++) { *optr++ = iptr[i]; } d_timeout = d_timeout_max; // tell the system to expect at least this many symbols for a frame d_state = STATE_FRAME; consume_each(index - d_fft_length + 1); // consume up to one fft_length away to keep the history ret = 1; break; case(STATE_FRAME): // use this state when we have processed a preamble and are getting the rest of the frames //FIXME: we could also have a power squelch system here to enter STATE_NO_SIG if no power is received // skip over fft length history and cyclic prefix pos = d_symbol_length; // keeps track of where we are in the input buffer while(pos < d_symbol_length + d_fft_length) { *optr++ = iptr[pos++]; } if(d_timeout-- == 0) { printf("TIMEOUT\n"); d_state = STATE_NO_SIG; } consume_each(d_symbol_length); // jump up by 1 fft length and the cyclic prefix length ret = 1; break; case(STATE_NO_SIG): default: consume_each(index-d_fft_length); // consume everything we've gone through so far leaving the fft length history ret = 0; break; } return ret; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/constellation_receiver_cb_impl.cc0000664000175000017500000001556512243706713024674 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "constellation_receiver_cb_impl.h" #include #include #include #include #include namespace gr { namespace digital { #define M_TWOPI (2*M_PI) #define VERBOSE_MM 0 // Used for debugging symbol timing loop #define VERBOSE_COSTAS 0 // Used for debugging phase and frequency tracking constellation_receiver_cb::sptr constellation_receiver_cb::make(constellation_sptr constell, float loop_bw, float fmin, float fmax) { return gnuradio::get_initial_sptr (new constellation_receiver_cb_impl(constell, loop_bw, fmin, fmax)); } static int ios[] = {sizeof(char), sizeof(float), sizeof(float), sizeof(float), sizeof(gr_complex)}; static std::vector iosig(ios, ios+sizeof(ios)/sizeof(int)); constellation_receiver_cb_impl::constellation_receiver_cb_impl(constellation_sptr constellation, float loop_bw, float fmin, float fmax) : block("constellation_receiver_cb", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::makev(1, 5, iosig)), blocks::control_loop(loop_bw, fmax, fmin), d_constellation(constellation), d_current_const_point(0) { if(d_constellation->dimensionality() != 1) throw std::runtime_error("This receiver only works with constellations of dimension 1."); message_port_register_in(pmt::mp("set_constellation")); set_msg_handler( pmt::mp("set_constellation"), boost::bind(&constellation_receiver_cb_impl::handle_set_constellation, this, _1)); } constellation_receiver_cb_impl::~constellation_receiver_cb_impl() { } void constellation_receiver_cb_impl::phase_error_tracking(float phase_error) { advance_loop(phase_error); phase_wrap(); frequency_limit(); #if VERBOSE_COSTAS printf("cl: phase_error: %f phase: %f freq: %f sample: %f+j%f constellation: %f+j%f\n", phase_error, d_phase, d_freq, sample.real(), sample.imag(), d_constellation->points()[d_current_const_point].real(), d_constellation->points()[d_current_const_point].imag()); #endif } void constellation_receiver_cb_impl::set_phase_freq(float phase, float freq) { d_phase = phase; d_freq = freq; } void constellation_receiver_cb_impl::handle_set_constellation(pmt::pmt_t constellation_pmt) { boost::any constellation_any = pmt::any_ref(constellation_pmt); constellation_sptr constellation = boost::any_cast( constellation_any); set_constellation(constellation); } void constellation_receiver_cb_impl::set_constellation(constellation_sptr constellation) { d_constellation = constellation; } int constellation_receiver_cb_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; int i=0; float phase_error; unsigned int sym_value; gr_complex sample, nco; float *out_err = 0, *out_phase = 0, *out_freq = 0; gr_complex *out_symbol; if(output_items.size() == 5) { out_err = (float*)output_items[1]; out_phase = (float*)output_items[2]; out_freq = (float*)output_items[3]; out_symbol = (gr_complex*)output_items[4]; } std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+ninput_items[0]); tag_checker tchecker(tags); while((i < noutput_items) && (i < ninput_items[0])) { std::vector tags_now; tchecker.get_tags(tags_now, i+nitems_read(0)); for (unsigned int j=0; jdecision_maker_pe(&sample, &phase_error); phase_error_tracking(phase_error); // corrects phase and frequency offsets out[i] = sym_value; if(output_items.size() == 5) { out_err[i] = phase_error; out_phase[i] = d_phase; out_freq[i] = d_freq; out_symbol[i] = sample; } i++; } consume_each(i); return i; } void constellation_receiver_cb_impl::setup_rpc() { #ifdef GR_CTRLPORT // Getters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "frequency", &control_loop::get_frequency, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Frequency Est.", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "phase", &control_loop::get_phase, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Phase Est.", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "loop_bw", &control_loop::get_loop_bandwidth, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Loop bandwidth", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); // Setters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "loop bw", &control_loop::set_loop_bandwidth, pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f), "", "Loop bandwidth", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/diff_encoder_bb_impl.cc0000664000175000017500000000404112207440367022523 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "diff_encoder_bb_impl.h" #include namespace gr { namespace digital { diff_encoder_bb::sptr diff_encoder_bb::make(unsigned int modulus) { return gnuradio::get_initial_sptr (new diff_encoder_bb_impl(modulus)); } diff_encoder_bb_impl::diff_encoder_bb_impl(unsigned int modulus) : sync_block("diff_encoder_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))), d_last_out(0), d_modulus(modulus) { } diff_encoder_bb_impl::~diff_encoder_bb_impl() { } int diff_encoder_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; unsigned last_out = d_last_out; unsigned modulus = d_modulus; for(int i = 0; i < noutput_items; i++) { out[i] = (in[i] + last_out) % modulus; last_out = out[i]; } d_last_out = last_out; return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/costas_loop_cc_impl.cc0000664000175000017500000001562512237515112022447 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "costas_loop_cc_impl.h" #include #include #include #include #include namespace gr { namespace digital { costas_loop_cc::sptr costas_loop_cc::make(float loop_bw, int order) { return gnuradio::get_initial_sptr (new costas_loop_cc_impl(loop_bw, order)); } costas_loop_cc_impl::costas_loop_cc_impl(float loop_bw, int order) : sync_block("costas_loop_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make2(1, 2, sizeof(gr_complex), sizeof(float))), blocks::control_loop(loop_bw, 1.0, -1.0), d_order(order), d_error(0), d_phase_detector(NULL) { // Set up the phase detector to use based on the constellation order switch(d_order) { case 2: d_phase_detector = &costas_loop_cc_impl::phase_detector_2; break; case 4: d_phase_detector = &costas_loop_cc_impl::phase_detector_4; break; case 8: d_phase_detector = &costas_loop_cc_impl::phase_detector_8; break; default: throw std::invalid_argument("order must be 2, 4, or 8"); break; } } costas_loop_cc_impl::~costas_loop_cc_impl() { } float costas_loop_cc_impl::phase_detector_8(gr_complex sample) const { /* This technique splits the 8PSK constellation into 2 squashed QPSK constellations, one when I is larger than Q and one where Q is larger than I. The error is then calculated proportionally to these squashed constellations by the const K = sqrt(2)-1. The signal magnitude must be > 1 or K will incorrectly bias the error value. Ref: Z. Huang, Z. Yi, M. Zhang, K. Wang, "8PSK demodulation for new generation DVB-S2", IEEE Proc. Int. Conf. Communications, Circuits and Systems, Vol. 2, pp. 1447 - 1450, 2004. */ float K = (sqrt(2.0) - 1); if(fabsf(sample.real()) >= fabsf(sample.imag())) { return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() - (sample.imag()>0 ? 1.0 : -1.0) * sample.real() * K); } else { return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() * K - (sample.imag()>0 ? 1.0 : -1.0) * sample.real()); } } float costas_loop_cc_impl::phase_detector_4(gr_complex sample) const { return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() - (sample.imag()>0 ? 1.0 : -1.0) * sample.real()); } float costas_loop_cc_impl::phase_detector_2(gr_complex sample) const { return (sample.real()*sample.imag()); } float costas_loop_cc_impl::error() const { return d_error; } int costas_loop_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *iptr = (gr_complex *) input_items[0]; gr_complex *optr = (gr_complex *) output_items[0]; float *foptr = (float *) output_items[1]; bool write_foptr = output_items.size() >= 2; gr_complex nco_out; std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+noutput_items, pmt::intern("phase_est")); if(write_foptr) { for(int i = 0; i < noutput_items; i++) { if(tags.size() > 0) { if(tags[0].offset-nitems_read(0) == (size_t)i) { d_phase = (float)pmt::to_double(tags[0].value); tags.erase(tags.begin()); } } nco_out = gr_expj(-d_phase); optr[i] = iptr[i] * nco_out; d_error = (*this.*d_phase_detector)(optr[i]); d_error = gr::branchless_clip(d_error, 1.0); advance_loop(d_error); phase_wrap(); frequency_limit(); foptr[i] = d_freq; } } else { for(int i = 0; i < noutput_items; i++) { if(tags.size() > 0) { if(tags[0].offset-nitems_read(0) == (size_t)i) { d_phase = (float)pmt::to_double(tags[0].value); tags.erase(tags.begin()); } } nco_out = gr_expj(-d_phase); optr[i] = iptr[i] * nco_out; d_error = (*this.*d_phase_detector)(optr[i]); d_error = gr::branchless_clip(d_error, 1.0); advance_loop(d_error); phase_wrap(); frequency_limit(); } } return noutput_items; } void costas_loop_cc_impl::setup_rpc() { #ifdef GR_CTRLPORT // Getters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "error", &costas_loop_cc::error, pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Error signal of loop", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "frequency", &control_loop::get_frequency, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Frequency Est.", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "phase", &control_loop::get_phase, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Phase Est.", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "loop_bw", &control_loop::get_loop_bandwidth, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Loop bandwidth", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); // Setters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "loop bw", &control_loop::set_loop_bandwidth, pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f), "", "Loop bandwidth", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_equalizer_simpledfe.cc0000664000175000017500000000663412207440367023500 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { namespace digital { ofdm_equalizer_simpledfe::sptr ofdm_equalizer_simpledfe::make( int fft_len, const gr::digital::constellation_sptr &constellation, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, int symbols_skipped, float alpha, bool input_is_shifted) { return ofdm_equalizer_simpledfe::sptr( new ofdm_equalizer_simpledfe( fft_len, constellation, occupied_carriers, pilot_carriers, pilot_symbols, symbols_skipped, alpha, input_is_shifted ) ); } ofdm_equalizer_simpledfe::ofdm_equalizer_simpledfe( int fft_len, const gr::digital::constellation_sptr &constellation, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, int symbols_skipped, float alpha, bool input_is_shifted) : ofdm_equalizer_1d_pilots(fft_len, occupied_carriers, pilot_carriers, pilot_symbols, symbols_skipped, input_is_shifted), d_constellation(constellation), d_alpha(alpha) { } ofdm_equalizer_simpledfe::~ofdm_equalizer_simpledfe() { } void ofdm_equalizer_simpledfe::equalize(gr_complex *frame, int n_sym, const std::vector &initial_taps, const std::vector &tags) { if (!initial_taps.empty()) { d_channel_state = initial_taps; } gr_complex sym_eq, sym_est; for (int i = 0; i < n_sym; i++) { for (int k = 0; k < d_fft_len; k++) { if (!d_occupied_carriers[k]) { continue; } if (!d_pilot_carriers.empty() && d_pilot_carriers[d_pilot_carr_set][k]) { d_channel_state[k] = d_alpha * d_channel_state[k] + (1-d_alpha) * frame[i*d_fft_len + k] / d_pilot_symbols[d_pilot_carr_set][k]; frame[i*d_fft_len+k] = d_pilot_symbols[d_pilot_carr_set][k]; } else { sym_eq = frame[i*d_fft_len+k] / d_channel_state[k]; d_constellation->map_to_points(d_constellation->decision_maker(&sym_eq), &sym_est); d_channel_state[k] = d_alpha * d_channel_state[k] + (1-d_alpha) * frame[i*d_fft_len + k] / sym_est; frame[i*d_fft_len+k] = sym_est; } } if (!d_pilot_carriers.empty()) { d_pilot_carr_set = (d_pilot_carr_set + 1) % d_pilot_carriers.size(); } } } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_cyclic_prefixer_impl.cc0000664000175000017500000001274012207440367023635 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "ofdm_cyclic_prefixer_impl.h" namespace gr { namespace digital { ofdm_cyclic_prefixer::sptr ofdm_cyclic_prefixer::make(size_t input_size, size_t output_size, int rolloff_len, const std::string &len_tag_key) { return gnuradio::get_initial_sptr (new ofdm_cyclic_prefixer_impl(input_size, output_size, rolloff_len, len_tag_key)); } ofdm_cyclic_prefixer_impl::ofdm_cyclic_prefixer_impl(size_t input_size, size_t output_size, int rolloff_len, const std::string &len_tag_key) : tagged_stream_block ("ofdm_cyclic_prefixer", io_signature::make (1, 1, input_size*sizeof(gr_complex)), io_signature::make (1, 1, sizeof(gr_complex)), len_tag_key), d_fft_len(input_size), d_output_size(output_size), d_cp_size(output_size - input_size), d_rolloff_len(rolloff_len), d_up_flank((rolloff_len ? rolloff_len-1 : 0), 0), d_down_flank((rolloff_len ? rolloff_len-1 : 0), 0), d_delay_line(0, 0) { set_relative_rate(d_output_size); // Flank of length 1 would just be rectangular if (d_rolloff_len == 1) { d_rolloff_len = 0; } if (d_rolloff_len) { d_delay_line.resize(d_rolloff_len-1, 0); if (rolloff_len > d_cp_size) { throw std::invalid_argument("cyclic prefixer: rolloff len must smaller than the cyclic prefix."); } // The actual flanks are one sample shorter than d_rolloff_len, because the // first sample of the up- and down flank is always zero and one, respectively for (int i = 1; i < d_rolloff_len; i++) { d_up_flank[i-1] = 0.5 * (1 + cos(M_PI * i/rolloff_len - M_PI)); d_down_flank[i-1] = 0.5 * (1 + cos(M_PI * (rolloff_len-i)/rolloff_len - M_PI)); } } if (len_tag_key.empty()) { set_output_multiple(d_output_size); } else { set_tag_propagation_policy(TPP_DONT); } } ofdm_cyclic_prefixer_impl::~ofdm_cyclic_prefixer_impl() { } int ofdm_cyclic_prefixer_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { int nout = ninput_items[0] * d_output_size + d_delay_line.size(); return nout; } // Operates in two ways: // - When there's a length tag name specified, operates in packet mode. // Here, an entire OFDM frame is processed at once. The final OFDM symbol // is postfixed with the delay line of the pulse shape. // We manually propagate tags. // - Otherwise, we're in freewheeling mode. Process as many OFDM symbols as // are space for in the output buffer. The delay line is never flushed. // Tags are propagated by the scheduler. int ofdm_cyclic_prefixer_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; int symbols_to_read = 0; // 1) Figure out if we're in freewheeling or packet mode if (!d_length_tag_key_str.empty()) { symbols_to_read = ninput_items[0]; noutput_items = symbols_to_read * d_output_size + d_delay_line.size(); } else { symbols_to_read = std::min(noutput_items / (int) d_output_size, ninput_items[0]); noutput_items = symbols_to_read * d_output_size; } // 2) Do the cyclic prefixing and, optionally, the pulse shaping for (int sym_idx = 0; sym_idx < symbols_to_read; sym_idx++) { memcpy((void *)(out + d_cp_size), (void *) in, d_fft_len * sizeof(gr_complex)); memcpy((void *) out, (void *) (in + d_fft_len - d_cp_size), d_cp_size * sizeof(gr_complex)); if (d_rolloff_len) { for (int i = 0; i < d_rolloff_len-1; i++) { out[i] = out[i] * d_up_flank[i] + d_delay_line[i]; d_delay_line[i] = in[i] * d_down_flank[i]; } } in += d_fft_len; out += d_output_size; } // 3) If we're in packet mode: // - flush the delay line, if applicable // - Propagate tags if (!d_length_tag_key_str.empty()) { if (d_rolloff_len) { for (unsigned i = 0; i < d_delay_line.size(); i++) { *out++ = d_delay_line[i]; } d_delay_line.assign(d_delay_line.size(), 0); } std::vector tags; get_tags_in_range( tags, 0, nitems_read(0), nitems_read(0)+symbols_to_read ); for (unsigned i = 0; i < tags.size(); i++) { tags[i].offset = ((tags[i].offset - nitems_read(0)) * d_output_size) + nitems_written(0); add_item_tag(0, tags[i].offset, tags[i].key, tags[i].value ); } } else { consume_each(symbols_to_read); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/glfsr_source_b_impl.cc0000664000175000017500000000464312207440367022457 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "glfsr_source_b_impl.h" #include #include namespace gr { namespace digital { glfsr_source_b::sptr glfsr_source_b::make(int degree, bool repeat, int mask, int seed) { return gnuradio::get_initial_sptr (new glfsr_source_b_impl(degree, repeat, mask, seed)); } glfsr_source_b_impl::glfsr_source_b_impl(int degree, bool repeat, int mask, int seed) : sync_block("glfsr_source_b", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(unsigned char))), d_repeat(repeat), d_index(0) { if(degree < 1 || degree > 32) throw std::runtime_error("glfsr_source_b_impl: degree must be between 1 and 32 inclusive"); d_length = (unsigned int)((1ULL << degree)-1); if(mask == 0) mask = glfsr::glfsr_mask(degree); d_glfsr = new glfsr(mask, seed); } glfsr_source_b_impl::~glfsr_source_b_impl() { delete d_glfsr; } int glfsr_source_b_impl::mask() const { return d_glfsr->mask(); } int glfsr_source_b_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *out = (char*)output_items[0]; if((d_index > d_length) && d_repeat == false) return -1; /* once through the sequence */ int i; for(i = 0; i < noutput_items; i++) { out[i] = d_glfsr->next_bit(); d_index++; if(d_index > d_length && d_repeat == false) break; } return i; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_carrier_allocator_cvc_impl.h0000664000175000017500000000513312207440367024645 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_CARRIER_ALLOCATOR_CVC_IMPL_H #define INCLUDED_DIGITAL_OFDM_CARRIER_ALLOCATOR_CVC_IMPL_H #include namespace gr { namespace digital { class ofdm_carrier_allocator_cvc_impl : public ofdm_carrier_allocator_cvc { private: //! FFT length const int d_fft_len; //! Which carriers/symbols carry data std::vector > d_occupied_carriers; //! Which carriers/symbols carry pilots symbols std::vector > d_pilot_carriers; //! Value of said pilot symbols const std::vector > d_pilot_symbols; //! Synch words const std::vector > d_sync_words; int d_symbols_per_set; const bool d_output_is_shifted; protected: int calculate_output_stream_length(const gr_vector_int &ninput_items); public: ofdm_carrier_allocator_cvc_impl( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, const std::vector > &sync_words, const std::string &len_tag_key, const bool output_is_shifted ); ~ofdm_carrier_allocator_cvc_impl(); std::string len_tag_key() { return d_length_tag_key_str; }; const int fft_len() { return d_fft_len; }; std::vector > occupied_carriers() { return d_occupied_carriers; }; int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_CARRIER_ALLOCATOR_CVC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/additive_scrambler_bb_impl.h0000664000175000017500000000414512237515112023600 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_ADDITIVE_SCRAMBLER_BB_IMPL_H #define INCLUDED_DIGITAL_ADDITIVE_SCRAMBLER_BB_IMPL_H #include #include namespace gr { namespace digital { class additive_scrambler_bb_impl : public additive_scrambler_bb { private: digital::lfsr d_lfsr; int d_count; //!< Reset the LFSR after this many bytes (not bits) int d_bytes; //!< Count the processed bytes int d_len; int d_seed; int d_bits_per_byte; pmt::pmt_t d_reset_tag_key; //!< Reset the LFSR when this tag is received int _get_next_reset_index(int noutput_items, int last_reset_index=-1); public: additive_scrambler_bb_impl(int mask, int seed, int len, int count=0, int bits_per_byte=1, const std::string &reset_tag_key=""); ~additive_scrambler_bb_impl(); int mask() const; int seed() const; int len() const; int count() const; int bits_per_byte() { return d_bits_per_byte; }; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_ADDITIVE_SCRAMBLER_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_carrier_allocator_cvc_impl.cc0000664000175000017500000001504312237515112024776 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "ofdm_carrier_allocator_cvc_impl.h" namespace gr { namespace digital { ofdm_carrier_allocator_cvc::sptr ofdm_carrier_allocator_cvc::make( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, const std::vector > &sync_words, const std::string &len_tag_key, const bool output_is_shifted ) { return gnuradio::get_initial_sptr( new ofdm_carrier_allocator_cvc_impl( fft_len, occupied_carriers, pilot_carriers, pilot_symbols, sync_words, len_tag_key, output_is_shifted ) ); } ofdm_carrier_allocator_cvc_impl::ofdm_carrier_allocator_cvc_impl( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, const std::vector > &sync_words, const std::string &len_tag_key, const bool output_is_shifted ) : tagged_stream_block("ofdm_carrier_allocator_cvc", io_signature::make(1, 1, sizeof (gr_complex)), io_signature::make(1, 1, sizeof (gr_complex) * fft_len), len_tag_key), d_fft_len(fft_len), d_occupied_carriers(occupied_carriers), d_pilot_carriers(pilot_carriers), d_pilot_symbols(pilot_symbols), d_sync_words(sync_words), d_symbols_per_set(0), d_output_is_shifted(output_is_shifted) { for (unsigned i = 0; i < d_occupied_carriers.size(); i++) { for (unsigned j = 0; j < d_occupied_carriers[i].size(); j++) { if (occupied_carriers[i][j] < 0) { d_occupied_carriers[i][j] += d_fft_len; } if (d_occupied_carriers[i][j] > d_fft_len || d_occupied_carriers[i][j] < 0) { throw std::invalid_argument("data carrier index out of bounds"); } if (d_output_is_shifted) { d_occupied_carriers[i][j] = (d_occupied_carriers[i][j] + fft_len/2) % fft_len; } } } for (unsigned i = 0; i < d_pilot_carriers.size(); i++) { if (d_pilot_carriers[i].size() != pilot_symbols[i].size()) { throw std::invalid_argument("pilot_carriers do not match pilot_symbols"); } for (unsigned j = 0; j < d_pilot_carriers[i].size(); j++) { if (d_pilot_carriers[i][j] < 0) { d_pilot_carriers[i][j] += d_fft_len; } if (d_pilot_carriers[i][j] > d_fft_len || d_pilot_carriers[i][j] < 0) { throw std::invalid_argument("pilot carrier index out of bounds"); } if (d_output_is_shifted) { d_pilot_carriers[i][j] = (d_pilot_carriers[i][j] + fft_len/2) % fft_len; } } } for (unsigned i = 0; i < d_sync_words.size(); i++) { if (d_sync_words[i].size() != (unsigned) d_fft_len) { throw std::invalid_argument("sync words must be fft length"); } } for (unsigned i = 0; i < d_occupied_carriers.size(); i++) { d_symbols_per_set += d_occupied_carriers[i].size(); } set_tag_propagation_policy(TPP_DONT); set_relative_rate((double) d_symbols_per_set / d_occupied_carriers.size()); } ofdm_carrier_allocator_cvc_impl::~ofdm_carrier_allocator_cvc_impl() { } int ofdm_carrier_allocator_cvc_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { int nin = ninput_items[0]; int nout = (nin / d_symbols_per_set) * d_occupied_carriers.size(); int k = 0; for (int i = 0; i < nin % d_symbols_per_set; k++) { nout++; i += d_occupied_carriers[k % d_occupied_carriers.size()].size(); } return nout + d_sync_words.size(); } int ofdm_carrier_allocator_cvc_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; std::vector tags; memset((void *) out, 0x00, sizeof(gr_complex) * d_fft_len * noutput_items); // Copy Sync word for (unsigned i = 0; i < d_sync_words.size(); i++) { memcpy((void *) out, (void *) &d_sync_words[i][0], sizeof(gr_complex) * d_fft_len); out += d_fft_len; } // Copy data symbols long n_ofdm_symbols = 0; // Number of output items int curr_set = 0; int symbols_to_allocate = d_occupied_carriers[0].size(); int symbols_allocated = 0; for (int i = 0; i < ninput_items[0]; i++) { if (symbols_allocated == 0) { // Copy all tags associated with these input symbols onto this OFDM symbol get_tags_in_range(tags, 0, nitems_read(0)+i, nitems_read(0)+std::min(i+symbols_to_allocate, (int) ninput_items[0]) ); for (unsigned t = 0; t < tags.size(); t++) { add_item_tag( 0, nitems_written(0) + n_ofdm_symbols + (n_ofdm_symbols == 0 ? 0 : d_sync_words.size()), tags[t].key, tags[t].value ); } n_ofdm_symbols++; } out[(n_ofdm_symbols-1) * d_fft_len + d_occupied_carriers[curr_set][symbols_allocated]] = in[i]; symbols_allocated++; if (symbols_allocated == symbols_to_allocate) { curr_set = (curr_set + 1) % d_occupied_carriers.size(); symbols_to_allocate = d_occupied_carriers[curr_set].size(); symbols_allocated = 0; } } // Copy pilot symbols curr_set = 0; for (int i = 0; i < n_ofdm_symbols; i++) { for (unsigned k = 0; k < d_pilot_carriers[curr_set].size(); k++) { out[i * d_fft_len + d_pilot_carriers[curr_set][k]] = d_pilot_symbols[curr_set][k]; } curr_set = (curr_set + 1) % d_pilot_carriers.size(); } return n_ofdm_symbols + d_sync_words.size(); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_frame_acquisition_impl.h0000664000175000017500000000630112207440367024023 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_FRAME_ACQUISITION_IMPL_H #define INCLUDED_DIGITAL_OFDM_FRAME_ACQUISITION_IMPL_H #include namespace gr { namespace digital { class ofdm_frame_acquisition_impl : public ofdm_frame_acquisition { private: unsigned char slicer(gr_complex x); void correlate(const gr_complex *symbol, int zeros_on_left); void calculate_equalizer(const gr_complex *symbol, int zeros_on_left); gr_complex coarse_freq_comp(int freq_delta, int count); unsigned int d_occupied_carriers; // !< \brief number of subcarriers with data unsigned int d_fft_length; // !< \brief length of FFT vector unsigned int d_cplen; // !< \brief length of cyclic prefix in samples unsigned int d_freq_shift_len; // !< \brief number of surrounding bins to look at for correlation std::vector d_known_symbol; // !< \brief known symbols at start of frame std::vector d_known_phase_diff; // !< \brief factor used in correlation from known symbol std::vector d_symbol_phase_diff; // !< \brief factor used in correlation from received symbol std::vector d_hestimate; // !< channel estimate int d_coarse_freq; // !< \brief search distance in number of bins unsigned int d_phase_count; // !< \brief accumulator for coarse freq correction float d_snr_est; // !< an estimation of the signal to noise ratio gr_complex *d_phase_lut; // !< look-up table for coarse frequency compensation void forecast(int noutput_items, gr_vector_int &ninput_items_required); public: ofdm_frame_acquisition_impl(unsigned int occupied_carriers, unsigned int fft_length, unsigned int cplen, const std::vector &known_symbol, unsigned int max_fft_shift_len=4); ~ofdm_frame_acquisition_impl(); /*! * \brief Return an estimate of the SNR of the channel */ float snr() { return d_snr_est; } int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_FRAME_ACQUISITION_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/gnuradio-digital.rc.in0000664000175000017500000000333212207440367022301 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-digital" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-digital.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-digital.dll" VALUE "ProductName", "gnuradio-digital" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-digital/lib/probe_density_b_impl.h0000664000175000017500000000316212207440367022465 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PROBE_DENSITY_B_IMPL_H #define INCLUDED_GR_PROBE_DENSITY_B_IMPL_H #include namespace gr { namespace digital { class probe_density_b_impl : public probe_density_b { private: double d_alpha; double d_beta; double d_density; public: probe_density_b_impl(double alpha); ~probe_density_b_impl(); /*! * \brief Returns the current density value */ double density() const { return d_density; } /*! * \brief Set the average filter constant */ void set_alpha(double alpha); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_PROBE_DENSITY_B_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/framer_sink_1_impl.h0000664000175000017500000000535112207440367022040 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FRAMER_SINK_1_IMPL_H #define INCLUDED_GR_FRAMER_SINK_1_IMPL_H #include namespace gr { namespace digital { class framer_sink_1_impl : public framer_sink_1 { private: enum state_t {STATE_SYNC_SEARCH, STATE_HAVE_SYNC, STATE_HAVE_HEADER}; static const int MAX_PKT_LEN = 4096; static const int HEADERBITLEN = 32; msg_queue::sptr d_target_queue; // where to send the packet when received state_t d_state; unsigned int d_header; // header bits int d_headerbitlen_cnt; // how many so far unsigned char d_packet[MAX_PKT_LEN]; // assembled payload unsigned char d_packet_byte; // byte being assembled int d_packet_byte_index; // which bit of d_packet_byte we're working on int d_packetlen; // length of packet int d_packet_whitener_offset; // offset into whitener string to use int d_packetlen_cnt; // how many so far protected: void enter_search(); void enter_have_sync(); void enter_have_header(int payload_len, int whitener_offset); bool header_ok() { // confirm that two copies of header info are identical return ((d_header >> 16) ^ (d_header & 0xffff)) == 0; } void header_payload(int *len, int *offset) { // header consists of two 16-bit shorts in network byte order // payload length is lower 12 bits // whitener offset is upper 4 bits *len = (d_header >> 16) & 0x0fff; *offset = (d_header >> 28) & 0x000f; } public: framer_sink_1_impl(msg_queue::sptr target_queue); ~framer_sink_1_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_FRAMER_SINK_1_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_equalizer_base.cc0000664000175000017500000000752312207440367022440 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { namespace digital { // *** Base class **************************************************** ofdm_equalizer_base::ofdm_equalizer_base(int fft_len) : d_fft_len(fft_len) { } ofdm_equalizer_base::~ofdm_equalizer_base() { } // *** Sub-Base class for 1D equalizers using pilot tones ************* ofdm_equalizer_1d_pilots::ofdm_equalizer_1d_pilots( int fft_len, const std::vector > &occupied_carriers, const std::vector > &pilot_carriers, const std::vector > &pilot_symbols, int symbols_skipped, bool input_is_shifted) : ofdm_equalizer_base(fft_len), d_occupied_carriers(fft_len, false), d_pilot_carriers(pilot_carriers.size(), std::vector(fft_len, false)), d_pilot_symbols(pilot_symbols.size(), std::vector(fft_len, gr_complex(0, 0))), d_symbols_skipped(symbols_skipped), d_pilot_carr_set(pilot_carriers.empty() ? 0 : symbols_skipped % pilot_carriers.size()), d_channel_state(fft_len, gr_complex(1, 0)) { int fft_shift_width = 0; if (input_is_shifted) { fft_shift_width = fft_len/2; } if (!occupied_carriers.size()) { std::fill(d_occupied_carriers.begin(), d_occupied_carriers.end(), true); } else { for (unsigned i = 0; i < occupied_carriers.size(); i++) { for (unsigned k = 0; k < occupied_carriers[i].size(); k++) { int carr_index = occupied_carriers[i][k]; if (occupied_carriers[i][k] < 0) { carr_index += fft_len; } if (carr_index >= fft_len || carr_index < 0) { throw std::invalid_argument("data carrier index out of bounds."); } d_occupied_carriers[(carr_index + fft_shift_width) % fft_len] = true; } } } if (pilot_carriers.size()) { for (unsigned i = 0; i < pilot_carriers.size(); i++) { if (pilot_carriers[i].size() != pilot_symbols[i].size()) { throw std::invalid_argument("pilot carriers and -symbols do not match."); } for (unsigned k = 0; k < pilot_carriers[i].size(); k++) { int carr_index = pilot_carriers[i][k]; if (pilot_carriers[i][k] < 0) { carr_index += fft_len; } if (carr_index >= fft_len || carr_index < 0) { throw std::invalid_argument("pilot carrier index out of bounds."); } d_pilot_carriers[i][(carr_index + fft_shift_width) % fft_len] = true; d_pilot_symbols[i][(carr_index + fft_shift_width) % fft_len] = pilot_symbols[i][k]; } } } } ofdm_equalizer_1d_pilots::~ofdm_equalizer_1d_pilots() { } void ofdm_equalizer_1d_pilots::reset() { std::fill(d_channel_state.begin(), d_channel_state.end(), gr_complex(1, 0)); d_pilot_carr_set = d_pilot_carriers.empty() ? 0 : d_symbols_skipped % d_pilot_carriers.size(); } void ofdm_equalizer_1d_pilots::get_channel_state(std::vector &taps) { taps = d_channel_state; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_chanest_vcvc_impl.h0000664000175000017500000000670412207440367022776 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_CHANEST_VCVC_IMPL_H #define INCLUDED_DIGITAL_OFDM_CHANEST_VCVC_IMPL_H #include namespace gr { namespace digital { class ofdm_chanest_vcvc_impl : public ofdm_chanest_vcvc { private: int d_fft_len; //! FFT length int d_n_data_syms; //! Number of data symbols following the sync symbol(s) int d_n_sync_syms; //! Number of sync symbols (1 or 2) //! 0 if no noise reduction is done for the initial channel state estimation. Otherwise, the maximum length of the channel delay in samples. int d_eq_noise_red_len; //! Is sync_symbol1 if d_n_sync_syms == 1, otherwise sync_symbol2. Used as a reference symbol to estimate the channel. std::vector d_ref_sym; //! If d_n_sync_syms == 2 this is used as a differential correlation vector (called 'v' in [1]). std::vector d_corr_v; //! If d_n_sync_syms == 1 we use this instead of d_corr_v to estimate the coarse freq. offset std::vector d_known_symbol_diffs; //! If d_n_sync_syms == 1 we use this instead of d_corr_v to estimate the coarse freq. offset (temp. variable) std::vector d_new_symbol_diffs; //! The index of the first carrier with data (index 0 is not DC here, but the lowest frequency) int d_first_active_carrier; //! The index of the last carrier with data int d_last_active_carrier; //! If true, the channel estimation must be interpolated bool d_interpolate; //! Maximum carrier offset (negative value!) int d_max_neg_carr_offset; //! Maximum carrier offset (positive value!) int d_max_pos_carr_offset; //! Calculate the coarse frequency offset in number of carriers int get_carr_offset(const gr_complex *sync_sym1, const gr_complex *sync_sym2); //! Estimate the channel (phase and amplitude offset per carrier) void get_chan_taps(const gr_complex *sync_sym1, const gr_complex *sync_sym2, int carr_offset, std::vector &taps); public: ofdm_chanest_vcvc_impl(const std::vector &sync_symbol1, const std::vector &sync_symbol2, int n_data_symbols, int eq_noise_red_len, int max_carr_offset, bool force_one_sync_symbol); ~ofdm_chanest_vcvc_impl(); void forecast (int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_CHANEST_VCVC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/diff_decoder_bb_impl.cc0000664000175000017500000000403312207440367022512 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "diff_decoder_bb_impl.h" #include namespace gr { namespace digital { diff_decoder_bb::sptr diff_decoder_bb::make(unsigned int modulus) { return gnuradio::get_initial_sptr (new diff_decoder_bb_impl(modulus)); } diff_decoder_bb_impl::diff_decoder_bb_impl(unsigned int modulus) : sync_block("diff_decoder_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))), d_modulus(modulus) { set_history(2); // need to look at two inputs } diff_decoder_bb_impl::~diff_decoder_bb_impl() { } int diff_decoder_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; in += 1; // ensure that in[-1] is valid unsigned modulus = d_modulus; for(int i = 0; i < noutput_items; i++) { out[i] = (in[i] - in[i-1]) % modulus; } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/probe_mpsk_snr_est_c_impl.cc0000664000175000017500000000742512207440367023662 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "probe_mpsk_snr_est_c_impl.h" #include #include namespace gr { namespace digital { probe_mpsk_snr_est_c::sptr probe_mpsk_snr_est_c::make(snr_est_type_t type, int msg_nsamples, double alpha) { return gnuradio::get_initial_sptr (new probe_mpsk_snr_est_c_impl(type, msg_nsamples, alpha)); } probe_mpsk_snr_est_c_impl::probe_mpsk_snr_est_c_impl(snr_est_type_t type, int msg_nsamples, double alpha) : sync_block("probe_mpsk_snr_est_c", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(0, 0, 0)) { d_snr_est = NULL; d_type = type; d_nsamples = msg_nsamples; d_count = 0; set_alpha(alpha); set_type(type); // at least 1 estimator has to look back set_history(2); d_key = pmt::string_to_symbol("snr"); } probe_mpsk_snr_est_c_impl::~probe_mpsk_snr_est_c_impl() { if(d_snr_est) delete d_snr_est; } int probe_mpsk_snr_est_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; return d_snr_est->update(noutput_items, in); } double probe_mpsk_snr_est_c_impl::snr() { if(d_snr_est) return d_snr_est->snr(); else throw std::runtime_error("probe_mpsk_snr_est_c_impl:: No SNR estimator defined.\n"); } snr_est_type_t probe_mpsk_snr_est_c_impl::type() const { return d_type; } int probe_mpsk_snr_est_c_impl::msg_nsample() const { return d_nsamples; } double probe_mpsk_snr_est_c_impl::alpha() const { return d_alpha; } void probe_mpsk_snr_est_c_impl::set_type(snr_est_type_t t) { d_type = t; if(d_snr_est) delete d_snr_est; switch (d_type) { case(SNR_EST_SIMPLE): d_snr_est = new mpsk_snr_est_simple(d_alpha); break; case(SNR_EST_SKEW): d_snr_est = new mpsk_snr_est_skew(d_alpha); break; case(SNR_EST_M2M4): d_snr_est = new mpsk_snr_est_m2m4(d_alpha); break; case(SNR_EST_SVR): d_snr_est = new mpsk_snr_est_svr(d_alpha); break; default: throw std::invalid_argument("probe_mpsk_snr_est_c_impl: unknown type specified.\n"); } } void probe_mpsk_snr_est_c_impl::set_msg_nsample(int n) { if(n > 0) { d_nsamples = n; d_count = 0; // reset state } else throw std::invalid_argument("probe_mpsk_snr_est_c_impl: msg_nsamples can't be <= 0\n"); } void probe_mpsk_snr_est_c_impl::set_alpha(double alpha) { if((alpha >= 0) && (alpha <= 1.0)) { d_alpha = alpha; if(d_snr_est) d_snr_est->set_alpha(d_alpha); } else throw std::invalid_argument("probe_mpsk_snr_est_c_impl: alpha must be in [0,1]\n"); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/packet_headerparser_b_impl.h0000664000175000017500000000302112207440367023605 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PACKET_HEADERPARSER_B_IMPL_H #define INCLUDED_DIGITAL_PACKET_HEADERPARSER_B_IMPL_H #include namespace gr { namespace digital { class packet_headerparser_b_impl : public packet_headerparser_b { private: packet_header_default::sptr d_header_formatter; public: packet_headerparser_b_impl(const gr::digital::packet_header_default::sptr &header_formatter); ~packet_headerparser_b_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_PACKET_HEADERPARSER_B_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/constellation.cc0000664000175000017500000006155012244272666021324 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include namespace gr { namespace digital { #define M_TWOPI (2*M_PI) #define SQRT_TWO 0.707107 // Base Constellation Class constellation::constellation(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality ) : d_constellation(constell), d_pre_diff_code(pre_diff_code), d_rotational_symmetry(rotational_symmetry), d_dimensionality(dimensionality), d_re_min(1e20), d_re_max(1e20), d_im_min(1e20), d_im_max(1e20), d_lut_precision(0), d_lut_scale(0) { // Scale constellation points so that average magnitude is 1. float summed_mag = 0; unsigned int constsize = d_constellation.size(); for (unsigned int i=0; i constellation::map_to_points_v(unsigned int value) { std::vector points_v; points_v.resize(d_dimensionality); map_to_points(value, &(points_v[0])); return points_v; } float constellation::get_distance(unsigned int index, const gr_complex *sample) { float dist = 0; for(unsigned int i=0; i constellation::s_points() { if(d_dimensionality != 1) throw std::runtime_error( "s_points only works for dimensionality 1 constellations."); else return d_constellation; } std::vector > constellation::v_points() { std::vector > vv_const; vv_const.resize(d_arity); for(unsigned int p=0; p v_const; v_const.resize(d_dimensionality); for(unsigned int d=0; d sample) { assert(sample.size() == d_dimensionality); return decision_maker(&(sample[0])); } void constellation::gen_soft_dec_lut(int precision, float npwr) { max_min_axes(); d_lut_scale = powf(2.0, static_cast(precision)); float xstep = (d_re_max - d_re_min) / (d_lut_scale-1); float ystep = (d_im_max - d_im_min) / (d_lut_scale-1); d_soft_dec_lut.clear(); float y = d_im_min; while(y < d_im_max) { float x = d_re_min; while(x < d_re_max) { gr_complex pt = gr_complex(x, y); d_soft_dec_lut.push_back(calc_soft_dec(pt, npwr)); x += xstep; } y += ystep; } d_lut_precision = precision; } std::vector constellation::calc_soft_dec(gr_complex sample, float npwr) { int M = static_cast(d_constellation.size()); int k = static_cast(log(static_cast(M))/log(2.0)); std::vector tmp(2*k, 0); std::vector s(k, 0); float scale = d_scalefactor*d_scalefactor; for(int i = 0; i < M; i++) { // Calculate the distance between the sample and the current // constellation point. float dist = powf(std::abs(sample - d_constellation[i]), 2.0f); // Calculate the probability factor from the distance and // the scaled noise power. float d = expf(-dist / (2.0*npwr*scale)); for(int j = 0; j < k; j++) { // Get the bit at the jth index int mask = 1 << j; int bit = (d_pre_diff_code[i] & mask) >> j; // If the bit is a 0, add to the probability of a zero if(bit == 0) tmp[2*j+0] += d; // else, add to the probability of a one else tmp[2*j+1] += d; } } // Calculate the log-likelihood ratio for all bits based on the // probability of ones (tmp[2*i+1]) over the probability of a zero // (tmp[2*i+0]). for(int i = 0; i < k; i++) { s[k-1-i] = (logf(tmp[2*i+1]) - logf(tmp[2*i+0])) * scale; } return s; } void constellation::set_soft_dec_lut(const std::vector< std::vector > &soft_dec_lut, int precision) { max_min_axes(); d_soft_dec_lut = soft_dec_lut; d_lut_precision = precision; d_lut_scale = powf(2.0, static_cast(precision)); } bool constellation::has_soft_dec_lut() { return d_soft_dec_lut.size() > 0; } std::vector constellation::soft_decision_maker(gr_complex sample) { if(has_soft_dec_lut()) { float xre = sample.real(); float xim = sample.imag(); float xstep = (d_re_max-d_re_min) / d_lut_scale; float ystep = (d_im_max-d_im_min) / d_lut_scale; float xscale = (d_lut_scale / (d_re_max-d_re_min)) - xstep; float yscale = (d_lut_scale / (d_im_max-d_im_min)) - ystep; xre = floorf((-d_re_min + std::min(d_re_max, std::max(d_re_min, xre))) * xscale); xim = floorf((-d_im_min + std::min(d_im_max, std::max(d_im_min, xim))) * yscale); int index = static_cast(d_lut_scale*xim + xre); int max_index = d_lut_scale*d_lut_scale; if(index > max_index) { return d_soft_dec_lut[max_index-1]; } if(index < 0) throw std::runtime_error("constellation::soft_decision_maker: input sample out of range."); return d_soft_dec_lut[index]; } else { return calc_soft_dec(sample); } } void constellation::max_min_axes() { // Find min/max of constellation for both real and imag axes. d_re_min = 1e20; d_im_min = 1e20; d_re_max = -1e20; d_im_max = -1e20; for(size_t i = 0; i < d_constellation.size(); i++) { if(d_constellation[i].real() > d_re_max) d_re_max = d_constellation[i].real(); if(d_constellation[i].imag() > d_im_max) d_im_max = d_constellation[i].imag(); if(d_constellation[i].real() < d_re_min) d_re_min = d_constellation[i].real(); if(d_constellation[i].imag() < d_im_min) d_im_min = d_constellation[i].imag(); } if(d_im_min == 0) d_im_min = d_re_min; if(d_im_max == 0) d_im_max = d_re_max; if(d_re_min == 0) d_re_min = d_im_min; if(d_re_max == 0) d_re_max = d_im_max; } /********************************************************************/ constellation_calcdist::sptr constellation_calcdist::make(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality) { return constellation_calcdist::sptr( new constellation_calcdist(constell, pre_diff_code, rotational_symmetry, dimensionality)); } constellation_calcdist::constellation_calcdist( std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality) : constellation(constell, pre_diff_code, rotational_symmetry, dimensionality) {} // Chooses points base on shortest distance. // Inefficient. unsigned int constellation_calcdist::decision_maker(const gr_complex *sample) { return get_closest_point(sample); } /********************************************************************/ constellation_sector::constellation_sector(std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int dimensionality, unsigned int n_sectors) : constellation(constell, pre_diff_code, rotational_symmetry, dimensionality), n_sectors(n_sectors) { } constellation_sector::~constellation_sector() { } unsigned int constellation_sector::decision_maker(const gr_complex *sample) { unsigned int sector; sector = get_sector(sample); return sector_values[sector]; } void constellation_sector::find_sector_values() { unsigned int i; sector_values.clear(); for(i=0; i constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors) { return constellation_rect::sptr(new constellation_rect (constell, pre_diff_code, rotational_symmetry, real_sectors, imag_sectors, width_real_sectors, width_imag_sectors)); } constellation_rect::constellation_rect( std::vector constell, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors) : constellation_sector(constell, pre_diff_code, rotational_symmetry, 1, real_sectors * imag_sectors), n_real_sectors(real_sectors), n_imag_sectors(imag_sectors), d_width_real_sectors(width_real_sectors), d_width_imag_sectors(width_imag_sectors) { d_width_real_sectors *= d_scalefactor; d_width_imag_sectors *= d_scalefactor; find_sector_values(); } constellation_rect::~constellation_rect() { } unsigned int constellation_rect::get_sector(const gr_complex *sample) { int real_sector, imag_sector; unsigned int sector; real_sector = int(real(*sample)/d_width_real_sectors + n_real_sectors/2.0); if(real_sector < 0) real_sector = 0; if(real_sector >= (int)n_real_sectors) real_sector = n_real_sectors-1; imag_sector = int(imag(*sample)/d_width_imag_sectors + n_imag_sectors/2.0); if(imag_sector < 0) imag_sector = 0; if(imag_sector >= (int)n_imag_sectors) imag_sector = n_imag_sectors-1; sector = real_sector * n_imag_sectors + imag_sector; return sector; } gr_complex constellation_rect::calc_sector_center(unsigned int sector) { unsigned int real_sector, imag_sector; gr_complex sector_center; real_sector = float(sector)/n_imag_sectors; imag_sector = sector - real_sector * n_imag_sectors; sector_center = gr_complex( (real_sector + 0.5 - n_real_sectors/2.0) * d_width_real_sectors, (imag_sector + 0.5 - n_imag_sectors/2.0) * d_width_imag_sectors); return sector_center; } unsigned int constellation_rect::calc_sector_value(unsigned int sector) { gr_complex sector_center = calc_sector_center(sector); unsigned int closest_point; closest_point = get_closest_point(§or_center); return closest_point; } /********************************************************************/ constellation_expl_rect::sptr constellation_expl_rect::make(std::vector constellation, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors, std::vector sector_values) { return constellation_expl_rect::sptr (new constellation_expl_rect(constellation, pre_diff_code, rotational_symmetry, real_sectors, imag_sectors, width_real_sectors, width_imag_sectors, sector_values)); } constellation_expl_rect::constellation_expl_rect( std::vector constellation, std::vector pre_diff_code, unsigned int rotational_symmetry, unsigned int real_sectors, unsigned int imag_sectors, float width_real_sectors, float width_imag_sectors, std::vector sector_values) : constellation_rect(constellation, pre_diff_code, rotational_symmetry, real_sectors, imag_sectors, width_real_sectors, width_imag_sectors), d_sector_values(sector_values) { } constellation_expl_rect::~constellation_expl_rect() { } /********************************************************************/ constellation_psk::sptr constellation_psk::make(std::vector constell, std::vector pre_diff_code, unsigned int n_sectors) { return constellation_psk::sptr(new constellation_psk (constell, pre_diff_code, n_sectors)); } constellation_psk::constellation_psk(std::vector constell, std::vector pre_diff_code, unsigned int n_sectors) : constellation_sector(constell, pre_diff_code, constell.size(), 1, n_sectors) { find_sector_values(); } constellation_psk::~constellation_psk() { } unsigned int constellation_psk::get_sector(const gr_complex *sample) { float phase = arg(*sample); float width = M_TWOPI / n_sectors; int sector = floor(phase/width + 0.5); if(sector < 0) sector += n_sectors; return sector; } unsigned int constellation_psk::calc_sector_value(unsigned int sector) { float phase = sector * M_TWOPI / n_sectors; gr_complex sector_center = gr_complex(cos(phase), sin(phase)); unsigned int closest_point = get_closest_point(§or_center); return closest_point; } /********************************************************************/ constellation_bpsk::sptr constellation_bpsk::make() { return constellation_bpsk::sptr(new constellation_bpsk()); } constellation_bpsk::constellation_bpsk() { d_constellation.resize(2); d_constellation[0] = gr_complex(-1, 0); d_constellation[1] = gr_complex(1, 0); d_rotational_symmetry = 2; d_dimensionality = 1; calc_arity(); } constellation_bpsk::~constellation_bpsk() { } unsigned int constellation_bpsk::decision_maker(const gr_complex *sample) { return (real(*sample) > 0); } /********************************************************************/ constellation_qpsk::sptr constellation_qpsk::make() { return constellation_qpsk::sptr(new constellation_qpsk()); } constellation_qpsk::constellation_qpsk() { d_constellation.resize(4); // Gray-coded d_constellation[0] = gr_complex(-SQRT_TWO, -SQRT_TWO); d_constellation[1] = gr_complex(SQRT_TWO, -SQRT_TWO); d_constellation[2] = gr_complex(-SQRT_TWO, SQRT_TWO); d_constellation[3] = gr_complex(SQRT_TWO, SQRT_TWO); /* d_constellation[0] = gr_complex(SQRT_TWO, SQRT_TWO); d_constellation[1] = gr_complex(-SQRT_TWO, SQRT_TWO); d_constellation[2] = gr_complex(SQRT_TWO, -SQRT_TWO); d_constellation[3] = gr_complex(SQRT_TWO, -SQRT_TWO); */ d_pre_diff_code.resize(4); d_pre_diff_code[0] = 0x0; d_pre_diff_code[1] = 0x2; d_pre_diff_code[2] = 0x3; d_pre_diff_code[3] = 0x1; d_rotational_symmetry = 4; d_dimensionality = 1; calc_arity(); } constellation_qpsk::~constellation_qpsk() { } unsigned int constellation_qpsk::decision_maker(const gr_complex *sample) { // Real component determines small bit. // Imag component determines big bit. return 2*(imag(*sample)>0) + (real(*sample)>0); /* bool a = real(*sample) > 0; bool b = imag(*sample) > 0; if(a) { if(b) return 0x0; else return 0x1; } else { if(b) return 0x2; else return 0x3; } */ } /********************************************************************/ constellation_dqpsk::sptr constellation_dqpsk::make() { return constellation_dqpsk::sptr(new constellation_dqpsk()); } constellation_dqpsk::constellation_dqpsk() { // This constellation is not gray coded, which allows // us to use differential encodings (through diff_encode and // diff_decode) on the symbols. d_constellation.resize(4); d_constellation[0] = gr_complex(+SQRT_TWO, +SQRT_TWO); d_constellation[1] = gr_complex(-SQRT_TWO, +SQRT_TWO); d_constellation[2] = gr_complex(-SQRT_TWO, -SQRT_TWO); d_constellation[3] = gr_complex(+SQRT_TWO, -SQRT_TWO); // Use this mapping to convert to gray code before diff enc. d_pre_diff_code.resize(4); d_pre_diff_code[0] = 0x0; d_pre_diff_code[1] = 0x1; d_pre_diff_code[2] = 0x3; d_pre_diff_code[3] = 0x2; d_apply_pre_diff_code = true; d_rotational_symmetry = 4; d_dimensionality = 1; calc_arity(); } constellation_dqpsk::~constellation_dqpsk() { } unsigned int constellation_dqpsk::decision_maker(const gr_complex *sample) { // Slower deicison maker as we can't slice along one axis. // Maybe there's a better way to do this, still. bool a = real(*sample) > 0; bool b = imag(*sample) > 0; if(a) { if(b) return 0x0; else return 0x3; } else { if(b) return 0x1; else return 0x2; } } /********************************************************************/ constellation_8psk::sptr constellation_8psk::make() { return constellation_8psk::sptr(new constellation_8psk()); } constellation_8psk::constellation_8psk() { float angle = M_PI/8.0; d_constellation.resize(8); // Gray-coded d_constellation[0] = gr_complex(cos( 1*angle), sin( 1*angle)); d_constellation[1] = gr_complex(cos( 7*angle), sin( 7*angle)); d_constellation[2] = gr_complex(cos(15*angle), sin(15*angle)); d_constellation[3] = gr_complex(cos( 9*angle), sin( 9*angle)); d_constellation[4] = gr_complex(cos( 3*angle), sin( 3*angle)); d_constellation[5] = gr_complex(cos( 5*angle), sin( 5*angle)); d_constellation[6] = gr_complex(cos(13*angle), sin(13*angle)); d_constellation[7] = gr_complex(cos(11*angle), sin(11*angle)); d_rotational_symmetry = 8; d_dimensionality = 1; calc_arity(); } constellation_8psk::~constellation_8psk() { } unsigned int constellation_8psk::decision_maker(const gr_complex *sample) { unsigned int ret = 0; float re = sample->real(); float im = sample->imag(); if(fabsf(re) <= fabsf(im)) ret = 4; if(re <= 0) ret |= 1; if(im <= 0) ret |= 2; return ret; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/packet_headerparser_b_impl.cc0000664000175000017500000000604112207440367023750 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "packet_headerparser_b_impl.h" #define msg_port_id pmt::mp("header_data") namespace gr { namespace digital { packet_headerparser_b::sptr packet_headerparser_b::make(long header_len, const std::string &len_tag_key) { const packet_header_default::sptr header_formatter( new packet_header_default(header_len, len_tag_key) ); return gnuradio::get_initial_sptr (new packet_headerparser_b_impl(header_formatter)); } packet_headerparser_b::sptr packet_headerparser_b::make(const gr::digital::packet_header_default::sptr &header_formatter) { return gnuradio::get_initial_sptr (new packet_headerparser_b_impl(header_formatter)); } packet_headerparser_b_impl::packet_headerparser_b_impl(const gr::digital::packet_header_default::sptr &header_formatter) : sync_block("packet_headerparser_b", io_signature::make(1, 1, sizeof (unsigned char)), io_signature::make(0, 0, 0)), d_header_formatter(header_formatter) { message_port_register_out(msg_port_id); set_output_multiple(header_formatter->header_len()); } packet_headerparser_b_impl::~packet_headerparser_b_impl() { } int packet_headerparser_b_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; if (noutput_items < d_header_formatter->header_len()) { return 0; } std::vector tags; get_tags_in_range( tags, 0, nitems_read(0), nitems_read(0)+d_header_formatter->header_len() ); if (!d_header_formatter->header_parser(in, tags)) { GR_LOG_INFO(d_logger, boost::format("Detected an invalid packet at item %1%") % nitems_read(0)); message_port_pub(msg_port_id, pmt::PMT_F); } else { pmt::pmt_t dict(pmt::make_dict()); for (unsigned i = 0; i < tags.size(); i++) { dict = pmt::dict_add(dict, tags[i].key, tags[i].value); } message_port_pub(msg_port_id, dict); } return d_header_formatter->header_len(); } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/correlate_and_sync_cc_impl.h0000664000175000017500000000405412237515112023614 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CORRELATE_AND_SYNC_CC_IMPL_H #define INCLUDED_DIGITAL_CORRELATE_AND_SYNC_CC_IMPL_H #include #include #include using namespace gr::filter; namespace gr { namespace digital { class correlate_and_sync_cc_impl : public correlate_and_sync_cc { private: std::vector d_symbols; unsigned int d_sps; float d_center_first_symbol; float d_thresh; kernel::fir_filter_ccc *d_filter; //kernel::fft_filter_ccc *d_filter; int d_last_index; public: correlate_and_sync_cc_impl(const std::vector &symbols, const std::vector &filter, unsigned int sps, unsigned int nfilts=32); ~correlate_and_sync_cc_impl(); std::vector symbols() const; void set_symbols(const std::vector &symbols); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_CORRELATE_AND_SYNC_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/clock_recovery_mm_ff_impl.cc0000664000175000017500000000711512207440367023633 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "clock_recovery_mm_ff_impl.h" #include #include #include namespace gr { namespace digital { clock_recovery_mm_ff::sptr clock_recovery_mm_ff::make(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limit) { return gnuradio::get_initial_sptr (new clock_recovery_mm_ff_impl(omega, gain_omega, mu, gain_mu, omega_relative_limit)); } clock_recovery_mm_ff_impl::clock_recovery_mm_ff_impl(float omega, float gain_omega, float mu, float gain_mu, float omega_relative_limit) : block("clock_recovery_mm_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), d_mu(mu), d_gain_mu(gain_mu), d_gain_omega(gain_omega), d_omega_relative_limit(omega_relative_limit), d_last_sample(0), d_interp(new filter::mmse_fir_interpolator_ff()) { if(omega < 1) throw std::out_of_range("clock rate must be > 0"); if(gain_mu < 0 || gain_omega < 0) throw std::out_of_range("Gains must be non-negative"); set_omega(omega); // also sets min and max omega set_relative_rate (1.0 / omega); } clock_recovery_mm_ff_impl::~clock_recovery_mm_ff_impl() { delete d_interp; } void clock_recovery_mm_ff_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) ninput_items_required[i] = (int) ceil((noutput_items * d_omega) + d_interp->ntaps()); } static inline float slice(float x) { return x < 0 ? -1.0F : 1.0F; } int clock_recovery_mm_ff_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; float *out = (float *)output_items[0]; int ii = 0; // input index int oo = 0; // output index int ni = ninput_items[0] - d_interp->ntaps(); // don't use more input than this float mm_val; while(oo < noutput_items && ii < ni ) { // produce output sample out[oo] = d_interp->interpolate(&in[ii], d_mu); mm_val = slice(d_last_sample) * out[oo] - slice(out[oo]) * d_last_sample; d_last_sample = out[oo]; d_omega = d_omega + d_gain_omega * mm_val; d_omega = d_omega_mid + gr::branchless_clip(d_omega-d_omega_mid, d_omega_relative_limit); d_mu = d_mu + d_omega + d_gain_mu * mm_val; ii += (int)floor(d_mu); d_mu = d_mu - floor(d_mu); oo++; } consume_each(ii); return oo; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/scrambler_bb_impl.cc0000664000175000017500000000362012207440367022070 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "scrambler_bb_impl.h" #include namespace gr { namespace digital { scrambler_bb::sptr scrambler_bb::make(int mask, int seed, int len) { return gnuradio::get_initial_sptr (new scrambler_bb_impl(mask, seed, len)); } scrambler_bb_impl::scrambler_bb_impl(int mask, int seed, int len) : sync_block("scrambler_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))), d_lfsr(mask, seed, len) { } scrambler_bb_impl::~scrambler_bb_impl() { } int scrambler_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = d_lfsr.next_bit_scramble(in[i]); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/pfb_clock_sync_fff_impl.cc0000664000175000017500000003043312237515112023246 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "pfb_clock_sync_fff_impl.h" #include #include namespace gr { namespace digital { pfb_clock_sync_fff::sptr pfb_clock_sync_fff::make(double sps, float gain, const std::vector &taps, unsigned int filter_size, float init_phase, float max_rate_deviation, int osps) { return gnuradio::get_initial_sptr (new pfb_clock_sync_fff_impl(sps, gain, taps, filter_size, init_phase, max_rate_deviation, osps)); } static int ios[] = {sizeof(float), sizeof(float), sizeof(float), sizeof(float)}; static std::vector iosig(ios, ios+sizeof(ios)/sizeof(int)); pfb_clock_sync_fff_impl::pfb_clock_sync_fff_impl(double sps, float loop_bw, const std::vector &taps, unsigned int filter_size, float init_phase, float max_rate_deviation, int osps) : block("pfb_clock_sync_fff", io_signature::make(1, 1, sizeof(float)), io_signature::makev(1, 4, iosig)), d_updated(false), d_nfilters(filter_size), d_max_dev(max_rate_deviation), d_osps(osps), d_error(0), d_out_idx(0) { // Let scheduler adjust our relative_rate. enable_update_rate(true); d_nfilters = filter_size; d_sps = floor(sps); // Set the damping factor for a critically damped system d_damping = 2*d_nfilters; // Set the bandwidth, which will then call update_gains() set_loop_bandwidth(loop_bw); // Store the last filter between calls to work // The accumulator keeps track of overflow to increment the stride correctly. // set it here to the fractional difference based on the initial phaes d_k = init_phase; d_rate = (sps-floor(sps))*(double)d_nfilters; d_rate_i = (int)floor(d_rate); d_rate_f = d_rate - (float)d_rate_i; d_filtnum = (int)floor(d_k); d_filters = std::vector(d_nfilters); d_diff_filters = std::vector(d_nfilters); // Create an FIR filter for each channel and zero out the taps std::vector vtaps(1,0); for(int i = 0; i < d_nfilters; i++) { d_filters[i] = new kernel::fir_filter_fff(1, vtaps); d_diff_filters[i] = new kernel::fir_filter_fff(1, vtaps); } // Now, actually set the filters' taps std::vector dtaps; create_diff_taps(taps, dtaps); set_taps(taps, d_taps, d_filters); set_taps(dtaps, d_dtaps, d_diff_filters); set_relative_rate((float)d_osps/(float)d_sps); } pfb_clock_sync_fff_impl::~pfb_clock_sync_fff_impl() { for(int i = 0; i < d_nfilters; i++) { delete d_filters[i]; delete d_diff_filters[i]; } } bool pfb_clock_sync_fff_impl::check_topology(int ninputs, int noutputs) { return noutputs == 1 || noutputs == 4; } void pfb_clock_sync_fff_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size (); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = (noutput_items + history()) * (d_sps/d_osps); } /******************************************************************* SET FUNCTIONS *******************************************************************/ void pfb_clock_sync_fff_impl::set_loop_bandwidth(float bw) { if(bw < 0) { throw std::out_of_range("pfb_clock_sync_fff: invalid bandwidth. Must be >= 0."); } d_loop_bw = bw; update_gains(); } void pfb_clock_sync_fff_impl::set_damping_factor(float df) { if(df < 0 || df > 1.0) { throw std::out_of_range("pfb_clock_sync_fff: invalid damping factor. Must be in [0,1]."); } d_damping = df; update_gains(); } void pfb_clock_sync_fff_impl::set_alpha(float alpha) { if(alpha < 0 || alpha > 1.0) { throw std::out_of_range("pfb_clock_sync_fff: invalid alpha. Must be in [0,1]."); } d_alpha = alpha; } void pfb_clock_sync_fff_impl::set_beta(float beta) { if(beta < 0 || beta > 1.0) { throw std::out_of_range("pfb_clock_sync_fff: invalid beta. Must be in [0,1]."); } d_beta = beta; } /******************************************************************* GET FUNCTIONS *******************************************************************/ float pfb_clock_sync_fff_impl::loop_bandwidth() const { return d_loop_bw; } float pfb_clock_sync_fff_impl::damping_factor() const { return d_damping; } float pfb_clock_sync_fff_impl::alpha() const { return d_alpha; } float pfb_clock_sync_fff_impl::beta() const { return d_beta; } float pfb_clock_sync_fff_impl::clock_rate() const { return d_rate_f; } /******************************************************************* *******************************************************************/ void pfb_clock_sync_fff_impl::update_gains() { float denom = (1.0 + 2.0*d_damping*d_loop_bw + d_loop_bw*d_loop_bw); d_alpha = (4*d_damping*d_loop_bw) / denom; d_beta = (4*d_loop_bw*d_loop_bw) / denom; } void pfb_clock_sync_fff_impl::set_taps(const std::vector &newtaps, std::vector< std::vector > &ourtaps, std::vector &ourfilter) { int i,j; unsigned int ntaps = newtaps.size(); d_taps_per_filter = (unsigned int)ceil((double)ntaps/(double)d_nfilters); // Create d_numchan vectors to store each channel's taps ourtaps.resize(d_nfilters); // Make a vector of the taps plus fill it out with 0's to fill // each polyphase filter with exactly d_taps_per_filter std::vector tmp_taps; tmp_taps = newtaps; while((float)(tmp_taps.size()) < d_nfilters*d_taps_per_filter) { tmp_taps.push_back(0.0); } // Partition the filter for(i = 0; i < d_nfilters; i++) { // Each channel uses all d_taps_per_filter with 0's if not enough taps to fill out ourtaps[i] = std::vector(d_taps_per_filter, 0); for(j = 0; j < d_taps_per_filter; j++) { ourtaps[i][j] = tmp_taps[i + j*d_nfilters]; } // Build a filter for each channel and add it's taps to it ourfilter[i]->set_taps(ourtaps[i]); } // Set the history to ensure enough input items for each filter set_history(d_taps_per_filter + d_sps + d_sps); // Make sure there is enough output space for d_osps outputs/input. set_output_multiple(d_osps); d_updated = true; } void pfb_clock_sync_fff_impl::create_diff_taps(const std::vector &newtaps, std::vector &difftaps) { std::vector diff_filter(3); diff_filter[0] = -1; diff_filter[1] = 0; diff_filter[2] = 1; float pwr = 0; difftaps.clear(); difftaps.push_back(0); for(unsigned int i = 0; i < newtaps.size()-2; i++) { float tap = 0; for(unsigned int j = 0; j < diff_filter.size(); j++) { tap += diff_filter[j]*newtaps[i+j]; } difftaps.push_back(tap); pwr += fabsf(tap); } difftaps.push_back(0); // Normalize the taps for(unsigned int i = 0; i < difftaps.size(); i++) { difftaps[i] *= d_nfilters/pwr; } } std::string pfb_clock_sync_fff_impl::taps_as_string() const { int i, j; std::stringstream str; str.precision(4); str.setf(std::ios::scientific); str << "[ "; for(i = 0; i < d_nfilters; i++) { str << "[" << d_taps[i][0] << ", "; for(j = 1; j < d_taps_per_filter-1; j++) { str << d_taps[i][j] << ", "; } str << d_taps[i][j] << "],"; } str << " ]" << std::endl; return str.str(); } std::string pfb_clock_sync_fff_impl::diff_taps_as_string() const { int i, j; std::stringstream str; str.precision(4); str.setf(std::ios::scientific); str << "[ "; for(i = 0; i < d_nfilters; i++) { str << "[" << d_dtaps[i][0] << ", "; for(j = 1; j < d_taps_per_filter-1; j++) { str << d_dtaps[i][j] << ", "; } str << d_dtaps[i][j] << "],"; } str << " ]" << std::endl; return str.str(); } std::vector< std::vector > pfb_clock_sync_fff_impl::taps() const { return d_taps; } std::vector< std::vector > pfb_clock_sync_fff_impl::diff_taps() const { return d_dtaps; } std::vector pfb_clock_sync_fff_impl::channel_taps(int channel) const { std::vector taps; for(int i = 0; i < d_taps_per_filter; i++) { taps.push_back(d_taps[channel][i]); } return taps; } std::vector pfb_clock_sync_fff_impl::diff_channel_taps(int channel) const { std::vector taps; for(int i = 0; i < d_taps_per_filter; i++) { taps.push_back(d_dtaps[channel][i]); } return taps; } int pfb_clock_sync_fff_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *in = (float *) input_items[0]; float *out = (float *) output_items[0]; float *err = NULL, *outrate = NULL, *outk = NULL; if(output_items.size() == 4) { err = (float *) output_items[1]; outrate = (float*)output_items[2]; outk = (float*)output_items[3]; } if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } int i = 0, count = 0; // produce output as long as we can and there are enough input samples while(i < noutput_items) { while(d_out_idx < d_osps) { d_filtnum = (int)floor(d_k); // Keep the current filter number in [0, d_nfilters] // If we've run beyond the last filter, wrap around and go to next sample // If we've gone below 0, wrap around and go to previous sample while(d_filtnum >= d_nfilters) { d_k -= d_nfilters; d_filtnum -= d_nfilters; count += 1; } while(d_filtnum < 0) { d_k += d_nfilters; d_filtnum += d_nfilters; count -= 1; } out[i+d_out_idx] = d_filters[d_filtnum]->filter(&in[count+d_out_idx]); d_k = d_k + d_rate_i + d_rate_f; // update phase d_out_idx++; if(output_items.size() == 4) { err[i] = d_error; outrate[i] = d_rate_f; outk[i] = d_k; } // We've run out of output items we can create; return now. if(i+d_out_idx >= noutput_items) { consume_each(count); return i; } } // reset here; if we didn't complete a full osps samples last time, // the early return would take care of it. d_out_idx = 0; // Update the phase and rate estimates for this symbol float diff = d_diff_filters[d_filtnum]->filter(&in[count]); d_error = out[i] * diff; // Run the control loop to update the current phase (k) and // tracking rate estimates based on the error value // Interpolating here to update rates for ever sps. for(int s = 0; s < d_sps; s++) { d_rate_f = d_rate_f + d_beta*d_error; d_k = d_k + d_rate_f + d_alpha*d_error; } // Keep our rate within a good range d_rate_f = gr::branchless_clip(d_rate_f, d_max_dev); i+=d_osps; count += (int)floor(d_sps); } consume_each(count); return i; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/scrambler_bb_impl.h0000664000175000017500000000271012207440367021731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SCRAMBLER_BB_IMPL_H #define INCLUDED_GR_SCRAMBLER_BB_IMPL_H #include #include #include namespace gr { namespace digital { class scrambler_bb_impl : public scrambler_bb { private: digital::lfsr d_lfsr; public: scrambler_bb_impl(int mask, int seed, int len); ~scrambler_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SCRAMBLER_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_insert_preamble_impl.cc0000664000175000017500000001214312207440367023633 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "ofdm_insert_preamble_impl.h" #include #include #include #include namespace gr { namespace digital { ofdm_insert_preamble::sptr ofdm_insert_preamble::make(int fft_length, const std::vector > &preamble) { return gnuradio::get_initial_sptr (new ofdm_insert_preamble_impl(fft_length, preamble)); } ofdm_insert_preamble_impl::ofdm_insert_preamble_impl(int fft_length, const std::vector > &preamble) : block("ofdm_insert_preamble", io_signature::make2(1, 2, sizeof(gr_complex)*fft_length, sizeof(char)), io_signature::make2(1, 2, sizeof(gr_complex)*fft_length, sizeof(char))), d_fft_length(fft_length), d_state(ST_IDLE), d_nsymbols_output(0), d_pending_flag(0), d_preamble(preamble) { // sanity check preamble symbols for(size_t i = 0; i < d_preamble.size(); i++) { if(d_preamble[i].size() != (size_t) d_fft_length) throw std::invalid_argument("ofdm_insert_preamble_impl: invalid length for preamble symbol"); } enter_idle(); } ofdm_insert_preamble_impl::~ofdm_insert_preamble_impl() { } void ofdm_insert_preamble_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { ninput_items_required[0] = noutput_items; } int ofdm_insert_preamble_impl::general_work(int noutput_items, gr_vector_int &ninput_items_v, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ninput_items = ninput_items_v.size() == 2 ? std::min(ninput_items_v[0], ninput_items_v[1]) : ninput_items_v[0]; const gr_complex *in_sym = (const gr_complex *)input_items[0]; const unsigned char *in_flag = 0; if(input_items.size() == 2) in_flag = (const unsigned char*)input_items[1]; gr_complex *out_sym = (gr_complex*)output_items[0]; unsigned char *out_flag = 0; if(output_items.size() == 2) out_flag = (unsigned char*)output_items[1]; int no = 0; // number items output int ni = 0; // number items read from input #define write_out_flag() \ do { \ if(out_flag) \ out_flag[no] = d_pending_flag; \ d_pending_flag = 0; \ } while(0) while(no < noutput_items && ni < ninput_items) { switch(d_state) { case ST_IDLE: if(in_flag && in_flag[ni] & 0x1) // this is first symbol of new payload enter_preamble(); else ni++; // eat one input symbol break; case ST_PREAMBLE: assert(!in_flag || in_flag[ni] & 0x1); if(d_nsymbols_output >= (int) d_preamble.size()) { // we've output all the preamble enter_first_payload(); } else { memcpy(&out_sym[no * d_fft_length], &d_preamble[d_nsymbols_output][0], d_fft_length*sizeof(gr_complex)); write_out_flag(); no++; d_nsymbols_output++; } break; case ST_FIRST_PAYLOAD: // copy first payload symbol from input to output memcpy(&out_sym[no * d_fft_length], &in_sym[ni * d_fft_length], d_fft_length * sizeof(gr_complex)); write_out_flag(); no++; ni++; enter_payload(); break; case ST_PAYLOAD: if(in_flag && in_flag[ni] & 0x1) { // this is first symbol of a new payload enter_preamble(); break; } // copy a symbol from input to output memcpy(&out_sym[no * d_fft_length], &in_sym[ni * d_fft_length], d_fft_length * sizeof(gr_complex)); write_out_flag(); no++; ni++; break; default: std::cerr << "ofdm_insert_preamble_impl: (can't happen) invalid state, resetting\n"; enter_idle(); } } consume_each(ni); return no; } void ofdm_insert_preamble_impl::enter_idle() { d_state = ST_IDLE; d_nsymbols_output = 0; d_pending_flag = 0; } void ofdm_insert_preamble_impl::enter_preamble() { d_state = ST_PREAMBLE; d_nsymbols_output = 0; d_pending_flag = 1; } void ofdm_insert_preamble_impl::enter_first_payload() { d_state = ST_FIRST_PAYLOAD; } void ofdm_insert_preamble_impl::enter_payload() { d_state = ST_PAYLOAD; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_frame_equalizer_vcvc_impl.cc0000664000175000017500000001306412207440367024657 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "ofdm_frame_equalizer_vcvc_impl.h" #define M_TWOPI (2*M_PI) namespace gr { namespace digital { ofdm_frame_equalizer_vcvc::sptr ofdm_frame_equalizer_vcvc::make( ofdm_equalizer_base::sptr equalizer, int cp_len, const std::string &len_tag_key, bool propagate_channel_state, int fixed_frame_len ) { return gnuradio::get_initial_sptr ( new ofdm_frame_equalizer_vcvc_impl( equalizer, cp_len, len_tag_key, propagate_channel_state, fixed_frame_len ) ); } ofdm_frame_equalizer_vcvc_impl::ofdm_frame_equalizer_vcvc_impl( ofdm_equalizer_base::sptr equalizer, int cp_len, const std::string &len_tag_key, bool propagate_channel_state, int fixed_frame_len ) : tagged_stream_block("ofdm_frame_equalizer_vcvc", io_signature::make(1, 1, sizeof (gr_complex) * equalizer->fft_len()), io_signature::make(1, 1, sizeof (gr_complex) * equalizer->fft_len()), len_tag_key), d_fft_len(equalizer->fft_len()), d_cp_len(cp_len), d_eq(equalizer), d_propagate_channel_state(propagate_channel_state), d_fixed_frame_len(fixed_frame_len), d_channel_state(equalizer->fft_len(), gr_complex(1, 0)) { if (len_tag_key.empty() && fixed_frame_len == 0) { throw std::invalid_argument("Either specify a length tag or a frame length!"); } if (d_fixed_frame_len < 0) { throw std::invalid_argument("Invalid frame length!"); } if (d_fixed_frame_len) { set_output_multiple(d_fixed_frame_len); } set_relative_rate(1.0); } ofdm_frame_equalizer_vcvc_impl::~ofdm_frame_equalizer_vcvc_impl() { } void ofdm_frame_equalizer_vcvc_impl::parse_length_tags( const std::vector > &tags, gr_vector_int &n_input_items_reqd ){ if (d_fixed_frame_len) { n_input_items_reqd[0] = d_fixed_frame_len; } else { for (unsigned k = 0; k < tags[0].size(); k++) { if (tags[0][k].key == pmt::string_to_symbol(d_length_tag_key_str)) { n_input_items_reqd[0] = pmt::to_long(tags[0][k].value); remove_item_tag(0, tags[0][k]); } } } } int ofdm_frame_equalizer_vcvc_impl::work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; int carrier_offset = 0; int frame_len = 0; if (d_fixed_frame_len) { frame_len = d_fixed_frame_len; } else { frame_len = ninput_items[0]; } std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+1); for (unsigned i = 0; i < tags.size(); i++) { if (pmt::symbol_to_string(tags[i].key) == "ofdm_sync_chan_taps") { d_channel_state = pmt::c32vector_elements(tags[i].value); remove_item_tag(0, tags[i]); } if (pmt::symbol_to_string(tags[i].key) == "ofdm_sync_carr_offset") { carrier_offset = pmt::to_long(tags[i].value); } } // Copy the frame and the channel state vector such that the symbols are shifted to the correct position if (carrier_offset < 0) { memset((void *) out, 0x00, sizeof(gr_complex) * (-carrier_offset)); memcpy( (void *) &out[-carrier_offset], (void *) in, sizeof(gr_complex) * (d_fft_len * frame_len + carrier_offset) ); } else { memset((void *) (out + d_fft_len * frame_len - carrier_offset), 0x00, sizeof(gr_complex) * carrier_offset); memcpy( (void *) out, (void *) (in+carrier_offset), sizeof(gr_complex) * (d_fft_len * frame_len - carrier_offset) ); } // Correct the frequency shift on the symbols gr_complex phase_correction; for (int i = 0; i < frame_len; i++) { phase_correction = gr_expj(-M_TWOPI * carrier_offset * d_cp_len / d_fft_len * (i+1)); for (int k = 0; k < d_fft_len; k++) { out[i*d_fft_len+k] *= phase_correction; } } // Do the equalizing d_eq->reset(); d_eq->equalize(out, frame_len, d_channel_state); d_eq->get_channel_state(d_channel_state); // Update the channel state regarding the frequency offset phase_correction = gr_expj(M_TWOPI * carrier_offset * d_cp_len / d_fft_len * frame_len); for (int k = 0; k < d_fft_len; k++) { d_channel_state[k] *= phase_correction; } // Housekeeping if (d_propagate_channel_state) { add_item_tag(0, nitems_written(0), pmt::string_to_symbol("ofdm_sync_chan_taps"), pmt::init_c32vector(d_fft_len, d_channel_state)); } if (d_fixed_frame_len && d_length_tag_key_str.empty()) { consume_each(frame_len); } return frame_len; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/costas_loop_cc_impl.h0000664000175000017500000000432712237515112022306 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_COSTAS_LOOP_CC_IMPL_H #define INCLUDED_DIGITAL_COSTAS_LOOP_CC_IMPL_H #include namespace gr { namespace digital { class costas_loop_cc_impl : public costas_loop_cc { private: int d_order; float d_error; /*! \brief the phase detector circuit for 8th-order PSK loops * \param sample complex sample * \return the phase error */ float phase_detector_8(gr_complex sample) const; // for 8PSK /*! \brief the phase detector circuit for fourth-order loops * \param sample complex sample * \return the phase error */ float phase_detector_4(gr_complex sample) const; // for QPSK /*! \brief the phase detector circuit for second-order loops * \param sample a complex sample * \return the phase error */ float phase_detector_2(gr_complex sample) const; // for BPSK float (costas_loop_cc_impl::*d_phase_detector)(gr_complex sample) const; public: costas_loop_cc_impl(float loop_bw, int order); ~costas_loop_cc_impl(); float error() const; void setup_rpc(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_COSTAS_LOOP_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/additive_scrambler_bb_impl.cc0000664000175000017500000001001712237515112023731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "additive_scrambler_bb_impl.h" #include namespace gr { namespace digital { additive_scrambler_bb::sptr additive_scrambler_bb::make (int mask, int seed, int len, int count, int bits_per_byte, const std::string &reset_tag_key) { return gnuradio::get_initial_sptr(new additive_scrambler_bb_impl (mask, seed, len, count, bits_per_byte, reset_tag_key)); } additive_scrambler_bb_impl::additive_scrambler_bb_impl(int mask, int seed, int len, int count, int bits_per_byte, const std::string &reset_tag_key) : sync_block("additive_scrambler_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))), d_lfsr(mask, seed, len), d_count(reset_tag_key.empty() ? count : -1), d_bytes(0), d_len(len), d_seed(seed), d_bits_per_byte(bits_per_byte), d_reset_tag_key(pmt::string_to_symbol(reset_tag_key)) { if (d_count < -1) { throw std::invalid_argument("count must be non-negative!"); } if (d_bits_per_byte < 1 || d_bits_per_byte > 8) { throw std::invalid_argument("bits_per_byte must be in [1, 8]"); } } additive_scrambler_bb_impl::~additive_scrambler_bb_impl() { } int additive_scrambler_bb_impl::mask() const { return d_lfsr.mask(); } int additive_scrambler_bb_impl::seed() const { return d_seed; } int additive_scrambler_bb_impl::len() const { return d_len; } int additive_scrambler_bb_impl::count() const { return d_count; } int additive_scrambler_bb_impl::_get_next_reset_index(int noutput_items, int last_reset_index /* = -1 */) { int reset_index = noutput_items; // This is a value that gets never reached in the for loop if (d_count == -1) { std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+noutput_items, d_reset_tag_key); for (unsigned i = 0; i < tags.size(); i++) { int reset_pos = tags[i].offset - nitems_read(0); if (reset_pos < reset_index && reset_pos > last_reset_index) { reset_index = reset_pos; }; } } else { if (last_reset_index == -1) { reset_index = d_count - d_bytes; } else { reset_index = last_reset_index + d_count; } } return reset_index; } int additive_scrambler_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; int reset_index = _get_next_reset_index(noutput_items); for(int i = 0; i < noutput_items; i++) { unsigned char scramble_byte = 0x00; for (int k = 0; k < d_bits_per_byte; k++) { scramble_byte ^= (d_lfsr.next_bit() << k); } out[i] = in[i] ^ scramble_byte; d_bytes++; if (i == reset_index) { d_lfsr.reset(); d_bytes = 0; reset_index = _get_next_reset_index(noutput_items, reset_index); } } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/diff_encoder_bb_impl.h0000664000175000017500000000266612207440367022400 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DIFF_ENCODER_BB_IMPL_H #define INCLUDED_GR_DIFF_ENCODER_BB_IMPL_H #include namespace gr { namespace digital { class diff_encoder_bb_impl : public diff_encoder_bb { public: diff_encoder_bb_impl(unsigned int modulus); ~diff_encoder_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); private: unsigned int d_last_out; unsigned int d_modulus; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_DIFF_ENCODER_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_chanest_vcvc_impl.cc0000664000175000017500000002072112207440367023127 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "ofdm_chanest_vcvc_impl.h" namespace gr { namespace digital { ofdm_chanest_vcvc::sptr ofdm_chanest_vcvc::make(const std::vector &sync_symbol1, const std::vector &sync_symbol2, int n_data_symbols, int eq_noise_red_len, int max_carr_offset, bool force_one_sync_symbol) { return gnuradio::get_initial_sptr ( new ofdm_chanest_vcvc_impl( sync_symbol1, sync_symbol2, n_data_symbols, eq_noise_red_len, max_carr_offset, force_one_sync_symbol ) ); } ofdm_chanest_vcvc_impl::ofdm_chanest_vcvc_impl( const std::vector &sync_symbol1, const std::vector &sync_symbol2, int n_data_symbols, int eq_noise_red_len, int max_carr_offset, bool force_one_sync_symbol ) : block("ofdm_chanest_vcvc", io_signature::make(1, 1, sizeof (gr_complex) * sync_symbol1.size()), io_signature::make(1, 2, sizeof (gr_complex) * sync_symbol1.size())), d_fft_len(sync_symbol1.size()), d_n_data_syms(n_data_symbols), d_n_sync_syms(1), d_eq_noise_red_len(eq_noise_red_len), d_ref_sym((sync_symbol2.size() && !force_one_sync_symbol) ? sync_symbol2 : sync_symbol1), d_corr_v(sync_symbol2), d_known_symbol_diffs(0, 0), d_new_symbol_diffs(0, 0), d_interpolate(false) { // Set index of first and last active carrier for (int i = 0; i < d_fft_len; i++) { if (d_ref_sym[i] != gr_complex(0, 0)) { d_first_active_carrier = i; break; } } for (int i = d_fft_len-1; i >= 0; i--) { if (d_ref_sym[i] != gr_complex(0, 0)) { d_last_active_carrier = i; break; } } // Sanity checks if (sync_symbol2.size()) { if (sync_symbol1.size() != sync_symbol2.size()) { throw std::invalid_argument("sync symbols must have equal length."); } if (!force_one_sync_symbol) { d_n_sync_syms = 2; } } else { if (sync_symbol1[d_first_active_carrier+1] == gr_complex(0, 0)) { d_last_active_carrier++; d_interpolate = true; } } // Set up coarse freq estimation info // Allow all possible values: d_max_neg_carr_offset = -d_first_active_carrier; d_max_pos_carr_offset = d_fft_len - d_last_active_carrier - 1; if (max_carr_offset != -1) { d_max_neg_carr_offset = std::max(-max_carr_offset, d_max_neg_carr_offset); d_max_pos_carr_offset = std::min(max_carr_offset, d_max_pos_carr_offset); } // Carrier offsets must be even if (d_max_neg_carr_offset % 2) d_max_neg_carr_offset++; if (d_max_pos_carr_offset % 2) d_max_pos_carr_offset--; if (d_n_sync_syms == 2) { for (int i = 0; i < d_fft_len; i++) { if (sync_symbol1[i] == gr_complex(0, 0)) { d_corr_v[i] = gr_complex(0, 0); } else { d_corr_v[i] /= sync_symbol1[i]; } } } else { d_corr_v.resize(0, 0); d_known_symbol_diffs.resize(d_fft_len, 0); d_new_symbol_diffs.resize(d_fft_len, 0); for (int i = d_first_active_carrier; i < d_last_active_carrier-2 && i < d_fft_len-2; i += 2) { d_known_symbol_diffs[i] = std::norm(sync_symbol1[i] - sync_symbol1[i+2]); } } set_output_multiple(d_n_data_syms); set_relative_rate((double) d_n_data_syms / (d_n_data_syms + d_n_sync_syms)); set_tag_propagation_policy(TPP_DONT); } ofdm_chanest_vcvc_impl::~ofdm_chanest_vcvc_impl() { } void ofdm_chanest_vcvc_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) { ninput_items_required[0] = (noutput_items/d_n_data_syms) * (d_n_data_syms + d_n_sync_syms); } int ofdm_chanest_vcvc_impl::get_carr_offset(const gr_complex *sync_sym1, const gr_complex *sync_sym2) { int carr_offset = 0; if (d_corr_v.size()) { // Use Schmidl & Cox method float Bg_max = 0; // g here is 2g in the paper for (int g = d_max_neg_carr_offset; g <= d_max_pos_carr_offset; g += 2) { gr_complex tmp = gr_complex(0, 0); for (int k = 0; k < d_fft_len; k++) { if (d_corr_v[k] != gr_complex(0, 0)) { tmp += std::conj(sync_sym1[k+g]) * std::conj(d_corr_v[k]) * sync_sym2[k+g]; } } if (std::abs(tmp) > Bg_max) { Bg_max = std::abs(tmp); carr_offset = g; } } } else { // Correlate std::fill(d_new_symbol_diffs.begin(), d_new_symbol_diffs.end(), 0); for(int i = 0; i < d_fft_len-2; i++) { d_new_symbol_diffs[i] = std::norm(sync_sym1[i] - sync_sym1[i+2]); } float sum; float max = 0; for (int g = d_max_neg_carr_offset; g <= d_max_pos_carr_offset; g += 2) { sum = 0; for (int j = 0; j < d_fft_len; j++) { if (d_known_symbol_diffs[j]) { sum += (d_known_symbol_diffs[j] * d_new_symbol_diffs[j + g]); } if(sum > max) { max = sum; carr_offset = g; } } } } return carr_offset; } void ofdm_chanest_vcvc_impl::get_chan_taps( const gr_complex *sync_sym1, const gr_complex *sync_sym2, int carr_offset, std::vector &taps) { const gr_complex *sym = ((d_n_sync_syms == 2) ? sync_sym2 : sync_sym1); std::fill(taps.begin(), taps.end(), gr_complex(0, 0)); int loop_start = 0; int loop_end = d_fft_len; if (carr_offset > 0) { loop_start = carr_offset; } else if (carr_offset < 0) { loop_end = d_fft_len + carr_offset; } for (int i = loop_start; i < loop_end; i++) { if ((d_ref_sym[i-carr_offset] != gr_complex(0, 0))) { taps[i-carr_offset] = sym[i] / d_ref_sym[i-carr_offset]; } } if (d_interpolate) { for (int i = d_first_active_carrier + 1; i < d_last_active_carrier; i += 2) { taps[i] = taps[i-1]; } taps[d_last_active_carrier] = taps[d_last_active_carrier-1]; } if (d_eq_noise_red_len) { // TODO // 1) IFFT // 2) Set all elements > d_eq_noise_red_len to zero // 3) FFT } } // Operates on a per-frame basis int ofdm_chanest_vcvc_impl::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; const int framesize = d_n_sync_syms + d_n_data_syms; // Channel info estimation int carr_offset = get_carr_offset(in, in+d_fft_len); std::vector chan_taps(d_fft_len, 0); get_chan_taps(in, in+d_fft_len, carr_offset, chan_taps); add_item_tag(0, nitems_written(0), pmt::string_to_symbol("ofdm_sync_carr_offset"), pmt::from_long(carr_offset)); add_item_tag(0, nitems_written(0), pmt::string_to_symbol("ofdm_sync_chan_taps"), pmt::init_c32vector(d_fft_len, chan_taps)); // Copy data symbols if (output_items.size() == 2) { gr_complex *out_chantaps = ((gr_complex *) output_items[1]); memcpy((void *) out_chantaps, (void *) &chan_taps[0], sizeof(gr_complex) * d_fft_len); produce(1, 1); } memcpy((void *) out, (void *) &in[d_n_sync_syms * d_fft_len], sizeof(gr_complex) * d_fft_len * d_n_data_syms); // Propagate tags std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+framesize); for (unsigned t = 0; t < tags.size(); t++) { int offset = tags[t].offset - nitems_read(0); if (offset < d_n_sync_syms) { offset = 0; } else { offset -= d_n_sync_syms; } tags[t].offset = offset + nitems_written(0); add_item_tag(0, tags[t]); } produce(0, d_n_data_syms); consume_each(framesize); return WORK_CALLED_PRODUCE; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/correlate_access_code_bb_impl.cc0000664000175000017500000000736112207440367024417 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "correlate_access_code_bb_impl.h" #include #include #include #include namespace gr { namespace digital { #define VERBOSE 0 correlate_access_code_bb::sptr correlate_access_code_bb::make(const std::string &access_code, int threshold) { return gnuradio::get_initial_sptr (new correlate_access_code_bb_impl(access_code, threshold)); } correlate_access_code_bb_impl::correlate_access_code_bb_impl( const std::string &access_code, int threshold) : sync_block("correlate_access_code_bb", io_signature::make(1, 1, sizeof(char)), io_signature::make(1, 1, sizeof(char))), d_data_reg(0), d_flag_reg(0), d_flag_bit(0), d_mask(0), d_threshold(threshold) { if(!set_access_code(access_code)) { throw std::out_of_range ("access_code is > 64 bits"); } } correlate_access_code_bb_impl::~correlate_access_code_bb_impl() { } bool correlate_access_code_bb_impl::set_access_code( const std::string &access_code) { unsigned len = access_code.length(); // # of bytes in string if(len > 64) return false; // set len top bits to 1. d_mask = ((~0ULL) >> (64 - len)) << (64 - len); d_flag_bit = 1LL << (64 - len); // Where we or-in new flag values. // new data always goes in 0x0000000000000001 d_access_code = 0; for(unsigned i=0; i < 64; i++){ d_access_code <<= 1; if(i < len) d_access_code |= access_code[i] & 1; // look at LSB only } return true; } int correlate_access_code_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { // compute output value unsigned int t = 0; t |= ((d_data_reg >> 63) & 0x1) << 0; t |= ((d_flag_reg >> 63) & 0x1) << 1; // flag bit out[i] = t; // compute hamming distance between desired access code and current data unsigned long long wrong_bits = 0; unsigned int nwrong = d_threshold+1; int new_flag = 0; wrong_bits = (d_data_reg ^ d_access_code) & d_mask; nwrong = gr::blocks::count_bits64(wrong_bits); // test for access code with up to threshold errors new_flag = (nwrong <= d_threshold); #if VERBOSE if(new_flag) { fprintf(stderr, "access code found: %llx\n", d_access_code); } else { fprintf(stderr, "%llx ==> %llx\n", d_access_code, d_data_reg); } #endif // shift in new data and new flag d_data_reg = (d_data_reg << 1) | (in[i] & 0x1); d_flag_reg = (d_flag_reg << 1); if(new_flag) { d_flag_reg |= d_flag_bit; } } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/map_bb_impl.cc0000664000175000017500000000445712207440367020704 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "map_bb_impl.h" #include namespace gr { namespace digital { map_bb::sptr map_bb::make(const std::vector &map) { return gnuradio::get_initial_sptr(new map_bb_impl(map)); } map_bb_impl::map_bb_impl(const std::vector &map) : sync_block("map_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))) { set_map(map); } map_bb_impl::~map_bb_impl() { } void map_bb_impl::set_map(const std::vector &map) { gr::thread::scoped_lock guard(d_mutex); for(int i = 0; i < 0x100; i++) d_map[i] = i; unsigned int size = std::min((size_t)0x100, map.size()); for(unsigned int i = 0; i < size; i++) d_map[i] = map[i]; } std::vector map_bb_impl::map() const { std::vector m; for(unsigned i = 0; i < 0x100; i++) m[i] = d_map[i]; return m; } int map_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock guard(d_mutex); const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = d_map[in[i]]; return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/constellation_decoder_cb_impl.cc0000664000175000017500000000502312207440367024461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "constellation_decoder_cb_impl.h" #include namespace gr { namespace digital { constellation_decoder_cb::sptr constellation_decoder_cb::make(constellation_sptr constellation) { return gnuradio::get_initial_sptr (new constellation_decoder_cb_impl(constellation)); } constellation_decoder_cb_impl:: constellation_decoder_cb_impl(constellation_sptr constellation) : block("constellation_decoder_cb", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(unsigned char))), d_constellation(constellation), d_dim(constellation->dimensionality()) { set_relative_rate(1.0 / ((double)d_dim)); } constellation_decoder_cb_impl::~constellation_decoder_cb_impl() { } void constellation_decoder_cb_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int input_required = noutput_items * d_dim; unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) ninput_items_required[i] = input_required; } int constellation_decoder_cb_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex const *in = (const gr_complex*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = d_constellation->decision_maker(&(in[i*d_dim])); } consume_each(noutput_items * d_dim); return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/diff_phasor_cc_impl.cc0000664000175000017500000000355312207440367022411 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "diff_phasor_cc_impl.h" #include namespace gr { namespace digital { diff_phasor_cc::sptr diff_phasor_cc::make() { return gnuradio::get_initial_sptr (new diff_phasor_cc_impl()); } diff_phasor_cc_impl::diff_phasor_cc_impl() : sync_block("diff_phasor_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))) { set_history(2); } diff_phasor_cc_impl::~diff_phasor_cc_impl() { } int diff_phasor_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex const *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; in += 1; // ensure that i - 1 is valid. for(int i = 0; i < noutput_items; i++) { out[i] = in[i] * conj(in[i-1]); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/binary_slicer_fb_impl.h0000664000175000017500000000256712207440367022622 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_BINARY_SLICER_FB_IMPL_H #define INCLUDED_DIGITAL_BINARY_SLICER_FB_IMPL_H #include namespace gr { namespace digital { class binary_slicer_fb_impl : public binary_slicer_fb { public: binary_slicer_fb_impl(); ~binary_slicer_fb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_BINARY_SLICER_FB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/kurtotic_equalizer_cc_impl.cc0000664000175000017500000000513412207440367024047 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "kurtotic_equalizer_cc_impl.h" #include #include namespace gr { namespace digital { kurtotic_equalizer_cc::sptr kurtotic_equalizer_cc::make(int num_taps, float mu) { return gnuradio::get_initial_sptr (new kurtotic_equalizer_cc_impl(num_taps, mu)); } kurtotic_equalizer_cc_impl::kurtotic_equalizer_cc_impl(int num_taps, float mu) : sync_decimator("kurtotic_equalizer_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex)), 1), filter::kernel::fir_filter_ccc(1, std::vector(num_taps, gr_complex(0,0))) { set_gain(mu); if(num_taps > 0) d_taps[0] = 1.0; set_taps(d_taps); d_alpha_p = 0.01; d_alpha_q = 0.01; d_alpha_m = 0.01; d_p = 0.0f; d_m = 0.0f; d_q = gr_complex(0,0); d_u = gr_complex(0,0); const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); set_history(num_taps+1); } kurtotic_equalizer_cc_impl::~kurtotic_equalizer_cc_impl() { } int kurtotic_equalizer_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in = (gr_complex *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; int j = 0, k, l = d_taps.size(); for(int i = 0; i < noutput_items; i++) { out[i] = filter(&in[j]); // Adjust taps d_error = error(out[i]); for(k = 0; k < l; k++) { update_tap(d_taps[l-k-1], in[j+k]); } j += decimation(); } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/map_bb_impl.h0000664000175000017500000000276512207440367020546 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MAP_BB_IMPL_H #define INCLUDED_GR_MAP_BB_IMPL_H #include #include namespace gr { namespace digital { class map_bb_impl : public map_bb { private: unsigned char d_map[0x100]; gr::thread::mutex d_mutex; public: map_bb_impl(const std::vector &map); ~map_bb_impl(); void set_map(const std::vector &map); std::vector map() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_MAP_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/simple_correlator_impl.h0000664000175000017500000000575512207440367023055 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SIMPLE_CORRELATOR_IMPL_H #define INCLUDED_GR_SIMPLE_CORRELATOR_IMPL_H #include //#define DEBUG_SIMPLE_CORRELATOR namespace gr { namespace digital { class simple_correlator_impl : public simple_correlator { private: static const int OVERSAMPLE = 8; enum state_t { ST_LOOKING, ST_UNDER_THRESHOLD, ST_LOCKED }; int d_payload_bytesize; state_t d_state; unsigned int d_osi; // over sample index [0,OVERSAMPLE-1] unsigned int d_transition_osi; // first index where Hamming dist < thresh unsigned int d_center_osi; // center of bit unsigned long long int d_shift_reg[OVERSAMPLE]; int d_bblen; // length of bitbuf unsigned char *d_bitbuf; // demodulated bits unsigned char *d_pktbuf; // temp packet buf int d_bbi; // bitbuf index static const int AVG_PERIOD = 512; // must be power of 2 (for freq offset correction) int d_avbi; float d_avgbuf[AVG_PERIOD]; float d_avg; float d_accum; #ifdef DEBUG_SIMPLE_CORRELATOR FILE *d_debug_fp; // binary log file #endif inline int slice (float x) { return x >= d_avg ? 1 : 0; } void update_avg(float x); void enter_locked (); void enter_under_threshold (); void enter_looking (); static int add_index (int a, int b) { int t = a + b; if(t >= OVERSAMPLE) t -= OVERSAMPLE; assert(t >= 0 && t < OVERSAMPLE); return t; } static int sub_index (int a, int b) { int t = a - b; if(t < 0) t += OVERSAMPLE; assert(t >= 0 && t < OVERSAMPLE); return t; } public: simple_correlator_impl(int payload_bytesize); ~simple_correlator_impl(); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_SIMPLE_CORRELATOR_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/correlate_access_code_bb_impl.h0000664000175000017500000000430712207440367024256 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_BB_IMPL_H #define INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_BB_IMPL_H #include namespace gr { namespace digital { class correlate_access_code_bb_impl : public correlate_access_code_bb { private: unsigned long long d_access_code; // access code to locate start of packet // access code is left justified in the word unsigned long long d_data_reg; // used to look for access_code unsigned long long d_flag_reg; // keep track of decisions unsigned long long d_flag_bit; // mask containing 1 bit which is location of new flag unsigned long long d_mask; // masks access_code bits (top N bits are set where // N is the number of bits in the access code) unsigned int d_threshold; // how many bits may be wrong in sync vector public: correlate_access_code_bb_impl(const std::string &access_code, int threshold); ~correlate_access_code_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); bool set_access_code(const std::string &access_code); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CORRELATE_ACCESS_CODE_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/packet_sink_impl.h0000664000175000017500000000577212207440367021622 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PACKET_SINK_IMPL_H #define INCLUDED_GR_PACKET_SINK_IMPL_H #include namespace gr { namespace digital { class packet_sink_impl : public packet_sink { private: enum state_t {STATE_SYNC_SEARCH, STATE_HAVE_SYNC, STATE_HAVE_HEADER}; static const int MAX_PKT_LEN = 4096; static const int HEADERBITLEN = 32; msg_queue::sptr d_target_queue; // where to send the packet when received unsigned long long d_sync_vector; // access code to locate start of packet unsigned int d_threshold; // how many bits may be wrong in sync vector state_t d_state; unsigned long long d_shift_reg; // used to look for sync_vector unsigned int d_header; // header bits int d_headerbitlen_cnt;// how many so far unsigned char d_packet[MAX_PKT_LEN]; // assembled payload unsigned char d_packet_byte; // byte being assembled int d_packet_byte_index; // which bit of d_packet_byte we're working on int d_packetlen; // length of packet int d_packetlen_cnt; // how many so far protected: void enter_search(); void enter_have_sync(); void enter_have_header(int payload_len); int slice(float x) { return x > 0 ? 1 : 0; } bool header_ok() { // confirm that two copies of header info are identical return ((d_header >> 16) ^ (d_header & 0xffff)) == 0; } int header_payload_len() { // header consists of two 16-bit shorts in network byte order int t = (d_header >> 16) & 0xffff; return t; } public: packet_sink_impl(const std::vector& sync_vector, msg_queue::sptr target_queue, int threshold=-1); ~packet_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); //! return true if we detect carrier bool carrier_sensed() const { return d_state != STATE_SYNC_SEARCH; } }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_PACKET_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/simple_framer_impl.cc0000664000175000017500000000620312207440367022300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "simple_framer_impl.h" #include #include #include #include namespace gr { namespace digital { simple_framer::sptr simple_framer::make(int payload_bytesize) { return gnuradio::get_initial_sptr (new simple_framer_impl(payload_bytesize)); } simple_framer_impl::simple_framer_impl(int payload_bytesize) : block("simple_framer", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char))), d_seqno (0), d_payload_bytesize (payload_bytesize), d_input_block_size (payload_bytesize), d_output_block_size (payload_bytesize + GRSF_OVERHEAD) { set_output_multiple(d_output_block_size); } simple_framer_impl::~simple_framer_impl() { } void simple_framer_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { assert(noutput_items % d_output_block_size == 0); int nblocks = noutput_items / d_output_block_size; int input_required = nblocks * d_input_block_size; unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) ninput_items_required[i] = input_required; } int simple_framer_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; int n = 0; int nblocks = 0; memset(out, 0x55, noutput_items); while(n < noutput_items) { out[0] = (GRSF_SYNC >> 56) & 0xff; out[1] = (GRSF_SYNC >> 48) & 0xff; out[2] = (GRSF_SYNC >> 40) & 0xff; out[3] = (GRSF_SYNC >> 32) & 0xff; out[4] = (GRSF_SYNC >> 24) & 0xff; out[5] = (GRSF_SYNC >> 16) & 0xff; out[6] = (GRSF_SYNC >> 8) & 0xff; out[7] = (GRSF_SYNC >> 0) & 0xff; out[8] = d_seqno++; memcpy(&out[9], in, d_input_block_size); in += d_input_block_size; out += d_output_block_size; n += d_output_block_size; nblocks++; } assert(n == noutput_items); consume_each(nblocks * d_input_block_size); return n; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/packet_headergenerator_bb_impl.h0000664000175000017500000000346412207440367024454 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_PACKET_HEADERGENERATOR_BB_IMPL_H #define INCLUDED_DIGITAL_PACKET_HEADERGENERATOR_BB_IMPL_H #include namespace gr { namespace digital { class packet_headergenerator_bb_impl : public packet_headergenerator_bb { private: gr::digital::packet_header_default::sptr d_formatter; public: packet_headergenerator_bb_impl( const packet_header_default::sptr &header_formatter, const std::string &len_tag_key ); ~packet_headergenerator_bb_impl(); void remove_length_tags(const std::vector > &tags) {}; int calculate_output_stream_length(const gr_vector_int &ninput_items) { return d_formatter->header_len(); }; int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_PACKET_HEADERGENERATOR_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/framer_sink_1_impl.cc0000664000175000017500000001201712207440367022173 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "framer_sink_1_impl.h" #include #include #include namespace gr { namespace digital { #define VERBOSE 0 inline void framer_sink_1_impl::enter_search() { if(VERBOSE) fprintf(stderr, "@ enter_search\n"); d_state = STATE_SYNC_SEARCH; } inline void framer_sink_1_impl::enter_have_sync() { if (VERBOSE) fprintf(stderr, "@ enter_have_sync\n"); d_state = STATE_HAVE_SYNC; d_header = 0; d_headerbitlen_cnt = 0; } inline void framer_sink_1_impl::enter_have_header(int payload_len, int whitener_offset) { if(VERBOSE) fprintf(stderr, "@ enter_have_header (payload_len = %d) (offset = %d)\n", payload_len, whitener_offset); d_state = STATE_HAVE_HEADER; d_packetlen = payload_len; d_packet_whitener_offset = whitener_offset; d_packetlen_cnt = 0; d_packet_byte = 0; d_packet_byte_index = 0; } framer_sink_1::sptr framer_sink_1::make(msg_queue::sptr target_queue) { return gnuradio::get_initial_sptr (new framer_sink_1_impl(target_queue)); } framer_sink_1_impl::framer_sink_1_impl(msg_queue::sptr target_queue) : sync_block("framer_sink_1", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(0, 0, 0)), d_target_queue(target_queue) { enter_search(); } framer_sink_1_impl::~framer_sink_1_impl() { } int framer_sink_1_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; int count=0; if(VERBOSE) fprintf(stderr,">>> Entering state machine\n"); while(count < noutput_items){ switch(d_state) { case STATE_SYNC_SEARCH: // Look for flag indicating beginning of pkt if(VERBOSE) fprintf(stderr,"SYNC Search, noutput=%d\n", noutput_items); while(count < noutput_items) { if(in[count] & 0x2){ // Found it, set up for header decode enter_have_sync(); break; } count++; } break; case STATE_HAVE_SYNC: if(VERBOSE) fprintf(stderr,"Header Search bitcnt=%d, header=0x%08x\n", d_headerbitlen_cnt, d_header); while(count < noutput_items) { // Shift bits one at a time into header d_header = (d_header << 1) | (in[count++] & 0x1); if(++d_headerbitlen_cnt == HEADERBITLEN) { if(VERBOSE) fprintf(stderr, "got header: 0x%08x\n", d_header); // we have a full header, check to see if it has been received properly if(header_ok()) { int payload_len; int whitener_offset; header_payload(&payload_len, &whitener_offset); enter_have_header(payload_len, whitener_offset); if(d_packetlen == 0) { // check for zero-length payload // build a zero-length message // NOTE: passing header field as arg1 is not scalable message::sptr msg = message::make(0, d_packet_whitener_offset, 0, 0); d_target_queue->insert_tail(msg); // send it msg.reset(); // free it up enter_search(); } } else enter_search(); // bad header break; // we're in a new state } } break; case STATE_HAVE_HEADER: if(VERBOSE) fprintf(stderr,"Packet Build\n"); while(count < noutput_items) { // shift bits into bytes of packet one at a time d_packet_byte = (d_packet_byte << 1) | (in[count++] & 0x1); if(d_packet_byte_index++ == 7) { // byte is full so move to next byte d_packet[d_packetlen_cnt++] = d_packet_byte; d_packet_byte_index = 0; if(d_packetlen_cnt == d_packetlen) { // packet is filled // build a message // NOTE: passing header field as arg1 is not scalable message::sptr msg = message::make(0, d_packet_whitener_offset, 0, d_packetlen_cnt); memcpy(msg->msg(), d_packet, d_packetlen_cnt); d_target_queue->insert_tail(msg); // send it msg.reset(); // free it up enter_search(); break; } } } break; default: assert(0); } // switch } // while return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_frame_equalizer_vcvc_impl.h0000664000175000017500000000371512207440367024523 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_FRAME_EQUALIZER_VCVC_IMPL_H #define INCLUDED_DIGITAL_OFDM_FRAME_EQUALIZER_VCVC_IMPL_H #include namespace gr { namespace digital { class ofdm_frame_equalizer_vcvc_impl : public ofdm_frame_equalizer_vcvc { private: const int d_fft_len; const int d_cp_len; ofdm_equalizer_base::sptr d_eq; bool d_propagate_channel_state; const int d_fixed_frame_len; std::vector d_channel_state; protected: void parse_length_tags( const std::vector > &tags, gr_vector_int &n_input_items_reqd ); public: ofdm_frame_equalizer_vcvc_impl( ofdm_equalizer_base::sptr equalizer, int cp_len, const std::string &len_tag_key, bool propagate_channel_state, int fixed_frame_len ); ~ofdm_frame_equalizer_vcvc_impl(); int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_FRAME_EQUALIZER_VCVC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/glfsr_source_f_impl.h0000664000175000017500000000315612207440367022323 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_GLFSR_SOURCE_F_IMPL_H #define INCLUDED_GR_GLFSR_SOURCE_F_IMPL_H #include #include namespace gr { namespace digital { class glfsr_source_f_impl : public glfsr_source_f { private: glfsr *d_glfsr; bool d_repeat; unsigned int d_index; unsigned int d_length; public: glfsr_source_f_impl(int degree, bool repeat=true, int mask=0, int seed=1); ~glfsr_source_f_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int period() const { return d_length; } int mask() const; }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_GR_GLFSR_SOURCE_F_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/crc32_bb_impl.h0000664000175000017500000000322412207440367020674 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CRC32_BB_IMPL_H #define INCLUDED_DIGITAL_CRC32_BB_IMPL_H #include #include namespace gr { namespace digital { class crc32_bb_impl : public crc32_bb { private: bool d_check; boost::crc_optimal<32, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true> d_crc_impl; public: crc32_bb_impl(bool check, const std::string& lengthtagname); ~crc32_bb_impl(); int calculate_output_stream_length(const gr_vector_int &ninput_items); int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); uint64_t d_npass; uint64_t d_nfail; }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_CRC32_BB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/fll_band_edge_cc_impl.cc0000664000175000017500000001753212225347633022656 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fll_band_edge_cc_impl.h" #include #include #include namespace gr { namespace digital { #define M_TWOPI (2*M_PI) float sinc(float x) { if(x == 0) return 1; else return sin(M_PI*x)/(M_PI*x); } fll_band_edge_cc::sptr fll_band_edge_cc::make(float samps_per_sym, float rolloff, int filter_size, float bandwidth) { return gnuradio::get_initial_sptr (new fll_band_edge_cc_impl(samps_per_sym, rolloff, filter_size, bandwidth)); } static int ios[] = {sizeof(gr_complex), sizeof(float), sizeof(float), sizeof(float)}; static std::vector iosig(ios, ios+sizeof(ios)/sizeof(int)); fll_band_edge_cc_impl::fll_band_edge_cc_impl(float samps_per_sym, float rolloff, int filter_size, float bandwidth) : sync_block("fll_band_edge_cc", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::makev(1, 4, iosig)), blocks::control_loop(bandwidth, M_TWOPI*(2.0/samps_per_sym), -M_TWOPI*(2.0/samps_per_sym)), d_updated(false) { // Initialize samples per symbol if(samps_per_sym <= 0) { throw std::out_of_range("fll_band_edge_cc: invalid number of sps. Must be > 0."); } d_sps = samps_per_sym; // Initialize rolloff factor if(rolloff < 0 || rolloff > 1.0) { throw std::out_of_range("fll_band_edge_cc: invalid rolloff factor. Must be in [0,1]."); } d_rolloff = rolloff; // Initialize filter length if(filter_size <= 0) { throw std::out_of_range("fll_band_edge_cc: invalid filter size. Must be > 0."); } d_filter_size = filter_size; // Build the band edge filters design_filter(d_sps, d_rolloff, d_filter_size); d_output_hist.resize(filter_size,0); } fll_band_edge_cc_impl::~fll_band_edge_cc_impl() { delete d_filter_upper; delete d_filter_lower; } /******************************************************************* SET FUNCTIONS *******************************************************************/ void fll_band_edge_cc_impl::set_samples_per_symbol(float sps) { if(sps <= 0) { throw std::out_of_range("fll_band_edge_cc: invalid number of sps. Must be > 0."); } d_sps = sps; design_filter(d_sps, d_rolloff, d_filter_size); } void fll_band_edge_cc_impl::set_rolloff(float rolloff) { if(rolloff < 0 || rolloff > 1.0) { throw std::out_of_range("fll_band_edge_cc: invalid rolloff factor. Must be in [0,1]."); } d_rolloff = rolloff; design_filter(d_sps, d_rolloff, d_filter_size); } void fll_band_edge_cc_impl::set_filter_size(int filter_size) { if(filter_size <= 0) { throw std::out_of_range("fll_band_edge_cc: invalid filter size. Must be > 0."); } d_filter_size = filter_size; design_filter(d_sps, d_rolloff, d_filter_size); } /******************************************************************* GET FUNCTIONS *******************************************************************/ float fll_band_edge_cc_impl::samples_per_symbol() const { return d_sps; } float fll_band_edge_cc_impl::rolloff() const { return d_rolloff; } int fll_band_edge_cc_impl::filter_size() const { return d_filter_size; } /******************************************************************* *******************************************************************/ void fll_band_edge_cc_impl::design_filter(float samps_per_sym, float rolloff, int filter_size) { int M = rint(filter_size / samps_per_sym); float power = 0; // Create the baseband filter by adding two sincs together std::vector bb_taps; for(int i = 0; i < filter_size; i++) { float k = -M + i*2.0/samps_per_sym; float tap = sinc(rolloff*k - 0.5) + sinc(rolloff*k + 0.5); power += tap; bb_taps.push_back(tap); } d_taps_lower.resize(filter_size); d_taps_upper.resize(filter_size); // Create the band edge filters by spinning the baseband // filter up and down to the right places in frequency. // Also, normalize the power in the filters int N = (bb_taps.size() - 1.0)/2.0; for(int i = 0; i < filter_size; i++) { float tap = bb_taps[i] / power; float k = (-N + (int)i)/(2.0*samps_per_sym); gr_complex t1 = tap * gr_expj(-M_TWOPI*(1+rolloff)*k); gr_complex t2 = tap * gr_expj(M_TWOPI*(1+rolloff)*k); d_taps_lower[filter_size-i-1] = t1; d_taps_upper[filter_size-i-1] = t2; } d_updated = true; // Set the history to ensure enough input items for each filter set_history(filter_size+1); d_filter_upper = new gr::filter::kernel::fir_filter_ccc(1, d_taps_upper); d_filter_lower = new gr::filter::kernel::fir_filter_ccc(1, d_taps_lower); } void fll_band_edge_cc_impl::print_taps() { unsigned int i; printf("Upper Band-edge: ["); for(i = 0; i < d_taps_upper.size(); i++) { printf(" %.4e + %.4ej,", d_taps_upper[i].real(), d_taps_upper[i].imag()); } printf("]\n\n"); printf("Lower Band-edge: ["); for(i = 0; i < d_taps_lower.size(); i++) { printf(" %.4e + %.4ej,", d_taps_lower[i].real(), d_taps_lower[i].imag()); } printf("]\n\n"); } int fll_band_edge_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; d_fllbuffer.reserve(d_filter_size+noutput_items); float *frq = NULL; float *phs = NULL; float *err = NULL; if(output_items.size() == 4) { frq = (float*)output_items[1]; phs = (float*)output_items[2]; err = (float*)output_items[3]; } if(d_updated) { d_updated = false; return 0; // history requirements may have changed. } int i; float error; gr_complex nco_out; gr_complex out_upper, out_lower; gr_complex out_uppersse, out_lowersse; copy(d_output_hist.begin(), d_output_hist.end(), d_fllbuffer.begin()); for(i = 0; i < noutput_items; i++) { nco_out = gr_expj(d_phase); d_fllbuffer[i+d_filter_size] = in[i] * nco_out; // Perform the dot product of the output with the filters out_upper = 0; out_lower = 0; out_upper = d_filter_lower->filter(&d_fllbuffer[i]); out_lower = d_filter_upper->filter(&d_fllbuffer[i]); error = norm(out_lower) - norm(out_upper); advance_loop(error); phase_wrap(); frequency_limit(); if(output_items.size() == 4) { frq[i] = d_freq; phs[i] = d_phase; err[i] = error; } } copy(d_fllbuffer.begin(), d_fllbuffer.begin()+noutput_items, out); copy(d_fllbuffer.begin()+noutput_items, d_fllbuffer.begin()+noutput_items+d_filter_size, d_output_hist.begin()); return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_serializer_vcc_impl.h0000664000175000017500000000467012207440367023334 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_SERIALIZER_VCC_IMPL_H #define INCLUDED_DIGITAL_OFDM_SERIALIZER_VCC_IMPL_H #include namespace gr { namespace digital { class ofdm_serializer_vcc_impl : public ofdm_serializer_vcc { private: int d_fft_len; //!< FFT length std::vector > d_occupied_carriers; //!< Which carriers/symbols carry data pmt::pmt_t d_packet_len_tag_key; //!< Key of the length tag pmt::pmt_t d_out_len_tag_key; //!< Key of the length tag const int d_symbols_skipped; //!< Start position in d_occupied_carriers pmt::pmt_t d_carr_offset_key; //!< Key of the carrier offset tag int d_curr_set; //!< Current position in d_occupied_carriers int d_symbols_per_set; protected: /*! * Calculate the number of scalar complex symbols given a number of * OFDM symbols. */ int calculate_output_stream_length(const gr_vector_int &ninput_items); void update_length_tags(int n_produced, int n_ports); public: ofdm_serializer_vcc_impl( int fft_len, const std::vector > &occupied_carriers, const std::string &len_tag_key, const std::string &packet_len_tag_key, int symbols_skipped, const std::string &carr_offset_key, bool input_is_shifted ); ~ofdm_serializer_vcc_impl(); int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_SERIALIZER_VCC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/lms_dd_equalizer_cc_impl.h0000664000175000017500000000426612207440367023314 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_LMS_DD_EQUALIZER_CC_IMPL_H #define INCLUDED_DIGITAL_LMS_DD_EQUALIZER_CC_IMPL_H #include #include #include namespace gr { namespace digital { class lms_dd_equalizer_cc_impl : public lms_dd_equalizer_cc, filter::kernel::fir_filter_ccc { private: std::vector d_new_taps; bool d_updated; gr_complex d_error; float d_mu; constellation_sptr d_cnst; protected: gr_complex error(const gr_complex &out); void update_tap(gr_complex &tap, const gr_complex &in); public: lms_dd_equalizer_cc_impl(int num_taps, float mu, int sps, constellation_sptr cnst); ~lms_dd_equalizer_cc_impl(); void set_taps(const std::vector &taps); std::vector taps() const; float gain() const { return d_mu; } void set_gain(float mu) { if(mu < 0.0f || mu > 1.0f) { throw std::out_of_range("lms_dd_equalizer_impl::set_mu: Gain value must in [0, 1]"); } else { d_mu = mu; } } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_LMS_DD_EQUALIZER_CC_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/constellation_decoder_cb_impl.h0000664000175000017500000000325312207440367024326 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_CONSTELLATION_DECODER_CB_IMPL_H #define INCLUDED_DIGITAL_CONSTELLATION_DECODER_CB_IMPL_H #include namespace gr { namespace digital { class constellation_decoder_cb_impl : public constellation_decoder_cb { private: constellation_sptr d_constellation; unsigned int d_dim; public: constellation_decoder_cb_impl(constellation_sptr constellation); ~constellation_decoder_cb_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_CONSTELLATION_DECODER_CB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/constellation_soft_decoder_cf_impl.cc0000664000175000017500000000476312237515112025524 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "constellation_soft_decoder_cf_impl.h" #include namespace gr { namespace digital { constellation_soft_decoder_cf::sptr constellation_soft_decoder_cf::make(constellation_sptr constellation) { return gnuradio::get_initial_sptr (new constellation_soft_decoder_cf_impl(constellation)); } constellation_soft_decoder_cf_impl:: constellation_soft_decoder_cf_impl(constellation_sptr constellation) : sync_interpolator("constellation_soft_decoder_cf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(float)), constellation->bits_per_symbol()), d_constellation(constellation), d_dim(constellation->dimensionality()), d_bps(constellation->bits_per_symbol()) { } constellation_soft_decoder_cf_impl::~constellation_soft_decoder_cf_impl() { } int constellation_soft_decoder_cf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex const *in = (const gr_complex*)input_items[0]; float *out = (float*)output_items[0]; std::vector bits; // FIXME: figure out how to manage d_dim for(int i = 0; i < noutput_items/d_bps; i++) { bits = d_constellation->soft_decision_maker(in[i]); for(size_t j = 0; j < bits.size(); j++) { out[d_bps*i+j] = bits[j]; } } return noutput_items; } } /* namespace digital */ } /* namespace gr */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_sync_sc_cfb_impl.h0000664000175000017500000000243212207440367022575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_SYNC_SC_CFB_IMPL_H #define INCLUDED_DIGITAL_OFDM_SYNC_SC_CFB_IMPL_H #include namespace gr { namespace digital { class ofdm_sync_sc_cfb_impl : public ofdm_sync_sc_cfb { public: ofdm_sync_sc_cfb_impl(int fft_len, int cp_len, bool use_even_carriers); ~ofdm_sync_sc_cfb_impl(); }; } // namespace digital } // namespace gr #endif /* INCLUDED_DIGITAL_OFDM_SYNC_SC_CFB_IMPL_H */ gnuradio-3.7.2.1/gr-digital/lib/ofdm_sampler_impl.h0000664000175000017500000000347312207440367021773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DIGITAL_OFDM_SAMPLER_IMPL_H #define INCLUDED_DIGITAL_OFDM_SAMPLER_IMPL_H #include #include namespace gr { namespace digital { class ofdm_sampler_impl : public ofdm_sampler { private: enum state_t {STATE_NO_SIG, STATE_PREAMBLE, STATE_FRAME}; state_t d_state; unsigned int d_timeout_max; unsigned int d_timeout; unsigned int d_fft_length; unsigned int d_symbol_length; public: ofdm_sampler_impl(unsigned int fft_length, unsigned int symbol_length, unsigned int timeout=1000); ~ofdm_sampler_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace digital */ } /* namespace gr */ #endif /* INCLUDED_DIGITAL_OFDM_SAMPLER_IMPL_H */ gnuradio-3.7.2.1/gr-digital/swig/0000755000175000017500000000000012237515112016315 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/swig/CMakeLists.txt0000664000175000017500000000432612207440367021072 0ustar jcorganjcorgan# Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_DIGITAL_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GR_ANALOG_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) # Setup swig docs to depend on includes and pull in from build directory set(GR_SWIG_TARGET_DEPS digital_generated_includes) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/digital_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/digital ${CMAKE_CURRENT_BINARY_DIR}/../include/gnuradio/digital ) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-digital gnuradio-filter gnuradio-analog gnuradio-blocks) GR_SWIG_MAKE(digital_swig digital_swig.i) GR_SWIG_INSTALL( TARGETS digital_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/digital COMPONENT "digital_python" ) install( FILES digital_swig.i constellation.i ofdm_equalizer.i packet_header.i ${CMAKE_CURRENT_BINARY_DIR}/digital_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "digital_swig" ) gnuradio-3.7.2.1/gr-digital/swig/constellation.i0000664000175000017500000000546212207440367021364 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %template(constellation_sptr) boost::shared_ptr; %template(constellation_calcdist_sptr) boost::shared_ptr; %pythoncode %{ constellation_calcdist_sptr.__repr__ = lambda self: "" % (len(self.points())) constellation_calcdist = constellation_calcdist.make; %} %template(constellation_rect_sptr) boost::shared_ptr; %pythoncode %{ constellation_rect_sptr.__repr__ = lambda self: "" % (len(self.points())) constellation_rect = constellation_rect.make; %} %template(constellation_expl_rect_sptr) boost::shared_ptr; %pythoncode %{ constellation_expl_rect_sptr.__repr__ = lambda self: "" % (len(self.points())) constellation_expl_rect = constellation_expl_rect.make; %} %template(constellation_psk_sptr) boost::shared_ptr; %pythoncode %{ constellation_psk_sptr.__repr__ = lambda self: "" % (len(self.points())) constellation_psk = constellation_psk.make; %} %template(constellation_bpsk_sptr) boost::shared_ptr; %pythoncode %{ constellation_bpsk_sptr.__repr__ = lambda self: "" constellation_bpsk = constellation_bpsk.make; %} %template(constellation_qpsk_sptr) boost::shared_ptr; %pythoncode %{ constellation_qpsk_sptr.__repr__ = lambda self: "" constellation_qpsk = constellation_qpsk.make; %} %template(constellation_dqpsk_sptr) boost::shared_ptr; %pythoncode %{ constellation_dqpsk_sptr.__repr__ = lambda self: "" constellation_dqpsk = constellation_dqpsk.make; %} %template(constellation_8psk_sptr) boost::shared_ptr; %pythoncode %{ constellation_8psk_sptr.__repr__ = lambda self: "" constellation_8psk = constellation_8psk.make; %} gnuradio-3.7.2.1/gr-digital/swig/packet_header.i0000664000175000017500000000241412207440367021257 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %template(packet_header_default_sptr) boost::shared_ptr; %pythoncode %{ packet_header_default_sptr.__repr__ = lambda self: "" packet_header_default = packet_header_default .make; %} %template(packet_header_ofdm_sptr) boost::shared_ptr; %pythoncode %{ packet_header_ofdm_sptr.__repr__ = lambda self: "" packet_header_ofdm = packet_header_ofdm .make; %} gnuradio-3.7.2.1/gr-digital/swig/ofdm_equalizer.i0000664000175000017500000000342612207440367021512 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %template(ofdm_equalizer_base_sptr) boost::shared_ptr; %template(ofdm_equalizer_1d_pilots_sptr) boost::shared_ptr; %pythoncode %{ ofdm_equalizer_1d_pilots_sptr.__repr__ = lambda self: "" %} %template(ofdm_equalizer_simpledfe_sptr) boost::shared_ptr; %pythoncode %{ ofdm_equalizer_simpledfe_sptr.__repr__ = lambda self: "" ofdm_equalizer_simpledfe = ofdm_equalizer_simpledfe.make; %} //%rename(ofdm_equalizer_simpledfe) make_ofdm_equalizer_simpledfe; //%ignore ofdm_equalizer_simpledfe; %template(ofdm_equalizer_static_sptr) boost::shared_ptr; %pythoncode %{ ofdm_equalizer_static_sptr.__repr__ = lambda self: "" ofdm_equalizer_static = ofdm_equalizer_static.make; %} //%rename(ofdm_equalizer_static) make_ofdm_equalizer_static; //%ignore ofdm_equalizer_static; gnuradio-3.7.2.1/gr-digital/swig/digital_swig.i0000664000175000017500000002470112237515112021143 0ustar jcorganjcorgan/* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define DIGITAL_API #define ANALOG_API #define BLOCKS_API %include "gnuradio.i" %include "stdint.i" //load generated python docstrings %include "digital_swig_doc.i" %include "gnuradio/analog/cpm.h" %{ #include %} %include %{ #include "gnuradio/digital/additive_scrambler_bb.h" #include "gnuradio/digital/binary_slicer_fb.h" #include "gnuradio/digital/chunks_to_symbols_bc.h" #include "gnuradio/digital/chunks_to_symbols_bf.h" #include "gnuradio/digital/chunks_to_symbols_ic.h" #include "gnuradio/digital/chunks_to_symbols_if.h" #include "gnuradio/digital/chunks_to_symbols_sc.h" #include "gnuradio/digital/chunks_to_symbols_sf.h" #include "gnuradio/digital/clock_recovery_mm_cc.h" #include "gnuradio/digital/clock_recovery_mm_ff.h" #include "gnuradio/digital/cma_equalizer_cc.h" #include "gnuradio/digital/constellation.h" #include "gnuradio/digital/constellation_decoder_cb.h" #include "gnuradio/digital/constellation_receiver_cb.h" #include "gnuradio/digital/constellation_soft_decoder_cf.h" #include "gnuradio/digital/correlate_access_code_bb.h" #include "gnuradio/digital/correlate_access_code_tag_bb.h" #include "gnuradio/digital/correlate_and_sync_cc.h" #include "gnuradio/digital/costas_loop_cc.h" #include "gnuradio/digital/cpmmod_bc.h" #include "gnuradio/digital/crc32.h" #include "gnuradio/digital/crc32_bb.h" #include "gnuradio/digital/descrambler_bb.h" #include "gnuradio/digital/diff_decoder_bb.h" #include "gnuradio/digital/diff_encoder_bb.h" #include "gnuradio/digital/diff_phasor_cc.h" #include "gnuradio/digital/fll_band_edge_cc.h" #include "gnuradio/digital/framer_sink_1.h" #include "gnuradio/digital/glfsr_source_b.h" #include "gnuradio/digital/glfsr_source_f.h" #include "gnuradio/digital/header_payload_demux.h" #include "gnuradio/digital/kurtotic_equalizer_cc.h" #include "gnuradio/digital/lfsr.h" #include "gnuradio/digital/lms_dd_equalizer_cc.h" #include "gnuradio/digital/map_bb.h" #include "gnuradio/digital/metric_type.h" #include "gnuradio/digital/mpsk_receiver_cc.h" #include "gnuradio/digital/mpsk_snr_est.h" #include "gnuradio/digital/mpsk_snr_est_cc.h" #include "gnuradio/digital/ofdm_carrier_allocator_cvc.h" #include "gnuradio/digital/ofdm_chanest_vcvc.h" #include "gnuradio/digital/ofdm_cyclic_prefixer.h" #include "gnuradio/digital/ofdm_equalizer_base.h" #include "gnuradio/digital/ofdm_equalizer_simpledfe.h" #include "gnuradio/digital/ofdm_equalizer_static.h" #include "gnuradio/digital/ofdm_frame_acquisition.h" #include "gnuradio/digital/ofdm_frame_equalizer_vcvc.h" #include "gnuradio/digital/ofdm_frame_sink.h" #include "gnuradio/digital/ofdm_insert_preamble.h" #include "gnuradio/digital/ofdm_mapper_bcv.h" #include "gnuradio/digital/ofdm_sampler.h" #include "gnuradio/digital/ofdm_serializer_vcc.h" #include "gnuradio/digital/ofdm_sync_sc_cfb.h" #include "gnuradio/digital/packet_header_default.h" #include "gnuradio/digital/packet_header_ofdm.h" #include "gnuradio/digital/packet_headergenerator_bb.h" #include "gnuradio/digital/packet_headerparser_b.h" #include "gnuradio/digital/packet_sink.h" #include "gnuradio/digital/pfb_clock_sync_ccf.h" #include "gnuradio/digital/pfb_clock_sync_fff.h" #include "gnuradio/digital/pn_correlator_cc.h" #include "gnuradio/digital/probe_density_b.h" #include "gnuradio/digital/probe_mpsk_snr_est_c.h" #include "gnuradio/digital/scrambler_bb.h" #include "gnuradio/digital/simple_correlator.h" #include "gnuradio/digital/simple_framer.h" #include "gnuradio/digital/ofdm_serializer_vcc.h" #include "gnuradio/digital/packet_headerparser_b.h" #include "gnuradio/digital/header_payload_demux.h" %} %include "gnuradio/digital/additive_scrambler_bb.h" %include "gnuradio/digital/binary_slicer_fb.h" %include "gnuradio/digital/chunks_to_symbols_bc.h" %include "gnuradio/digital/chunks_to_symbols_bf.h" %include "gnuradio/digital/chunks_to_symbols_ic.h" %include "gnuradio/digital/chunks_to_symbols_if.h" %include "gnuradio/digital/chunks_to_symbols_sc.h" %include "gnuradio/digital/chunks_to_symbols_sf.h" %include "gnuradio/digital/clock_recovery_mm_cc.h" %include "gnuradio/digital/clock_recovery_mm_ff.h" %include "gnuradio/digital/cma_equalizer_cc.h" %include "gnuradio/digital/constellation.h" %include "gnuradio/digital/constellation_decoder_cb.h" %include "gnuradio/digital/constellation_receiver_cb.h" %include "gnuradio/digital/constellation_soft_decoder_cf.h" %include "gnuradio/digital/correlate_access_code_bb.h" %include "gnuradio/digital/correlate_access_code_tag_bb.h" %include "gnuradio/digital/correlate_and_sync_cc.h" %include "gnuradio/digital/costas_loop_cc.h" %include "gnuradio/digital/cpmmod_bc.h" %include "gnuradio/digital/crc32.h" %include "gnuradio/digital/crc32_bb.h" %include "gnuradio/digital/descrambler_bb.h" %include "gnuradio/digital/diff_decoder_bb.h" %include "gnuradio/digital/diff_encoder_bb.h" %include "gnuradio/digital/diff_phasor_cc.h" %include "gnuradio/digital/fll_band_edge_cc.h" %include "gnuradio/digital/framer_sink_1.h" %include "gnuradio/digital/glfsr_source_b.h" %include "gnuradio/digital/glfsr_source_f.h" %include "gnuradio/digital/header_payload_demux.h" %include "gnuradio/digital/kurtotic_equalizer_cc.h" %include "gnuradio/digital/lfsr.h" %include "gnuradio/digital/lms_dd_equalizer_cc.h" %include "gnuradio/digital/map_bb.h" %include "gnuradio/digital/metric_type.h" %include "gnuradio/digital/mpsk_receiver_cc.h" %include "gnuradio/digital/mpsk_snr_est.h" %include "gnuradio/digital/mpsk_snr_est_cc.h" %include "gnuradio/digital/ofdm_carrier_allocator_cvc.h" %include "gnuradio/digital/ofdm_chanest_vcvc.h" %include "gnuradio/digital/ofdm_cyclic_prefixer.h" %include "gnuradio/digital/ofdm_equalizer_base.h" %include "gnuradio/digital/ofdm_equalizer_simpledfe.h" %include "gnuradio/digital/ofdm_equalizer_static.h" %include "gnuradio/digital/ofdm_frame_acquisition.h" %include "gnuradio/digital/ofdm_frame_equalizer_vcvc.h" %include "gnuradio/digital/ofdm_frame_sink.h" %include "gnuradio/digital/ofdm_insert_preamble.h" %include "gnuradio/digital/ofdm_mapper_bcv.h" %include "gnuradio/digital/ofdm_sampler.h" %include "gnuradio/digital/ofdm_serializer_vcc.h" %include "gnuradio/digital/ofdm_sync_sc_cfb.h" %include "gnuradio/digital/packet_header_default.h" %include "gnuradio/digital/packet_header_ofdm.h" %include "gnuradio/digital/packet_headergenerator_bb.h" %include "gnuradio/digital/packet_headerparser_b.h" %include "gnuradio/digital/packet_sink.h" %include "gnuradio/digital/pfb_clock_sync_ccf.h" %include "gnuradio/digital/pfb_clock_sync_fff.h" %include "gnuradio/digital/pn_correlator_cc.h" %include "gnuradio/digital/probe_density_b.h" %include "gnuradio/digital/probe_mpsk_snr_est_c.h" %include "gnuradio/digital/scrambler_bb.h" %include "gnuradio/digital/simple_correlator.h" %include "gnuradio/digital/simple_framer.h" GR_SWIG_BLOCK_MAGIC2(digital, additive_scrambler_bb); GR_SWIG_BLOCK_MAGIC2(digital, binary_slicer_fb); GR_SWIG_BLOCK_MAGIC2(digital, chunks_to_symbols_bc); GR_SWIG_BLOCK_MAGIC2(digital, chunks_to_symbols_bf); GR_SWIG_BLOCK_MAGIC2(digital, chunks_to_symbols_ic); GR_SWIG_BLOCK_MAGIC2(digital, chunks_to_symbols_if); GR_SWIG_BLOCK_MAGIC2(digital, chunks_to_symbols_sc); GR_SWIG_BLOCK_MAGIC2(digital, chunks_to_symbols_sf); GR_SWIG_BLOCK_MAGIC2(digital, clock_recovery_mm_cc); GR_SWIG_BLOCK_MAGIC2(digital, clock_recovery_mm_ff); GR_SWIG_BLOCK_MAGIC2(digital, cma_equalizer_cc); GR_SWIG_BLOCK_MAGIC2(digital, constellation_decoder_cb); GR_SWIG_BLOCK_MAGIC2(digital, constellation_receiver_cb); GR_SWIG_BLOCK_MAGIC2(digital, constellation_soft_decoder_cf); GR_SWIG_BLOCK_MAGIC2(digital, correlate_access_code_bb); GR_SWIG_BLOCK_MAGIC2(digital, correlate_access_code_tag_bb); GR_SWIG_BLOCK_MAGIC2(digital, correlate_and_sync_cc); GR_SWIG_BLOCK_MAGIC2(digital, costas_loop_cc); GR_SWIG_BLOCK_MAGIC2(digital, crc32_bb); GR_SWIG_BLOCK_MAGIC2(digital, cpmmod_bc); GR_SWIG_BLOCK_MAGIC2(digital, descrambler_bb); GR_SWIG_BLOCK_MAGIC2(digital, diff_decoder_bb); GR_SWIG_BLOCK_MAGIC2(digital, diff_encoder_bb); GR_SWIG_BLOCK_MAGIC2(digital, diff_phasor_cc); GR_SWIG_BLOCK_MAGIC2(digital, fll_band_edge_cc); GR_SWIG_BLOCK_MAGIC2(digital, framer_sink_1); GR_SWIG_BLOCK_MAGIC2(digital, glfsr_source_b); GR_SWIG_BLOCK_MAGIC2(digital, glfsr_source_f); GR_SWIG_BLOCK_MAGIC2(digital, header_payload_demux); GR_SWIG_BLOCK_MAGIC2(digital, kurtotic_equalizer_cc); GR_SWIG_BLOCK_MAGIC2(digital, lms_dd_equalizer_cc); GR_SWIG_BLOCK_MAGIC2(digital, map_bb); GR_SWIG_BLOCK_MAGIC2(digital, mpsk_receiver_cc); GR_SWIG_BLOCK_MAGIC2(digital, mpsk_snr_est_cc); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_carrier_allocator_cvc); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_chanest_vcvc); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_cyclic_prefixer); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_frame_acquisition); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_frame_equalizer_vcvc); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_frame_sink); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_insert_preamble); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_mapper_bcv); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_sampler); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_serializer_vcc); GR_SWIG_BLOCK_MAGIC2(digital, ofdm_sync_sc_cfb); GR_SWIG_BLOCK_MAGIC2(digital, packet_headergenerator_bb); GR_SWIG_BLOCK_MAGIC2(digital, packet_headerparser_b); GR_SWIG_BLOCK_MAGIC2(digital, packet_sink); GR_SWIG_BLOCK_MAGIC2(digital, pfb_clock_sync_ccf); GR_SWIG_BLOCK_MAGIC2(digital, pfb_clock_sync_fff); GR_SWIG_BLOCK_MAGIC2(digital, pn_correlator_cc); GR_SWIG_BLOCK_MAGIC2(digital, probe_density_b); GR_SWIG_BLOCK_MAGIC2(digital, probe_mpsk_snr_est_c); GR_SWIG_BLOCK_MAGIC2(digital, scrambler_bb); GR_SWIG_BLOCK_MAGIC2(digital, simple_correlator); GR_SWIG_BLOCK_MAGIC2(digital, simple_framer); GR_SWIG_BLOCK_MAGIC_FACTORY(digital, cpmmod_bc, gmskmod_bc); // Properly package up non-block objects %include "constellation.i" %include "packet_header.i" %include "ofdm_equalizer.i" gnuradio-3.7.2.1/gr-digital/gnuradio-digital.pc.in0000664000175000017500000000041512207440367021530 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-digital Description: GNU Radio blocks for digital communications Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-digital Cflags: -I${includedir} gnuradio-3.7.2.1/gr-digital/README0000644000175000017500000000014411700377700016226 0ustar jcorganjcorganThis GNU Radio component for implementing digitial modulators and demodulators. FIXME: just fixme.gnuradio-3.7.2.1/gr-digital/examples/0000755000175000017500000000000012237515112017162 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/examples/CMakeLists.txt0000664000175000017500000000452212237515112021727 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) # Base stuff GR_PYTHON_INSTALL(PROGRAMS example_costas.py example_fll.py example_timing.py run_length.py gen_whitener.py snr_estimators.py DESTINATION ${GR_PKG_DIGITAL_EXAMPLES_DIR} COMPONENT "digital_python" ) # Narrowband GR_PYTHON_INSTALL(PROGRAMS narrowband/transmit_path.py narrowband/receive_path.py narrowband/uhd_interface.py narrowband/benchmark_tx.py narrowband/benchmark_rx.py narrowband/tx_voice.py narrowband/rx_voice.py narrowband/digital_bert_rx.py narrowband/digital_bert_tx.py narrowband/tunnel.py DESTINATION ${GR_PKG_DIGITAL_EXAMPLES_DIR}/narrowband COMPONENT "digital_python" ) # OFDM GR_PYTHON_INSTALL(PROGRAMS ofdm/benchmark_add_channel.py ofdm/benchmark_rx.py ofdm/benchmark_tx.py ofdm/gr_plot_ofdm.py ofdm/receive_path.py ofdm/transmit_path.py ofdm/tunnel.py ofdm/uhd_interface.py DESTINATION ${GR_PKG_DIGITAL_EXAMPLES_DIR}/ofdm COMPONENT "digital_python" ) install( FILES ofdm/tx_ofdm.grc ofdm/rx_ofdm.grc ofdm/ofdm_loopback.grc DESTINATION ${GR_PKG_DIGITAL_EXAMPLES_DIR}/ofdm COMPONENT "digital_python" ) # DEMOD install( FILES demod/digital_freq_lock.grc demod/mpsk_demod.grc demod/pam_sync.grc demod/pam_timing.grc demod/ber_simulation.grc demod/dpsk_loopback.grc demod/gfsk_loopback.grc demod/test_corr_and_sync.grc demod/uhd_corr_and_sync_tx.grc demod/uhd_corr_and_sync_rx.grc DESTINATION ${GR_PKG_DIGITAL_EXAMPLES_DIR}/demod COMPONENT "digital_python" ) gnuradio-3.7.2.1/gr-digital/examples/example_timing.py0000775000175000017500000002177312237515112022555 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, digital, filter from gnuradio import blocks from gnuradio import channels from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser try: import scipy except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) from scipy import fftpack class example_timing(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset, mode=0): gr.top_block.__init__(self) rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) gain = bw nfilts = 32 rrc_taps_rx = filter.firdes.root_raised_cosine( nfilts, sps*nfilts, 1.0, rolloff, ntaps*nfilts) data = 2.0*scipy.random.randint(0, 2, N) - 1.0 data = scipy.exp(1j*poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) self.chn = channels.channel_model(noise, foffset, toffset) self.off = filter.fractional_resampler_cc(0.20, 1.0) if mode == 0: self.clk = digital.pfb_clock_sync_ccf(sps, gain, rrc_taps_rx, nfilts, nfilts//2, 1) self.taps = self.clk.taps() self.dtaps = self.clk.diff_taps() self.delay = int(scipy.ceil(((len(rrc_taps)-1)/2 + (len(self.taps[0])-1)/2)/float(sps))) + 1 self.vsnk_err = blocks.vector_sink_f() self.vsnk_rat = blocks.vector_sink_f() self.vsnk_phs = blocks.vector_sink_f() self.connect((self.clk,1), self.vsnk_err) self.connect((self.clk,2), self.vsnk_rat) self.connect((self.clk,3), self.vsnk_phs) else: # mode == 1 mu = 0.5 gain_mu = bw gain_omega = 0.25*gain_mu*gain_mu omega_rel_lim = 0.02 self.clk = digital.clock_recovery_mm_cc(sps, gain_omega, mu, gain_mu, omega_rel_lim) self.vsnk_err = blocks.vector_sink_f() self.connect((self.clk,1), self.vsnk_err) self.vsnk_src = blocks.vector_sink_c() self.vsnk_clk = blocks.vector_sink_c() self.connect(self.src, self.rrc, self.chn, self.off, self.clk, self.vsnk_clk) self.connect(self.src, self.vsnk_src) def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=2000, help="Set the number of samples to process [default=%default]") parser.add_option("-S", "--sps", type="int", default=4, help="Set the samples per symbol [default=%default]") parser.add_option("-r", "--rolloff", type="eng_float", default=0.35, help="Set the rolloff factor [default=%default]") parser.add_option("-W", "--bandwidth", type="eng_float", default=2*scipy.pi/100.0, help="Set the loop bandwidth (PFB) or gain (M&M) [default=%default]") parser.add_option("-n", "--ntaps", type="int", default=45, help="Set the number of taps in the filters [default=%default]") parser.add_option("", "--noise", type="eng_float", default=0.0, help="Set the simulation noise voltage [default=%default]") parser.add_option("-f", "--foffset", type="eng_float", default=0.0, help="Set the simulation's normalized frequency offset (in Hz) [default=%default]") parser.add_option("-t", "--toffset", type="eng_float", default=1.0, help="Set the simulation's timing offset [default=%default]") parser.add_option("-p", "--poffset", type="eng_float", default=0.0, help="Set the simulation's phase offset [default=%default]") parser.add_option("-M", "--mode", type="int", default=0, help="Set the recovery mode (0: polyphase, 1: M&M) [default=%default]") (options, args) = parser.parse_args () # Adjust N for the interpolation by sps options.nsamples = options.nsamples // options.sps # Set up the program-under-test put = example_timing(options.nsamples, options.sps, options.rolloff, options.ntaps, options.bandwidth, options.noise, options.foffset, options.toffset, options.poffset, options.mode) put.run() if options.mode == 0: data_src = scipy.array(put.vsnk_src.data()[20:]) data_clk = scipy.array(put.vsnk_clk.data()[20:]) data_err = scipy.array(put.vsnk_err.data()[20:]) data_rat = scipy.array(put.vsnk_rat.data()[20:]) data_phs = scipy.array(put.vsnk_phs.data()[20:]) f1 = pylab.figure(1, figsize=(12,10), facecolor='w') # Plot the IQ symbols s1 = f1.add_subplot(2,2,1) s1.plot(data_src.real, data_src.imag, "bo") s1.plot(data_clk.real, data_clk.imag, "ro") s1.set_title("IQ") s1.set_xlabel("Real part") s1.set_ylabel("Imag part") s1.set_xlim([-2, 2]) s1.set_ylim([-2, 2]) # Plot the symbols in time delay = put.delay m = len(data_clk.real) s2 = f1.add_subplot(2,2,2) s2.plot(data_src.real, "bs", markersize=10, label="Input") s2.plot(data_clk.real[delay:], "ro", label="Recovered") s2.set_title("Symbols") s2.set_xlabel("Samples") s2.set_ylabel("Real Part of Signals") s2.legend() # Plot the clock recovery loop's error s3 = f1.add_subplot(2,2,3) s3.plot(data_err, label="Error") s3.plot(data_rat, 'r', label="Update rate") s3.set_title("Clock Recovery Loop Error") s3.set_xlabel("Samples") s3.set_ylabel("Error") s3.set_ylim([-0.5, 0.5]) s3.legend() # Plot the clock recovery loop's error s4 = f1.add_subplot(2,2,4) s4.plot(data_phs) s4.set_title("Clock Recovery Loop Filter Phase") s4.set_xlabel("Samples") s4.set_ylabel("Filter Phase") diff_taps = put.dtaps ntaps = len(diff_taps[0]) nfilts = len(diff_taps) t = scipy.arange(0, ntaps*nfilts) f3 = pylab.figure(3, figsize=(12,10), facecolor='w') s31 = f3.add_subplot(2,1,1) s32 = f3.add_subplot(2,1,2) s31.set_title("Differential Filters") s32.set_title("FFT of Differential Filters") for i,d in enumerate(diff_taps): D = 20.0*scipy.log10(1e-20+abs(fftpack.fftshift(fftpack.fft(d, 10000)))) s31.plot(t[i::nfilts].real, d, "-o") s32.plot(D) s32.set_ylim([-120, 10]) # If testing the M&M clock recovery loop else: data_src = scipy.array(put.vsnk_src.data()[20:]) data_clk = scipy.array(put.vsnk_clk.data()[20:]) data_err = scipy.array(put.vsnk_err.data()[20:]) f1 = pylab.figure(1, figsize=(12,10), facecolor='w') # Plot the IQ symbols s1 = f1.add_subplot(2,2,1) s1.plot(data_src.real, data_src.imag, "o") s1.plot(data_clk.real, data_clk.imag, "ro") s1.set_title("IQ") s1.set_xlabel("Real part") s1.set_ylabel("Imag part") s1.set_xlim([-2, 2]) s1.set_ylim([-2, 2]) # Plot the symbols in time s2 = f1.add_subplot(2,2,2) s2.plot(data_src.real, "bs", markersize=10, label="Input") s2.plot(data_clk.real, "ro", label="Recovered") s2.set_title("Symbols") s2.set_xlabel("Samples") s2.set_ylabel("Real Part of Signals") s2.legend() # Plot the clock recovery loop's error s3 = f1.add_subplot(2,2,3) s3.plot(data_err) s3.set_title("Clock Recovery Loop Error") s3.set_xlabel("Samples") s3.set_ylabel("Error") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/example_costas.py0000775000175000017500000001230612207440367022560 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, digital, filter from gnuradio import blocks from gnuradio import channels from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser try: import scipy except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) class example_costas(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset): gr.top_block.__init__(self) rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) data = 2.0*scipy.random.randint(0, 2, N) - 1.0 data = scipy.exp(1j*poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) self.chn = channels.channel_model(noise, foffset, toffset) self.cst = digital.costas_loop_cc(bw, 2) self.vsnk_src = blocks.vector_sink_c() self.vsnk_cst = blocks.vector_sink_c() self.vsnk_frq = blocks.vector_sink_f() self.connect(self.src, self.rrc, self.chn, self.cst, self.vsnk_cst) self.connect(self.rrc, self.vsnk_src) self.connect((self.cst,1), self.vsnk_frq) def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=2000, help="Set the number of samples to process [default=%default]") parser.add_option("-S", "--sps", type="int", default=4, help="Set the samples per symbol [default=%default]") parser.add_option("-r", "--rolloff", type="eng_float", default=0.35, help="Set the rolloff factor [default=%default]") parser.add_option("-W", "--bandwidth", type="eng_float", default=2*scipy.pi/100.0, help="Set the loop bandwidth [default=%default]") parser.add_option("-n", "--ntaps", type="int", default=45, help="Set the number of taps in the filters [default=%default]") parser.add_option("", "--noise", type="eng_float", default=0.0, help="Set the simulation noise voltage [default=%default]") parser.add_option("-f", "--foffset", type="eng_float", default=0.0, help="Set the simulation's normalized frequency offset (in Hz) [default=%default]") parser.add_option("-t", "--toffset", type="eng_float", default=1.0, help="Set the simulation's timing offset [default=%default]") parser.add_option("-p", "--poffset", type="eng_float", default=0.707, help="Set the simulation's phase offset [default=%default]") (options, args) = parser.parse_args () # Adjust N for the interpolation by sps options.nsamples = options.nsamples // options.sps # Set up the program-under-test put = example_costas(options.nsamples, options.sps, options.rolloff, options.ntaps, options.bandwidth, options.noise, options.foffset, options.toffset, options.poffset) put.run() data_src = scipy.array(put.vsnk_src.data()) # Convert the FLL's LO frequency from rads/sec to Hz data_frq = scipy.array(put.vsnk_frq.data()) / (2.0*scipy.pi) # adjust this to align with the data. data_cst = scipy.array(3*[0,]+list(put.vsnk_cst.data())) # Plot the Costas loop's LO frequency f1 = pylab.figure(1, figsize=(12,10), facecolor='w') s1 = f1.add_subplot(2,2,1) s1.plot(data_frq) s1.set_title("Costas LO") s1.set_xlabel("Samples") s1.set_ylabel("Frequency (normalized Hz)") # Plot the IQ symbols s3 = f1.add_subplot(2,2,2) s3.plot(data_src.real, data_src.imag, "o") s3.plot(data_cst.real, data_cst.imag, "rx") s3.set_title("IQ") s3.set_xlabel("Real part") s3.set_ylabel("Imag part") s3.set_xlim([-2, 2]) s3.set_ylim([-2, 2]) # Plot the symbols in time s4 = f1.add_subplot(2,2,3) s4.set_position([0.125, 0.05, 0.775, 0.4]) s4.plot(data_src.real, "o-") s4.plot(data_cst.real, "rx-") s4.set_title("Symbols") s4.set_xlabel("Samples") s4.set_ylabel("Real Part of Signals") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/run_length.py0000755000175000017500000000452511700377701021716 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from optparse import OptionParser import sys def main(): parser = OptionParser() parser.add_option("-f", "--file", default=None, help="Choose file to read data from.") (options, args) = parser.parse_args() if options.file == None: print "Must specify file to read from using '-f'." sys.exit(1) print "Using", options.file, "for data." f = open(options.file, 'r') runs = [] count = 0 current = 0 bytes = 0 bits = 0 for ch in f.read(): x = ord(ch) bytes = bytes + 1 for i in range(7,-1,-1): bits = bits + 1 t = (x >> i) & 0x1 if t == current: count = count + 1 else: if count > 0: if len(runs) < count: for j in range(count - len(runs)): runs.append(0); runs[count-1] = runs[count-1] + 1 current = 1-current; count = 1 # Deal with last run at EOF if len(runs) < count and count > 0: for j in range(count - len(runs)): runs.append(0); runs[count-1] = runs[count-1] + 1 chk = 0 print "Bytes read: ", bytes print "Bits read: ", bits print for i in range(len(runs)): chk = chk + runs[i]*(i+1) print "Runs of length", i+1, ":", runs[i] print print "Sum of runs:", chk, "bits" print print "Maximum run length is", len(runs), "bits" if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-digital/examples/narrowband/0000755000175000017500000000000012207702530021316 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/examples/narrowband/benchmark_add_channel.py0000775000175000017500000001022612207440367026137 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import random, math, sys class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): gr.top_block.__init__(self) SNR = 10.0**(options.snr/10.0) frequency_offset = options.frequency_offset time_offset = options.time_offset phase_offset = options.phase_offset*(math.pi/180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude)**2 noise_power = power_in_signal/SNR noise_voltage = math.sqrt(noise_power) self.src = blocks.file_source(gr.sizeof_gr_complex, ifile) #self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = filter.channel_model(noise_voltage, frequency_offset, time_offset, noise_seed=-random.randint(0,100000)) self.phase = blocks.multiply_const_cc(complex(math.cos(phase_offset), math.sin(phase_offset))) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] " parser = OptionParser (usage=usage, option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--seed", action="store_true", default=False, help="use a random seed for AWGN noise [default=%default]") parser.add_option("-f", "--frequency-offset", type="eng_float", default=0, help="set frequency offset introduced by channel [default=%default]") parser.add_option("-t", "--time-offset", type="eng_float", default=1.0, help="set timing offset between Tx and Rx [default=%default]") parser.add_option("-p", "--phase-offset", type="eng_float", default=0, help="set phase offset (in degrees) between Tx and Rx [default=%default]") parser.add_option("-m", "--use-multipath", action="store_true", default=False, help="Use a multipath channel [default=%default]") parser.add_option("", "--tx-amplitude", type="eng_float", default=1.0, help="tell the simulator the signal amplitude [default=%default]") (options, args) = parser.parse_args () if len(args) != 2: parser.print_help(sys.stderr) sys.exit(1) ifile = args[0] ofile = args[1] # build the graph tb = my_top_block(ifile, ofile, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: Failed to enable realtime scheduling." tb.start() # start flow graph tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/benchmark_rx.py0000775000175000017500000001127112207702530024342 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser # From gr-digital from gnuradio import digital # from current dir from receive_path import receive_path from uhd_interface import uhd_receiver import struct import sys #import os #print os.getpid() #raw_input('Attach and press enter: ') class my_top_block(gr.top_block): def __init__(self, demodulator, rx_callback, options): gr.top_block.__init__(self) if(options.rx_freq is not None): # Work-around to get the modulation's bits_per_symbol args = demodulator.extract_kwargs_from_options(options) symbol_rate = options.bitrate / demodulator(**args).bits_per_symbol() self.source = uhd_receiver(options.args, symbol_rate, options.samples_per_symbol, options.rx_freq, options.lo_offset, options.rx_gain, options.spec, options.antenna, options.clock_source, options.verbose) options.samples_per_symbol = self.source._sps elif(options.from_file is not None): sys.stderr.write(("Reading samples from '%s'.\n\n" % (options.from_file))) self.source = blocks.file_source(gr.sizeof_gr_complex, options.from_file) else: sys.stderr.write("No source defined, pulling samples from null source.\n\n") self.source = blocks.null_source(gr.sizeof_gr_complex) # Set up receive path # do this after for any adjustments to the options that may # occur in the sinks (specifically the UHD sink) self.rxpath = receive_path(demodulator, rx_callback, options) self.connect(self.source, self.rxpath) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// global n_rcvd, n_right def main(): global n_rcvd, n_right n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right (pktno,) = struct.unpack('!H', payload[0:2]) n_rcvd += 1 if ok: n_right += 1 print "ok = %5s pktno = %4d n_rcvd = %4d n_right = %4d" % ( ok, pktno, n_rcvd, n_right) demods = digital.modulation_utils.type_1_demods() # Create Options Parser: parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=demods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(demods.keys()),)) parser.add_option("","--from-file", default=None, help="input file of samples to demod") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) for mod in demods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(demods[options.modulation], rx_callback, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: Failed to enable realtime scheduling." tb.start() # start flow graph tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/receive_path.py0000664000175000017500000001374412207440367024350 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, filter from gnuradio import eng_notation from gnuradio import digital from gnuradio import analog import copy import sys # ///////////////////////////////////////////////////////////////////////////// # receive path # ///////////////////////////////////////////////////////////////////////////// class receive_path(gr.hier_block2): def __init__(self, demod_class, rx_callback, options): gr.hier_block2.__init__(self, "receive_path", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) options = copy.copy(options) # make a copy so we can destructively modify self._verbose = options.verbose self._bitrate = options.bitrate # desired bit rate self._rx_callback = rx_callback # this callback is fired when a packet arrives self._demod_class = demod_class # the demodulator_class we're using self._chbw_factor = options.chbw_factor # channel filter bandwidth factor # Get demod_kwargs demod_kwargs = self._demod_class.extract_kwargs_from_options(options) # Build the demodulator self.demodulator = self._demod_class(**demod_kwargs) # Make sure the channel BW factor is between 1 and sps/2 # or the filter won't work. if(self._chbw_factor < 1.0 or self._chbw_factor > self.samples_per_symbol()/2): sys.stderr.write("Channel bandwidth factor ({0}) must be within the range [1.0, {1}].\n".format(self._chbw_factor, self.samples_per_symbol()/2)) sys.exit(1) # Design filter to get actual channel we want sw_decim = 1 chan_coeffs = filter.firdes.low_pass(1.0, # gain sw_decim * self.samples_per_symbol(), # sampling rate self._chbw_factor, # midpoint of trans. band 0.5, # width of trans. band filter.firdes.WIN_HANN) # filter type self.channel_filter = filter.fft_filter_ccc(sw_decim, chan_coeffs) # receiver self.packet_receiver = \ digital.demod_pkts(self.demodulator, access_code=None, callback=self._rx_callback, threshold=-1) # Carrier Sensing Blocks alpha = 0.001 thresh = 30 # in dB, will have to adjust self.probe = analog.probe_avg_mag_sqrd_c(thresh,alpha) # Display some information about the setup if self._verbose: self._print_verbage() # connect block input to channel filter self.connect(self, self.channel_filter) # connect the channel input filter to the carrier power detector self.connect(self.channel_filter, self.probe) # connect channel filter to the packet receiver self.connect(self.channel_filter, self.packet_receiver) def bitrate(self): return self._bitrate def samples_per_symbol(self): return self.demodulator._samples_per_symbol def differential(self): return self.demodulator._differential def carrier_sensed(self): """ Return True if we think carrier is present. """ #return self.probe.level() > X return self.probe.unmuted() def carrier_threshold(self): """ Return current setting in dB. """ return self.probe.threshold() def set_carrier_threshold(self, threshold_in_db): """ Set carrier threshold. Args: threshold_in_db: set detection threshold (float (dB)) """ self.probe.set_threshold(threshold_in_db) def add_options(normal, expert): """ Adds receiver-specific options to the Options Parser """ if not normal.has_option("--bitrate"): normal.add_option("-r", "--bitrate", type="eng_float", default=100e3, help="specify bitrate [default=%default].") normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") expert.add_option("", "--chbw-factor", type="float", default=1.0, help="Channel bandwidth = chbw_factor x signal bandwidth [defaut=%default]") # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the receive path """ print "\nReceive Path:" print "modulation: %s" % (self._demod_class.__name__) print "bitrate: %sb/s" % (eng_notation.num_to_str(self._bitrate)) print "samples/symbol: %.4f" % (self.samples_per_symbol()) print "Differential: %s" % (self.differential()) gnuradio-3.7.2.1/gr-digital/examples/narrowband/tx_voice.py0000775000175000017500000001330412207440367023525 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2009,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser from gnuradio import blocks from gnuradio import filter from gnuradio import digital from gnuradio import vocoder import random import time import struct import sys # from current dir from transmit_path import transmit_path from uhd_interface import uhd_transmitter #import os #print os.getpid() #raw_input('Attach and press enter') class audio_rx(gr.hier_block2): def __init__(self, audio_input_dev): gr.hier_block2.__init__(self, "audio_rx", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.sample_rate = sample_rate = 8000 src = audio.source(sample_rate, audio_input_dev) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() voice_coder = vocoder.gsm_fr_encode_sp() self.packets_from_encoder = gr.msg_queue() packet_sink = blocks.message_sink(33, self.packets_from_encoder, False) self.connect(src, src_scale, f2s, voice_coder, packet_sink) def get_encoded_voice_packet(self): return self.packets_from_encoder.delete_head() class my_top_block(gr.top_block): def __init__(self, modulator_class, options): gr.top_block.__init__(self) self.txpath = transmit_path(modulator_class, options) self.audio_rx = audio_rx(options.audio_input) if(options.tx_freq is not None): self.sink = uhd_transmitter(options.address, options.bitrate, options.samples_per_symbol, options.tx_freq, options.tx_gain, options.antenna, options.verbose) options.samples_per_symbol = self.sink._sps audio_rate = self.audio_rx.sample_rate usrp_rate = self.sink.get_sample_rate() rrate = usrp_rate / audio_rate elif(options.to_file is not None): self.sink = blocks.file_sink(gr.sizeof_gr_complex, options.to_file) rrate = 1 else: self.sink = blocks.null_sink(gr.sizeof_gr_complex) rrate = 1 self.resampler = filter.pfb.arb_resampler_ccf(rrate) self.connect(self.audio_rx) self.connect(self.txpath, self.resampler, self.sink) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) def rx_callback(ok, payload): print "ok = %r, payload = '%s'" % (ok, payload) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-M", "--megabytes", type="eng_float", default=0, help="set megabytes to transmit [default=inf]") parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) parser.set_defaults(bitrate=50e3) # override default bitrate default (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.to_file is None: if options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 while nbytes == 0 or n < nbytes: packet = tb.audio_rx.get_encoded_voice_packet() s = packet.to_string() send_pkt(s) n += len(s) sys.stderr.write('.') pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/digital_bert_tx.py0000775000175000017500000001257612207440367025063 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys from gnuradio import blocks from gnuradio import digital # from current dir from uhd_interface import uhd_transmitter n2s = eng_notation.num_to_str class bert_transmit(gr.hier_block2): def __init__(self, constellation, samples_per_symbol, differential, excess_bw, gray_coded, verbose, log): gr.hier_block2.__init__(self, "bert_transmit", gr.io_signature(0, 0, 0), # Output signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Input signature # Create BERT data bit stream self._bits = blocks.vector_source_b([1,], True) # Infinite stream of ones self._scrambler = digital.scrambler_bb(0x8A, 0x7F, 7) # CCSDS 7-bit scrambler self._mod = digital.generic_mod(constellation, differential, samples_per_symbol, gray_coded, excess_bw, verbose, log) self._pack = blocks.unpacked_to_packed_bb(self._mod.bits_per_symbol(), gr.GR_MSB_FIRST) self.connect(self._bits, self._scrambler, self._pack, self._mod, self) class tx_psk_block(gr.top_block): def __init__(self, mod, options): gr.top_block.__init__(self, "tx_mpsk") self._modulator_class = mod # Get mod_kwargs mod_kwargs = self._modulator_class.extract_kwargs_from_options(options) # transmitter self._modulator = self._modulator_class(**mod_kwargs) if(options.tx_freq is not None): symbol_rate = options.bitrate / self._modulator.bits_per_symbol() self._sink = uhd_transmitter(options.args, symbol_rate, options.samples_per_symbol, options.tx_freq, options.tx_gain, options.spec, options.antenna, options.verbose) options.samples_per_symbol = self._sink._sps elif(options.to_file is not None): self._sink = blocks.file_sink(gr.sizeof_gr_complex, options.to_file) else: self._sink = blocks.null_sink(gr.sizeof_gr_complex) self._transmitter = bert_transmit(self._modulator._constellation, options.samples_per_symbol, options.differential, options.excess_bw, gray_coded=True, verbose=options.verbose, log=options.log) self.amp = blocks.multiply_const_cc(options.amplitude) self.connect(self._transmitter, self.amp, self._sink) def get_options(mods): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("", "--amplitude", type="eng_float", default=0.2, help="set Tx amplitude (0-1) (default=%default)") parser.add_option("-r", "--bitrate", type="eng_float", default=250e3, help="Select modulation bit rate (default=%default)") parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") if not parser.has_option("--verbose"): parser.add_option("-v", "--verbose", action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) return (options, args) if __name__ == "__main__": mods = digital.modulation_utils.type_1_mods() (options, args) = get_options(mods) mod = mods[options.modulation] tb = tx_psk_block(mod, options) try: tb.run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/tunnel.py0000775000175000017500000002406512207440367023220 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2006,2009,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # //////////////////////////////////////////////////////////////////// # # This code sets up up a virtual ethernet interface (typically # gr0), and relays packets between the interface and the GNU Radio # PHY+MAC # # What this means in plain language, is that if you've got a couple # of USRPs on different machines, and if you run this code on those # machines, you can talk between them using normal TCP/IP # networking. # # //////////////////////////////////////////////////////////////////// from gnuradio import gr, digital from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser # from current dir from receive_path import receive_path from transmit_path import transmit_path from uhd_interface import uhd_transmitter from uhd_interface import uhd_receiver import os, sys import random, time, struct #print os.getpid() #raw_input('Attach and press enter') # //////////////////////////////////////////////////////////////////// # # Use the Universal TUN/TAP device driver to move packets to/from # kernel # # See /usr/src/linux/Documentation/networking/tuntap.txt # # //////////////////////////////////////////////////////////////////// # Linux specific... # TUNSETIFF ifr flags from IFF_TUN = 0x0001 # tunnel IP packets IFF_TAP = 0x0002 # tunnel ethernet frames IFF_NO_PI = 0x1000 # don't pass extra packet info IFF_ONE_QUEUE = 0x2000 # beats me ;) def open_tun_interface(tun_device_filename): from fcntl import ioctl mode = IFF_TAP | IFF_NO_PI TUNSETIFF = 0x400454ca tun = os.open(tun_device_filename, os.O_RDWR) ifs = ioctl(tun, TUNSETIFF, struct.pack("16sH", "gr%d", mode)) ifname = ifs[:16].strip("\x00") return (tun, ifname) # //////////////////////////////////////////////////////////////////// # the flow graph # //////////////////////////////////////////////////////////////////// class my_top_block(gr.top_block): def __init__(self, mod_class, demod_class, rx_callback, options): gr.top_block.__init__(self) # Get the modulation's bits_per_symbol args = mod_class.extract_kwargs_from_options(options) symbol_rate = options.bitrate / mod_class(**args).bits_per_symbol() self.source = uhd_receiver(options.args, symbol_rate, options.samples_per_symbol, options.rx_freq, options.rx_gain, options.spec, options.antenna, options.verbose) self.sink = uhd_transmitter(options.args, symbol_rate, options.samples_per_symbol, options.tx_freq, options.tx_gain, options.spec, options.antenna, options.verbose) options.samples_per_symbol = self.source._sps self.txpath = transmit_path(mod_class, options) self.rxpath = receive_path(demod_class, rx_callback, options) self.connect(self.txpath, self.sink) self.connect(self.source, self.rxpath) def send_pkt(self, payload='', eof=False): return self.txpath.send_pkt(payload, eof) def carrier_sensed(self): """ Return True if the receive path thinks there's carrier """ return self.rxpath.carrier_sensed() def set_freq(self, target_freq): """ Set the center frequency we're interested in. """ self.sink.set_freq(target_freq) self.source.set_freq(target_freq) # //////////////////////////////////////////////////////////////////// # Carrier Sense MAC # //////////////////////////////////////////////////////////////////// class cs_mac(object): """ Prototype carrier sense MAC Reads packets from the TUN/TAP interface, and sends them to the PHY. Receives packets from the PHY via phy_rx_callback, and sends them into the TUN/TAP interface. Of course, we're not restricted to getting packets via TUN/TAP, this is just an example. """ def __init__(self, tun_fd, verbose=False): self.tun_fd = tun_fd # file descriptor for TUN/TAP interface self.verbose = verbose self.tb = None # top block (access to PHY) def set_top_block(self, tb): self.tb = tb def phy_rx_callback(self, ok, payload): """ Invoked by thread associated with PHY to pass received packet up. Args: ok: bool indicating whether payload CRC was OK payload: contents of the packet (string) """ if self.verbose: print "Rx: ok = %r len(payload) = %4d" % (ok, len(payload)) if ok: os.write(self.tun_fd, payload) def main_loop(self): """ Main loop for MAC. Only returns if we get an error reading from TUN. FIXME: may want to check for EINTR and EAGAIN and reissue read """ min_delay = 0.001 # seconds while 1: payload = os.read(self.tun_fd, 10*1024) if not payload: self.tb.send_pkt(eof=True) break if self.verbose: print "Tx: len(payload) = %4d" % (len(payload),) delay = min_delay while self.tb.carrier_sensed(): sys.stderr.write('B') time.sleep(delay) if delay < 0.050: delay = delay * 2 # exponential back-off self.tb.send_pkt(payload) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-v","--verbose", action="store_true", default=False) expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = my_top_block(mods[options.modulation], demods[options.modulation], mac.phy_rx_callback, options) mac.set_top_block(tb) # give the MAC a handle for the PHY if tb.txpath.bitrate() != tb.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(tb.txpath.bitrate()), eng_notation.num_to_str(tb.rxpath.bitrate())) print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),) print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname,) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,) print print "Be sure to use a different address in the same subnet for each machine." print tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/benchmark_tx.py0000775000175000017500000001257112207702530024350 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser # From gr-digital from gnuradio import digital # from current dir from transmit_path import transmit_path from uhd_interface import uhd_transmitter import time, struct, sys #import os #print os.getpid() #raw_input('Attach and press enter') class my_top_block(gr.top_block): def __init__(self, modulator, options): gr.top_block.__init__(self) if(options.tx_freq is not None): # Work-around to get the modulation's bits_per_symbol args = modulator.extract_kwargs_from_options(options) symbol_rate = options.bitrate / modulator(**args).bits_per_symbol() self.sink = uhd_transmitter(options.args, symbol_rate, options.samples_per_symbol, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) options.samples_per_symbol = self.sink._sps elif(options.to_file is not None): sys.stderr.write(("Saving samples to '%s'.\n\n" % (options.to_file))) self.sink = blocks.file_sink(gr.sizeof_gr_complex, options.to_file) else: sys.stderr.write("No sink defined, dumping samples to null sink.\n\n") self.sink = blocks.null_sink(gr.sizeof_gr_complex) # do this after for any adjustments to the options that may # occur in the sinks (specifically the UHD sink) self.txpath = transmit_path(modulator, options) self.connect(self.txpath, self.sink) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/rx_voice.py0000775000175000017500000001307412207440367023527 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2006,2009,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser from gnuradio import blocks from gnuradio import digital from gnuradio import vocoder import random import struct import sys # from current dir from receive_path import receive_path from uhd_interface import uhd_receiver #import os #print os.getpid() #raw_input('Attach and press enter') class audio_tx(gr.hier_block2): def __init__(self, audio_output_dev): gr.hier_block2.__init__(self, "audio_tx", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.sample_rate = sample_rate = 8000 self.packet_src = blocks.message_source(33) voice_decoder = vocoder.gsm_fr_decode_ps() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) audio_sink = audio.sink(sample_rate, audio_output_dev) self.connect(self.packet_src, voice_decoder, s2f, sink_scale, audio_sink) def msgq(self): return self.packet_src.msgq() class my_top_block(gr.top_block): def __init__(self, demod_class, rx_callback, options): gr.top_block.__init__(self) self.rxpath = receive_path(demod_class, rx_callback, options) self.audio_tx = audio_tx(options.audio_output) if(options.rx_freq is not None): self.source = uhd_receiver(options.args, options.bitrate, options.samples_per_symbol, options.rx_freq, options.rx_gain, options.antenna, options.verbose) options.samples_per_symbol = self.source._sps audio_rate = self.audio_tx.sample_rate usrp_rate = self.source.get_sample_rate() rrate = audio_rate / usrp_rate self.resampler = filter.pfb.arb_resampler_ccf(rrate) self.connect(self.source, self.resampler, self.rxpath) elif(options.from_file is not None): self.thr = blocks.throttle(gr.sizeof_gr_complex, options.bitrate) self.source = blocks.file_source(gr.sizeof_gr_complex, options.from_file) self.connect(self.source, self.thr, self.rxpath) else: self.thr = blocks.throttle(gr.sizeof_gr_complex, 1e6) self.source = blocks.null_source(gr.sizeof_gr_complex) self.connect(self.source, self.thr, self.rxpath) self.connect(self.audio_tx) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// global n_rcvd, n_right def main(): global n_rcvd, n_right n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right n_rcvd += 1 if ok: n_right += 1 tb.audio_tx.msgq().insert_tail(gr.message_from_string(payload)) print "ok = %r n_rcvd = %4d n_right = %4d" % ( ok, n_rcvd, n_right) demods = digital.modulation_utils.type_1_demods() # Create Options Parser: parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=demods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(demods.keys()),)) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("","--from-file", default=None, help="input file of samples to demod") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) for mod in demods.values(): mod.add_options(expert_grp) parser.set_defaults(bitrate=50e3) # override default bitrate default (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(demods[options.modulation], rx_callback, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: Failed to enable realtime scheduling." tb.run() if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/narrowband/digital_bert_rx.py0000775000175000017500000001740312207440367025053 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, eng_notation from optparse import OptionParser from gnuradio.eng_option import eng_option import gnuradio.gr.gr_threading as _threading import sys, time, math from gnuradio import digital from gnuradio import blocks # from current dir from uhd_interface import uhd_receiver n2s = eng_notation.num_to_str class status_thread(_threading.Thread): def __init__(self, tb): _threading.Thread.__init__(self) self.setDaemon(1) self.tb = tb self.done = False self.start() def run(self): while not self.done: print "Freq. Offset: {0:5.0f} Hz Timing Offset: {1:10.1f} ppm Estimated SNR: {2:4.1f} dB BER: {3:g}".format( tb.frequency_offset(), tb.timing_offset()*1e6, tb.snr(), tb.ber()) try: time.sleep(1.0) except KeyboardInterrupt: self.done = True class bert_receiver(gr.hier_block2): def __init__(self, bitrate, constellation, samples_per_symbol, differential, excess_bw, gray_coded, freq_bw, timing_bw, phase_bw, verbose, log): gr.hier_block2.__init__(self, "bert_receive", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(0, 0, 0)) # Output signature self._bitrate = bitrate self._demod = digital.generic_demod(constellation, differential, samples_per_symbol, gray_coded, excess_bw, freq_bw, timing_bw, phase_bw, verbose, log) self._symbol_rate = self._bitrate / self._demod.bits_per_symbol() self._sample_rate = self._symbol_rate * samples_per_symbol # Add an SNR probe on the demodulated constellation self._snr_probe = digital.probe_mpsk_snr_est_c(digital.SNR_EST_M2M4, 1000, alpha=10.0/self._symbol_rate) self.connect(self._demod.time_recov, self._snr_probe) # Descramble BERT sequence. A channel error will create 3 incorrect bits self._descrambler = digital.descrambler_bb(0x8A, 0x7F, 7) # CCSDS 7-bit descrambler # Measure BER by the density of 0s in the stream self._ber = digital.probe_density_b(1.0/self._symbol_rate) self.connect(self, self._demod, self._descrambler, self._ber) def frequency_offset(self): return self._demod.freq_recov.get_frequency()*self._sample_rate/(2*math.pi) def timing_offset(self): return self._demod.time_recov.clock_rate() def snr(self): return self._snr_probe.snr() def ber(self): return (1.0-self._ber.density())/3.0 class rx_psk_block(gr.top_block): def __init__(self, demod, options): gr.top_block.__init__(self, "rx_mpsk") self._demodulator_class = demod # Get demod_kwargs demod_kwargs = self._demodulator_class.extract_kwargs_from_options(options) # demodulator self._demodulator = self._demodulator_class(**demod_kwargs) if(options.rx_freq is not None): symbol_rate = options.bitrate / self._demodulator.bits_per_symbol() self._source = uhd_receiver(options.args, symbol_rate, options.samples_per_symbol, options.rx_freq, options.rx_gain, options.spec, options.antenna, options.verbose) options.samples_per_symbol = self._source._sps elif(options.from_file is not None): self._source = blocks.file_source(gr.sizeof_gr_complex, options.from_file) else: self._source = blocks.null_source(gr.sizeof_gr_complex) # Create the BERT receiver self._receiver = bert_receiver(options.bitrate, self._demodulator._constellation, options.samples_per_symbol, options.differential, options.excess_bw, gray_coded=True, freq_bw=options.freq_bw, timing_bw=options.timing_bw, phase_bw=options.phase_bw, verbose=options.verbose, log=options.log) self.connect(self._source, self._receiver) def snr(self): return self._receiver.snr() def mag(self): return self._receiver.signal_mean() def var(self): return self._receiver.noise_variance() def ber(self): return self._receiver.ber() def frequency_offset(self): return self._receiver.frequency_offset() def timing_offset(self): return self._receiver.timing_offset() def get_options(demods): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("","--from-file", default=None, help="input file of samples to demod") parser.add_option("-m", "--modulation", type="choice", choices=demods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(demods.keys()),)) parser.add_option("-r", "--bitrate", type="eng_float", default=250e3, help="Select modulation bit rate (default=%default)") parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") if not parser.has_option("--verbose"): parser.add_option("-v", "--verbose", action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") uhd_receiver.add_options(parser) demods = digital.modulation_utils.type_1_demods() for mod in demods.values(): mod.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) return (options, args) if __name__ == "__main__": demods = digital.modulation_utils.type_1_demods() (options, args) = get_options(demods) demod = demods[options.modulation] tb = rx_psk_block(demod, options) print "\n*** SNR estimator is inaccurate below about 7dB" print "*** BER estimator is inaccurate above about 10%\n" updater = status_thread(tb) try: tb.run() except KeyboardInterrupt: updater.done = True updater = None gnuradio-3.7.2.1/gr-digital/examples/narrowband/uhd_interface.py0000664000175000017500000002401312207702530024472 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, uhd from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq """ def freq_callback(option, opt_str, value, parser): parser.values.rx_freq = value parser.values.tx_freq = value if not parser.has_option('--freq'): parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") class uhd_interface: def __init__(self, istx, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None): if(istx): self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) else: self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) # Set clock source if(clock_source): self.u.set_clock_source(clock_source, 0) # Set the subdevice spec if(spec): self.u.set_subdev_spec(spec, 0) # Set the antenna if(antenna): self.u.set_antenna(antenna, 0) self._args = args self._ant = antenna self._spec = spec self._gain = self.set_gain(gain) self._lo_offset = lo_offset self._freq = self.set_freq(freq, lo_offset) self._rate, self._sps = self.set_sample_rate(sym_rate, sps) self._clock_source = clock_source def set_sample_rate(self, sym_rate, req_sps): start_sps = req_sps while(True): asked_samp_rate = sym_rate * req_sps self.u.set_samp_rate(asked_samp_rate) actual_samp_rate = self.u.get_samp_rate() sps = actual_samp_rate/sym_rate if(sps < 2): req_sps +=1 else: actual_sps = sps break if(sps != req_sps): print "\nSymbol Rate: %f" % (sym_rate) print "Requested sps: %f" % (start_sps) print "Given sample rate: %f" % (actual_samp_rate) print "Actual sps for rate: %f" % (actual_sps) if(actual_samp_rate != asked_samp_rate): print "\nRequested sample rate: %f" % (asked_samp_rate) print "Actual sample rate: %f" % (actual_samp_rate) return (actual_samp_rate, actual_sps) def get_sample_rate(self): return self.u.get_samp_rate() def set_gain(self, gain=None): if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() gain = float(g.start()+g.stop())/2 print "\nNo gain specified." print "Setting gain to %f (from [%f, %f])" % \ (gain, g.start(), g.stop()) self.u.set_gain(gain, 0) return gain def set_freq(self, freq=None, lo_offset=None): if(freq is None): sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") sys.exit(1) r = self.u.set_center_freq(uhd.tune_request(freq, lo_offset)) if r: return freq else: frange = self.u.get_freq_range() sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ (freq, frange.start(), frange.stop())) sys.exit(1) #-------------------------------------------------------------------# # TRANSMITTER #-------------------------------------------------------------------# class uhd_transmitter(uhd_interface, gr.hier_block2): def __init__(self, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_transmitter", gr.io_signature(1,1,gr.sizeof_gr_complex), gr.io_signature(0,0,0)) # Set up the UHD interface as a transmitter uhd_interface.__init__(self, True, args, sym_rate, sps, freq, lo_offset, gain, spec, antenna, clock_source) self.connect(self, self.u) if(verbose): self._print_verbage() def add_options(parser): add_freq_option(parser) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("", "--lo-offset", type="eng_float", default=0, help="set local oscillator offset in Hz (default is 0)") parser.add_option("", "--tx-gain", type="eng_float", default=None, help="set transmit gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the UHD transmitter """ print "\nUHD Transmitter:" print "Args: %s" % (self._args) print "Freq: %sHz" % (eng_notation.num_to_str(self._freq)) print "LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) print "Gain: %f dB" % (self._gain) print "Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate)) print "Antenna: %s" % (self._ant) print "Subdev Spec: %s" % (self._spec) print "Clock Source: %s" % (self._clock_source) #-------------------------------------------------------------------# # RECEIVER #-------------------------------------------------------------------# class uhd_receiver(uhd_interface, gr.hier_block2): def __init__(self, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_receiver", gr.io_signature(0,0,0), gr.io_signature(1,1,gr.sizeof_gr_complex)) # Set up the UHD interface as a receiver uhd_interface.__init__(self, False, args, sym_rate, sps, freq, lo_offset, gain, spec, antenna, clock_source) self.connect(self.u, self) if(verbose): self._print_verbage() def add_options(parser): add_freq_option(parser) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--rx-freq", type="eng_float", default=None, help="set receive frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("", "--lo-offset", type="eng_float", default=0, help="set local oscillator offset in Hz (default is 0)") parser.add_option("", "--rx-gain", type="eng_float", default=None, help="set receive gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") if not parser.has_option("--verbose"): parser.add_option("-v", "--verbose", action="store_true", default=False) # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the UHD transmitter """ print "\nUHD Receiver:" print "UHD Args: %s" % (self._args) print "Freq: %sHz" % (eng_notation.num_to_str(self._freq)) print "LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) print "Gain: %f dB" % (self._gain) print "Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate)) print "Antenna: %s" % (self._ant) print "Spec: %s" % (self._spec) print "Clock Source: %s" % (self._clock_source) gnuradio-3.7.2.1/gr-digital/examples/narrowband/transmit_path.py0000664000175000017500000001137512207440367024565 0ustar jcorganjcorgan# # Copyright 2005-2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import eng_notation from gnuradio import blocks from gnuradio import digital import copy import sys # ///////////////////////////////////////////////////////////////////////////// # transmit path # ///////////////////////////////////////////////////////////////////////////// class transmit_path(gr.hier_block2): def __init__(self, modulator_class, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "transmit_path", gr.io_signature(0,0,0), gr.io_signature(1,1,gr.sizeof_gr_complex)) options = copy.copy(options) # make a copy so we can destructively modify self._verbose = options.verbose self._tx_amplitude = options.tx_amplitude # digital amplitude sent to USRP self._bitrate = options.bitrate # desired bit rate self._modulator_class = modulator_class # the modulator_class we are using # Get mod_kwargs mod_kwargs = self._modulator_class.extract_kwargs_from_options(options) # transmitter self.modulator = self._modulator_class(**mod_kwargs) self.packet_transmitter = \ digital.mod_pkts(self.modulator, access_code=None, msgq_limit=4, pad_for_usrp=True) self.amp = blocks.multiply_const_cc(1) self.set_tx_amplitude(self._tx_amplitude) # Display some information about the setup if self._verbose: self._print_verbage() # Connect components in the flowgraph self.connect(self.packet_transmitter, self.amp, self) def set_tx_amplitude(self, ampl): """ Sets the transmit amplitude sent to the USRP in volts Args: : ampl 0 <= ampl < 1. """ self._tx_amplitude = max(0.0, min(ampl, 1)) self.amp.set_k(self._tx_amplitude) def send_pkt(self, payload='', eof=False): """ Calls the transmitter method to send a packet """ return self.packet_transmitter.send_pkt(payload, eof) def bitrate(self): return self._bitrate def samples_per_symbol(self): return self.modulator._samples_per_symbol def differential(self): return self.modulator._differential def add_options(normal, expert): """ Adds transmitter-specific options to the Options Parser """ if not normal.has_option('--bitrate'): normal.add_option("-r", "--bitrate", type="eng_float", default=100e3, help="specify bitrate [default=%default].") normal.add_option("", "--tx-amplitude", type="eng_float", default=0.250, metavar="AMPL", help="set transmitter digital amplitude: 0 <= AMPL < 1 [default=%default]") normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to file (CAUTION: lots of data)") # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the transmit path """ print "Tx amplitude %s" % (self._tx_amplitude) print "modulation: %s" % (self._modulator_class.__name__) print "bitrate: %sb/s" % (eng_notation.num_to_str(self._bitrate)) print "samples/symbol: %.4f" % (self.samples_per_symbol()) print "Differential: %s" % (self.differential()) gnuradio-3.7.2.1/gr-digital/examples/narrowband/README0000644000175000017500000001506311700377701022210 0ustar jcorganjcorganQuick overview of what's here: * benchmark_tx.py: generates packets of the size you specify and sends them across the air using the USRP. Known to work well using the USRP with the RFX transceiver daughterboards. You can specify the bitrate to use with the -r command line parameter. The default is 500k. Some machines will do 1M or more. You can select the modulation to use with the -m command line argument. The legal values for are gmsk, dbpsk and dqpsk. * benchmark_rx.py: the receiver half of benchmark_tx.py. Command line arguments are pretty much the same as rx. Works well with a USRP and RFX transceiver daughterboards. Will also work with TVRX daugherboard, but you'll need to fiddle with the gain. See below. Prints a summary of each packet received and keeps a running total of packets received, and how many of them were error free. There are two levels of error reporting going on. If the access code (PN code) and header of a packet were properly detected, then you'll get an output line. If the CRC32 of the payload was correct you get "ok = True", else "ok = False". The "pktno" is extracted from the received packet. If there are skipped numbers, you're missing some packets. Be sure you've got a suitable antenna connected to the TX/RX port on each board. For the RFX-400, "70 cm" / 420 MHz antennas for ham handi-talkies work great. These are available at ham radio supplies, etc. The boards need to be at least 3m apart. You can also try experimenting with the rx gain (-g command line option). Generally speaking, I start the rx first on one machine, and then fire up the tx on the other machine. The tx also supports a discontinous transmission mode where it sends bursts of 5 packets and then waits 1 second. This is useful for ensuring that all the receiver control loops lock up fast enough. * tunnel.py: This program provides a framework for building your own MACs. It creates a "TAP" interface in the kernel, typically gr0, and sends and receives ethernet frames through it. See /usr/src/linux/Documentation/networking/tuntap.txt and/or Google for "universal tun tap". The Linux 2.6 kernel includes the tun module, you don't have to build it. You may have to "modprobe tun" if it's not loaded by default. If /dev/net/tun doesn't exist, try "modprobe tun". To run this program you'll need to be root or running with the appropriate capability to open the tun interface. You'll need to fire up two copies on different machines. Once each is running you'll need to ifconfig the gr0 interface to set the IP address. This will allow two machines to talk, but anything beyond the two machines depends on your networking setup. Left as an exercise... On machine A: $ su # ./tunnel.py --freq 423.0M --bitrate 500k # # in another window on A, also as root... # ifconfig gr0 192.168.200.1 On machine B: $ su # ./tunnel.py --freq 423.0M --bitrate 500k # # in another window on B, also as root... # ifconfig gr0 192.168.200.2 Now, on machine A you shold be able to ping machine B: $ ping 192.168.200.2 and you should see some output for each packet in the tunnel.py window if you used the -v option. Likewise, on machine B: $ ping 192.168.200.1 This now uses a carrier sense MAC, so you should be able to ssh between the machines, web browse, etc. * run_length.py: This program takes a single argument '-f FILE' and outputs the number of runs of similar bits within the file. It is useful as a diagnostic tool when experimenting with line coding or whitening algorithms. ********************************************************************** ********************************************************************** BERT testing example scripts benchmark_tx.py This sets up a BPSK transmitter that is modulated with a pseudorandom sequence of bits. The PN code is generated by sending an all 1s sequence through a 7-bit scrambler. The transmitter performs the BPSK modulation, then passes the complex baseband waveform through a root-raised-cosine filter and onto the USRP. The --sps parameter controls how many baseband samples per symbol are created and passed through the RRC filter, prior to going to the USRP over the USB for interpolation to the final DAC rate. The baseband bit rate is controlled by -r or --rate. This value, when multiplied by the --sps parameter, must result in valid interpolation rate for the USRP. For example, if the baseband rate is 250k bits/sec, and the samples per symbol is 4, then the final rate is 1M samples/sec, which results in an interpolation rate of 128. The valid interpolation rates for the USRP are multiples of 4 between 16 and 512. Finally, the RRC excess bandwidth may be specified by --excess-bw. (See ./benchmark_tx.py -h for additional parameters.) benchmark_rx.py This sets up a BPSK receiver to demodulate the received waveform. It accepts a similar set of parameters as the transmitter, except that one specifies the USRP decimation rate desired. The resulting sample stream rate must be an integral number of baseband symbols. For example, the parameters corresponding to the above transmitter would be to use a decimation rate of 8 (32 sps), 16 (16 sps), 32 (8 sps), 64, (4 sps), or 128 (2 sps). The lower the USRP decimation, the more CPU is required to demodulate the signal, so not all valid decimation rates will work. The baseband signal from the USRP is first passed through an AGC to establish an average power of 1.0. It is then passed through a matched filter (another RRC), a Costas phase-locked loop, and a Mueller and Muller bit timing recovery loop. The resulting constellation has an SNR estimation probe attached, and is then sliced into a bit stream. The recovered bits are then passed through a 7-bit descrambler. If there are no channel errors, the all 1s sequence is recovered. In the event of a channel error, there will be a 0 in the bit stream for each feedback tap in the descrambler. In this case, the CCSDS descrambler is using 3 feedback taps. Finally, the signal is passed into a bit density measurement probe. The channel BER is measured by dividing the 0s density by three. This measurement is inaccurate at high BER rates (>10%) as the error 0s begin to overlap. The benchmark script will, once per second, output the Costas loop frequency offset, the recovered timing error, the estimated SNR, and the average BER. NOTE: The particular SNR estimator used is inaccurate below about 7dB, and will report erroneously high values even for random noise. There are a variety of Costas and M&M loop parameters one can adjust. See ./benchmark_rx.py -h for the full set. gnuradio-3.7.2.1/gr-digital/examples/example_fll.py0000775000175000017500000001312512207440367022041 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, digital, filter from gnuradio import blocks from gnuradio import channels from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser try: import scipy except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) class example_fll(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset): gr.top_block.__init__(self) rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) data = 2.0*scipy.random.randint(0, 2, N) - 1.0 data = scipy.exp(1j*poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) self.chn = channels.channel_model(noise, foffset, toffset) self.fll = digital.fll_band_edge_cc(sps, rolloff, ntaps, bw) self.vsnk_src = blocks.vector_sink_c() self.vsnk_fll = blocks.vector_sink_c() self.vsnk_frq = blocks.vector_sink_f() self.vsnk_phs = blocks.vector_sink_f() self.vsnk_err = blocks.vector_sink_f() self.connect(self.src, self.rrc, self.chn, self.fll, self.vsnk_fll) self.connect(self.rrc, self.vsnk_src) self.connect((self.fll,1), self.vsnk_frq) self.connect((self.fll,2), self.vsnk_phs) self.connect((self.fll,3), self.vsnk_err) def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=2000, help="Set the number of samples to process [default=%default]") parser.add_option("-S", "--sps", type="int", default=4, help="Set the samples per symbol [default=%default]") parser.add_option("-r", "--rolloff", type="eng_float", default=0.35, help="Set the rolloff factor [default=%default]") parser.add_option("-W", "--bandwidth", type="eng_float", default=2*scipy.pi/100.0, help="Set the loop bandwidth [default=%default]") parser.add_option("-n", "--ntaps", type="int", default=45, help="Set the number of taps in the filters [default=%default]") parser.add_option("", "--noise", type="eng_float", default=0.0, help="Set the simulation noise voltage [default=%default]") parser.add_option("-f", "--foffset", type="eng_float", default=0.2, help="Set the simulation's normalized frequency offset (in Hz) [default=%default]") parser.add_option("-t", "--toffset", type="eng_float", default=1.0, help="Set the simulation's timing offset [default=%default]") parser.add_option("-p", "--poffset", type="eng_float", default=0.0, help="Set the simulation's phase offset [default=%default]") (options, args) = parser.parse_args () # Adjust N for the interpolation by sps options.nsamples = options.nsamples // options.sps # Set up the program-under-test put = example_fll(options.nsamples, options.sps, options.rolloff, options.ntaps, options.bandwidth, options.noise, options.foffset, options.toffset, options.poffset) put.run() data_src = scipy.array(put.vsnk_src.data()) data_err = scipy.array(put.vsnk_err.data()) # Convert the FLL's LO frequency from rads/sec to Hz data_frq = scipy.array(put.vsnk_frq.data()) / (2.0*scipy.pi) # adjust this to align with the data. There are 2 filters of # ntaps long and the channel introduces another 4 sample delay. data_fll = scipy.array(put.vsnk_fll.data()[2*options.ntaps-4:]) # Plot the FLL's LO frequency f1 = pylab.figure(1, figsize=(12,10)) s1 = f1.add_subplot(2,2,1) s1.plot(data_frq) s1.set_title("FLL LO") s1.set_xlabel("Samples") s1.set_ylabel("Frequency (normalized Hz)") # Plot the FLL's error s2 = f1.add_subplot(2,2,2) s2.plot(data_err) s2.set_title("FLL Error") s2.set_xlabel("Samples") s2.set_ylabel("FLL Loop error") # Plot the IQ symbols s3 = f1.add_subplot(2,2,3) s3.plot(data_src.real, data_src.imag, "o") s3.plot(data_fll.real, data_fll.imag, "rx") s3.set_title("IQ") s3.set_xlabel("Real part") s3.set_ylabel("Imag part") # Plot the symbols in time s4 = f1.add_subplot(2,2,4) s4.plot(data_src.real, "o-") s4.plot(data_fll.real, "rx-") s4.set_title("Symbols") s4.set_xlabel("Samples") s4.set_ylabel("Real Part of Signals") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/demod/0000755000175000017500000000000012237515112020252 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/examples/demod/pam_sync.grc0000664000175000017500000006730712207440367022605 0ustar jcorganjcorgan Sun Mar 17 21:08:58 2013 options id pam_sync _enabled True title author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (-1, 0) _rotation 0 variable id const _enabled True value digital.qpsk_constellation() _coordinate (336, -2) _rotation 0 virtual_sink id virtual_sink_0 _enabled True stream_id input_signal_probe _coordinate (330, 183) _rotation 0 variable id samp_rate _enabled True value 128000 _coordinate (193, -1) _rotation 0 analog_random_source_x id analog_random_source_x _enabled True type byte min 0 max const.arity() num_samps 10000000 repeat True _coordinate (0, 72) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0_1 _enabled True type complex title Pre-sync Signal samp_rate samp_rate v_scale .5 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,1 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (1081, 439) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title Received spectrum samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook notebook_0,1 freqvar None _coordinate (1081, 563) _rotation 0 variable_slider id phase_bw _enabled True label Costas Loop (Phase) Bandwidth value 0 min 0 max 0.1 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (7,2,1,1) notebook _coordinate (866, 313) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx _enabled True in_type byte out_type complex symbol_table const.points() dimension 1 num_ports 1 _coordinate (178, 87) _rotation 0 variable id spb _enabled True value 4.0 _coordinate (513, -1) _rotation 0 variable id rolloff _enabled True value 0.35 _coordinate (578, -1) _rotation 0 variable id rrctaps _enabled True value firdes.root_raised_cosine(nfilts,1.0,1.0/(nfilts*spb), rolloff, int(11*spb*nfilts)) _coordinate (660, 0) _rotation 0 variable id sig_amp _enabled True value 1.0 _coordinate (887, -1) _rotation 0 variable id nfilts _enabled True value 32 _coordinate (816, 0) _rotation 0 digital_pfb_clock_sync_xxx id digital_pfb_clock_sync_xxx_0 _enabled True type ccf sps spb loop_bw time_bw taps rrctaps filter_size nfilts init_phase 16 max_dev 1.5 osps 1 _coordinate (598, 241) _rotation 0 pfb_arb_resampler_xxx id pfb_arb_resampler_xxx_0 _enabled True type ccf rrate spb taps firdes.root_raised_cosine(nfilts, 1.0, 1.0/nfilts, rolloff, int(11*spb*nfilts)) nfilts 32 atten 100 _coordinate (503, 63) _rotation 0 variable_slider id freq_offset _enabled True label Frequency Offset value 0 min -0.5 max 0.5 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (2,2,1,1) notebook _coordinate (8, 314) _rotation 0 variable_slider id noise_amp _enabled True label Channel Noise value 0 min 0 max 1.0 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (1,2,1,1) notebook _coordinate (136, 314) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise_amp freq_offset freq_offset epsilon interpratio taps 1.0 seed 42 _coordinate (59, 184) _rotation 0 digital_fll_band_edge_cc id digital_fll_band_edge_cc_0 _enabled True type cc samps_per_sym spb rolloff rolloff filter_size 44 w freq_bw _coordinate (331, 238) _rotation 0 variable_slider id freq_bw _enabled True label FLL Bandwidth value 0 min 0.0 max 0.05 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (4,2,1,1) notebook _coordinate (335, 379) _rotation 180 wxgui_fftsink2 id wxgui_fftsink2_0_0 _enabled True type complex title Post-sync spectrum samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook notebook_0,0 freqvar None _coordinate (337, 523) _rotation 180 digital_costas_loop_cc id digital_costas_loop_cc_0 _enabled True w phase_bw order const.arity() _coordinate (871, 225) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title Post-sync Signal samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode True num_inputs 1 win_size grid_pos notebook notebook_0,0 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (1103, 196) _rotation 0 virtual_source id virtual_source_0 _enabled True stream_id input_signal_probe _coordinate (828, 562) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const sig_amp vlen 1 _coordinate (807, 95) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (987, 95) _rotation 0 variable_slider id time_bw _enabled True label Timing Loop BW value 0 min 0 max 0.1 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (5,2,1,1) notebook _coordinate (598, 388) _rotation 0 variable_slider id interpratio _enabled True label Timing Offset value 1.00 min 0.99 max 1.01 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (3,2,1,1) notebook _coordinate (42, 459) _rotation 180 notebook id notebook_0 _enabled True style wx.NB_TOP labels ['Synched Signal', 'Received Signal'] grid_pos (1,1,8,1) notebook _coordinate (9, 601) _rotation 0 channels_channel_model_0 virtual_sink_0 0 0 digital_fll_band_edge_cc_0 digital_pfb_clock_sync_xxx_0 0 0 digital_pfb_clock_sync_xxx_0 digital_costas_loop_cc_0 0 0 digital_costas_loop_cc_0 wxgui_scopesink2_0 0 0 pfb_arb_resampler_xxx_0 blocks_multiply_const_vxx_0 0 0 channels_channel_model_0 digital_fll_band_edge_cc_0 0 0 digital_fll_band_edge_cc_0 wxgui_fftsink2_0_0 0 0 virtual_source_0 wxgui_fftsink2_0 0 0 virtual_source_0 wxgui_scopesink2_0_0_1 0 0 analog_random_source_x digital_chunks_to_symbols_xx 0 0 blocks_throttle_0 channels_channel_model_0 0 0 blocks_multiply_const_vxx_0 blocks_throttle_0 0 0 digital_chunks_to_symbols_xx pfb_arb_resampler_xxx_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/mpsk_demod.grc0000664000175000017500000002642112207440367023106 0ustar jcorganjcorgan Sun Mar 17 21:08:14 2013 options id mpsk_demod _enabled True title MPSK Demod Demo author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (10, 170) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 2**8 num_samps 10000 repeat True _coordinate (161, 119) _rotation 0 variable id samps_per_sym _enabled True value 4 _coordinate (12, 99) _rotation 0 variable_qtgui_range id freq_off _enabled True label Freq. Offset value 0 start -0.5 stop 0.5 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (17, 260) _rotation 0 variable_qtgui_range id noise _enabled True label Noise value 0.1 start 0 stop 1 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (146, 262) _rotation 0 qtgui_tab_widget id notebook _enabled True num_tabs 2 label0 Constellation label1 Spectrum label2 Tab 2 label3 Tab 3 label4 Tab 4 gui_hint _coordinate (21, 394) _rotation 0 qtgui_const_sink_x id qtgui_const_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 1 update_time 0.10 gui_hint notebook@0 _coordinate (810, 184) _rotation 0 qtgui_freq_sink_x id qtgui_freq_sink_x_0 _enabled True type complex name QT GUI Plot fftsize 1024 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate ymin -140 ymax 10 nconnections 1 update_time 0.10 gui_hint notebook@1 _coordinate (810, 65) _rotation 0 digital_dxpsk_mod id digital_dxpsk_mod_0 _enabled True type dqpsk samples_per_symbol samps_per_sym excess_bw 0.35 mod_code "gray" verbose False log False _coordinate (361, 119) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (597, 142) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise freq_offset freq_off epsilon 1.0 taps 1.0 + 1.0j seed 0 _coordinate (494, 263) _rotation 0 analog_random_source_x_0 digital_dxpsk_mod_0 0 0 blocks_throttle_0 qtgui_freq_sink_x_0 0 0 blocks_throttle_0 qtgui_const_sink_x_0 0 0 digital_dxpsk_mod_0 channels_channel_model_0 0 0 channels_channel_model_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/gmsk_loopback.grc0000664000175000017500000002765012207440367023604 0ustar jcorganjcorgan Tue Nov 6 20:49:18 2012 options id gfsk_loopback _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id fm_sensitivity _enabled True value 1.0 _coordinate (14, 273) _rotation 0 variable id sps _enabled True value 4 _coordinate (15, 338) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (12, 76) _rotation 0 variable_qtgui_range id freq _enabled True label value 500 start 0 stop 500 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (13, 152) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_1 _enabled True type float name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 gui_hint _coordinate (906, 122) _rotation 0 blks2_packet_encoder id blks2_packet_encoder_0 _enabled True type float samples_per_symbol sps bits_per_symbol 1 access_code pad_for_usrp True payload_length 0 _coordinate (237, 261) _rotation 0 blks2_packet_decoder id blks2_packet_decoder_0 _enabled True type float access_code threshold -1 _coordinate (720, 130) _rotation 0 digital_gmsk_demod id digital_gmsk_demod_0 _enabled True samples_per_symbol 2 gain_mu 0.175 mu 0.5 omega_relative_limit 0.005 freq_error 0.0 verbose False log False _coordinate (666, 261) _rotation 0 blocks_throttle id blocks_throttle_0_0 _enabled True type float samples_per_second samp_rate vlen 1 _coordinate (413, 50) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq freq amp 1 offset 0 _coordinate (210, 18) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_1_0 _enabled True type float name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 gui_hint _coordinate (888, 386) _rotation 0 digital_gmsk_mod id digital_gmsk_mod_0 _enabled True samples_per_symbol 2 bt 0.35 verbose False log False _coordinate (446, 285) _rotation 0 analog_quadrature_demod_cf id analog_quadrature_demod_cf_0 _enabled True gain 1 _coordinate (675, 402) _rotation 0 blocks_throttle_0_0 blks2_packet_encoder_0 0 0 blks2_packet_decoder_0 qtgui_time_sink_x_1 0 0 blks2_packet_encoder_0 digital_gmsk_mod_0 0 0 digital_gmsk_mod_0 digital_gmsk_demod_0 0 0 digital_gmsk_demod_0 blks2_packet_decoder_0 0 0 analog_sig_source_x_0 blocks_throttle_0_0 0 0 analog_quadrature_demod_cf_0 qtgui_time_sink_x_1_0 0 0 digital_gmsk_mod_0 analog_quadrature_demod_cf_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/test_corr_and_sync.grc0000664000175000017500000012240212237515112024634 0ustar jcorganjcorgan Thu Nov 7 11:05:37 2013 options id test_corr_and_sync _enabled True title author description window_size 2000,2000 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id rrc_taps _enabled True value firdes.root_raised_cosine(nfilts, nfilts, 1.0/float(sps), eb, 5*sps*nfilts) _coordinate (1075, 73) _rotation 0 variable id nfilts _enabled True value 32 _coordinate (1074, 9) _rotation 0 variable id payload_size _enabled True value 992 _coordinate (101, 73) _rotation 0 variable id gap _enabled True value 20000 _coordinate (202, 72) _rotation 0 variable id bb_filter _enabled True value firdes.root_raised_cosine(sps, sps, 1, eb, 101) _coordinate (429, 8) _rotation 0 variable id sps _enabled True value 4 _coordinate (278, 72) _rotation 0 variable id preamble _enabled True value [1,-1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,-1,-1,1,-1,1,1,1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,1,1,1,1,1,1,-1,-1] _coordinate (279, 8) _rotation 0 variable id matched_filter _enabled True value firdes.root_raised_cosine(nfilts, nfilts, 1, eb, int(11*sps*nfilts)) _coordinate (429, 72) _rotation 0 variable id eb _enabled True value 0.35 _coordinate (346, 72) _rotation 0 variable id samp_rate _enabled True value 100000 _coordinate (11, 72) _rotation 0 digital_costas_loop_cc id digital_costas_loop_cc_0 _enabled True w 1*3.14/50.0 order 2 affinity minoutbuf 0 _coordinate (1091, 303) _rotation 0 blocks_complex_to_float id blocks_complex_to_float_0 _enabled True vlen 1 affinity minoutbuf 0 _coordinate (1235, 194) _rotation 0 blocks_complex_to_mag id blocks_complex_to_mag_0 _enabled True vlen 1 affinity minoutbuf 0 _coordinate (1235, 149) _rotation 0 digital_correlate_and_sync_cc id digital_correlate_and_sync_cc_0 _enabled True symbols preamble filter matched_filter sps sps affinity minoutbuf 0 _coordinate (972, 174) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise freq_offset freq_offset epsilon time_offset taps 1.0 seed 0 affinity minoutbuf 0 _coordinate (772, 158) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (586, 190) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0_0 _enabled True type byte vector map(lambda x: (-x+1)/2, preamble) tags [] repeat True vlen 1 affinity minoutbuf 0 _coordinate (15, 165) _rotation 0 digital_constellation_modulator id digital_constellation_modulator_0 _enabled True constellation constel differential False samples_per_symbol sps excess_bw eb verbose False log False affinity minoutbuf 0 _coordinate (312, 166) _rotation 0 blocks_stream_mux id blocks_stream_mux_0_0 _enabled True type complex lengths (len(preamble)+8*payload_size)*sps, gap num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (568, 288) _rotation 0 blocks_null_source id blocks_null_source_0_0 _enabled True type complex vlen 1 affinity minoutbuf 0 _coordinate (402, 322) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_1 _enabled True type float name QT GUI Plot size 80000 srate samp_rate ymin -200 ymax 400 nconnections 3 update_time 0.10 tr_mode qtgui.TRIG_MODE_NORM tr_slope qtgui.TRIG_SLOPE_POS tr_level 200 tr_delay 0 tr_chan 0 tr_tag "" entags True gui_hint 1,0,1,2 affinity _coordinate (1433, 160) _rotation 0 import id import_0 _enabled True import import scipy _coordinate (181, 16) _rotation 0 qtgui_const_sink_x id qtgui_const_sink_x_0_0 _enabled True type complex name QT GUI Plot size 20000 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 1 update_time 0.10 gui_hint 0,1,1,1 affinity _coordinate (1399, 291) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0 _enabled True type complex name QT GUI Plot size 50000 srate samp_rate ymin -2 ymax 2 nconnections 1 update_time 0.10 tr_mode qtgui.TRIG_MODE_TAG tr_slope qtgui.TRIG_SLOPE_POS tr_level 1 tr_delay 0.1 tr_chan 0 tr_tag time_est entags True gui_hint 0,0,1,1 affinity 0 _coordinate (1397, 358) _rotation 0 variable_qtgui_range id phase _enabled True label Phase offset value 0 start -2*scipy.pi stop 2*scipy.pi step 0.1 widget slider orient Qt.Horizontal min_len 200 gui_hint 3,1,1,1 _coordinate (692, 7) _rotation 0 variable_qtgui_range id freq_offset _enabled True label Frequency Offset value 0 start -0.001 stop 0.001 step 0.00002 widget slider orient Qt.Horizontal min_len 200 gui_hint 4,0,1,1 _coordinate (808, 7) _rotation 0 variable_qtgui_range id time_offset _enabled True label Timing Offset value 1 start 0.995 stop 1.005 step 0.00001 widget slider orient Qt.Horizontal min_len 200 gui_hint 4,1,1,1 _coordinate (950, 8) _rotation 0 variable_qtgui_range id noise _enabled True label Noise value 0 start 0 stop 1 step 0.005 widget slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,1 _coordinate (584, 7) _rotation 0 digital_pfb_clock_sync_xxx id digital_pfb_clock_sync_xxx_0 _enabled True type ccf sps sps loop_bw 2*3.14/100.0 taps rrc_taps filter_size nfilts init_phase 0 max_dev 0.5 osps 1 affinity minoutbuf 0 _coordinate (790, 289) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 256 num_samps 100000 repeat True affinity minoutbuf 0 _coordinate (30, 324) _rotation 0 blocks_pack_k_bits_bb id blocks_pack_k_bits_bb_0 _enabled True k 8 affinity minoutbuf 0 _coordinate (55, 274) _rotation 0 blocks_stream_mux id blocks_stream_mux_0_0_0 _enabled True type byte lengths len(preamble)/8,payload_size num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (247, 318) _rotation 0 variable_constellation id constel _enabled True value "ok" sym_map [0,1] const_points [1,- 1] rot_sym 2 dims 1 precision 8 soft_dec_lut None _coordinate (1237, 27) _rotation 0 blocks_sub_xx id blocks_sub_xx_0 _enabled False type float vlen 1 num_inputs 2 affinity minoutbuf 0 _coordinate (1125, 617) _rotation 0 variable_qtgui_range id delay _enabled False label delay value 90 start 0 stop 200 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 5,0,1,2 _coordinate (875, 571) _rotation 0 blocks_char_to_float id blocks_char_to_float_0 _enabled False vlen 1 scale 1 affinity minoutbuf 0 _coordinate (752, 517) _rotation 0 blocks_unpack_k_bits_bb id blocks_unpack_k_bits_bb_0 _enabled False k 8 affinity minoutbuf 0 _coordinate (576, 517) _rotation 0 blocks_stream_mux id blocks_stream_mux_0 _enabled False type byte lengths (len(preamble)/8+payload_size), gap/sps/8 num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (390, 504) _rotation 0 blocks_null_source id blocks_null_source_0 _enabled False type byte vlen 1 affinity minoutbuf 0 _coordinate (210, 538) _rotation 0 blocks_delay id blocks_delay_0 _enabled False type float delay int(delay) num_ports 1 vlen 1 affinity minoutbuf 0 _coordinate (923, 518) _rotation 0 blocks_char_to_float id blocks_char_to_float_0_0 _enabled False vlen 1 scale 1 affinity minoutbuf 0 _coordinate (1112, 482) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_1 _enabled False type float name QT GUI Plot size 20000 srate samp_rate ymin -2 ymax 2 nconnections 3 update_time 0.10 tr_mode qtgui.TRIG_MODE_TAG tr_slope qtgui.TRIG_SLOPE_POS tr_level 0.0 tr_delay 0.010 tr_chan 0 tr_tag time_est entags True gui_hint 2,0,1,2 affinity _coordinate (1345, 531) _rotation 0 digital_constellation_decoder_cb id digital_constellation_decoder_cb_0 _enabled False constellation constel affinity minoutbuf 0 _coordinate (1111, 433) _rotation 180 digital_costas_loop_cc_0 qtgui_const_sink_x_0_0 0 0 digital_costas_loop_cc_0 qtgui_time_sink_x_0 0 0 digital_costas_loop_cc_0 digital_constellation_decoder_cb_0 0 0 blocks_complex_to_float_0 qtgui_time_sink_x_1 0 1 blocks_complex_to_mag_0 qtgui_time_sink_x_1 0 0 digital_correlate_and_sync_cc_0 digital_pfb_clock_sync_xxx_0 0 0 blocks_null_source_0_0 blocks_stream_mux_0_0 0 1 blocks_vector_source_x_0_0 blocks_pack_k_bits_bb_0 0 0 blocks_stream_mux_0_0 blocks_throttle_0 0 0 blocks_complex_to_float_0 qtgui_time_sink_x_1 1 2 channels_channel_model_0 digital_correlate_and_sync_cc_0 0 0 blocks_stream_mux_0_0_0 digital_constellation_modulator_0 0 0 digital_constellation_modulator_0 blocks_stream_mux_0_0 0 0 digital_correlate_and_sync_cc_0 blocks_complex_to_mag_0 1 0 digital_correlate_and_sync_cc_0 blocks_complex_to_float_0 1 0 blocks_throttle_0 channels_channel_model_0 0 0 digital_pfb_clock_sync_xxx_0 digital_costas_loop_cc_0 0 0 blocks_pack_k_bits_bb_0 blocks_stream_mux_0_0_0 0 0 analog_random_source_x_0 blocks_stream_mux_0_0_0 0 1 blocks_stream_mux_0_0_0 blocks_stream_mux_0 0 0 blocks_delay_0 qtgui_time_sink_x_0_1 0 1 blocks_char_to_float_0_0 blocks_sub_xx_0 0 0 blocks_delay_0 blocks_sub_xx_0 0 1 blocks_sub_xx_0 qtgui_time_sink_x_0_1 0 2 blocks_char_to_float_0_0 qtgui_time_sink_x_0_1 0 0 blocks_stream_mux_0 blocks_unpack_k_bits_bb_0 0 0 blocks_unpack_k_bits_bb_0 blocks_char_to_float_0 0 0 blocks_null_source_0 blocks_stream_mux_0 0 1 blocks_char_to_float_0 blocks_delay_0 0 0 digital_constellation_decoder_cb_0 blocks_char_to_float_0_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/dpsk_loopback.grc0000664000175000017500000002441712207440367023602 0ustar jcorganjcorgan Sat Nov 10 15:13:23 2012 options id dpsk_loopback _enabled True title DPSK Loopback author GNU Radio description Encode a signal into a packet, modulate, demodulate, decode and show it's the same data. window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 10000 _coordinate (11, 120) _rotation 0 variable_slider id freq _enabled True label Frequency (Hz) value 500 min 0 max samp_rate/2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (13, 188) _rotation 0 blocks_throttle id blocks_throttle_0_0 _enabled True type float samples_per_second samp_rate vlen 1 _coordinate (381, 51) _rotation 0 blks2_packet_encoder id blks2_packet_encoder_0 _enabled True type float samples_per_symbol 2 bits_per_symbol 1 access_code pad_for_usrp True payload_length 0 _coordinate (598, 19) _rotation 0 digital_dxpsk_mod id digital_dxpsk_mod_1 _enabled True type dbpsk samples_per_symbol 2 excess_bw 0.35 mod_code "gray" verbose False log False _coordinate (806, 27) _rotation 0 digital_dxpsk_demod id digital_dxpsk_demod_1 _enabled True type dbpsk samples_per_symbol 2 excess_bw 0.35 freq_bw 6.28/100.0 phase_bw 6.28/100.0 timing_bw 6.28/100.0 mod_code "gray" verbose False log False sync_out False _coordinate (745, 139) _rotation 180 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type float title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale 1./freq ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (184, 163) _rotation 180 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq freq amp 1 offset 0 _coordinate (190, 19) _rotation 0 blks2_packet_decoder id blks2_packet_decoder_0 _enabled True type float access_code threshold -1 _coordinate (545, 187) _rotation 180 blks2_packet_decoder_0 wxgui_scopesink2_0 0 0 blks2_packet_encoder_0 digital_dxpsk_mod_1 0 0 digital_dxpsk_mod_1 digital_dxpsk_demod_1 0 0 digital_dxpsk_demod_1 blks2_packet_decoder_0 0 0 blocks_throttle_0_0 blks2_packet_encoder_0 0 0 analog_sig_source_x_0 blocks_throttle_0_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/pam_timing.grc0000664000175000017500000005762512207440367023122 0ustar jcorganjcorgan Tue Jan 15 15:21:46 2013 options id pam_timing _enabled True title author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (-1, 0) _rotation 0 analog_random_source_x id analog_random_source_x _enabled True type byte min 0 max const.arity() num_samps 10000000 repeat True _coordinate (-1, 163) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx _enabled True in_type byte out_type complex symbol_table const.points() dimension 1 num_ports 1 _coordinate (203, 178) _rotation 0 variable id const _enabled True value digital.qpsk_constellation() _coordinate (206, 116) _rotation 0 import id import_0 _enabled True import from gnuradio import digital _coordinate (-1, 61) _rotation 0 variable id spb _enabled True value 4.2563 _coordinate (300, 0) _rotation 0 variable id sig_amp _enabled True value 1 _coordinate (791, 46) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (258, 431) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise_amp freq_offset freq_offset epsilon interpratio taps 1.0 seed 42 _coordinate (57, 401) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (267, 357) _rotation 0 variable id rolloff _enabled True value .35 _coordinate (482, 335) _rotation 0 variable id nfilts _enabled True value 32 _coordinate (562, 335) _rotation 0 digital_pfb_clock_sync_xxx id digital_pfb_clock_sync_xxx_0 _enabled True type ccf sps spb loop_bw time_bw taps firdes.root_raised_cosine(nfilts, nfilts*spb, 1.0, rolloff, 44*nfilts) filter_size nfilts init_phase 16 max_dev 1.5 osps 1 _coordinate (467, 403) _rotation 0 pfb_arb_resampler_xxx id pfb_arb_resampler_xxx_0 _enabled True type ccf rrate spb taps firdes.root_raised_cosine(nfilts, nfilts, 1.0, rolloff, 44*nfilts) nfilts 32 atten 100 _coordinate (458, 179) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0_1 _enabled True type complex title Error samp_rate samp_rate v_scale .5 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,3 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (961, 84) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0_0 _enabled True type float title Scope Plot samp_rate samp_rate v_scale 9 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,1 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (991, 592) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (1029, 243) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0 _enabled True type float title Error samp_rate samp_rate v_scale 3 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,0 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (1029, 335) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0_0_0 _enabled True type float title Scope Plot samp_rate samp_rate v_scale 1.25 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,2 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (1024, 462) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const sig_amp vlen 1 _coordinate (760, 159) _rotation 0 variable_slider id interpratio _enabled True label Timing Offset value 1.00 min 0.99 max 1.01 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (2,2,1,1) notebook _coordinate (4, 530) _rotation 180 variable_slider id time_bw _enabled True label Timing Loop BW value 0 min 0 max 0.1 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (1,2,1,1) notebook _coordinate (552, 4) _rotation 0 variable_slider id noise_amp _enabled True label Channel Noise value 0 min 0 max 1.0 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (3,2,1,1) notebook _coordinate (149, 530) _rotation 0 variable_slider id freq_offset _enabled True label Frequency Offset value 0 min -0.5 max 0.5 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos (4,2,1,1) notebook _coordinate (293, 530) _rotation 0 notebook id notebook_0 _enabled True style wx.NB_TOP labels ['error', 'phase', 'freq', 'Resampled Signal'] grid_pos (1,1,5,1) notebook _coordinate (443, 577) _rotation 0 blocks_throttle_0 digital_pfb_clock_sync_xxx_0 0 0 digital_pfb_clock_sync_xxx_0 wxgui_scopesink2_0_0_0_0 2 0 blocks_multiply_const_vxx_0 wxgui_scopesink2_0_0_1 0 0 pfb_arb_resampler_xxx_0 blocks_multiply_const_vxx_0 0 0 digital_chunks_to_symbols_xx pfb_arb_resampler_xxx_0 0 0 analog_random_source_x digital_chunks_to_symbols_xx 0 0 digital_pfb_clock_sync_xxx_0 wxgui_scopesink2_0_0_0 3 0 digital_pfb_clock_sync_xxx_0 wxgui_scopesink2_0_0 1 0 digital_pfb_clock_sync_xxx_0 wxgui_scopesink2_0 0 0 channels_channel_model_0 blocks_throttle_0 0 0 blocks_multiply_const_vxx_0 channels_channel_model_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/ber_simulation.grc0000664000175000017500000003506012207440367023777 0ustar jcorganjcorgan Mon Jan 14 11:20:53 2013 options id ber_simulation _enabled True title BER Simulation author Example description Adjust the noise and constellation... see what happens! window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (16, 10) _rotation 0 blocks_throttle id blocks_throttle _enabled True type byte samples_per_second samp_rate vlen 1 _coordinate (284, 24) _rotation 0 blocks_add_xx id blocks_add_xx _enabled True type complex num_inputs 2 vlen 1 _coordinate (486, 151) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2 _enabled True type float title BER units % samp_rate samp_rate min_value 0.0 max_value 1.0 factor 100 decimal_places 4 ref_level 0 number_rate 15 peak_hold False average False avg_alpha 0 show_gauge False win_size grid_pos 1, 0, 1, 1 notebook _coordinate (791, 228) _rotation 180 import id import _enabled True import import math _coordinate (18, 373) _rotation 0 variable_slider id EbN0 _enabled True label Eb/N0 (dB) value 10 min -10 max 200 num_steps 211 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (311, 309) _rotation 0 variable id const _enabled True value (digital.constellation_bpsk(), digital.constellation_qpsk(), digital.constellation_8psk()) _coordinate (116, 310) _rotation 0 analog_random_source_x id analog_random_source_x _enabled True type byte min 0 max const[const_type].arity() num_samps 10000000 repeat True _coordinate (17, 125) _rotation 0 analog_noise_source_x id analog_noise_source_x _enabled True type complex noise_type analog.GR_GAUSSIAN amp 1.0 / math.sqrt(2.0 * const[const_type].bits_per_symbol() * 10**(EbN0/10)) seed 42 _coordinate (16, 224) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx _enabled True in_type byte out_type complex symbol_table const[const_type].points() dimension 1 num_ports 1 _coordinate (240, 140) _rotation 0 blks2_error_rate id blks2_error_rate _enabled True type 'BER' win_size int(1e7) bits_per_symbol const[const_type].bits_per_symbol() _coordinate (720, 25) _rotation 0 digital_constellation_decoder_cb id digital_constellation_decoder_cb_0 _enabled True constellation const[const_type].base() _coordinate (618, 164) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title "Constellation: "+str(const[const_type].arity()) + "-PSK" samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode True num_inputs 1 win_size grid_pos 2, 0, 1, 1 notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (623, 228) _rotation 0 variable id samp_rate _enabled True value 100e3 _coordinate (16, 308) _rotation 0 variable id const_type _enabled True value 1 _coordinate (18, 428) _rotation 0 variable_static_text id variable_static_text_0 _enabled True label Constellation Type value {0: 'BPSK', 1: 'QPSK', 2: '8-PSK'}[const_type] + " - Change const_type for different constellation types!" converver str_converter formatter None grid_pos notebook _coordinate (422, 311) _rotation 0 blks2_error_rate wxgui_numbersink2 0 0 blocks_throttle blks2_error_rate 0 0 digital_chunks_to_symbols_xx blocks_add_xx 0 0 analog_noise_source_x blocks_add_xx 0 1 analog_random_source_x blocks_throttle 0 0 analog_random_source_x digital_chunks_to_symbols_xx 0 0 blocks_add_xx wxgui_scopesink2_0 0 0 digital_constellation_decoder_cb_0 blks2_error_rate 0 1 blocks_add_xx digital_constellation_decoder_cb_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/uhd_corr_and_sync_tx.grc0000664000175000017500000007601112237515112025154 0ustar jcorganjcorgan Thu Nov 7 12:23:18 2013 blocks_vector_source_x id blocks_vector_source_x_0_0 _enabled True type byte vector map(lambda x: (-x+1)/2, preamble) tags [] repeat True vlen 1 affinity minoutbuf 0 _coordinate (15, 165) _rotation 0 variable id samp_rate _enabled True value 250000 _coordinate (11, 75) _rotation 0 variable id gap _enabled True value 20000 _coordinate (104, 74) _rotation 0 variable id sps _enabled True value 4 _coordinate (181, 75) _rotation 0 variable id eb _enabled True value 0.35 _coordinate (249, 75) _rotation 0 variable id addr _enabled True value "addr=192.168.10.2" _coordinate (335, 76) _rotation 0 variable id preamble _enabled True value [1,-1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,-1,-1,1,-1,1,1,1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,1,1,1,1,1,1,-1,-1] _coordinate (279, 8) _rotation 0 variable id payload_size _enabled True value 992 _coordinate (175, 9) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 256 num_samps 100000 repeat True affinity minoutbuf 0 _coordinate (30, 324) _rotation 0 blocks_pack_k_bits_bb id blocks_pack_k_bits_bb_0 _enabled True k 8 affinity minoutbuf 0 _coordinate (55, 274) _rotation 0 blocks_stream_mux id blocks_stream_mux_0_0_0 _enabled True type byte lengths len(preamble)/8,payload_size num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (252, 278) _rotation 0 digital_constellation_modulator id digital_constellation_modulator_0 _enabled True constellation constel differential False samples_per_symbol sps excess_bw eb verbose False log False affinity minoutbuf 0 _coordinate (289, 155) _rotation 0 blocks_null_source id blocks_null_source_0_0 _enabled True type complex vlen 1 affinity minoutbuf 0 _coordinate (260, 362) _rotation 0 blocks_stream_mux id blocks_stream_mux_0_0 _enabled True type complex lengths (len(preamble)+8*payload_size)*sps, gap num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (539, 281) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const digital_gain vlen 1 affinity minoutbuf 0 _coordinate (727, 294) _rotation 0 uhd_usrp_sink id uhd_usrp_sink_0 _enabled True type fc32 otw stream_args stream_chans [] dev_addr addr sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 freq+fine_freq gain0 gain ant0 TX/RX bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 affinity _coordinate (911, 262) _rotation 0 qtgui_freq_sink_x id qtgui_freq_sink_x_0 _enabled True type complex name QT GUI Plot fftsize 1024 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate ymin -120 ymax 20 nconnections 1 update_time 0.10 gui_hint 0,0,1,2 affinity _coordinate (912, 375) _rotation 0 variable_constellation id constel _enabled True value "ok" sym_map [0,1] const_points [1,- 1] rot_sym 2 dims 1 precision 8 soft_dec_lut None _coordinate (485, 30) _rotation 0 variable_qtgui_range id gain _enabled True label Tx Gain value 12.5 start 0 stop 31.5 step 0.5 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,0,1,1 _coordinate (651, 15) _rotation 0 variable_qtgui_range id digital_gain _enabled True label Digital Gain value 45 start 0 stop 200 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (778, 16) _rotation 0 variable_qtgui_range id freq _enabled True label Tx Frequency value 450e6 start 400e6 stop 500e6 step 100e3 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,1 _coordinate (899, 16) _rotation 0 variable_qtgui_range id fine_freq _enabled True label Fine Frequency value 0 start -10e3 stop 10e3 step 10 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,1,1,1 _coordinate (1031, 17) _rotation 0 options id test_corr_and_sync_tx _enabled True title author description window_size 2000,2000 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 blocks_vector_source_x_0_0 blocks_pack_k_bits_bb_0 0 0 blocks_stream_mux_0_0_0 digital_constellation_modulator_0 0 0 digital_constellation_modulator_0 blocks_stream_mux_0_0 0 0 blocks_pack_k_bits_bb_0 blocks_stream_mux_0_0_0 0 0 analog_random_source_x_0 blocks_stream_mux_0_0_0 0 1 blocks_null_source_0_0 blocks_stream_mux_0_0 0 1 blocks_stream_mux_0_0 blocks_multiply_const_vxx_0 0 0 blocks_multiply_const_vxx_0 uhd_usrp_sink_0 0 0 blocks_multiply_const_vxx_0 qtgui_freq_sink_x_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/digital_freq_lock.grc0000664000175000017500000004377312207440367024437 0ustar jcorganjcorgan Tue Jan 15 14:17:18 2013 options id digital_freq_lock _enabled True title author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (-1, 0) _rotation 0 variable id sps _enabled True value 4 _coordinate (166, -2) _rotation 0 variable id rolloff _enabled True value 0.35 _coordinate (231, 0) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (439, -1) _rotation 0 variable_slider id freq_offset _enabled True label Frequency Offset value 0 min -0.5 max 0.5 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (673, -1) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0 _enabled True type complex title Frequency Corrected Signal samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,1 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (439, 289) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0_0 _enabled True type complex title Frequency Corrected Signal samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook notebook_0,0 freqvar None _coordinate (439, 423) _rotation 0 variable_slider id freq_bw _enabled True label FLL Loop Bandwidth value 0 min 0 max 0.1 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (74, 436) _rotation 0 notebook id notebook_0 _enabled True style wx.NB_TOP labels ['Freq', 'Time'] grid_pos notebook _coordinate (108, 568) _rotation 0 digital_fll_band_edge_cc id digital_fll_band_edge_cc_0 _enabled True type cc samps_per_sym sps rolloff rolloff filter_size 44 w freq_bw _coordinate (75, 295) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title Signal into Receiver samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook notebook_0,0 freqvar None _coordinate (918, 107) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title Signal into Receiver samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook notebook_0,1 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (918, 0) _rotation 0 digital_psk_mod id digital_psk_mod_0 _enabled True constellation_points 2 mod_code "gray" differential False samples_per_symbol sps excess_bw rolloff verbose False log False _coordinate (202, 142) _rotation 0 analog_random_source_x id analog_random_source_x _enabled True type byte min 0 max 256 num_samps 10000000 repeat True _coordinate (8, 150) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise_amp freq_offset freq_offset epsilon 1.0 taps 1.0 seed 42 _coordinate (681, 142) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (487, 174) _rotation 0 variable_slider id noise_amp _enabled True label Channel Noise value 0 min 0 max 1.0 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (549, 0) _rotation 0 channels_channel_model_0 wxgui_scopesink2_0 0 0 channels_channel_model_0 wxgui_fftsink2_0 0 0 analog_random_source_x digital_psk_mod_0 0 0 digital_psk_mod_0 blocks_throttle_0 0 0 blocks_throttle_0 channels_channel_model_0 0 0 channels_channel_model_0 digital_fll_band_edge_cc_0 0 0 digital_fll_band_edge_cc_0 wxgui_scopesink2_0_0 0 0 digital_fll_band_edge_cc_0 wxgui_fftsink2_0_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/gfsk_loopback.grc0000664000175000017500000003014012207440367023561 0ustar jcorganjcorgan Tue Nov 6 20:52:00 2012 options id gfsk_loopback _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id fm_sensitivity _enabled True value 1.0 _coordinate (14, 273) _rotation 0 variable id sps _enabled True value 4 _coordinate (15, 338) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (12, 76) _rotation 0 variable_qtgui_range id freq _enabled True label value 500 start 0 stop 500 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (13, 152) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_1 _enabled True type float name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 gui_hint _coordinate (906, 122) _rotation 0 blks2_packet_encoder id blks2_packet_encoder_0 _enabled True type float samples_per_symbol sps bits_per_symbol 1 access_code pad_for_usrp True payload_length 0 _coordinate (237, 261) _rotation 0 blks2_packet_decoder id blks2_packet_decoder_0 _enabled True type float access_code threshold -1 _coordinate (720, 130) _rotation 0 blocks_throttle id blocks_throttle_0_0 _enabled True type float samples_per_second samp_rate vlen 1 _coordinate (413, 50) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq freq amp 1 offset 0 _coordinate (214, 18) _rotation 0 digital_gfsk_demod id digital_gfsk_demod_0 _enabled True samples_per_symbol sps sensitivity fm_sensitivity gain_mu 0.175 mu 0.5 omega_relative_limit 0.005 freq_error 0.0 verbose False log False _coordinate (670, 253) _rotation 0 digital_gfsk_mod id digital_gfsk_mod_0 _enabled True samples_per_symbol sps sensitivity fm_sensitivity bt 0.35 verbose False log False _coordinate (456, 277) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_1_0 _enabled True type float name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 gui_hint _coordinate (888, 386) _rotation 0 analog_quadrature_demod_cf id analog_quadrature_demod_cf_0 _enabled True gain 1 _coordinate (673, 403) _rotation 0 blks2_packet_encoder_0 digital_gfsk_mod_0 0 0 blocks_throttle_0_0 blks2_packet_encoder_0 0 0 digital_gfsk_demod_0 blks2_packet_decoder_0 0 0 digital_gfsk_mod_0 digital_gfsk_demod_0 0 0 blks2_packet_decoder_0 qtgui_time_sink_x_1 0 0 analog_sig_source_x_0 blocks_throttle_0_0 0 0 digital_gfsk_mod_0 analog_quadrature_demod_cf_0 0 0 analog_quadrature_demod_cf_0 qtgui_time_sink_x_1_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/demod/uhd_corr_and_sync_rx.grc0000664000175000017500000010100412237515112025141 0ustar jcorganjcorgan Thu Nov 7 12:17:40 2013 variable id addr _enabled True value "addr=192.168.10.2" _coordinate (481, 10) _rotation 0 variable id rrc_taps _enabled True value firdes.root_raised_cosine(nfilts, nfilts, 1.0/float(sps), eb, 5*sps*nfilts) _coordinate (412, 74) _rotation 0 variable id preamble _enabled True value [1,-1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,-1,-1,1,-1,1,1,1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,-1,-1,1,1,1,1,1,1,-1,-1] _coordinate (260, 11) _rotation 0 variable id matched_filter _enabled True value firdes.root_raised_cosine(nfilts, nfilts, 1, eb, int(11*sps*nfilts)) _coordinate (254, 74) _rotation 0 variable id eb _enabled True value 0.35 _coordinate (171, 74) _rotation 0 variable id sps _enabled True value 4 _coordinate (177, 10) _rotation 0 variable id nfilts _enabled True value 32 _coordinate (411, 10) _rotation 0 variable id samp_rate _enabled True value 250000 _coordinate (11, 72) _rotation 0 digital_correlate_and_sync_cc id digital_correlate_and_sync_cc_0 _enabled True symbols preamble filter matched_filter sps sps affinity minoutbuf 0 _coordinate (733, 179) _rotation 0 blocks_complex_to_mag id blocks_complex_to_mag_0 _enabled True vlen 1 affinity minoutbuf 0 _coordinate (1015, 183) _rotation 0 blocks_complex_to_float id blocks_complex_to_float_0 _enabled True vlen 1 affinity minoutbuf 0 _coordinate (1015, 228) _rotation 0 digital_costas_loop_cc id digital_costas_loop_cc_0 _enabled True w 1*3.14/50.0 order 2 affinity minoutbuf 0 _coordinate (641, 378) _rotation 0 qtgui_const_sink_x id qtgui_const_sink_x_0_0 _enabled True type complex name QT GUI Plot size 20000 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 1 update_time 0.10 gui_hint 0,1,1,1 affinity _coordinate (946, 328) _rotation 0 digital_pfb_clock_sync_xxx id digital_pfb_clock_sync_xxx_0 _enabled True type ccf sps sps loop_bw 2*3.14/100.0 taps rrc_taps filter_size nfilts init_phase 0 max_dev 0.5 osps 1 affinity minoutbuf 0 _coordinate (297, 358) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_1 _enabled True type float name QT GUI Plot size 40000 srate samp_rate ymin -200 ymax 400 nconnections 3 update_time 0.10 tr_mode qtgui.TRIG_MODE_NORM tr_slope qtgui.TRIG_SLOPE_POS tr_level 200 tr_delay 0.010 tr_chan 0 tr_tag "" entags True gui_hint 1,0,1,2 affinity _coordinate (1213, 194) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0 _enabled True type complex name QT GUI Plot size 25000 srate samp_rate ymin -2 ymax 2 nconnections 1 update_time 0.10 tr_mode qtgui.TRIG_MODE_TAG tr_slope qtgui.TRIG_SLOPE_POS tr_level 1 tr_delay 0.010 tr_chan 0 tr_tag time_est entags True gui_hint 0,0,1,1 affinity 0 _coordinate (946, 396) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled True type fc32 otw stream_args stream_chans [] dev_addr addr sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 freq gain0 gain ant0 TX/RX bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 affinity minoutbuf 0 _coordinate (23, 163) _rotation 0 digital_fll_band_edge_cc id digital_fll_band_edge_cc_0 _enabled True type cc samps_per_sym sps rolloff eb filter_size 45 w 2*3.14/100.0 affinity minoutbuf 0 _coordinate (463, 148) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const digital_gain vlen 1 affinity minoutbuf 0 _coordinate (278, 195) _rotation 0 variable_qtgui_range id gain _enabled True label Rx Gain value 12.5 start 0 stop 31.5 step 0.5 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,0,1,1 _coordinate (633, 11) _rotation 0 variable_qtgui_range id freq _enabled True label Rx Frequency value 450e6 start 400e6 stop 500e6 step 100e3 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,2 _coordinate (882, 14) _rotation 0 variable_qtgui_range id digital_gain _enabled True label Digital Gain value 45 start 0 stop 200 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (761, 13) _rotation 0 options id uhd_corr_and_sync_rx _enabled True title author description window_size 2000,2000 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 uhd_usrp_source_0 blocks_multiply_const_vxx_0 0 0 digital_correlate_and_sync_cc_0 blocks_complex_to_float_0 1 0 digital_correlate_and_sync_cc_0 blocks_complex_to_mag_0 1 0 blocks_multiply_const_vxx_0 digital_fll_band_edge_cc_0 0 0 digital_correlate_and_sync_cc_0 digital_pfb_clock_sync_xxx_0 0 0 digital_fll_band_edge_cc_0 digital_correlate_and_sync_cc_0 0 0 blocks_complex_to_mag_0 qtgui_time_sink_x_1 0 0 blocks_complex_to_float_0 qtgui_time_sink_x_1 0 1 blocks_complex_to_float_0 qtgui_time_sink_x_1 1 2 digital_pfb_clock_sync_xxx_0 digital_costas_loop_cc_0 0 0 digital_costas_loop_cc_0 qtgui_const_sink_x_0_0 0 0 digital_costas_loop_cc_0 qtgui_time_sink_x_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/ofdm/0000755000175000017500000000000012237515112020107 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-digital/examples/ofdm/gr_plot_ofdm.py0000755000175000017500000002531511700377701023151 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math, struct, sys from optparse import OptionParser from math import log10 try: import scipy from scipy import fftpack except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) try: from pylab import * from matplotlib.font_manager import fontManager, FontProperties except ImportError: print "Error: Program requires matplotlib (see: matplotlib.sourceforge.net)." sys.exit(1) matplotlib.interactive(True) matplotlib.use('TkAgg') class draw_constellation: def __init__(self, options): derot_file = "ofdm_frame_sink_c.dat" acq_file = "ofdm_frame_acq_c.dat" fft_file = "ofdm_receiver-fft_out_c.dat" self.h_derot_file = open(derot_file, "r") self.h_acq_file = open(acq_file, "r") self.h_fft_file = open(fft_file, "r") self.occ_tones = options.occ_tones self.fft_size = options.fft_size self.symbol = options.start self.sample_rate = options.sample_rate self.axis_font_size = 16 self.label_font_size = 18 self.title_font_size = 20 self.text_size = 22 # Setup PLOT self.fig = figure(1, figsize=(14, 9), facecolor='w') rcParams['xtick.labelsize'] = self.axis_font_size rcParams['ytick.labelsize'] = self.axis_font_size self.text_sym = figtext(0.05, 0.95, ("Symbol: %s" % self.symbol), weight="heavy", size=self.text_size) self.make_plots() self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True) self.button_left = Button(self.button_left_axes, "<") self.button_left_callback = self.button_left.on_clicked(self.button_left_click) self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True) self.button_right = Button(self.button_right_axes, ">") self.button_right_callback = self.button_right.on_clicked(self.button_right_click) self.xlim = self.sp_eq.get_xlim() self.manager = get_current_fig_manager() #connect('draw_event', self.zoom) connect('key_press_event', self.click) show() def get_data(self): self.text_sym.set_text("Symbol: %d" % (self.symbol)) derot_data = scipy.fromfile(self.h_derot_file, dtype=scipy.complex64, count=self.occ_tones) acq_data = scipy.fromfile(self.h_acq_file, dtype=scipy.complex64, count=self.occ_tones) fft_data = scipy.fromfile(self.h_fft_file, dtype=scipy.complex64, count=self.fft_size) if(len(acq_data) == 0): print "End of File" else: self.acq_data_reals = [r.real for r in acq_data] self.acq_data_imags = [i.imag for i in acq_data] self.derot_data_reals = [r.real for r in derot_data] self.derot_data_imags = [i.imag for i in derot_data] self.unequalized_angle = [math.atan2(x.imag, x.real) for x in fft_data] self.equalized_angle = [math.atan2(x.imag, x.real) for x in acq_data] self.derot_equalized_angle = [math.atan2(x.imag, x.real) for x in derot_data] self.time = [i*(1/self.sample_rate) for i in range(len(acq_data))] ffttime = [i*(1/self.sample_rate) for i in range(len(fft_data))] self.freq = self.get_freq(ffttime, self.sample_rate) for i in range(len(fft_data)): if(abs(fft_data[i]) == 0.0): fft_data[i] = complex(1e-6,1e-6) self.fft_data = [20*log10(abs(f)) for f in fft_data] def get_freq(self, time, sample_rate, T=1): N = len(time) Fs = 1.0 / (max(time) - min(time)) Fn = 0.5 * sample_rate freq = [-Fn + i*Fs for i in range(N)] return freq def make_plots(self): self.h_acq_file.seek(8*self.symbol*self.occ_tones, 0) self.h_fft_file.seek(8*self.symbol*self.fft_size, 0) self.h_derot_file.seek(8*self.symbol*self.occ_tones, 0) self.get_data() # Subplot: constellation of rotated symbols self.sp_const = self.fig.add_subplot(4,1,1, position=[0.15, 0.55, 0.3, 0.35]) self.sp_const.set_title(("Constellation"), fontsize=self.title_font_size, fontweight="bold") self.sp_const.set_xlabel("Inphase", fontsize=self.label_font_size, fontweight="bold") self.sp_const.set_ylabel("Qaudrature", fontsize=self.label_font_size, fontweight="bold") self.plot_const = plot(self.acq_data_reals, self.acq_data_imags, 'bo') self.plot_const += plot(self.derot_data_reals, self.derot_data_imags, 'ro') self.sp_const.axis([-2, 2, -2, 2]) # Subplot: unequalized angle self.sp_uneq = self.fig.add_subplot(4,2,1, position=[0.575, 0.55, 0.3, 0.35]) self.sp_uneq.set_title(("Unequalized Angle"), fontsize=self.title_font_size, fontweight="bold") self.sp_uneq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold") self.sp_uneq.set_ylabel("Angle", fontsize=self.label_font_size, fontweight="bold") uneqscale = range(len(self.unequalized_angle)) self.plot_uneq = plot(uneqscale, self.unequalized_angle, 'bo') # Subplot: equalized angle self.sp_eq = self.fig.add_subplot(4,1,2, position=[0.15, 0.1, 0.3, 0.35]) self.sp_eq.set_title(("Equalized Angle"), fontsize=self.title_font_size, fontweight="bold") self.sp_eq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold") self.sp_eq.set_ylabel("Angle", fontsize=self.label_font_size, fontweight="bold") eqscale = range(len(self.equalized_angle)) self.plot_eq = plot(eqscale, self.equalized_angle, 'bo') self.plot_eq += plot(eqscale, self.derot_equalized_angle, 'ro', markersize=4) # Subplot: FFT self.sp_fft = self.fig.add_subplot(4,2,2, position=[0.575, 0.1, 0.3, 0.35]) self.sp_fft.set_title(("FFT"), fontsize=self.title_font_size, fontweight="bold") self.sp_fft.set_xlabel("Frequency (MHz)", fontsize=self.label_font_size, fontweight="bold") self.sp_fft.set_ylabel("Power (dBm)", fontsize=self.label_font_size, fontweight="bold") self.plot_fft = plot(self.freq, self.fft_data, '-bo') draw() def update_plots(self): eqscale = range(len(self.equalized_angle)) uneqscale = range(len(self.unequalized_angle)) self.plot_eq[0].set_data([eqscale, self.equalized_angle]) self.plot_eq[1].set_data([eqscale, self.derot_equalized_angle]) self.plot_uneq[0].set_data([uneqscale, self.unequalized_angle]) self.sp_eq.set_ylim([-4, 4]) self.sp_uneq.set_ylim([-4, 4]) #self.sp_iq.axis([min(self.time), max(self.time), # 1.5*min([min(self.acq_data_reals), min(self.acq_data_imags)]), # 1.5*max([max(self.acq_data_reals), max(self.acq_data_imags)])]) self.plot_const[0].set_data([self.acq_data_reals, self.acq_data_imags]) self.plot_const[1].set_data([self.derot_data_reals, self.derot_data_imags]) self.sp_const.axis([-2, 2, -2, 2]) self.plot_fft[0].set_data([self.freq, self.fft_data]) draw() def zoom(self, event): newxlim = self.sp_eq.get_xlim() if(newxlim != self.xlim): self.xlim = newxlim r = self.reals[int(ceil(self.xlim[0])) : int(ceil(self.xlim[1]))] i = self.imags[int(ceil(self.xlim[0])) : int(ceil(self.xlim[1]))] self.plot_const[0].set_data(r, i) self.sp_const.axis([-2, 2, -2, 2]) self.manager.canvas.draw() draw() def click(self, event): forward_valid_keys = [" ", "down", "right"] backward_valid_keys = ["up", "left"] if(find(event.key, forward_valid_keys)): self.step_forward() elif(find(event.key, backward_valid_keys)): self.step_backward() def button_left_click(self, event): self.step_backward() def button_right_click(self, event): self.step_forward() def step_forward(self): self.symbol += 1 self.get_data() self.update_plots() def step_backward(self): # Step back in file position self.symbol -= 1 if(self.h_acq_file.tell() >= 16*self.occ_tones): self.h_acq_file.seek(-16*self.occ_tones, 1) else: self.symbol = 0 self.h_acq_file.seek(-self.h_acq_file.tell(),1) if(self.h_derot_file.tell() >= 16*self.occ_tones): self.h_derot_file.seek(-16*self.occ_tones, 1) else: self.symbol = 0 self.h_derot_file.seek(-self.h_derot_file.tell(),1) if(self.h_fft_file.tell() >= 16*self.fft_size): self.h_fft_file.seek(-16*self.fft_size, 1) else: self.symbol = 0 self.h_fft_file.seek(-self.h_fft_file.tell(),1) self.get_data() self.update_plots() #FIXME: there must be a way to do this with a Python builtin def find(item_in, list_search): for l in list_search: if item_in == l: return True return False def main(): usage="%prog: [options]" parser = OptionParser(conflict_handler="resolve", usage=usage) parser.add_option("", "--fft-size", type="int", default=512, help="Specify the size of the FFT [default=%default]") parser.add_option("", "--occ-tones", type="int", default=200, help="Specify the number of occupied tones [default=%default]") parser.add_option("-s", "--start", type="int", default=0, help="Specify the starting symbol to plot [default=%default]") parser.add_option("-R", "--sample-rate", type="float", default=1.0, help="Set the sampler rate of the data [default=%default]") (options, args) = parser.parse_args () dc = draw_constellation(options) if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/ofdm/benchmark_add_channel.py0000775000175000017500000001075612207440367024737 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import random, math, sys class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): gr.top_block.__init__(self) SNR = 10.0**(options.snr/10.0) time_offset = options.time_offset phase_offset = options.phase_offset*(math.pi/180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude)**2 noise_power = power_in_signal/SNR noise_voltage = math.sqrt(noise_power) print "Noise voltage: ", noise_voltage frequency_offset = options.frequency_offset / options.fft_length self.src = blocks.file_source(gr.sizeof_gr_complex, ifile) #self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = filter.channel_model(noise_voltage, frequency_offset, time_offset, noise_seed=-random.randint(0,100000)) self.phase = blocks.multiply_const_cc(complex(math.cos(phase_offset), math.sin(phase_offset))) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] " parser = OptionParser (usage=usage, option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--seed", action="store_true", default=False, help="use a random seed for AWGN noise [default=%default]") parser.add_option("-f", "--frequency-offset", type="eng_float", default=0, help="set frequency offset introduced by channel [default=%default]") parser.add_option("-t", "--time-offset", type="eng_float", default=1.0, help="set timing offset between Tx and Rx [default=%default]") parser.add_option("-p", "--phase-offset", type="eng_float", default=0, help="set phase offset (in degrees) between Tx and Rx [default=%default]") parser.add_option("-m", "--use-multipath", action="store_true", default=False, help="Use a multipath channel [default=%default]") parser.add_option("", "--fft-length", type="intx", default=None, help="set the number of FFT bins [default=%default]") parser.add_option("", "--tx-amplitude", type="eng_float", default=1.0, help="tell the simulator the signal amplitude [default=%default]") (options, args) = parser.parse_args () if len(args) != 2: parser.print_help(sys.stderr) sys.exit(1) if options.fft_length is None: sys.stderr.write("Please enter the FFT length of the OFDM signal.\n") sys.exit(1) ifile = args[0] ofile = args[1] # build the graph tb = my_top_block(ifile, ofile, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: Failed to enable realtime scheduling." tb.start() # start flow graph tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/ofdm/ofdm_loopback.grc0000664000175000017500000004375312237515112023421 0ustar jcorganjcorgan Sun Nov 3 19:13:00 2013 options id ofdm_loopback_example _enabled True title OFDM Loopback Example author description Transmit a pre-defined signal (a complex sine) as OFDM packets. window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (0, -1) _rotation 0 variable id samp_rate _enabled True value 100000 _coordinate (493, 7) _rotation 0 variable id fft_len _enabled True value 64 _coordinate (403, 8) _rotation 0 variable id len_tag_key _enabled True value "packet_len" _coordinate (283, 6) _rotation 0 variable id packet_len _enabled True value 50 _coordinate (182, 6) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0 _enabled True type byte vector range(packet_len) tags () repeat True vlen 1 affinity minoutbuf 0 _coordinate (5, 124) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title Rx Spectrum samp_rate 100e3 baseband_freq 0 y_per_div 10 y_divs 10 ref_level 0 ref_scale 2.0 fft_size 1024 fft_rate 15 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook freqvar None affinity _coordinate (51, 500) _rotation 0 blocks_tag_debug id blocks_tag_debug_0 _enabled True type byte name Rx Packets num_inputs 1 vlen 1 display True affinity _coordinate (325, 483) _rotation 0 blocks_stream_to_tagged_stream id blocks_stream_to_tagged_stream_0 _enabled True type byte vlen 1 packet_len packet_len len_tag_key len_tag_key affinity minoutbuf 0 _coordinate (282, 132) _rotation 0 digital_ofdm_rx id digital_ofdm_rx_0 _enabled True fft_len fft_len cp_len fft_len/4 packet_len_key "rx_len" occupied_carriers () pilot_carriers () pilot_symbols () sync_word1 () sync_word2 () header_mod "BPSK" payload_mod "QPSK" scramble_bits False log False affinity minoutbuf 0 _coordinate (52, 374) _rotation 0 blocks_uchar_to_float id blocks_uchar_to_float_0 _enabled True affinity minoutbuf 0 _coordinate (326, 408) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type float title Scope Plot samp_rate 1.0 v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts affinity _coordinate (530, 382) _rotation 0 digital_ofdm_tx id digital_ofdm_tx_0 _enabled True fft_len fft_len cp_len fft_len/4 packet_len_key len_tag_key occupied_carriers () pilot_carriers () pilot_symbols () sync_word1 () sync_word2 () header_mod "BPSK" payload_mod "QPSK" rolloff 0 scramble_bits False log False affinity minoutbuf 0 _coordinate (557, 94) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise_voltage freq_offset freq_offset * 1.0/fft_len epsilon 1.0 taps 1.0 + 1.0j seed 0 block_tags True affinity minoutbuf 0 _coordinate (453, 244) _rotation 180 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (177, 281) _rotation 180 variable_slider id freq_offset _enabled True label Frequency Offset (Multiples of Sub-carrier spacing) value 0 min -3 max 3 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (466, 508) _rotation 0 variable_slider id noise_voltage _enabled True label Noise Amplitude value 0.01 min 0 max 1 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (653, 505) _rotation 0 digital_ofdm_tx_0 channels_channel_model_0 0 0 blocks_throttle_0 wxgui_fftsink2_0 0 0 blocks_throttle_0 digital_ofdm_rx_0 0 0 blocks_vector_source_x_0 blocks_stream_to_tagged_stream_0 0 0 blocks_stream_to_tagged_stream_0 digital_ofdm_tx_0 0 0 digital_ofdm_rx_0 blocks_tag_debug_0 0 0 digital_ofdm_rx_0 blocks_uchar_to_float_0 0 0 blocks_uchar_to_float_0 wxgui_scopesink2_0 0 0 channels_channel_model_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/ofdm/benchmark_rx.py0000775000175000017500000001012412207702530023126 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser from gnuradio import blocks from gnuradio import digital # from current dir from receive_path import receive_path from uhd_interface import uhd_receiver import struct, sys class my_top_block(gr.top_block): def __init__(self, callback, options): gr.top_block.__init__(self) if(options.rx_freq is not None): self.source = uhd_receiver(options.args, options.bandwidth, options.rx_freq, options.lo_offset, options.rx_gain, options.spec, options.antenna, options.clock_source, options.verbose) elif(options.from_file is not None): self.source = blocks.file_source(gr.sizeof_gr_complex, options.from_file) else: self.source = blocks.null_source(gr.sizeof_gr_complex) # Set up receive path # do this after for any adjustments to the options that may # occur in the sinks (specifically the UHD sink) self.rxpath = receive_path(callback, options) self.connect(self.source, self.rxpath) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): global n_rcvd, n_right n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right n_rcvd += 1 (pktno,) = struct.unpack('!H', payload[0:2]) if ok: n_right += 1 print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right) if 0: printlst = list() for x in payload[2:]: t = hex(ord(x)).replace('0x', '') if(len(t) == 1): t = '0' + t printlst.append(t) printable = ''.join(printlst) print printable print "\n" parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinuous") parser.add_option("","--from-file", default=None, help="input file of samples to demod") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args () if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(rx_callback, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/ofdm/receive_path.py0000664000175000017500000000664212207440367023137 0ustar jcorganjcorgan# # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import eng_notation from gnuradio import digital from gnuradio import analog import copy import sys # ///////////////////////////////////////////////////////////////////////////// # receive path # ///////////////////////////////////////////////////////////////////////////// class receive_path(gr.hier_block2): def __init__(self, rx_callback, options): gr.hier_block2.__init__(self, "receive_path", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) options = copy.copy(options) # make a copy so we can destructively modify self._verbose = options.verbose self._log = options.log self._rx_callback = rx_callback # this callback is fired when there's a packet available # receiver self.ofdm_rx = digital.ofdm_demod(options, callback=self._rx_callback) # Carrier Sensing Blocks alpha = 0.001 thresh = 30 # in dB, will have to adjust self.probe = analog.probe_avg_mag_sqrd_c(thresh,alpha) self.connect(self, self.ofdm_rx) self.connect(self.ofdm_rx, self.probe) # Display some information about the setup if self._verbose: self._print_verbage() def carrier_sensed(self): """ Return True if we think carrier is present. """ #return self.probe.level() > X return self.probe.unmuted() def carrier_threshold(self): """ Return current setting in dB. """ return self.probe.threshold() def set_carrier_threshold(self, threshold_in_db): """ Set carrier threshold. Args: threshold_in_db: set detection threshold (float (dB)) """ self.probe.set_threshold(threshold_in_db) def add_options(normal, expert): """ Adds receiver-specific options to the Options Parser """ normal.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]") normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the receive path """ pass gnuradio-3.7.2.1/gr-digital/examples/ofdm/tunnel.py0000775000175000017500000002202612207440367022003 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # ///////////////////////////////////////////////////////////////////////////// # # This code sets up up a virtual ethernet interface (typically gr0), # and relays packets between the interface and the GNU Radio PHY+MAC # # What this means in plain language, is that if you've got a couple # of USRPs on different machines, and if you run this code on those # machines, you can talk between them using normal TCP/IP networking. # # ///////////////////////////////////////////////////////////////////////////// from gnuradio import gr, digital from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser # from current dir from receive_path import receive_path from transmit_path import transmit_path from uhd_interface import uhd_transmitter from uhd_interface import uhd_receiver import os, sys import random, time, struct #print os.getpid() #raw_input('Attach and press enter') # ///////////////////////////////////////////////////////////////////////////// # # Use the Universal TUN/TAP device driver to move packets to/from kernel # # See /usr/src/linux/Documentation/networking/tuntap.txt # # ///////////////////////////////////////////////////////////////////////////// # Linux specific... # TUNSETIFF ifr flags from IFF_TUN = 0x0001 # tunnel IP packets IFF_TAP = 0x0002 # tunnel ethernet frames IFF_NO_PI = 0x1000 # don't pass extra packet info IFF_ONE_QUEUE = 0x2000 # beats me ;) def open_tun_interface(tun_device_filename): from fcntl import ioctl mode = IFF_TAP | IFF_NO_PI TUNSETIFF = 0x400454ca tun = os.open(tun_device_filename, os.O_RDWR) ifs = ioctl(tun, TUNSETIFF, struct.pack("16sH", "gr%d", mode)) ifname = ifs[:16].strip("\x00") return (tun, ifname) # ///////////////////////////////////////////////////////////////////////////// # the flow graph # ///////////////////////////////////////////////////////////////////////////// class my_top_block(gr.top_block): def __init__(self, callback, options): gr.top_block.__init__(self) self.source = uhd_receiver(options.args, options.bandwidth, options.rx_freq, options.rx_gain, options.spec, options.antenna, options.verbose) self.sink = uhd_transmitter(options.args, options.bandwidth, options.tx_freq, options.tx_gain, options.spec, options.antenna, options.verbose) self.txpath = transmit_path(options) self.rxpath = receive_path(callback, options) self.connect(self.txpath, self.sink) self.connect(self.source, self.rxpath) def carrier_sensed(self): """ Return True if the receive path thinks there's carrier """ return self.rxpath.carrier_sensed() def set_freq(self, target_freq): """ Set the center frequency we're interested in. """ self.u_snk.set_freq(target_freq) self.u_src.set_freq(target_freq) # ///////////////////////////////////////////////////////////////////////////// # Carrier Sense MAC # ///////////////////////////////////////////////////////////////////////////// class cs_mac(object): """ Prototype carrier sense MAC Reads packets from the TUN/TAP interface, and sends them to the PHY. Receives packets from the PHY via phy_rx_callback, and sends them into the TUN/TAP interface. Of course, we're not restricted to getting packets via TUN/TAP, this is just an example. """ def __init__(self, tun_fd, verbose=False): self.tun_fd = tun_fd # file descriptor for TUN/TAP interface self.verbose = verbose self.tb = None # top block (access to PHY) def set_flow_graph(self, tb): self.tb = tb def phy_rx_callback(self, ok, payload): """ Invoked by thread associated with PHY to pass received packet up. Args: ok: bool indicating whether payload CRC was OK payload: contents of the packet (string) """ if self.verbose: print "Rx: ok = %r len(payload) = %4d" % (ok, len(payload)) if ok: os.write(self.tun_fd, payload) def main_loop(self): """ Main loop for MAC. Only returns if we get an error reading from TUN. FIXME: may want to check for EINTR and EAGAIN and reissue read """ min_delay = 0.001 # seconds while 1: payload = os.read(self.tun_fd, 10*1024) if not payload: self.tb.txpath.send_pkt(eof=True) break if self.verbose: print "Tx: len(payload) = %4d" % (len(payload),) delay = min_delay while self.tb.carrier_sensed(): sys.stderr.write('B') time.sleep(delay) if delay < 0.050: delay = delay * 2 # exponential back-off self.tb.txpath.send_pkt(payload) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'], default='bpsk', help="Select modulation from: bpsk, qpsk [default=%%default]") parser.add_option("-v","--verbose", action="store_true", default=False) expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") digital.ofdm_mod.add_options(parser, expert_grp) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = my_top_block(mac.phy_rx_callback, options) mac.set_flow_graph(tb) # give the MAC a handle for the PHY print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname,) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,) print print "Be sure to use a different address in the same subnet for each machine." print tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/ofdm/ofdm_sync_pn.m0000644000175000017500000000104711700377701022751 0ustar jcorganjcorganmf = read_float_binary('ofdm_sync_pn-mf_f.dat'); theta_pn = read_float_binary('ofdm_sync_pn-theta_f.dat'); peaks_pn = read_char_binary('ofdm_sync_pn-peaks_b.dat'); regen_pn = read_char_binary('ofdm_sync_pn-regen_b.dat'); angle_pn = read_float_binary('ofdm_sync_pn-epsilon_f.dat'); plot(mf, 'k') hold plot(theta_pn, 'g'); plot(peaks_pn, 'r'); plot(regen_pn, 'b'); xlim([100, 50000]); ylim([0, 1]) i = find(peaks_pn); i(100:200) hold off ipeaks = find(peaks_pn); dpeaks = diff(ipeaks); hist(dpeaks, 30) set(gca, 'FontSize', 30, 'FontWeight', 'Bold'); gnuradio-3.7.2.1/gr-digital/examples/ofdm/benchmark_tx.py0000775000175000017500000001055012207702530023133 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2006,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import time, struct, sys from gnuradio import digital from gnuradio import blocks # from current dir from transmit_path import transmit_path from uhd_interface import uhd_transmitter class my_top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) if(options.tx_freq is not None): self.sink = uhd_transmitter(options.args, options.bandwidth, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) elif(options.to_file is not None): self.sink = blocks.file_sink(gr.sizeof_gr_complex, options.to_file) else: self.sink = blocks.null_sink(gr.sizeof_gr_complex) # do this after for any adjustments to the options that may # occur in the sinks (specifically the UHD sink) self.txpath = transmit_path(options) self.connect(self.txpath, self.sink) # ///////////////////////////////////////////////////////////////////////////// # main # ///////////////////////////////////////////////////////////////////////////// def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinuous mode") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 send_pkt(eof=True) time.sleep(2) # allow time for queued packets to be sent tb.wait() # wait for it to finish if __name__ == '__main__': try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/ofdm/tx_ofdm.grc0000664000175000017500000011124612237515112022253 0ustar jcorganjcorgan Sun Nov 3 18:45:28 2013 options id tx_ofdm _enabled True title OFDM Tx author description Example of an OFDM Transmitter window_size 1280, 1024 generate_options wx_gui category Custom run_options run run True max_nouts 0 realtime_scheduling _coordinate (0, -1) _rotation 0 variable id sync_word1 _enabled True value [0., 0., 0., 0., 0., 0., 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., -1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., -1.41421356, 0., -1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 0., 0., 0., 0., 0.] _coordinate (352, 128) _rotation 0 variable id sync_word2 _enabled True value [0, 0, 0, 0, 0, 0, -1, -1, -1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 0, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, -1, 1, -1, 1, -1, -1, -1, -1, 0, 0, 0, 0, 0] _coordinate (496, 128) _rotation 0 variable id pilot_symbols _enabled True value ((1, 1, 1, -1,),) _coordinate (601, 64) _rotation 0 variable id occupied_carriers _enabled True value (range(-26, -21) + range(-20, -7) + range(-6, 0) + range(1, 7) + range(8, 21) + range(22, 27),) _coordinate (329, 64) _rotation 0 variable id pilot_carriers _enabled True value ((-21, -7, 7, 21,),) _coordinate (480, 64) _rotation 0 variable id header_formatter _enabled True value digital.packet_header_ofdm(occupied_carriers, 1, length_tag_key) _coordinate (708, 64) _rotation 0 variable id fft_len _enabled True value 64 _coordinate (181, -1) _rotation 0 variable id packet_len _enabled True value 96 _coordinate (476, 0) _rotation 0 variable id header_mod _enabled True value digital.constellation_bpsk() _coordinate (567, 0) _rotation 0 variable id payload_mod _enabled True value digital.constellation_qpsk() _coordinate (734, 0) _rotation 0 variable id rolloff _enabled True value 0 _coordinate (898, -1) _rotation 0 variable id samp_rate _enabled True value 100000 _coordinate (255, 0) _rotation 0 variable id length_tag_key _enabled True value "packet_len" _coordinate (352, 0) _rotation 0 virtual_source id virtual_source_0_0 _enabled True stream_id Payload Bits _coordinate (0, 458) _rotation 0 import id import_0 _enabled True import import numpy _coordinate (237, 93) _rotation 0 import id import_1 _enabled True import from gnuradio.digital.utils import tagged_streams _coordinate (99, 93) _rotation 0 import id import_0_0 _enabled True import import random _coordinate (3, 94) _rotation 0 virtual_source id virtual_source_0_0_0_0 _enabled True stream_id Time Domain _coordinate (1, 747) _rotation 0 virtual_sink id virtual_sink_0_0_0 _enabled True stream_id Pre-OFDM _coordinate (745, 441) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0_0 _enabled True in_type byte out_type complex symbol_table payload_mod.points() dimension 1 num_ports 1 affinity minoutbuf 0 _coordinate (212, 450) _rotation 0 virtual_source id virtual_source_0_0_0 _enabled True stream_id Pre-OFDM _coordinate (0, 578) _rotation 0 virtual_sink id virtual_sink_0 _enabled True stream_id Time Domain _coordinate (855, 578) _rotation 0 fft_vxx id fft_vxx_0 _enabled True type complex fft_size fft_len forward False window () shift True nthreads 1 affinity minoutbuf 0 _coordinate (414, 548) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const 0.05 vlen 1 affinity minoutbuf 0 _coordinate (209, 747) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0 _enabled True in_type byte out_type complex symbol_table header_mod.points() dimension 1 num_ports 1 affinity minoutbuf 0 _coordinate (214, 376) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 255 num_samps 1000 repeat True affinity minoutbuf 0 _coordinate (13, 220) _rotation 0 blocks_tagged_stream_mux id blocks_tagged_stream_mux_0 _enabled True type complex ninputs 2 lengthtagname length_tag_key vlen 1 tag_preserve_head_pos 0 affinity minoutbuf 0 _coordinate (510, 428) _rotation 0 digital_ofdm_cyclic_prefixer id digital_ofdm_cyclic_prefixer_0 _enabled True input_size fft_len cp_len fft_len/4 rolloff rolloff tagname length_tag_key affinity minoutbuf 0 _coordinate (632, 564) _rotation 0 blocks_tag_gate id blocks_tag_gate_0 _enabled True type complex vlen 1 propagate_tags False affinity minoutbuf 0 _coordinate (372, 747) _rotation 0 blocks_repack_bits_bb id blocks_repack_bits_bb_0 _enabled True k 8 l payload_mod.bits_per_symbol() len_tag_key length_tag_key align_output False affinity minoutbuf 0 _coordinate (710, 301) _rotation 0 digital_packet_headergenerator_bb id digital_packet_headergenerator_bb_0 _enabled True header_formatter header_formatter.formatter() affinity minoutbuf 0 _coordinate (703, 242) _rotation 0 blocks_stream_to_tagged_stream id blocks_stream_to_tagged_stream_0 _enabled True type byte vlen 1 packet_len packet_len len_tag_key length_tag_key affinity minoutbuf 0 _coordinate (193, 235) _rotation 0 virtual_sink id header_bits _enabled True stream_id Header Bits _coordinate (936, 243) _rotation 0 virtual_sink id virtual_sink_0_0 _enabled True stream_id Payload Bits _coordinate (934, 324) _rotation 0 virtual_source id virtual_source_0 _enabled True stream_id Header Bits _coordinate (1, 382) _rotation 0 digital_crc32_bb id digital_crc32_bb_0 _enabled True check False lengthtagname length_tag_key affinity minoutbuf 0 _coordinate (430, 235) _rotation 0 digital_ofdm_carrier_allocator_cvc id digital_ofdm_carrier_allocator_cvc_0 _enabled True fft_len fft_len occupied_carriers occupied_carriers pilot_carriers pilot_carriers pilot_symbols pilot_symbols sync_words (sync_word1, sync_word2) len_tag_key length_tag_key affinity minoutbuf 0 _coordinate (192, 540) _rotation 0 virtual_source id virtual_source_1 _enabled True stream_id Tx Signal _coordinate (0, 894) _rotation 0 virtual_sink id virtual_sink_1 _enabled True stream_id Tx Signal _coordinate (990, 646) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts affinity _coordinate (992, 716) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 0 ref_scale 2.0 fft_size 1024 fft_rate 15 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook freqvar None affinity _coordinate (994, 810) _rotation 0 digital_ofdm_rx id digital_ofdm_rx_0 _enabled True fft_len fft_len cp_len fft_len/4 packet_len_key "length" occupied_carriers occupied_carriers pilot_carriers pilot_carriers pilot_symbols pilot_symbols sync_word1 sync_word1 sync_word2 sync_word2 header_mod "BPSK" payload_mod "QPSK" scramble_bits False log False affinity minoutbuf 0 _coordinate (439, 823) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage 0.0 freq_offset 0.0 epsilon 1.0 taps 1.0 + 1.0j seed 0 block_tags True affinity minoutbuf 0 _coordinate (193, 858) _rotation 0 blocks_tag_debug id blocks_tag_debug_0 _enabled True type byte name Rx'd Packets num_inputs 1 vlen 1 display True affinity _coordinate (689, 889) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (559, 747) _rotation 0 blocks_tagged_stream_mux_0 virtual_sink_0_0_0 0 0 virtual_source_0_0 digital_chunks_to_symbols_xx_0_0 0 0 virtual_source_0 digital_chunks_to_symbols_xx_0 0 0 digital_chunks_to_symbols_xx_0_0 blocks_tagged_stream_mux_0 0 1 virtual_source_0_0_0_0 blocks_multiply_const_vxx_0 0 0 virtual_source_0_0_0 digital_ofdm_carrier_allocator_cvc_0 0 0 digital_ofdm_carrier_allocator_cvc_0 fft_vxx_0 0 0 fft_vxx_0 digital_ofdm_cyclic_prefixer_0 0 0 digital_ofdm_cyclic_prefixer_0 virtual_sink_0 0 0 blocks_multiply_const_vxx_0 blocks_tag_gate_0 0 0 blocks_tag_gate_0 blocks_throttle_0 0 0 digital_chunks_to_symbols_xx_0 blocks_tagged_stream_mux_0 0 0 analog_random_source_x_0 blocks_stream_to_tagged_stream_0 0 0 blocks_throttle_0 wxgui_scopesink2_0 0 0 blocks_throttle_0 wxgui_fftsink2_0 0 0 blocks_stream_to_tagged_stream_0 digital_crc32_bb_0 0 0 digital_crc32_bb_0 digital_packet_headergenerator_bb_0 0 0 digital_crc32_bb_0 blocks_repack_bits_bb_0 0 0 digital_packet_headergenerator_bb_0 header_bits 0 0 blocks_repack_bits_bb_0 virtual_sink_0_0 0 0 blocks_throttle_0 virtual_sink_1 0 0 virtual_source_1 channels_channel_model_0 0 0 channels_channel_model_0 digital_ofdm_rx_0 0 0 digital_ofdm_rx_0 blocks_tag_debug_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/ofdm/uhd_interface.py0000664000175000017500000002237512207702530023273 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2010,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, uhd from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq """ def freq_callback(option, opt_str, value, parser): parser.values.rx_freq = value parser.values.tx_freq = value if not parser.has_option('--freq'): parser.add_option('-f', '--freq', type="eng_float", action="callback", callback=freq_callback, help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") class uhd_interface: def __init__(self, istx, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None): if(istx): self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) else: self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) # Set clock source to external. if(clock_source): self.u.set_clock_source(clock_source, 0) # Set the subdevice spec if(spec): self.u.set_subdev_spec(spec, 0) # Set the antenna if(antenna): self.u.set_antenna(antenna, 0) self._args = args self._ant = antenna self._spec = spec self._gain = self.set_gain(gain) self._lo_offset = lo_offset self._freq = self.set_freq(freq, lo_offset) self._rate = self.set_sample_rate(bandwidth) self._clock_source = clock_source def set_sample_rate(self, bandwidth): self.u.set_samp_rate(bandwidth) actual_bw = self.u.get_samp_rate() return actual_bw def get_sample_rate(self): return self.u.get_samp_rate() def set_gain(self, gain=None): if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() gain = float(g.start()+g.stop())/2 print "\nNo gain specified." print "Setting gain to %f (from [%f, %f])" % \ (gain, g.start(), g.stop()) self.u.set_gain(gain, 0) return gain def set_freq(self, freq=None, lo_offset=None): if(freq is None): sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") sys.exit(1) r = self.u.set_center_freq(uhd.tune_request(freq, lo_offset)) if r: return freq else: frange = self.u.get_freq_range() sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ (freq, frange.start(), frange.stop())) sys.exit(1) #-------------------------------------------------------------------# # TRANSMITTER #-------------------------------------------------------------------# class uhd_transmitter(uhd_interface, gr.hier_block2): def __init__(self, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_transmitter", gr.io_signature(1,1,gr.sizeof_gr_complex), gr.io_signature(0,0,0)) # Set up the UHD interface as a transmitter uhd_interface.__init__(self, True, args, bandwidth, freq, lo_offset, gain, spec, antenna, clock_source) self.connect(self, self.u) if(verbose): self._print_verbage() def add_options(parser): add_freq_option(parser) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("", "--lo-offset", type="eng_float", default=0, help="set local oscillator offset in Hz (default is 0)") parser.add_option("", "--tx-gain", type="eng_float", default=None, help="set transmit gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the UHD transmitter """ print "\nUHD Transmitter:" print "UHD Args: %s" % (self._args) print "Freq: %sHz" % (eng_notation.num_to_str(self._freq)) print "LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) print "Gain: %f dB" % (self._gain) print "Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate)) print "Antenna: %s" % (self._ant) print "Subdev Sec: %s" % (self._spec) print "Clock Source: %s" % (self._clock_source) #-------------------------------------------------------------------# # RECEIVER #-------------------------------------------------------------------# class uhd_receiver(uhd_interface, gr.hier_block2): def __init__(self, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_receiver", gr.io_signature(0,0,0), gr.io_signature(1,1,gr.sizeof_gr_complex)) # Set up the UHD interface as a receiver uhd_interface.__init__(self, False, args, bandwidth, freq, lo_offset, gain, spec, antenna, clock_source) self.connect(self.u, self) if(verbose): self._print_verbage() def add_options(parser): add_freq_option(parser) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--rx-freq", type="eng_float", default=None, help="set receive frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("", "--lo-offset", type="eng_float", default=0, help="set local oscillator offset in Hz (default is 0)") parser.add_option("", "--rx-gain", type="eng_float", default=None, help="set receive gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") if not parser.has_option("--verbose"): parser.add_option("-v", "--verbose", action="store_true", default=False) # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the UHD transmitter """ print "\nUHD Receiver:" print "UHD Args: %s" % (self._args) print "Freq: %sHz" % (eng_notation.num_to_str(self._freq)) print "LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) print "Gain: %f dB" % (self._gain) print "Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate)) print "Antenna: %s" % (self._ant) print "Subdev Sec: %s" % (self._spec) print "Clock Source: %s" % (self._clock_source) gnuradio-3.7.2.1/gr-digital/examples/ofdm/transmit_path.py0000664000175000017500000000720312207440367023350 0ustar jcorganjcorgan# # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import eng_notation from gnuradio import blocks from gnuradio import digital import copy import sys # ///////////////////////////////////////////////////////////////////////////// # transmit path # ///////////////////////////////////////////////////////////////////////////// class transmit_path(gr.hier_block2): def __init__(self, options): ''' See below for what options should hold ''' gr.hier_block2.__init__(self, "transmit_path", gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_gr_complex)) options = copy.copy(options) # make a copy so we can destructively modify self._verbose = options.verbose # turn verbose mode on/off self._tx_amplitude = options.tx_amplitude # digital amp sent to radio self.ofdm_tx = digital.ofdm_mod(options, msgq_limit=4, pad_for_usrp=False) self.amp = blocks.multiply_const_cc(1) self.set_tx_amplitude(self._tx_amplitude) # Display some information about the setup if self._verbose: self._print_verbage() # Create and setup transmit path flow graph self.connect(self.ofdm_tx, self.amp, self) def set_tx_amplitude(self, ampl): """ Sets the transmit amplitude sent to the USRP Args: : ampl 0 <= ampl < 1.0. Try 0.10 """ self._tx_amplitude = max(0.0, min(ampl, 1)) self.amp.set_k(self._tx_amplitude) def send_pkt(self, payload='', eof=False): """ Calls the transmitter method to send a packet """ return self.ofdm_tx.send_pkt(payload, eof) def add_options(normal, expert): """ Adds transmitter-specific options to the Options Parser """ normal.add_option("", "--tx-amplitude", type="eng_float", default=0.1, metavar="AMPL", help="set transmitter digital amplitude: 0 <= AMPL < 1.0 [default=%default]") normal.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]") normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to file (CAUTION: lots of data)") # Make a static method to call before instantiation add_options = staticmethod(add_options) def _print_verbage(self): """ Prints information about the transmit path """ print "Tx amplitude %s" % (self._tx_amplitude) gnuradio-3.7.2.1/gr-digital/examples/ofdm/rx_ofdm.grc0000664000175000017500000011545212237515112022254 0ustar jcorganjcorgan Sun Oct 27 16:24:42 2013 options id rx_ofdm _enabled True title OFDM Rx author description Example of an OFDM receiver window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (0, -1) _rotation 0 variable id payload_mod _enabled True value digital.constellation_qpsk() _coordinate (663, 1) _rotation 0 variable id samp_rate _enabled True value 10000 _coordinate (170, 65) _rotation 0 variable id header_equalizer _enabled True value digital.ofdm_equalizer_simpledfe(fft_len, header_mod.base(), occupied_carriers, pilot_carriers, pilot_symbols) _coordinate (931, 69) _rotation 0 variable id payload_equalizer _enabled True value digital.ofdm_equalizer_simpledfe(fft_len, payload_mod.base(), occupied_carriers, pilot_carriers, pilot_symbols, 1) _coordinate (1112, 73) _rotation 0 variable id sync_word2 _enabled True value [0j, 0j, 0j, 0j, 0j, 0j, (-1+0j), (-1+0j), (-1+0j), (-1+0j), (1+0j), (1+0j), (-1+0j), (-1+0j), (-1+0j), (1+0j), (-1+0j), (1+0j), (1+0j), (1 +0j), (1+0j), (1+0j), (-1+0j), (-1+0j), (-1+0j), (-1+0j), (-1+0j), (1+0j), (-1+0j), (-1+0j), (1+0j), (-1+0j), 0j, (1+0j), (-1+0j), (1+0j), (1+0j), (1+0j), (-1+0j), (1+0j), (1+0j), (1+0j), (-1+0j), (1+0j), (1+0j), (1+0j), (1+0j), (-1+0j), (1+0j), (-1+0j), (-1+0j), (-1+0j), (1+0j), (-1+0j), (1+0j), (-1+0j), (-1+0j), (-1+0j), (-1+0j), 0j, 0j, 0j, 0j, 0j] _coordinate (399, 66) _rotation 0 variable id sync_word1 _enabled True value [0., 0., 0., 0., 0., 0., 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., -1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., -1.41421356, 0., -1.41421356, 0., -1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 1.41421356, 0., -1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 1.41421356, 0., 0., 0., 0., 0., 0.] _coordinate (255, 67) _rotation 0 variable id fft_len _enabled True value 64 _coordinate (301, -1) _rotation 0 variable id header_mod _enabled True value digital.constellation_bpsk() _coordinate (490, 0) _rotation 0 variable id packet_len _enabled True value 96 _coordinate (1034, 0) _rotation 0 variable id pilot_carriers _enabled True value ((-21, -7, 7, 21,),) _coordinate (692, 70) _rotation 0 variable id pilot_symbols _enabled True value ((1, 1, 1, -1,),) _coordinate (813, 70) _rotation 0 variable id occupied_carriers _enabled True value (range(-26, -21) + range(-20, -7) + range(-6, 0) + range(1, 7) + range(8, 21) + range(22, 27),) _coordinate (541, 70) _rotation 0 variable id length_tag_key _enabled True value "frame_len" _coordinate (367, -1) _rotation 0 variable id packet_length_tag_key _enabled True value "packet_len" _coordinate (1132, 0) _rotation 0 variable id header_formatter _enabled True value digital.packet_header_ofdm(occupied_carriers, n_syms=1, len_tag_key=packet_length_tag_key, frame_len_tag_key=length_tag_key, bits_per_header_sym=header_mod.bits_per_symbol(), bits_per_payload_sym=payload_mod.bits_per_symbol(), scramble_header=False) _coordinate (855, 0) _rotation 0 import id import_1 _enabled True import from gnuradio.digital.utils import tagged_streams _coordinate (163, 0) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 255 num_samps 1000 repeat True affinity minoutbuf 0 _coordinate (2, 167) _rotation 0 analog_frequency_modulator_fc id analog_frequency_modulator_fc_0 _enabled True sensitivity -2.0/fft_len affinity minoutbuf 0 _coordinate (920, 171) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (440, 187) _rotation 0 blocks_delay id blocks_delay_0 _enabled True type complex delay fft_len+fft_len/4 num_ports 1 vlen 1 affinity minoutbuf 0 _coordinate (637, 294) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_0 _enabled True type complex num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (1117, 265) _rotation 0 digital_ofdm_sync_sc_cfb id digital_ofdm_sync_sc_cfb_0 _enabled True fft_len fft_len cp_len fft_len/4 use_even_carriers False affinity minoutbuf 0 _coordinate (627, 175) _rotation 0 digital_packet_headerparser_b id digital_packet_headerparser_b_0 _enabled True header_formatter header_formatter.base() affinity minoutbuf 0 _coordinate (634, 529) _rotation 180 digital_constellation_decoder_cb id digital_constellation_decoder_cb_0 _enabled True constellation header_mod.base() affinity minoutbuf 0 _coordinate (903, 530) _rotation 180 fft_vxx id fft_vxx_0 _enabled True type complex fft_size fft_len forward True window () shift True nthreads 1 affinity minoutbuf 0 _coordinate (217, 576) _rotation 0 virtual_sink id virtual_sink_0 _enabled True stream_id Header Stream _coordinate (1098, 414) _rotation 0 blocks_stream_to_tagged_stream id blocks_stream_to_tagged_stream_0 _enabled True type byte vlen 1 packet_len packet_len len_tag_key packet_length_tag_key affinity minoutbuf 0 _coordinate (171, 182) _rotation 0 digital_header_payload_demux id digital_header_payload_demux_0 _enabled True header_len 3 items_per_symbol fft_len guard_interval fft_len/4 length_tag_key length_tag_key trigger_tag_key "" output_symbols True type complex affinity minoutbuf 0 _coordinate (775, 408) _rotation 0 digital_ofdm_chanest_vcvc id digital_ofdm_chanest_vcvc_0 _enabled True sync_symbol1 sync_word1 sync_symbol2 sync_word2 n_data_symbols 1 eq_noise_red_len 0 max_carr_offset 3 force_one_symbol False affinity minoutbuf 0 _coordinate (442, 584) _rotation 0 digital_ofdm_frame_equalizer_vcvc id digital_ofdm_frame_equalizer_vcvc_0 _enabled True fft_len fft_len cp_len fft_len/4 equalizer header_equalizer.base() len_tag_key length_tag_key propagate_channel_state True fixed_frame_len 1 affinity minoutbuf 0 _coordinate (675, 577) _rotation 0 virtual_source id virtual_source_1 _enabled True stream_id Payload Stream _coordinate (0, 732) _rotation 0 digital_ofdm_serializer_vcc id digital_ofdm_serializer_vcc_header _enabled True fft_len fft_len occupied_carriers occupied_carriers len_tag_key length_tag_key packet_len_tag_key symbols_skipped 0 carr_offset_key input_is_shifted True affinity minoutbuf 0 _coordinate (914, 584) _rotation 0 virtual_sink id virtual_sink_1 _enabled True stream_id Payload Stream _coordinate (1094, 470) _rotation 0 virtual_source id virtual_source_0 _enabled True stream_id Header Stream _coordinate (5, 606) _rotation 0 fft_vxx id fft_vxx_1 _enabled True type complex fft_size fft_len forward True window shift True nthreads 1 affinity minoutbuf 0 _coordinate (221, 702) _rotation 0 digital_ofdm_frame_equalizer_vcvc id digital_ofdm_frame_equalizer_vcvc_1 _enabled True fft_len fft_len cp_len fft_len/4 equalizer payload_equalizer.base() len_tag_key length_tag_key propagate_channel_state True fixed_frame_len 0 affinity minoutbuf 0 _coordinate (672, 702) _rotation 0 virtual_sink id virtual_sink_1_0 _enabled True stream_id Payload IQ _coordinate (1139, 732) _rotation 0 digital_ofdm_serializer_vcc id digital_ofdm_serializer_vcc_payload _enabled True fft_len fft_len occupied_carriers occupied_carriers len_tag_key length_tag_key packet_len_tag_key packet_length_tag_key symbols_skipped 1 carr_offset_key input_is_shifted True affinity minoutbuf 0 _coordinate (916, 710) _rotation 0 digital_crc32_bb id digital_crc32_bb_0 _enabled True check True lengthtagname packet_length_tag_key affinity minoutbuf 0 _coordinate (659, 841) _rotation 0 blocks_repack_bits_bb id blocks_repack_bits_bb_0 _enabled True k payload_mod.bits_per_symbol() l 8 len_tag_key packet_length_tag_key align_output True affinity minoutbuf 0 _coordinate (430, 826) _rotation 0 digital_constellation_decoder_cb id digital_constellation_decoder_cb_1 _enabled True constellation payload_mod.base() affinity minoutbuf 0 _coordinate (183, 848) _rotation 0 virtual_source id virtual_source_0_0 _enabled True stream_id Payload IQ _coordinate (1, 851) _rotation 0 blocks_tag_debug id blocks_tag_debug_1 _enabled True type byte name Rx Bytes num_inputs 1 vlen 1 display True affinity _coordinate (898, 841) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage 0.1 freq_offset 0 * 1.0/fft_len epsilon 1.0 taps 1.0 seed 0 block_tags True affinity minoutbuf 0 _coordinate (303, 372) _rotation 0 digital_ofdm_tx id digital_ofdm_tx_0 _enabled True fft_len fft_len cp_len fft_len/4 packet_len_key packet_length_tag_key occupied_carriers occupied_carriers pilot_carriers pilot_carriers pilot_symbols pilot_symbols sync_word1 sync_word1 sync_word2 sync_word2 header_mod "BPSK" payload_mod "QPSK" rolloff 0 scramble_bits False log True affinity minoutbuf 0 _coordinate (58, 327) _rotation 0 analog_random_source_x_0 blocks_stream_to_tagged_stream_0 0 0 blocks_stream_to_tagged_stream_0 digital_ofdm_tx_0 0 0 digital_ofdm_tx_0 channels_channel_model_0 0 0 channels_channel_model_0 blocks_throttle_0 0 0 blocks_throttle_0 digital_ofdm_sync_sc_cfb_0 0 0 digital_header_payload_demux_0 virtual_sink_0 0 0 digital_ofdm_sync_sc_cfb_0 analog_frequency_modulator_fc_0 0 0 analog_frequency_modulator_fc_0 blocks_multiply_xx_0 0 0 blocks_multiply_xx_0 digital_header_payload_demux_0 0 0 blocks_throttle_0 blocks_delay_0 0 0 blocks_delay_0 blocks_multiply_xx_0 0 1 digital_ofdm_sync_sc_cfb_0 digital_header_payload_demux_0 1 1 digital_header_payload_demux_0 virtual_sink_1 1 0 digital_packet_headerparser_b_0 digital_header_payload_demux_0 header_data header_data digital_ofdm_chanest_vcvc_0 digital_ofdm_frame_equalizer_vcvc_0 0 0 digital_ofdm_frame_equalizer_vcvc_0 digital_ofdm_serializer_vcc_header 0 0 digital_ofdm_serializer_vcc_header digital_constellation_decoder_cb_0 0 0 digital_constellation_decoder_cb_0 digital_packet_headerparser_b_0 0 0 fft_vxx_0 digital_ofdm_chanest_vcvc_0 0 0 virtual_source_0 fft_vxx_0 0 0 virtual_source_1 fft_vxx_1 0 0 digital_ofdm_serializer_vcc_payload virtual_sink_1_0 0 0 digital_ofdm_frame_equalizer_vcvc_1 digital_ofdm_serializer_vcc_payload 0 0 fft_vxx_1 digital_ofdm_frame_equalizer_vcvc_1 0 0 digital_crc32_bb_0 blocks_tag_debug_1 0 0 blocks_repack_bits_bb_0 digital_crc32_bb_0 0 0 virtual_source_0_0 digital_constellation_decoder_cb_1 0 0 digital_constellation_decoder_cb_1 blocks_repack_bits_bb_0 0 0 gnuradio-3.7.2.1/gr-digital/examples/ofdm/plot_ofdm.m0000755000175000017500000000413111700377701022256 0ustar jcorganjcorganfunction plot_ofdm(fft_size, occ_tones) ofdm = read_complex_binary('ofdm_frame_acq_c.dat'); ofdm_split = split_vect(ofdm, occ_tones); ofdm_derot = read_complex_binary('ofdm_frame_sink_c.dat'); ofdm_derot_split = split_vect(ofdm_derot, occ_tones); fftc = read_complex_binary('fft_out_c.dat'); fftc_split = split_vect(fftc, fft_size); size(ofdm_split) size(ofdm_derot_split) disp "DEROTATED SPLIT" ofdm_derot(1:100) figure(1) #set(gcf, 'Position', [50 50 1000 600]); a = size(ofdm_split); if nargin == 3 maxcount = count; if maxcount > a(1) error('plot_ofdm:tolong', 'Requested count size exceeds size of vectors'); end else maxcount = a(1); end for i = 1:size(ofdm_split)[0] x = ofdm_split(i,:); y = fftc_split(i+1,:); subplot(2,2,1); plot(real(x), imag(x), 'bo'); #set(gca, 'FontSize', 30, 'FontWeight', 'Bold'); axis([-1.5, 1.5, -1.5, 1.5]) #title('I&Q Constellation', 'FontSize', 36); #xlabel('Inphase', 'FontSize', 32); #ylabel('Quadrature', 'FontSize', 32); subplot(2,2,3); plot(angle(x*j), 'bo'); #set(gca, 'FontSize', 30, 'FontWeight', 'Bold'); axis([0, occ_tones, -3.5, 3.5]) #title('Equalized Symbol Angle', 'FontSize', 36); #xlabel('Bin Number (Occ. Tones)', 'FontSize', 32); #ylabel('Symbol Angle', 'FontSize', 32); subplot(2,2,2); plot(angle(y*j), 'bo'); #set(gca, 'FontSize', 30, 'FontWeight', 'Bold'); axis([0, fft_size, -3.5, 3.5]) #title('Unequalized Symbol Angle', 'FontSize', 36); #xlabel('Bin Number (FFT Size)', 'FontSize', 32); #ylabel('Symbol Angle', 'FontSize', 32); Y = 20*log10(abs(y) ./ max(abs(y))); subplot(2,2,4); plot(Y, 'b-'); #set(gca, 'FontSize', 30, 'FontWeight', 'Bold'); axis([0, fft_size, -50, 1]); #title('Frequency Domain of Unequalized Rx', 'FontSize', 36); #xlabel('Bin Number (FFT Size)', 'FontSize', 32); #ylabel('Power (dB)', 'FontSize', 32); #N = 20*log10(var(abs(x)-1)); disp(sprintf('Symbol Number: %d\n', i)) #disp(sprintf('\tFreq Error: %f\n', anglesh_pn(1+(i-1)*fft_size))) pause end gnuradio-3.7.2.1/gr-digital/examples/ofdm/ofdm_sync.m0000644000175000017500000000106111700377701022250 0ustar jcorganjcorgan% function [theta, g, g1, k, h] = ofdm_sync(signal,SNR,FFTSIZE,CPLEN) rho = SNR/(SNR+1); d = abs(signal).^2; g = [ zeros(1,FFTSIZE) signal(1:max(size(signal))-FFTSIZE) ]; g1 = conj(g); f = abs(g).^2; c = d + f; moving_sum_taps = rho/2 * ones(1,CPLEN); b = conv(c,moving_sum_taps); b = b(1:max(size(signal))); %b = b(CPLEN:max(size(b))); k = g1 .* signal; moving_sum_taps2 = ones(1, CPLEN); h = conv(k,moving_sum_taps2); h = h(1:max(size(signal))); %h = h(CPLEN:max(size(h))); a = abs(h); theta = a-b; endfunction gnuradio-3.7.2.1/gr-digital/examples/gen_whitener.py0000775000175000017500000000342612207440367022232 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import sys class my_graph(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 src = blocks.lfsr_32k_source_s() head = blocks.head(gr.sizeof_short, 2048) self.dst = blocks.vector_sink_s() self.connect(src, head, self.dst) if __name__ == '__main__': try: tb = my_graph() tb.run() f = sys.stdout i = 0 for s in tb.dst.data(): f.write("%3d, " % (s & 0xff,)) f.write("%3d, " % ((s >> 8) & 0xff,)) i = i+2 if i % 16 == 0: f.write('\n') except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-digital/examples/snr_estimators.py0000775000175000017500000001403612207440367022627 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys try: import scipy from scipy import stats except ImportError: print "Error: Program requires scipy (www.scipy.org)." sys.exit(1) try: import pylab except ImportError: print "Error: Program requires Matplotlib (matplotlib.sourceforge.net)." sys.exit(1) from gnuradio import gr, digital, filter from gnuradio import blocks from gnuradio import channels from optparse import OptionParser from gnuradio.eng_option import eng_option ''' This example program uses Python and GNU Radio to calculate SNR of a noise BPSK signal to compare them. For an explination of the online algorithms, see: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics ''' def online_skewness(data, alpha): n = 0 mean = 0 M2 = 0 M3 = 0 d_M3 = 0 for n in xrange(len(data)): delta = data[n] - mean delta_n = delta / (n+1) term1 = delta * delta_n * (n) mean = mean + delta_n M3 = term1 * delta_n * (n - 1) - 3 * delta_n * M2 M2 = M2 + term1 d_M3 = (0.001)*M3 + (1-0.001)*d_M3; return d_M3 def snr_est_simple(signal): y1 = scipy.mean(abs(signal)) y2 = scipy.real(scipy.mean(signal**2)) y3 = (y1*y1 - y2) snr_rat = y1*y1/y3 return 10.0*scipy.log10(snr_rat), snr_rat def snr_est_skew(signal): y1 = scipy.mean(abs(signal)) y2 = scipy.mean(scipy.real(signal**2)) y3 = (y1*y1 - y2) y4 = online_skewness(abs(signal.real), 0.001) skw = y4*y4 / (y2*y2*y2); snr_rat = y1*y1 / (y3 + skw*y1*y1) return 10.0*scipy.log10(snr_rat), snr_rat def snr_est_m2m4(signal): M2 = scipy.mean(abs(signal)**2) M4 = scipy.mean(abs(signal)**4) snr_rat = 2*scipy.sqrt(2*M2*M2 - M4) / (M2 - scipy.sqrt(2*M2*M2 - M4)) return 10.0*scipy.log10(snr_rat), snr_rat def snr_est_svr(signal): N = len(signal) ssum = 0 msum = 0 for i in xrange(1, N): ssum += (abs(signal[i])**2)*(abs(signal[i-1])**2) msum += (abs(signal[i])**4) savg = (1.0/(float(N)-1.0))*ssum mavg = (1.0/(float(N)-1.0))*msum beta = savg / (mavg - savg) snr_rat = 2*((beta - 1) + scipy.sqrt(beta*(beta-1))) return 10.0*scipy.log10(snr_rat), snr_rat def main(): gr_estimators = {"simple": digital.SNR_EST_SIMPLE, "skew": digital.SNR_EST_SKEW, "m2m4": digital.SNR_EST_M2M4, "svr": digital.SNR_EST_SVR} py_estimators = {"simple": snr_est_simple, "skew": snr_est_skew, "m2m4": snr_est_m2m4, "svr": snr_est_svr} parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=10000, help="Set the number of samples to process [default=%default]") parser.add_option("", "--snr-min", type="float", default=-5, help="Minimum SNR [default=%default]") parser.add_option("", "--snr-max", type="float", default=20, help="Maximum SNR [default=%default]") parser.add_option("", "--snr-step", type="float", default=0.5, help="SNR step amount [default=%default]") parser.add_option("-t", "--type", type="choice", choices=gr_estimators.keys(), default="simple", help="Estimator type {0} [default=%default]".format( gr_estimators.keys())) (options, args) = parser.parse_args () N = options.nsamples xx = scipy.random.randn(N) xy = scipy.random.randn(N) bits = 2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1 snr_known = list() snr_python = list() snr_gr = list() # when to issue an SNR tag; can be ignored in this example. ntag = 10000 n_cpx = xx + 1j*xy py_est = py_estimators[options.type] gr_est = gr_estimators[options.type] SNR_min = options.snr_min SNR_max = options.snr_max SNR_step = options.snr_step SNR_dB = scipy.arange(SNR_min, SNR_max+SNR_step, SNR_step) for snr in SNR_dB: SNR = 10.0**(snr/10.0) scale = scipy.sqrt(SNR) yy = bits + n_cpx/scale print "SNR: ", snr Sknown = scipy.mean(yy**2) Nknown = scipy.var(n_cpx/scale)/2 snr0 = Sknown/Nknown snr0dB = 10.0*scipy.log10(snr0) snr_known.append(snr0dB) snrdB, snr = py_est(yy) snr_python.append(snrdB) gr_src = blocks.vector_source_c(bits.tolist(), False) gr_snr = digital.mpsk_snr_est_cc(gr_est, ntag, 0.001) gr_chn = channels.channel_model(1.0/scale) gr_snk = blocks.null_sink(gr.sizeof_gr_complex) tb = gr.top_block() tb.connect(gr_src, gr_chn, gr_snr, gr_snk) tb.run() snr_gr.append(gr_snr.snr()) f1 = pylab.figure(1) s1 = f1.add_subplot(1,1,1) s1.plot(SNR_dB, snr_known, "k-o", linewidth=2, label="Known") s1.plot(SNR_dB, snr_python, "b-o", linewidth=2, label="Python") s1.plot(SNR_dB, snr_gr, "g-o", linewidth=2, label="GNU Radio") s1.grid(True) s1.set_title('SNR Estimators') s1.set_xlabel('SNR (dB)') s1.set_ylabel('Estimated SNR') s1.legend() pylab.show() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-digital/examples/berawgn.py0000775000175000017500000001143312207440367021176 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ BER simulation for QPSK signals, compare to theoretical values. Change the N_BITS value to simulate more bits per Eb/N0 value, thus allowing to check for lower BER values. Lower values will work faster, higher values will use a lot of RAM. Also, this app isn't highly optimized--the flow graph is completely reinstantiated for every Eb/N0 value. Of course, expect the maximum value for BER to be one order of magnitude below what you chose for N_BITS. """ import math import numpy from gnuradio import gr, digital from gnuradio import analog from gnuradio import blocks try: from scipy.special import erfc except ImportError: print "Error: could not import scipy (http://www.scipy.org/)" sys.exit(1) try: import pylab except ImportError: print "Error: could not import pylab (http://matplotlib.sourceforge.net/)" sys.exit(1) # Best to choose powers of 10 N_BITS = 1e7 RAND_SEED = 42 def berawgn(EbN0): """ Calculates theoretical bit error rate in AWGN (for BPSK and given Eb/N0) """ return 0.5 * erfc(math.sqrt(10**(float(EbN0)/10))) class BitErrors(gr.hier_block2): """ Two inputs: true and received bits. We compare them and add up the number of incorrect bits. Because integrate_ff() can only add up a certain number of values, the output is not a scalar, but a sequence of values, the sum of which is the BER. """ def __init__(self, bits_per_byte): gr.hier_block2.__init__(self, "BitErrors", gr.io_signature(2, 2, gr.sizeof_char), gr.io_signature(1, 1, gr.sizeof_int)) # Bit comparison comp = blocks.xor_bb() intdump_decim = 100000 if N_BITS < intdump_decim: intdump_decim = int(N_BITS) self.connect(self, comp, blocks.unpack_k_bits_bb(bits_per_byte), blocks.uchar_to_float(), blocks.integrate_ff(intdump_decim), blocks.multiply_const_ff(1.0/N_BITS), self) self.connect((self, 1), (comp, 1)) class BERAWGNSimu(gr.top_block): " This contains the simulation flow graph " def __init__(self, EbN0): gr.top_block.__init__(self) self.const = digital.qpsk_constellation() # Source is N_BITS bits, non-repeated data = map(int, numpy.random.randint(0, self.const.arity(), N_BITS/self.const.bits_per_symbol())) src = blocks.vector_source_b(data, False) mod = digital.chunks_to_symbols_bc((self.const.points()), 1) add = blocks.add_vcc() noise = analog.noise_source_c(analog.GR_GAUSSIAN, self.EbN0_to_noise_voltage(EbN0), RAND_SEED) demod = digital.constellation_decoder_cb(self.const.base()) ber = BitErrors(self.const.bits_per_symbol()) self.sink = blocks.vector_sink_f() self.connect(src, mod, add, demod, ber, self.sink) self.connect(noise, (add, 1)) self.connect(src, (ber, 1)) def EbN0_to_noise_voltage(self, EbN0): """ Converts Eb/N0 to a single-sided noise voltage (assuming unit symbol power) """ return 1.0 / math.sqrt(2.0 * self.const.bits_per_symbol() * 10**(float(EbN0)/10)) def simulate_ber(EbN0): """ All the work's done here: create flow graph, run, read out BER """ print "Eb/N0 = %d dB" % EbN0 fg = BERAWGNSimu(EbN0) fg.run() return numpy.sum(fg.sink.data()) if __name__ == "__main__": EbN0_min = 0 EbN0_max = 15 EbN0_range = range(EbN0_min, EbN0_max+1) ber_theory = [berawgn(x) for x in EbN0_range] print "Simulating..." ber_simu = [simulate_ber(x) for x in EbN0_range] f = pylab.figure() s = f.add_subplot(1,1,1) s.semilogy(EbN0_range, ber_theory, 'g-.', label="Theoretical") s.semilogy(EbN0_range, ber_simu, 'b-o', label="Simulated") s.set_title('BER Simulation') s.set_xlabel('Eb/N0 (dB)') s.set_ylabel('BER') s.legend() s.grid() pylab.show() gnuradio-3.7.2.1/config.h.in0000664000175000017500000000224612207440367015360 0ustar jcorganjcorgan/* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GNURADIO_CONFIG_H #define GNURADIO_CONFIG_H #ifndef TRY_SHM_VMCIRCBUF #cmakedefine TRY_SHM_VMCIRCBUF #endif #ifndef GR_PERFORMANCE_COUNTERS #cmakedefine GR_PERFORMANCE_COUNTERS #endif #ifndef GR_CTRLPORT #cmakedefine GR_CTRLPORT #endif #ifndef ENABLE_GR_LOG #cmakedefine ENABLE_GR_LOG #endif #ifndef HAVE_LOG4CPP #cmakedefine HAVE_LOG4CPP #endif #endif /* GNURADIO_CONFIG_H */ gnuradio-3.7.2.1/gr-audio/0000755000175000017500000000000012207440367015036 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/gnuradio-audio.pc.in0000664000175000017500000000042712207440367020703 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-audio Description: The GNU Radio block for all supported audio sound systems Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-audio Cflags: -I${includedir} gnuradio-3.7.2.1/gr-audio/CMakeLists.txt0000664000175000017500000000721512207440367017605 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-audio" ENABLE_GR_AUDIO Boost_FOUND ENABLE_GNURADIO_RUNTIME ) GR_SET_GLOBAL(GR_AUDIO_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ) SET(GR_PKG_AUDIO_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/audio) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_AUDIO) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_AUDIO_DESCRIPTION "GNU Radio Audio Blocks") CPACK_COMPONENT("audio_runtime" GROUP "Audio" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("audio_devel" GROUP "Audio" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("audio_python" GROUP "Audio" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;audio_runtime" ) CPACK_COMPONENT("audio_examples" GROUP "Audio" DISPLAY_NAME "Examples" DESCRIPTION "Example programs" DEPENDS "audio_runtime" ) CPACK_COMPONENT("audio_swig" GROUP "Audio" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;audio_python;audio_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/audio) add_subdirectory(lib) add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/audio) add_subdirectory(grc) add_subdirectory(examples/python) add_subdirectory(examples/grc) endif(ENABLE_PYTHON) if(ENABLE_GR_ANALOG) add_subdirectory(examples/c++) endif(ENABLE_GR_ANALOG) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-audio.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-audio.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-audio.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "audio_devel" ) endif(ENABLE_GR_AUDIO) gnuradio-3.7.2.1/gr-audio/include/0000775000175000017500000000000012207440367016463 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/include/gnuradio/0000775000175000017500000000000012207440367020273 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/include/gnuradio/audio/0000775000175000017500000000000012207440367021374 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/include/gnuradio/audio/CMakeLists.txt0000664000175000017500000000207012207440367024133 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h source.h sink.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/audio COMPONENT "audio_devel" ) gnuradio-3.7.2.1/gr-audio/include/gnuradio/audio/sink.h0000664000175000017500000000353312207440367022515 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_AUDIO_SINK_H #define INCLUDED_GR_AUDIO_SINK_H #include #include namespace gr { namespace audio { /*! * \brief Creates a sink from an audio device. * \ingroup audio_blk */ class GR_AUDIO_API sink : virtual public sync_block { public: typedef boost::shared_ptr sptr; /*! * Creates a sink from an audio device at a specified * sample_rate. The specific audio device to use can be * specified as the device_name parameter. Typical choices are: * \li pulse * \li hw:0,0 * \li plughw:0,0 * \li surround51 * \li /dev/dsp * * \xmlonly * - pulse, hw:0,0, plughw:0,0, surround51, /dev/dsp * \endxmlonly */ static sptr make(int sampling_rate, const std::string device_name = "", bool ok_to_block = true); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_GR_AUDIO_SINK_H */ gnuradio-3.7.2.1/gr-audio/include/gnuradio/audio/source.h0000664000175000017500000000355112207440367023051 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_AUDIO_SOURCE_H #define INCLUDED_GR_AUDIO_SOURCE_H #include #include namespace gr { namespace audio { /*! * \brief Creates a source from an audio device. * \ingroup audio_blk */ class GR_AUDIO_API source : virtual public sync_block { public: typedef boost::shared_ptr sptr; /*! * Creates a source from an audio device at a specified * sample_rate. The specific audio device to use can be * specified as the device_name parameter. Typical choices are: * \li pulse * \li hw:0,0 * \li plughw:0,0 * \li surround51 * \li /dev/dsp * * \xmlonly * - pulse, hw:0,0, plughw:0,0, surround51, /dev/dsp * \endxmlonly */ static sptr make(int sampling_rate, const std::string device_name = "", bool ok_to_block = true); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_GR_AUDIO_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/include/gnuradio/audio/api.h0000664000175000017500000000205012207440367022313 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_AUDIO_API_H #define INCLUDED_GR_AUDIO_API_H #include #ifdef gnuradio_audio_EXPORTS # define GR_AUDIO_API __GR_ATTR_EXPORT #else # define GR_AUDIO_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_GR_AUDIO_API_H */ gnuradio-3.7.2.1/gr-audio/grc/0000755000175000017500000000000012207440367015611 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/grc/CMakeLists.txt0000644000175000017500000000170411744612271020353 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "audio_python") gnuradio-3.7.2.1/gr-audio/grc/audio_sink.xml0000664000175000017500000000352712207440367020471 0ustar jcorganjcorgan Audio Sink audio_sink Audio 1 from gnuradio import audio audio.sink($samp_rate, $device_name, $ok_to_block) Sample Rate samp_rate samp_rate int Device Name device_name string #if $device_name() then 'none' else 'part'# OK to Block ok_to_block True enum part Num Inputs num_inputs 1 int 0 < $num_inputs in float $num_inputs Not all sampling rates will be supported by your hardware. Leave the device name blank to choose deafult audio device. \ ALSA users with audio trouble may try setting the device name to plughw:0,0 The audio sink can have multiple inputs depending upon your hardware. \ For example, set the inputs to 2 for stereo audio. gnuradio-3.7.2.1/gr-audio/grc/audio_source.xml0000664000175000017500000000355412207440367021025 0ustar jcorganjcorgan Audio Source audio_source Audio 1 from gnuradio import audio audio.source($samp_rate, $device_name, $ok_to_block) Sample Rate samp_rate samp_rate int Device Name device_name string #if $device_name() then 'none' else 'part'# OK to Block ok_to_block True enum part Num Outputs num_outputs 1 int 0 < $num_outputs out float $num_outputs Not all sampling rates will be supported by your hardware. Leave the device name blank to choose deafult audio device. \ ALSA users with audio trouble may try setting the device name to plughw:0,0 The audio source can have multiple outputs depending upon your hardware. \ For example, set the outputs to 2 for stereo audio. gnuradio-3.7.2.1/gr-audio/doc/0000755000175000017500000000000012207440367015603 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/doc/CMakeLists.txt0000644000175000017500000000151711744612271020347 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.audio DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-audio/doc/README.audio0000664000175000017500000000167012207440367017571 0ustar jcorganjcorganThe gnuradio audio component provides gr::audio::source and gr::audio::sink blocks. The audio blocks stream floating point samples to and from audio hardware. The gr-audio component will be built automatically when gnuradio-runtime is enabled. Support for underlying audio architectures depends on OS and installed libraries. At the time of writing, gr-audio supports OSS, ALSA, Jack, Portaudio, Audiounit, and Winmm. At runtime, gr-audio will automatically select from the available architectures. The user can override the selection via configuration file by setting "audio_module" to one of the following strings: - oss - alsa - jack - portaudio - osx - windows See gr-audio.conf for an example. Import this package with: from gnuradio import audio See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(audio) gnuradio-3.7.2.1/gr-audio/doc/audio.dox0000664000175000017500000000334112207440367017423 0ustar jcorganjcorgan/*! \page page_audio Audio Interface \section Introduction The gnuradio audio component provides gr::audio::source and gr::audio::sink blocks. The audio blocks stream floating point samples to and from audio hardware. The gr-audio component will be built automatically when gnuradio-runtime is enabled. Support for underlying audio architectures depends on OS and installed libraries. At the time of writing, gr-audio supports OSS, ALSA, Jack, Portaudio, Audiounit, and Winmm. At runtime, gr-audio will automatically select from the available architectures. The user can override the selection via configuration file by setting "audio_module" to one of the following strings: \li oss \li alsa \li jack \li portaudio \li osx \li windows See gr-audio.conf for an example. Import this package with: \code from gnuradio import audio \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(audio) \endcode \section Usage For an audio source, a typical OptionParser option and it's use looks like: \code parser.add_option("-O", "--audio-output", type="string", default="", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") audio_rate = 32e3 audio_sink = audio.sink (int (audio_rate), options.audio_output) \endcode Similarly, an audio sink would have a typical OptionParser option and its use would look like: \code parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") audio_rate = 32e3 audio_source = audio.source(int(audio_rate), audio_input) \endcode */ gnuradio-3.7.2.1/gr-audio/python/0000775000175000017500000000000012207440367016361 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/python/audio/0000775000175000017500000000000012207440367017462 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/python/audio/CMakeLists.txt0000664000175000017500000000316712207440367022231 0ustar jcorganjcorgan# Copyright 2012, 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/audio COMPONENT "audio_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-audio/python/audio/__init__.py0000664000175000017500000000231712207440367021576 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks to connect to audio sources (mic-in) and sinks (speaker-out) ports on a computer. The underlying hardware driver is system and OS dependent and this module should automatically discover the correct one to use. ''' import os try: from audio_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from audio_swig import * gnuradio-3.7.2.1/gr-audio/lib/0000755000175000017500000000000012207440367015604 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/CMakeLists.txt0000664000175000017500000001431712207440367020354 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${GR_AUDIO_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${LOG4CPP_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) link_directories(${LOG4CPP_LIBRARY_DIRS}) list(APPEND gr_audio_libs gnuradio-runtime ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES}) list(APPEND gr_audio_sources audio_registry.cc) list(APPEND gr_audio_confs ${CMAKE_CURRENT_SOURCE_DIR}/gr-audio.conf) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## ## ALSA Support ######################################################################## find_package(ALSA) if(ALSA_FOUND) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/alsa) include_directories(${ALSA_INCLUDE_DIRS}) list(APPEND gr_audio_libs ${ALSA_LIBRARIES}) list(APPEND gr_audio_sources ${CMAKE_CURRENT_SOURCE_DIR}/alsa/alsa_impl.cc ${CMAKE_CURRENT_SOURCE_DIR}/alsa/alsa_source.cc ${CMAKE_CURRENT_SOURCE_DIR}/alsa/alsa_sink.cc ) list(APPEND gr_audio_confs ${CMAKE_CURRENT_SOURCE_DIR}/alsa/gr-audio-alsa.conf) endif(ALSA_FOUND) ######################################################################## ## OSS Support ######################################################################## find_package(OSS) if(OSS_FOUND) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/oss) include_directories(${OSS_INCLUDE_DIRS}) list(APPEND gr_audio_sources ${CMAKE_CURRENT_SOURCE_DIR}/oss/oss_source.cc ${CMAKE_CURRENT_SOURCE_DIR}/oss/oss_sink.cc ) list(APPEND gr_audio_confs ${CMAKE_CURRENT_SOURCE_DIR}/oss/gr-audio-oss.conf) endif(OSS_FOUND) ######################################################################## ## Jack Support ######################################################################## find_package(Jack) if(JACK_FOUND) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/jack) include_directories(${JACK_INCLUDE_DIRS}) list(APPEND gr_audio_libs ${JACK_LIBRARIES}) add_definitions(${JACK_DEFINITIONS}) list(APPEND gr_audio_sources ${CMAKE_CURRENT_SOURCE_DIR}/jack/jack_impl.cc ${CMAKE_CURRENT_SOURCE_DIR}/jack/jack_source.cc ${CMAKE_CURRENT_SOURCE_DIR}/jack/jack_sink.cc ) list(APPEND gr_audio_confs ${CMAKE_CURRENT_SOURCE_DIR}/jack/gr-audio-jack.conf) endif(JACK_FOUND) ######################################################################## ## OSX Support ######################################################################## include(CheckIncludeFileCXX) CHECK_INCLUDE_FILE_CXX(AudioUnit/AudioUnit.h AUDIO_UNIT_H) CHECK_INCLUDE_FILE_CXX(AudioToolbox/AudioToolbox.h AUDIO_TOOLBOX_H) if(AUDIO_UNIT_H AND AUDIO_TOOLBOX_H) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/osx) list(APPEND gr_audio_libs "-framework AudioUnit" "-framework CoreAudio" "-framework AudioToolbox" "-framework Carbon" ) list(APPEND gr_audio_sources ${CMAKE_CURRENT_SOURCE_DIR}/osx/osx_source.cc ${CMAKE_CURRENT_SOURCE_DIR}/osx/osx_sink.cc ) endif(AUDIO_UNIT_H AND AUDIO_TOOLBOX_H) ######################################################################## ## PortAudio Support ######################################################################## find_package(Portaudio) if(PORTAUDIO_FOUND) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/portaudio) include_directories(${PORTAUDIO_INCLUDE_DIRS}) list(APPEND gr_audio_libs ${PORTAUDIO_LIBRARIES}) add_definitions(${PORTAUDIO_DEFINITIONS}) list(APPEND gr_audio_sources ${CMAKE_CURRENT_SOURCE_DIR}/portaudio/portaudio_impl.cc ${CMAKE_CURRENT_SOURCE_DIR}/portaudio/portaudio_source.cc ${CMAKE_CURRENT_SOURCE_DIR}/portaudio/portaudio_sink.cc ) list(APPEND gr_audio_confs ${CMAKE_CURRENT_SOURCE_DIR}/portaudio/gr-audio-portaudio.conf) endif(PORTAUDIO_FOUND) ######################################################################## ## Windows Support ######################################################################## if(WIN32) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/windows) list(APPEND gr_audio_libs winmm.lib) list(APPEND gr_audio_sources ${CMAKE_CURRENT_SOURCE_DIR}/windows/windows_source.cc ${CMAKE_CURRENT_SOURCE_DIR}/windows/windows_sink.cc ) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-audio.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-audio.rc @ONLY) list(APPEND gr_audio_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-audio.rc ) ENDIF() endif(WIN32) ######################################################################## # Setup library ######################################################################## add_library(gnuradio-audio SHARED ${gr_audio_sources}) target_link_libraries(gnuradio-audio ${gr_audio_libs}) GR_LIBRARY_FOO(gnuradio-audio RUNTIME_COMPONENT "audio_runtime" DEVEL_COMPONENT "audio_devel") install(FILES ${gr_audio_confs} DESTINATION ${GR_PREFSDIR} COMPONENT "audio_runtime") gnuradio-3.7.2.1/gr-audio/lib/audio_registry.h0000664000175000017500000000434312207440367021014 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_AUDIO_REGISTRY_H #define INCLUDED_GR_AUDIO_REGISTRY_H #include #include #include namespace gr { namespace audio { typedef source::sptr(*source_factory_t)(int, const std::string &, bool); typedef sink::sptr(*sink_factory_t)(int, const std::string &, bool); enum reg_prio_type { REG_PRIO_LOW = 100, REG_PRIO_MED = 200, REG_PRIO_HIGH = 300 }; void register_source(reg_prio_type prio, const std::string &arch, source_factory_t source); void register_sink(reg_prio_type prio, const std::string &arch, sink_factory_t sink); #define AUDIO_REGISTER_FIXTURE(x) static struct x{x();}x;x::x() #define AUDIO_REGISTER_SOURCE(prio, arch) \ static source::sptr arch##_source_fcn(int, const std::string &, bool); \ AUDIO_REGISTER_FIXTURE(arch##_source_reg) { \ register_source(prio, #arch, &arch##_source_fcn); \ } static source::sptr arch##_source_fcn #define AUDIO_REGISTER_SINK(prio, arch) \ static sink::sptr arch##_sink_fcn(int, const std::string &, bool); \ AUDIO_REGISTER_FIXTURE(arch##_sink_reg) { \ register_sink(prio, #arch, &arch##_sink_fcn); \ } static sink::sptr arch##_sink_fcn } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_GR_AUDIO_REGISTRY_H */ gnuradio-3.7.2.1/gr-audio/lib/portaudio/0000755000175000017500000000000012207440367017612 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/portaudio/portaudio_impl.h0000664000175000017500000000221712207440367023016 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_PORTAUDIO_IMPL_H #define INCLUDED_AUDIO_PORTAUDIO_IMPL_H #include #include namespace gr { namespace audio { PaDeviceIndex pa_find_device_by_name(const char *name); void print_devices(); } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_PORTAUDIO_IMPL_H */ gnuradio-3.7.2.1/gr-audio/lib/portaudio/portaudio_sink.h0000664000175000017500000000536012207440367023023 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_PORTAUDIO_SINK_H #define INCLUDED_AUDIO_PORTAUDIO_SINK_H #include #include #include #include #include #include //#include namespace gr { namespace audio { PaStreamCallback portaudio_sink_callback; /*! * \brief Audio sink using PORTAUDIO * \ingroup audio_blk * * Input samples must be in the range [-1,1]. */ class portaudio_sink : public sink { friend PaStreamCallback portaudio_sink_callback; unsigned int d_sampling_rate; std::string d_device_name; bool d_ok_to_block; bool d_verbose; unsigned int d_portaudio_buffer_size_frames; // number of frames in a portaudio buffer PaStream *d_stream; PaStreamParameters d_output_parameters; gr::buffer_sptr d_writer; // buffer used between work and callback gr::buffer_reader_sptr d_reader; gr::thread::mutex d_ringbuffer_mutex; gr::thread::condition_variable d_ringbuffer_cond; bool d_ringbuffer_ready; // random stats int d_nunderuns; // count of underruns //gri_logger_sptr d_log; // handle to non-blocking logging instance void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); void create_ringbuffer(); public: portaudio_sink(int sampling_rate, const std::string device_name, bool ok_to_block); ~portaudio_sink(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_PORTAUDIO_SINK_H */ gnuradio-3.7.2.1/gr-audio/lib/portaudio/portaudio_source.h0000664000175000017500000000523312207440367023356 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_PORTAUDIO_SOURCE_H #define INCLUDED_AUDIO_PORTAUDIO_SOURCE_H #include #include #include #include #include #include namespace gr { namespace audio { PaStreamCallback portaudio_source_callback; /*! * \brief Audio source using PORTAUDIO * \ingroup audio_blk * * Input samples must be in the range [-1,1]. */ class portaudio_source : public source { friend PaStreamCallback portaudio_source_callback; unsigned int d_sampling_rate; std::string d_device_name; bool d_ok_to_block; bool d_verbose; unsigned int d_portaudio_buffer_size_frames; // number of frames in a portaudio buffer PaStream *d_stream; PaStreamParameters d_input_parameters; gr::buffer_sptr d_writer; // buffer used between work and callback gr::buffer_reader_sptr d_reader; gr::thread::mutex d_ringbuffer_mutex; gr::thread::condition_variable d_ringbuffer_cond; bool d_ringbuffer_ready; // random stats int d_noverruns; // count of overruns void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); void create_ringbuffer(); public: portaudio_source(int sampling_rate, const std::string device_name, bool ok_to_block); ~portaudio_source(); bool check_topology(int ninputs, int noutputs); int work(int ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_PORTAUDIO_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/lib/portaudio/portaudio_impl.cc0000664000175000017500000000712412207440367023156 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace audio { PaDeviceIndex pa_find_device_by_name(const char *name) { int i; int numDevices; const PaDeviceInfo *pdi; int len = strlen(name); PaDeviceIndex result = paNoDevice; numDevices = Pa_GetDeviceCount(); for(i = 0; i < numDevices; i++) { pdi = Pa_GetDeviceInfo(i); if(strncmp(name, pdi->name, len) == 0) { result = i; break; } } return result; } void print_devices() { int numDevices, defaultDisplayed; const PaDeviceInfo *deviceInfo; numDevices = Pa_GetDeviceCount(); if(numDevices < 0) return; printf("Number of devices found = %d\n", numDevices); for(int i = 0; i < numDevices; i++) { deviceInfo = Pa_GetDeviceInfo(i); printf("--------------------------------------- device #%d\n", i); /* Mark global and API specific default devices */ defaultDisplayed = 0; if(i == Pa_GetDefaultInputDevice()) { printf("[ Default Input"); defaultDisplayed = 1; } else if(i == Pa_GetHostApiInfo(deviceInfo->hostApi)->defaultInputDevice) { const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); printf("[ Default %s Input", hostInfo->name); defaultDisplayed = 1; } if(i == Pa_GetDefaultOutputDevice()) { printf((defaultDisplayed ? "," : "[")); printf(" Default Output"); defaultDisplayed = 1; } else if(i == Pa_GetHostApiInfo(deviceInfo->hostApi)->defaultOutputDevice) { const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); printf((defaultDisplayed ? "," : "[")); printf(" Default %s Output", hostInfo->name); defaultDisplayed = 1; } if(defaultDisplayed) printf(" ]\n"); /* print device info fields */ printf("Name = %s\n", deviceInfo->name); printf("Host API = %s\n", Pa_GetHostApiInfo(deviceInfo->hostApi)->name ); printf("Max inputs = %d", deviceInfo->maxInputChannels); printf(", Max outputs = %d\n", deviceInfo->maxOutputChannels); printf("Default low input latency = %8.3f\n", deviceInfo->defaultLowInputLatency); printf("Default low output latency = %8.3f\n", deviceInfo->defaultLowOutputLatency); printf("Default high input latency = %8.3f\n", deviceInfo->defaultHighInputLatency); printf("Default high output latency = %8.3f\n", deviceInfo->defaultHighOutputLatency); } } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/portaudio/gr-audio-portaudio.conf0000644000175000017500000000037711700377700024200 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [audio_portaudio] #default_input_device = hw:0,0 #default_output_device = hw:0,0 verbose = false gnuradio-3.7.2.1/gr-audio/lib/portaudio/portaudio_source.cc0000664000175000017500000003117412207440367023517 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in he hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SOURCE(REG_PRIO_MED, portaudio)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return source::sptr (new portaudio_source(sampling_rate, device_name, ok_to_block)); } //#define LOGGING 0 // define to 0 or 1 #define SAMPLE_FORMAT paFloat32 typedef float sample_t; // Number of portaudio buffers in the ringbuffer static const unsigned int N_BUFFERS = 4; static std::string default_device_name() { return prefs::singleton()->get_string ("audio_portaudio", "default_input_device", ""); } void portaudio_source::create_ringbuffer(void) { int bufsize_samples = d_portaudio_buffer_size_frames * d_input_parameters.channelCount; if(d_verbose) { fprintf(stderr, "ring buffer size = %d frames\n", N_BUFFERS*bufsize_samples/d_input_parameters.channelCount); } // FYI, the buffer indicies are in units of samples. d_writer = gr::make_buffer(N_BUFFERS * bufsize_samples, sizeof(sample_t)); d_reader = gr::buffer_add_reader(d_writer, 0); } /* * This routine will be called by the PortAudio engine when audio is needed. * It may called at interrupt level on some machines so don't do anything * that could mess up the system like calling malloc() or free(). * * Our job is to copy framesPerBuffer frames from inputBuffer. */ int portaudio_source_callback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *arg) { portaudio_source *self = (portaudio_source *)arg; int nchan = self->d_input_parameters.channelCount; int nframes_to_copy = framesPerBuffer; int nframes_room = self->d_writer->space_available() / nchan; if(nframes_to_copy <= nframes_room) { // We've got room for the data .. //if (LOGGING) // self->d_log->printf("PAsrc cb: f/b = %4ld\n", framesPerBuffer); // copy from input buffer to ringbuffer { gr::thread::scoped_lock(d_ringbuffer_mutex); memcpy(self->d_writer->write_pointer(), inputBuffer, nframes_to_copy * nchan * sizeof(sample_t)); self->d_writer->update_write_pointer(nframes_to_copy * nchan); // Tell the source thread there is new data in the ringbuffer. self->d_ringbuffer_ready = true; } self->d_ringbuffer_cond.notify_one(); return paContinue; } else { // overrun self->d_noverruns++; ssize_t r = ::write(2, "aO", 2); // FIXME change to non-blocking call if(r == -1) { perror("audio_portaudio_source::portaudio_source_callback write error to stderr."); } self->d_ringbuffer_ready = false; self->d_ringbuffer_cond.notify_one(); // Tell the sink to get going! return paContinue; } } // ---------------------------------------------------------------- portaudio_source::portaudio_source(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_portaudio_source", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_ok_to_block(ok_to_block), d_verbose(prefs::singleton()->get_bool("audio_portaudio", "verbose", false)), d_portaudio_buffer_size_frames(0), d_stream(0), d_ringbuffer_mutex(), d_ringbuffer_cond(), d_ringbuffer_ready(false), d_noverruns(0) { memset(&d_input_parameters, 0, sizeof(d_input_parameters)); //if(LOGGING) // d_log = gri_logger::singleton(); PaError err; int i, numDevices; PaDeviceIndex device = 0; const PaDeviceInfo *deviceInfo = NULL; err = Pa_Initialize(); if(err != paNoError) { bail("Initialize failed", err); } if(d_verbose) print_devices(); numDevices = Pa_GetDeviceCount(); if(numDevices < 0) bail("Pa Device count failed", 0); if(numDevices == 0) bail("no devices available", 0); if(d_device_name.empty()) { // FIXME Get smarter about picking something device = Pa_GetDefaultInputDevice(); deviceInfo = Pa_GetDeviceInfo(device); fprintf(stderr,"%s is the chosen device using %s as the host\n", deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name); } else { bool found = false; for(i = 0; i < numDevices; i++) { deviceInfo = Pa_GetDeviceInfo(i); fprintf(stderr,"Testing device name: %s",deviceInfo->name); if(deviceInfo->maxInputChannels <= 0) { fprintf(stderr,"\n"); continue; } if(strstr(deviceInfo->name, d_device_name.c_str())) { fprintf(stderr," Chosen!\n"); device = i; fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(), Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr); found = true; deviceInfo = Pa_GetDeviceInfo(device); i = numDevices; // force loop exit } else fprintf(stderr,"\n"),fflush(stderr); } if(!found) { bail("Failed to find specified device name", 0); } } d_input_parameters.device = device; d_input_parameters.channelCount = deviceInfo->maxInputChannels; d_input_parameters.sampleFormat = SAMPLE_FORMAT; d_input_parameters.suggestedLatency = deviceInfo->defaultLowInputLatency; d_input_parameters.hostApiSpecificStreamInfo = NULL; // We fill in the real channelCount in check_topology when we know // how many inputs are connected to us. // Now that we know the maximum number of channels (allegedly) // supported by the h/w, we can compute a reasonable output // signature. The portaudio specs say that they'll accept any // number of channels from 1 to max. set_output_signature(io_signature::make(1, deviceInfo->maxInputChannels, sizeof (sample_t))); } bool portaudio_source::check_topology(int ninputs, int noutputs) { PaError err; if(Pa_IsStreamActive(d_stream)) { Pa_CloseStream(d_stream); d_stream = 0; d_reader.reset(); // boost::shared_ptr for d_reader = 0 d_writer.reset(); // boost::shared_ptr for d_write = 0 } d_input_parameters.channelCount = noutputs; // # of channels we're really using #if 1 d_portaudio_buffer_size_frames = (int)(0.0213333333 * d_sampling_rate + 0.5); // Force 512 frame buffers at 48000 fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms 0.0213333333, (double)d_sampling_rate); #endif err = Pa_OpenStream(&d_stream, &d_input_parameters, NULL, // No output d_sampling_rate, d_portaudio_buffer_size_frames, paClipOff, &portaudio_source_callback, (void*)this); if(err != paNoError) { output_error_msg("OpenStream failed", err); return false; } #if 0 const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream); d_portaudio_buffer_size_frames = (int)(d_input_parameters.suggestedLatency * psi->sampleRate); fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n", d_input_parameters.suggestedLatency, psi->sampleRate); #endif fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames); assert(d_portaudio_buffer_size_frames != 0); create_ringbuffer(); err = Pa_StartStream(d_stream); if(err != paNoError) { output_error_msg("StartStream failed", err); return false; } return true; } portaudio_source::~portaudio_source() { Pa_StopStream(d_stream); // wait for output to drain Pa_CloseStream(d_stream); Pa_Terminate(); } int portaudio_source::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float **out = (float **)&output_items[0]; const unsigned nchan = d_input_parameters.channelCount; // # of channels == samples/frame int k; for(k = 0; k < noutput_items;) { int nframes = d_reader->items_available() / nchan; // # of frames in ringbuffer if(nframes == 0) { // no data right now... if(k > 0) // If we've produced anything so far, return that return k; if(d_ok_to_block) { gr::thread::scoped_lock guard(d_ringbuffer_mutex); while(d_ringbuffer_ready == false) d_ringbuffer_cond.wait(guard); // block here, then try again continue; } assert(k == 0); // There's no data and we're not allowed to block. // (A USRP is most likely controlling the pacing through the pipeline.) // This is an underun. The scheduler wouldn't have called us if it // had anything better to do. Thus we really need to produce some amount // of "fill". // // There are lots of options for comfort noise, etc. // FIXME We'll fill with zeros for now. Yes, it will "click"... // Fill with some frames of zeros { gr::thread::scoped_lock guard(d_ringbuffer_mutex); int nf = std::min(noutput_items - k, (int)d_portaudio_buffer_size_frames); for(int i = 0; i < nf; i++) { for(unsigned int c = 0; c < nchan; c++) { out[c][k + i] = 0; } } k += nf; d_ringbuffer_ready = false; return k; } } // We can read the smaller of the request and what's in the buffer. { gr::thread::scoped_lock guard(d_ringbuffer_mutex); int nf = std::min(noutput_items - k, nframes); const float *p = (const float*)d_reader->read_pointer(); for(int i = 0; i < nf; i++) { for(unsigned int c = 0; c < nchan; c++) { out[c][k + i] = *p++; } } d_reader->update_read_pointer(nf * nchan); k += nf; d_ringbuffer_ready = false; } } return k; // tell how many we actually did } void portaudio_source::output_error_msg(const char *msg, int err) { fprintf(stderr, "audio_portaudio_source[%s]: %s: %s\n", d_device_name.c_str (), msg, Pa_GetErrorText(err)); } void portaudio_source::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("audio_portaudio_source"); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/portaudio/portaudio_sink.cc0000664000175000017500000003024612207440367023162 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in he hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SINK(REG_PRIO_MED, portaudio)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return sink::sptr (new portaudio_sink(sampling_rate, device_name, ok_to_block)); } //#define LOGGING 0 // define to 0 or 1 #define SAMPLE_FORMAT paFloat32 typedef float sample_t; // Number of portaudio buffers in the ringbuffer static const unsigned int N_BUFFERS = 4; static std::string default_device_name() { return prefs::singleton()->get_string ("audio_portaudio", "default_output_device", ""); } void portaudio_sink::create_ringbuffer(void) { int bufsize_samples = d_portaudio_buffer_size_frames * d_output_parameters.channelCount; if(d_verbose) { fprintf(stderr,"ring buffer size = %d frames\n", N_BUFFERS*bufsize_samples/d_output_parameters.channelCount); } // FYI, the buffer indicies are in units of samples. d_writer = gr::make_buffer(N_BUFFERS * bufsize_samples, sizeof(sample_t)); d_reader = gr::buffer_add_reader(d_writer, 0); } /* * This routine will be called by the PortAudio engine when audio is needed. * It may called at interrupt level on some machines so don't do anything * that could mess up the system like calling malloc() or free(). * * Our job is to write framesPerBuffer frames into outputBuffer. */ int portaudio_sink_callback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *arg) { portaudio_sink *self = (portaudio_sink *)arg; int nreqd_samples = framesPerBuffer * self->d_output_parameters.channelCount; int navail_samples = self->d_reader->items_available(); if(nreqd_samples <= navail_samples) { // We've got enough data... { gr::thread::scoped_lock guard(self->d_ringbuffer_mutex); memcpy(outputBuffer, self->d_reader->read_pointer(), nreqd_samples * sizeof(sample_t)); self->d_reader->update_read_pointer(nreqd_samples); self->d_ringbuffer_ready = true; } // Tell the sink thread there is new room in the ringbuffer. self->d_ringbuffer_cond.notify_one(); return paContinue; } else { // underrun self->d_nunderuns++; ssize_t r = ::write(2, "aU", 2); // FIXME change to non-blocking call if(r == -1) { perror("audio_portaudio_source::portaudio_source_callback write error to stderr."); } // FIXME we should transfer what we've got and pad the rest memset(outputBuffer, 0, nreqd_samples * sizeof(sample_t)); self->d_ringbuffer_ready = true; self->d_ringbuffer_cond.notify_one(); // Tell the sink to get going! return paContinue; } } // ---------------------------------------------------------------- portaudio_sink::portaudio_sink(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_portaudio_sink", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_ok_to_block(ok_to_block), d_verbose(prefs::singleton()->get_bool("audio_portaudio", "verbose", false)), d_portaudio_buffer_size_frames(0), d_stream(0), d_ringbuffer_mutex(), d_ringbuffer_cond(), d_ringbuffer_ready(false), d_nunderuns(0) { memset(&d_output_parameters, 0, sizeof(d_output_parameters)); //if(LOGGING) // d_log = gri_logger::singleton(); PaError err; int i, numDevices; PaDeviceIndex device = 0; const PaDeviceInfo *deviceInfo = NULL; err = Pa_Initialize(); if(err != paNoError) { bail("Initialize failed", err); } if(d_verbose) print_devices(); numDevices = Pa_GetDeviceCount(); if(numDevices < 0) bail("Pa Device count failed", 0); if(numDevices == 0) bail("no devices available", 0); if(d_device_name.empty()) { // FIXME Get smarter about picking something fprintf(stderr,"\nUsing Default Device\n"); device = Pa_GetDefaultOutputDevice(); deviceInfo = Pa_GetDeviceInfo(device); fprintf(stderr,"%s is the chosen device using %s as the host\n", deviceInfo->name, Pa_GetHostApiInfo(deviceInfo->hostApi)->name); } else { bool found = false; fprintf(stderr,"\nTest Devices\n"); for(i = 0; i < numDevices; i++) { deviceInfo = Pa_GetDeviceInfo(i); fprintf(stderr,"Testing device name: %s",deviceInfo->name); if(deviceInfo->maxOutputChannels <= 0) { fprintf(stderr,"\n"); continue; } if(strstr(deviceInfo->name, d_device_name.c_str())) { fprintf(stderr," Chosen!\n"); device = i; fprintf(stderr,"%s using %s as the host\n",d_device_name.c_str(), Pa_GetHostApiInfo(deviceInfo->hostApi)->name), fflush(stderr); found = true; deviceInfo = Pa_GetDeviceInfo(device); i = numDevices; // force loop exit } else fprintf(stderr,"\n"), fflush(stderr); } if(!found) { bail("Failed to find specified device name", 0); exit(1); } } d_output_parameters.device = device; d_output_parameters.channelCount = deviceInfo->maxOutputChannels; d_output_parameters.sampleFormat = SAMPLE_FORMAT; d_output_parameters.suggestedLatency = deviceInfo->defaultLowOutputLatency; d_output_parameters.hostApiSpecificStreamInfo = NULL; // We fill in the real channelCount in check_topology when we know // how many inputs are connected to us. // Now that we know the maximum number of channels (allegedly) // supported by the h/w, we can compute a reasonable input // signature. The portaudio specs say that they'll accept any // number of channels from 1 to max. set_input_signature(io_signature::make(1, deviceInfo->maxOutputChannels, sizeof(sample_t))); } bool portaudio_sink::check_topology(int ninputs, int noutputs) { PaError err; if(Pa_IsStreamActive(d_stream)) { Pa_CloseStream(d_stream); d_stream = 0; d_reader.reset(); // boost::shared_ptr for d_reader = 0 d_writer.reset(); // boost::shared_ptr for d_write = 0 } d_output_parameters.channelCount = ninputs; // # of channels we're really using #if 1 d_portaudio_buffer_size_frames = (int)(0.0213333333 * d_sampling_rate + 0.5); // Force 1024 frame buffers at 48000 fprintf(stderr, "Latency = %8.5f, requested sampling_rate = %g\n", // Force latency to 21.3333333.. ms 0.0213333333, (double)d_sampling_rate); #endif err = Pa_OpenStream(&d_stream, NULL, // No input &d_output_parameters, d_sampling_rate, d_portaudio_buffer_size_frames, paClipOff, &portaudio_sink_callback, (void*)this); if(err != paNoError) { output_error_msg("OpenStream failed", err); return false; } #if 0 const PaStreamInfo *psi = Pa_GetStreamInfo(d_stream); d_portaudio_buffer_size_frames = (int)(d_output_parameters.suggestedLatency * psi->sampleRate); fprintf(stderr, "Latency = %7.4f, psi->sampleRate = %g\n", d_output_parameters.suggestedLatency, psi->sampleRate); #endif fprintf(stderr, "d_portaudio_buffer_size_frames = %d\n", d_portaudio_buffer_size_frames); assert(d_portaudio_buffer_size_frames != 0); create_ringbuffer(); err = Pa_StartStream(d_stream); if(err != paNoError) { output_error_msg("StartStream failed", err); return false; } return true; } portaudio_sink::~portaudio_sink() { Pa_StopStream(d_stream); // wait for output to drain Pa_CloseStream(d_stream); Pa_Terminate(); } /* * This version consumes everything sent to it, blocking if required. * I think this will allow us better control of the total buffering/latency * in the audio path. */ int portaudio_sink::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float **in = (const float **)&input_items[0]; const unsigned nchan = d_output_parameters.channelCount; // # of channels == samples/frame int k; for(k = 0; k < noutput_items;) { int nframes = d_writer->space_available() / nchan; // How much space in ringbuffer if(nframes == 0) { // no room... if(d_ok_to_block) { { gr::thread::scoped_lock guard(d_ringbuffer_mutex); while(!d_ringbuffer_ready) d_ringbuffer_cond.wait(guard); } continue; } else { // There's no room and we're not allowed to block. // (A USRP is most likely controlling the pacing through the pipeline.) // We drop the samples on the ground, and say we processed them all ;) // // FIXME, there's probably room for a bit more finesse here. return noutput_items; } } // We can write the smaller of the request and the room we've got { gr::thread::scoped_lock guard(d_ringbuffer_mutex); int nf = std::min(noutput_items - k, nframes); float *p = (float*)d_writer->write_pointer(); for(int i = 0; i < nf; i++) { for(unsigned int c = 0; c < nchan; c++) { *p++ = in[c][k + i]; } } d_writer->update_write_pointer(nf * nchan); k += nf; d_ringbuffer_ready = false; } } return k; // tell how many we actually did } void portaudio_sink::output_error_msg(const char *msg, int err) { fprintf(stderr, "audio_portaudio_sink[%s]: %s: %s\n", d_device_name.c_str(), msg, Pa_GetErrorText(err)); } void portaudio_sink::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("audio_portaudio_sink"); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/windows/0000775000175000017500000000000012207440367017300 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/windows/windows_source.h0000664000175000017500000000341012207440367022521 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_WINDOWS_SOURCE_H #define INCLUDED_AUDIO_WINDOWS_SOURCE_H #include #include namespace gr { namespace audio { /*! * \brief audio source using winmm mmsystem (win32 only) * \ingroup audio_blk * * Output signature is one or two streams of floats. * Output samples will be in the range [-1,1]. */ class windows_source : public source { int d_sampling_freq; std::string d_device_name; int d_fd; short *d_buffer; int d_chunk_size; public: windows_source(int sampling_freq, const std::string device_name = ""); ~windows_source(); int work(int noutput_items, gr_vector_const_void_star & input_items, gr_vector_void_star & output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_WINDOWS_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/lib/windows/windows_sink.cc0000664000175000017500000002506412207440367022334 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SINK(REG_PRIO_HIGH, windows)(int sampling_rate, const std::string &device_name, bool) { return sink::sptr (new windows_sink(sampling_rate, device_name)); } static const double CHUNK_TIME = 0.1; //0.001; // 100 ms // FIXME these should query some kind of user preference static std::string default_device_name() { return "WAVE_MAPPER"; } windows_sink::windows_sink(int sampling_freq, const std::string device_name) : sync_block("audio_windows_sink", io_signature::make(1, 2, sizeof(float)), io_signature::make(0, 0, 0)), d_sampling_freq(sampling_freq), d_device_name(device_name.empty() ? default_device_name() : device_name), d_fd(-1), d_buffer(0), d_chunk_size(0) { d_wave_write_event = CreateEvent(NULL, FALSE, FALSE, NULL); if(open_waveout_device() < 0) { //fprintf(stderr, "audio_windows_sink:open_waveout_device() failed\n"); perror("audio_windows_sink:open_waveout_device() failed\n"); throw std::runtime_error ("audio_windows_sink:open_waveout_device() failed"); } d_chunk_size = (int)(d_sampling_freq * CHUNK_TIME); set_output_multiple(d_chunk_size); d_buffer = new short[d_chunk_size * 2]; } windows_sink::~windows_sink() { /* Free the callback Event */ CloseHandle(d_wave_write_event); waveOutClose(d_h_waveout); delete [] d_buffer; } int windows_sink::work(int noutput_items, gr_vector_const_void_star & input_items, gr_vector_void_star & output_items) { const float *f0, *f1; bool playtestsound = false; if(playtestsound) { // dummy f0 = (const float*)input_items[0]; for(int i = 0; i < noutput_items; i += d_chunk_size) { for(int j = 0; j < d_chunk_size; j++) { d_buffer[2*j + 0] = (short)(sin(2.0 * 3.1415926535897932384626 * (float)j * 1000.0 / (float)d_sampling_freq) * 8192 + 0); //+32767 d_buffer[2*j + 1] = d_buffer[2*j + 0]; } f0 += d_chunk_size; if(write_waveout ((HPSTR)d_buffer, 2*d_chunk_size * sizeof(short)) < 0) { fprintf(stderr, "audio_windows_sink: write failed\n"); perror("audio_windows_sink: write failed"); } } // break; } else { switch(input_items.size ()) { case 1: // mono input f0 = (const float*)input_items[0]; for(int i = 0; i < noutput_items; i += d_chunk_size) { for(int j = 0; j < d_chunk_size; j++) { d_buffer[2*j + 0] = (short)(f0[j] * 32767); d_buffer[2*j + 1] = (short)(f0[j] * 32767); } f0 += d_chunk_size; if(write_waveout ((HPSTR)d_buffer, 2*d_chunk_size * sizeof(short)) < 0) { //fprintf(stderr, "audio_windows_sink: write failed\n"); perror("audio_windows_sink: write failed"); } } break; case 2: // stereo input f0 = (const float*)input_items[0]; f1 = (const float*)input_items[1]; for(int i = 0; i < noutput_items; i += d_chunk_size) { for(int j = 0; j < d_chunk_size; j++) { d_buffer[2*j + 0] = (short)(f0[j] * 32767); d_buffer[2*j + 1] = (short)(f1[j] * 32767); } f0 += d_chunk_size; f1 += d_chunk_size; if(write_waveout ((HPSTR)d_buffer, 2*d_chunk_size * sizeof(short)) < 0) { //fprintf(stderr, "audio_windows_sink: write failed\n"); perror("audio_windows_sink: write failed"); } } break; } } return noutput_items; } int windows_sink::string_to_int(const std::string & s) { int i; std::istringstream (s) >> i; return i; } //ToInt() int windows_sink::open_waveout_device(void) { UINT /*UINT_PTR */ u_device_id; /** Identifier of the waveform-audio output device to open. It can be either a device identifier or a handle of an open waveform-audio input device. You can use the following flag instead of a device identifier. * * Value Meaning * WAVE_MAPPER The function selects a waveform-audio output * device capable of playing the given format. */ if(d_device_name.empty () || default_device_name () == d_device_name) u_device_id = WAVE_MAPPER; else u_device_id = (UINT) string_to_int (d_device_name); // Open a waveform device for output using event callback. unsigned long result; //HWAVEOUT outHandle; WAVEFORMATEX wave_format; /* Initialize the WAVEFORMATEX for 16-bit, 44KHz, stereo */ wave_format.wFormatTag = WAVE_FORMAT_PCM; wave_format.nChannels = 2; wave_format.nSamplesPerSec = d_sampling_freq; //44100; wave_format.wBitsPerSample = 16; wave_format.nBlockAlign = wave_format.nChannels * (wave_format.wBitsPerSample / 8); wave_format.nAvgBytesPerSec = wave_format.nSamplesPerSec * wave_format.nBlockAlign; wave_format.cbSize = 0; /* Open the (preferred) Digital Audio Out device. */ result = waveOutOpen(&d_h_waveout, WAVE_MAPPER, &wave_format, (DWORD_PTR)d_wave_write_event, 0, CALLBACK_EVENT | WAVE_ALLOWSYNC); //|WAVE_FORMAT_DIRECT | CALLBACK_EVENT| WAVE_ALLOWSYNC if(result) { //fprintf(stderr, "audio_windows_sink: Failed to open waveform output device.\n"); perror("audio_windows_sink: Failed to open waveform output device."); //LocalUnlock(hFormat); //LocalFree(hFormat); //mmioClose(hmmio, 0); return -1; } // // Do not Swallow the "open" event. // //WaitForSingleObject(d_wave_write_event, INFINITE); // Allocate and lock memory for the header. d_h_wave_hdr = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, (DWORD)sizeof(WAVEHDR)); if(d_h_wave_hdr == NULL) { //GlobalUnlock(hData); //GlobalFree(hData); //fprintf(stderr, "audio_windows_sink: Not enough memory for header.\n"); perror("audio_windows_sink: Not enough memory for header."); return -1; } d_lp_wave_hdr = (LPWAVEHDR)GlobalLock(d_h_wave_hdr); if(d_lp_wave_hdr == NULL) { //GlobalUnlock(hData); //GlobalFree(hData); //fprintf(stderr, "audio_windows_sink: Failed to lock memory for header.\n"); perror("audio_windows_sink: Failed to lock memory for header."); return -1; } //d_lp_wave_hdr->dwFlags = WHDR_DONE; return 0; } int windows_sink::write_waveout(HPSTR lp_data, DWORD dw_data_size) { UINT w_result; int teller = 100; // After allocation, set up and prepare header. /*while ((d_lp_wave_hdr->dwFlags & WHDR_DONE)==0 && teller>0) { teller--; Sleep(1); } */ // Wait until previous wave write completes (first event is the open event). WaitForSingleObject(d_wave_write_event, 100); // INFINITE d_lp_wave_hdr->lpData = lp_data; d_lp_wave_hdr->dwBufferLength = dw_data_size; d_lp_wave_hdr->dwFlags = 0L; /* Clear the WHDR_DONE bit (which the driver set last time that this WAVEHDR was sent via waveOutWrite and was played). Some drivers need this to be cleared */ //d_lp_wave_hdr->dwFlags &= ~WHDR_DONE; d_lp_wave_hdr->dwLoops = 0L; w_result = waveOutPrepareHeader(d_h_waveout, d_lp_wave_hdr, sizeof(WAVEHDR)); if(w_result != 0) { //GlobalUnlock(hData); //GlobalFree(hData); //fprintf(stderr, "audio_windows_sink: Failed to waveOutPrepareHeader. error %i\n",w_result); perror("audio_windows_sink: Failed to waveOutPrepareHeader"); } // Now the data block can be sent to the output device. The // waveOutWrite function returns immediately and waveform // data is sent to the output device in the background. //while(!readyforplayback) Sleep(1); //readyforplayback=false; w_result = waveOutWrite(d_h_waveout, d_lp_wave_hdr, sizeof(WAVEHDR)); if(w_result != 0) { //GlobalUnlock(hData); //GlobalFree(hData); //fprintf(stderr, "audio_windows_sink: Failed to write block to device.error %i\n",w_result); perror("audio_windows_sink: Failed to write block to device"); switch(w_result) { case MMSYSERR_INVALHANDLE: fprintf(stderr, "Specified device handle is invalid.\n"); break; case MMSYSERR_NODRIVER: fprintf(stderr, " No device driver is present.\n"); break; case MMSYSERR_NOMEM: fprintf(stderr, " Unable to allocate or lock memory.\n"); break; case WAVERR_UNPREPARED: fprintf(stderr, " The data block pointed to by the pwh parameter hasn't been prepared.\n"); break; default: fprintf(stderr, "Unknown error %i\n", w_result); } waveOutUnprepareHeader(d_h_waveout, d_lp_wave_hdr, sizeof(WAVEHDR)); return -1; } //WaitForSingleObject(d_wave_write_event, INFINITE); return 0; } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/windows/windows_source.cc0000664000175000017500000001354012207440367022664 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include //include //include #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SOURCE(REG_PRIO_HIGH, windows)(int sampling_rate, const std::string &device_name, bool) { return source::sptr (new windows_source(sampling_rate, device_name)); } static const double CHUNK_TIME = 0.005; // 5 ms // FIXME these should query some kind of user preference static std::string default_device_name() { return "/dev/dsp"; } windows_source::windows_source(int sampling_freq, const std::string device_name) : sync_block("audio_windows_source", io_signature::make(0, 0, 0), io_signature::make(1, 2, sizeof(float))), d_sampling_freq(sampling_freq), d_device_name(device_name.empty() ? default_device_name() : device_name), d_fd(-1), d_buffer(0), d_chunk_size(0) { //FIXME TODO implement me #if 0 if((d_fd = open(d_device_name.c_str(), O_RDONLY)) < 0) { fprintf(stderr, "audio_windows_source: "); perror(d_device_name.c_str()); throw std::runtime_error("audio_windows_source"); } d_chunk_size = (int)(d_sampling_freq * CHUNK_TIME); set_output_multiple(d_chunk_size); d_buffer = new short[d_chunk_size * 2]; int format = AFMT_S16_NE; int orig_format = format; if(ioctl(d_fd, SNDCTL_DSP_SETFMT, &format) < 0) { std::cerr << "audio_windows_source: " << d_device_name << " ioctl failed\n"; perror(d_device_name.c_str()); throw std::runtime_error("audio_windows_source"); } if(format != orig_format) { fprintf(stderr, "audio_windows_source: unable to support format %d\n", orig_format); fprintf(stderr, " card requested %d instead.\n", format); } // set to stereo no matter what. Some hardware only does stereo int channels = 2; if(ioctl(d_fd, SNDCTL_DSP_CHANNELS, &channels) < 0 || channels != 2) { perror("audio_windows_source: could not set STEREO mode"); throw std::runtime_error("audio_windows_source"); } // set sampling freq int sf = sampling_freq; if(ioctl(d_fd, SNDCTL_DSP_SPEED, &sf) < 0) { std::cerr << "audio_windows_source: " << d_device_name << ": invalid sampling_freq " << sampling_freq << "\n"; sampling_freq = 8000; if(ioctl(d_fd, SNDCTL_DSP_SPEED, &sf) < 0) { std::cerr << "audio_windows_source: failed to set sampling_freq to 8000\n"; throw std::runtime_error ("audio_windows_source"); } } #endif } windows_source::~windows_source() { /*close(d_fd); delete [] d_buffer; */ } int windows_source::work(int noutput_items, gr_vector_const_void_star & input_items, gr_vector_void_star & output_items) { //FIXME TODO implement me #if 0 float *f0 = (float*)output_items[0]; float *f1 = (float*)output_items[1]; // will be invalid if this is mono output const int shorts_per_item = 2; // L + R const int bytes_per_item = shorts_per_item * sizeof(short); // To minimize latency, never return more than CHUNK_TIME // worth of samples per call to work. // FIXME, we need an API to set this value noutput_items = std::min(noutput_items, d_chunk_size); int base = 0; int ntogo = noutput_items; while(ntogo > 0) { int nbytes = std::min(ntogo, d_chunk_size) * bytes_per_item; int result_nbytes = read(d_fd, d_buffer, nbytes); if(result_nbytes < 0) { perror("audio_windows_source"); return -1; // say we're done } if((result_nbytes & (bytes_per_item - 1)) != 0) { fprintf(stderr, "audio_windows_source: internal error.\n"); throw std::runtime_error("internal error"); } int result_nitems = result_nbytes / bytes_per_item; // now unpack samples into output streams switch(output_items.size()) { case 1: // mono output for(int i = 0; i < result_nitems; i++) { f0[base + i] = d_buffer[2 * i + 0] * (1.0 / 32767); } break; case 2: // stereo output for(int i = 0; i < result_nitems; i++) { f0[base + i] = d_buffer[2 * i + 0] * (1.0 / 32767); f1[base + i] = d_buffer[2 * i + 1] * (1.0 / 32767); } break; default: assert(0); } ntogo -= result_nitems; base += result_nitems; } return noutput_items - ntogo; #endif return -1; // EOF } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/windows/windows_sink.h0000664000175000017500000000424412207440367022173 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_WINDOWS_SINK_H #define INCLUDED_AUDIO_WINDOWS_SINK_H #define WIN32_LEAN_AND_MEAN #define NOMINMAX // stops windef.h defining max/min under cygwin #include #include #include #include namespace gr { namespace audio { /*! * \brief audio sink using winmm mmsystem (win32 only) * \ingroup audio_blk * * input signature is one or two streams of floats. * Input samples must be in the range [-1,1]. */ class windows_sink : public sink { int d_sampling_freq; std::string d_device_name; int d_fd; short *d_buffer; int d_chunk_size; HWAVEOUT d_h_waveout; HGLOBAL d_h_wave_hdr; LPWAVEHDR d_lp_wave_hdr; HANDLE d_wave_write_event; protected: int string_to_int(const std::string & s); int open_waveout_device(void); int write_waveout(HPSTR lp_data, DWORD dw_data_size); public: windows_sink(int sampling_freq, const std::string device_name = ""); ~windows_sink(); int work(int noutput_items, gr_vector_const_void_star & input_items, gr_vector_void_star & output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_WINDOWS_SINK_H */ gnuradio-3.7.2.1/gr-audio/lib/gnuradio-audio.rc.in0000664000175000017500000000332212207440367021450 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-audio" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-audio.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-audio.dll" VALUE "ProductName", "gnuradio-audio" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-audio/lib/gr-audio.conf0000644000175000017500000000063611700377700020164 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf # specify which audio module to load, or use "auto" to have the system # select one. Valid choices depend on your OS and which modules # you've installed, but typically include: # auto, alsa, oss, portaudio, jack, osx, windows [audio] audio_module = auto gnuradio-3.7.2.1/gr-audio/lib/alsa/0000755000175000017500000000000012207440367016524 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/alsa/alsa_source.cc0000664000175000017500000004274312207440367021347 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SOURCE(REG_PRIO_HIGH, alsa)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return source::sptr (new alsa_source(sampling_rate, device_name, ok_to_block)); } static bool CHATTY_DEBUG = false; static snd_pcm_format_t acceptable_formats[] = { // these are in our preferred order... SND_PCM_FORMAT_S32, SND_PCM_FORMAT_S16 }; #define NELEMS(x) (sizeof(x)/sizeof(x[0])) static std::string default_device_name() { return prefs::singleton()->get_string("audio_alsa", "default_input_device", "default"); } static double default_period_time() { return std::max(0.001, prefs::singleton()->get_double("audio_alsa", "period_time", 0.010)); } static int default_nperiods() { return std::max(2L, prefs::singleton()->get_long("audio_alsa", "nperiods", 4)); } // ---------------------------------------------------------------- alsa_source::alsa_source(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_alsa_source", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_pcm_handle(0), d_hw_params((snd_pcm_hw_params_t*)(new char[snd_pcm_hw_params_sizeof()])), d_sw_params((snd_pcm_sw_params_t*)(new char[snd_pcm_sw_params_sizeof()])), d_nperiods(default_nperiods()), d_period_time_us((unsigned int)(default_period_time() * 1e6)), d_period_size(0), d_buffer_size_bytes(0), d_buffer(0), d_worker(0), d_hw_nchan(0), d_special_case_stereo_to_mono(false), d_noverruns(0), d_nsuspends(0) { CHATTY_DEBUG = prefs::singleton()->get_bool("audio_alsa", "verbose", false); int error; int dir; // open the device for capture error = snd_pcm_open(&d_pcm_handle, d_device_name.c_str(), SND_PCM_STREAM_CAPTURE, 0); if(error < 0){ fprintf(stderr, "audio_alsa_source[%s]: %s\n", d_device_name.c_str(), snd_strerror(error)); throw std::runtime_error("audio_alsa_source"); } // Fill params with a full configuration space for a PCM. error = snd_pcm_hw_params_any(d_pcm_handle, d_hw_params); if(error < 0) bail("broken configuration for playback", error); if(CHATTY_DEBUG) gri_alsa_dump_hw_params(d_pcm_handle, d_hw_params, stdout); // now that we know how many channels the h/w can handle, set output signature unsigned int umax_chan; unsigned int umin_chan; snd_pcm_hw_params_get_channels_min(d_hw_params, &umin_chan); snd_pcm_hw_params_get_channels_max(d_hw_params, &umax_chan); int min_chan = std::min(umin_chan, 1000U); int max_chan = std::min(umax_chan, 1000U); // As a special case, if the hw's min_chan is two, we'll accept // a single output and handle the demux ourselves. if(min_chan == 2) { min_chan = 1; d_special_case_stereo_to_mono = true; } set_output_signature(io_signature::make(min_chan, max_chan, sizeof(float))); // fill in portions of the d_hw_params that we know now... // Specify the access methods we implement // For now, we only handle RW_INTERLEAVED... snd_pcm_access_mask_t *access_mask; snd_pcm_access_mask_t **access_mask_ptr = &access_mask; // FIXME: workaround for compiler warning snd_pcm_access_mask_alloca(access_mask_ptr); snd_pcm_access_mask_none(access_mask); snd_pcm_access_mask_set(access_mask, SND_PCM_ACCESS_RW_INTERLEAVED); // snd_pcm_access_mask_set(access_mask, SND_PCM_ACCESS_RW_NONINTERLEAVED); if((error = snd_pcm_hw_params_set_access_mask(d_pcm_handle, d_hw_params, access_mask)) < 0) bail("failed to set access mask", error); // set sample format if(!gri_alsa_pick_acceptable_format(d_pcm_handle, d_hw_params, acceptable_formats, NELEMS(acceptable_formats), &d_format, "audio_alsa_source", CHATTY_DEBUG)) throw std::runtime_error("audio_alsa_source"); // sampling rate unsigned int orig_sampling_rate = d_sampling_rate; if((error = snd_pcm_hw_params_set_rate_near(d_pcm_handle, d_hw_params, &d_sampling_rate, 0)) < 0) bail("failed to set rate near", error); if(orig_sampling_rate != d_sampling_rate){ fprintf(stderr, "audio_alsa_source[%s]: unable to support sampling rate %d\n", snd_pcm_name (d_pcm_handle), orig_sampling_rate); fprintf(stderr, " card requested %d instead.\n", d_sampling_rate); } /* * ALSA transfers data in units of "periods". * We indirectly determine the underlying buffersize by specifying * the number of periods we want (typically 4) and the length of each * period in units of time (typically 1ms). */ unsigned int min_nperiods, max_nperiods; snd_pcm_hw_params_get_periods_min(d_hw_params, &min_nperiods, &dir); snd_pcm_hw_params_get_periods_max(d_hw_params, &max_nperiods, &dir); //fprintf (stderr, "alsa_source: min_nperiods = %d, max_nperiods = %d\n", // min_nperiods, max_nperiods); unsigned int orig_nperiods = d_nperiods; d_nperiods = std::min(std::max (min_nperiods, d_nperiods), max_nperiods); // adjust period time so that total buffering remains more-or-less constant d_period_time_us = (d_period_time_us * orig_nperiods) / d_nperiods; error = snd_pcm_hw_params_set_periods(d_pcm_handle, d_hw_params, d_nperiods, 0); if(error < 0) bail("set_periods failed", error); dir = 0; error = snd_pcm_hw_params_set_period_time_near(d_pcm_handle, d_hw_params, &d_period_time_us, &dir); if(error < 0) bail("set_period_time_near failed", error); dir = 0; error = snd_pcm_hw_params_get_period_size(d_hw_params, &d_period_size, &dir); if(error < 0) bail("get_period_size failed", error); set_output_multiple(d_period_size); } bool alsa_source::check_topology(int ninputs, int noutputs) { // noutputs is how many channels the user has connected. // Now we can finish up setting up the hw params... unsigned int nchan = noutputs; int err; // Check the state of the stream // Ensure that the pcm is in a state where we can still mess with the hw_params snd_pcm_state_t state; state=snd_pcm_state(d_pcm_handle); if(state== SND_PCM_STATE_RUNNING) return true; // If stream is running, don't change any parameters else if(state == SND_PCM_STATE_XRUN) snd_pcm_prepare(d_pcm_handle); // Prepare stream on underrun, and we can set parameters; bool special_case = nchan == 1 && d_special_case_stereo_to_mono; if(special_case) nchan = 2; d_hw_nchan = nchan; err = snd_pcm_hw_params_set_channels(d_pcm_handle, d_hw_params, d_hw_nchan); if(err < 0) { output_error_msg("set_channels failed", err); return false; } // set the parameters into the driver... err = snd_pcm_hw_params(d_pcm_handle, d_hw_params); if(err < 0) { output_error_msg("snd_pcm_hw_params failed", err); return false; } d_buffer_size_bytes = d_period_size * d_hw_nchan * snd_pcm_format_size(d_format, 1); d_buffer = new char[d_buffer_size_bytes]; if(CHATTY_DEBUG) { fprintf(stdout, "audio_alsa_source[%s]: sample resolution = %d bits\n", snd_pcm_name(d_pcm_handle), snd_pcm_hw_params_get_sbits(d_hw_params)); } switch(d_format) { case SND_PCM_FORMAT_S16: if(special_case) d_worker = &alsa_source::work_s16_2x1; else d_worker = &alsa_source::work_s16; break; case SND_PCM_FORMAT_S32: if(special_case) d_worker = &alsa_source::work_s32_2x1; else d_worker = &alsa_source::work_s32; break; default: assert(0); } return true; } alsa_source::~alsa_source() { if(snd_pcm_state(d_pcm_handle) == SND_PCM_STATE_RUNNING) snd_pcm_drop(d_pcm_handle); snd_pcm_close(d_pcm_handle); delete [] ((char*)d_hw_params); delete [] ((char*)d_sw_params); delete [] d_buffer; } int alsa_source::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { assert((noutput_items % d_period_size) == 0); assert(noutput_items != 0); // this is a call through a pointer to a method... return (this->*d_worker)(noutput_items, input_items, output_items); } /* * Work function that deals with float to S16 conversion */ int alsa_source::work_s16(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int16 sample_t; // the type of samples we're creating static const float scale_factor = 1.0 / std::pow(2.0f, 16-1); unsigned int nchan = output_items.size (); float **out = (float **)&output_items[0]; sample_t *buf = (sample_t *)d_buffer; int bi; unsigned int sizeof_frame = d_hw_nchan * sizeof (sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); // To minimize latency, return at most a single period's worth of samples. // [We could also read the first one in a blocking mode and subsequent // ones in non-blocking mode, but we'll leave that for later (or never).] if(!read_buffer(buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { for(unsigned int chan = 0; chan < nchan; chan++) { out[chan][i] = (float) buf[bi++] * scale_factor; } } return d_period_size; } /* * Work function that deals with float to S16 conversion * and stereo to mono kludge... */ int alsa_source::work_s16_2x1(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int16 sample_t; // the type of samples we're creating static const float scale_factor = 1.0 / std::pow(2.0f, 16-1); float **out = (float**)&output_items[0]; sample_t *buf = (sample_t*)d_buffer; int bi; assert(output_items.size () == 1); unsigned int sizeof_frame = d_hw_nchan * sizeof(sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); // To minimize latency, return at most a single period's worth of samples. // [We could also read the first one in a blocking mode and subsequent // ones in non-blocking mode, but we'll leave that for later (or never).] if(!read_buffer (buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { int t = (buf[bi] + buf[bi+1]) / 2; bi += 2; out[0][i] = (float) t * scale_factor; } return d_period_size; } /* * Work function that deals with float to S32 conversion */ int alsa_source::work_s32(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int32 sample_t; // the type of samples we're creating static const float scale_factor = 1.0 / std::pow(2.0f, 32-1); unsigned int nchan = output_items.size (); float **out = (float**)&output_items[0]; sample_t *buf = (sample_t*)d_buffer; int bi; unsigned int sizeof_frame = d_hw_nchan * sizeof(sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); // To minimize latency, return at most a single period's worth of samples. // [We could also read the first one in a blocking mode and subsequent // ones in non-blocking mode, but we'll leave that for later (or never).] if(!read_buffer(buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { for(unsigned int chan = 0; chan < nchan; chan++) { out[chan][i] = (float) buf[bi++] * scale_factor; } } return d_period_size; } /* * Work function that deals with float to S32 conversion * and stereo to mono kludge... */ int alsa_source::work_s32_2x1(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int32 sample_t; // the type of samples we're creating static const float scale_factor = 1.0 / std::pow(2.0f, 32-1); float **out = (float**)&output_items[0]; sample_t *buf = (sample_t*)d_buffer; int bi; assert(output_items.size () == 1); unsigned int sizeof_frame = d_hw_nchan * sizeof(sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); // To minimize latency, return at most a single period's worth of samples. // [We could also read the first one in a blocking mode and subsequent // ones in non-blocking mode, but we'll leave that for later (or never).] if(!read_buffer(buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { int t = (buf[bi] + buf[bi+1]) / 2; bi += 2; out[0][i] = (float)t * scale_factor; } return d_period_size; } bool alsa_source::read_buffer(void *vbuffer, unsigned nframes, unsigned sizeof_frame) { unsigned char *buffer = (unsigned char*)vbuffer; while(nframes > 0) { int r = snd_pcm_readi (d_pcm_handle, buffer, nframes); if(r == -EAGAIN) continue; // try again else if(r == -EPIPE) { // overrun d_noverruns++; fputs("aO", stderr); if((r = snd_pcm_prepare (d_pcm_handle)) < 0) { output_error_msg("snd_pcm_prepare failed. Can't recover from overrun", r); return false; } continue; // try again } else if(r == -ESTRPIPE) { // h/w is suspended (whatever that means) // This is apparently related to power management d_nsuspends++; if((r = snd_pcm_resume (d_pcm_handle)) < 0) { output_error_msg ("failed to resume from suspend", r); return false; } continue; // try again } else if(r < 0) { output_error_msg("snd_pcm_readi failed", r); return false; } nframes -= r; buffer += r * sizeof_frame; } return true; } void alsa_source::output_error_msg(const char *msg, int err) { fprintf(stderr, "audio_alsa_source[%s]: %s: %s\n", snd_pcm_name(d_pcm_handle), msg, snd_strerror (err)); } void alsa_source::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("audio_alsa_source"); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/alsa/gr-audio-alsa.conf0000664000175000017500000000055312207440367022025 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [audio_alsa] default_input_device = default default_output_device = default period_time = 0.010 # in seconds nperiods = 4 # total buffering = period_time * nperiods verbose = false gnuradio-3.7.2.1/gr-audio/lib/alsa/alsa_source.h0000664000175000017500000000755012207440367021206 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_ALSA_SOURCE_H #define INCLUDED_AUDIO_ALSA_SOURCE_H // use new ALSA API #define ALSA_PCM_NEW_HW_PARAMS_API #define ALSA_PCM_NEW_SW_PARAMS_API #include #include #include #include namespace gr { namespace audio { class alsa_source; typedef boost::shared_ptr alsa_source_sptr; /*! * \brief audio source using ALSA * \ingroup audio_blk * * The source has between 1 and N input streams of floats, where N is * depends on the hardware characteristics of the selected device. * * Output samples will be in the range [-1,1]. */ class alsa_source : public source { // typedef for pointer to class work method typedef int(alsa_source::*work_t)(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int d_sampling_rate; std::string d_device_name; snd_pcm_t *d_pcm_handle; snd_pcm_hw_params_t *d_hw_params; snd_pcm_sw_params_t *d_sw_params; snd_pcm_format_t d_format; unsigned int d_nperiods; unsigned int d_period_time_us; // microseconds snd_pcm_uframes_t d_period_size; // in frames unsigned int d_buffer_size_bytes; // sizeof of d_buffer char *d_buffer; work_t d_worker; // the work method to use unsigned int d_hw_nchan; // # of configured h/w channels bool d_special_case_stereo_to_mono; // random stats int d_noverruns; // count of overruns int d_nsuspends; // count of suspends void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); public: alsa_source(int sampling_rate, const std::string device_name, bool ok_to_block); ~alsa_source(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); protected: bool read_buffer(void *buffer, unsigned nframes, unsigned sizeof_frame); int work_s16(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work_s16_2x1(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work_s32(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work_s32_2x1(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_ALSA_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/lib/alsa/alsa_impl.h0000664000175000017500000000245212207440367020643 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_ALSA_IMPL_H #define INCLUDED_ALSA_IMPL_H #include #include void gri_alsa_dump_hw_params (snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams, FILE *fp); bool gri_alsa_pick_acceptable_format (snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams, snd_pcm_format_t acceptable_formats[], unsigned nacceptable_formats, snd_pcm_format_t *selected_format, const char *error_msg_tag, bool verbose); #endif /* INCLUDED_GRI_ALSA_H */ gnuradio-3.7.2.1/gr-audio/lib/alsa/alsa_sink.h0000664000175000017500000000737012207440367020652 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_ALSA_SINK_H #define INCLUDED_AUDIO_ALSA_SINK_H // use new ALSA API #define ALSA_PCM_NEW_HW_PARAMS_API #define ALSA_PCM_NEW_SW_PARAMS_API #include #include #include #include namespace gr { namespace audio { /*! * \brief audio sink using ALSA * \ingroup audio_blk * * The sink has N input streams of floats, where N depends * on the hardware characteristics of the selected device. * * Input samples must be in the range [-1,1]. */ class alsa_sink : public sink { // typedef for pointer to class work method typedef int(alsa_sink::*work_t)(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int d_sampling_rate; std::string d_device_name; snd_pcm_t *d_pcm_handle; snd_pcm_hw_params_t *d_hw_params; snd_pcm_sw_params_t *d_sw_params; snd_pcm_format_t d_format; unsigned int d_nperiods; unsigned int d_period_time_us; // microseconds snd_pcm_uframes_t d_period_size; // in frames unsigned int d_buffer_size_bytes; // sizeof of d_buffer char *d_buffer; work_t d_worker; // the work method to use bool d_special_case_mono_to_stereo; // random stats int d_nunderuns; // count of underruns int d_nsuspends; // count of suspends bool d_ok_to_block; // defaults to "true", controls blocking/non-block I/O void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); public: alsa_sink(int sampling_rate, const std::string device_name, bool ok_to_block); ~alsa_sink(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); protected: bool write_buffer(const void *buffer, unsigned nframes, unsigned sizeof_frame); int work_s16(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work_s16_1x2(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work_s32(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work_s32_1x2(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_ALSA_SINK_H */ gnuradio-3.7.2.1/gr-audio/lib/alsa/alsa_sink.cc0000664000175000017500000004422512207440367021010 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SINK(REG_PRIO_HIGH, alsa)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return sink::sptr (new alsa_sink(sampling_rate, device_name, ok_to_block)); } static bool CHATTY_DEBUG = false; static snd_pcm_format_t acceptable_formats[] = { // these are in our preferred order... SND_PCM_FORMAT_S32, SND_PCM_FORMAT_S16 }; #define NELEMS(x) (sizeof(x)/sizeof(x[0])) static std::string default_device_name() { return prefs::singleton()->get_string("audio_alsa", "default_output_device", "default"); } static double default_period_time() { return std::max(0.001, prefs::singleton()->get_double("audio_alsa", "period_time", 0.010)); } static int default_nperiods() { return std::max(2L, prefs::singleton()->get_long("audio_alsa", "nperiods", 4)); } // ---------------------------------------------------------------- alsa_sink::alsa_sink(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_alsa_sink", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_pcm_handle(0), d_hw_params((snd_pcm_hw_params_t*)(new char[snd_pcm_hw_params_sizeof()])), d_sw_params((snd_pcm_sw_params_t*)(new char[snd_pcm_sw_params_sizeof()])), d_nperiods(default_nperiods()), d_period_time_us((unsigned int)(default_period_time() * 1e6)), d_period_size(0), d_buffer_size_bytes(0), d_buffer(0), d_worker(0), d_special_case_mono_to_stereo(false), d_nunderuns(0), d_nsuspends(0), d_ok_to_block(ok_to_block) { CHATTY_DEBUG = prefs::singleton()->get_bool("audio_alsa", "verbose", false); int error=-1; int dir; // open the device for playback int attempts = 10; while((error!=0)&&(attempts-->0)){ error = snd_pcm_open(&d_pcm_handle, d_device_name.c_str(), SND_PCM_STREAM_PLAYBACK, 0); if(error<0){ boost::this_thread::sleep( boost::posix_time::milliseconds(10)); } } if(ok_to_block == false) snd_pcm_nonblock(d_pcm_handle, !ok_to_block); if(error < 0){ fprintf(stderr, "audio_alsa_sink[%s]: %s\n", d_device_name.c_str(), snd_strerror(error)); throw std::runtime_error("audio_alsa_sink"); } // Fill params with a full configuration space for a PCM. error = snd_pcm_hw_params_any(d_pcm_handle, d_hw_params); if(error < 0) bail("broken configuration for playback", error); if(CHATTY_DEBUG) gri_alsa_dump_hw_params(d_pcm_handle, d_hw_params, stdout); // now that we know how many channels the h/w can handle, set input signature unsigned int umin_chan, umax_chan; snd_pcm_hw_params_get_channels_min(d_hw_params, &umin_chan); snd_pcm_hw_params_get_channels_max(d_hw_params, &umax_chan); int min_chan = std::min(umin_chan, 1000U); int max_chan = std::min(umax_chan, 1000U); // As a special case, if the hw's min_chan is two, we'll accept // a single input and handle the duplication ourselves. if(min_chan == 2) { min_chan = 1; d_special_case_mono_to_stereo = true; } set_input_signature(io_signature::make(min_chan, max_chan, sizeof(float))); // fill in portions of the d_hw_params that we know now... // Specify the access methods we implement // For now, we only handle RW_INTERLEAVED... snd_pcm_access_mask_t *access_mask; snd_pcm_access_mask_t **access_mask_ptr = &access_mask; // FIXME: workaround for compiler warning snd_pcm_access_mask_alloca(access_mask_ptr); snd_pcm_access_mask_none(access_mask); snd_pcm_access_mask_set(access_mask, SND_PCM_ACCESS_RW_INTERLEAVED); // snd_pcm_access_mask_set(access_mask, SND_PCM_ACCESS_RW_NONINTERLEAVED); if((error = snd_pcm_hw_params_set_access_mask(d_pcm_handle, d_hw_params, access_mask)) < 0) bail("failed to set access mask", error); // set sample format if(!gri_alsa_pick_acceptable_format(d_pcm_handle, d_hw_params, acceptable_formats, NELEMS(acceptable_formats), &d_format, "audio_alsa_sink", CHATTY_DEBUG)) throw std::runtime_error("audio_alsa_sink"); // sampling rate unsigned int orig_sampling_rate = d_sampling_rate; if((error = snd_pcm_hw_params_set_rate_near(d_pcm_handle, d_hw_params, &d_sampling_rate, 0)) < 0) bail("failed to set rate near", error); if(orig_sampling_rate != d_sampling_rate) { fprintf(stderr, "audio_alsa_sink[%s]: unable to support sampling rate %d\n", snd_pcm_name(d_pcm_handle), orig_sampling_rate); fprintf(stderr, " card requested %d instead.\n", d_sampling_rate); } /* * ALSA transfers data in units of "periods". * We indirectly determine the underlying buffersize by specifying * the number of periods we want (typically 4) and the length of each * period in units of time (typically 1ms). */ unsigned int min_nperiods, max_nperiods; snd_pcm_hw_params_get_periods_min(d_hw_params, &min_nperiods, &dir); snd_pcm_hw_params_get_periods_max(d_hw_params, &max_nperiods, &dir); //fprintf(stderr, "alsa_sink: min_nperiods = %d, max_nperiods = %d\n", // min_nperiods, max_nperiods); unsigned int orig_nperiods = d_nperiods; d_nperiods = std::min (std::max (min_nperiods, d_nperiods), max_nperiods); // adjust period time so that total buffering remains more-or-less constant d_period_time_us = (d_period_time_us * orig_nperiods) / d_nperiods; error = snd_pcm_hw_params_set_periods(d_pcm_handle, d_hw_params, d_nperiods, 0); if(error < 0) bail("set_periods failed", error); dir = 0; error = snd_pcm_hw_params_set_period_time_near(d_pcm_handle, d_hw_params, &d_period_time_us, &dir); if(error < 0) bail("set_period_time_near failed", error); dir = 0; error = snd_pcm_hw_params_get_period_size(d_hw_params, &d_period_size, &dir); if(error < 0) bail("get_period_size failed", error); set_output_multiple(d_period_size); } bool alsa_sink::check_topology(int ninputs, int noutputs) { // ninputs is how many channels the user has connected. // Now we can finish up setting up the hw params... int nchan = ninputs; int err; // Check the state of the stream // Ensure that the pcm is in a state where we can still mess with the hw_params snd_pcm_state_t state; state = snd_pcm_state(d_pcm_handle); if(state == SND_PCM_STATE_RUNNING) return true; // If stream is running, don't change any parameters else if(state == SND_PCM_STATE_XRUN) snd_pcm_prepare(d_pcm_handle); // Prepare stream on underrun, and we can set parameters; bool special_case = nchan == 1 && d_special_case_mono_to_stereo; if(special_case) nchan = 2; err = snd_pcm_hw_params_set_channels(d_pcm_handle, d_hw_params, nchan); if(err < 0) { output_error_msg("set_channels failed", err); return false; } // set the parameters into the driver... err = snd_pcm_hw_params(d_pcm_handle, d_hw_params); if(err < 0) { output_error_msg("snd_pcm_hw_params failed", err); return false; } // get current s/w params err = snd_pcm_sw_params_current(d_pcm_handle, d_sw_params); if(err < 0) bail("snd_pcm_sw_params_current", err); // Tell the PCM device to wait to start until we've filled // it's buffers half way full. This helps avoid audio underruns. err = snd_pcm_sw_params_set_start_threshold(d_pcm_handle, d_sw_params, d_nperiods * d_period_size / 2); if(err < 0) bail("snd_pcm_sw_params_set_start_threshold", err); // store the s/w params err = snd_pcm_sw_params(d_pcm_handle, d_sw_params); if(err < 0) bail("snd_pcm_sw_params", err); d_buffer_size_bytes = d_period_size * nchan * snd_pcm_format_size(d_format, 1); d_buffer = new char[d_buffer_size_bytes]; if(CHATTY_DEBUG) fprintf(stdout, "audio_alsa_sink[%s]: sample resolution = %d bits\n", snd_pcm_name(d_pcm_handle), snd_pcm_hw_params_get_sbits(d_hw_params)); switch(d_format) { case SND_PCM_FORMAT_S16: if(special_case) d_worker = &alsa_sink::work_s16_1x2; else d_worker = &alsa_sink::work_s16; break; case SND_PCM_FORMAT_S32: if(special_case) d_worker = &alsa_sink::work_s32_1x2; else d_worker = &alsa_sink::work_s32; break; default: assert(0); } return true; } alsa_sink::~alsa_sink() { if(snd_pcm_state(d_pcm_handle) == SND_PCM_STATE_RUNNING) snd_pcm_drop(d_pcm_handle); snd_pcm_close(d_pcm_handle); delete [] ((char*)d_hw_params); delete [] ((char*)d_sw_params); delete [] d_buffer; } int alsa_sink::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { assert((noutput_items % d_period_size) == 0); // this is a call through a pointer to a method... return (this->*d_worker)(noutput_items, input_items, output_items); } /* * Work function that deals with float to S16 conversion */ int alsa_sink::work_s16(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int16 sample_t; // the type of samples we're creating static const float scale_factor = std::pow(2.0f, 16-1) - 1; unsigned int nchan = input_items.size(); const float **in = (const float **)&input_items[0]; sample_t *buf = (sample_t *)d_buffer; int bi; int n; unsigned int sizeof_frame = nchan * sizeof(sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); for(n = 0; n < noutput_items; n += d_period_size) { // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { for (unsigned int chan = 0; chan < nchan; chan++) { buf[bi++] = (sample_t) (in[chan][i] * scale_factor); } } // update src pointers for(unsigned int chan = 0; chan < nchan; chan++) in[chan] += d_period_size; if(!write_buffer (buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. } return n; } /* * Work function that deals with float to S32 conversion */ int alsa_sink::work_s32(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int32 sample_t; // the type of samples we're creating static const float scale_factor = std::pow(2.0f, 32-1) - 1; unsigned int nchan = input_items.size(); const float **in = (const float **)&input_items[0]; sample_t *buf = (sample_t *)d_buffer; int bi; int n; unsigned int sizeof_frame = nchan * sizeof (sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); for(n = 0; n < noutput_items; n += d_period_size) { // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { for(unsigned int chan = 0; chan < nchan; chan++) { buf[bi++] = (sample_t)(in[chan][i] * scale_factor); } } // update src pointers for(unsigned int chan = 0; chan < nchan; chan++) in[chan] += d_period_size; if(!write_buffer (buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. } return n; } /* * Work function that deals with float to S16 conversion and * mono to stereo kludge. */ int alsa_sink::work_s16_1x2(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int16 sample_t; // the type of samples we're creating static const float scale_factor = std::pow(2.0f, 16-1) - 1; assert(input_items.size () == 1); static const unsigned int nchan = 2; const float **in = (const float **)&input_items[0]; sample_t *buf = (sample_t *)d_buffer; int bi; int n; unsigned int sizeof_frame = nchan * sizeof(sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); for(n = 0; n < noutput_items; n += d_period_size) { // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { sample_t t = (sample_t) (in[0][i] * scale_factor); buf[bi++] = t; buf[bi++] = t; } // update src pointers in[0] += d_period_size; if(!write_buffer (buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. } return n; } /* * Work function that deals with float to S32 conversion and * mono to stereo kludge. */ int alsa_sink::work_s32_1x2(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { typedef gr_int32 sample_t; // the type of samples we're creating static const float scale_factor = std::pow(2.0f, 32-1) - 1; assert(input_items.size () == 1); static unsigned int nchan = 2; const float **in = (const float **)&input_items[0]; sample_t *buf = (sample_t*)d_buffer; int bi; int n; unsigned int sizeof_frame = nchan * sizeof(sample_t); assert(d_buffer_size_bytes == d_period_size * sizeof_frame); for(n = 0; n < noutput_items; n += d_period_size) { // process one period of data bi = 0; for(unsigned int i = 0; i < d_period_size; i++) { sample_t t = (sample_t)(in[0][i] * scale_factor); buf[bi++] = t; buf[bi++] = t; } // update src pointers in[0] += d_period_size; if(!write_buffer (buf, d_period_size, sizeof_frame)) return -1; // No fixing this problem. Say we're done. } return n; } bool alsa_sink::write_buffer(const void *vbuffer, unsigned nframes, unsigned sizeof_frame) { const unsigned char *buffer = (const unsigned char *)vbuffer; while(nframes > 0){ int r = snd_pcm_writei(d_pcm_handle, buffer, nframes); if(r == -EAGAIN) { if(d_ok_to_block == true) continue; // try again break; } else if(r == -EPIPE) { // underrun d_nunderuns++; fputs("aU", stderr); if((r = snd_pcm_prepare (d_pcm_handle)) < 0){ output_error_msg("snd_pcm_prepare failed. Can't recover from underrun", r); return false; } continue; // try again } else if(r == -ESTRPIPE) { // h/w is suspended (whatever that means) // This is apparently related to power management d_nsuspends++; if((r = snd_pcm_resume (d_pcm_handle)) < 0) { output_error_msg("failed to resume from suspend", r); return false; } continue; // try again } else if (r < 0) { output_error_msg("snd_pcm_writei failed", r); return false; } nframes -= r; buffer += r * sizeof_frame; } return true; } void alsa_sink::output_error_msg (const char *msg, int err) { fprintf(stderr, "audio_alsa_sink[%s]: %s: %s\n", snd_pcm_name(d_pcm_handle), msg, snd_strerror(err)); } void alsa_sink::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("audio_alsa_sink"); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/alsa/alsa_impl.cc0000664000175000017500000001246012207440367021001 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include static snd_pcm_access_t access_types[] = { SND_PCM_ACCESS_MMAP_INTERLEAVED, SND_PCM_ACCESS_MMAP_NONINTERLEAVED, SND_PCM_ACCESS_MMAP_COMPLEX, SND_PCM_ACCESS_RW_INTERLEAVED, SND_PCM_ACCESS_RW_NONINTERLEAVED }; static snd_pcm_format_t format_types[] = { // SND_PCM_FORMAT_UNKNOWN, SND_PCM_FORMAT_S8, SND_PCM_FORMAT_U8, SND_PCM_FORMAT_S16_LE, SND_PCM_FORMAT_S16_BE, SND_PCM_FORMAT_U16_LE, SND_PCM_FORMAT_U16_BE, SND_PCM_FORMAT_S24_LE, SND_PCM_FORMAT_S24_BE, SND_PCM_FORMAT_U24_LE, SND_PCM_FORMAT_U24_BE, SND_PCM_FORMAT_S32_LE, SND_PCM_FORMAT_S32_BE, SND_PCM_FORMAT_U32_LE, SND_PCM_FORMAT_U32_BE, SND_PCM_FORMAT_FLOAT_LE, SND_PCM_FORMAT_FLOAT_BE, SND_PCM_FORMAT_FLOAT64_LE, SND_PCM_FORMAT_FLOAT64_BE, SND_PCM_FORMAT_IEC958_SUBFRAME_LE, SND_PCM_FORMAT_IEC958_SUBFRAME_BE, SND_PCM_FORMAT_MU_LAW, SND_PCM_FORMAT_A_LAW, SND_PCM_FORMAT_IMA_ADPCM, SND_PCM_FORMAT_MPEG, SND_PCM_FORMAT_GSM, SND_PCM_FORMAT_SPECIAL, SND_PCM_FORMAT_S24_3LE, SND_PCM_FORMAT_S24_3BE, SND_PCM_FORMAT_U24_3LE, SND_PCM_FORMAT_U24_3BE, SND_PCM_FORMAT_S20_3LE, SND_PCM_FORMAT_S20_3BE, SND_PCM_FORMAT_U20_3LE, SND_PCM_FORMAT_U20_3BE, SND_PCM_FORMAT_S18_3LE, SND_PCM_FORMAT_S18_3BE, SND_PCM_FORMAT_U18_3LE, SND_PCM_FORMAT_U18_3BE }; static unsigned int test_rates[] = { 8000, 16000, 22050, 32000, 44100, 48000, 96000, 192000 }; #define NELEMS(x) (sizeof(x)/sizeof(x[0])) void gri_alsa_dump_hw_params (snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams, FILE *fp) { fprintf (fp, "PCM name: %s\n", snd_pcm_name (pcm)); fprintf (fp, "Access types:\n"); for (unsigned i = 0; i < NELEMS (access_types); i++){ snd_pcm_access_t at = access_types[i]; fprintf (fp, " %-20s %s\n", snd_pcm_access_name (at), snd_pcm_hw_params_test_access (pcm, hwparams, at) == 0 ? "YES" : "NO"); } fprintf (fp, "Formats:\n"); for (unsigned i = 0; i < NELEMS (format_types); i++){ snd_pcm_format_t ft = format_types[i]; if (0) fprintf (fp, " %-20s %s\n", snd_pcm_format_name (ft), snd_pcm_hw_params_test_format (pcm, hwparams, ft) == 0 ? "YES" : "NO"); else { if (snd_pcm_hw_params_test_format (pcm, hwparams, ft) == 0) fprintf (fp, " %-20s YES\n", snd_pcm_format_name (ft)); } } fprintf (fp, "Number of channels\n"); unsigned int min_chan, max_chan; snd_pcm_hw_params_get_channels_min (hwparams, &min_chan); snd_pcm_hw_params_get_channels_max (hwparams, &max_chan); fprintf (fp, " min channels: %d\n", min_chan); fprintf (fp, " max channels: %d\n", max_chan); unsigned int chan; max_chan = std::min (max_chan, 16U); // truncate display... for (chan = min_chan; chan <= max_chan; chan++){ fprintf (fp, " %d channels\t%s\n", chan, snd_pcm_hw_params_test_channels (pcm, hwparams, chan) == 0 ? "YES" : "NO"); } fprintf (fp, "Sample Rates:\n"); unsigned int min_rate, max_rate; int min_dir, max_dir; snd_pcm_hw_params_get_rate_min (hwparams, &min_rate, &min_dir); snd_pcm_hw_params_get_rate_max (hwparams, &max_rate, &max_dir); fprintf (fp, " min rate: %7d (dir = %d)\n", min_rate, min_dir); fprintf (fp, " max rate: %7d (dir = %d)\n", max_rate, max_dir); for (unsigned i = 0; i < NELEMS (test_rates); i++){ unsigned int rate = test_rates[i]; fprintf (fp, " %6u %s\n", rate, snd_pcm_hw_params_test_rate (pcm, hwparams, rate, 0) == 0 ? "YES" : "NO"); } fflush (fp); } bool gri_alsa_pick_acceptable_format (snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams, snd_pcm_format_t acceptable_formats[], unsigned nacceptable_formats, snd_pcm_format_t *selected_format, const char *error_msg_tag, bool verbose) { int err; // pick a format that we like... for (unsigned i = 0; i < nacceptable_formats; i++){ if (snd_pcm_hw_params_test_format (pcm, hwparams, acceptable_formats[i]) == 0){ err = snd_pcm_hw_params_set_format (pcm, hwparams, acceptable_formats[i]); if (err < 0){ fprintf (stderr, "%s[%s]: failed to set format: %s\n", error_msg_tag, snd_pcm_name (pcm), snd_strerror (err)); return false; } if (verbose) fprintf (stdout, "%s[%s]: using %s\n", error_msg_tag, snd_pcm_name (pcm), snd_pcm_format_name (acceptable_formats[i])); *selected_format = acceptable_formats[i]; return true; } } fprintf (stderr, "%s[%s]: failed to find acceptable format", error_msg_tag, snd_pcm_name (pcm)); return false; } gnuradio-3.7.2.1/gr-audio/lib/audio_registry.cc0000664000175000017500000001134312207440367021150 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "audio_registry.h" #include #include #include #include #include namespace gr { namespace audio { /*********************************************************************** * Create registries **********************************************************************/ struct source_entry_t { reg_prio_type prio; std::string arch; source_factory_t source; }; static std::vector &get_source_registry(void) { static std::vector d_registry; return d_registry; } struct sink_entry_t { reg_prio_type prio; std::string arch; sink_factory_t sink; }; static std::vector &get_sink_registry(void) { static std::vector d_registry; return d_registry; } /*********************************************************************** * Register functions **********************************************************************/ void register_source(reg_prio_type prio, const std::string &arch, source_factory_t source) { source_entry_t entry; entry.prio = prio; entry.arch = arch; entry.source = source; get_source_registry().push_back(entry); } void register_sink(reg_prio_type prio, const std::string &arch, sink_factory_t sink) { sink_entry_t entry; entry.prio = prio; entry.arch = arch; entry.sink = sink; get_sink_registry().push_back(entry); } /*********************************************************************** * Factory functions **********************************************************************/ static std::string default_arch_name(void) { return prefs::singleton()->get_string("audio", "audio_module", "auto"); } static void do_arch_warning(const std::string &arch) { if(arch == "auto") return; //no warning when arch not specified std::cerr << "Could not find audio architecture \"" << arch << "\" in registry." << std::endl; std::cerr << " Defaulting to the first available architecture..." << std::endl; } source::sptr source::make(int sampling_rate, const std::string device_name, bool ok_to_block) { if(get_source_registry().empty()) { throw std::runtime_error("no available audio source factories"); } std::string arch = default_arch_name(); source_entry_t entry = get_source_registry().front(); BOOST_FOREACH(const source_entry_t &e, get_source_registry()) { if(e.prio > entry.prio) entry = e; //entry is highest prio if(arch != e.arch) continue; //continue when no match return e.source(sampling_rate, device_name, ok_to_block); } //std::cout << "Audio source arch: " << entry.name << std::endl; return entry.source(sampling_rate, device_name, ok_to_block); } sink::sptr sink::make(int sampling_rate, const std::string device_name, bool ok_to_block) { if(get_sink_registry().empty()) { throw std::runtime_error("no available audio sink factories"); } std::string arch = default_arch_name(); sink_entry_t entry = get_sink_registry().front(); BOOST_FOREACH(const sink_entry_t &e, get_sink_registry()) { if(e.prio > entry.prio) entry = e; //entry is highest prio if(arch != e.arch) continue; //continue when no match return e.sink(sampling_rate, device_name, ok_to_block); } do_arch_warning(arch); //std::cout << "Audio sink arch: " << entry.name << std::endl; return entry.sink(sampling_rate, device_name, ok_to_block); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/jack/0000755000175000017500000000000012207440367016514 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/jack/jack_source.h0000664000175000017500000000524412207440367021164 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_JACK_SOURCE_H #define INCLUDED_AUDIO_JACK_SOURCE_H #include #include #include #include #include namespace gr { namespace audio { int jack_source_process(jack_nframes_t nframes, void *arg); /*! * \brief audio source using JACK * \ingroup audio_blk * * The source has one input stream of floats. * * Output samples will be in the range [-1,1]. */ class jack_source : public source { friend int jack_source_process(jack_nframes_t nframes, void *arg); // typedef for pointer to class work method typedef int(jack_source::*work_t)(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int d_sampling_rate; std::string d_device_name; bool d_ok_to_block; jack_client_t *d_jack_client; jack_port_t *d_jack_input_port; jack_ringbuffer_t *d_ringbuffer; jack_nframes_t d_jack_buffer_size; pthread_cond_t d_ringbuffer_ready; pthread_mutex_t d_jack_process_lock; // random stats int d_noverruns; // count of overruns void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); public: jack_source(int sampling_rate, const std::string device_name, bool ok_to_block); ~jack_source(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_JACK_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/lib/jack/jack_source.cc0000664000175000017500000001754312207440367021327 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2006,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #ifndef NO_PTHREAD #include #endif namespace gr { namespace audio { AUDIO_REGISTER_SOURCE(REG_PRIO_MED, jack)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return source::sptr (new jack_source(sampling_rate, device_name, ok_to_block)); } typedef jack_default_audio_sample_t sample_t; // Number of jack buffers in the ringbuffer // TODO: make it to match at least the quantity of items passed to work() static const unsigned int N_BUFFERS = 16; static std::string default_device_name() { return prefs::singleton()->get_string ("audio_jack", "default_input_device", "gr_source"); } int jack_source_process(jack_nframes_t nframes, void *arg) { jack_source *self = (jack_source *)arg; unsigned int write_size = nframes*sizeof(sample_t); if(jack_ringbuffer_write_space (self->d_ringbuffer) < write_size) { self->d_noverruns++; // FIXME: move this fputs out, we shouldn't use blocking calls in process() fputs ("jO", stderr); return 0; } char *buffer = (char *)jack_port_get_buffer(self->d_jack_input_port, nframes); jack_ringbuffer_write (self->d_ringbuffer, buffer, write_size); #ifndef NO_PTHREAD // Tell the source thread there is data in the ringbuffer. // If it is already running, the lock will not be available. // We can't wait here in the process() thread, but we don't // need to signal in that case, because the source thread will // check for data availability. if(pthread_mutex_trylock(&self->d_jack_process_lock) == 0) { pthread_cond_signal(&self->d_ringbuffer_ready); pthread_mutex_unlock(&self->d_jack_process_lock); } #endif return 0; } // ---------------------------------------------------------------- jack_source::jack_source(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_jack_source", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_ok_to_block(ok_to_block), d_jack_client(0), d_ringbuffer(0), d_noverruns(0) { #ifndef NO_PTHREAD pthread_cond_init(&d_ringbuffer_ready, NULL);; pthread_mutex_init(&d_jack_process_lock, NULL); #endif // try to become a client of the JACK server jack_options_t options = JackNullOption; jack_status_t status; const char *server_name = NULL; if((d_jack_client = jack_client_open(d_device_name.c_str(), options, &status, server_name)) == NULL) { fprintf(stderr, "audio_jack_source[%s]: jack server not running?\n", d_device_name.c_str()); throw std::runtime_error("audio_jack_source"); } // tell the JACK server to call `jack_source_process()' whenever // there is work to be done. jack_set_process_callback(d_jack_client, &jack_source_process, (void*)this); // tell the JACK server to call `jack_shutdown()' if // it ever shuts down, either entirely, or if it // just decides to stop calling us. //jack_on_shutdown (d_jack_client, &jack_shutdown, (void*)this); d_jack_input_port = jack_port_register(d_jack_client, "in", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); d_jack_buffer_size = jack_get_buffer_size(d_jack_client); set_output_multiple(d_jack_buffer_size); d_ringbuffer = jack_ringbuffer_create(N_BUFFERS*d_jack_buffer_size*sizeof(sample_t)); if(d_ringbuffer == NULL) bail("jack_ringbuffer_create failed", 0); assert(sizeof(float)==sizeof(sample_t)); set_output_signature(io_signature::make(1, 1, sizeof(sample_t))); jack_nframes_t sample_rate = jack_get_sample_rate(d_jack_client); if((jack_nframes_t)sampling_rate != sample_rate) { fprintf(stderr, "audio_jack_source[%s]: unable to support sampling rate %d\n", d_device_name.c_str(), sampling_rate); fprintf(stderr, " card requested %d instead.\n", sample_rate); } } bool jack_source::check_topology(int ninputs, int noutputs) { // tell the JACK server that we are ready to roll if(jack_activate (d_jack_client)) throw std::runtime_error("audio_jack_source"); return true; } jack_source::~jack_source() { jack_client_close(d_jack_client); jack_ringbuffer_free(d_ringbuffer); } int jack_source::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // read_size and work_size are in bytes unsigned int read_size; // Minimize latency noutput_items = std::min (noutput_items, (int)d_jack_buffer_size); int work_size = noutput_items*sizeof(sample_t); while(work_size > 0) { unsigned int read_space; // bytes #ifdef NO_PTHREAD while((read_space=jack_ringbuffer_read_space (d_ringbuffer)) < d_jack_buffer_size*sizeof(sample_t)) { usleep(1000000*((d_jack_buffer_size-read_space/sizeof(sample_t))/d_sampling_rate)); } #else // JACK actually requires POSIX pthread_mutex_lock(&d_jack_process_lock); while((read_space = jack_ringbuffer_read_space(d_ringbuffer)) < d_jack_buffer_size*sizeof(sample_t)) { // wait until jack_source_process() signals more data pthread_cond_wait(&d_ringbuffer_ready, &d_jack_process_lock); } pthread_mutex_unlock(&d_jack_process_lock); #endif read_space -= read_space%(d_jack_buffer_size*sizeof(sample_t)); read_size = std::min(read_space, (unsigned int)work_size); if(jack_ringbuffer_read(d_ringbuffer, (char *) output_items[0], read_size) < read_size) { bail("jack_ringbuffer_read failed", 0); } work_size -= read_size; } return noutput_items; } void jack_source::output_error_msg(const char *msg, int err) { fprintf(stderr, "audio_jack_source[%s]: %s: %d\n", d_device_name.c_str(), msg, err); } void jack_source::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("audio_jack_source"); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/jack/jack_sink.cc0000664000175000017500000001727312207440367020773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #ifndef NO_PTHREAD #include #endif namespace gr { namespace audio { AUDIO_REGISTER_SINK(REG_PRIO_MED, jack)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return sink::sptr (new jack_sink(sampling_rate, device_name, ok_to_block)); } typedef jack_default_audio_sample_t sample_t; // Number of jack buffers in the ringbuffer // TODO: make it to match at least the quantity of items passed by work() static const unsigned int N_BUFFERS = 16; static std::string default_device_name() { return prefs::singleton()->get_string ("audio_jack", "default_output_device", "gr_sink"); } int jack_sink_process(jack_nframes_t nframes, void *arg) { jack_sink *self = (jack_sink *)arg; unsigned int read_size = nframes*sizeof(sample_t); if(jack_ringbuffer_read_space(self->d_ringbuffer) < read_size) { self->d_nunderuns++; // FIXME: move this fputs out, we shouldn't use blocking calls in process() fputs("jU", stderr); return 0; } char *buffer = (char *)jack_port_get_buffer(self->d_jack_output_port, nframes); jack_ringbuffer_read(self->d_ringbuffer, buffer, read_size); #ifndef NO_PTHREAD // Tell the sink thread there is room in the ringbuffer. // If it is already running, the lock will not be available. // We can't wait here in the process() thread, but we don't // need to signal in that case, because the sink thread will // check for room availability. if(pthread_mutex_trylock (&self->d_jack_process_lock) == 0) { pthread_cond_signal(&self->d_ringbuffer_ready); pthread_mutex_unlock(&self->d_jack_process_lock); } #endif return 0; } // ---------------------------------------------------------------- jack_sink::jack_sink(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_jack_sink", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_ok_to_block(ok_to_block), d_jack_client(0), d_ringbuffer(0), d_nunderuns(0) { #ifndef NO_PTHREAD pthread_cond_init(&d_ringbuffer_ready, NULL);; pthread_mutex_init(&d_jack_process_lock, NULL); #endif // try to become a client of the JACK server jack_options_t options = JackNullOption; jack_status_t status; const char *server_name = NULL; if((d_jack_client = jack_client_open(d_device_name.c_str(), options, &status, server_name)) == NULL) { fprintf(stderr, "audio_jack_sink[%s]: jack server not running?\n", d_device_name.c_str()); throw std::runtime_error("audio_jack_sink"); } // tell the JACK server to call `jack_sink_process()' whenever // there is work to be done. jack_set_process_callback(d_jack_client, &jack_sink_process, (void*)this); // tell the JACK server to call `jack_shutdown()' if // it ever shuts down, either entirely, or if it // just decides to stop calling us. //jack_on_shutdown (d_jack_client, &jack_shutdown, (void*)this); d_jack_output_port = jack_port_register(d_jack_client, "out", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); d_jack_buffer_size = jack_get_buffer_size(d_jack_client); set_output_multiple(d_jack_buffer_size); d_ringbuffer = jack_ringbuffer_create(N_BUFFERS*d_jack_buffer_size*sizeof(sample_t)); if(d_ringbuffer == NULL) bail("jack_ringbuffer_create failed", 0); assert(sizeof(float)==sizeof(sample_t)); set_input_signature(io_signature::make(1, 1, sizeof(sample_t))); jack_nframes_t sample_rate = jack_get_sample_rate(d_jack_client); if((jack_nframes_t)sampling_rate != sample_rate) { fprintf(stderr, "audio_jack_sink[%s]: unable to support sampling rate %d\n", d_device_name.c_str(), sampling_rate); fprintf(stderr, " card requested %d instead.\n", sample_rate); } } bool jack_sink::check_topology (int ninputs, int noutputs) { if(ninputs != 1) return false; // tell the JACK server that we are ready to roll if(jack_activate (d_jack_client)) throw std::runtime_error("audio_jack_sink"); return true; } jack_sink::~jack_sink() { jack_client_close(d_jack_client); jack_ringbuffer_free(d_ringbuffer); } int jack_sink::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // write_size and work_size are in bytes int work_size = noutput_items*sizeof(sample_t); unsigned int write_size; while(work_size > 0) { unsigned int write_space; // bytes #ifdef NO_PTHREAD while((write_space=jack_ringbuffer_write_space(d_ringbuffer)) < d_jack_buffer_size*sizeof(sample_t)) { usleep(1000000*((d_jack_buffer_size-write_space/sizeof(sample_t))/d_sampling_rate)); } #else // JACK actually requires POSIX pthread_mutex_lock(&d_jack_process_lock); while((write_space = jack_ringbuffer_write_space(d_ringbuffer)) < d_jack_buffer_size*sizeof(sample_t)) { // wait until jack_sink_process() signals more room pthread_cond_wait(&d_ringbuffer_ready, &d_jack_process_lock); } pthread_mutex_unlock(&d_jack_process_lock); #endif write_space -= write_space%(d_jack_buffer_size*sizeof(sample_t)); write_size = std::min(write_space, (unsigned int)work_size); if(jack_ringbuffer_write(d_ringbuffer, (char *) input_items[0], write_size) < write_size) { bail("jack_ringbuffer_write failed", 0); } work_size -= write_size; } return noutput_items; } void jack_sink::output_error_msg(const char *msg, int err) { fprintf(stderr, "audio_jack_sink[%s]: %s: %d\n", d_device_name.c_str(), msg, err); } void jack_sink::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("audio_jack_sink"); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/jack/jack_impl.cc0000664000175000017500000000162512207440367020762 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include gnuradio-3.7.2.1/gr-audio/lib/jack/gr-audio-jack.conf0000644000175000017500000000035311700377700021776 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [audio_jack] default_input_device = gr_source default_output_device = gr_sink gnuradio-3.7.2.1/gr-audio/lib/jack/jack_sink.h0000664000175000017500000000520212207440367020622 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_JACK_SINK_H #define INCLUDED_AUDIO_JACK_SINK_H #include #include #include #include #include namespace gr { namespace audio { int sink_process(jack_nframes_t nframes, void *arg); /*! * \brief audio sink using JACK * \ingroup audio_blk * * The sink has one input stream of floats. * * Input samples must be in the range [-1,1]. */ class jack_sink : public sink { friend int jack_sink_process(jack_nframes_t nframes, void *arg); // typedef for pointer to class work method typedef int (jack_sink::*work_t)(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int d_sampling_rate; std::string d_device_name; bool d_ok_to_block; jack_client_t *d_jack_client; jack_port_t *d_jack_output_port; jack_ringbuffer_t *d_ringbuffer; jack_nframes_t d_jack_buffer_size; pthread_cond_t d_ringbuffer_ready; pthread_mutex_t d_jack_process_lock; // random stats int d_nunderuns; // count of underruns void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); public: jack_sink(int sampling_rate, const std::string device_name, bool ok_to_block); ~jack_sink(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_JACK_SINK_H */ gnuradio-3.7.2.1/gr-audio/lib/jack/jack_impl.h0000664000175000017500000000167112207440367020625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_JACK_IMPL_H #define INCLUDED_AUDIO_JACK_IMPL_H #include #endif /* INCLUDED_AUDIO_JACK_IMPL_H */ gnuradio-3.7.2.1/gr-audio/lib/oss/0000755000175000017500000000000012207440367016410 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/oss/oss_sink.cc0000664000175000017500000001243512207440367020556 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SINK(REG_PRIO_LOW, oss)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return sink::sptr (new oss_sink(sampling_rate, device_name, ok_to_block)); } static std::string default_device_name() { return prefs::singleton()->get_string ("audio_oss", "default_output_device", "/dev/dsp"); } oss_sink::oss_sink(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_oss_sink", io_signature::make(1, 2, sizeof(float)), io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_fd(-1), d_buffer(0), d_chunk_size(0) { if((d_fd = open(d_device_name.c_str(), O_WRONLY)) < 0) { fprintf(stderr, "audio_oss_sink: "); perror(d_device_name.c_str()); throw std::runtime_error("audio_oss_sink"); } double CHUNK_TIME = std::max(0.001, prefs::singleton()->get_double("audio_oss", "latency", 0.005)); d_chunk_size = (int)(d_sampling_rate * CHUNK_TIME); set_output_multiple(d_chunk_size); d_buffer = new short[d_chunk_size * 2]; int format = AFMT_S16_NE; int orig_format = format; if(ioctl(d_fd, SNDCTL_DSP_SETFMT, &format) < 0) { std::cerr << "audio_oss_sink: " << d_device_name << " ioctl failed\n"; perror(d_device_name.c_str ()); throw std::runtime_error("audio_oss_sink"); } if(format != orig_format) { fprintf(stderr, "audio_oss_sink: unable to support format %d\n", orig_format); fprintf(stderr, " card requested %d instead.\n", format); } // set to stereo no matter what. Some hardware only does stereo int channels = 2; if(ioctl(d_fd, SNDCTL_DSP_CHANNELS, &channels) < 0 || channels != 2) { perror("audio_oss_sink: could not set STEREO mode"); throw std::runtime_error("audio_oss_sink"); } // set sampling freq int sf = sampling_rate; if(ioctl(d_fd, SNDCTL_DSP_SPEED, &sf) < 0) { std::cerr << "audio_oss_sink: " << d_device_name << ": invalid sampling_rate " << sampling_rate << "\n"; sampling_rate = 8000; if(ioctl(d_fd, SNDCTL_DSP_SPEED, &sf) < 0) { std::cerr << "audio_oss_sink: failed to set sampling_rate to 8000\n"; throw std::runtime_error("audio_oss_sink"); } } } oss_sink::~oss_sink() { close(d_fd); delete [] d_buffer; } int oss_sink::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *f0, *f1; switch(input_items.size()) { case 1: // mono input f0 = (const float *)input_items[0]; for(int i = 0; i < noutput_items; i += d_chunk_size) { for(int j = 0; j < d_chunk_size; j++) { d_buffer[2*j+0] = (short) (f0[j] * 32767); d_buffer[2*j+1] = (short) (f0[j] * 32767); } f0 += d_chunk_size; if(write(d_fd, d_buffer, 2 * d_chunk_size * sizeof (short)) < 0) perror("audio_oss_sink: write"); } break; case 2: // stereo input f0 = (const float *) input_items[0]; f1 = (const float *) input_items[1]; for(int i = 0; i < noutput_items; i += d_chunk_size) { for(int j = 0; j < d_chunk_size; j++) { d_buffer[2*j+0] = (short)(f0[j] * 32767); d_buffer[2*j+1] = (short)(f1[j] * 32767); } f0 += d_chunk_size; f1 += d_chunk_size; if(write(d_fd, d_buffer, 2 * d_chunk_size * sizeof (short)) < 0) perror("audio_oss_sink: write"); } break; } return noutput_items; } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/oss/oss_source.h0000664000175000017500000000337612207440367020760 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_OSS_SOURCE_H #define INCLUDED_AUDIO_OSS_SOURCE_H #include #include namespace gr { namespace audio { /*! * \brief audio source using OSS * \ingroup audio_blk * * Output signature is one or two streams of floats. * Output samples will be in the range [-1,1]. */ class oss_source : public source { int d_sampling_rate; std::string d_device_name; int d_fd; short *d_buffer; int d_chunk_size; public: oss_source(int sampling_rate, const std::string device_name = "", bool ok_to_block = true); ~oss_source(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_OSS_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/lib/oss/oss_source.cc0000664000175000017500000001347612207440367021120 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace gr { namespace audio { AUDIO_REGISTER_SOURCE(REG_PRIO_LOW, oss)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return source::sptr (new oss_source(sampling_rate, device_name, ok_to_block)); } static std::string default_device_name() { return prefs::singleton()->get_string ("audio_oss", "default_input_device", "/dev/dsp"); } oss_source::oss_source(int sampling_rate, const std::string device_name, bool ok_to_block) : sync_block("audio_oss_source", io_signature::make(0, 0, 0), io_signature::make(1, 2, sizeof(float))), d_sampling_rate(sampling_rate), d_device_name(device_name.empty() ? default_device_name() : device_name), d_fd(-1), d_buffer(0), d_chunk_size(0) { if((d_fd = open(d_device_name.c_str(), O_RDONLY)) < 0) { fprintf(stderr, "audio_oss_source: "); perror(d_device_name.c_str()); throw std::runtime_error("audio_oss_source"); } double CHUNK_TIME = std::max(0.001, prefs::singleton()->get_double("audio_oss", "latency", 0.005)); d_chunk_size = (int)(d_sampling_rate * CHUNK_TIME); set_output_multiple(d_chunk_size); d_buffer = new short[d_chunk_size * 2]; int format = AFMT_S16_NE; int orig_format = format; if(ioctl(d_fd, SNDCTL_DSP_SETFMT, &format) < 0) { std::cerr << "audio_oss_source: " << d_device_name << " ioctl failed\n"; perror(d_device_name.c_str ()); throw std::runtime_error("audio_oss_source"); } if(format != orig_format) { fprintf(stderr, "audio_oss_source: unable to support format %d\n", orig_format); fprintf(stderr, " card requested %d instead.\n", format); } // set to stereo no matter what. Some hardware only does stereo int channels = 2; if(ioctl(d_fd, SNDCTL_DSP_CHANNELS, &channels) < 0 || channels != 2) { perror("audio_oss_source: could not set STEREO mode"); throw std::runtime_error("audio_oss_source"); } // set sampling freq int sf = sampling_rate; if(ioctl(d_fd, SNDCTL_DSP_SPEED, &sf) < 0) { std::cerr << "audio_oss_source: " << d_device_name << ": invalid sampling_rate " << sampling_rate << "\n"; sampling_rate = 8000; if(ioctl(d_fd, SNDCTL_DSP_SPEED, &sf) < 0) { std::cerr << "audio_oss_source: failed to set sampling_rate to 8000\n"; throw std::runtime_error ("audio_oss_source"); } } } oss_source::~oss_source() { close(d_fd); delete [] d_buffer; } int oss_source::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *f0 = (float *)output_items[0]; float *f1 = (float *)output_items[1]; // will be invalid if this is mono output const int shorts_per_item = 2; // L + R const int bytes_per_item = shorts_per_item * sizeof(short); // To minimize latency, never return more than CHUNK_TIME // worth of samples per call to work. noutput_items = std::min(noutput_items, d_chunk_size); int base = 0; int ntogo = noutput_items; while(ntogo > 0) { int nbytes = std::min(ntogo, d_chunk_size) * bytes_per_item; int result_nbytes = read(d_fd, d_buffer, nbytes); if(result_nbytes < 0) { perror("audio_oss_source"); return -1; // say we're done } if((result_nbytes & (bytes_per_item - 1)) != 0) { fprintf(stderr, "audio_oss_source: internal error.\n"); throw std::runtime_error("internal error"); } int result_nitems = result_nbytes / bytes_per_item; // now unpack samples into output streams switch(output_items.size()) { case 1: // mono output for(int i = 0; i < result_nitems; i++) { f0[base+i] = d_buffer[2*i+0] * (1.0 / 32767); } break; case 2: // stereo output for(int i = 0; i < result_nitems; i++) { f0[base+i] = d_buffer[2*i+0] * (1.0 / 32767); f1[base+i] = d_buffer[2*i+1] * (1.0 / 32767); } break; default: assert(0); } ntogo -= result_nitems; base += result_nitems; } return noutput_items - ntogo; } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/oss/oss_sink.h0000664000175000017500000000334512207440367020420 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_OSS_SINK_H #define INCLUDED_AUDIO_OSS_SINK_H #include #include namespace gr { namespace audio { /*! * \brief audio sink using OSS * \ingroup audio_blk * * input signature is one or two streams of floats. * Input samples must be in the range [-1,1]. */ class oss_sink : public sink { int d_sampling_rate; std::string d_device_name; int d_fd; short *d_buffer; int d_chunk_size; public: oss_sink(int sampling_rate, const std::string device_name = "", bool ok_to_block = true); ~oss_sink(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_OSS_SINK_H */ gnuradio-3.7.2.1/gr-audio/lib/oss/gr-audio-oss.conf0000644000175000017500000000043411700377700021566 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [audio_oss] default_input_device = /dev/dsp default_output_device = /dev/dsp latency = 0.005 # in seconds gnuradio-3.7.2.1/gr-audio/lib/osx/0000755000175000017500000000000012207440367016415 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/lib/osx/osx_sink.h0000664000175000017500000000506312207440367020431 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_OSX_SINK_H #define INCLUDED_AUDIO_OSX_SINK_H #include #include #include #include #include namespace gr { namespace audio { /*! * \brief audio sink using OSX * \ingroup audio_blk * * input signature is one or two streams of floats. * Input samples must be in the range [-1,1]. */ class osx_sink : public sink { Float64 d_sample_rate; int d_channel_config; UInt32 d_n_channels; UInt32 d_queueSampleCount, d_max_sample_count; bool d_do_block; gr::thread::mutex* d_internal; gr::thread::condition_variable* d_cond_data; circular_buffer** d_buffers; // AudioUnits and Such AudioUnit d_OutputAU; public: osx_sink(int sample_rate = 44100, const std::string device_name = "2", bool do_block = true, int channel_config = -1, int max_sample_count = -1); ~osx_sink(); bool IsRunning(); bool start(); bool stop(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); private: static OSStatus AUOutputCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_OSX_SINK_H */ gnuradio-3.7.2.1/gr-audio/lib/osx/osx_impl.h0000664000175000017500000000600012207440367020416 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006, 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_OSX_IMPL_H #define INCLUDED_AUDIO_OSX_IMPL_H #include #include namespace gr { namespace audio { #define CheckErrorAndThrow(err,what,throw_str) \ if(err) { \ OSStatus error = static_cast(err); \ char err_str[4]; \ strncpy(err_str, (char*)(&err), 4); \ std::cerr << what << std::endl; \ std::cerr << " Error# " << error << " ('" << err_str \ << "')" << std::endl; \ std::cerr << " " << __FILE__ << ":" << __LINE__ << std::endl; \ fflush(stderr); \ throw std::runtime_error(throw_str); \ } #define CheckError(err,what) \ if(err) { \ OSStatus error = static_cast(err); \ char err_str[4]; \ strncpy(err_str, (char*)(&err), 4); \ std::cerr << what << std::endl; \ std::cerr << " Error# " << error << " ('" << err_str \ << "')" << std::endl; \ std::cerr << " " << __FILE__ << ":" << __LINE__ << std::endl; \ fflush(stderr); \ } #include //BOOST_BIG_ENDIAN #ifdef BOOST_BIG_ENDIAN #define GR_PCM_ENDIANNESS kLinearPCMFormatFlagIsBigEndian #else #define GR_PCM_ENDIANNESS 0 #endif // Check the version of MacOSX being used #ifdef __APPLE_CC__ #include #ifndef MAC_OS_X_VERSION_10_6 #define MAC_OS_X_VERSION_10_6 1060 #endif #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 #define GR_USE_OLD_AUDIO_UNIT #endif #endif } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_OSX_IMPL_H */ gnuradio-3.7.2.1/gr-audio/lib/osx/osx_sink.cc0000664000175000017500000003441512207440367020572 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include namespace gr { namespace audio { #define _OSX_AU_DEBUG_ 0 AUDIO_REGISTER_SINK(REG_PRIO_HIGH, osx)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return sink::sptr (new osx_sink(sampling_rate, device_name, ok_to_block)); } osx_sink::osx_sink(int sample_rate, const std::string device_name, bool do_block, int channel_config, int max_sample_count) : sync_block("audio_osx_sink", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sample_rate(0.0), d_channel_config(0), d_n_channels(0), d_queueSampleCount(0), d_max_sample_count(0), d_do_block(do_block), d_internal(0), d_cond_data(0), d_OutputAU(0) { if(sample_rate <= 0) { std::cerr << "Invalid Sample Rate: " << sample_rate << std::endl; throw std::invalid_argument ("audio_osx_sink::audio_osx_sink"); } else d_sample_rate = (Float64)sample_rate; if(channel_config <= 0 & channel_config != -1) { std::cerr << "Invalid Channel Config: " << channel_config << std::endl; throw std::invalid_argument ("audio_osx_sink::audio_osx_sink"); } else if(channel_config == -1) { // no user input; try "device name" instead int l_n_channels = (int)strtol(device_name.data(), (char**)NULL, 10); if((l_n_channels == 0) & errno) { std::cerr << "Error Converting Device Name: " << errno << std::endl; throw std::invalid_argument("audio_osx_sink::audio_osx_sink"); } if(l_n_channels <= 0) channel_config = 2; else channel_config = l_n_channels; } d_n_channels = d_channel_config = channel_config; // set the input signature set_input_signature(io_signature::make(1, d_n_channels, sizeof(float))); // check that the max # of samples to store is valid if(max_sample_count == -1) max_sample_count = sample_rate; else if(max_sample_count <= 0) { std::cerr << "Invalid Max Sample Count: " << max_sample_count << std::endl; throw std::invalid_argument ("audio_osx_sink::audio_osx_sink"); } d_max_sample_count = max_sample_count; // allocate the output circular buffer(s), one per channel d_buffers = (circular_buffer**) new circular_buffer* [d_n_channels]; UInt32 n_alloc = (UInt32) ceil((double)d_max_sample_count); for(UInt32 n = 0; n < d_n_channels; n++) { d_buffers[n] = new circular_buffer(n_alloc, false, false); } // create the default AudioUnit for output OSStatus err = noErr; // Open the default output unit #ifndef GR_USE_OLD_AUDIO_UNIT AudioComponentDescription desc; #else ComponentDescription desc; #endif desc.componentType = kAudioUnitType_Output; desc.componentSubType = kAudioUnitSubType_DefaultOutput; desc.componentManufacturer = kAudioUnitManufacturer_Apple; desc.componentFlags = 0; desc.componentFlagsMask = 0; #ifndef GR_USE_OLD_AUDIO_UNIT AudioComponent comp = AudioComponentFindNext(NULL, &desc); if(comp == NULL) { std::cerr << "AudioComponentFindNext Error" << std::endl; throw std::runtime_error("audio_osx_sink::audio_osx_sink"); } #else Component comp = FindNextComponent(NULL, &desc); if(comp == NULL) { std::cerr << "FindNextComponent Error" << std::endl; throw std::runtime_error("audio_osx_sink::audio_osx_sink"); } #endif #ifndef GR_USE_OLD_AUDIO_UNIT err = AudioComponentInstanceNew(comp, &d_OutputAU); CheckErrorAndThrow(err, "AudioComponentInstanceNew", "audio_osx_sink::audio_osx_sink"); #else err = OpenAComponent(comp, &d_OutputAU); CheckErrorAndThrow(err, "OpenAComponent", "audio_osx_sink::audio_osx_sink"); #endif // Set up a callback function to generate output to the output unit AURenderCallbackStruct input; input.inputProc = (AURenderCallback)(osx_sink::AUOutputCallback); input.inputProcRefCon = this; err = AudioUnitSetProperty(d_OutputAU, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, sizeof (input)); CheckErrorAndThrow(err, "AudioUnitSetProperty Render Callback", "audio_osx_sink::audio_osx_sink"); // tell the Output Unit what format data will be supplied to it // so that it handles any format conversions AudioStreamBasicDescription streamFormat; streamFormat.mSampleRate = (Float64)(sample_rate); streamFormat.mFormatID = kAudioFormatLinearPCM; streamFormat.mFormatFlags = (kLinearPCMFormatFlagIsFloat | GR_PCM_ENDIANNESS | kLinearPCMFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved); streamFormat.mBytesPerPacket = 4; streamFormat.mFramesPerPacket = 1; streamFormat.mBytesPerFrame = 4; streamFormat.mChannelsPerFrame = d_n_channels; streamFormat.mBitsPerChannel = 32; err = AudioUnitSetProperty(d_OutputAU, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamFormat, sizeof(AudioStreamBasicDescription)); CheckErrorAndThrow(err, "AudioUnitSetProperty StreamFormat", "audio_osx_sink::audio_osx_sink"); // create the stuff to regulate I/O d_cond_data = new gr::thread::condition_variable(); if(d_cond_data == NULL) CheckErrorAndThrow(errno, "new condition (data)", "audio_osx_sink::audio_osx_sink"); d_internal = new gr::thread::mutex(); if(d_internal == NULL) CheckErrorAndThrow(errno, "new mutex (internal)", "audio_osx_sink::audio_osx_sink"); // initialize the AU for output err = AudioUnitInitialize(d_OutputAU); CheckErrorAndThrow(err, "AudioUnitInitialize", "audio_osx_sink::audio_osx_sink"); #if _OSX_AU_DEBUG_ std::cerr << "audio_osx_sink Parameters:" << std::endl; std::cerr << " Sample Rate is " << d_sample_rate << std::endl; std::cerr << " Number of Channels is " << d_n_channels << std::endl; std::cerr << " Max # samples to store per channel is " << d_max_sample_count << std::endl; #endif } bool osx_sink::IsRunning() { UInt32 AURunning = 0, AUSize = sizeof(UInt32); OSStatus err = AudioUnitGetProperty(d_OutputAU, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, 0, &AURunning, &AUSize); CheckErrorAndThrow(err, "AudioUnitGetProperty IsRunning", "audio_osx_sink::IsRunning"); return (AURunning); } bool osx_sink::start() { if(!IsRunning()) { OSStatus err = AudioOutputUnitStart(d_OutputAU); CheckErrorAndThrow(err, "AudioOutputUnitStart", "audio_osx_sink::start"); } return (true); } bool osx_sink::stop() { if(IsRunning ()) { OSStatus err = AudioOutputUnitStop(d_OutputAU); CheckErrorAndThrow(err, "AudioOutputUnitStop", "audio_osx_sink::stop"); for(UInt32 n = 0; n < d_n_channels; n++) { d_buffers[n]->abort(); } } return (true); } osx_sink::~osx_sink() { // stop and close the AudioUnit stop(); AudioUnitUninitialize(d_OutputAU); #ifndef GR_USE_OLD_AUDIO_UNIT AudioComponentInstanceDispose(d_OutputAU); #else CloseComponent(d_OutputAU); #endif // empty and delete the queues for(UInt32 n = 0; n < d_n_channels; n++) { delete d_buffers[n]; d_buffers[n] = 0; } delete [] d_buffers; d_buffers = 0; // close and delete control stuff delete d_cond_data; d_cond_data = 0; delete d_internal; d_internal = 0; } int osx_sink::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(*d_internal); /* take the input data, copy it, and push it to the bottom of the queue mono input are pushed onto queue[0]; stereo input are pushed onto queue[1]. Start the AudioUnit if necessary. */ UInt32 l_max_count; int diff_count = d_max_sample_count - noutput_items; if(diff_count < 0) l_max_count = 0; else l_max_count = (UInt32)diff_count; #if 0 if(l_max_count < d_queueItemLength->back()) { // allow 2 buffers at a time, regardless of length l_max_count = d_queueItemLength->back(); } #endif #if _OSX_AU_DEBUG_ std::cerr << "work1: qSC = " << d_queueSampleCount << ", lMC = "<< l_max_count << ", dmSC = " << d_max_sample_count << ", nOI = " << noutput_items << std::endl; #endif if(d_queueSampleCount > l_max_count) { // data coming in too fast; do_block decides what to do if(d_do_block == true) { // block until there is data to return while(d_queueSampleCount > l_max_count) { // release control so-as to allow data to be retrieved; // block until there is data to return d_cond_data->wait(l); // the condition's 'notify' was called; acquire control // to keep thread safe } } } // not blocking case and overflow is handled by the circular buffer // add the input frames to the buffers' queue, checking for overflow UInt32 l_counter; int res = 0; float* inBuffer = (float*)input_items[0]; const UInt32 l_size = input_items.size(); for(l_counter = 0; l_counter < l_size; l_counter++) { inBuffer = (float*)input_items[l_counter]; int l_res = d_buffers[l_counter]->enqueue(inBuffer, noutput_items); if(l_res == -1) res = -1; } while(l_counter < d_n_channels) { // for extra channels, copy the last input's data int l_res = d_buffers[l_counter++]->enqueue(inBuffer, noutput_items); if(l_res == -1) res = -1; } if(res == -1) { // data coming in too fast // drop oldest buffer fputs("aO", stderr); fflush(stderr); // set the local number of samples available to the max d_queueSampleCount = d_buffers[0]->buffer_length_items(); } else { // keep up the local sample count d_queueSampleCount += noutput_items; } #if _OSX_AU_DEBUG_ std::cerr << "work2: #OI = " << noutput_items << ", #Cnt = " << d_queueSampleCount << ", mSC = " << d_max_sample_count << std::endl; #endif return (noutput_items); } OSStatus osx_sink::AUOutputCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { osx_sink* This = (osx_sink*)inRefCon; OSStatus err = noErr; gr::thread::scoped_lock l(*This->d_internal); #if _OSX_AU_DEBUG_ std::cerr << "cb_in: SC = " << This->d_queueSampleCount << ", in#F = " << inNumberFrames << std::endl; #endif if(This->d_queueSampleCount < inNumberFrames) { // not enough data to fill request err = -1; } else { // enough data; remove data from our buffers into the AU's buffers int l_counter = This->d_n_channels; while(--l_counter >= 0) { size_t t_n_output_items = inNumberFrames; float* outBuffer = (float*)ioData->mBuffers[l_counter].mData; This->d_buffers[l_counter]->dequeue(outBuffer, &t_n_output_items); if(t_n_output_items != inNumberFrames) { throw std::runtime_error("audio_osx_sink::AUOutputCallback(): " "number of available items changing " "unexpectedly.\n"); } } This->d_queueSampleCount -= inNumberFrames; } #if _OSX_AU_DEBUG_ std::cerr << "cb_out: SC = " << This->d_queueSampleCount << std::endl; #endif // signal that data is available This->d_cond_data->notify_one(); return (err); } } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/osx/osx_source.cc0000664000175000017500000012153012207440367021121 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audio_registry.h" #include #include #include #include namespace gr { namespace audio { #define _OSX_AU_DEBUG_ 0 #define _OSX_DO_LISTENERS_ 0 AUDIO_REGISTER_SOURCE(REG_PRIO_HIGH, osx)(int sampling_rate, const std::string &device_name, bool ok_to_block) { return source::sptr (new osx_source(sampling_rate, device_name, ok_to_block)); } void PrintStreamDesc(AudioStreamBasicDescription *inDesc) { if(inDesc == NULL) { std::cerr << "PrintStreamDesc: Can't print a NULL desc!" << std::endl; return; } std::cerr << " Sample Rate : " << inDesc->mSampleRate << std::endl; char format_id[4]; strncpy(format_id, (char*)(&inDesc->mFormatID), 4); std::cerr << " Format ID : " << format_id << std::endl; std::cerr << " Format Flags : " << inDesc->mFormatFlags << std::endl; std::cerr << " Bytes per Packet : " << inDesc->mBytesPerPacket << std::endl; std::cerr << " Frames per Packet : " << inDesc->mFramesPerPacket << std::endl; std::cerr << " Bytes per Frame : " << inDesc->mBytesPerFrame << std::endl; std::cerr << " Channels per Frame : " << inDesc->mChannelsPerFrame << std::endl; std::cerr << " Bits per Channel : " << inDesc->mBitsPerChannel << std::endl; } // FIXME these should query some kind of user preference osx_source::osx_source(int sample_rate, const std::string device_name, bool do_block, int channel_config, int max_sample_count) : sync_block("audio_osx_source", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_deviceSampleRate(0.0), d_outputSampleRate(0.0), d_channel_config(0), d_inputBufferSizeFrames(0), d_inputBufferSizeBytes(0), d_outputBufferSizeFrames(0), d_outputBufferSizeBytes(0), d_deviceBufferSizeFrames(0), d_deviceBufferSizeBytes(0), d_leadSizeFrames(0), d_leadSizeBytes(0), d_trailSizeFrames(0), d_trailSizeBytes(0), d_extraBufferSizeFrames(0), d_extraBufferSizeBytes(0), d_queueSampleCount(0), d_max_sample_count(0), d_n_AvailableInputFrames(0), d_n_ActualInputFrames(0), d_n_user_channels(0), d_n_max_channels(0), d_n_deviceChannels(0), d_do_block(do_block), d_passThrough(false), d_internal(0), d_cond_data(0), d_buffers(0), d_InputAU(0), d_InputBuffer(0), d_OutputBuffer(0), d_AudioConverter(0) { if(sample_rate <= 0) { std::cerr << "Invalid Sample Rate: " << sample_rate << std::endl; throw std::invalid_argument("audio_osx_source::audio_osx_source"); } else d_outputSampleRate = (Float64)sample_rate; if(channel_config <= 0 & channel_config != -1) { std::cerr << "Invalid Channel Config: " << channel_config << std::endl; throw std::invalid_argument("audio_osx_source::audio_osx_source"); } else if (channel_config == -1) { // no user input; try "device name" instead int l_n_channels = (int)strtol(device_name.data(), (char **)NULL, 10); if((l_n_channels == 0) & errno) { std::cerr << "Error Converting Device Name: " << errno << std::endl; throw std::invalid_argument("audio_osx_source::audio_osx_source"); } if(l_n_channels <= 0) channel_config = 2; else channel_config = l_n_channels; } d_channel_config = channel_config; // check that the max # of samples to store is valid if(max_sample_count == -1) max_sample_count = sample_rate; else if(max_sample_count <= 0) { std::cerr << "Invalid Max Sample Count: " << max_sample_count << std::endl; throw std::invalid_argument("audio_osx_source::audio_osx_source"); } d_max_sample_count = max_sample_count; #if _OSX_AU_DEBUG_ std::cerr << "source(): max # samples = " << d_max_sample_count << std::endl; #endif OSStatus err = noErr; // create the default AudioUnit for input // Open the default input unit #ifndef GR_USE_OLD_AUDIO_UNIT AudioComponentDescription InputDesc; #else ComponentDescription InputDesc; #endif InputDesc.componentType = kAudioUnitType_Output; InputDesc.componentSubType = kAudioUnitSubType_HALOutput; InputDesc.componentManufacturer = kAudioUnitManufacturer_Apple; InputDesc.componentFlags = 0; InputDesc.componentFlagsMask = 0; #ifndef GR_USE_OLD_AUDIO_UNIT AudioComponent comp = AudioComponentFindNext(NULL, &InputDesc); #else Component comp = FindNextComponent(NULL, &InputDesc); #endif if(comp == NULL) { #ifndef GR_USE_OLD_AUDIO_UNIT std::cerr << "AudioComponentFindNext Error" << std::endl; #else std::cerr << "FindNextComponent Error" << std::endl; #endif throw std::runtime_error("audio_osx_source::audio_osx_source"); } #ifndef GR_USE_OLD_AUDIO_UNIT err = AudioComponentInstanceNew(comp, &d_InputAU); CheckErrorAndThrow(err, "AudioComponentInstanceNew", "audio_osx_source::audio_osx_source"); #else err = OpenAComponent(comp, &d_InputAU); CheckErrorAndThrow(err, "OpenAComponent", "audio_osx_source::audio_osx_source"); #endif UInt32 enableIO; // must enable the AUHAL for input and disable output // before setting the AUHAL's current device // Enable input on the AUHAL enableIO = 1; err = AudioUnitSetProperty(d_InputAU, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, // input element &enableIO, sizeof(UInt32)); CheckErrorAndThrow(err, "AudioUnitSetProperty Input Enable", "audio_osx_source::audio_osx_source"); // Disable output on the AUHAL enableIO = 0; err = AudioUnitSetProperty(d_InputAU, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, // output element &enableIO, sizeof (UInt32)); CheckErrorAndThrow(err, "AudioUnitSetProperty Output Disable", "audio_osx_source::audio_osx_source"); // set the default input device for our input AU SetDefaultInputDeviceAsCurrent(); #if _OSX_DO_LISTENERS_ // set up a listener if default hardware input device changes err = AudioHardwareAddPropertyListener (kAudioHardwarePropertyDefaultInputDevice, (AudioHardwarePropertyListenerProc)HardwareListener, this); CheckErrorAndThrow(err, "AudioHardwareAddPropertyListener", "audio_osx_source::audio_osx_source"); // Add a listener for any changes in the input AU's output stream // the function "UnitListener" will be called if the stream format // changes for whatever reason err = AudioUnitAddPropertyListener (d_InputAU, kAudioUnitProperty_StreamFormat, (AudioUnitPropertyListenerProc)UnitListener, this); CheckErrorAndThrow(err, "Adding Unit Property Listener", "audio_osx_source::audio_osx_source"); #endif // Now find out if it actually can do input. UInt32 hasInput = 0; UInt32 dataSize = sizeof(hasInput); err = AudioUnitGetProperty(d_InputAU, kAudioOutputUnitProperty_HasIO, kAudioUnitScope_Input, 1, &hasInput, &dataSize); CheckErrorAndThrow(err, "AudioUnitGetProperty HasIO", "audio_osx_source::audio_osx_source"); if(hasInput == 0) { std::cerr << "Selected Audio Device does not support Input." << std::endl; throw std::runtime_error("audio_osx_source::audio_osx_source"); } // Set up a callback function to retrieve input from the Audio Device AURenderCallbackStruct AUCallBack; AUCallBack.inputProc = (AURenderCallback)(osx_source::AUInputCallback); AUCallBack.inputProcRefCon = this; err = AudioUnitSetProperty(d_InputAU, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &AUCallBack, sizeof (AURenderCallbackStruct)); CheckErrorAndThrow(err, "AudioUnitSetProperty Input Callback", "audio_osx_source::audio_osx_source"); UInt32 propertySize; AudioStreamBasicDescription asbd_device, asbd_client, asbd_user; // asbd_device: ASBD of the device that is creating the input data stream // asbd_client: ASBD of the client size (output) of the hardware device // asbd_user: ASBD of the user's arguments // Get the Stream Format (device side) propertySize = sizeof(asbd_device); err = AudioUnitGetProperty(d_InputAU, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &asbd_device, &propertySize); CheckErrorAndThrow(err, "AudioUnitGetProperty Device Input Stream Format", "audio_osx_source::audio_osx_source"); #if _OSX_AU_DEBUG_ std::cerr << std::endl << "---- Device Stream Format ----" << std::endl; PrintStreamDesc(&asbd_device); #endif // Get the Stream Format (client side) propertySize = sizeof(asbd_client); err = AudioUnitGetProperty(d_InputAU, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &asbd_client, &propertySize); CheckErrorAndThrow(err, "AudioUnitGetProperty Device Ouput Stream Format", "audio_osx_source::audio_osx_source"); #if _OSX_AU_DEBUG_ std::cerr << std::endl << "---- Client Stream Format ----" << std::endl; PrintStreamDesc(&asbd_client); #endif // Set the format of all the AUs to the input/output devices channel count // get the max number of input (& thus output) channels supported by // this device d_n_max_channels = asbd_device.mChannelsPerFrame; // create the output io signature; // no input siganture to set (source is hardware) set_output_signature(io_signature::make(1, d_n_max_channels, sizeof(float))); // allocate the output circular buffer(s), one per channel d_buffers = (circular_buffer**)new circular_buffer* [d_n_max_channels]; UInt32 n_alloc = (UInt32)ceil((double)d_max_sample_count); for(UInt32 n = 0; n < d_n_max_channels; n++) { d_buffers[n] = new circular_buffer(n_alloc, false, false); } d_deviceSampleRate = asbd_device.mSampleRate; d_n_deviceChannels = asbd_device.mChannelsPerFrame; asbd_client.mSampleRate = asbd_device.mSampleRate; asbd_client.mFormatID = kAudioFormatLinearPCM; asbd_client.mFormatFlags = (kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved); if((asbd_client.mFormatID == kAudioFormatLinearPCM) && (d_n_deviceChannels == 1)) { asbd_client.mFormatFlags &= ~kLinearPCMFormatFlagIsNonInterleaved; } asbd_client.mBytesPerFrame = sizeof(float); asbd_client.mFramesPerPacket = 1; asbd_client.mBitsPerChannel = asbd_client.mBytesPerFrame * 8; asbd_client.mChannelsPerFrame = d_n_deviceChannels; asbd_client.mBytesPerPacket = asbd_client.mBytesPerFrame; propertySize = sizeof(AudioStreamBasicDescription); err = AudioUnitSetProperty(d_InputAU, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &asbd_client, propertySize); CheckErrorAndThrow(err, "AudioUnitSetProperty Device Ouput Stream Format", "audio_osx_source::audio_osx_source"); // create an ASBD for the user's wants asbd_user.mSampleRate = d_outputSampleRate; asbd_user.mFormatID = kAudioFormatLinearPCM; asbd_user.mFormatFlags = (kLinearPCMFormatFlagIsFloat | GR_PCM_ENDIANNESS | kLinearPCMFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved); asbd_user.mBytesPerPacket = sizeof(float); asbd_user.mFramesPerPacket = 1; asbd_user.mBytesPerFrame = asbd_user.mBytesPerPacket; asbd_user.mChannelsPerFrame = d_n_deviceChannels; asbd_user.mBitsPerChannel = asbd_user.mBytesPerPacket * 8; if(d_deviceSampleRate == d_outputSampleRate) { // no need to do conversion if asbd_client matches user wants d_passThrough = true; d_leadSizeFrames = d_trailSizeFrames = 0L; } else { d_passThrough = false; // Create the audio converter err = AudioConverterNew(&asbd_client, &asbd_user, &d_AudioConverter); CheckErrorAndThrow(err, "AudioConverterNew", "audio_osx_source::audio_osx_source"); // Set the audio converter sample rate quality to "max" ... // requires more samples, but should sound nicer UInt32 ACQuality = kAudioConverterQuality_Max; propertySize = sizeof(ACQuality); err = AudioConverterSetProperty(d_AudioConverter, kAudioConverterSampleRateConverterQuality, propertySize, &ACQuality); CheckErrorAndThrow(err, "AudioConverterSetProperty " "SampleRateConverterQuality", "audio_osx_source::audio_osx_source"); // set the audio converter's prime method to "pre", // which uses both leading and trailing frames // from the "current input". All of this is handled // internally by the AudioConverter; we just supply // the frames for conversion. // UInt32 ACPrimeMethod = kConverterPrimeMethod_None; UInt32 ACPrimeMethod = kConverterPrimeMethod_Pre; propertySize = sizeof (ACPrimeMethod); err = AudioConverterSetProperty(d_AudioConverter, kAudioConverterPrimeMethod, propertySize, &ACPrimeMethod); CheckErrorAndThrow(err, "AudioConverterSetProperty PrimeMethod", "audio_osx_source::audio_osx_source"); // Get the size of the I/O buffer(s) to allow for pre-allocated buffers // lead frame info (trail frame info is ignored) AudioConverterPrimeInfo ACPrimeInfo = {0, 0}; propertySize = sizeof(ACPrimeInfo); err = AudioConverterGetProperty(d_AudioConverter, kAudioConverterPrimeInfo, &propertySize, &ACPrimeInfo); CheckErrorAndThrow(err, "AudioConverterGetProperty PrimeInfo", "audio_osx_source::audio_osx_source"); switch(ACPrimeMethod) { case(kConverterPrimeMethod_None): d_leadSizeFrames = d_trailSizeFrames = 0L; break; case(kConverterPrimeMethod_Normal): d_leadSizeFrames = 0L; d_trailSizeFrames = ACPrimeInfo.trailingFrames; break; default: d_leadSizeFrames = ACPrimeInfo.leadingFrames; d_trailSizeFrames = ACPrimeInfo.trailingFrames; } } d_leadSizeBytes = d_leadSizeFrames * sizeof(Float32); d_trailSizeBytes = d_trailSizeFrames * sizeof(Float32); propertySize = sizeof(d_deviceBufferSizeFrames); err = AudioUnitGetProperty(d_InputAU, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &d_deviceBufferSizeFrames, &propertySize); CheckErrorAndThrow(err, "AudioUnitGetProperty Buffer Frame Size", "audio_osx_source::audio_osx_source"); d_deviceBufferSizeBytes = d_deviceBufferSizeFrames * sizeof(Float32); d_inputBufferSizeBytes = d_deviceBufferSizeBytes + d_leadSizeBytes; d_inputBufferSizeFrames = d_deviceBufferSizeFrames + d_leadSizeFrames; // outBufSizeBytes = floor (inBufSizeBytes * rate_out / rate_in) // since this is rarely exact, we need another buffer to hold // "extra" samples not processed at any given sampling period // this buffer must be at least 4 floats in size, but generally // follows the rule that // extraBufSize = ceil (rate_in / rate_out)*sizeof(float) d_extraBufferSizeFrames = ((UInt32)ceil(d_deviceSampleRate / d_outputSampleRate) * sizeof(float)); if(d_extraBufferSizeFrames < 4) d_extraBufferSizeFrames = 4; d_extraBufferSizeBytes = d_extraBufferSizeFrames * sizeof(float); d_outputBufferSizeFrames = (UInt32)ceil(((Float64)d_inputBufferSizeFrames) * d_outputSampleRate / d_deviceSampleRate); d_outputBufferSizeBytes = d_outputBufferSizeFrames * sizeof(float); d_inputBufferSizeFrames += d_extraBufferSizeFrames; // pre-alloc all buffers AllocAudioBufferList(&d_InputBuffer, d_n_deviceChannels, d_inputBufferSizeBytes); if(d_passThrough == false) { AllocAudioBufferList(&d_OutputBuffer, d_n_max_channels, d_outputBufferSizeBytes); } else { d_OutputBuffer = d_InputBuffer; } // create the stuff to regulate I/O d_cond_data = new gr::thread::condition_variable(); if(d_cond_data == NULL) CheckErrorAndThrow(errno, "new condition (data)", "audio_osx_source::audio_osx_source"); d_internal = new gr::thread::mutex(); if(d_internal == NULL) CheckErrorAndThrow(errno, "new mutex (internal)", "audio_osx_source::audio_osx_source"); // initialize the AU for input err = AudioUnitInitialize(d_InputAU); CheckErrorAndThrow(err, "AudioUnitInitialize", "audio_osx_source::audio_osx_source"); #if _OSX_AU_DEBUG_ std::cerr << "audio_osx_source Parameters:" << std::endl; std::cerr << " Device Sample Rate is " << d_deviceSampleRate << std::endl; std::cerr << " User Sample Rate is " << d_outputSampleRate << std::endl; std::cerr << " Max Sample Count is " << d_max_sample_count << std::endl; std::cerr << " # Device Channels is " << d_n_deviceChannels << std::endl; std::cerr << " # Max Channels is " << d_n_max_channels << std::endl; std::cerr << " Device Buffer Size is Frames = " << d_deviceBufferSizeFrames << std::endl; std::cerr << " Lead Size is Frames = " << d_leadSizeFrames << std::endl; std::cerr << " Trail Size is Frames = " << d_trailSizeFrames << std::endl; std::cerr << " Input Buffer Size is Frames = " << d_inputBufferSizeFrames << std::endl; std::cerr << " Output Buffer Size is Frames = " << d_outputBufferSizeFrames << std::endl; #endif } void osx_source::AllocAudioBufferList(AudioBufferList** t_ABL, UInt32 n_channels, UInt32 bufferSizeBytes) { FreeAudioBufferList(t_ABL); UInt32 propertySize = (offsetof(AudioBufferList, mBuffers[0]) + (sizeof(AudioBuffer) * n_channels)); *t_ABL = (AudioBufferList*)calloc(1, propertySize); (*t_ABL)->mNumberBuffers = n_channels; int counter = n_channels; while(--counter >= 0) { (*t_ABL)->mBuffers[counter].mNumberChannels = 1; (*t_ABL)->mBuffers[counter].mDataByteSize = bufferSizeBytes; (*t_ABL)->mBuffers[counter].mData = calloc (1, bufferSizeBytes); } } void osx_source::FreeAudioBufferList(AudioBufferList** t_ABL) { // free pre-allocated audio buffer, if it exists if(*t_ABL != NULL) { int counter = (*t_ABL)->mNumberBuffers; while(--counter >= 0) free((*t_ABL)->mBuffers[counter].mData); free(*t_ABL); (*t_ABL) = 0; } } bool osx_source::IsRunning() { UInt32 AURunning = 0, AUSize = sizeof(UInt32); OSStatus err = AudioUnitGetProperty(d_InputAU, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, 0, &AURunning, &AUSize); CheckErrorAndThrow(err, "AudioUnitGetProperty IsRunning", "audio_osx_source::IsRunning"); return (AURunning); } bool osx_source::start() { if(! IsRunning ()) { OSStatus err = AudioOutputUnitStart(d_InputAU); CheckErrorAndThrow(err, "AudioOutputUnitStart", "audio_osx_source::start"); } return (true); } bool osx_source::stop() { if(IsRunning ()) { OSStatus err = AudioOutputUnitStop(d_InputAU); CheckErrorAndThrow(err, "AudioOutputUnitStart", "audio_osx_source::stop"); for(UInt32 n = 0; n < d_n_user_channels; n++) { d_buffers[n]->abort (); } } return (true); } osx_source::~osx_source() { OSStatus err = noErr; // stop the AudioUnit stop(); #if _OSX_DO_LISTENERS_ // remove the listeners err = AudioUnitRemovePropertyListener (d_InputAU, kAudioUnitProperty_StreamFormat, (AudioUnitPropertyListenerProc)UnitListener); CheckError(err, "~audio_osx_source: AudioUnitRemovePropertyListener"); err = AudioHardwareRemovePropertyListener (kAudioHardwarePropertyDefaultInputDevice, (AudioHardwarePropertyListenerProc)HardwareListener); CheckError(err, "~audio_osx_source: AudioHardwareRemovePropertyListener"); #endif // free pre-allocated audio buffers FreeAudioBufferList(&d_InputBuffer); if(d_passThrough == false) { err = AudioConverterDispose(d_AudioConverter); CheckError(err, "~audio_osx_source: AudioConverterDispose"); FreeAudioBufferList(&d_OutputBuffer); } // remove the audio unit err = AudioUnitUninitialize(d_InputAU); CheckError(err, "~audio_osx_source: AudioUnitUninitialize"); #ifndef GR_USE_OLD_AUDIO_UNIT err = AudioComponentInstanceDispose(d_InputAU); CheckError(err, "~audio_osx_source: AudioComponentInstanceDispose"); #else err = CloseComponent(d_InputAU); CheckError(err, "~audio_osx_source: CloseComponent"); #endif // empty and delete the queues for(UInt32 n = 0; n < d_n_max_channels; n++) { delete d_buffers[n]; d_buffers[n] = 0; } delete [] d_buffers; d_buffers = 0; // close and delete the control stuff delete d_cond_data; d_cond_data = 0; delete d_internal; d_internal = 0; } bool osx_source::check_topology(int ninputs, int noutputs) { // check # inputs to make sure it's valid if(ninputs != 0) { std::cerr << "audio_osx_source::check_topology(): number of input " << "streams provided (" << ninputs << ") should be 0." << std::endl; throw std::runtime_error("audio_osx_source::check_topology()"); } // check # outputs to make sure it's valid if((noutputs < 1) | (noutputs > (int) d_n_max_channels)) { std::cerr << "audio_osx_source::check_topology(): number of output " << "streams provided (" << noutputs << ") should be in [1," << d_n_max_channels << "] for the selected audio device." << std::endl; throw std::runtime_error("audio_osx_source::check_topology()"); } // save the actual number of output (user) channels d_n_user_channels = noutputs; #if _OSX_AU_DEBUG_ std::cerr << "chk_topo: Actual # user output channels = " << noutputs << std::endl; #endif return (true); } int osx_source::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // acquire control to do processing here only gr::thread::scoped_lock l(*d_internal); #if _OSX_AU_DEBUG_ std::cerr << "work1: SC = " << d_queueSampleCount << ", #OI = " << noutput_items << ", #Chan = " << output_items.size() << std::endl; #endif // set the actual # of output items to the 'desired' amount then // verify that data is available; if not enough data is available, // either wait until it is (is "do_block" is true), return (0) is no // data is available and "do_block" is false, or process the actual // amount of available data. UInt32 actual_noutput_items = noutput_items; if(d_queueSampleCount < actual_noutput_items) { if(d_queueSampleCount == 0) { // no data; do_block decides what to do if(d_do_block == true) { while(d_queueSampleCount == 0) { // release control so-as to allow data to be retrieved; // block until there is data to return d_cond_data->wait(l); // the condition's 'notify' was called; acquire control to // keep thread safe } } else { // no data & not blocking; return nothing return (0); } } // use the actual amount of available data actual_noutput_items = d_queueSampleCount; } // number of channels int l_counter = (int)output_items.size(); // copy the items from the circular buffer(s) to 'work's output buffers // verify that the number copied out is as expected. while(--l_counter >= 0) { size_t t_n_output_items = actual_noutput_items; d_buffers[l_counter]->dequeue((float*)output_items[l_counter], &t_n_output_items); if(t_n_output_items != actual_noutput_items) { std::cerr << "audio_osx_source::work(): ERROR: number of " << "available items changing unexpectedly; expecting " << actual_noutput_items << ", got " << t_n_output_items << "." << std::endl; throw std::runtime_error("audio_osx_source::work()"); } } // subtract the actual number of items removed from the buffer(s) // from the local accounting of the number of available samples d_queueSampleCount -= actual_noutput_items; #if _OSX_AU_DEBUG_ std::cerr << "work2: SC = " << d_queueSampleCount << ", act#OI = " << actual_noutput_items << std::endl << "Returning." << std::endl; #endif return (actual_noutput_items); } OSStatus osx_source::ConverterCallback(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets, AudioBufferList* ioData, AudioStreamPacketDescription** ioASPD, void* inUserData) { // take current device buffers and copy them to the tail of the // input buffers the lead buffer is already there in the first // d_leadSizeFrames slots osx_source* This = static_cast(inUserData); AudioBufferList* l_inputABL = This->d_InputBuffer; UInt32 totalInputBufferSizeBytes = ((*ioNumberDataPackets) * sizeof(float)); int counter = This->d_n_deviceChannels; ioData->mNumberBuffers = This->d_n_deviceChannels; This->d_n_ActualInputFrames = (*ioNumberDataPackets); #if _OSX_AU_DEBUG_ std::cerr << "cc1: io#DP = " << (*ioNumberDataPackets) << ", TIBSB = " << totalInputBufferSizeBytes << ", #C = " << counter << std::endl; #endif while(--counter >= 0) { AudioBuffer* l_ioD_AB = &(ioData->mBuffers[counter]); l_ioD_AB->mNumberChannels = 1; l_ioD_AB->mData = (float*)(l_inputABL->mBuffers[counter].mData); l_ioD_AB->mDataByteSize = totalInputBufferSizeBytes; } #if _OSX_AU_DEBUG_ std::cerr << "cc2: Returning." << std::endl; #endif return (noErr); } OSStatus osx_source::AUInputCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) { OSStatus err = noErr; osx_source* This = static_cast(inRefCon); gr::thread::scoped_lock l(*This->d_internal); #if _OSX_AU_DEBUG_ std::cerr << "cb0: in#F = " << inNumberFrames << ", inBN = " << inBusNumber << ", SC = " << This->d_queueSampleCount << std::endl; #endif // Get the new audio data from the input device err = AudioUnitRender(This->d_InputAU, ioActionFlags, inTimeStamp, 1, //inBusNumber, inNumberFrames, This->d_InputBuffer); CheckErrorAndThrow(err, "AudioUnitRender", "audio_osx_source::AUInputCallback"); UInt32 AvailableInputFrames = inNumberFrames; This->d_n_AvailableInputFrames = inNumberFrames; // get the number of actual output frames, // either via converting the buffer or not UInt32 ActualOutputFrames; if(This->d_passThrough == true) { ActualOutputFrames = AvailableInputFrames; } else { UInt32 AvailableInputBytes = AvailableInputFrames * sizeof(float); UInt32 AvailableOutputBytes = AvailableInputBytes; UInt32 AvailableOutputFrames = AvailableOutputBytes / sizeof(float); UInt32 propertySize = sizeof (AvailableOutputBytes); err = AudioConverterGetProperty(This->d_AudioConverter, kAudioConverterPropertyCalculateOutputBufferSize, &propertySize, &AvailableOutputBytes); CheckErrorAndThrow(err, "AudioConverterGetProperty CalculateOutputBufferSize", "audio_osx_source::audio_osx_source"); AvailableOutputFrames = AvailableOutputBytes / sizeof(float); #if 0 // when decimating too much, the output sounds warbly due to // fluctuating # of output frames // This should not be a surprise, but there's probably some // clever programming that could lessed the effect ... // like finding the "ideal" # of output frames, and keeping // that number constant no matter the # of input frames UInt32 l_InputBytes = AvailableOutputBytes; propertySize = sizeof(AvailableOutputBytes); err = AudioConverterGetProperty(This->d_AudioConverter, kAudioConverterPropertyCalculateInputBufferSize, &propertySize, &l_InputBytes); CheckErrorAndThrow(err, "AudioConverterGetProperty CalculateInputBufferSize", "audio_osx_source::audio_osx_source"); if(l_InputBytes < AvailableInputBytes) { // OK to zero pad the input a little AvailableOutputFrames += 1; AvailableOutputBytes = AvailableOutputFrames * sizeof(float); } #endif #if _OSX_AU_DEBUG_ std::cerr << "cb1: avail: #IF = " << AvailableInputFrames << ", #OF = " << AvailableOutputFrames << std::endl; #endif ActualOutputFrames = AvailableOutputFrames; // convert the data to the correct rate // on input, ActualOutputFrames is the number of available output frames err = AudioConverterFillComplexBuffer(This->d_AudioConverter, (AudioConverterComplexInputDataProc) (This->ConverterCallback), inRefCon, &ActualOutputFrames, This->d_OutputBuffer, NULL); CheckErrorAndThrow(err, "AudioConverterFillComplexBuffer", "audio_osx_source::AUInputCallback"); // on output, ActualOutputFrames is the actual number of output frames #if _OSX_AU_DEBUG_ std::cerr << "cb2: actual: #IF = " << This->d_n_ActualInputFrames << ", #OF = " << AvailableOutputFrames << std::endl; if(This->d_n_ActualInputFrames != AvailableInputFrames) std::cerr << "cb2.1: avail#IF = " << AvailableInputFrames << ", actual#IF = " << This->d_n_ActualInputFrames << std::endl; #endif } // add the output frames to the buffers' queue, checking for overflow int l_counter = This->d_n_user_channels; int res = 0; while(--l_counter >= 0) { float* inBuffer = (float*) This->d_OutputBuffer->mBuffers[l_counter].mData; #if _OSX_AU_DEBUG_ std::cerr << "cb3: enqueuing audio data." << std::endl; #endif int l_res = This->d_buffers[l_counter]->enqueue(inBuffer, ActualOutputFrames); if(l_res == -1) res = -1; } if(res == -1) { // data coming in too fast // drop oldest buffer fputs("aO", stderr); fflush(stderr); // set the local number of samples available to the max This->d_queueSampleCount = This->d_buffers[0]->buffer_length_items(); } else { // keep up the local sample count This->d_queueSampleCount += ActualOutputFrames; } #if _OSX_AU_DEBUG_ std::cerr << "cb4: #OI = " << ActualOutputFrames << ", #Cnt = " << This->d_queueSampleCount << ", mSC = " << This->d_max_sample_count << std::endl; #endif // signal that data is available, if appropraite This->d_cond_data->notify_one(); #if _OSX_AU_DEBUG_ std::cerr << "cb5: returning." << std::endl; #endif return (err); } void osx_source::SetDefaultInputDeviceAsCurrent() { // set the default input device AudioDeviceID deviceID = 0; UInt32 dataSize = sizeof (AudioDeviceID); OSStatus err = noErr; #ifndef GR_USE_OLD_AUDIO_UNIT AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, &dataSize, &deviceID); #else err = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &dataSize, &deviceID); #endif CheckErrorAndThrow(err, "Get Audio Unit Property for Current Device", "audio_osx_source::SetDefaultInputDeviceAsCurrent"); err = AudioUnitSetProperty(d_InputAU, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceID, sizeof(AudioDeviceID)); CheckErrorAndThrow(err, "AudioUnitSetProperty Current Device", "audio_osx_source::SetDefaultInputDeviceAsCurrent"); } #if _OSX_DO_LISTENERS_ OSStatus osx_source::HardwareListener(AudioHardwarePropertyID inPropertyID, void *inClientData) { OSStatus err = noErr; osx_source* This = static_cast(inClientData); std::cerr << "a_o_s::HardwareListener" << std::endl; // set the new default hardware input device for use by our AU This->SetDefaultInputDeviceAsCurrent(); // reset the converter to tell it that the stream has changed err = AudioConverterReset(This->d_AudioConverter); CheckErrorAndThrow(err, "AudioConverterReset", "audio_osx_source::UnitListener"); return (err); } OSStatus osx_source::UnitListener(void *inRefCon, AudioUnit ci, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement) { OSStatus err = noErr; osx_source* This = static_cast(inRefCon); AudioStreamBasicDescription asbd; std::cerr << "a_o_s::UnitListener" << std::endl; // get the converter's input ASBD (for printing) UInt32 propertySize = sizeof(asbd); err = AudioConverterGetProperty(This->d_AudioConverter, kAudioConverterCurrentInputStreamDescription, &propertySize, &asbd); CheckErrorAndThrow(err, "AudioConverterGetProperty " "CurrentInputStreamDescription", "audio_osx_source::UnitListener"); std::cerr << "UnitListener: Input Source changed." << std::endl << "Old Source Output Info:" << std::endl; PrintStreamDesc(&asbd); // get the new input unit's output ASBD propertySize = sizeof(asbd); err = AudioUnitGetProperty(This->d_InputAU, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &asbd, &propertySize); CheckErrorAndThrow(err, "AudioUnitGetProperty StreamFormat", "audio_osx_source::UnitListener"); std::cerr << "New Source Output Info:" << std::endl; PrintStreamDesc(&asbd); // set the converter's input ASBD to this err = AudioConverterSetProperty(This->d_AudioConverter, kAudioConverterCurrentInputStreamDescription, propertySize, &asbd); CheckErrorAndThrow(err, "AudioConverterSetProperty " "CurrentInputStreamDescription", "audio_osx_source::UnitListener"); // reset the converter to tell it that the stream has changed err = AudioConverterReset(This->d_AudioConverter); CheckErrorAndThrow(err, "AudioConverterReset", "audio_osx_source::UnitListener"); return (err); } #endif /* _OSX_DO_LISTENERS_ */ } /* namespace audio */ } /* namespace gr */ gnuradio-3.7.2.1/gr-audio/lib/osx/osx_source.h0000664000175000017500000001075212207440367020766 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_AUDIO_OSX_SOURCE_H #define INCLUDED_AUDIO_OSX_SOURCE_H #include #include #include #include #include namespace gr { namespace audio { /*! * \brief audio source using OSX * \ingroup audio_blk * * Input signature is one or two streams of floats. * Samples must be in the range [-1,1]. */ class osx_source : public source { Float64 d_deviceSampleRate, d_outputSampleRate; int d_channel_config; UInt32 d_inputBufferSizeFrames, d_inputBufferSizeBytes; UInt32 d_outputBufferSizeFrames, d_outputBufferSizeBytes; UInt32 d_deviceBufferSizeFrames, d_deviceBufferSizeBytes; UInt32 d_leadSizeFrames, d_leadSizeBytes; UInt32 d_trailSizeFrames, d_trailSizeBytes; UInt32 d_extraBufferSizeFrames, d_extraBufferSizeBytes; UInt32 d_queueSampleCount, d_max_sample_count; UInt32 d_n_AvailableInputFrames, d_n_ActualInputFrames; UInt32 d_n_user_channels, d_n_max_channels, d_n_deviceChannels; bool d_do_block, d_passThrough, d_waiting_for_data; gr::thread::mutex* d_internal; gr::thread::condition_variable* d_cond_data; circular_buffer** d_buffers; // AudioUnits and Such AudioUnit d_InputAU; AudioBufferList* d_InputBuffer; AudioBufferList* d_OutputBuffer; AudioConverterRef d_AudioConverter; public: osx_source(int sample_rate = 44100, const std::string device_name = "", bool do_block = true, int channel_config = -1, int max_sample_count = -1); ~osx_source(); bool start(); bool stop(); bool IsRunning(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); private: void SetDefaultInputDeviceAsCurrent(); void AllocAudioBufferList(AudioBufferList** t_ABL, UInt32 n_channels, UInt32 inputBufferSizeBytes); void FreeAudioBufferList(AudioBufferList** t_ABL); static OSStatus ConverterCallback(AudioConverterRef inAudioConverter, UInt32* ioNumberDataPackets, AudioBufferList* ioData, AudioStreamPacketDescription** outASPD, void* inUserData); static OSStatus AUInputCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); #if _OSX_DO_LISTENERS_ static OSStatus UnitListener(void *inRefCon, AudioUnit ci, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement); static OSStatus HardwareListener(AudioHardwarePropertyID inPropertyID, void *inClientData); #endif }; } /* namespace audio */ } /* namespace gr */ #endif /* INCLUDED_AUDIO_OSX_SOURCE_H */ gnuradio-3.7.2.1/gr-audio/lib/osx/circular_buffer.h0000664000175000017500000002325212207440367021731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio. * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _CIRCULAR_BUFFER_H_ #define _CIRCULAR_BUFFER_H_ #include #include #include #ifndef DO_DEBUG #define DO_DEBUG 0 #endif #if DO_DEBUG #define DEBUG(X) do{X} while(0); #else #define DEBUG(X) do{} while(0); #endif template class circular_buffer { private: // the buffer to use T* d_buffer; // the following are in Items (type T) size_t d_bufLen_I, d_readNdx_I, d_writeNdx_I; size_t d_n_avail_write_I, d_n_avail_read_I; // stuff to control access to class internals gr::thread::mutex* d_internal; gr::thread::condition_variable* d_readBlock; gr::thread::condition_variable* d_writeBlock; // booleans to decide how to control reading, writing, and aborting bool d_doWriteBlock, d_doFullRead, d_doAbort; void delete_mutex_cond () { if (d_internal) { delete d_internal; d_internal = NULL; } if (d_readBlock) { delete d_readBlock; d_readBlock = NULL; } if (d_writeBlock) { delete d_writeBlock; d_writeBlock = NULL; } }; public: circular_buffer (size_t bufLen_I, bool doWriteBlock = true, bool doFullRead = false) { if (bufLen_I == 0) throw std::runtime_error ("circular_buffer(): " "Number of items to buffer must be > 0.\n"); d_bufLen_I = bufLen_I; d_buffer = (T*) new T[d_bufLen_I]; d_doWriteBlock = doWriteBlock; d_doFullRead = doFullRead; d_internal = NULL; d_readBlock = d_writeBlock = NULL; reset (); DEBUG (std::cerr << "c_b(): buf len (items) = " << d_bufLen_ << ", doWriteBlock = " << (d_doWriteBlock ? "true" : "false") << ", doFullRead = " << (d_doFullRead ? "true" : "false") << std::endl); }; ~circular_buffer () { delete_mutex_cond (); delete [] d_buffer; }; inline size_t n_avail_write_items () { gr::thread::scoped_lock l (*d_internal); size_t retVal = d_n_avail_write_I; return (retVal); }; inline size_t n_avail_read_items () { gr::thread::scoped_lock l (*d_internal); size_t retVal = d_n_avail_read_I; return (retVal); }; inline size_t buffer_length_items () {return (d_bufLen_I);}; inline bool do_write_block () {return (d_doWriteBlock);}; inline bool do_full_read () {return (d_doFullRead);}; void reset () { d_doAbort = false; bzero (d_buffer, d_bufLen_I * sizeof (T)); d_readNdx_I = d_writeNdx_I = d_n_avail_read_I = 0; d_n_avail_write_I = d_bufLen_I; delete_mutex_cond (); // create a mutex to handle contention of shared resources; // any routine needed access to shared resources uses lock() // before doing anything, then unlock() when finished. d_internal = new gr::thread::mutex (); // link the internal mutex to the read and write conditions; // when wait() is called, the internal mutex will automatically // be unlock()'ed. Upon return (from a notify_one() to the condition), // the internal mutex will be lock()'ed. d_readBlock = new gr::thread::condition_variable (); d_writeBlock = new gr::thread::condition_variable (); }; /* * enqueue: add the given buffer of item-length to the queue, * first-in-first-out (FIFO). * * inputs: * buf: a pointer to the buffer holding the data * * bufLen_I: the buffer length in items (of the instantiated type) * * returns: * -1: on overflow (write is not blocking, and data is being * written faster than it is being read) * 0: if nothing to do (0 length buffer) * 1: if success * 2: in the process of aborting, do doing nothing * * will throw runtime errors if inputs are improper: * buffer pointer is NULL * buffer length is larger than the instantiated buffer length */ int enqueue (T* buf, size_t bufLen_I) { DEBUG (std::cerr << "enqueue: buf = " << (void*) buf << ", bufLen = " << bufLen_I << ", #av_wr = " << d_n_avail_write_I << ", #av_rd = " << d_n_avail_read_I << std::endl); if (bufLen_I > d_bufLen_I) { std::cerr << "ERROR: cannot add buffer longer (" << bufLen_I << ") than instantiated length (" << d_bufLen_I << ")." << std::endl; throw std::runtime_error ("circular_buffer::enqueue()"); } if (bufLen_I == 0) return (0); if (!buf) throw std::runtime_error ("circular_buffer::enqueue(): " "input buffer is NULL.\n"); gr::thread::scoped_lock l (*d_internal); if (d_doAbort) { return (2); } // set the return value to 1: success; change if needed int retval = 1; if (bufLen_I > d_n_avail_write_I) { if (d_doWriteBlock) { while (bufLen_I > d_n_avail_write_I) { DEBUG (std::cerr << "enqueue: #len > #a, waiting." << std::endl); // wait; will automatically unlock() the internal mutex via // the scoped lock d_writeBlock->wait (l); // and auto re-lock() it here. if (d_doAbort) { DEBUG (std::cerr << "enqueue: #len > #a, aborting." << std::endl); return (2); } DEBUG (std::cerr << "enqueue: #len > #a, done waiting." << std::endl); } } else { d_n_avail_read_I = d_bufLen_I - bufLen_I; d_n_avail_write_I = bufLen_I; DEBUG (std::cerr << "circular_buffer::enqueue: overflow" << std::endl); retval = -1; } } size_t n_now_I = d_bufLen_I - d_writeNdx_I, n_start_I = 0; if (n_now_I > bufLen_I) n_now_I = bufLen_I; else if (n_now_I < bufLen_I) n_start_I = bufLen_I - n_now_I; bcopy (buf, &(d_buffer[d_writeNdx_I]), n_now_I * sizeof (T)); if (n_start_I) { bcopy (&(buf[n_now_I]), d_buffer, n_start_I * sizeof (T)); d_writeNdx_I = n_start_I; } else d_writeNdx_I += n_now_I; d_n_avail_read_I += bufLen_I; d_n_avail_write_I -= bufLen_I; d_readBlock->notify_one (); return (retval); }; /* * dequeue: removes from the queue the number of items requested, or * available, into the given buffer on a FIFO basis. * * inputs: * buf: a pointer to the buffer into which to copy the data * * bufLen_I: pointer to the number of items to remove in items * (of the instantiated type) * * returns: * 0: if nothing to do (0 length buffer) * 1: if success * 2: in the process of aborting, do doing nothing * * will throw runtime errors if inputs are improper: * buffer pointer is NULL * buffer length pointer is NULL * buffer length is larger than the instantiated buffer length */ int dequeue (T* buf, size_t* bufLen_I) { DEBUG (std::cerr << "dequeue: buf = " << ((void*) buf) << ", *bufLen = " << (*bufLen_I) << ", #av_wr = " << d_n_avail_write_I << ", #av_rd = " << d_n_avail_read_I << std::endl); if (!bufLen_I) throw std::runtime_error ("circular_buffer::dequeue(): " "input bufLen pointer is NULL.\n"); if (!buf) throw std::runtime_error ("circular_buffer::dequeue(): " "input buffer pointer is NULL.\n"); size_t l_bufLen_I = *bufLen_I; if (l_bufLen_I == 0) return (0); if (l_bufLen_I > d_bufLen_I) { std::cerr << "ERROR: cannot remove buffer longer (" << l_bufLen_I << ") than instantiated length (" << d_bufLen_I << ")." << std::endl; throw std::runtime_error ("circular_buffer::dequeue()"); } gr::thread::scoped_lock l (*d_internal); if (d_doAbort) { return (2); } if (d_doFullRead) { while (d_n_avail_read_I < l_bufLen_I) { DEBUG (std::cerr << "dequeue: #a < #len, waiting." << std::endl); // wait; will automatically unlock() the internal mutex via // the scoped lock d_readBlock->wait (l); // and re-lock() it here. if (d_doAbort) { DEBUG (std::cerr << "dequeue: #a < #len, aborting." << std::endl); return (2); } DEBUG (std::cerr << "dequeue: #a < #len, done waiting." << std::endl); } } else { while (d_n_avail_read_I == 0) { DEBUG (std::cerr << "dequeue: #a == 0, waiting." << std::endl); // wait; will automatically unlock() the internal mutex via // the scoped lock d_readBlock->wait (l); // and re-lock() it here. if (d_doAbort) { DEBUG (std::cerr << "dequeue: #a == 0, aborting." << std::endl); return (2); } DEBUG (std::cerr << "dequeue: #a == 0, done waiting." << std::endl); } } if (l_bufLen_I > d_n_avail_read_I) l_bufLen_I = d_n_avail_read_I; size_t n_now_I = d_bufLen_I - d_readNdx_I, n_start_I = 0; if (n_now_I > l_bufLen_I) n_now_I = l_bufLen_I; else if (n_now_I < l_bufLen_I) n_start_I = l_bufLen_I - n_now_I; bcopy (&(d_buffer[d_readNdx_I]), buf, n_now_I * sizeof (T)); if (n_start_I) { bcopy (d_buffer, &(buf[n_now_I]), n_start_I * sizeof (T)); d_readNdx_I = n_start_I; } else d_readNdx_I += n_now_I; *bufLen_I = l_bufLen_I; d_n_avail_read_I -= l_bufLen_I; d_n_avail_write_I += l_bufLen_I; d_writeBlock->notify_one (); return (1); }; void abort () { gr::thread::scoped_lock l (*d_internal); d_doAbort = true; d_writeBlock->notify_one (); d_readBlock->notify_one (); }; }; #endif /* _CIRCULAR_BUFFER_H_ */ gnuradio-3.7.2.1/gr-audio/swig/0000755000175000017500000000000012207440367016007 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/swig/CMakeLists.txt0000664000175000017500000000342412207440367020554 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_AUDIO_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/audio_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/audio) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-audio) GR_SWIG_MAKE(audio_swig audio_swig.i) GR_SWIG_INSTALL( TARGETS audio_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/audio COMPONENT "audio_python" ) install( FILES audio_swig.i ${CMAKE_CURRENT_BINARY_DIR}/audio_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "audio_swig" ) gnuradio-3.7.2.1/gr-audio/swig/audio_swig.i0000664000175000017500000000215512207440367020320 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define GR_AUDIO_API %include "gnuradio.i" //load generated python docstrings %include "audio_swig_doc.i" %{ #include #include %} %include %include GR_SWIG_BLOCK_MAGIC2(audio, source) GR_SWIG_BLOCK_MAGIC2(audio, sink) gnuradio-3.7.2.1/gr-audio/examples/0000755000175000017500000000000011744612271016654 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/examples/grc/0000755000175000017500000000000012207440367017427 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/examples/grc/CMakeLists.txt0000644000175000017500000000162011744612271022166 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES cvsd_sweep.grc dial_tone.grc DESTINATION ${GR_PKG_AUDIO_EXAMPLES_DIR} COMPONENT "audio_python" ) gnuradio-3.7.2.1/gr-audio/examples/grc/cvsd_sweep.grc0000664000175000017500000005053512207440367022300 0ustar jcorganjcorgan Sat Nov 10 15:10:11 2012 options id cvsd_sweep _enabled True title CVSD Vocoder Test author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 import id import_0 _enabled True import import math _coordinate (157, 11) _rotation 0 vocoder_cvsd_decode_bf id vocoder_cvsd_decode_bf_0 _enabled True resample resample bw bw _coordinate (887, 340) _rotation 0 blocks_vco_f id vco _enabled True samp_rate audio_rate sensitivity audio_rate*2*math.pi amplitude 0.9 _coordinate (427, 332) _rotation 0 vocoder_cvsd_encode_fb id enc _enabled True resample resample bw bw _coordinate (655, 340) _rotation 0 blocks_packed_to_unpacked_xx id p2u _enabled True type byte bits_per_chunk 1 endianness gr.GR_MSB_FIRST num_ports 1 _coordinate (648, 415) _rotation 180 blocks_char_to_float id c2f _enabled True vlen 1 scale 1 _coordinate (676, 483) _rotation 0 audio_sink id audio_sink _enabled True samp_rate audio_rate device_name plughw:0,0 ok_to_block True num_inputs 1 _coordinate (1127, 340) _rotation 0 variable id audio_rate _enabled True value 8000 _coordinate (251, 10) _rotation 0 variable id resample _enabled True value 8 _coordinate (344, 11) _rotation 0 variable id bw _enabled True value 0.5 _coordinate (431, 11) _rotation 0 notebook id displays _enabled True style wx.NB_TOP labels ['Original','Encoded','Decoded'] grid_pos notebook _coordinate (12, 106) _rotation 0 wxgui_fftsink2 id orig_fft _enabled True type float title Original Spectrum samp_rate audio_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 0 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos 0, 0, 1, 1 notebook displays, 0 freqvar None _coordinate (415, 97) _rotation 180 wxgui_scopesink2 id orig_scope _enabled True type float title Original Waveform samp_rate audio_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos 1, 0, 1, 1 notebook displays, 0 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (414, 425) _rotation 180 wxgui_scopesink2 id enc_scope _enabled True type float title Encoded Waveform samp_rate audio_rate*resample v_scale 0.5 v_offset 0 t_scale 20.0/(audio_rate*resample) ac_couple False xy_mode False num_inputs 1 win_size grid_pos 0, 0, 1, 1 notebook displays, 1 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (858, 591) _rotation 0 wxgui_fftsink2 id dec_fft _enabled True type float title Decoded Spectrum samp_rate audio_rate baseband_freq 0 y_per_div 5 y_divs 10 ref_level 10 ref_scale 0.1 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos 0, 0, 1, 1 notebook displays, 2 freqvar None _coordinate (891, 98) _rotation 180 wxgui_scopesink2 id dec_scope _enabled True type float title Decoded Waveform samp_rate audio_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos 1, 0, 1, 1 notebook displays, 2 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (889, 422) _rotation 180 blocks_throttle id throttle _enabled True type float samples_per_second audio_rate vlen 1 _coordinate (238, 348) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate audio_rate waveform analog.GR_TRI_WAVE freq 0.05 amp 0.5 offset 0 _coordinate (29, 316) _rotation 0 wxgui_fftsink2 id enc_fft _enabled True type float title Encoded Spectrum samp_rate audio_rate*resample baseband_freq 0 y_per_div 10 y_divs 8 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos 1, 0, 1, 1 notebook displays, 1 freqvar None _coordinate (610, 559) _rotation 180 vco orig_fft 0 0 throttle vco 0 0 vco enc 0 0 enc vocoder_cvsd_decode_bf_0 0 0 vco orig_scope 0 0 vocoder_cvsd_decode_bf_0 dec_fft 0 0 vocoder_cvsd_decode_bf_0 dec_scope 0 0 vocoder_cvsd_decode_bf_0 audio_sink 0 0 enc p2u 0 0 p2u c2f 0 0 c2f enc_fft 0 0 c2f enc_scope 0 0 analog_sig_source_x_0 throttle 0 0 gnuradio-3.7.2.1/gr-audio/examples/grc/dial_tone.grc0000664000175000017500000002012112207440367022060 0ustar jcorganjcorgan Sat Nov 10 15:10:08 2012 options id dial_tone _enabled True title Dial Tone author Example description example flow graph window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 audio_sink id audio_sink _enabled True samp_rate 32000 device_name ok_to_block True num_inputs 1 _coordinate (699, 112) _rotation 0 variable_slider id ampl _enabled True label Volume value .4 min 0 max .5 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 0, 0, 1, 2 notebook _coordinate (634, 413) _rotation 0 variable_slider id noise _enabled True label Noise value .005 min 0 max .2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 1, 0, 1, 2 notebook _coordinate (443, 412) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (11, 171) _rotation 0 blocks_add_xx id blocks_add_xx _enabled True type float num_inputs 3 vlen 1 _coordinate (513, 277) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq 350 amp ampl offset 0 _coordinate (251, 100) _rotation 0 analog_sig_source_x id analog_sig_source_x_1 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq 440 amp ampl offset 0 _coordinate (250, 214) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type float noise_type analog.GR_GAUSSIAN amp noise seed -42 _coordinate (245, 342) _rotation 0 blocks_add_xx audio_sink 0 0 analog_sig_source_x_0 blocks_add_xx 0 0 analog_sig_source_x_1 blocks_add_xx 0 1 analog_noise_source_x_0 blocks_add_xx 0 2 gnuradio-3.7.2.1/gr-audio/examples/python/0000755000175000017500000000000012207440367020175 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/examples/python/audio_fft.py0000755000175000017500000001076411744612271022522 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, audio from gnuradio import eng_notation from gnuradio.eng_option import eng_option from gnuradio.wxgui import stdgui2, fftsink2, waterfallsink2, scopesink2, form, slider from optparse import OptionParser import wx import sys class app_top_block(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) self.frame = frame self.panel = panel parser = OptionParser(option_class=eng_option) parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Enable waterfall display") parser.add_option("-S", "--oscilloscope", action="store_true", default=False, help="Enable oscilloscope display") parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") (options, args) = parser.parse_args() sample_rate = int(options.sample_rate) if len(args) != 0: parser.print_help() sys.exit(1) self.show_debug_info = True # build the graph if options.waterfall: self.scope = \ waterfallsink2.waterfall_sink_f (panel, fft_size=1024, sample_rate=sample_rate) elif options.oscilloscope: self.scope = scopesink2.scope_sink_f(panel, sample_rate=sample_rate) else: self.scope = fftsink2.fft_sink_f (panel, fft_size=1024, sample_rate=sample_rate, fft_rate=30, ref_scale=1.0, ref_level=0, y_divs=12) self.src = audio.source (sample_rate, options.audio_input) self.connect(self.src, self.scope) self._build_gui(vbox) # set initial values def _set_status_msg(self, msg): self.frame.GetStatusBar().SetStatusText(msg, 0) def _build_gui(self, vbox): def _form_set_freq(kv): return self.set_freq(kv['freq']) vbox.Add(self.scope.win, 10, wx.EXPAND) #self._build_subpanel(vbox) def _build_subpanel(self, vbox_arg): # build a secondary information panel (sometimes hidden) # FIXME figure out how to have this be a subpanel that is always # created, but has its visibility controlled by foo.Show(True/False) def _form_set_decim(kv): return self.set_decim(kv['decim']) if not(self.show_debug_info): return panel = self.panel vbox = vbox_arg myform = self.myform #panel = wx.Panel(self.panel, -1) #vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['decim'] = form.int_field( parent=panel, sizer=hbox, label="Decim", callback=myform.check_input_and_call(_form_set_decim, self._set_status_msg)) hbox.Add((5,0), 1) myform['fs@usb'] = form.static_float_field( parent=panel, sizer=hbox, label="Fs@USB") hbox.Add((5,0), 1) myform['dbname'] = form.static_text_field( parent=panel, sizer=hbox) hbox.Add((5,0), 1) myform['baseband'] = form.static_float_field( parent=panel, sizer=hbox, label="Analog BB") hbox.Add((5,0), 1) myform['ddc'] = form.static_float_field( parent=panel, sizer=hbox, label="DDC") hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) def main (): app = stdgui2.stdapp(app_top_block, "Audio FFT", nstatus=1) app.MainLoop() if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-audio/examples/python/CMakeLists.txt0000644000175000017500000000215511744612271022740 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS audio_copy.py audio_fft.py audio_play.py audio_to_file.py dial_tone.py dial_tone_daemon.py dial_tone_wav.py mono_tone.py multi_tone.py noise.py spectrum_inversion.py test_resampler.py DESTINATION ${GR_PKG_AUDIO_EXAMPLES_DIR} COMPONENT "audio_python" ) gnuradio-3.7.2.1/gr-audio/examples/python/noise.py0000775000175000017500000000366012207440367021676 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import digital from gnuradio.eng_option import eng_option from optparse import OptionParser class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) ampl = 0.1 src = digital.glfsr_source_b(32) # Pseudorandom noise source b2f = digital.chunks_to_symbols_bf([ampl, -ampl], 1) dst = audio.sink(sample_rate, options.audio_output) self.connect(src, b2f, dst) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/dial_tone_daemon.py0000775000175000017500000000422412207440367024037 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2008,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru from gnuradio import audio from gnuradio.eng_option import eng_option from optparse import OptionParser import os try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) ampl = 0.1 src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl) src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl) dst = audio.sink(sample_rate, options.audio_output) self.connect(src0, (dst, 0)) self.connect(src1, (dst, 1)) if __name__ == '__main__': pid = gru.daemonize() print "To stop this program, enter 'kill %d'" % pid my_top_block().run() gnuradio-3.7.2.1/gr-audio/examples/python/dial_tone_wav.py0000775000175000017500000000453612207440367023377 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2008,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # GNU Radio example program to record a dial tone to a WAV file from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) usage = "%prog: [options] filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option("-N", "--samples", type="eng_float", default=None, help="number of samples to record") (options, args) = parser.parse_args () if len(args) != 1 or options.samples is None: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) ampl = 0.1 src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl) src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl) head0 = blocks.head(gr.sizeof_float, int(options.samples)) head1 = blocks.head(gr.sizeof_float, int(options.samples)) dst = blocks.wavfile_sink(args[0], 2, int(options.sample_rate), 16) self.connect(src0, head0, (dst, 0)) self.connect(src1, head1, (dst, 1)) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/test_resampler.py0000775000175000017500000000515212207440367023610 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru from gnuradio import audio from gnuradio import filter from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import blocks except ImportError: sys.stderr.write("Error: Program requires gr-blocks.\n") sys.exit(1) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-i", "--input-rate", type="eng_float", default=8000, help="set input sample rate to RATE (%default)") parser.add_option("-o", "--output-rate", type="eng_float", default=48000, help="set output sample rate to RATE (%default)") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 input_rate = int(options.input_rate) output_rate = int(options.output_rate) interp = gru.lcm(input_rate, output_rate) / input_rate decim = gru.lcm(input_rate, output_rate) / output_rate print "interp =", interp print "decim =", decim ampl = 0.1 src0 = analog.sig_source_f(input_rate, analog.GR_SIN_WAVE, 650, ampl) rr = filter.rational_resampler_fff(interp, decim) dst = audio.sink(output_rate, options.audio_output) self.connect(src0, rr, (dst, 0)) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/audio_to_file.py0000775000175000017500000000437612207440367023370 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) usage="%prog: [options] output_filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option("-N", "--nsamples", type="eng_float", default=None, help="number of samples to collect [default=+inf]") (options, args) = parser.parse_args () if len(args) != 1: parser.print_help() raise SystemExit, 1 filename = args[0] sample_rate = int(options.sample_rate) src = audio.source (sample_rate, options.audio_input) dst = blocks.file_sink (gr.sizeof_float, filename) if options.nsamples is None: self.connect((src, 0), dst) else: head = blocks.head(gr.sizeof_float, int(options.nsamples)) self.connect((src, 0), head, dst) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/multi_tone.py0000775000175000017500000000641012207440367022734 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2006,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) #import os #print os.getpid() #raw_input('Attach gdb and press Enter: ') class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option ("-m", "--max-channels", type="int", default="16", help="set maximum channels to use") parser.add_option("-D", "--dont-block", action="store_false", default=True, dest="ok_to_block") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) limit_channels = options.max_channels ampl = 0.1 # With a tip of the hat to Harry Partch, may he R.I.P. # See "Genesis of a Music". He was into some very wild tunings... base = 392 ratios = { 1 : 1.0, 3 : 3.0/2, 5 : 5.0/4, 7 : 7.0/4, 9 : 9.0/8, 11 : 11.0/8 } # progression = (1, 5, 3, 7) # progression = (1, 9, 3, 7) # progression = (3, 7, 9, 11) # progression = (7, 11, 1, 5) progression = (7, 11, 1, 5, 9) dst = audio.sink(sample_rate, options.audio_output, options.ok_to_block) max_chan = dst.input_signature().max_streams() if (max_chan == -1) or (max_chan > limit_channels): max_chan = limit_channels for i in range(max_chan): quo, rem = divmod(i, len (progression)) freq = base * ratios[progression[rem]] * (quo + 1) src = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, freq, ampl) self.connect(src, (dst, i)) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/audio_copy.py0000755000175000017500000000450111744612271022705 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio.eng_option import eng_option from optparse import OptionParser class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) src = audio.source (sample_rate, options.audio_input) dst = audio.sink (sample_rate, options.audio_output) # Determine the maximum number of outputs on the source and # maximum number of inputs on the sink, then connect together # the most channels we can without overlap nchan = min (src.output_signature().max_streams(), dst.input_signature().max_streams()) for i in range (nchan): self.connect ((src, i), (dst, i)) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/audio_play.py0000775000175000017500000000411212207440367022700 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-F", "--filename", type="string", default="audio.dat", help="read input from FILE") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option("-R", "--repeat", action="store_true", default=False) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) src = blocks.file_source (gr.sizeof_float, options.filename, options.repeat) dst = audio.sink (sample_rate, options.audio_output) self.connect(src, dst) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/dial_tone.py0000775000175000017500000000414612207440367022517 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) ampl = 0.1 src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, ampl) src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, ampl) dst = audio.sink(sample_rate, options.audio_output) self.connect(src0, (dst, 0)) self.connect(src1, (dst, 1)) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/spectrum_inversion.py0000775000175000017500000000463712207440367024524 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # Gang - Here's a simple script that demonstrates spectrum inversion # using the multiply by [1,-1] method (mixing with Nyquist frequency). # Requires nothing but a sound card, and sounds just like listening # to a SSB signal on the wrong sideband. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=8000, help="set sample rate to RATE (8000)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) src = audio.source (sample_rate, options.audio_input) dst = audio.sink (sample_rate, options.audio_output) vec1 = [1, -1] vsource = blocks.vector_source_f(vec1, True) multiply = blocks.multiply_ff() self.connect(src, (multiply, 0)) self.connect(vsource, (multiply, 1)) self.connect(multiply, dst) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/python/mono_tone.py0000775000175000017500000000441312207440367022553 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) #import os #print os.getpid() #raw_input('Attach gdb and press Enter: ') class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) parser = OptionParser(option_class=eng_option) parser.add_option("-O", "--audio-output", type="string", default="", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option("-D", "--dont-block", action="store_false", default=True, dest="ok_to_block") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 sample_rate = int(options.sample_rate) ampl = 0.1 src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 650, ampl) dst = audio.sink(sample_rate, options.audio_output, options.ok_to_block) self.connect (src0, (dst, 0)) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-audio/examples/c++/0000755000175000017500000000000012207440367017224 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-audio/examples/c++/CMakeLists.txt0000664000175000017500000000220012207440367021760 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include_directories( ${GR_AUDIO_INCLUDE_DIRS} ${GR_ANALOG_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) add_executable(dial_tone dial_tone.cc) target_link_libraries(dial_tone gnuradio-runtime gnuradio-audio gnuradio-analog) INSTALL(TARGETS dial_tone DESTINATION ${GR_PKG_AUDIO_EXAMPLES_DIR} COMPONENT "audio_examples" ) gnuradio-3.7.2.1/gr-audio/examples/c++/dial_tone.cc0000664000175000017500000000603312207440367021475 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * GNU Radio C++ example creating dial tone * ("the simplest thing that could possibly work") * * Send a tone each to the left and right channels of stereo audio * output and let the user's brain sum them. * * GNU Radio makes extensive use of Boost shared pointers. Signal processing * blocks are typically created by calling a "make" factory function, which * returns an instance of the block as a typedef'd shared pointer that can * be used in any way a regular pointer can. Shared pointers created this way * keep track of their memory and free it at the right time, so the user * doesn't need to worry about it (really). * */ // Include header files for each block used in flowgraph #include #include #include using namespace gr; int main(int argc, char **argv) { int rate = 48000; // Audio card sample rate float ampl = 0.1; // Don't exceed 0.5 or clipping will occur // Construct a top block that will contain flowgraph blocks. Alternatively, // one may create a derived class from top_block and hold instantiated blocks // as member data for later manipulation. top_block_sptr tb = make_top_block("dial_tone"); // Construct a real-valued signal source for each tone, at given sample rate analog::sig_source_f::sptr src0 = analog::sig_source_f::make(rate, analog::GR_SIN_WAVE, 350, ampl); analog::sig_source_f::sptr src1 = analog::sig_source_f::make(rate, analog::GR_SIN_WAVE, 440, ampl); // Construct an audio sink to accept audio tones audio::sink::sptr sink = audio::sink::make(rate); // Connect output #0 of src0 to input #0 of sink (left channel) tb->connect(src0, 0, sink, 0); // Connect output #0 of src1 to input #1 of sink (right channel) tb->connect(src1, 0, sink, 1); // Tell GNU Radio runtime to start flowgraph threads; the foreground thread // will block until either flowgraph exits (this example doesn't) or the // application receives SIGINT (e.g., user hits CTRL-C). // // Real applications may use tb->start() which returns, allowing the foreground // thread to proceed, then later use tb->stop(), followed by tb->wait(), to cleanup // GNU Radio before exiting. tb->run(); // Exit normally. return 0; } gnuradio-3.7.2.1/gr-wxgui/0000755000175000017500000000000012235766174015110 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/CMakeLists.txt0000664000175000017500000000756612235766174017670 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) include(GrPython) GR_PYTHON_CHECK_MODULE("wx >= 2.8" wx "wx.version().split()[0] >= '2.8'" WX_FOUND) GR_PYTHON_CHECK_MODULE("numpy" numpy True NUMPY_FOUND) ######################################################################## # Register component ######################################################################## include(GrComponent) if(NOT CMAKE_CROSSCOMPILING) set(wxgui_python_deps NUMPY_FOUND WX_FOUND ) endif(NOT CMAKE_CROSSCOMPILING) GR_REGISTER_COMPONENT("gr-wxgui" ENABLE_GR_WXGUI ENABLE_GNURADIO_RUNTIME ENABLE_GR_FFT ENABLE_GR_FILTER ENABLE_GR_ANALOG ENABLE_PYTHON ${wxgui_python_deps} ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_WXGUI) GR_SET_GLOBAL(GR_WXGUI_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/lib ${CMAKE_CURRENT_BINARY_DIR}/include ) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_COMPONENT("wxgui_runtime" DISPLAY_NAME "WxGUI" DESCRIPTION "Wx GUI plotter widgets and grc wrappers" DEPENDS "runtime_python" ) CPACK_COMPONENT("wxgui_devel" GROUP "WxGUI" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("wxgui_python" GROUP "WxGUI" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;wxgui_runtime" ) CPACK_COMPONENT("wxgui_swig" GROUP "WxGUI" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;wxgui_python;wxgui_devel" ) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gr-wxgui.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gr-wxgui.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gr-wxgui.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "wxgui" ) ######################################################################## # Install the conf file ######################################################################## install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/gr-wxgui.conf DESTINATION ${GR_PREFSDIR} COMPONENT "wxgui" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/wxgui) add_subdirectory(lib) add_subdirectory(grc) add_subdirectory(python/wxgui) add_subdirectory(swig) endif(ENABLE_GR_WXGUI) gnuradio-3.7.2.1/gr-wxgui/include/0000775000175000017500000000000012207440367016525 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/include/gnuradio/0000775000175000017500000000000012207440367020335 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/0000775000175000017500000000000012207440367021500 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/CMakeLists.txt0000664000175000017500000000217312207440367024243 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h histo_sink_f.h oscope_guts.h oscope_sink_f.h oscope_sink_x.h trigger_mode.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/wxgui COMPONENT "wxgui_devel" ) gnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/trigger_mode.h0000664000175000017500000000231612207440367024322 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TRIGGER_MODE_H #define INCLUDED_GR_TRIGGER_MODE_H namespace gr { namespace wxgui { enum trigger_mode { TRIG_MODE_FREE, TRIG_MODE_AUTO, TRIG_MODE_NORM, TRIG_MODE_STRIPCHART, }; enum trigger_slope { TRIG_SLOPE_POS, TRIG_SLOPE_NEG, }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_TRIGGER_MODE_H */ gnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/histo_sink_f.h0000664000175000017500000000316112207440367024331 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_HISTO_SINK_F_H #define INCLUDED_GR_HISTO_SINK_F_H #include #include #include namespace gr { namespace wxgui { /*! * \brief Histogram module. * \ingroup sink_blk */ class WXGUI_API histo_sink_f : virtual public sync_block { public: // gr::blocks::histo_sink_f::sptr typedef boost::shared_ptr sptr; static sptr make(msg_queue::sptr msgq); virtual unsigned int get_frame_size(void) = 0; virtual unsigned int get_num_bins(void) = 0; virtual void set_frame_size(unsigned int frame_size) = 0; virtual void set_num_bins(unsigned int num_bins) = 0; }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_HISTO_SINK_F_H */ gnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/oscope_sink_x.h0000664000175000017500000000570212207440367024520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_OSCOPE_SINK_X_H #define INCLUDED_GR_OSCOPE_SINK_X_H #include #include #include #include namespace gr { namespace wxgui { /*! * \brief Abstract class for python oscilloscope module. * \ingroup sink_blk * * Don't instantiate this. Use gr::blocks::oscope_sink_f instead. */ class WXGUI_API oscope_sink_x : public sync_block { protected: double d_sampling_rate; oscope_guts *d_guts; oscope_sink_x() {}; oscope_sink_x(const std::string name, gr::io_signature::sptr input_sig, double sampling_rate); public: virtual ~oscope_sink_x(); //// gr::blocks::oscope_sink_x::sptr //typedef boost::shared_ptr sptr; // //static sptr make(const std::string name, // gnuradio/io_signature.h_sptr input_sig, // double sampling_rate); bool set_update_rate(double update_rate); bool set_decimation_count(int decimation_count); bool set_trigger_channel(int channel); bool set_trigger_mode(trigger_mode mode); bool set_trigger_slope(trigger_slope slope); bool set_trigger_level(double trigger_level); bool set_trigger_level_auto(); bool set_sample_rate(double sample_rate); bool set_num_channels(int nchannels); // ACCESSORS int num_channels() const; double sample_rate() const; double update_rate() const; int get_decimation_count() const; int get_trigger_channel() const; trigger_mode get_trigger_mode() const; trigger_slope get_trigger_slope() const; double get_trigger_level() const; // # of samples written to each output record. int get_samples_per_output_record() const; virtual int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) = 0; }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_OSCOPE_SINK_X_H */ gnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/oscope_guts.h0000664000175000017500000001075712207440367024215 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_OSCOPE_GUTS_H #define INCLUDED_GR_OSCOPE_GUTS_H #include #include #include namespace gr { namespace wxgui { /*! * \brief guts of oscilloscope trigger and buffer module * * This module processes sets of samples provided the \p * process_sample method. When appropriate given the updateRate, * sampleRate and trigger conditions, process_sample will * periodically write output records of captured data to * output_fd. For each trigger event, nchannels records will be * written. Each record consists of get_samples_per_output_record * binary floats. The trigger instant occurs at the 1/2 way point * in the buffer. Thus, output records consist of 50% pre-trigger * data and 50% post-trigger data. */ class WXGUI_API oscope_guts { public: static const int MAX_CHANNELS = 8; private: enum scope_state { HOLD_OFF, LOOK_FOR_TRIGGER, POST_TRIGGER }; int d_nchannels; // how many channels msg_queue::sptr d_msgq; // message queue we stuff output records into trigger_mode d_trigger_mode; trigger_slope d_trigger_slope; int d_trigger_channel; // which channel to watch for trigger condition double d_sample_rate; // input sample rate in Hz double d_update_rate; // approx freq to produce an output record (Hz) double d_trigger_level; int d_obi; // output buffer index float *d_buffer[MAX_CHANNELS]; scope_state d_state; int d_decimator_count; int d_decimator_count_init; int d_hold_off_count; int d_hold_off_count_init; int d_pre_trigger_count; int d_post_trigger_count; int d_post_trigger_count_init; float d_trigger_off; //%sample trigger is off // NOT IMPLEMENTED oscope_guts(const oscope_guts &rhs); // no copy constructor oscope_guts &operator= (const oscope_guts &rhs); // no assignment operator void trigger_changed(); void update_rate_or_decimation_changed(); bool found_trigger(); // returns true if found void write_output_records(); void enter_hold_off(); // called on state entry void enter_look_for_trigger(); void enter_post_trigger(); public: // CREATORS oscope_guts(double sample_rate, msg_queue::sptr msgq); ~oscope_guts(); // MANIPULATORS /*! * \param channel_data points to nchannels float values. These * are the values for each channel at this sample time. */ void process_sample(const float *channel_data); bool set_update_rate(double update_rate); bool set_decimation_count(int decimation_count); bool set_trigger_channel(int channel); bool set_trigger_mode(trigger_mode mode); bool set_trigger_slope(trigger_slope slope); bool set_trigger_level(double trigger_level); bool set_trigger_level_auto(); // set to 50% level bool set_sample_rate(double sample_rate); bool set_num_channels(int nchannels); // ACCESSORS int num_channels() const; double sample_rate() const; double update_rate() const; int get_decimation_count() const; int get_trigger_channel() const; trigger_mode get_trigger_mode() const; trigger_slope get_trigger_slope() const; double get_trigger_level() const; // # of samples written to each output record. int get_samples_per_output_record() const; }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_OSCOPE_GUTS_H */ gnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/oscope_sink_f.h0000664000175000017500000000301212207440367024466 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003-2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_OSCOPE_SINK_F_H #define INCLUDED_GR_OSCOPE_SINK_F_H #include #include #include namespace gr { namespace wxgui { /*! * \brief Building block for python oscilloscope module. * \ingroup sink_blk * * Accepts multiple float streams. */ class WXGUI_API oscope_sink_f : virtual public oscope_sink_x { public: // gr::blocks::oscope_sink_f::sptr typedef boost::shared_ptr sptr; static sptr make(double sampling_rate, msg_queue::sptr msgq); }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_OSCOPE_SINK_F_H */ gnuradio-3.7.2.1/gr-wxgui/include/gnuradio/wxgui/api.h0000664000175000017500000000203112207440367022416 0ustar jcorganjcorgan/* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WXGUI_API_H #define INCLUDED_WXGUI_API_H #include #ifdef gnuradio_wxgui_EXPORTS # define WXGUI_API __GR_ATTR_EXPORT #else # define WXGUI_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_WXGUI_API_H */ gnuradio-3.7.2.1/gr-wxgui/grc/0000755000175000017500000000000012207440367015653 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/grc/variable_static_text.xml0000664000175000017500000000460512207440367022604 0ustar jcorganjcorgan WX GUI Static Text variable_static_text GUI Widgets/WX from gnuradio.wxgui import forms self.$(id) = $(id) = $value #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' #set $win = 'self._%s_static_text'%$id $win = forms.static_text( parent=$(parent).GetWin(), value=self.$id, callback=self.set_$(id), #if $label() label=$label, #else label='$id', #end if #if $formatter() converter=forms.$(converver)(formatter=$formatter), #else converter=forms.$(converver)(), #end if ) #if not $grid_pos() $(parent).Add($win) #else $(parent).GridAdd($win, $(', '.join(map(str, $grid_pos())))) #end if self.set_$(id)($value) self._$(id)_static_text.set_value($id) Label label string #if $label() then 'none' else 'part'# Default Value value 0 raw Converter converver float_converter enum Formatter formatter None raw part Grid Position grid_pos grid_pos Notebook notebook notebook This block creates a variable with a static text form. \ Leave the label blank to use the variable id as the label. Format should be a function/lambda that converts a value into a string or None for the default formatter. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/CMakeLists.txt0000644000175000017500000000246411744612271020421 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "wxgui") ######################################################################## #The wxgui module contains a top_block + wxgui frame. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py panel.py top_block_gui.py DESTINATION ${GR_PYTHON_DIR}/grc_gnuradio/wxgui COMPONENT "wxgui" ) gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_numbersink2.xml0000664000175000017500000001017712207440367022067 0ustar jcorganjcorgan WX GUI Number Sink wxgui_numbersink2 Instrumentation/WX from gnuradio.wxgui import numbersink2 from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' numbersink2.$(type.fcn)( $(parent).GetWin(), unit=$units, minval=$min_value, maxval=$max_value, factor=$factor, decimal_places=$decimal_places, ref_level=$ref_level, sample_rate=$samp_rate, number_rate=$number_rate, average=$average, avg_alpha=#if $avg_alpha() then $avg_alpha else 'None'#, label=$title, peak_hold=$peak_hold, show_gauge=$show_gauge, #if $win_size() size=$win_size, #end if ) #if not $grid_pos() $(parent).Add(self.$(id).win) #else $(parent).GridAdd(self.$(id).win, $(', '.join(map(str, $grid_pos())))) #end if Type type complex enum Title title Number Plot string Units units Units string Sample Rate samp_rate samp_rate real Min Value min_value -100 real Max Value max_value 100 real Factor factor 1.0 real Decimal Places decimal_places 10 int Reference Level ref_level 0 real Number Rate number_rate 15 int Peak Hold peak_hold False enum #if $peak_hold() == 'True' then 'none' else 'part'# Average average False enum part Average Alpha avg_alpha 0 real #if $average() == 'True' then 'none' else 'all'# Show Gauge show_gauge True enum Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook not $win_size or len($win_size) == 2 in $type Set Average Alpha to 0 for automatic setting. Leave the window blank for the default size, otherwise enter a tuple of (width, height) pixels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. Incoming numbers are multiplied by the factor, and then added-to by the reference level. gnuradio-3.7.2.1/gr-wxgui/grc/variable_slider.xml0000664000175000017500000000637312207440367021537 0ustar jcorganjcorgan WX GUI Slider variable_slider GUI Widgets/WX from gnuradio.wxgui import forms self.$(id) = $(id) = $value #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' #set $win = '_%s_sizer'%$id $win = wx.BoxSizer(wx.VERTICAL) self._$(id)_text_box = forms.text_box( parent=$(parent).GetWin(), sizer=$win, value=self.$id, callback=self.set_$(id), #if $label() label=$label, #else label='$id', #end if converter=forms.$(converver)(), proportion=0, ) self._$(id)_slider = forms.slider( parent=$(parent).GetWin(), sizer=$win, value=self.$id, callback=self.set_$(id), minimum=$min, maximum=$max, num_steps=$num_steps, style=$style, cast=$(converver.slider_cast), proportion=1, ) #if not $grid_pos() $(parent).Add($win) #else $(parent).GridAdd($win, $(', '.join(map(str, $grid_pos())))) #end if self.set_$(id)($value) self._$(id)_slider.set_value($id) self._$(id)_text_box.set_value($id) Label label string #if $label() then 'none' else 'part'# Default Value value 50 real Minimum min 0 real Maximum max 100 real Num Steps num_steps 100 int part Style style wx.SL_HORIZONTAL enum part Converter converver float_converter enum Grid Position grid_pos grid_pos Notebook notebook notebook $min <= $value <= $max $min < $max 0 < $num_steps <= 1000 This block creates a variable with a slider. \ Leave the label blank to use the variable id as the label. \ The value must be a real number. \ The value must be between the minimum and the maximum. \ The number of steps must be between 0 and 1000. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/variable_text_box.xml0000664000175000017500000000466512207440367022113 0ustar jcorganjcorgan WX GUI Text Box variable_text_box GUI Widgets/WX from gnuradio.wxgui import forms self.$(id) = $(id) = $value #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' #set $win = 'self._%s_text_box'%$id $win = forms.text_box( parent=$(parent).GetWin(), value=self.$id, callback=self.set_$(id), #if $label() label=$label, #else label='$id', #end if #if $formatter() converter=forms.$(converver)(formatter=$formatter), #else converter=forms.$(converver)(), #end if ) #if not $grid_pos() $(parent).Add($win) #else $(parent).GridAdd($win, $(', '.join(map(str, $grid_pos())))) #end if self.set_$(id)($value) self._$(id)_text_box.set_value($id) Label label string #if $label() then 'none' else 'part'# Default Value value 0 raw Converter converver float_converter enum Formatter formatter None raw part Grid Position grid_pos grid_pos Notebook notebook notebook This block creates a variable with a text box. \ Leave the label blank to use the variable id as the label. Format should be a function/lambda that converts a value into a string or None for the default formatter. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_constellationsink2.xml0000664000175000017500000000606212207440367023453 0ustar jcorganjcorgan WX GUI Constellation Sink wxgui_constellationsink2 Instrumentation/WX from gnuradio.wxgui import constsink_gl from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' constsink_gl.const_sink_c( $(parent).GetWin(), title=$title, sample_rate=$samp_rate, frame_rate=$frame_rate, const_size=$const_size, M=$M, theta=$theta, loop_bw=$loop_bw, fmax=$fmax, mu=$mu, gain_mu=$gain_mu, symbol_rate=$symbol_rate, omega_limit=$omega_limit, #if $win_size() size=$win_size, #end if ) #if not $grid_pos() $(parent).Add(self.$(id).win) #else $(parent).GridAdd(self.$(id).win, $(', '.join(map(str, $grid_pos())))) #end if set_sample_rate($samp_rate) Title title Constellation Plot string Sample Rate samp_rate samp_rate real Frame Rate frame_rate 5 real Constellation Size const_size 2048 real M M 4 int Theta theta 0 real Loop Bandwidth loop_bw 6.28/100.0 real Max Freq fmax 0.06 real Mu mu 0.5 real Gain Mu gain_mu 0.005 real Symbol Rate symbol_rate samp_rate/4. real Omega Limit omega_limit 0.005 real Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook not $win_size or len($win_size) == 2 in complex Leave the window blank for the default size, otherwise enter a tuple of (width, height) pixels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_waterfallsink2.xml0000664000175000017500000001065412207440367022560 0ustar jcorganjcorgan WX GUI Waterfall Sink wxgui_waterfallsink2 Instrumentation/WX from gnuradio.fft import window from gnuradio.wxgui import waterfallsink2 from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' waterfallsink2.$(type.fcn)( $(parent).GetWin(), baseband_freq=$baseband_freq, dynamic_range=$dynamic_range, ref_level=$ref_level, ref_scale=$ref_scale, sample_rate=$samp_rate, fft_size=$fft_size, fft_rate=$fft_rate, average=$average, avg_alpha=#if $avg_alpha() then $avg_alpha else 'None'#, title=$title, #if $win() win=$win, #end if #if $win_size() size=$win_size, #end if ) #if not $grid_pos() $(parent).Add(self.$(id).win) #else $(parent).GridAdd(self.$(id).win, $(', '.join(map(str, $grid_pos())))) #end if #if $freqvar() is not None def $(id)_callback(x, y): self.set_$(freqvar)(x) self.$(id).set_callback($(id)_callback) #end if set_baseband_freq($baseband_freq) set_sample_rate($samp_rate) Type type complex enum Title title Waterfall Plot string Sample Rate samp_rate samp_rate real Baseband Freq baseband_freq 0 real Dynamic Range dynamic_range 100 real Reference Level ref_level 0 real Ref Scale (p2p) ref_scale 2.0 real FFT Size fft_size 512 int FFT Rate fft_rate 15 int Average average False enum part Average Alpha avg_alpha 0 real #if $average() == 'True' then 'none' else 'all'# Window win None raw #if $win() is None then 'part' else 'none'# Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook Freq Set Varname freqvar None raw not $win_size or len($win_size) == 2 in $type Set Average Alpha to 0 for automatic setting. Leave the window blank for the default size, otherwise enter a tuple of (width, height) pixels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_histosink2.xml0000664000175000017500000000372512207440367021726 0ustar jcorganjcorgan WX GUI Histo Sink wxgui_histosink2 Instrumentation/WX from gnuradio.wxgui import histosink_gl from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' histosink_gl.histo_sink_f( $(parent).GetWin(), title=$title, num_bins=$num_bins, frame_size=$frame_size, #if $win_size() size=$win_size, #end if ) #if not $grid_pos() $(parent).Add(self.$(id).win) #else $(parent).GridAdd(self.$(id).win, $(', '.join(map(str, $grid_pos())))) #end if set_num_bins($num_bins) set_frame_size($frame_size) Title title Histogram Plot string Num Bins num_bins 27 int Frame Size frame_size 1000 int Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook not $win_size or len($win_size) == 2 in float Leave the window blank for the default size, otherwise enter a tuple of (width, height) pixels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_scopesink2.xml0000664000175000017500000001024712207440367021706 0ustar jcorganjcorgan WX GUI Scope Sink wxgui_scopesink2 Instrumentation/WX from gnuradio.wxgui import scopesink2 from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' scopesink2.$(type.fcn)( $(parent).GetWin(), title=$title, sample_rate=$samp_rate, v_scale=$v_scale, v_offset=$v_offset, t_scale=$t_scale, ac_couple=$ac_couple, xy_mode=$xy_mode, num_inputs=$num_inputs, trig_mode=$trig_mode, y_axis_label=$y_axis_label, #if $win_size() size=$win_size, #end if ) #if not $grid_pos() $(parent).Add(self.$(id).win) #else $(parent).GridAdd(self.$(id).win, $(', '.join(map(str, $grid_pos())))) #end if set_sample_rate($samp_rate) Type type complex enum Title title Scope Plot string Sample Rate samp_rate samp_rate real V Scale v_scale 0 real #if $v_scale() then 'none' else 'part'# V Offset v_offset 0 real #if $v_offset() then 'none' else 'part'# T Scale t_scale 0 real #if $t_scale() then 'none' else 'part'# AC Couple ac_couple False bool #if $ac_couple() then 'none' else 'part'# XY Mode xy_mode False enum #if $xy_mode() == 'True' then 'none' else 'part'# Num Inputs num_inputs 1 int Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook Trigger Mode trig_mode enum Y Axis Label y_axis_label Counts string not $win_size or len($win_size) == 2 not $xy_mode or '$type' == 'complex' or $num_inputs != 1 in $type $num_inputs Set the V Scale to 0 for the scope to auto-scale. Set the T Scale to 0 for automatic setting. XY Mode allows the scope to initialize as an XY plotter. Leave the window blank for the default size, otherwise enter a tuple of (width, height) pixels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/top_block_gui.py0000664000175000017500000000465112207440367021055 0ustar jcorganjcorgan# Copyright 2008, 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from gnuradio import gr import panel default_gui_size = (200, 100) class top_block_gui(gr.top_block): """gr top block with wx gui app and grid sizer.""" def __init__(self, title='', size=default_gui_size): """ Initialize the gr top block. Create the wx gui elements. Args: title: the main window title size: the main window size tuple in pixels icon: the file path to an icon or None """ #initialize gr.top_block.__init__(self) self._size = size #create gui elements self._app = wx.App() self._frame = wx.Frame(None, title=title) self._panel = panel.Panel(self._frame) self.Add = self._panel.Add self.GridAdd = self._panel.GridAdd self.GetWin = self._panel.GetWin def SetIcon(self, *args, **kwargs): self._frame.SetIcon(*args, **kwargs) def Start(self, start=True, max_nouts=0): #set minimal window size self._frame.SetSizeHints(*self._size) #create callback for quit def _quit(event): self.stop(); self.wait() self._frame.Destroy() #setup app self._frame.Bind(wx.EVT_CLOSE, _quit) self._sizer = wx.BoxSizer(wx.VERTICAL) self._sizer.Add(self._panel, 0, wx.EXPAND) self._frame.SetSizerAndFit(self._sizer) self._frame.SetAutoLayout(True) self._frame.Show(True) self._app.SetTopWindow(self._frame) #start flow graph if start: if max_nouts != 0: self.start(max_nouts) else: self.start() def Run(self, start=True, max_nouts=0): """ Setup the wx gui elements. Start the gr top block. Block with the wx main loop. """ #blocking main loop self.Start(start, max_nouts) self._app.MainLoop() def Wait(self): self._app.MainLoop() gnuradio-3.7.2.1/gr-wxgui/grc/variable_chooser.xml0000664000175000017500000000577512207440367021724 0ustar jcorganjcorgan WX GUI Chooser variable_chooser GUI Widgets/WX from gnuradio.wxgui import forms self.$(id) = $(id) = $value #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' #set $win = 'self._%s_chooser'%$id $win = forms.$(type)( parent=$(parent).GetWin(), value=self.$id, callback=self.set_$(id), #if $label() label=$label, #else label='$id', #end if choices=$choices, labels=$labels, #if $type() == 'radio_buttons' style=$style, #end if ) #if not $grid_pos() $(parent).Add($win) #else $(parent).GridAdd($win, $(', '.join(map(str, $grid_pos())))) #end if self.set_$(id)($value) self._$(id)_chooser.set_value($id) Label label string #if $label() then 'none' else 'part'# Default Value value 1 raw Choices choices [1, 2, 3] raw Labels labels [] raw Type type drop_down enum Style style wx.RA_HORIZONTAL enum #if $type() == 'radio_buttons' then 'part' else 'all'# Grid Position grid_pos grid_pos Notebook notebook notebook $value in $choices not $labels or len($labels) == len($choices) This block creates a variable with a drop down, radio buttons, or a button. \ Leave the label blank to use the variable id as the label. \ The value index is the index of a particular choice, \ which defines the default choice when the flow graph starts. \ The choices must be a list of possible values. \ Leave labels empty to use the choices as the labels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/panel.py0000664000175000017500000000316712207440367017335 0ustar jcorganjcorgan# Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx class Panel(wx.Panel): def __init__(self, parent, orient=wx.VERTICAL): wx.Panel.__init__(self, parent) self._box = wx.BoxSizer(orient) self._grid = wx.GridBagSizer(5, 5) self.Add(self._grid) self.SetSizer(self._box) def GetWin(self): return self def Add(self, win): """ Add a window to the wx vbox. Args: win: the wx window """ self._box.Add(win, 0, wx.EXPAND) def GridAdd(self, win, row, col, row_span=1, col_span=1): """ Add a window to the wx grid at the given position. Args: win: the wx window row: the row specification (integer >= 0) col: the column specification (integer >= 0) row_span: the row span specification (integer >= 1) col_span: the column span specification (integer >= 1) """ self._grid.Add(win, wx.GBPosition(row, col), wx.GBSpan(row_span, col_span), wx.EXPAND) gnuradio-3.7.2.1/gr-wxgui/grc/notebook.xml0000664000175000017500000000341712207440367020224 0ustar jcorganjcorgan WX GUI Notebook notebook GUI Widgets/WX from grc_gnuradio import wxgui as grc_wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' self.$(id) = wx.Notebook($(parent).GetWin(), style=$style) #for $label in $labels() self.$(id).AddPage(grc_wxgui.Panel(self.$(id)), "$label") #end for #if not $grid_pos() $(parent).Add(self.$(id)) #else $(parent).GridAdd(self.$(id), $(', '.join(map(str, $grid_pos())))) #end if Tab Orientation style wx.NB_TOP enum Labels labels ['tab1', 'tab2', 'tab3'] raw Grid Position grid_pos grid_pos Notebook notebook notebook isinstance($labels, (list, tuple)) all(map(lambda x: isinstance(x, str), $labels)) len($labels) > 0 Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_fftsink2.xml0000664000175000017500000001213012207440367021345 0ustar jcorganjcorgan WX GUI FFT Sink wxgui_fftsink2 Instrumentation/WX from gnuradio.fft import window from gnuradio.wxgui import fftsink2 from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' fftsink2.$(type.fcn)( $(parent).GetWin(), baseband_freq=$baseband_freq, y_per_div=$y_per_div, y_divs=$y_divs, ref_level=$ref_level, ref_scale=$ref_scale, sample_rate=$samp_rate, fft_size=$fft_size, fft_rate=$fft_rate, average=$average, avg_alpha=#if $avg_alpha() then $avg_alpha else 'None'#, title=$title, peak_hold=$peak_hold, #if $win() win=$win, #end if #if $win_size() size=$win_size, #end if ) #if not $grid_pos() $(parent).Add(self.$(id).win) #else $(parent).GridAdd(self.$(id).win, $(', '.join(map(str, $grid_pos())))) #end if #if $freqvar() is not None def $(id)_callback(x, y): self.set_$(freqvar)(x) self.$(id).set_callback($(id)_callback) #end if set_baseband_freq($baseband_freq) set_sample_rate($samp_rate) Type type complex enum Title title FFT Plot string Sample Rate samp_rate samp_rate real Baseband Freq baseband_freq 0 real Y per Div y_per_div 10 enum Y Divs y_divs 10 int Ref Level (dB) ref_level 0 real Ref Scale (p2p) ref_scale 2.0 real FFT Size fft_size 1024 int Refresh Rate fft_rate 15 int Peak Hold peak_hold False enum #if $peak_hold() == 'True' then 'none' else 'part'# Average average False enum part Average Alpha avg_alpha 0 real #if $average() == 'True' then 'none' else 'all'# Window win None raw #if $win() is None then 'part' else 'none'# Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook Freq Set Varname freqvar None raw not $win_size or len($win_size) == 2 in $type Set Average Alpha to 0 for automatic setting. Leave the window blank for the default size, otherwise enter a tuple of (width, height) pixels. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/grc/wxgui_termsink.xml0000664000175000017500000000227012207440367021457 0ustar jcorganjcorgan WX GUI Terminal Sink wxgui_termsink Instrumentation/WX from gnuradio.wxgui import termsink from gnuradio import wxgui #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' termsink.termsink( parent=$(parent).GetWin(), #if $win_size() size=$win_size, #end if msgq=$(id)_msgq_in, ) #if not $grid_pos() $(parent).Add(self.$(id)) #else $(parent).GridAdd(self.$(id), $(', '.join(map(str, $grid_pos())))) #end if Window Size win_size int_vector #if $win_size() then 'none' else 'part'# Grid Position grid_pos grid_pos Notebook notebook notebook not $win_size or len($win_size) == 2 in msg gnuradio-3.7.2.1/gr-wxgui/grc/__init__.py0000644000175000017500000000152311700377701017763 0ustar jcorganjcorgan# Copyright 2008, 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from top_block_gui import top_block_gui from panel import Panel gnuradio-3.7.2.1/gr-wxgui/grc/variable_check_box.xml0000664000175000017500000000412412207440367022172 0ustar jcorganjcorgan WX GUI Check Box variable_check_box GUI Widgets/WX from gnuradio.wxgui import forms self.$(id) = $(id) = $value #set $parent = $notebook() and 'self.%s.GetPage(%s)'%$notebook() or 'self' #set $win = 'self._%s_check_box'%$id $win = forms.check_box( parent=$(parent).GetWin(), value=self.$id, callback=self.set_$(id), #if $label() label=$label, #else label='$id', #end if true=$true, false=$false, ) #if not $grid_pos() $(parent).Add($win) #else $(parent).GridAdd($win, $(', '.join(map(str, $grid_pos())))) #end if self.set_$(id)($value) self._$(id)_check_box.set_value($id) Label label string #if $label() then 'none' else 'part'# Default Value value True raw True true True raw False false False raw Grid Position grid_pos grid_pos Notebook notebook notebook $value in ($true, $false) This block creates a variable with a check box form. \ Leave the label blank to use the variable id as the label. A check box form can switch between two states; \ the default being True and False. \ Override True and False to use alternative states. Use the Grid Position (row, column, row span, column span) to position the graphical element in the window. Use the Notebook Param (notebook-id, page-index) to place the graphical element inside of a notebook page. gnuradio-3.7.2.1/gr-wxgui/gr-wxgui.conf0000644000175000017500000000042411700377701017516 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [wxgui] # 'gl', 'nongl', or 'auto' style = auto # fftsink and waterfallsink fft_rate = 15 # scopesink frame_decim = 1 gnuradio-3.7.2.1/gr-wxgui/python/0000775000175000017500000000000012207440367016423 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/python/wxgui/0000775000175000017500000000000012235766174017576 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/python/wxgui/constants.py0000664000175000017500000000451212207440367022156 0ustar jcorganjcorgan# # Copyright 2008,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Controller Keys ################################################## AC_COUPLE_KEY = 'ac_couple' ALPHA_KEY = 'alpha' AUTORANGE_KEY = 'autorange' AVERAGE_KEY = 'average' AVG_ALPHA_KEY = 'avg_alpha' USE_PERSISTENCE_KEY = 'use_persistence' PERSIST_ALPHA_KEY = 'persist_alpha' BASEBAND_FREQ_KEY = 'baseband_freq' BETA_KEY = 'beta' COLOR_MODE_KEY = 'color_mode' DECIMATION_KEY = 'decimation' DYNAMIC_RANGE_KEY = 'dynamic_range' FRAME_RATE_KEY = 'frame_rate' GAIN_MU_KEY = 'gain_mu' GAIN_OMEGA_KEY = 'gain_omega' MARKER_KEY = 'marker' XY_MARKER_KEY = 'xy_marker' MSG_KEY = 'msg' NUM_LINES_KEY = 'num_lines' OMEGA_KEY = 'omega' PEAK_HOLD_KEY = 'peak_hold' TRACE_STORE_KEY = 'trace_store' TRACE_SHOW_KEY = 'trace_show' REF_LEVEL_KEY = 'ref_level' RUNNING_KEY = 'running' SAMPLE_RATE_KEY = 'sample_rate' TRIGGER_CHANNEL_KEY = 'trigger_channel' TRIGGER_LEVEL_KEY = 'trigger_level' TRIGGER_MODE_KEY = 'trigger_mode' TRIGGER_SLOPE_KEY = 'trigger_slope' TRIGGER_SHOW_KEY = 'trigger_show' XY_MODE_KEY = 'xy_mode' X_CHANNEL_KEY = 'x_channel' Y_CHANNEL_KEY = 'y_channel' T_FRAC_OFF_KEY = 't_frac_off' T_DIVS_KEY = 't_divs' T_OFF_KEY = 't_off' T_PER_DIV_KEY = 't_per_div' X_DIVS_KEY = 'x_divs' X_OFF_KEY = 'x_off' X_PER_DIV_KEY = 'x_per_div' Y_DIVS_KEY = 'y_divs' Y_OFF_KEY = 'y_off' Y_PER_DIV_KEY = 'y_per_div' Y_AXIS_LABEL = 'y_axis_label' MAXIMUM_KEY = 'maximum' MINIMUM_KEY = 'minimum' NUM_BINS_KEY = 'num_bins' FRAME_SIZE_KEY = 'frame_size' CHANNEL_OPTIONS_KEY = 'channel_options' SHOW_CONTROL_PANEL_KEY = 'show_control_panel' LOOP_BW_KEY = 'loop_bw' gnuradio-3.7.2.1/gr-wxgui/python/wxgui/CMakeLists.txt0000664000175000017500000000506012235766174022337 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) ######################################################################## # Install python files into wxgui module ######################################################################## GR_PYTHON_INSTALL( FILES __init__.py common.py constants.py constsink_gl.py const_window.py form.py fftsink2.py fftsink_nongl.py fftsink_gl.py fft_window.py gui.py histosink_gl.py histo_window.py numbersink2.py number_window.py plot.py powermate.py pubsub.py scopesink2.py scopesink_nongl.py scopesink_gl.py scope_window.py termsink.py waterfallsink2.py waterfallsink_nongl.py waterfallsink_gl.py waterfall_window.py slider.py stdgui2.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/wxgui COMPONENT "wxgui_python" ) ######################################################################## # Install python files into wxgui forms sub-module ######################################################################## GR_PYTHON_INSTALL( FILES forms/__init__.py forms/forms.py forms/converters.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/wxgui/forms COMPONENT "wxgui_python" ) ######################################################################## # Install python files into wxgui plotter sub-module ######################################################################## GR_PYTHON_INSTALL( FILES plotter/__init__.py plotter/bar_plotter.py plotter/channel_plotter.py plotter/common.py plotter/gltext.py plotter/grid_plotter_base.py plotter/plotter_base.py plotter/waterfall_plotter.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/wxgui/plotter COMPONENT "wxgui_python" ) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/numbersink2.py0000664000175000017500000001241012207440367022375 0ustar jcorganjcorgan# # Copyright 2008,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import number_window import common from gnuradio import gr, filter from gnuradio import analog from gnuradio import blocks from pubsub import pubsub from constants import * ################################################## # Number sink block (wrapper for old wxgui) ################################################## class _number_sink_base(gr.hier_block2, common.wxgui_hb): """ An decimator block with a number window display """ def __init__( self, parent, unit='units', minval=0, maxval=1, factor=1, decimal_places=3, ref_level=0, sample_rate=1, number_rate=number_window.DEFAULT_NUMBER_RATE, average=False, avg_alpha=None, label='Number Plot', size=number_window.DEFAULT_WIN_SIZE, peak_hold=False, show_gauge=True, **kwargs #catchall for backwards compatibility ): #ensure avg alpha if avg_alpha is None: avg_alpha = 2.0/number_rate #init gr.hier_block2.__init__( self, "number_sink", gr.io_signature(1, 1, self._item_size), gr.io_signature(0, 0, 0), ) #blocks sd = blocks.stream_to_vector_decimator( item_size=self._item_size, sample_rate=sample_rate, vec_rate=number_rate, vec_len=1, ) if self._real: mult = blocks.multiply_const_ff(factor) add = blocks.add_const_ff(ref_level) avg = filter.single_pole_iir_filter_ff(1.0) else: mult = blocks.multiply_const_cc(factor) add = blocks.add_const_cc(ref_level) avg = filter.single_pole_iir_filter_cc(1.0) msgq = gr.msg_queue(2) sink = blocks.message_sink(self._item_size, msgq, True) #controller self.controller = pubsub() self.controller.subscribe(SAMPLE_RATE_KEY, sd.set_sample_rate) self.controller.publish(SAMPLE_RATE_KEY, sd.sample_rate) self.controller[AVERAGE_KEY] = average self.controller[AVG_ALPHA_KEY] = avg_alpha def update_avg(*args): if self.controller[AVERAGE_KEY]: avg.set_taps(self.controller[AVG_ALPHA_KEY]) else: avg.set_taps(1.0) update_avg() self.controller.subscribe(AVERAGE_KEY, update_avg) self.controller.subscribe(AVG_ALPHA_KEY, update_avg) #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY) #create window self.win = number_window.number_window( parent=parent, controller=self.controller, size=size, title=label, units=unit, real=self._real, minval=minval, maxval=maxval, decimal_places=decimal_places, show_gauge=show_gauge, average_key=AVERAGE_KEY, avg_alpha_key=AVG_ALPHA_KEY, peak_hold=peak_hold, msg_key=MSG_KEY, sample_rate_key=SAMPLE_RATE_KEY, ) common.register_access_methods(self, self.controller) #backwards compadibility self.set_show_gauge = self.win.show_gauges #connect self.wxgui_connect(self, sd, mult, add, avg, sink) class number_sink_f(_number_sink_base): _item_size = gr.sizeof_float _real = True class number_sink_c(_number_sink_base): _item_size = gr.sizeof_gr_complex _real = False # ---------------------------------------------------------------- # Standalone test app # ---------------------------------------------------------------- import wx from gnuradio.wxgui import stdgui2 class test_app_flow_graph(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) # build our flow graph input_rate = 20.48e3 # Generate a real and complex sinusoids src1 = analog.sig_source_f(input_rate, analog.GR_SIN_WAVE, 2.21e3, 1) src2 = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 2.21e3, 1) # We add these throttle blocks so that this demo doesn't # suck down all the CPU available. Normally you wouldn't use these. thr1 = blocks.throttle(gr.sizeof_float, input_rate) thr2 = blocks.throttle(gr.sizeof_gr_complex, input_rate) sink1 = number_sink_f(panel, unit='V',label="Real Data", avg_alpha=0.001, sample_rate=input_rate, minval=-1, maxval=1, ref_level=0, decimal_places=3) vbox.Add(sink1.win, 1, wx.EXPAND) sink2 = number_sink_c(panel, unit='V',label="Complex Data", avg_alpha=0.001, sample_rate=input_rate, minval=-1, maxval=1, ref_level=0, decimal_places=3) vbox.Add(sink2.win, 1, wx.EXPAND) self.connect(src1, thr1, sink1) self.connect(src2, thr2, sink2) def main (): app = stdgui2.stdapp(test_app_flow_graph, "Number Sink Test App") app.MainLoop() if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/const_window.py0000664000175000017500000001376312207440367022667 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import plotter import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 200 LOOP_BW_MIN_EXP, LOOP_BW_MAX_EXP = -6, 0.0 GAIN_MU_MIN_EXP, GAIN_MU_MAX_EXP = -6, -0.301 DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'const_rate', 5) DEFAULT_WIN_SIZE = (500, 400) DEFAULT_CONST_SIZE = gr.prefs().get_long('wxgui', 'const_size', 2048) CONST_PLOT_COLOR_SPEC = (0, 0, 1) MARKER_TYPES = ( ('Dot Small', 1.0), ('Dot Medium', 2.0), ('Dot Large', 3.0), ('Line Link', None), ) DEFAULT_MARKER_TYPE = 2.0 ################################################## # Constellation window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the plotter. """ def __init__(self, parent): """ Create a new control panel. Args: parent: the wx parent window """ self.parent = parent wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER) parent[SHOW_CONTROL_PANEL_KEY] = True parent.subscribe(SHOW_CONTROL_PANEL_KEY, self.Show) control_box = forms.static_box_sizer( parent=self, label='Options', bold=True, orient=wx.VERTICAL, ) #loop_bw control_box.AddStretchSpacer() forms.text_box( sizer=control_box, parent=self, label='Loop Bandwidth', converter=forms.float_converter(), ps=parent, key=LOOP_BW_KEY, ) forms.log_slider( sizer=control_box, parent=self, min_exp=LOOP_BW_MIN_EXP, max_exp=LOOP_BW_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=LOOP_BW_KEY, ) #gain_mu control_box.AddStretchSpacer() forms.text_box( sizer=control_box, parent=self, label='Gain Mu', converter=forms.float_converter(), ps=parent, key=GAIN_MU_KEY, ) forms.log_slider( sizer=control_box, parent=self, min_exp=GAIN_MU_MIN_EXP, max_exp=GAIN_MU_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=GAIN_MU_KEY, ) #marker control_box.AddStretchSpacer() forms.drop_down( sizer=control_box, parent=self, ps=parent, key=MARKER_KEY, label='Marker', choices=map(lambda x: x[1], MARKER_TYPES), labels=map(lambda x: x[0], MARKER_TYPES), ) #run/stop control_box.AddStretchSpacer() forms.toggle_button( sizer=control_box, parent=self, true_label='Stop', false_label='Run', ps=parent, key=RUNNING_KEY, ) #set sizer self.SetSizerAndFit(control_box) ################################################## # Constellation window with plotter and control panel ################################################## class const_window(wx.Panel, pubsub.pubsub): def __init__( self, parent, controller, size, title, msg_key, loop_bw_key, gain_mu_key, gain_omega_key, omega_key, sample_rate_key, ): pubsub.pubsub.__init__(self) #proxy the keys self.proxy(MSG_KEY, controller, msg_key) self.proxy(LOOP_BW_KEY, controller, loop_bw_key) self.proxy(GAIN_MU_KEY, controller, gain_mu_key) self.proxy(GAIN_OMEGA_KEY, controller, gain_omega_key) self.proxy(OMEGA_KEY, controller, omega_key) self.proxy(SAMPLE_RATE_KEY, controller, sample_rate_key) #initialize values self[RUNNING_KEY] = True self[X_DIVS_KEY] = 8 self[Y_DIVS_KEY] = 8 self[MARKER_KEY] = DEFAULT_MARKER_TYPE #init panel and plot wx.Panel.__init__(self, parent, style=wx.SIMPLE_BORDER) self.plotter = plotter.channel_plotter(self) self.plotter.SetSize(wx.Size(*size)) self.plotter.SetSizeHints(*size) self.plotter.set_title(title) self.plotter.set_x_label('Inphase') self.plotter.set_y_label('Quadrature') self.plotter.enable_point_label(True) self.plotter.enable_grid_lines(True) #setup the box with plot and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer(wx.HORIZONTAL) main_box.Add(self.plotter, 1, wx.EXPAND) main_box.Add(self.control_panel, 0, wx.EXPAND) self.SetSizerAndFit(main_box) #alpha and gain mu 2nd orders def set_gain_omega(gain_mu): self[GAIN_OMEGA_KEY] = .25*gain_mu**2 self.subscribe(GAIN_MU_KEY, set_gain_omega) #register events self.subscribe(MSG_KEY, self.handle_msg) self.subscribe(X_DIVS_KEY, self.update_grid) self.subscribe(Y_DIVS_KEY, self.update_grid) #initial update self.update_grid() def handle_msg(self, msg): """ Plot the samples onto the complex grid. Args: msg: the array of complex samples """ if not self[RUNNING_KEY]: return #convert to complex floating point numbers samples = numpy.fromstring(msg, numpy.complex64) real = numpy.real(samples) imag = numpy.imag(samples) #plot self.plotter.set_waveform( channel=0, samples=(real, imag), color_spec=CONST_PLOT_COLOR_SPEC, marker=self[MARKER_KEY], ) #update the plotter self.plotter.update() def update_grid(self): #update the x axis x_max = 2.0 self.plotter.set_x_grid(-x_max, x_max, common.get_clean_num(2.0*x_max/self[X_DIVS_KEY])) #update the y axis y_max = 2.0 self.plotter.set_y_grid(-y_max, y_max, common.get_clean_num(2.0*y_max/self[Y_DIVS_KEY])) #update plotter self.plotter.update() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/waterfall_window.py0000664000175000017500000002466212207440367023522 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1`301, USA. # ################################################## # Imports ################################################## import plotter import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_EXP = -3, 0 DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'waterfall_rate', 30) DEFAULT_COLOR_MODE = gr.prefs().get_string('wxgui', 'waterfall_color', 'rgb1') DEFAULT_WIN_SIZE = (600, 300) DIV_LEVELS = (1, 2, 5, 10, 20) MIN_DYNAMIC_RANGE, MAX_DYNAMIC_RANGE = 10, 200 DYNAMIC_RANGE_STEP = 10. COLOR_MODES = ( ('RGB1', 'rgb1'), ('RGB2', 'rgb2'), ('RGB3', 'rgb3'), ('Gray', 'gray'), ) ################################################## # Waterfall window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the plotter and fft block chain. """ def __init__(self, parent): """ Create a new control panel. Args: parent: the wx parent window """ self.parent = parent wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER) parent[SHOW_CONTROL_PANEL_KEY] = True parent.subscribe(SHOW_CONTROL_PANEL_KEY, self.Show) control_box = wx.BoxSizer(wx.VERTICAL) control_box.AddStretchSpacer() options_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Options', bold=True, orient=wx.VERTICAL, ) #average forms.check_box( sizer=options_box, parent=self, label='Average', ps=parent, key=AVERAGE_KEY, ) avg_alpha_text = forms.static_text( sizer=options_box, parent=self, label='Avg Alpha', converter=forms.float_converter(lambda x: '%.4f'%x), ps=parent, key=AVG_ALPHA_KEY, width=50, ) avg_alpha_slider = forms.log_slider( sizer=options_box, parent=self, min_exp=AVG_ALPHA_MIN_EXP, max_exp=AVG_ALPHA_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=AVG_ALPHA_KEY, ) for widget in (avg_alpha_text, avg_alpha_slider): parent.subscribe(AVERAGE_KEY, widget.Enable) widget.Enable(parent[AVERAGE_KEY]) #begin axes box control_box.AddStretchSpacer() axes_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Axes Options', bold=True, orient=wx.VERTICAL, ) #num lines buttons forms.incr_decr_buttons( parent=self, sizer=axes_box, label='Time Scale', on_incr=self._on_incr_time_scale, on_decr=self._on_decr_time_scale, ) #dyanmic range buttons forms.incr_decr_buttons( parent=self, sizer=axes_box, label='Dyn Range', on_incr=self._on_incr_dynamic_range, on_decr=self._on_decr_dynamic_range, ) #ref lvl buttons forms.incr_decr_buttons( parent=self, sizer=axes_box, label='Ref Level', on_incr=self._on_incr_ref_level, on_decr=self._on_decr_ref_level, ) #color mode forms.drop_down( parent=self, sizer=axes_box, width=100, ps=parent, key=COLOR_MODE_KEY, label='Color', choices=map(lambda x: x[1], COLOR_MODES), labels=map(lambda x: x[0], COLOR_MODES), ) #autoscale forms.single_button( parent=self, sizer=axes_box, label='Autoscale', callback=self.parent.autoscale, ) #clear control_box.AddStretchSpacer() forms.single_button( parent=self, sizer=control_box, label='Clear', callback=self._on_clear_button, ) #run/stop forms.toggle_button( sizer=control_box, parent=self, true_label='Stop', false_label='Run', ps=parent, key=RUNNING_KEY, ) #set sizer self.SetSizerAndFit(control_box) ################################################## # Event handlers ################################################## def _on_clear_button(self, event): self.parent[NUM_LINES_KEY] = self.parent[NUM_LINES_KEY] def _on_incr_dynamic_range(self, event): self.parent[DYNAMIC_RANGE_KEY] = min(MAX_DYNAMIC_RANGE, common.get_clean_incr(self.parent[DYNAMIC_RANGE_KEY])) def _on_decr_dynamic_range(self, event): self.parent[DYNAMIC_RANGE_KEY] = max(MIN_DYNAMIC_RANGE, common.get_clean_decr(self.parent[DYNAMIC_RANGE_KEY])) def _on_incr_ref_level(self, event): self.parent[REF_LEVEL_KEY] = self.parent[REF_LEVEL_KEY] + self.parent[DYNAMIC_RANGE_KEY]/DYNAMIC_RANGE_STEP def _on_decr_ref_level(self, event): self.parent[REF_LEVEL_KEY] = self.parent[REF_LEVEL_KEY] - self.parent[DYNAMIC_RANGE_KEY]/DYNAMIC_RANGE_STEP def _on_incr_time_scale(self, event): old_rate = self.parent[FRAME_RATE_KEY] self.parent[FRAME_RATE_KEY] *= 0.75 if self.parent[FRAME_RATE_KEY] < 1.0: self.parent[FRAME_RATE_KEY] = 1.0 if self.parent[FRAME_RATE_KEY] == old_rate: self.parent[DECIMATION_KEY] += 1 def _on_decr_time_scale(self, event): old_rate = self.parent[FRAME_RATE_KEY] self.parent[FRAME_RATE_KEY] *= 1.25 if self.parent[FRAME_RATE_KEY] == old_rate: self.parent[DECIMATION_KEY] -= 1 ################################################## # Waterfall window with plotter and control panel ################################################## class waterfall_window(wx.Panel, pubsub.pubsub): def __init__( self, parent, controller, size, title, real, fft_size, num_lines, decimation_key, baseband_freq, sample_rate_key, frame_rate_key, dynamic_range, ref_level, average_key, avg_alpha_key, msg_key, ): pubsub.pubsub.__init__(self) #setup self.samples = list() self.real = real self.fft_size = fft_size #proxy the keys self.proxy(MSG_KEY, controller, msg_key) self.proxy(DECIMATION_KEY, controller, decimation_key) self.proxy(FRAME_RATE_KEY, controller, frame_rate_key) self.proxy(AVERAGE_KEY, controller, average_key) self.proxy(AVG_ALPHA_KEY, controller, avg_alpha_key) self.proxy(SAMPLE_RATE_KEY, controller, sample_rate_key) #init panel and plot wx.Panel.__init__(self, parent, style=wx.SIMPLE_BORDER) self.plotter = plotter.waterfall_plotter(self) self.plotter.SetSize(wx.Size(*size)) self.plotter.SetSizeHints(*size) self.plotter.set_title(title) self.plotter.enable_point_label(True) self.plotter.enable_grid_lines(False) #plotter listeners self.subscribe(COLOR_MODE_KEY, self.plotter.set_color_mode) self.subscribe(NUM_LINES_KEY, self.plotter.set_num_lines) #initialize values self[DYNAMIC_RANGE_KEY] = dynamic_range self[NUM_LINES_KEY] = num_lines self[Y_DIVS_KEY] = 8 self[X_DIVS_KEY] = 8 #approximate self[REF_LEVEL_KEY] = ref_level self[BASEBAND_FREQ_KEY] = baseband_freq self[COLOR_MODE_KEY] = COLOR_MODES[0][1] self[COLOR_MODE_KEY] = DEFAULT_COLOR_MODE self[RUNNING_KEY] = True #setup the box with plot and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer(wx.HORIZONTAL) main_box.Add(self.plotter, 1, wx.EXPAND) main_box.Add(self.control_panel, 0, wx.EXPAND) self.SetSizerAndFit(main_box) #register events self.subscribe(MSG_KEY, self.handle_msg) for key in ( DECIMATION_KEY, SAMPLE_RATE_KEY, FRAME_RATE_KEY, BASEBAND_FREQ_KEY, X_DIVS_KEY, Y_DIVS_KEY, NUM_LINES_KEY, ): self.subscribe(key, self.update_grid) #initial update self.update_grid() def set_callback(self,callb): self.plotter.set_callback(callb) def autoscale(self, *args): """ Autoscale the waterfall plot to the last frame. Set the dynamic range and reference level. Does not affect the current data in the waterfall. """ if not len(self.samples): return min_level, max_level = common.get_min_max_fft(self.samples) #set the range and level self[DYNAMIC_RANGE_KEY] = common.get_clean_num(max_level - min_level) self[REF_LEVEL_KEY] = DYNAMIC_RANGE_STEP*round(.5+max_level/DYNAMIC_RANGE_STEP) def handle_msg(self, msg): """ Handle the message from the fft sink message queue. If complex, reorder the fft samples so the negative bins come first. If real, keep take only the positive bins. Send the data to the plotter. Args: msg: the fft array as a character array """ if not self[RUNNING_KEY]: return #convert to floating point numbers self.samples = samples = numpy.fromstring(msg, numpy.float32)[:self.fft_size] #only take first frame num_samps = len(samples) #reorder fft if self.real: samples = samples[:(num_samps+1)/2] else: samples = numpy.concatenate((samples[num_samps/2+1:], samples[:(num_samps+1)/2])) #plot the fft self.plotter.set_samples( samples=samples, minimum=self[REF_LEVEL_KEY] - self[DYNAMIC_RANGE_KEY], maximum=self[REF_LEVEL_KEY], ) #update the plotter self.plotter.update() def update_grid(self, *args): """ Update the plotter grid. This update method is dependent on the variables below. Determine the x and y axis grid parameters. The x axis depends on sample rate, baseband freq, and x divs. The y axis depends on y per div, y divs, and ref level. """ #grid parameters sample_rate = self[SAMPLE_RATE_KEY] frame_rate = self[FRAME_RATE_KEY] if frame_rate < 1.0 : frame_rate = 1.0 baseband_freq = self[BASEBAND_FREQ_KEY] num_lines = self[NUM_LINES_KEY] y_divs = self[Y_DIVS_KEY] x_divs = self[X_DIVS_KEY] #determine best fitting x_per_div if self.real: x_width = sample_rate/2.0 else: x_width = sample_rate/1.0 x_per_div = common.get_clean_num(x_width/x_divs) #update the x grid if self.real: self.plotter.set_x_grid( baseband_freq, baseband_freq + sample_rate/2.0, x_per_div, True, ) else: self.plotter.set_x_grid( baseband_freq - sample_rate/2.0, baseband_freq + sample_rate/2.0, x_per_div, True, ) #update x units self.plotter.set_x_label('Frequency', 'Hz') #update y grid duration = float(num_lines)/frame_rate y_per_div = common.get_clean_num(duration/y_divs) self.plotter.set_y_grid(0, duration, y_per_div, True) #update y units self.plotter.set_y_label('Time', 's') #update plotter self.plotter.update() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/0000775000175000017500000000000012207440367021257 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/gltext.py0000664000175000017500000004052012207440367023141 0ustar jcorganjcorgan#!/usr/bin/env python # -*- coding: utf-8 # # Provides some text display functions for wx + ogl # Copyright (C) 2007 Christian Brugger, Stefan Hacker # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import wx from OpenGL.GL import * """ Optimize with psyco if possible, this gains us about 50% speed when creating our textures in trade for about 4MBytes of additional memory usage for psyco. If you don't like loosing the memory you have to turn the lines following "enable psyco" into a comment while uncommenting the line after "Disable psyco". """ #Try to enable psyco try: import psyco psyco_optimized = False except ImportError: psyco = None #Disable psyco #psyco = None class TextElement(object): """ A simple class for using system Fonts to display text in an OpenGL scene """ def __init__(self, text = '', font = None, foreground = wx.BLACK, centered = False): """ text (String) - Text font (wx.Font) - Font to draw with (None = System default) foreground (wx.Color) - Color of the text or (wx.Bitmap)- Bitmap to overlay the text with centered (bool) - Center the text Initializes the TextElement """ # save given variables self._text = text self._lines = text.split('\n') self._font = font self._foreground = foreground self._centered = centered # init own variables self._owner_cnt = 0 #refcounter self._texture = None #OpenGL texture ID self._text_size = None #x/y size tuple of the text self._texture_size= None #x/y Texture size tuple # create Texture self.createTexture() #---Internal helpers def _getUpper2Base(self, value): """ Returns the lowest value with the power of 2 greater than 'value' (2^n>value) """ base2 = 1 while base2 < value: base2 *= 2 return base2 #---Functions def draw_text(self, position = wx.Point(0,0), scale = 1.0, rotation = 0): """ position (wx.Point) - x/y Position to draw in scene scale (float) - Scale rotation (int) - Rotation in degree Draws the text to the scene """ #Enable necessary functions glColor(1,1,1,1) glEnable(GL_TEXTURE_2D) glEnable(GL_ALPHA_TEST) #Enable alpha test glAlphaFunc(GL_GREATER, 0) glEnable(GL_BLEND) #Enable blending glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #Bind texture glBindTexture(GL_TEXTURE_2D, self._texture) ow, oh = self._text_size w , h = self._texture_size #Perform transformations glPushMatrix() glTranslated(position.x, position.y, 0) glRotate(-rotation, 0, 0, 1) glScaled(scale, scale, scale) if self._centered: glTranslate(-w/2, -oh/2, 0) #Draw vertices glBegin(GL_QUADS) glTexCoord2f(0,0); glVertex2f(0,0) glTexCoord2f(0,1); glVertex2f(0,h) glTexCoord2f(1,1); glVertex2f(w,h) glTexCoord2f(1,0); glVertex2f(w,0) glEnd() glPopMatrix() #Disable features glDisable(GL_BLEND) glDisable(GL_ALPHA_TEST) glDisable(GL_TEXTURE_2D) def createTexture(self): """ Creates a texture from the settings saved in TextElement, to be able to use normal system fonts conviently a wx.MemoryDC is used to draw on a wx.Bitmap. As wxwidgets device contexts don't support alpha at all it is necessary to apply a little hack to preserve antialiasing without sticking to a fixed background color: We draw the bmp in b/w mode so we can use its data as a alpha channel for a solid color bitmap which after GL_ALPHA_TEST and GL_BLEND will show a nicely antialiased text on any surface. To access the raw pixel data the bmp gets converted to a wx.Image. Now we just have to merge our foreground color with the alpha data we just created and push it all into a OpenGL texture and we are DONE *inhalesdelpy* DRAWBACK of the whole conversion thing is a really long time for creating the texture. If you see any optimizations that could save time PLEASE CREATE A PATCH!!! """ # get a memory dc dc = wx.MemoryDC() # set our font dc.SetFont(self._font) # Approximate extend to next power of 2 and create our bitmap # REMARK: You wouldn't believe how much fucking speed this little # sucker gains compared to sizes not of the power of 2. It's like # 500ms --> 0.5ms (on my ATI-GPU powered Notebook). On Sams nvidia # machine there don't seem to occur any losses...bad drivers? ow, oh = dc.GetMultiLineTextExtent(self._text)[:2] w, h = self._getUpper2Base(ow), self._getUpper2Base(oh) self._text_size = wx.Size(ow,oh) self._texture_size = wx.Size(w,h) bmp = wx.EmptyBitmap(w,h) #Draw in b/w mode to bmp so we can use it as alpha channel dc.SelectObject(bmp) dc.SetBackground(wx.BLACK_BRUSH) dc.Clear() dc.SetTextForeground(wx.WHITE) x,y = 0,0 centered = self.centered for line in self._lines: if not line: line = ' ' tw, th = dc.GetTextExtent(line) if centered: x = int(round((w-tw)/2)) dc.DrawText(line, x, y) x = 0 y += th #Release the dc dc.SelectObject(wx.NullBitmap) del dc #Generate a correct RGBA data string from our bmp """ NOTE: You could also use wx.AlphaPixelData to access the pixel data in 'bmp' directly, but the iterator given by it is much slower than first converting to an image and using wx.Image.GetData(). """ img = wx.ImageFromBitmap(bmp) alpha = img.GetData() if isinstance(self._foreground, wx.Colour): """ If we have a static color... """ r,g,b = self._foreground.Get() color = "%c%c%c" % (chr(r), chr(g), chr(b)) data = '' for i in xrange(0, len(alpha)-1, 3): data += color + alpha[i] elif isinstance(self._foreground, wx.Bitmap): """ If we have a bitmap... """ bg_img = wx.ImageFromBitmap(self._foreground) bg = bg_img.GetData() bg_width = self._foreground.GetWidth() bg_height = self._foreground.GetHeight() data = '' for y in xrange(0, h): for x in xrange(0, w): if (y > (bg_height-1)) or (x > (bg_width-1)): color = "%c%c%c" % (chr(0),chr(0),chr(0)) else: pos = (x+y*bg_width) * 3 color = bg[pos:pos+3] data += color + alpha[(x+y*w)*3] # now convert it to ogl texture self._texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self._texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 2) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) def deleteTexture(self): """ Deletes the OpenGL texture object """ if self._texture: if glIsTexture(self._texture): glDeleteTextures(self._texture) else: self._texture = None def bind(self): """ Increase refcount """ self._owner_cnt += 1 def release(self): """ Decrease refcount """ self._owner_cnt -= 1 def isBound(self): """ Return refcount """ return self._owner_cnt def __del__(self): """ Destructor """ self.deleteTexture() #---Getters/Setters def getText(self): return self._text def getFont(self): return self._font def getForeground(self): return self._foreground def getCentered(self): return self._centered def getTexture(self): return self._texture def getTexture_size(self): return self._texture_size def getOwner_cnt(self): return self._owner_cnt def setOwner_cnt(self, value): self._owner_cnt = value #---Properties text = property(getText, None, None, "Text of the object") font = property(getFont, None, None, "Font of the object") foreground = property(getForeground, None, None, "Color of the text") centered = property(getCentered, None, None, "Is text centered") owner_cnt = property(getOwner_cnt, setOwner_cnt, None, "Owner count") texture = property(getTexture, None, None, "Used texture") texture_size = property(getTexture_size, None, None, "Size of the used texture") class Text(object): """ A simple class for using System Fonts to display text in an OpenGL scene. The Text adds a global Cache of already created text elements to TextElement's base functionality so you can save some memory and increase speed """ _texts = [] #Global cache for TextElements def __init__(self, text = 'Text', font = None, font_size = 8, foreground = wx.BLACK, centered = False, bold = False): """ text (string) - displayed text font (wx.Font) - if None, system default font will be used with font_size font_size (int) - font size in points foreground (wx.Color) - Color of the text or (wx.Bitmap) - Bitmap to overlay the text with centered (bool) - should the text drawn centered towards position? Initializes the text object """ #Init/save variables self._aloc_text = None self._text = text self._font_size = font_size self._foreground= foreground self._centered = centered #Check if we are offered a font if not font: #if not use the system default self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: #save it self._font = font if bold: self._font.SetWeight(wx.FONTWEIGHT_BOLD) #Bind us to our texture self._initText() #---Internal helpers def _initText(self): """ Initializes/Reinitializes the Text object by binding it to a TextElement suitable for its current settings """ #Check if we already bound to a texture if self._aloc_text: #if so release it self._aloc_text.release() if not self._aloc_text.isBound(): self._texts.remove(self._aloc_text) self._aloc_text = None #Adjust our font self._font.SetPointSize(self._font_size) #Search for existing element in our global buffer for element in self._texts: if element.text == self._text and\ element.font == self._font and\ element.foreground == self._foreground and\ element.centered == self._centered: # We already exist in global buffer ;-) element.bind() self._aloc_text = element break if not self._aloc_text: # We are not in the global buffer, let's create ourselves aloc_text = self._aloc_text = TextElement(self._text, self._font, self._foreground, self._centered) aloc_text.bind() self._texts.append(aloc_text) def __del__(self): """ Destructor """ aloc_text = self._aloc_text aloc_text.release() if not aloc_text.isBound(): self._texts.remove(aloc_text) #---Functions def draw_text(self, position = wx.Point(0,0), scale = 1.0, rotation = 0): """ position (wx.Point) - x/y Position to draw in scene scale (float) - Scale rotation (int) - Rotation in degree Draws the text to the scene """ self._aloc_text.draw_text(position, scale, rotation) #---Setter/Getter def getText(self): return self._text def setText(self, value, reinit = True): """ value (bool) - New Text reinit (bool) - Create a new texture Sets a new text """ self._text = value if reinit: self._initText() def getFont(self): return self._font def setFont(self, value, reinit = True): """ value (bool) - New Font reinit (bool) - Create a new texture Sets a new font """ self._font = value if reinit: self._initText() def getFont_size(self): return self._font_size def setFont_size(self, value, reinit = True): """ value (bool) - New font size reinit (bool) - Create a new texture Sets a new font size """ self._font_size = value if reinit: self._initText() def getForeground(self): return self._foreground def setForeground(self, value, reinit = True): """ value (bool) - New centered value reinit (bool) - Create a new texture Sets a new value for 'centered' """ self._foreground = value if reinit: self._initText() def getCentered(self): return self._centered def setCentered(self, value, reinit = True): """ value (bool) - New centered value reinit (bool) - Create a new texture Sets a new value for 'centered' """ self._centered = value if reinit: self._initText() def get_size(self): """ Returns a text size tuple """ return self._aloc_text._text_size def getTexture_size(self): """ Returns a texture size tuple """ return self._aloc_text.texture_size def getTextElement(self): """ Returns the text element bound to the Text class """ return self._aloc_text def getTexture(self): """ Returns the texture of the bound TextElement """ return self._aloc_text.texture #---Properties text = property(getText, setText, None, "Text of the object") font = property(getFont, setFont, None, "Font of the object") font_size = property(getFont_size, setFont_size, None, "Font size") foreground = property(getForeground, setForeground, None, "Color/Overlay bitmap of the text") centered = property(getCentered, setCentered, None, "Display the text centered") texture_size = property(getTexture_size, None, None, "Size of the used texture") texture = property(getTexture, None, None, "Texture of bound TextElement") text_element = property(getTextElement,None , None, "TextElement bound to this class") #Optimize critical functions if psyco and not psyco_optimized: psyco.bind(TextElement.createTexture) psyco_optimized = True gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/plotter_base.py0000664000175000017500000001403112207440367024313 0ustar jcorganjcorgan# # Copyright 2008, 2009, 2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx import wx.glcanvas from OpenGL import GL import common BACKGROUND_COLOR_SPEC = (1, 0.976, 1, 1) #creamy white ################################################## # GL caching interface ################################################## class gl_cache(object): """ Cache a set of gl drawing routines in a compiled list. """ def __init__(self, draw): """ Create a new cache. Args: draw: a function to draw gl stuff """ self.changed(True) self._draw = draw def init(self): """ To be called when gl initializes. Create a new compiled list. """ self._grid_compiled_list_id = GL.glGenLists(1) def draw(self): """ Draw the gl stuff using a compiled list. If changed, reload the compiled list. """ if self.changed(): GL.glNewList(self._grid_compiled_list_id, GL.GL_COMPILE) self._draw() GL.glEndList() self.changed(False) #draw the grid GL.glCallList(self._grid_compiled_list_id) def changed(self, state=None): """ Set the changed flag if state is not None. Otherwise return the changed flag. """ if state is None: return self._changed self._changed = state ################################################## # OpenGL WX Plotter Canvas ################################################## class plotter_base(wx.glcanvas.GLCanvas, common.mutex): """ Plotter base class for all plot types. """ def __init__(self, parent): """ Create a new plotter base. Initialize the GLCanvas with double buffering. Initialize various plotter flags. Bind the paint and size events. Args: parent: the parent widgit """ attribList = (wx.glcanvas.WX_GL_DOUBLEBUFFER, wx.glcanvas.WX_GL_RGBA) wx.glcanvas.GLCanvas.__init__(self, parent, wx.ID_ANY, attribList=attribList); # Specifically use the CTOR which does NOT create an implicit GL context self._gl_ctx = wx.glcanvas.GLContext(self) # Create the explicit GL context self.use_persistence=False self.persist_alpha=2.0/15 self.clear_accum=True self._gl_init_flag = False self._resized_flag = True self._init_fcns = list() self._draw_fcns = list() self._gl_caches = list() self.Bind(wx.EVT_PAINT, self._on_paint) self.Bind(wx.EVT_SIZE, self._on_size) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None) def set_use_persistence(self,enable): self.use_persistence=enable self.clear_accum=True def set_persist_alpha(self,analog_alpha): self.persist_alpha=analog_alpha def new_gl_cache(self, draw_fcn, draw_pri=50): """ Create a new gl cache. Register its draw and init function. Returns: the new cache object """ cache = gl_cache(draw_fcn) self.register_init(cache.init) self.register_draw(cache.draw, draw_pri) self._gl_caches.append(cache) return cache def register_init(self, init_fcn): self._init_fcns.append(init_fcn) def register_draw(self, draw_fcn, draw_pri=50): """ Register a draw function with a layer priority. Large pri values are drawn last. Small pri values are drawn first. """ for i in range(len(self._draw_fcns)): if draw_pri < self._draw_fcns[i][0]: self._draw_fcns.insert(i, (draw_pri, draw_fcn)) return self._draw_fcns.append((draw_pri, draw_fcn)) def _on_size(self, event): """ Flag the resize event. The paint event will handle the actual resizing. """ self.lock() self._resized_flag = True self.clear_accum=True self.unlock() def _on_paint(self, event): """ Respond to paint events. Initialize GL if this is the first paint event. Resize the view port if the width or height changed. Redraw the screen, calling the draw functions. """ if not self.IsShownOnScreen(): # Cannot realise a GL context on OS X if window is not yet shown return # create device context (needed on Windows, noop on X) dc = None if event.GetEventObject(): # Only create DC if paint triggered by WM message (for OS X) dc = wx.PaintDC(self) self.lock() self.SetCurrent(self._gl_ctx) # Real the explicit GL context # check if gl was initialized if not self._gl_init_flag: GL.glClearColor(*BACKGROUND_COLOR_SPEC) for fcn in self._init_fcns: fcn() self._gl_init_flag = True # check for a change in window size if self._resized_flag: self.width, self.height = self.GetSize() GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(0, self.width, self.height, 0, 1, 0) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glViewport(0, 0, self.width, self.height) for cache in self._gl_caches: cache.changed(True) self._resized_flag = False # clear buffer if needed if self.clear_accum or not self.use_persistence: GL.glClear(GL.GL_COLOR_BUFFER_BIT) self.clear_accum=False # apply fading if self.use_persistence: GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glBegin(GL.GL_QUADS) GL.glColor4f(1,1,1,self.persist_alpha) GL.glVertex2f(0, self.height) GL.glVertex2f(self.width, self.height) GL.glVertex2f(self.width, 0) GL.glVertex2f(0, 0) GL.glEnd() GL.glDisable(GL.GL_BLEND) # draw functions for fcn in self._draw_fcns: fcn[1]() # show result self.SwapBuffers() self.unlock() def update(self): """ Force a paint event. """ if not self._gl_init_flag: return wx.PostEvent(self, wx.PaintEvent()) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/channel_plotter.py0000664000175000017500000001711512207440367025017 0ustar jcorganjcorgan# # Copyright 2008, 2009, 2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from grid_plotter_base import grid_plotter_base from OpenGL import GL import common import numpy import gltext import math LEGEND_TEXT_FONT_SIZE = 8 LEGEND_BOX_PADDING = 3 MIN_PADDING = 35, 10, 0, 0 #top, right, bottom, left #constants for the waveform storage SAMPLES_KEY = 'samples' COLOR_SPEC_KEY = 'color_spec' MARKERY_KEY = 'marker' TRIG_OFF_KEY = 'trig_off' ################################################## # Channel Plotter for X Y Waveforms ################################################## class channel_plotter(grid_plotter_base): def __init__(self, parent): """ Create a new channel plotter. """ #init grid_plotter_base.__init__(self, parent, MIN_PADDING) self.set_use_persistence(False) #setup legend cache self._legend_cache = self.new_gl_cache(self._draw_legend, 50) self.enable_legend(False) #setup waveform cache self._waveform_cache = self.new_gl_cache(self._draw_waveforms, 50) self._channels = dict() #init channel plotter self.register_init(self._init_channel_plotter) self.callback = None def _init_channel_plotter(self): """ Run gl initialization tasks. """ GL.glEnableClientState(GL.GL_VERTEX_ARRAY) def enable_legend(self, enable=None): """ Enable/disable the legend. Args: enable: true to enable Returns: the enable state when None """ if enable is None: return self._enable_legend self.lock() self._enable_legend = enable self._legend_cache.changed(True) self.unlock() def _draw_waveforms(self): """ Draw the waveforms for each channel. Scale the waveform data to the grid using gl matrix operations. """ #use scissor to prevent drawing outside grid GL.glEnable(GL.GL_SCISSOR_TEST) GL.glScissor( self.padding_left+1, self.padding_bottom+1, self.width-self.padding_left-self.padding_right-1, self.height-self.padding_top-self.padding_bottom-1, ) for channel in reversed(sorted(self._channels.keys())): samples = self._channels[channel][SAMPLES_KEY] num_samps = len(samples) if not num_samps: continue #use opengl to scale the waveform GL.glPushMatrix() GL.glTranslatef(self.padding_left, self.padding_top, 0) GL.glScalef( (self.width-self.padding_left-self.padding_right), (self.height-self.padding_top-self.padding_bottom), 1, ) GL.glTranslatef(0, 1, 0) if isinstance(samples, tuple): x_scale, x_trans = 1.0/(self.x_max-self.x_min), -self.x_min points = zip(*samples) else: x_scale, x_trans = 1.0/(num_samps-1), -self._channels[channel][TRIG_OFF_KEY] points = zip(numpy.arange(0, num_samps), samples) GL.glScalef(x_scale, -1.0/(self.y_max-self.y_min), 1) GL.glTranslatef(x_trans, -self.y_min, 0) #draw the points/lines GL.glColor3f(*self._channels[channel][COLOR_SPEC_KEY]) marker = self._channels[channel][MARKERY_KEY] if marker is None: GL.glVertexPointerf(points) GL.glDrawArrays(GL.GL_LINE_STRIP, 0, len(points)) elif isinstance(marker, (int, float)) and marker > 0: GL.glPointSize(marker) GL.glVertexPointerf(points) GL.glDrawArrays(GL.GL_POINTS, 0, len(points)) GL.glPopMatrix() GL.glDisable(GL.GL_SCISSOR_TEST) def _populate_point_label(self, x_val, y_val): """ Get the text the will populate the point label. Give X and Y values for the current point. Give values for the channel at the X coordinate. Args: x_val: the current x value y_val: the current y value Returns: a string with newlines """ #create text label_str = '%s: %s\n%s: %s'%( self.x_label, common.eng_format(x_val, self.x_units), self.y_label, common.eng_format(y_val, self.y_units), ) for channel in sorted(self._channels.keys()): samples = self._channels[channel][SAMPLES_KEY] num_samps = len(samples) if not num_samps: continue if isinstance(samples, tuple): continue #linear interpolation x_index = (num_samps-1)*(x_val-self.x_min)/(self.x_max-self.x_min) x_index_low = int(math.floor(x_index)) x_index_high = int(math.ceil(x_index)) scale = x_index - x_index_low + self._channels[channel][TRIG_OFF_KEY] y_value = (samples[x_index_high] - samples[x_index_low])*scale + samples[x_index_low] if math.isnan(y_value): continue label_str += '\n%s: %s'%(channel, common.eng_format(y_value, self.y_units)) return label_str def _call_callback (self, x_val, y_val): if self.callback != None: self.callback(x_val, y_val) def set_callback (self, callback): self.callback = callback def _draw_legend(self): """ Draw the legend in the upper right corner. For each channel, draw a rectangle out of the channel color, and overlay the channel text on top of the rectangle. """ if not self.enable_legend(): return x_off = self.width - self.padding_right - LEGEND_BOX_PADDING for i, channel in enumerate(reversed(sorted(self._channels.keys()))): samples = self._channels[channel][SAMPLES_KEY] if not len(samples): continue color_spec = self._channels[channel][COLOR_SPEC_KEY] txt = gltext.Text(channel, font_size=LEGEND_TEXT_FONT_SIZE) w, h = txt.get_size() #draw rect + text GL.glColor3f(*color_spec) self._draw_rect( x_off - w - LEGEND_BOX_PADDING, self.padding_top/2 - h/2 - LEGEND_BOX_PADDING, w+2*LEGEND_BOX_PADDING, h+2*LEGEND_BOX_PADDING, ) txt.draw_text(wx.Point(x_off - w, self.padding_top/2 - h/2)) x_off -= w + 4*LEGEND_BOX_PADDING def clear_waveform(self, channel): """ Remove a waveform from the list of waveforms. Args: channel: the channel key """ self.lock() if channel in self._channels.keys(): self._channels.pop(channel) self._legend_cache.changed(True) self._waveform_cache.changed(True) self.unlock() def set_waveform(self, channel, samples=[], color_spec=(0, 0, 0), marker=None, trig_off=0): """ Set the waveform for a given channel. Args: channel: the channel key samples: the waveform samples color_spec: the 3-tuple for line color marker: None for line trig_off: fraction of sample for trigger offset """ self.lock() if channel not in self._channels.keys(): self._legend_cache.changed(True) self._channels[channel] = { SAMPLES_KEY: samples, COLOR_SPEC_KEY: color_spec, MARKERY_KEY: marker, TRIG_OFF_KEY: trig_off, } self._waveform_cache.changed(True) self.unlock() if __name__ == '__main__': app = wx.PySimpleApp() frame = wx.Frame(None, -1, 'Demo', wx.DefaultPosition) vbox = wx.BoxSizer(wx.VERTICAL) plotter = channel_plotter(frame) plotter.set_x_grid(-1, 1, .2) plotter.set_y_grid(-1, 1, .4) vbox.Add(plotter, 1, wx.EXPAND) plotter = channel_plotter(frame) plotter.set_x_grid(-1, 1, .2) plotter.set_y_grid(-1, 1, .4) vbox.Add(plotter, 1, wx.EXPAND) frame.SetSizerAndFit(vbox) frame.SetSize(wx.Size(800, 600)) frame.Show() app.MainLoop() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/grid_plotter_base.py0000664000175000017500000003600212207440367025322 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx import wx.glcanvas from OpenGL import GL import common from plotter_base import plotter_base import gltext import math GRID_LINE_COLOR_SPEC = (.7, .7, .7) #gray GRID_BORDER_COLOR_SPEC = (0, 0, 0) #black TICK_TEXT_FONT_SIZE = 9 TITLE_TEXT_FONT_SIZE = 13 UNITS_TEXT_FONT_SIZE = 9 AXIS_LABEL_PADDING = 5 TICK_LABEL_PADDING = 5 TITLE_LABEL_PADDING = 7 POINT_LABEL_FONT_SIZE = 8 POINT_LABEL_COLOR_SPEC = (1, 1, 0.5, 0.75) POINT_LABEL_PADDING = 3 POINT_LABEL_OFFSET = 10 GRID_LINE_DASH_LEN = 4 ################################################## # Grid Plotter Base Class ################################################## class grid_plotter_base(plotter_base): def __init__(self, parent, min_padding=(0, 0, 0, 0)): plotter_base.__init__(self, parent) #setup grid cache self._grid_cache = self.new_gl_cache(self._draw_grid, 25) self.enable_grid_lines(True) #setup padding self.padding_top_min, self.padding_right_min, self.padding_bottom_min, self.padding_left_min = min_padding #store title and unit strings self.set_title('Title') self.set_x_label('X Label') self.set_y_label('Y Label') #init the grid to some value self.set_x_grid(-1, 1, 1) self.set_y_grid(-1, 1, 1) #setup point label cache self._point_label_cache = self.new_gl_cache(self._draw_point_label, 75) self.enable_point_label(False) self.enable_grid_aspect_ratio(False) self.set_point_label_coordinate(None) common.point_label_thread(self) #init grid plotter self.register_init(self._init_grid_plotter) def _init_grid_plotter(self): """ Run gl initialization tasks. """ GL.glEnableClientState(GL.GL_VERTEX_ARRAY) def set_point_label_coordinate(self, coor): """ Set the point label coordinate. Args: coor: the coordinate x, y tuple or None """ self.lock() self._point_label_coordinate = coor self._point_label_cache.changed(True) self.update() self.unlock() def call_freq_callback(self, coor): try: x, y = self._point_label_coordinate except: return if x < self.padding_left or x > self.width-self.padding_right: return if y < self.padding_top or y > self.height-self.padding_bottom: return #scale to window bounds x_win_scalar = float(x - self.padding_left)/(self.width-self.padding_left-self.padding_right) y_win_scalar = float((self.height - y) - self.padding_bottom)/(self.height-self.padding_top-self.padding_bottom) #scale to grid bounds x_val = x_win_scalar*(self.x_max-self.x_min) + self.x_min y_val = y_win_scalar*(self.y_max-self.y_min) + self.y_min self._call_callback(x_val, y_val) def enable_grid_aspect_ratio(self, enable=None): """ Enable/disable the grid aspect ratio. If enabled, enforce the aspect ratio on the padding: horizontal_padding:vertical_padding == width:height Args: enable: true to enable Returns: the enable state when None """ if enable is None: return self._enable_grid_aspect_ratio self.lock() self._enable_grid_aspect_ratio = enable for cache in self._gl_caches: cache.changed(True) self.unlock() def enable_point_label(self, enable=None): """ Enable/disable the point label. Args: enable: true to enable Returns: the enable state when None """ if enable is None: return self._enable_point_label self.lock() self._enable_point_label = enable self._point_label_cache.changed(True) self.unlock() def set_title(self, title): """ Set the title. Args: title the title string """ self.lock() self.title = title self._grid_cache.changed(True) self.unlock() def set_x_label(self, x_label, x_units=''): """ Set the x label and units. Args: x_label: the x label string x_units: the x units string """ self.lock() self.x_label = x_label self.x_units = x_units self._grid_cache.changed(True) self.unlock() def set_y_label(self, y_label, y_units=''): """ Set the y label and units. Args: y_label: the y label string y_units: the y units string """ self.lock() self.y_label = y_label self.y_units = y_units self._grid_cache.changed(True) self.unlock() def set_x_grid(self, minimum, maximum, step, scale=False): """ Set the x grid parameters. Args: minimum: the left-most value maximum: the right-most value step: the grid spacing scale: true to scale the x grid """ self.lock() self.x_min = float(minimum) self.x_max = float(maximum) self.x_step = float(step) if scale: coeff, exp, prefix = common.get_si_components(max(abs(self.x_min), abs(self.x_max))) self.x_scalar = 10**(-exp) self.x_prefix = prefix else: self.x_scalar = 1.0 self.x_prefix = '' for cache in self._gl_caches: cache.changed(True) self.unlock() def set_y_grid(self, minimum, maximum, step, scale=False): """ Set the y grid parameters. Args: minimum: the bottom-most value maximum: the top-most value step: the grid spacing scale: true to scale the y grid """ self.lock() self.y_min = float(minimum) self.y_max = float(maximum) self.y_step = float(step) if scale: coeff, exp, prefix = common.get_si_components(max(abs(self.y_min), abs(self.y_max))) self.y_scalar = 10**(-exp) self.y_prefix = prefix else: self.y_scalar = 1.0 self.y_prefix = '' for cache in self._gl_caches: cache.changed(True) self.unlock() def _draw_grid(self): """ Create the x, y, tick, and title labels. Resize the padding for the labels. Draw the border, grid, title, and labels. """ ################################################## # Create GL text labels ################################################## #create x tick labels x_tick_labels = [(tick, self._get_tick_label(tick, self.x_units)) for tick in self._get_ticks(self.x_min, self.x_max, self.x_step, self.x_scalar)] #create x tick labels y_tick_labels = [(tick, self._get_tick_label(tick, self.y_units)) for tick in self._get_ticks(self.y_min, self.y_max, self.y_step, self.y_scalar)] #create x label x_label_str = self.x_units and "%s (%s%s)"%(self.x_label, self.x_prefix, self.x_units) or self.x_label x_label = gltext.Text(x_label_str, bold=True, font_size=UNITS_TEXT_FONT_SIZE, centered=True) #create y label y_label_str = self.y_units and "%s (%s%s)"%(self.y_label, self.y_prefix, self.y_units) or self.y_label y_label = gltext.Text(y_label_str, bold=True, font_size=UNITS_TEXT_FONT_SIZE, centered=True) #create title title_label = gltext.Text(self.title, bold=True, font_size=TITLE_TEXT_FONT_SIZE, centered=True) ################################################## # Resize the padding ################################################## self.padding_top = max(2*TITLE_LABEL_PADDING + title_label.get_size()[1], self.padding_top_min) self.padding_right = max(2*TICK_LABEL_PADDING, self.padding_right_min) self.padding_bottom = max(2*AXIS_LABEL_PADDING + TICK_LABEL_PADDING + x_label.get_size()[1] + max([label.get_size()[1] for tick, label in x_tick_labels]), self.padding_bottom_min) self.padding_left = max(2*AXIS_LABEL_PADDING + TICK_LABEL_PADDING + y_label.get_size()[1] + max([label.get_size()[0] for tick, label in y_tick_labels]), self.padding_left_min) #enforce padding aspect ratio if enabled if self.enable_grid_aspect_ratio(): w_over_h_ratio = float(self.width)/float(self.height) horizontal_padding = float(self.padding_right + self.padding_left) veritical_padding = float(self.padding_top + self.padding_bottom) if w_over_h_ratio > horizontal_padding/veritical_padding: #increase the horizontal padding new_padding = veritical_padding*w_over_h_ratio - horizontal_padding #distribute the padding to left and right self.padding_left += int(round(new_padding/2)) self.padding_right += int(round(new_padding/2)) else: #increase the vertical padding new_padding = horizontal_padding/w_over_h_ratio - veritical_padding #distribute the padding to top and bottom self.padding_top += int(round(new_padding/2)) self.padding_bottom += int(round(new_padding/2)) ################################################## # Draw Grid X ################################################## for tick, label in x_tick_labels: scaled_tick = (self.width-self.padding_left-self.padding_right)*\ (tick/self.x_scalar-self.x_min)/(self.x_max-self.x_min) + self.padding_left self._draw_grid_line( (scaled_tick, self.padding_top), (scaled_tick, self.height-self.padding_bottom), ) w, h = label.get_size() label.draw_text(wx.Point(scaled_tick-w/2, self.height-self.padding_bottom+TICK_LABEL_PADDING)) ################################################## # Draw Grid Y ################################################## for tick, label in y_tick_labels: scaled_tick = (self.height-self.padding_top-self.padding_bottom)*\ (1 - (tick/self.y_scalar-self.y_min)/(self.y_max-self.y_min)) + self.padding_top self._draw_grid_line( (self.padding_left, scaled_tick), (self.width-self.padding_right, scaled_tick), ) w, h = label.get_size() label.draw_text(wx.Point(self.padding_left-w-TICK_LABEL_PADDING, scaled_tick-h/2)) ################################################## # Draw Border ################################################## GL.glColor3f(*GRID_BORDER_COLOR_SPEC) self._draw_rect( self.padding_left, self.padding_top, self.width - self.padding_right - self.padding_left, self.height - self.padding_top - self.padding_bottom, fill=False, ) ################################################## # Draw Labels ################################################## #draw title label title_label.draw_text(wx.Point(self.width/2.0, TITLE_LABEL_PADDING + title_label.get_size()[1]/2)) #draw x labels x_label.draw_text(wx.Point( (self.width-self.padding_left-self.padding_right)/2.0 + self.padding_left, self.height-(AXIS_LABEL_PADDING + x_label.get_size()[1]/2), ) ) #draw y labels y_label.draw_text(wx.Point( AXIS_LABEL_PADDING + y_label.get_size()[1]/2, (self.height-self.padding_top-self.padding_bottom)/2.0 + self.padding_top, ), rotation=90, ) def _get_tick_label(self, tick, unit): """ Format the tick value and create a gl text. Args: tick: the floating point tick value unit: the axis unit Returns: the tick label text """ if unit: tick_str = common.sci_format(tick) else: tick_str = common.eng_format(tick) return gltext.Text(tick_str, font_size=TICK_TEXT_FONT_SIZE) def _get_ticks(self, min, max, step, scalar): """ Determine the positions for the ticks. Args: min: the lower bound max: the upper bound step: the grid spacing scalar: the grid scaling Returns: a list of tick positions between min and max """ #cast to float min = float(min) max = float(max) step = float(step) #check for valid numbers try: assert step > 0 assert max > min assert max - min > step except AssertionError: return [-1, 1] #determine the start and stop value start = int(math.ceil(min/step)) stop = int(math.floor(max/step)) return [i*step*scalar for i in range(start, stop+1)] def enable_grid_lines(self, enable=None): """ Enable/disable the grid lines. Args: enable: true to enable Returns: the enable state when None """ if enable is None: return self._enable_grid_lines self.lock() self._enable_grid_lines = enable self._grid_cache.changed(True) self.unlock() def _draw_grid_line(self, coor1, coor2): """ Draw a dashed line from coor1 to coor2. Args: corr1: a tuple of x, y corr2: a tuple of x, y """ if not self.enable_grid_lines(): return length = math.sqrt((coor1[0] - coor2[0])**2 + (coor1[1] - coor2[1])**2) num_points = int(length/GRID_LINE_DASH_LEN) #calculate points array points = [( coor1[0] + i*(coor2[0]-coor1[0])/(num_points - 1), coor1[1] + i*(coor2[1]-coor1[1])/(num_points - 1) ) for i in range(num_points)] #set color and draw GL.glColor3f(*GRID_LINE_COLOR_SPEC) GL.glVertexPointerf(points) GL.glDrawArrays(GL.GL_LINES, 0, len(points)) def _draw_rect(self, x, y, width, height, fill=True): """ Draw a rectangle on the x, y plane. X and Y are the top-left corner. Args: x: the left position of the rectangle y: the top position of the rectangle width: the width of the rectangle height: the height of the rectangle fill: true to color inside of rectangle """ GL.glBegin(fill and GL.GL_QUADS or GL.GL_LINE_LOOP) GL.glVertex2f(x, y) GL.glVertex2f(x+width, y) GL.glVertex2f(x+width, y+height) GL.glVertex2f(x, y+height) GL.glEnd() def _draw_point_label(self): """ Draw the point label for the last mouse motion coordinate. The mouse coordinate must be an X, Y tuple. The label will be drawn at the X, Y coordinate. The values of the X, Y coordinate will be scaled to the current X, Y bounds. """ if not self.enable_point_label(): return if not self._point_label_coordinate: return x, y = self._point_label_coordinate if x < self.padding_left or x > self.width-self.padding_right: return if y < self.padding_top or y > self.height-self.padding_bottom: return #scale to window bounds x_win_scalar = float(x - self.padding_left)/(self.width-self.padding_left-self.padding_right) y_win_scalar = float((self.height - y) - self.padding_bottom)/(self.height-self.padding_top-self.padding_bottom) #scale to grid bounds x_val = x_win_scalar*(self.x_max-self.x_min) + self.x_min y_val = y_win_scalar*(self.y_max-self.y_min) + self.y_min #create text label_str = self._populate_point_label(x_val, y_val) if not label_str: return txt = gltext.Text(label_str, font_size=POINT_LABEL_FONT_SIZE) w, h = txt.get_size() #enable transparency GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) #draw rect + text GL.glColor4f(*POINT_LABEL_COLOR_SPEC) if x > self.width/2: x -= w+2*POINT_LABEL_PADDING + POINT_LABEL_OFFSET else: x += POINT_LABEL_OFFSET self._draw_rect(x, y-h-2*POINT_LABEL_PADDING, w+2*POINT_LABEL_PADDING, h+2*POINT_LABEL_PADDING) txt.draw_text(wx.Point(x+POINT_LABEL_PADDING, y-h-POINT_LABEL_PADDING)) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/common.py0000664000175000017500000000775312207440367023135 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import threading import time import math import wx ################################################## # Number formatting ################################################## def get_exp(num): """ Get the exponent of the number in base 10. Args: num: the floating point number Returns: the exponent as an integer """ if num == 0: return 0 return int(math.floor(math.log10(abs(num)))) def get_si_components(num): """ Get the SI units for the number. Extract the coeff and exponent of the number. The exponent will be a multiple of 3. Args: num: the floating point number Returns: the tuple coeff, exp, prefix """ num = float(num) exp = get_exp(num) exp -= exp%3 exp = min(max(exp, -24), 24) #bounds on SI table below prefix = { 24: 'Y', 21: 'Z', 18: 'E', 15: 'P', 12: 'T', 9: 'G', 6: 'M', 3: 'k', 0: '', -3: 'm', -6: 'u', -9: 'n', -12: 'p', -15: 'f', -18: 'a', -21: 'z', -24: 'y', }[exp] coeff = num/10**exp return coeff, exp, prefix def sci_format(num): """ Format a floating point number into scientific notation. Args: num: the number to format Returns: a label string """ coeff, exp, prefix = get_si_components(num) if -3 <= exp < 3: return '%g'%num return '%.3ge%d'%(coeff, exp) def eng_format(num, units=''): """ Format a floating point number into engineering notation. Args: num: the number to format units: the units to append Returns: a label string """ coeff, exp, prefix = get_si_components(num) if -3 <= exp < 3: return '%g'%num return '%g%s%s%s'%(coeff, units and ' ' or '', prefix, units) ################################################## # Interface with thread safe lock/unlock ################################################## class mutex(object): _lock = threading.Lock() def lock(self): self._lock.acquire() def unlock(self): self._lock.release() ################################################## # Periodic update thread for point label ################################################## class point_label_thread(threading.Thread, mutex): def __init__(self, plotter): self._plotter = plotter self._coor_queue = list() #bind plotter mouse events self._plotter.Bind(wx.EVT_MOTION, lambda evt: self.enqueue(evt.GetPosition())) self._plotter.Bind(wx.EVT_LEAVE_WINDOW, lambda evt: self.enqueue(None)) self._plotter.Bind(wx.EVT_RIGHT_DOWN, lambda evt: plotter.enable_point_label(not plotter.enable_point_label())) self._plotter.Bind(wx.EVT_LEFT_DOWN, lambda evt: plotter.call_freq_callback(evt.GetPosition())) #start the thread threading.Thread.__init__(self) self.start() def enqueue(self, coor): self.lock() self._coor_queue.append(coor) self.unlock() def run(self): last_ts = time.time() last_coor = coor = None try: while True: time.sleep(1.0/30.0) self.lock() #get most recent coor change if self._coor_queue: coor = self._coor_queue[-1] self._coor_queue = list() self.unlock() #update if coor change, or enough time expired if last_coor != coor or (time.time() - last_ts) > (1.0/2.0): self._plotter.set_point_label_coordinate(coor) last_coor = coor last_ts = time.time() except wx.PyDeadObjectError: pass gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/__init__.py0000664000175000017500000000161712207440367023375 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from channel_plotter import channel_plotter from waterfall_plotter import waterfall_plotter from bar_plotter import bar_plotter gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/bar_plotter.py0000664000175000017500000001027112207440367024147 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from grid_plotter_base import grid_plotter_base from OpenGL import GL import common import numpy LEGEND_TEXT_FONT_SIZE = 8 LEGEND_BOX_PADDING = 3 MIN_PADDING = 0, 0, 0, 70 #top, right, bottom, left #constants for the waveform storage SAMPLES_KEY = 'samples' COLOR_SPEC_KEY = 'color_spec' MARKERY_KEY = 'marker' TRIG_OFF_KEY = 'trig_off' ################################################## # Bar Plotter for histogram waveforms ################################################## class bar_plotter(grid_plotter_base): def __init__(self, parent): """ Create a new bar plotter. """ #init grid_plotter_base.__init__(self, parent, MIN_PADDING) self._bars = list() self._bar_width = .5 self._color_spec = (0, 0, 0) #setup bar cache self._bar_cache = self.new_gl_cache(self._draw_bars) #setup bar plotter self.register_init(self._init_bar_plotter) def _init_bar_plotter(self): """ Run gl initialization tasks. """ GL.glEnableClientState(GL.GL_VERTEX_ARRAY) def _draw_bars(self): """ Draw the vertical bars. """ bars = self._bars num_bars = len(bars) if num_bars == 0: return #use scissor to prevent drawing outside grid GL.glEnable(GL.GL_SCISSOR_TEST) GL.glScissor( self.padding_left, self.padding_bottom+1, self.width-self.padding_left-self.padding_right-1, self.height-self.padding_top-self.padding_bottom-1, ) #load the points points = list() width = self._bar_width/2 for i, bar in enumerate(bars): points.extend([ (i-width, 0), (i+width, 0), (i+width, bar), (i-width, bar), ] ) GL.glColor3f(*self._color_spec) #matrix transforms GL.glPushMatrix() GL.glTranslatef(self.padding_left, self.padding_top, 0) GL.glScalef( (self.width-self.padding_left-self.padding_right), (self.height-self.padding_top-self.padding_bottom), 1, ) GL.glTranslatef(0, 1, 0) GL.glScalef(1.0/(num_bars-1), -1.0/(self.y_max-self.y_min), 1) GL.glTranslatef(0, -self.y_min, 0) #draw the bars GL.glVertexPointerf(points) GL.glDrawArrays(GL.GL_QUADS, 0, len(points)) GL.glPopMatrix() GL.glDisable(GL.GL_SCISSOR_TEST) def _populate_point_label(self, x_val, y_val): """ Get the text the will populate the point label. Give X and Y values for the current point. Give values for the channel at the X coordinate. Args: x_val: the current x value y_val: the current y value Returns: a string with newlines """ if len(self._bars) == 0: return '' scalar = float(len(self._bars)-1)/(self.x_max - self.x_min) #convert x val to bar # bar_index = scalar*(x_val - self.x_min) #if abs(bar_index - round(bar_index)) > self._bar_width/2: return '' bar_index = int(round(bar_index)) bar_start = (bar_index - self._bar_width/2)/scalar + self.x_min bar_end = (bar_index + self._bar_width/2)/scalar + self.x_min bar_value = self._bars[bar_index] return '%s to %s\n%s: %s'%( common.eng_format(bar_start, self.x_units), common.eng_format(bar_end, self.x_units), self.y_label, common.eng_format(bar_value, self.y_units), ) def set_bars(self, bars, bar_width, color_spec): """ Set the bars. Args: bars: a list of bars bar_width: the fractional width of the bar, between 0 and 1 color_spec: the color tuple """ self.lock() self._bars = bars self._bar_width = float(bar_width) self._color_spec = color_spec self._bar_cache.changed(True) self.unlock() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plotter/waterfall_plotter.py0000664000175000017500000002316012207440367025365 0ustar jcorganjcorgan# # Copyright 2008, 2009, 2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from grid_plotter_base import grid_plotter_base from OpenGL import GL import common import numpy import gltext import math import struct LEGEND_LEFT_PAD = 7 LEGEND_NUM_BLOCKS = 256 LEGEND_NUM_LABELS = 9 LEGEND_WIDTH = 8 LEGEND_FONT_SIZE = 8 LEGEND_BORDER_COLOR_SPEC = (0, 0, 0) #black MIN_PADDING = 0, 60, 0, 0 #top, right, bottom, left ceil_log2 = lambda x: 2**int(math.ceil(math.log(x)/math.log(2))) pack_color = lambda x: struct.unpack('I', struct.pack('BBBB', *x))[0] unpack_color = lambda x: struct.unpack('BBBB', struct.pack('I', int(x))) def _get_rbga(red_pts, green_pts, blue_pts, alpha_pts=[(0, 0), (1, 0)]): """ Get an array of 256 rgba values where each index maps to a color. The scaling for red, green, blue, alpha are specified in piece-wise functions. The piece-wise functions consist of a set of x, y coordinates. The x and y values of the coordinates range from 0 to 1. The coordinates must be specified so that x increases with the index value. Resulting values are calculated along the line formed between 2 coordinates. Args: red_pts, green_pts, blue_pts, alpha_pts: an array of x,y coordinates for each color element Returns: array of rbga values (4 bytes) each """ def _fcn(x, pw): for (x1, y1), (x2, y2) in zip(pw, pw[1:]): #linear interpolation if x <= x2: return float(y1 - y2)/(x1 - x2)*(x - x1) + y1 raise Exception return numpy.array([pack_color(map( lambda pw: int(255*_fcn(i/255.0, pw)), (red_pts, green_pts, blue_pts, alpha_pts), )) for i in range(0, 256)], numpy.uint32) COLORS = { 'rgb1': _get_rbga( #http://www.ks.uiuc.edu/Research/vmd/vmd-1.7.1/ug/img47.gif red_pts = [(0, 0), (.5, 0), (1, 1)], green_pts = [(0, 0), (.5, 1), (1, 0)], blue_pts = [(0, 1), (.5, 0), (1, 0)], ), 'rgb2': _get_rbga( #http://xtide.ldeo.columbia.edu/~krahmann/coledit/screen.jpg red_pts = [(0, 0), (3.0/8, 0), (5.0/8, 1), (7.0/8, 1), (1, .5)], green_pts = [(0, 0), (1.0/8, 0), (3.0/8, 1), (5.0/8, 1), (7.0/8, 0), (1, 0)], blue_pts = [(0, .5), (1.0/8, 1), (3.0/8, 1), (5.0/8, 0), (1, 0)], ), 'rgb3': _get_rbga( red_pts = [(0, 0), (1.0/3.0, 0), (2.0/3.0, 0), (1, 1)], green_pts = [(0, 0), (1.0/3.0, 0), (2.0/3.0, 1), (1, 0)], blue_pts = [(0, 0), (1.0/3.0, 1), (2.0/3.0, 0), (1, 0)], ), 'gray': _get_rbga( red_pts = [(0, 0), (1, 1)], green_pts = [(0, 0), (1, 1)], blue_pts = [(0, 0), (1, 1)], ), } ################################################## # Waterfall Plotter ################################################## class waterfall_plotter(grid_plotter_base): def __init__(self, parent): """ Create a new channel plotter. """ #init grid_plotter_base.__init__(self, parent, MIN_PADDING) #setup legend cache self._legend_cache = self.new_gl_cache(self._draw_legend) #setup waterfall cache self._waterfall_cache = self.new_gl_cache(self._draw_waterfall, 50) #setup waterfall plotter self.register_init(self._init_waterfall) self._resize_texture(False) self._minimum = 0 self._maximum = 0 self._fft_size = 1 self._buffer = list() self._pointer = 0 self._counter = 0 self.set_num_lines(0) self.set_color_mode(COLORS.keys()[0]) self.callback = None def _init_waterfall(self): """ Run gl initialization tasks. """ self._waterfall_texture = GL.glGenTextures(1) def _draw_waterfall(self): """ Draw the waterfall from the texture. The texture is circularly filled and will wrap around. Use matrix modeling to shift and scale the texture onto the coordinate plane. """ #resize texture self._resize_texture() #setup texture GL.glBindTexture(GL.GL_TEXTURE_2D, self._waterfall_texture) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_REPLACE) #write the buffer to the texture while self._buffer: GL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, self._pointer, self._fft_size, 1, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, self._buffer.pop(0)) self._pointer = (self._pointer + 1)%self._num_lines #begin drawing GL.glEnable(GL.GL_TEXTURE_2D) GL.glPushMatrix() #matrix scaling GL.glTranslatef(self.padding_left, self.padding_top, 0) GL.glScalef( float(self.width-self.padding_left-self.padding_right), float(self.height-self.padding_top-self.padding_bottom), 1.0, ) #draw texture with wrapping GL.glBegin(GL.GL_QUADS) prop_y = float(self._pointer)/(self._num_lines-1) prop_x = float(self._fft_size)/ceil_log2(self._fft_size) off = 1.0/(self._num_lines-1) GL.glTexCoord2f(0, prop_y+1-off) GL.glVertex2f(0, 1) GL.glTexCoord2f(prop_x, prop_y+1-off) GL.glVertex2f(1, 1) GL.glTexCoord2f(prop_x, prop_y) GL.glVertex2f(1, 0) GL.glTexCoord2f(0, prop_y) GL.glVertex2f(0, 0) GL.glEnd() GL.glPopMatrix() GL.glDisable(GL.GL_TEXTURE_2D) def _populate_point_label(self, x_val, y_val): """ Get the text the will populate the point label. Give the X value for the current point. Args: x_val: the current x value y_val: the current y value Returns: a value string with units """ return '%s: %s'%(self.x_label, common.eng_format(x_val, self.x_units)) def _call_callback(self, x_val, y_val): if self.callback != None: self.callback(x_val,y_val) def set_callback(self,callback): self.callback = callback def _draw_legend(self): """ Draw the color scale legend. """ if not self._color_mode: return legend_height = self.height-self.padding_top-self.padding_bottom #draw each legend block block_height = float(legend_height)/LEGEND_NUM_BLOCKS x = self.width - self.padding_right + LEGEND_LEFT_PAD for i in range(LEGEND_NUM_BLOCKS): color = unpack_color(COLORS[self._color_mode][int(255*i/float(LEGEND_NUM_BLOCKS-1))]) GL.glColor4f(*numpy.array(color)/255.0) y = self.height - (i+1)*block_height - self.padding_bottom self._draw_rect(x, y, LEGEND_WIDTH, block_height) #draw rectangle around color scale border GL.glColor3f(*LEGEND_BORDER_COLOR_SPEC) self._draw_rect(x, self.padding_top, LEGEND_WIDTH, legend_height, fill=False) #draw each legend label label_spacing = float(legend_height)/(LEGEND_NUM_LABELS-1) x = self.width - (self.padding_right - LEGEND_LEFT_PAD - LEGEND_WIDTH)/2 for i in range(LEGEND_NUM_LABELS): proportion = i/float(LEGEND_NUM_LABELS-1) dB = proportion*(self._maximum - self._minimum) + self._minimum y = self.height - i*label_spacing - self.padding_bottom txt = gltext.Text('%ddB'%int(dB), font_size=LEGEND_FONT_SIZE, centered=True) txt.draw_text(wx.Point(x, y)) def _resize_texture(self, flag=None): """ Create the texture to fit the fft_size X num_lines. Args: flag: the set/unset or update flag """ if flag is not None: self._resize_texture_flag = flag return if not self._resize_texture_flag: return self._buffer = list() self._pointer = 0 if self._num_lines and self._fft_size: GL.glBindTexture(GL.GL_TEXTURE_2D, self._waterfall_texture) data = numpy.zeros(self._num_lines*ceil_log2(self._fft_size)*4, numpy.uint8).tostring() GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, ceil_log2(self._fft_size), self._num_lines, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, data) self._resize_texture_flag = False def set_color_mode(self, color_mode): """ Set the color mode. New samples will be converted to the new color mode. Old samples will not be recolorized. Args: color_mode: the new color mode string """ self.lock() if color_mode in COLORS.keys(): self._color_mode = color_mode self._legend_cache.changed(True) self.update() self.unlock() def set_num_lines(self, num_lines): """ Set number of lines. Powers of two only. Args: num_lines: the new number of lines """ self.lock() self._num_lines = num_lines self._resize_texture(True) self.update() self.unlock() def set_samples(self, samples, minimum, maximum): """ Set the samples to the waterfall. Convert the samples to color data. Args: samples: the array of floats minimum: the minimum value to scale maximum: the maximum value to scale """ self.lock() #set the min, max values if self._minimum != minimum or self._maximum != maximum: self._minimum = minimum self._maximum = maximum self._legend_cache.changed(True) if self._fft_size != len(samples): self._fft_size = len(samples) self._resize_texture(True) #normalize the samples to min/max samples = (samples - minimum)*float(255/(maximum-minimum)) samples = numpy.clip(samples, 0, 255) #clip samples = numpy.array(samples, numpy.uint8) #convert the samples to RGBA data data = COLORS[self._color_mode][samples].tostring() self._buffer.append(data) self._waterfall_cache.changed(True) self.unlock() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/constsink_gl.py0000664000175000017500000001032612207440367022637 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import const_window import common from gnuradio import gr from gnuradio import blocks from gnuradio import analog from pubsub import pubsub from constants import * import sys try: from gnuradio import digital except ImportError: sys.stderr.write("Error: could not import gnuradio.digital, please install gr-digitial.\n") sys.exit(1) ################################################## # Constellation sink block (wrapper for old wxgui) ################################################## class const_sink_c(gr.hier_block2, common.wxgui_hb): """ A constellation block with a gui window. """ def __init__( self, parent, title='', sample_rate=1, size=const_window.DEFAULT_WIN_SIZE, frame_rate=const_window.DEFAULT_FRAME_RATE, const_size=const_window.DEFAULT_CONST_SIZE, #mpsk recv params M=4, theta=0, loop_bw=6.28/100.0, fmax=0.06, mu=0.5, gain_mu=0.005, symbol_rate=1, omega_limit=0.005, ): #init gr.hier_block2.__init__( self, "const_sink", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0), ) #blocks sd = blocks.stream_to_vector_decimator( item_size=gr.sizeof_gr_complex, sample_rate=sample_rate, vec_rate=frame_rate, vec_len=const_size, ) fmin = -fmax gain_omega = .25*gain_mu**2 #redundant, will be updated omega = 1 #set_sample_rate will update this # Costas frequency/phase recovery loop # Critically damped 2nd order PLL self._costas = digital.costas_loop_cc(loop_bw, M) # Timing recovery loop # Critically damped 2nd order DLL self._retime = digital.clock_recovery_mm_cc(omega, gain_omega, mu, gain_mu, omega_limit) #sync = gr.mpsk_receiver_cc( # M, #psk order # theta, # alpha, # beta, # fmin, # fmax, # mu, # gain_mu, # omega, # gain_omega, # omega_limit, #) agc = analog.feedforward_agc_cc(16, 1) msgq = gr.msg_queue(2) sink = blocks.message_sink(gr.sizeof_gr_complex*const_size, msgq, True) #controller def setter(p, k, x): p[k] = x self.controller = pubsub() self.controller.subscribe(LOOP_BW_KEY, self._costas.set_loop_bandwidth) self.controller.publish(LOOP_BW_KEY, self._costas.get_loop_bandwidth) self.controller.subscribe(GAIN_MU_KEY, self._retime.set_gain_mu) self.controller.publish(GAIN_MU_KEY, self._retime.gain_mu) self.controller.subscribe(OMEGA_KEY, self._retime.set_omega) self.controller.publish(OMEGA_KEY, self._retime.omega) self.controller.subscribe(GAIN_OMEGA_KEY, self._retime.set_gain_omega) self.controller.publish(GAIN_OMEGA_KEY, self._retime.gain_omega) self.controller.subscribe(SAMPLE_RATE_KEY, sd.set_sample_rate) self.controller.subscribe(SAMPLE_RATE_KEY, lambda x: setter(self.controller, OMEGA_KEY, float(x)/symbol_rate)) self.controller.publish(SAMPLE_RATE_KEY, sd.sample_rate) #initial update self.controller[SAMPLE_RATE_KEY] = sample_rate #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY) #create window self.win = const_window.const_window( parent=parent, controller=self.controller, size=size, title=title, msg_key=MSG_KEY, loop_bw_key=LOOP_BW_KEY, gain_mu_key=GAIN_MU_KEY, gain_omega_key=GAIN_OMEGA_KEY, omega_key=OMEGA_KEY, sample_rate_key=SAMPLE_RATE_KEY, ) common.register_access_methods(self, self.win) #connect self.wxgui_connect(self, self._costas, self._retime, agc, sd, sink) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/fftsink2.py0000664000175000017500000000262512207440367021673 0ustar jcorganjcorgan# # Copyright 2008,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr p = gr.prefs() style = p.get_string('wxgui', 'style', 'auto') if style == 'auto' or style == 'gl': try: import wx.glcanvas from OpenGL.GL import * from fftsink_gl import fft_sink_f, fft_sink_c except ImportError: if style == 'gl': raise RuntimeError("Unable to import OpenGL. Are Python wrappers for OpenGL installed?") else: # Fall backto non-gl sinks from fftsink_nongl import fft_sink_f, fft_sink_c elif style == 'nongl': from fftsink_nongl import fft_sink_f, fft_sink_c else: raise RuntimeError("Unknown wxgui style") gnuradio-3.7.2.1/gr-wxgui/python/wxgui/pubsub.py0000664000175000017500000001137612207440367021450 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Abstract GNU Radio publisher/subscriber interface This is a proof of concept implementation, will likely change significantly. """ class pubsub(dict): def __init__(self): self._publishers = { } self._subscribers = { } self._proxies = { } def __missing__(self, key, value=None): dict.__setitem__(self, key, value) self._publishers[key] = None self._subscribers[key] = [] self._proxies[key] = None def __setitem__(self, key, val): if not self.has_key(key): self.__missing__(key, val) elif self._proxies[key] is not None: (p, pkey) = self._proxies[key] p[pkey] = val else: dict.__setitem__(self, key, val) for sub in self._subscribers[key]: # Note this means subscribers will get called in the thread # context of the 'set' caller. sub(val) def __getitem__(self, key): if not self.has_key(key): self.__missing__(key) if self._proxies[key] is not None: (p, pkey) = self._proxies[key] return p[pkey] elif self._publishers[key] is not None: return self._publishers[key]() else: return dict.__getitem__(self, key) def publish(self, key, publisher): if not self.has_key(key): self.__missing__(key) if self._proxies[key] is not None: (p, pkey) = self._proxies[key] p.publish(pkey, publisher) else: self._publishers[key] = publisher def subscribe(self, key, subscriber): if not self.has_key(key): self.__missing__(key) if self._proxies[key] is not None: (p, pkey) = self._proxies[key] p.subscribe(pkey, subscriber) else: self._subscribers[key].append(subscriber) def unpublish(self, key): if self._proxies[key] is not None: (p, pkey) = self._proxies[key] p.unpublish(pkey) else: self._publishers[key] = None def unsubscribe(self, key, subscriber): if self._proxies[key] is not None: (p, pkey) = self._proxies[key] p.unsubscribe(pkey, subscriber) else: self._subscribers[key].remove(subscriber) def proxy(self, key, p, pkey=None): if not self.has_key(key): self.__missing__(key) if pkey is None: pkey = key self._proxies[key] = (p, pkey) def unproxy(self, key): self._proxies[key] = None # Test code if __name__ == "__main__": import sys o = pubsub() # Non-existent key gets auto-created with None value print "Auto-created key 'foo' value:", o['foo'] # Add some subscribers # First is a bare function def print_len(x): print "len=%i" % (len(x), ) o.subscribe('foo', print_len) # The second is a class member function class subber(object): def __init__(self, param): self._param = param def printer(self, x): print self._param, `x` s = subber('param') o.subscribe('foo', s.printer) # The third is a lambda function o.subscribe('foo', lambda x: sys.stdout.write('val='+`x`+'\n')) # Update key 'foo', will notify subscribers print "Updating 'foo' with three subscribers:" o['foo'] = 'bar'; # Remove first subscriber o.unsubscribe('foo', print_len) # Update now will only trigger second and third subscriber print "Updating 'foo' after removing a subscriber:" o['foo'] = 'bar2'; # Publish a key as a function, in this case, a lambda function o.publish('baz', lambda : 42) print "Published value of 'baz':", o['baz'] # Unpublish the key o.unpublish('baz') # This will return None, as there is no publisher print "Value of 'baz' with no publisher:", o['baz'] # Set 'baz' key, it gets cached o['baz'] = 'bazzz' # Now will return cached value, since no provider print "Cached value of 'baz' after being set:", o['baz'] gnuradio-3.7.2.1/gr-wxgui/python/wxgui/scopesink_gl.py0000664000175000017500000001756512207440367022636 0ustar jcorganjcorgan# # Copyright 2008,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import scope_window import common from gnuradio import gr, filter from gnuradio import blocks from gnuradio import analog from gnuradio import wxgui from pubsub import pubsub from constants import * import math class ac_couple_block(gr.hier_block2): """ AC couple the incoming stream by subtracting out the low pass signal. Mute the low pass filter to disable ac coupling. """ def __init__(self, controller, ac_couple_key, sample_rate_key): gr.hier_block2.__init__( self, "ac_couple", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float), ) #blocks lpf = filter.single_pole_iir_filter_ff(0.0) sub = blocks.sub_ff() mute = blocks.mute_ff() #connect self.connect(self, sub, self) self.connect(self, lpf, mute, (sub, 1)) #subscribe controller.subscribe(ac_couple_key, lambda x: mute.set_mute(not x)) controller.subscribe(sample_rate_key, lambda x: lpf.set_taps(0.05)) #initialize controller[ac_couple_key] = controller[ac_couple_key] controller[sample_rate_key] = controller[sample_rate_key] ################################################## # Scope sink block (wrapper for old wxgui) ################################################## class _scope_sink_base(gr.hier_block2, common.wxgui_hb): """ A scope block with a gui window. """ def __init__( self, parent, title='', sample_rate=1, size=scope_window.DEFAULT_WIN_SIZE, v_scale=0, t_scale=0, v_offset=0, xy_mode=False, ac_couple=False, num_inputs=1, trig_mode=scope_window.DEFAULT_TRIG_MODE, y_axis_label='Counts', frame_rate=scope_window.DEFAULT_FRAME_RATE, use_persistence=False, persist_alpha=None, **kwargs #do not end with a comma ): #ensure analog alpha if persist_alpha is None: actual_frame_rate=float(frame_rate) analog_cutoff_freq=0.5 # Hertz #calculate alpha from wanted cutoff freq persist_alpha = 1.0 - math.exp(-2.0*math.pi*analog_cutoff_freq/actual_frame_rate) if not t_scale: t_scale = 10.0/sample_rate #init gr.hier_block2.__init__( self, "scope_sink", gr.io_signature(num_inputs, num_inputs, self._item_size), gr.io_signature(0, 0, 0), ) #scope msgq = gr.msg_queue(2) scope = wxgui.oscope_sink_f(sample_rate, msgq) #controller self.controller = pubsub() self.controller.subscribe(SAMPLE_RATE_KEY, scope.set_sample_rate) self.controller.publish(SAMPLE_RATE_KEY, scope.sample_rate) self.controller.subscribe(DECIMATION_KEY, scope.set_decimation_count) self.controller.publish(DECIMATION_KEY, scope.get_decimation_count) self.controller.subscribe(TRIGGER_LEVEL_KEY, scope.set_trigger_level) self.controller.publish(TRIGGER_LEVEL_KEY, scope.get_trigger_level) self.controller.subscribe(TRIGGER_MODE_KEY, scope.set_trigger_mode) self.controller.publish(TRIGGER_MODE_KEY, scope.get_trigger_mode) self.controller.subscribe(TRIGGER_SLOPE_KEY, scope.set_trigger_slope) self.controller.publish(TRIGGER_SLOPE_KEY, scope.get_trigger_slope) self.controller.subscribe(TRIGGER_CHANNEL_KEY, scope.set_trigger_channel) self.controller.publish(TRIGGER_CHANNEL_KEY, scope.get_trigger_channel) actual_num_inputs = self._real and num_inputs or num_inputs*2 #init ac couple for i in range(actual_num_inputs): self.controller[common.index_key(AC_COUPLE_KEY, i)] = ac_couple #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY) #create window self.win = scope_window.scope_window( parent=parent, controller=self.controller, size=size, title=title, frame_rate=frame_rate, num_inputs=actual_num_inputs, sample_rate_key=SAMPLE_RATE_KEY, t_scale=t_scale, v_scale=v_scale, v_offset=v_offset, xy_mode=xy_mode, trig_mode=trig_mode, y_axis_label=y_axis_label, ac_couple_key=AC_COUPLE_KEY, trigger_level_key=TRIGGER_LEVEL_KEY, trigger_mode_key=TRIGGER_MODE_KEY, trigger_slope_key=TRIGGER_SLOPE_KEY, trigger_channel_key=TRIGGER_CHANNEL_KEY, decimation_key=DECIMATION_KEY, msg_key=MSG_KEY, use_persistence=use_persistence, persist_alpha=persist_alpha, ) common.register_access_methods(self, self.win) #connect if self._real: for i in range(num_inputs): self.wxgui_connect( (self, i), ac_couple_block(self.controller, common.index_key(AC_COUPLE_KEY, i), SAMPLE_RATE_KEY), (scope, i), ) else: for i in range(num_inputs): c2f = blocks.complex_to_float() self.wxgui_connect((self, i), c2f) for j in range(2): self.connect( (c2f, j), ac_couple_block(self.controller, common.index_key(AC_COUPLE_KEY, 2*i+j), SAMPLE_RATE_KEY), (scope, 2*i+j), ) class scope_sink_f(_scope_sink_base): _item_size = gr.sizeof_float _real = True class scope_sink_c(_scope_sink_base): _item_size = gr.sizeof_gr_complex _real = False # ---------------------------------------------------------------- # Stand-alone test application # ---------------------------------------------------------------- import wx from gnuradio.wxgui import stdgui2 class test_top_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) default_input_rate = 1e6 if len(argv) > 1: input_rate = int(argv[1]) else: input_rate = default_input_rate if len(argv) > 2: v_scale = float(argv[2]) # start up at this v_scale value else: v_scale = None # start up in autorange mode, default if len(argv) > 3: t_scale = float(argv[3]) # start up at this t_scale value else: t_scale = .00003*default_input_rate/input_rate # old behavior print "input rate %s v_scale %s t_scale %s" % (input_rate,v_scale,t_scale) # Generate a complex sinusoid ampl=1.0e3 self.src0 = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 25.1e3*input_rate/default_input_rate, ampl) self.noise = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 11.1*25.1e3*input_rate/default_input_rate, ampl/10) #self.noise = analog.noise_source_c(analog.GR_GAUSSIAN, ampl/10) self.combine = blocks.add_cc() # We add this throttle block so that this demo doesn't suck down # all the CPU available. You normally wouldn't use it... self.thr = blocks.throttle(gr.sizeof_gr_complex, input_rate) scope = scope_sink_c(panel,"Secret Data",sample_rate=input_rate, v_scale=v_scale, t_scale=t_scale) vbox.Add(scope.win, 1, wx.EXPAND) # Ultimately this will be # self.connect("src0 throttle scope") self.connect(self.src0,(self.combine,0)) self.connect(self.noise,(self.combine,1)) self.connect(self.combine, self.thr, scope) def main (): app = stdgui2.stdapp(test_top_block, "O'Scope Test App") app.MainLoop() if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/fft_window.py0000664000175000017500000003251712207440367022316 0ustar jcorganjcorgan# # Copyright 2008, 2009, 2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import plotter import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_EXP = -3, 0 PERSIST_ALPHA_MIN_EXP, PERSIST_ALPHA_MAX_EXP = -2, 0 DEFAULT_WIN_SIZE = (600, 300) DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'fft_rate', 30) DB_DIV_MIN, DB_DIV_MAX = 1, 20 FFT_PLOT_COLOR_SPEC = (0.3, 0.3, 1.0) PEAK_VALS_COLOR_SPEC = (0.0, 0.8, 0.0) EMPTY_TRACE = list() TRACES = ('A', 'B') TRACES_COLOR_SPEC = { 'A': (1.0, 0.0, 0.0), 'B': (0.8, 0.0, 0.8), } ################################################## # FFT window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the plotter and fft block chain. """ def __init__(self, parent): """ Create a new control panel. Args: parent: the wx parent window """ self.parent = parent wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER) parent[SHOW_CONTROL_PANEL_KEY] = True parent.subscribe(SHOW_CONTROL_PANEL_KEY, self.Show) control_box = wx.BoxSizer(wx.VERTICAL) control_box.AddStretchSpacer() #checkboxes for average and peak hold options_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Trace Options', bold=True, orient=wx.VERTICAL, ) forms.check_box( sizer=options_box, parent=self, label='Peak Hold', ps=parent, key=PEAK_HOLD_KEY, ) forms.check_box( sizer=options_box, parent=self, label='Average', ps=parent, key=AVERAGE_KEY, ) #static text and slider for averaging avg_alpha_text = forms.static_text( sizer=options_box, parent=self, label='Avg Alpha', converter=forms.float_converter(lambda x: '%.4f'%x), ps=parent, key=AVG_ALPHA_KEY, width=50, ) avg_alpha_slider = forms.log_slider( sizer=options_box, parent=self, min_exp=AVG_ALPHA_MIN_EXP, max_exp=AVG_ALPHA_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=AVG_ALPHA_KEY, ) for widget in (avg_alpha_text, avg_alpha_slider): parent.subscribe(AVERAGE_KEY, widget.Enable) widget.Enable(parent[AVERAGE_KEY]) parent.subscribe(AVERAGE_KEY, widget.ShowItems) #allways show initially, so room is reserved for them widget.ShowItems(True) # (parent[AVERAGE_KEY]) parent.subscribe(AVERAGE_KEY, self._update_layout) forms.check_box( sizer=options_box, parent=self, label='Persistence', ps=parent, key=USE_PERSISTENCE_KEY, ) #static text and slider for persist alpha persist_alpha_text = forms.static_text( sizer=options_box, parent=self, label='Persist Alpha', converter=forms.float_converter(lambda x: '%.4f'%x), ps=parent, key=PERSIST_ALPHA_KEY, width=50, ) persist_alpha_slider = forms.log_slider( sizer=options_box, parent=self, min_exp=PERSIST_ALPHA_MIN_EXP, max_exp=PERSIST_ALPHA_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=PERSIST_ALPHA_KEY, ) for widget in (persist_alpha_text, persist_alpha_slider): parent.subscribe(USE_PERSISTENCE_KEY, widget.Enable) widget.Enable(parent[USE_PERSISTENCE_KEY]) parent.subscribe(USE_PERSISTENCE_KEY, widget.ShowItems) #allways show initially, so room is reserved for them widget.ShowItems(True) # (parent[USE_PERSISTENCE_KEY]) parent.subscribe(USE_PERSISTENCE_KEY, self._update_layout) #trace menu for trace in TRACES: trace_box = wx.BoxSizer(wx.HORIZONTAL) options_box.Add(trace_box, 0, wx.EXPAND) forms.check_box( sizer=trace_box, parent=self, ps=parent, key=TRACE_SHOW_KEY+trace, label='Trace %s'%trace, ) trace_box.AddSpacer(10) forms.single_button( sizer=trace_box, parent=self, ps=parent, key=TRACE_STORE_KEY+trace, label='Store', style=wx.BU_EXACTFIT, ) trace_box.AddSpacer(10) #radio buttons for div size control_box.AddStretchSpacer() y_ctrl_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Axis Options', bold=True, orient=wx.VERTICAL, ) forms.incr_decr_buttons( parent=self, sizer=y_ctrl_box, label='dB/Div', on_incr=self._on_incr_db_div, on_decr=self._on_decr_db_div, ) #ref lvl buttons forms.incr_decr_buttons( parent=self, sizer=y_ctrl_box, label='Ref Level', on_incr=self._on_incr_ref_level, on_decr=self._on_decr_ref_level, ) y_ctrl_box.AddSpacer(2) #autoscale forms.single_button( sizer=y_ctrl_box, parent=self, label='Autoscale', callback=self.parent.autoscale, ) #run/stop control_box.AddStretchSpacer() forms.toggle_button( sizer=control_box, parent=self, true_label='Stop', false_label='Run', ps=parent, key=RUNNING_KEY, ) #set sizer self.SetSizerAndFit(control_box) #mouse wheel event def on_mouse_wheel(event): if event.GetWheelRotation() < 0: self._on_incr_ref_level(event) else: self._on_decr_ref_level(event) parent.plotter.Bind(wx.EVT_MOUSEWHEEL, on_mouse_wheel) ################################################## # Event handlers ################################################## def _on_incr_ref_level(self, event): self.parent[REF_LEVEL_KEY] = self.parent[REF_LEVEL_KEY] + self.parent[Y_PER_DIV_KEY] def _on_decr_ref_level(self, event): self.parent[REF_LEVEL_KEY] = self.parent[REF_LEVEL_KEY] - self.parent[Y_PER_DIV_KEY] def _on_incr_db_div(self, event): self.parent[Y_PER_DIV_KEY] = min(DB_DIV_MAX, common.get_clean_incr(self.parent[Y_PER_DIV_KEY])) def _on_decr_db_div(self, event): self.parent[Y_PER_DIV_KEY] = max(DB_DIV_MIN, common.get_clean_decr(self.parent[Y_PER_DIV_KEY])) ################################################## # subscriber handlers ################################################## def _update_layout(self,key): # Just ignore the key value we get # we only need to now that the visability or size of something has changed self.parent.Layout() #self.parent.Fit() ################################################## # FFT window with plotter and control panel ################################################## class fft_window(wx.Panel, pubsub.pubsub): def __init__( self, parent, controller, size, title, real, fft_size, baseband_freq, sample_rate_key, y_per_div, y_divs, ref_level, average_key, avg_alpha_key, peak_hold, msg_key, use_persistence, persist_alpha, ): pubsub.pubsub.__init__(self) #setup self.samples = EMPTY_TRACE self.real = real self.fft_size = fft_size self._reset_peak_vals() self._traces = dict() #proxy the keys self.proxy(MSG_KEY, controller, msg_key) self.proxy(AVERAGE_KEY, controller, average_key) self.proxy(AVG_ALPHA_KEY, controller, avg_alpha_key) self.proxy(SAMPLE_RATE_KEY, controller, sample_rate_key) #initialize values self[PEAK_HOLD_KEY] = peak_hold self[Y_PER_DIV_KEY] = y_per_div self[Y_DIVS_KEY] = y_divs self[X_DIVS_KEY] = 8 #approximate self[REF_LEVEL_KEY] = ref_level self[BASEBAND_FREQ_KEY] = baseband_freq self[RUNNING_KEY] = True self[USE_PERSISTENCE_KEY] = use_persistence self[PERSIST_ALPHA_KEY] = persist_alpha for trace in TRACES: #a function that returns a function #so the function wont use local trace def new_store_trace(my_trace): def store_trace(*args): self._traces[my_trace] = self.samples self.update_grid() return store_trace def new_toggle_trace(my_trace): def toggle_trace(toggle): #do an automatic store if toggled on and empty trace if toggle and not len(self._traces[my_trace]): self._traces[my_trace] = self.samples self.update_grid() return toggle_trace self._traces[trace] = EMPTY_TRACE self[TRACE_STORE_KEY+trace] = False self[TRACE_SHOW_KEY+trace] = False self.subscribe(TRACE_STORE_KEY+trace, new_store_trace(trace)) self.subscribe(TRACE_SHOW_KEY+trace, new_toggle_trace(trace)) #init panel and plot wx.Panel.__init__(self, parent, style=wx.SIMPLE_BORDER) self.plotter = plotter.channel_plotter(self) self.plotter.SetSize(wx.Size(*size)) self.plotter.SetSizeHints(*size) self.plotter.set_title(title) self.plotter.enable_legend(True) self.plotter.enable_point_label(True) self.plotter.enable_grid_lines(True) self.plotter.set_use_persistence(use_persistence) self.plotter.set_persist_alpha(persist_alpha) #setup the box with plot and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer(wx.HORIZONTAL) main_box.Add(self.plotter, 1, wx.EXPAND) main_box.Add(self.control_panel, 0, wx.EXPAND) self.SetSizerAndFit(main_box) #register events self.subscribe(AVERAGE_KEY, self._reset_peak_vals) self.subscribe(MSG_KEY, self.handle_msg) self.subscribe(SAMPLE_RATE_KEY, self.update_grid) for key in ( BASEBAND_FREQ_KEY, Y_PER_DIV_KEY, X_DIVS_KEY, Y_DIVS_KEY, REF_LEVEL_KEY, ): self.subscribe(key, self.update_grid) self.subscribe(USE_PERSISTENCE_KEY, self.plotter.set_use_persistence) self.subscribe(PERSIST_ALPHA_KEY, self.plotter.set_persist_alpha) #initial update self.update_grid() def set_callback(self,callb): self.plotter.set_callback(callb) def autoscale(self, *args): """ Autoscale the fft plot to the last frame. Set the dynamic range and reference level. """ if not len(self.samples): return min_level, max_level = common.get_min_max_fft(self.samples) #set the range to a clean number of the dynamic range self[Y_PER_DIV_KEY] = common.get_clean_num(1+(max_level - min_level)/self[Y_DIVS_KEY]) #set the reference level to a multiple of y per div self[REF_LEVEL_KEY] = self[Y_PER_DIV_KEY]*round(.5+max_level/self[Y_PER_DIV_KEY]) def _reset_peak_vals(self, *args): self.peak_vals = EMPTY_TRACE def handle_msg(self, msg): """ Handle the message from the fft sink message queue. If complex, reorder the fft samples so the negative bins come first. If real, keep take only the positive bins. Plot the samples onto the grid as channel 1. If peak hold is enabled, plot peak vals as channel 2. Args: msg: the fft array as a character array """ if not self[RUNNING_KEY]: return #convert to floating point numbers samples = numpy.fromstring(msg, numpy.float32)[:self.fft_size] #only take first frame num_samps = len(samples) #reorder fft if self.real: samples = samples[:(num_samps+1)/2] else: samples = numpy.concatenate((samples[num_samps/2+1:], samples[:(num_samps+1)/2])) self.samples = samples #peak hold calculation if self[PEAK_HOLD_KEY]: if len(self.peak_vals) != len(samples): self.peak_vals = samples self.peak_vals = numpy.maximum(samples, self.peak_vals) #plot the peak hold self.plotter.set_waveform( channel='Peak', samples=self.peak_vals, color_spec=PEAK_VALS_COLOR_SPEC, ) else: self._reset_peak_vals() self.plotter.clear_waveform(channel='Peak') #plot the fft self.plotter.set_waveform( channel='FFT', samples=samples, color_spec=FFT_PLOT_COLOR_SPEC, ) #update the plotter self.plotter.update() def update_grid(self, *args): """ Update the plotter grid. This update method is dependent on the variables below. Determine the x and y axis grid parameters. The x axis depends on sample rate, baseband freq, and x divs. The y axis depends on y per div, y divs, and ref level. """ for trace in TRACES: channel = '%s'%trace.upper() if self[TRACE_SHOW_KEY+trace]: self.plotter.set_waveform( channel=channel, samples=self._traces[trace], color_spec=TRACES_COLOR_SPEC[trace], ) else: self.plotter.clear_waveform(channel=channel) #grid parameters sample_rate = self[SAMPLE_RATE_KEY] baseband_freq = self[BASEBAND_FREQ_KEY] y_per_div = self[Y_PER_DIV_KEY] y_divs = self[Y_DIVS_KEY] x_divs = self[X_DIVS_KEY] ref_level = self[REF_LEVEL_KEY] #determine best fitting x_per_div if self.real: x_width = sample_rate/2.0 else: x_width = sample_rate/1.0 x_per_div = common.get_clean_num(x_width/x_divs) #update the x grid if self.real: self.plotter.set_x_grid( baseband_freq, baseband_freq + sample_rate/2.0, x_per_div, True, ) else: self.plotter.set_x_grid( baseband_freq - sample_rate/2.0, baseband_freq + sample_rate/2.0, x_per_div, True, ) #update x units self.plotter.set_x_label('Frequency', 'Hz') #update y grid self.plotter.set_y_grid(ref_level-y_per_div*y_divs, ref_level, y_per_div) #update y units self.plotter.set_y_label('Amplitude', 'dB') #update plotter self.plotter.update() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/gui.py0000664000175000017500000001072512207440367020731 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from gnuradio import gr # # Top-level display panel with vertical box sizer. User does not create or # subclass this class; rather, the user supplies his own class constructor # that gets invoked with needed parameters. # class top_panel(wx.Panel): def __init__(self, frame, top_block, gui, options, args): wx.Panel.__init__(self, frame, -1) vbox = wx.BoxSizer(wx.VERTICAL) # Create the user's GUI class if gui is not None: self.gui = gui(frame, # Top-level window frame self, # Parent class for user created windows vbox, # Sizer for user to add windows to top_block, # GUI-unaware flowgraph to manipulate options, # Command-line options args) # Command-line arguments else: # User hasn't made their own GUI, create our default # We don't have a default GUI yet either :) p = wx.Panel(self) p.SetSize((640,480)) vbox.Add(p, 1, wx.EXPAND) self.SetSizer(vbox) self.SetAutoLayout(True) vbox.Fit(self) def shutdown(self): try: self.gui.shutdown() except AttributeError: pass # # Top-level window frame with menu and status bars. # class top_frame(wx.Frame): def __init__ (self, top_block, gui, options, args, title, nstatus, start, realtime): wx.Frame.__init__(self, None, -1, title) self.top_block = top_block self.CreateStatusBar(nstatus) mainmenu = wx.MenuBar() self.SetMenuBar(mainmenu) menu = wx.Menu() item = menu.Append(200, 'E&xit', 'Exit Application') # FIXME magic ID self.Bind(wx.EVT_MENU, self.OnCloseWindow, item) mainmenu.Append(menu, "&File") self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) # Create main panel, creates user GUI class with supplied parameters self.panel = top_panel(self, top_block, gui, options, args) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.panel, 1, wx.EXPAND) self.SetSizer(vbox) self.SetAutoLayout(True) vbox.Fit(self) if realtime: if gr.enable_realtime_scheduling() != gr.RT_OK: self.SetStatusText("Failed to enable realtime scheduling") if start and self.top_block is not None: self.top_block.start() def OnCloseWindow(self, event): # Give user API a chance to do something self.panel.shutdown() # Stop flowgraph as a convenience self.SetStatusText("Ensuring flowgraph has completed before exiting...") if self.top_block is not None: self.top_block.stop() self.top_block.wait() self.Destroy() # # Top-level wxPython application object. User creates or subclasses this # in their GUI script. # class app(wx.App): def __init__ (self, top_block=None, gui=None, options=None, args=None, title="GNU Radio", nstatus=1, start=False, realtime=False): self.top_block = top_block self.gui = gui self.options = options self.args = args self.title = title self.nstatus = nstatus self.start = start self.realtime = realtime wx.App.__init__ (self, redirect=False) def OnInit(self): # Pass user parameters to top window frame frame = top_frame(self.top_block, self.gui, self.options, self.args, self.title, self.nstatus, self.start, self.realtime) frame.Show(True) self.SetTopWindow(frame) return True gnuradio-3.7.2.1/gr-wxgui/python/wxgui/plot.py0000664000175000017500000021414512207440367021125 0ustar jcorganjcorgan#----------------------------------------------------------------------------- # Name: wx.lib.plot.py # Purpose: Line, Bar and Scatter Graphs # # Author: Gordon Williams # # Created: 2003/11/03 # RCS-ID: $Id$ # Copyright: (c) 2002,2007,2010 # Licence: Use as you wish. #----------------------------------------------------------------------------- # 12/15/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o 2.5 compatability update. # o Renamed to plot.py in the wx.lib directory. # o Reworked test frame to work with wx demo framework. This saves a bit # of tedious cut and paste, and the test app is excellent. # # 12/18/2003 - Jeff Grimmett (grimmtooth@softhome.net) # # o wxScrolledMessageDialog -> ScrolledMessageDialog # # Oct 6, 2004 Gordon Williams (g_will@cyberus.ca) # - Added bar graph demo # - Modified line end shape from round to square. # - Removed FloatDCWrapper for conversion to ints and ints in arguments # # Oct 15, 2004 Gordon Williams (g_will@cyberus.ca) # - Imported modules given leading underscore to name. # - Added Cursor Line Tracking and User Point Labels. # - Demo for Cursor Line Tracking and Point Labels. # - Size of plot preview frame adjusted to show page better. # - Added helper functions PositionUserToScreen and PositionScreenToUser in PlotCanvas. # - Added functions GetClosestPoints (all curves) and GetClosestPoint (only closest curve) # can be in either user coords or screen coords. # # May 27, 2007 Johnathan Corgan (jcorgan@corganenterprises.com) # - Converted from numarray to numpy # # Apr 23, 2010 Martin Dudok van Heel (http://www.olifantasia.com/gnuradio/contact_olifantasia.gif) # - Added Persistence option (emulate after glow of an analog CRT display using IIR) """ This is a simple light weight plotting module that can be used with Boa or easily integrated into your own wxPython application. The emphasis is on small size and fast plotting for large data sets. It has a reasonable number of features to do line and scatter graphs easily as well as simple bar graphs. It is not as sophisticated or as powerful as SciPy Plt or Chaco. Both of these are great packages but consume huge amounts of computer resources for simple plots. They can be found at http://scipy.com This file contains two parts; first the re-usable library stuff, then, after a "if __name__=='__main__'" test, a simple frame and a few default plots for examples and testing. Based on wxPlotCanvas Written by K.Hinsen, R. Srinivasan; Ported to wxPython Harm van der Heijden, feb 1999 Major Additions Gordon Williams Feb. 2003 (g_will@cyberus.ca) -More style options -Zooming using mouse 'rubber band' -Scroll left, right -Grid(graticule) -Printing, preview, and page set up (margins) -Axis and title labels -Cursor xy axis values -Doc strings and lots of comments -Optimizations for large number of points -Legends Did a lot of work here to speed markers up. Only a factor of 4 improvement though. Lines are much faster than markers, especially filled markers. Stay away from circles and triangles unless you only have a few thousand points. Times for 25,000 points Line - 0.078 sec Markers Square - 0.22 sec dot - 0.10 circle - 0.87 cross,plus - 0.28 triangle, triangle_down - 0.90 Thanks to Chris Barker for getting this version working on Linux. Zooming controls with mouse (when enabled): Left mouse drag - Zoom box. Left mouse double click - reset zoom. Right mouse click - zoom out centred on click location. """ import string as _string import time as _time import wx # Needs numpy or numarray try: import numpy as _numpy except: try: import numarray as _numpy #if numarray is used it is renamed numpy except: msg= """ This module requires the numpy or numarray module, which could not be imported. It probably is not installed (it's not part of the standard Python distribution). See the Python site (http://www.python.org) for information on downloading source or binaries.""" raise ImportError, "numpy or numarray not found. \n" + msg # # Plotting classes... # class PolyPoints: """Base Class for lines and markers - All methods are private. """ def __init__(self, points, attr): self.points = _numpy.array(points) self.currentScale= (1,1) self.currentShift= (0,0) self.scaled = self.points self.attributes = {} self.attributes.update(self._attributes) for name, value in attr.items(): if name not in self._attributes.keys(): raise KeyError, "Style attribute incorrect. Should be one of %s" % self._attributes.keys() self.attributes[name] = value def boundingBox(self): if len(self.points) == 0: # no curves to draw # defaults to (-1,-1) and (1,1) but axis can be set in Draw minXY= _numpy.array([-1,-1]) maxXY= _numpy.array([ 1, 1]) else: minXY= _numpy.minimum.reduce(self.points) maxXY= _numpy.maximum.reduce(self.points) return minXY, maxXY def scaleAndShift(self, scale=(1,1), shift=(0,0)): if len(self.points) == 0: # no curves to draw return if (scale is not self.currentScale) or (shift is not self.currentShift): # update point scaling self.scaled = scale*self.points+shift self.currentScale= scale self.currentShift= shift # else unchanged use the current scaling def getLegend(self): return self.attributes['legend'] def getClosestPoint(self, pntXY, pointScaled= True): """Returns the index of closest point on the curve, pointXY, scaledXY, distance x, y in user coords if pointScaled == True based on screen coords if pointScaled == False based on user coords """ if pointScaled == True: #Using screen coords p = self.scaled pxy = self.currentScale * _numpy.array(pntXY)+ self.currentShift else: #Using user coords p = self.points pxy = _numpy.array(pntXY) #determine distance for each point d= _numpy.sqrt(_numpy.add.reduce((p-pxy)**2,1)) #sqrt(dx^2+dy^2) pntIndex = _numpy.argmin(d) dist = d[pntIndex] return [pntIndex, self.points[pntIndex], self.scaled[pntIndex], dist] class PolyLine(PolyPoints): """Class to define line type and style - All methods except __init__ are private. """ _attributes = {'colour': 'black', 'width': 1, 'style': wx.SOLID, 'legend': ''} def __init__(self, points, **attr): """Creates PolyLine object points - sequence (array, tuple or list) of (x,y) points making up line **attr - key word attributes Defaults: 'colour'= 'black', - wx.Pen Colour any wx.NamedColour 'width'= 1, - Pen width 'style'= wx.SOLID, - wx.Pen style 'legend'= '' - Line Legend to display """ PolyPoints.__init__(self, points, attr) def draw(self, dc, printerScale, coord= None): colour = self.attributes['colour'] width = self.attributes['width'] * printerScale style= self.attributes['style'] pen = wx.Pen(wx.NamedColour(colour), width, style) pen.SetCap(wx.CAP_BUTT) dc.SetPen(pen) if coord == None: dc.DrawLines(self.scaled) else: dc.DrawLines(coord) # draw legend line def getSymExtent(self, printerScale): """Width and Height of Marker""" h= self.attributes['width'] * printerScale w= 5 * h return (w,h) class PolyMarker(PolyPoints): """Class to define marker type and style - All methods except __init__ are private. """ _attributes = {'colour': 'black', 'width': 1, 'size': 2, 'fillcolour': None, 'fillstyle': wx.SOLID, 'marker': 'circle', 'legend': ''} def __init__(self, points, **attr): """Creates PolyMarker object points - sequence (array, tuple or list) of (x,y) points **attr - key word attributes Defaults: 'colour'= 'black', - wx.Pen Colour any wx.NamedColour 'width'= 1, - Pen width 'size'= 2, - Marker size 'fillcolour'= same as colour, - wx.Brush Colour any wx.NamedColour 'fillstyle'= wx.SOLID, - wx.Brush fill style (use wx.TRANSPARENT for no fill) 'marker'= 'circle' - Marker shape 'legend'= '' - Marker Legend to display Marker Shapes: - 'circle' - 'dot' - 'square' - 'triangle' - 'triangle_down' - 'cross' - 'plus' """ PolyPoints.__init__(self, points, attr) def draw(self, dc, printerScale, coord= None): colour = self.attributes['colour'] width = self.attributes['width'] * printerScale size = self.attributes['size'] * printerScale fillcolour = self.attributes['fillcolour'] fillstyle = self.attributes['fillstyle'] marker = self.attributes['marker'] dc.SetPen(wx.Pen(wx.NamedColour(colour), width)) if fillcolour: dc.SetBrush(wx.Brush(wx.NamedColour(fillcolour),fillstyle)) else: dc.SetBrush(wx.Brush(wx.NamedColour(colour), fillstyle)) if coord == None: self._drawmarkers(dc, self.scaled, marker, size) else: self._drawmarkers(dc, coord, marker, size) # draw legend marker def getSymExtent(self, printerScale): """Width and Height of Marker""" s= 5*self.attributes['size'] * printerScale return (s,s) def _drawmarkers(self, dc, coords, marker,size=1): f = eval('self._' +marker) f(dc, coords, size) def _circle(self, dc, coords, size=1): fact= 2.5*size wh= 5.0*size rect= _numpy.zeros((len(coords),4),_numpy.float)+[0.0,0.0,wh,wh] rect[:,0:2]= coords-[fact,fact] dc.DrawEllipseList(rect.astype(_numpy.int32)) def _dot(self, dc, coords, size=1): dc.DrawPointList(coords) def _square(self, dc, coords, size=1): fact= 2.5*size wh= 5.0*size rect= _numpy.zeros((len(coords),4),_numpy.float)+[0.0,0.0,wh,wh] rect[:,0:2]= coords-[fact,fact] dc.DrawRectangleList(rect.astype(_numpy.int32)) def _triangle(self, dc, coords, size=1): shape= [(-2.5*size,1.44*size), (2.5*size,1.44*size), (0.0,-2.88*size)] poly= _numpy.repeat(coords,3) poly.shape= (len(coords),3,2) poly += shape dc.DrawPolygonList(poly.astype(_numpy.int32)) def _triangle_down(self, dc, coords, size=1): shape= [(-2.5*size,-1.44*size), (2.5*size,-1.44*size), (0.0,2.88*size)] poly= _numpy.repeat(coords,3) poly.shape= (len(coords),3,2) poly += shape dc.DrawPolygonList(poly.astype(_numpy.int32)) def _cross(self, dc, coords, size=1): fact= 2.5*size for f in [[-fact,-fact,fact,fact],[-fact,fact,fact,-fact]]: lines= _numpy.concatenate((coords,coords),axis=1)+f dc.DrawLineList(lines.astype(_numpy.int32)) def _plus(self, dc, coords, size=1): fact= 2.5*size for f in [[-fact,0,fact,0],[0,-fact,0,fact]]: lines= _numpy.concatenate((coords,coords),axis=1)+f dc.DrawLineList(lines.astype(_numpy.int32)) class PlotGraphics: """Container to hold PolyXXX objects and graph labels - All methods except __init__ are private. """ def __init__(self, objects, title='', xLabel='', yLabel= ''): """Creates PlotGraphics object objects - list of PolyXXX objects to make graph title - title shown at top of graph xLabel - label shown on x-axis yLabel - label shown on y-axis """ if type(objects) not in [list,tuple]: raise TypeError, "objects argument should be list or tuple" self.objects = objects self.title= title self.xLabel= xLabel self.yLabel= yLabel def boundingBox(self): p1, p2 = self.objects[0].boundingBox() for o in self.objects[1:]: p1o, p2o = o.boundingBox() p1 = _numpy.minimum(p1, p1o) p2 = _numpy.maximum(p2, p2o) return p1, p2 def scaleAndShift(self, scale=(1,1), shift=(0,0)): for o in self.objects: o.scaleAndShift(scale, shift) def setPrinterScale(self, scale): """Thickens up lines and markers only for printing""" self.printerScale= scale def setXLabel(self, xLabel= ''): """Set the X axis label on the graph""" self.xLabel= xLabel def setYLabel(self, yLabel= ''): """Set the Y axis label on the graph""" self.yLabel= yLabel def setTitle(self, title= ''): """Set the title at the top of graph""" self.title= title def getXLabel(self): """Get x axis label string""" return self.xLabel def getYLabel(self): """Get y axis label string""" return self.yLabel def getTitle(self, title= ''): """Get the title at the top of graph""" return self.title def draw(self, dc): for o in self.objects: #t=_time.clock() # profile info o.draw(dc, self.printerScale) #dt= _time.clock()-t #print o, "time=", dt def getSymExtent(self, printerScale): """Get max width and height of lines and markers symbols for legend""" symExt = self.objects[0].getSymExtent(printerScale) for o in self.objects[1:]: oSymExt = o.getSymExtent(printerScale) symExt = _numpy.maximum(symExt, oSymExt) return symExt def getLegendNames(self): """Returns list of legend names""" lst = [None]*len(self) for i in range(len(self)): lst[i]= self.objects[i].getLegend() return lst def __len__(self): return len(self.objects) def __getitem__(self, item): return self.objects[item] #------------------------------------------------------------------------------- # Main window that you will want to import into your application. class PlotCanvas(wx.Window): """Subclass of a wx.Window to allow simple general plotting of data with zoom, labels, and automatic axis scaling.""" def __init__(self, parent, id = -1, pos=wx.DefaultPosition, size=wx.DefaultSize, style= wx.DEFAULT_FRAME_STYLE, name= ""): self.use_persistence=False self.alpha=0.3 self.decimation=10 self.decim_counter=0 """Constucts a window, which can be a child of a frame, dialog or any other non-control window""" wx.Window.__init__(self, parent, id, pos, size, style, name) self.border = (1,1) self.SetBackgroundColour("white") # Create some mouse events for zooming self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown) self.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp) self.Bind(wx.EVT_MOTION, self.OnMotion) self.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDoubleClick) self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown) # set curser as cross-hairs self.SetCursor(wx.CROSS_CURSOR) # Things for printing self.print_data = wx.PrintData() self.print_data.SetPaperId(wx.PAPER_LETTER) self.print_data.SetOrientation(wx.LANDSCAPE) self.pageSetupData= wx.PageSetupDialogData() self.pageSetupData.SetMarginBottomRight((25,25)) self.pageSetupData.SetMarginTopLeft((25,25)) self.pageSetupData.SetPrintData(self.print_data) self.printerScale = 1 self.parent= parent # Zooming variables self._zoomInFactor = 0.5 self._zoomOutFactor = 2 self._zoomCorner1= _numpy.array([0.0, 0.0]) # left mouse down corner self._zoomCorner2= _numpy.array([0.0, 0.0]) # left mouse up corner self._zoomEnabled= False self._hasDragged= False # Drawing Variables self.last_draw = None self._pointScale= 1 self._pointShift= 0 self._xSpec= 'auto' self._ySpec= 'auto' self._gridEnabled= False self._legendEnabled= False self._xUseScopeTicks= False # Fonts self._fontCache = {} self._fontSizeAxis= 10 self._fontSizeTitle= 15 self._fontSizeLegend= 7 # pointLabels self._pointLabelEnabled= False self.last_PointLabel= None self._pointLabelFunc= None self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) # OnSize called to make sure the buffer is initialized. # This might result in OnSize getting called twice on some # platforms at initialization, but little harm done. self.OnSize(None) # sets the initial size based on client size # UNCONDITIONAL, needed to create self._Buffer def set_use_persistence(self, enable): self.use_persistence = enable def set_persist_alpha(self, persist_alpha): self.alpha = persist_alpha # SaveFile def SaveFile(self, fileName= ''): """Saves the file to the type specified in the extension. If no file name is specified a dialog box is provided. Returns True if sucessful, otherwise False. .bmp Save a Windows bitmap file. .xbm Save an X bitmap file. .xpm Save an XPM bitmap file. .png Save a Portable Network Graphics file. .jpg Save a Joint Photographic Experts Group file. """ if _string.lower(fileName[-3:]) not in ['bmp','xbm','xpm','png','jpg']: dlg1 = wx.FileDialog( self, "Choose a file with extension bmp, gif, xbm, xpm, png, or jpg", ".", "", "BMP files (*.bmp)|*.bmp|XBM files (*.xbm)|*.xbm|XPM file (*.xpm)|*.xpm|PNG files (*.png)|*.png|JPG files (*.jpg)|*.jpg", wx.SAVE|wx.OVERWRITE_PROMPT ) try: while 1: if dlg1.ShowModal() == wx.ID_OK: fileName = dlg1.GetPath() # Check for proper exension if _string.lower(fileName[-3:]) not in ['bmp','xbm','xpm','png','jpg']: dlg2 = wx.MessageDialog(self, 'File name extension\n' 'must be one of\n' 'bmp, xbm, xpm, png, or jpg', 'File Name Error', wx.OK | wx.ICON_ERROR) try: dlg2.ShowModal() finally: dlg2.Destroy() else: break # now save file else: # exit without saving return False finally: dlg1.Destroy() # File name has required extension fType = _string.lower(fileName[-3:]) if fType == "bmp": tp= wx.BITMAP_TYPE_BMP # Save a Windows bitmap file. elif fType == "xbm": tp= wx.BITMAP_TYPE_XBM # Save an X bitmap file. elif fType == "xpm": tp= wx.BITMAP_TYPE_XPM # Save an XPM bitmap file. elif fType == "jpg": tp= wx.BITMAP_TYPE_JPEG # Save a JPG file. else: tp= wx.BITMAP_TYPE_PNG # Save a PNG file. # Save Bitmap res= self._Buffer.SaveFile(fileName, tp) return res def PageSetup(self): """Brings up the page setup dialog""" data = self.pageSetupData data.SetPrintData(self.print_data) dlg = wx.PageSetupDialog(self.parent, data) try: if dlg.ShowModal() == wx.ID_OK: data = dlg.GetPageSetupData() # returns wx.PageSetupDialogData # updates page parameters from dialog self.pageSetupData.SetMarginBottomRight(data.GetMarginBottomRight()) self.pageSetupData.SetMarginTopLeft(data.GetMarginTopLeft()) self.pageSetupData.SetPrintData(data.GetPrintData()) self.print_data=data.GetPrintData() # updates print_data finally: dlg.Destroy() def Printout(self, paper=None): """Print current plot.""" if paper != None: self.print_data.SetPaperId(paper) pdd = wx.PrintDialogData() pdd.SetPrintData(self.print_data) printer = wx.Printer(pdd) out = PlotPrintout(self) print_ok = printer.Print(self.parent, out) if print_ok: self.print_data = printer.GetPrintDialogData().GetPrintData() out.Destroy() def PrintPreview(self): """Print-preview current plot.""" printout = PlotPrintout(self) printout2 = PlotPrintout(self) self.preview = wx.PrintPreview(printout, printout2, self.print_data) if not self.preview.Ok(): wx.MessageDialog(self, "Print Preview failed.\n" \ "Check that default printer is configured\n", \ "Print error", wx.OK|wx.CENTRE).ShowModal() self.preview.SetZoom(40) # search up tree to find frame instance frameInst= self while not isinstance(frameInst, wx.Frame): frameInst= frameInst.GetParent() frame = wx.PreviewFrame(self.preview, frameInst, "Preview") frame.Initialize() frame.SetPosition(self.GetPosition()) frame.SetSize((600,550)) frame.Centre(wx.BOTH) frame.Show(True) def SetFontSizeAxis(self, point= 10): """Set the tick and axis label font size (default is 10 point)""" self._fontSizeAxis= point def GetFontSizeAxis(self): """Get current tick and axis label font size in points""" return self._fontSizeAxis def SetFontSizeTitle(self, point= 15): """Set Title font size (default is 15 point)""" self._fontSizeTitle= point def GetFontSizeTitle(self): """Get current Title font size in points""" return self._fontSizeTitle def SetFontSizeLegend(self, point= 7): """Set Legend font size (default is 7 point)""" self._fontSizeLegend= point def GetFontSizeLegend(self): """Get current Legend font size in points""" return self._fontSizeLegend def SetEnableZoom(self, value): """Set True to enable zooming.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._zoomEnabled= value def GetEnableZoom(self): """True if zooming enabled.""" return self._zoomEnabled def SetEnableGrid(self, value): """Set True to enable grid.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._gridEnabled= value self.Redraw() def GetEnableGrid(self): """True if grid enabled.""" return self._gridEnabled def SetEnableLegend(self, value): """Set True to enable legend.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._legendEnabled= value self.Redraw() def GetEnableLegend(self): """True if Legend enabled.""" return self._legendEnabled def SetEnablePointLabel(self, value): """Set True to enable pointLabel.""" if value not in [True,False]: raise TypeError, "Value should be True or False" self._pointLabelEnabled= value self.Redraw() #will erase existing pointLabel if present self.last_PointLabel = None def GetEnablePointLabel(self): """True if pointLabel enabled.""" return self._pointLabelEnabled def SetPointLabelFunc(self, func): """Sets the function with custom code for pointLabel drawing ******** more info needed *************** """ self._pointLabelFunc= func def GetPointLabelFunc(self): """Returns pointLabel Drawing Function""" return self._pointLabelFunc def Reset(self): """Unzoom the plot.""" self.last_PointLabel = None #reset pointLabel if self.last_draw is not None: self.Draw(self.last_draw[0]) def ScrollRight(self, units): """Move view right number of axis units.""" self.last_PointLabel = None #reset pointLabel if self.last_draw is not None: graphics, xAxis, yAxis= self.last_draw xAxis= (xAxis[0]+units, xAxis[1]+units) self.Draw(graphics,xAxis,yAxis) def ScrollUp(self, units): """Move view up number of axis units.""" self.last_PointLabel = None #reset pointLabel if self.last_draw is not None: graphics, xAxis, yAxis= self.last_draw yAxis= (yAxis[0]+units, yAxis[1]+units) self.Draw(graphics,xAxis,yAxis) def GetXY(self,event): """Takes a mouse event and returns the XY user axis values.""" x,y= self.PositionScreenToUser(event.GetPosition()) return x,y def PositionUserToScreen(self, pntXY): """Converts User position to Screen Coordinates""" userPos= _numpy.array(pntXY) x,y= userPos * self._pointScale + self._pointShift return x,y def PositionScreenToUser(self, pntXY): """Converts Screen position to User Coordinates""" screenPos= _numpy.array(pntXY) x,y= (screenPos-self._pointShift)/self._pointScale return x,y def SetXSpec(self, type= 'auto'): """xSpec- defines x axis type. Can be 'none', 'min' or 'auto' where: 'none' - shows no axis or tick mark values 'min' - shows min bounding box values 'auto' - rounds axis range to sensible values """ self._xSpec= type def SetYSpec(self, type= 'auto'): """ySpec- defines x axis type. Can be 'none', 'min' or 'auto' where: 'none' - shows no axis or tick mark values 'min' - shows min bounding box values 'auto' - rounds axis range to sensible values """ self._ySpec= type def GetXSpec(self): """Returns current XSpec for axis""" return self._xSpec def GetYSpec(self): """Returns current YSpec for axis""" return self._ySpec def GetXMaxRange(self): """Returns (minX, maxX) x-axis range for displayed graph""" graphics= self.last_draw[0] p1, p2 = graphics.boundingBox() # min, max points of graphics xAxis = self._axisInterval(self._xSpec, p1[0], p2[0]) # in user units return xAxis def GetYMaxRange(self): """Returns (minY, maxY) y-axis range for displayed graph""" graphics= self.last_draw[0] p1, p2 = graphics.boundingBox() # min, max points of graphics yAxis = self._axisInterval(self._ySpec, p1[1], p2[1]) return yAxis def GetXCurrentRange(self): """Returns (minX, maxX) x-axis for currently displayed portion of graph""" return self.last_draw[1] def GetYCurrentRange(self): """Returns (minY, maxY) y-axis for currently displayed portion of graph""" return self.last_draw[2] def SetXUseScopeTicks(self, v=False): """Always 10 divisions, no labels""" self._xUseScopeTicks = v def GetXUseScopeTicks(self): return self._xUseScopeTicks def Draw(self, graphics, xAxis = None, yAxis = None, dc = None, step=None): """Draw objects in graphics with specified x and y axis. graphics- instance of PlotGraphics with list of PolyXXX objects xAxis - tuple with (min, max) axis range to view yAxis - same as xAxis dc - drawing context - doesn't have to be specified. If it's not, the offscreen buffer is used """ # check Axis is either tuple or none if type(xAxis) not in [type(None),tuple]: raise TypeError, "xAxis should be None or (minX,maxX)" if type(yAxis) not in [type(None),tuple]: raise TypeError, "yAxis should be None or (minY,maxY)" # check case for axis = (a,b) where a==b caused by improper zooms if xAxis != None: if xAxis[0] == xAxis[1]: return if yAxis != None: if yAxis[0] == yAxis[1]: return if dc == None: # sets new dc and clears it if self.use_persistence: dc = wx.MemoryDC() dc.SelectObject(self._Buffer) dc.Clear() else: dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer) dc.Clear() dc.BeginDrawing() # dc.Clear() # set font size for every thing but title and legend dc.SetFont(self._getFont(self._fontSizeAxis)) # sizes axis to axis type, create lower left and upper right corners of plot if xAxis == None or yAxis == None: # One or both axis not specified in Draw p1, p2 = graphics.boundingBox() # min, max points of graphics if xAxis == None: xAxis = self._axisInterval(self._xSpec, p1[0], p2[0]) # in user units if yAxis == None: yAxis = self._axisInterval(self._ySpec, p1[1], p2[1]) # Adjust bounding box for axis spec p1[0],p1[1] = xAxis[0], yAxis[0] # lower left corner user scale (xmin,ymin) p2[0],p2[1] = xAxis[1], yAxis[1] # upper right corner user scale (xmax,ymax) else: # Both axis specified in Draw p1= _numpy.array([xAxis[0], yAxis[0]]) # lower left corner user scale (xmin,ymin) p2= _numpy.array([xAxis[1], yAxis[1]]) # upper right corner user scale (xmax,ymax) self.last_draw = (graphics, xAxis, yAxis) # saves most recient values if False: ptx,pty,rectWidth,rectHeight= self._point2ClientCoord(p1, p2) #dc.SetPen(wx.Pen(wx.BLACK)) dc.SetBrush(wx.Brush( wx.BLACK, wx.SOLID ) ) #wx.SOLID wx.TRANSPARENT ) ) #dc.SetLogicalFunction(wx.INVERT) #wx.XOR wx.INVERT dc.DrawRectangle( ptx,pty, rectWidth,rectHeight) #dc.SetBrush(wx.Brush( wx.WHITE, wx.SOLID ) ) #dc.SetLogicalFunction(wx.COPY) # Get ticks and textExtents for axis if required if self._xSpec is not 'none': if self._xUseScopeTicks: xticks = self._scope_ticks(xAxis[0], xAxis[1]) else: xticks = self._ticks(xAxis[0], xAxis[1]) xTextExtent = dc.GetTextExtent(xticks[-1][1])# w h of x axis text last number on axis else: xticks = None xTextExtent= (0,0) # No text for ticks if self._ySpec is not 'none': yticks = self._ticks(yAxis[0], yAxis[1], step) yTextExtentBottom= dc.GetTextExtent(yticks[0][1]) yTextExtentTop = dc.GetTextExtent(yticks[-1][1]) yTextExtent= (max(yTextExtentBottom[0],yTextExtentTop[0]), max(yTextExtentBottom[1],yTextExtentTop[1])) else: yticks = None yTextExtent= (0,0) # No text for ticks # TextExtents for Title and Axis Labels titleWH, xLabelWH, yLabelWH= self._titleLablesWH(dc, graphics) # TextExtents for Legend legendBoxWH, legendSymExt, legendTextExt = self._legendWH(dc, graphics) # room around graph area rhsW= max(xTextExtent[0], legendBoxWH[0]) # use larger of number width or legend width lhsW= yTextExtent[0]+ yLabelWH[1] bottomH= max(xTextExtent[1], yTextExtent[1]/2.)+ xLabelWH[1] topH= yTextExtent[1]/2. + titleWH[1] textSize_scale= _numpy.array([rhsW+lhsW,bottomH+topH]) # make plot area smaller by text size textSize_shift= _numpy.array([lhsW, bottomH]) # shift plot area by this amount # drawing title and labels text dc.SetFont(self._getFont(self._fontSizeTitle)) titlePos= (self.plotbox_origin[0]+ lhsW + (self.plotbox_size[0]-lhsW-rhsW)/2.- titleWH[0]/2., self.plotbox_origin[1]- self.plotbox_size[1]) dc.DrawText(graphics.getTitle(),titlePos[0],titlePos[1]) dc.SetFont(self._getFont(self._fontSizeAxis)) xLabelPos= (self.plotbox_origin[0]+ lhsW + (self.plotbox_size[0]-lhsW-rhsW)/2.- xLabelWH[0]/2., self.plotbox_origin[1]- xLabelWH[1]) dc.DrawText(graphics.getXLabel(),xLabelPos[0],xLabelPos[1]) yLabelPos= (self.plotbox_origin[0], self.plotbox_origin[1]- bottomH- (self.plotbox_size[1]-bottomH-topH)/2.+ yLabelWH[0]/2.) if graphics.getYLabel(): # bug fix for Linux dc.DrawRotatedText(graphics.getYLabel(),yLabelPos[0],yLabelPos[1],90) # drawing legend makers and text if self._legendEnabled: self._drawLegend(dc,graphics,rhsW,topH,legendBoxWH, legendSymExt, legendTextExt) # allow for scaling and shifting plotted points scale = (self.plotbox_size-textSize_scale) / (p2-p1)* _numpy.array((1,-1)) shift = -p1*scale + self.plotbox_origin + textSize_shift * _numpy.array((1,-1)) self._pointScale= scale # make available for mouse events self._pointShift= shift #dc.SetLogicalFunction(wx.INVERT) #wx.XOR wx.INVERT self._drawAxes(dc, p1, p2, scale, shift, xticks, yticks) #dc.SetLogicalFunction(wx.COPY) graphics.scaleAndShift(scale, shift) graphics.setPrinterScale(self.printerScale) # thicken up lines and markers if printing # set clipping area so drawing does not occur outside axis box ptx,pty,rectWidth,rectHeight= self._point2ClientCoord(p1, p2) dc.SetClippingRegion(ptx,pty,rectWidth,rectHeight) # Draw the lines and markers #start = _time.clock() graphics.draw(dc) # print "entire graphics drawing took: %f second"%(_time.clock() - start) # remove the clipping region dc.DestroyClippingRegion() dc.EndDrawing() if self.use_persistence: dc=None self._Buffer.CopyToBuffer(self._Bufferarray) #, format=wx.BitmapBufferFormat_RGB, stride=-1) ## do the IIR filter alpha_int=int(float(self.alpha*256)) if True: _numpy.add(self._Bufferarray,0,self._Buffer3array) _numpy.multiply(self._Buffer3array,alpha_int,self._Buffer3array) _numpy.multiply(self._Buffer2array,(256-alpha_int),self._Buffer2array) _numpy.add(self._Buffer3array,self._Buffer2array,self._Buffer2array) _numpy.right_shift(self._Buffer2array,8,self._Buffer2array) elif False: self._Buffer2array=(self._Bufferarray.astype(_numpy.uint32) *alpha_int + self._Buffer2array*(256-alpha_int)).__rshift__(8) elif False: self._Buffer2array *=(256-alpha_int) self._Buffer2array +=self._Bufferarray.astype(_numpy.uint32)*alpha_int self._Buffer2array /=256 ##copy back to image buffer self._Buffer2.CopyFromBuffer(self._Buffer2array.astype(_numpy.uint8)) #, format=wx.BitmapBufferFormat_RGB, stride=-1) #draw to the screen #self.decim_counter=self.decim_counter+1 if True: #self.decim_counter>self.decimation: #self.decim_counter=0 dc2 = wx.ClientDC( self ) dc2.BeginDrawing() dc2.DrawBitmap(self._Buffer2, 0, 0, False) #dc2.DrawBitmap(self._Buffer, 0, 0, False) dc2.EndDrawing() def Redraw(self, dc= None): """Redraw the existing plot.""" if self.last_draw is not None: graphics, xAxis, yAxis= self.last_draw self.Draw(graphics,xAxis,yAxis,dc) def Clear(self): """Erase the window.""" self.last_PointLabel = None #reset pointLabel dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer) dc.Clear() self.last_draw = None def Zoom(self, Center, Ratio): """ Zoom on the plot Centers on the X,Y coords given in Center Zooms by the Ratio = (Xratio, Yratio) given """ self.last_PointLabel = None #reset maker x,y = Center if self.last_draw != None: (graphics, xAxis, yAxis) = self.last_draw w = (xAxis[1] - xAxis[0]) * Ratio[0] h = (yAxis[1] - yAxis[0]) * Ratio[1] xAxis = ( x - w/2, x + w/2 ) yAxis = ( y - h/2, y + h/2 ) self.Draw(graphics, xAxis, yAxis) def GetClosestPoints(self, pntXY, pointScaled= True): """Returns list with [curveNumber, legend, index of closest point, pointXY, scaledXY, distance] list for each curve. Returns [] if no curves are being plotted. x, y in user coords if pointScaled == True based on screen coords if pointScaled == False based on user coords """ if self.last_draw == None: #no graph available return [] graphics, xAxis, yAxis= self.last_draw l = [] for curveNum,obj in enumerate(graphics): #check there are points in the curve if len(obj.points) == 0: continue #go to next obj #[curveNumber, legend, index of closest point, pointXY, scaledXY, distance] cn = [curveNum]+ [obj.getLegend()]+ obj.getClosestPoint( pntXY, pointScaled) l.append(cn) return l def GetClosetPoint(self, pntXY, pointScaled= True): """Returns list with [curveNumber, legend, index of closest point, pointXY, scaledXY, distance] list for only the closest curve. Returns [] if no curves are being plotted. x, y in user coords if pointScaled == True based on screen coords if pointScaled == False based on user coords """ #closest points on screen based on screen scaling (pointScaled= True) #list [curveNumber, index, pointXY, scaledXY, distance] for each curve closestPts= self.GetClosestPoints(pntXY, pointScaled) if closestPts == []: return [] #no graph present #find one with least distance dists = [c[-1] for c in closestPts] mdist = min(dists) #Min dist i = dists.index(mdist) #index for min dist return closestPts[i] #this is the closest point on closest curve def UpdatePointLabel(self, mDataDict): """Updates the pointLabel point on screen with data contained in mDataDict. mDataDict will be passed to your function set by SetPointLabelFunc. It can contain anything you want to display on the screen at the scaledXY point you specify. This function can be called from parent window with onClick, onMotion events etc. """ if self.last_PointLabel != None: #compare pointXY if mDataDict["pointXY"] != self.last_PointLabel["pointXY"]: #closest changed self._drawPointLabel(self.last_PointLabel) #erase old self._drawPointLabel(mDataDict) #plot new else: #just plot new with no erase self._drawPointLabel(mDataDict) #plot new #save for next erase self.last_PointLabel = mDataDict # event handlers ********************************** def OnMotion(self, event): if self._zoomEnabled and event.LeftIsDown(): if self._hasDragged: self._drawRubberBand(self._zoomCorner1, self._zoomCorner2) # remove old else: self._hasDragged= True self._zoomCorner2[0], self._zoomCorner2[1] = self.GetXY(event) self._drawRubberBand(self._zoomCorner1, self._zoomCorner2) # add new def OnMouseLeftDown(self,event): self._zoomCorner1[0], self._zoomCorner1[1]= self.GetXY(event) def OnMouseLeftUp(self, event): if self._zoomEnabled: if self._hasDragged == True: self._drawRubberBand(self._zoomCorner1, self._zoomCorner2) # remove old self._zoomCorner2[0], self._zoomCorner2[1]= self.GetXY(event) self._hasDragged = False # reset flag minX, minY= _numpy.minimum( self._zoomCorner1, self._zoomCorner2) maxX, maxY= _numpy.maximum( self._zoomCorner1, self._zoomCorner2) self.last_PointLabel = None #reset pointLabel if self.last_draw != None: self.Draw(self.last_draw[0], xAxis = (minX,maxX), yAxis = (minY,maxY), dc = None) #else: # A box has not been drawn, zoom in on a point ## this interfered with the double click, so I've disables it. # X,Y = self.GetXY(event) # self.Zoom( (X,Y), (self._zoomInFactor,self._zoomInFactor) ) def OnMouseDoubleClick(self,event): if self._zoomEnabled: self.Reset() def OnMouseRightDown(self,event): if self._zoomEnabled: X,Y = self.GetXY(event) self.Zoom( (X,Y), (self._zoomOutFactor, self._zoomOutFactor) ) def OnPaint(self, event): # All that is needed here is to draw the buffer to screen if self.last_PointLabel != None: self._drawPointLabel(self.last_PointLabel) #erase old self.last_PointLabel = None #paint current buffer to screen dc = wx.BufferedPaintDC(self, self._Buffer) def OnSize(self,event): # The Buffer init is done here, to make sure the buffer is always # the same size as the Window Size = self.GetClientSize() # Make new offscreen bitmap: this bitmap will always have the # current drawing in it, so it can be used to save the image to # a file, or whatever. self._Buffer = wx.EmptyBitmap(Size[0],Size[1],24) if True: #self.use_persistence: #self._Bufferarray = _numpy.zeros((Size[0], Size[1],3), dtype=_numpy.uint8) self._Bufferarray = _numpy.zeros((Size[0]* Size[1]*3), dtype=_numpy.uint8) # Make new second offscreen bitmap: this bitmap will always have the # last drawing in it, so it can be used to do display time dependent processing # like averaging (IIR) or show differences between updates self._Buffer2 = wx.EmptyBitmap(Size[0],Size[1],24) # now the extra buffers for the IIR processing # note the different datatype uint32 self._Buffer2array = _numpy.zeros((Size[0]* Size[1]*3), dtype=_numpy.uint32) #dtype=_numpy.float self._Buffer3array = _numpy.zeros((Size[0]* Size[1]*3), dtype=_numpy.uint32) #dtype=_numpy.float # optional you can set the ufunct buffer size to improve speed #_numpy.setbufsize(16*((Size[0]* Size[1]*3)/16 +1)) self._setSize() self.last_PointLabel = None #reset pointLabel if self.last_draw is None: self.Clear() else: graphics, xSpec, ySpec = self.last_draw self.Draw(graphics,xSpec,ySpec) def OnLeave(self, event): """Used to erase pointLabel when mouse outside window""" if self.last_PointLabel != None: self._drawPointLabel(self.last_PointLabel) #erase old self.last_PointLabel = None # Private Methods ************************************************** def _setSize(self, width=None, height=None): """DC width and height.""" if width == None: (self.width,self.height) = self.GetClientSize() else: self.width, self.height= width,height self.plotbox_size = 0.97*_numpy.array([self.width, self.height]) xo = 0.5*(self.width-self.plotbox_size[0]) yo = self.height-0.5*(self.height-self.plotbox_size[1]) self.plotbox_origin = _numpy.array([xo, yo]) def _setPrinterScale(self, scale): """Used to thicken lines and increase marker size for print out.""" # line thickness on printer is very thin at 600 dot/in. Markers small self.printerScale= scale def _printDraw(self, printDC): """Used for printing.""" if self.last_draw != None: graphics, xSpec, ySpec= self.last_draw self.Draw(graphics,xSpec,ySpec,printDC) def _drawPointLabel(self, mDataDict): """Draws and erases pointLabels""" width = self._Buffer.GetWidth() height = self._Buffer.GetHeight() tmp_Buffer = wx.EmptyBitmap(width,height) dcs = wx.MemoryDC() dcs.SelectObject(tmp_Buffer) dcs.Clear() dcs.BeginDrawing() self._pointLabelFunc(dcs,mDataDict) #custom user pointLabel function dcs.EndDrawing() dc = wx.ClientDC( self ) #this will erase if called twice dc.Blit(0, 0, width, height, dcs, 0, 0, wx.EQUIV) #(NOT src) XOR dst def _drawLegend(self,dc,graphics,rhsW,topH,legendBoxWH, legendSymExt, legendTextExt): """Draws legend symbols and text""" # top right hand corner of graph box is ref corner trhc= self.plotbox_origin+ (self.plotbox_size-[rhsW,topH])*[1,-1] legendLHS= .091* legendBoxWH[0] # border space between legend sym and graph box lineHeight= max(legendSymExt[1], legendTextExt[1]) * 1.1 #1.1 used as space between lines dc.SetFont(self._getFont(self._fontSizeLegend)) for i in range(len(graphics)): o = graphics[i] s= i*lineHeight if isinstance(o,PolyMarker): # draw marker with legend pnt= (trhc[0]+legendLHS+legendSymExt[0]/2., trhc[1]+s+lineHeight/2.) o.draw(dc, self.printerScale, coord= _numpy.array([pnt])) elif isinstance(o,PolyLine): # draw line with legend pnt1= (trhc[0]+legendLHS, trhc[1]+s+lineHeight/2.) pnt2= (trhc[0]+legendLHS+legendSymExt[0], trhc[1]+s+lineHeight/2.) o.draw(dc, self.printerScale, coord= _numpy.array([pnt1,pnt2])) else: raise TypeError, "object is neither PolyMarker or PolyLine instance" # draw legend txt pnt= (trhc[0]+legendLHS+legendSymExt[0], trhc[1]+s+lineHeight/2.-legendTextExt[1]/2) dc.DrawText(o.getLegend(),pnt[0],pnt[1]) dc.SetFont(self._getFont(self._fontSizeAxis)) # reset def _titleLablesWH(self, dc, graphics): """Draws Title and labels and returns width and height for each""" # TextExtents for Title and Axis Labels dc.SetFont(self._getFont(self._fontSizeTitle)) title= graphics.getTitle() titleWH= dc.GetTextExtent(title) dc.SetFont(self._getFont(self._fontSizeAxis)) xLabel, yLabel= graphics.getXLabel(),graphics.getYLabel() xLabelWH= dc.GetTextExtent(xLabel) yLabelWH= dc.GetTextExtent(yLabel) return titleWH, xLabelWH, yLabelWH def _legendWH(self, dc, graphics): """Returns the size in screen units for legend box""" if self._legendEnabled != True: legendBoxWH= symExt= txtExt= (0,0) else: # find max symbol size symExt= graphics.getSymExtent(self.printerScale) # find max legend text extent dc.SetFont(self._getFont(self._fontSizeLegend)) txtList= graphics.getLegendNames() txtExt= dc.GetTextExtent(txtList[0]) for txt in graphics.getLegendNames()[1:]: txtExt= _numpy.maximum(txtExt,dc.GetTextExtent(txt)) maxW= symExt[0]+txtExt[0] maxH= max(symExt[1],txtExt[1]) # padding .1 for lhs of legend box and space between lines maxW= maxW* 1.1 maxH= maxH* 1.1 * len(txtList) dc.SetFont(self._getFont(self._fontSizeAxis)) legendBoxWH= (maxW,maxH) return (legendBoxWH, symExt, txtExt) def _drawRubberBand(self, corner1, corner2): """Draws/erases rect box from corner1 to corner2""" ptx,pty,rectWidth,rectHeight= self._point2ClientCoord(corner1, corner2) # draw rectangle dc = wx.ClientDC( self ) dc.BeginDrawing() dc.SetPen(wx.Pen(wx.BLACK)) dc.SetBrush(wx.Brush( wx.WHITE, wx.TRANSPARENT ) ) dc.SetLogicalFunction(wx.INVERT) dc.DrawRectangle( ptx,pty, rectWidth,rectHeight) dc.SetLogicalFunction(wx.COPY) dc.EndDrawing() def _getFont(self,size): """Take font size, adjusts if printing and returns wx.Font""" s = size*self.printerScale of = self.GetFont() # Linux speed up to get font from cache rather than X font server key = (int(s), of.GetFamily (), of.GetStyle (), of.GetWeight ()) font = self._fontCache.get (key, None) if font: return font # yeah! cache hit else: font = wx.Font(int(s), of.GetFamily(), of.GetStyle(), of.GetWeight()) self._fontCache[key] = font return font def _point2ClientCoord(self, corner1, corner2): """Converts user point coords to client screen int coords x,y,width,height""" c1= _numpy.array(corner1) c2= _numpy.array(corner2) # convert to screen coords pt1= c1*self._pointScale+self._pointShift pt2= c2*self._pointScale+self._pointShift # make height and width positive pul= _numpy.minimum(pt1,pt2) # Upper left corner plr= _numpy.maximum(pt1,pt2) # Lower right corner rectWidth, rectHeight= plr-pul ptx,pty= pul return ptx, pty, rectWidth, rectHeight def _axisInterval(self, spec, lower, upper): """Returns sensible axis range for given spec""" if spec == 'none' or spec == 'min': if lower == upper: return lower-0.5, upper+0.5 else: return lower, upper elif spec == 'auto': range = upper-lower # if range == 0.: if abs(range) < 1e-36: return lower-0.5, upper+0.5 log = _numpy.log10(range) power = _numpy.floor(log) fraction = log-power if fraction <= 0.05: power = power-1 grid = 10.**power lower = lower - lower % grid mod = upper % grid if mod != 0: upper = upper - mod + grid return lower, upper elif type(spec) == type(()): lower, upper = spec if lower <= upper: return lower, upper else: return upper, lower else: raise ValueError, str(spec) + ': illegal axis specification' def _drawAxes(self, dc, p1, p2, scale, shift, xticks, yticks): penWidth= self.printerScale # increases thickness for printing only dc.SetPen(wx.Pen(wx.NamedColour('BLACK'), penWidth)) # set length of tick marks--long ones make grid if self._gridEnabled: x,y,width,height= self._point2ClientCoord(p1,p2) yTickLength= width/2.0 +1 xTickLength= height/2.0 +1 else: yTickLength= 3 * self.printerScale # lengthens lines for printing xTickLength= 3 * self.printerScale if self._xSpec is not 'none': lower, upper = p1[0],p2[0] text = 1 for y, d in [(p1[1], -xTickLength), (p2[1], xTickLength)]: # miny, maxy and tick lengths a1 = scale*_numpy.array([lower, y])+shift a2 = scale*_numpy.array([upper, y])+shift dc.DrawLine(a1[0],a1[1],a2[0],a2[1]) # draws upper and lower axis line for x, label in xticks: pt = scale*_numpy.array([x, y])+shift dc.DrawLine(pt[0],pt[1],pt[0],pt[1] + d) # draws tick mark d units if text: dc.DrawText(label,pt[0],pt[1]) text = 0 # axis values not drawn on top side if self._ySpec is not 'none': lower, upper = p1[1],p2[1] text = 1 h = dc.GetCharHeight() for x, d in [(p1[0], -yTickLength), (p2[0], yTickLength)]: a1 = scale*_numpy.array([x, lower])+shift a2 = scale*_numpy.array([x, upper])+shift dc.DrawLine(a1[0],a1[1],a2[0],a2[1]) for y, label in yticks: pt = scale*_numpy.array([x, y])+shift dc.DrawLine(pt[0],pt[1],pt[0]-d,pt[1]) if text: dc.DrawText(label,pt[0]-dc.GetTextExtent(label)[0], pt[1]-0.5*h) text = 0 # axis values not drawn on right side def _ticks(self, lower, upper, step=None): ideal = (upper-lower)/7. log = _numpy.log10(ideal) power = _numpy.floor(log) fraction = log-power factor = 1. error = fraction for f, lf in self._multiples: e = _numpy.fabs(fraction-lf) if e < error: error = e factor = f grid = factor * 10.**power if power > 4 or power < -4: format = '%+7.1e' elif power >= 0: digits = max(1, int(power)) format = '%' + `digits`+'.0f' else: digits = -int(power) format = '%'+`digits+2`+'.'+`digits`+'f' #force grid when step is not None if step is not None: grid = step ticks = [] t = -grid*_numpy.floor(-lower/grid) while t <= upper: if t == -0: t = 0 #remove neg zero condition ticks.append( (t, format % (t,)) ) t = t + grid return ticks def _scope_ticks (self, lower, upper): '''Always 10 divisions, no labels''' grid = (upper - lower) / 10.0 ticks = [] t = lower while t <= upper: ticks.append( (t, "")) t = t + grid return ticks _multiples = [(2., _numpy.log10(2.)), (5., _numpy.log10(5.))] #------------------------------------------------------------------------------- # Used to layout the printer page class PlotPrintout(wx.Printout): """Controls how the plot is made in printing and previewing""" # Do not change method names in this class, # we have to override wx.Printout methods here! def __init__(self, graph): """graph is instance of plotCanvas to be printed or previewed""" wx.Printout.__init__(self) self.graph = graph def HasPage(self, page): if page == 1: return True else: return False def GetPageInfo(self): return (1, 1, 1, 1) # disable page numbers def OnPrintPage(self, page): dc = self.GetDC() # allows using floats for certain functions ## print "PPI Printer",self.GetPPIPrinter() ## print "PPI Screen", self.GetPPIScreen() ## print "DC GetSize", dc.GetSize() ## print "GetPageSizePixels", self.GetPageSizePixels() # Note PPIScreen does not give the correct number # Calulate everything for printer and then scale for preview PPIPrinter= self.GetPPIPrinter() # printer dots/inch (w,h) #PPIScreen= self.GetPPIScreen() # screen dots/inch (w,h) dcSize= dc.GetSize() # DC size pageSize= self.GetPageSizePixels() # page size in terms of pixcels clientDcSize= self.graph.GetClientSize() # find what the margins are (mm) margLeftSize,margTopSize= self.graph.pageSetupData.GetMarginTopLeft() margRightSize, margBottomSize= self.graph.pageSetupData.GetMarginBottomRight() # calculate offset and scale for dc pixLeft= margLeftSize*PPIPrinter[0]/25.4 # mm*(dots/in)/(mm/in) pixRight= margRightSize*PPIPrinter[0]/25.4 pixTop= margTopSize*PPIPrinter[1]/25.4 pixBottom= margBottomSize*PPIPrinter[1]/25.4 plotAreaW= pageSize[0]-(pixLeft+pixRight) plotAreaH= pageSize[1]-(pixTop+pixBottom) # ratio offset and scale to screen size if preview if self.IsPreview(): ratioW= float(dcSize[0])/pageSize[0] ratioH= float(dcSize[1])/pageSize[1] pixLeft *= ratioW pixTop *= ratioH plotAreaW *= ratioW plotAreaH *= ratioH # rescale plot to page or preview plot area self.graph._setSize(plotAreaW,plotAreaH) # Set offset and scale dc.SetDeviceOrigin(pixLeft,pixTop) # Thicken up pens and increase marker size for printing ratioW= float(plotAreaW)/clientDcSize[0] ratioH= float(plotAreaH)/clientDcSize[1] aveScale= (ratioW+ratioH)/2 self.graph._setPrinterScale(aveScale) # tickens up pens for printing self.graph._printDraw(dc) # rescale back to original self.graph._setSize() self.graph._setPrinterScale(1) self.graph.Redraw() #to get point label scale and shift correct return True #--------------------------------------------------------------------------- # if running standalone... # # ...a sample implementation using the above # def _draw1Objects(): # 100 points sin function, plotted as green circles data1 = 2.*_numpy.pi*_numpy.arange(200)/200. data1.shape = (100, 2) data1[:,1] = _numpy.sin(data1[:,0]) markers1 = PolyMarker(data1, legend='Green Markers', colour='green', marker='circle',size=1) # 50 points cos function, plotted as red line data1 = 2.*_numpy.pi*_numpy.arange(100)/100. data1.shape = (50,2) data1[:,1] = _numpy.cos(data1[:,0]) lines = PolyLine(data1, legend= 'Red Line', colour='red') # A few more points... pi = _numpy.pi markers2 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.), (3.*pi/4., -1)], legend='Cross Legend', colour='blue', marker='cross') return PlotGraphics([markers1, lines, markers2],"Graph Title", "X Axis", "Y Axis") def _draw2Objects(): # 100 points sin function, plotted as green dots data1 = 2.*_numpy.pi*_numpy.arange(200)/200. data1.shape = (100, 2) data1[:,1] = _numpy.sin(data1[:,0]) line1 = PolyLine(data1, legend='Green Line', colour='green', width=6, style=wx.DOT) # 50 points cos function, plotted as red dot-dash data1 = 2.*_numpy.pi*_numpy.arange(100)/100. data1.shape = (50,2) data1[:,1] = _numpy.cos(data1[:,0]) line2 = PolyLine(data1, legend='Red Line', colour='red', width=3, style= wx.DOT_DASH) # A few more points... pi = _numpy.pi markers1 = PolyMarker([(0., 0.), (pi/4., 1.), (pi/2, 0.), (3.*pi/4., -1)], legend='Cross Hatch Square', colour='blue', width= 3, size= 6, fillcolour= 'red', fillstyle= wx.CROSSDIAG_HATCH, marker='square') return PlotGraphics([markers1, line1, line2], "Big Markers with Different Line Styles") def _draw3Objects(): markerList= ['circle', 'dot', 'square', 'triangle', 'triangle_down', 'cross', 'plus', 'circle'] m=[] for i in range(len(markerList)): m.append(PolyMarker([(2*i+.5,i+.5)], legend=markerList[i], colour='blue', marker=markerList[i])) return PlotGraphics(m, "Selection of Markers", "Minimal Axis", "No Axis") def _draw4Objects(): # 25,000 point line data1 = _numpy.arange(5e5,1e6,10) data1.shape = (25000, 2) line1 = PolyLine(data1, legend='Wide Line', colour='green', width=5) # A few more points... markers2 = PolyMarker(data1, legend='Square', colour='blue', marker='square') return PlotGraphics([line1, markers2], "25,000 Points", "Value X", "") def _draw5Objects(): # Empty graph with axis defined but no points/lines points=[] line1 = PolyLine(points, legend='Wide Line', colour='green', width=5) return PlotGraphics([line1], "Empty Plot With Just Axes", "Value X", "Value Y") def _draw6Objects(): # Bar graph points1=[(1,0), (1,10)] line1 = PolyLine(points1, colour='green', legend='Feb.', width=10) points1g=[(2,0), (2,4)] line1g = PolyLine(points1g, colour='red', legend='Mar.', width=10) points1b=[(3,0), (3,6)] line1b = PolyLine(points1b, colour='blue', legend='Apr.', width=10) points2=[(4,0), (4,12)] line2 = PolyLine(points2, colour='Yellow', legend='May', width=10) points2g=[(5,0), (5,8)] line2g = PolyLine(points2g, colour='orange', legend='June', width=10) points2b=[(6,0), (6,4)] line2b = PolyLine(points2b, colour='brown', legend='July', width=10) return PlotGraphics([line1, line1g, line1b, line2, line2g, line2b], "Bar Graph - (Turn on Grid, Legend)", "Months", "Number of Students") class TestFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (600, 400)) # Now Create the menu bar and items self.mainmenu = wx.MenuBar() menu = wx.Menu() menu.Append(200, 'Page Setup...', 'Setup the printer page') self.Bind(wx.EVT_MENU, self.OnFilePageSetup, id=200) menu.Append(201, 'Print Preview...', 'Show the current plot on page') self.Bind(wx.EVT_MENU, self.OnFilePrintPreview, id=201) menu.Append(202, 'Print...', 'Print the current plot') self.Bind(wx.EVT_MENU, self.OnFilePrint, id=202) menu.Append(203, 'Save Plot...', 'Save current plot') self.Bind(wx.EVT_MENU, self.OnSaveFile, id=203) menu.Append(205, 'E&xit', 'Enough of this already!') self.Bind(wx.EVT_MENU, self.OnFileExit, id=205) self.mainmenu.Append(menu, '&File') menu = wx.Menu() menu.Append(206, 'Draw1', 'Draw plots1') self.Bind(wx.EVT_MENU,self.OnPlotDraw1, id=206) menu.Append(207, 'Draw2', 'Draw plots2') self.Bind(wx.EVT_MENU,self.OnPlotDraw2, id=207) menu.Append(208, 'Draw3', 'Draw plots3') self.Bind(wx.EVT_MENU,self.OnPlotDraw3, id=208) menu.Append(209, 'Draw4', 'Draw plots4') self.Bind(wx.EVT_MENU,self.OnPlotDraw4, id=209) menu.Append(210, 'Draw5', 'Draw plots5') self.Bind(wx.EVT_MENU,self.OnPlotDraw5, id=210) menu.Append(260, 'Draw6', 'Draw plots6') self.Bind(wx.EVT_MENU,self.OnPlotDraw6, id=260) menu.Append(211, '&Redraw', 'Redraw plots') self.Bind(wx.EVT_MENU,self.OnPlotRedraw, id=211) menu.Append(212, '&Clear', 'Clear canvas') self.Bind(wx.EVT_MENU,self.OnPlotClear, id=212) menu.Append(213, '&Scale', 'Scale canvas') self.Bind(wx.EVT_MENU,self.OnPlotScale, id=213) menu.Append(214, 'Enable &Zoom', 'Enable Mouse Zoom', kind=wx.ITEM_CHECK) self.Bind(wx.EVT_MENU,self.OnEnableZoom, id=214) menu.Append(215, 'Enable &Grid', 'Turn on Grid', kind=wx.ITEM_CHECK) self.Bind(wx.EVT_MENU,self.OnEnableGrid, id=215) menu.Append(220, 'Enable &Legend', 'Turn on Legend', kind=wx.ITEM_CHECK) self.Bind(wx.EVT_MENU,self.OnEnableLegend, id=220) menu.Append(222, 'Enable &Point Label', 'Show Closest Point', kind=wx.ITEM_CHECK) self.Bind(wx.EVT_MENU,self.OnEnablePointLabel, id=222) menu.Append(225, 'Scroll Up 1', 'Move View Up 1 Unit') self.Bind(wx.EVT_MENU,self.OnScrUp, id=225) menu.Append(230, 'Scroll Rt 2', 'Move View Right 2 Units') self.Bind(wx.EVT_MENU,self.OnScrRt, id=230) menu.Append(235, '&Plot Reset', 'Reset to original plot') self.Bind(wx.EVT_MENU,self.OnReset, id=235) self.mainmenu.Append(menu, '&Plot') menu = wx.Menu() menu.Append(300, '&About', 'About this thing...') self.Bind(wx.EVT_MENU, self.OnHelpAbout, id=300) self.mainmenu.Append(menu, '&Help') self.SetMenuBar(self.mainmenu) # A status bar to tell people what's happening self.CreateStatusBar(1) self.client = PlotCanvas(self) #define the function for drawing pointLabels self.client.SetPointLabelFunc(self.DrawPointLabel) # Create mouse event for showing cursor coords in status bar self.client.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown) # Show closest point when enabled self.client.Bind(wx.EVT_MOTION, self.OnMotion) self.Show(True) def DrawPointLabel(self, dc, mDataDict): """This is the fuction that defines how the pointLabels are plotted dc - DC that will be passed mDataDict - Dictionary of data that you want to use for the pointLabel As an example I have decided I want a box at the curve point with some text information about the curve plotted below. Any wxDC method can be used. """ # ---------- dc.SetPen(wx.Pen(wx.BLACK)) dc.SetBrush(wx.Brush( wx.BLACK, wx.SOLID ) ) sx, sy = mDataDict["scaledXY"] #scaled x,y of closest point dc.DrawRectangle( sx-5,sy-5, 10, 10) #10by10 square centered on point px,py = mDataDict["pointXY"] cNum = mDataDict["curveNum"] pntIn = mDataDict["pIndex"] legend = mDataDict["legend"] #make a string to display s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" %(cNum, legend, px, py, pntIn) dc.DrawText(s, sx , sy+1) # ----------- def OnMouseLeftDown(self,event): s= "Left Mouse Down at Point: (%.4f, %.4f)" % self.client.GetXY(event) self.SetStatusText(s) event.Skip() #allows plotCanvas OnMouseLeftDown to be called def OnMotion(self, event): #show closest point (when enbled) if self.client.GetEnablePointLabel() == True: #make up dict with info for the pointLabel #I've decided to mark the closest point on the closest curve dlst= self.client.GetClosetPoint( self.client.GetXY(event), pointScaled= True) if dlst != []: #returns [] if none curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst #make up dictionary to pass to my user function (see DrawPointLabel) mDataDict= {"curveNum":curveNum, "legend":legend, "pIndex":pIndex,\ "pointXY":pointXY, "scaledXY":scaledXY} #pass dict to update the pointLabel self.client.UpdatePointLabel(mDataDict) event.Skip() #go to next handler def OnFilePageSetup(self, event): self.client.PageSetup() def OnFilePrintPreview(self, event): self.client.PrintPreview() def OnFilePrint(self, event): self.client.Printout() def OnSaveFile(self, event): self.client.SaveFile() def OnFileExit(self, event): self.Close() def OnPlotDraw1(self, event): self.resetDefaults() self.client.Draw(_draw1Objects()) def OnPlotDraw2(self, event): self.resetDefaults() self.client.Draw(_draw2Objects()) def OnPlotDraw3(self, event): self.resetDefaults() self.client.SetFont(wx.Font(10,wx.SCRIPT,wx.NORMAL,wx.NORMAL)) self.client.SetFontSizeAxis(20) self.client.SetFontSizeLegend(12) self.client.SetXSpec('min') self.client.SetYSpec('none') self.client.Draw(_draw3Objects()) def OnPlotDraw4(self, event): self.resetDefaults() drawObj= _draw4Objects() self.client.Draw(drawObj) ## # profile ## start = _time.clock() ## for x in range(10): ## self.client.Draw(drawObj) ## print "10 plots of Draw4 took: %f sec."%(_time.clock() - start) ## # profile end def OnPlotDraw5(self, event): # Empty plot with just axes self.resetDefaults() drawObj= _draw5Objects() # make the axis X= (0,5), Y=(0,10) # (default with None is X= (-1,1), Y= (-1,1)) self.client.Draw(drawObj, xAxis= (0,5), yAxis= (0,10)) def OnPlotDraw6(self, event): #Bar Graph Example self.resetDefaults() #self.client.SetEnableLegend(True) #turn on Legend #self.client.SetEnableGrid(True) #turn on Grid self.client.SetXSpec('none') #turns off x-axis scale self.client.SetYSpec('auto') self.client.Draw(_draw6Objects(), xAxis= (0,7)) def OnPlotRedraw(self,event): self.client.Redraw() def OnPlotClear(self,event): self.client.Clear() def OnPlotScale(self, event): if self.client.last_draw != None: graphics, xAxis, yAxis= self.client.last_draw self.client.Draw(graphics,(1,3.05),(0,1)) def OnEnableZoom(self, event): self.client.SetEnableZoom(event.IsChecked()) def OnEnableGrid(self, event): self.client.SetEnableGrid(event.IsChecked()) def OnEnableLegend(self, event): self.client.SetEnableLegend(event.IsChecked()) def OnEnablePointLabel(self, event): self.client.SetEnablePointLabel(event.IsChecked()) def OnScrUp(self, event): self.client.ScrollUp(1) def OnScrRt(self,event): self.client.ScrollRight(2) def OnReset(self,event): self.client.Reset() def OnHelpAbout(self, event): from wx.lib.dialogs import ScrolledMessageDialog about = ScrolledMessageDialog(self, __doc__, "About...") about.ShowModal() def resetDefaults(self): """Just to reset the fonts back to the PlotCanvas defaults""" self.client.SetFont(wx.Font(10,wx.SWISS,wx.NORMAL,wx.NORMAL)) self.client.SetFontSizeAxis(10) self.client.SetFontSizeLegend(7) self.client.SetXSpec('auto') self.client.SetYSpec('auto') def __test(): class MyApp(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame = TestFrame(None, -1, "PlotCanvas") #frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop() if __name__ == '__main__': __test() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/waterfallsink_nongl.py0000664000175000017500000003721512207440367024213 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2003-2005,2007,2008,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, fft, filter from gnuradio import blocks from gnuradio import analog from gnuradio.wxgui import stdgui2 from gnuradio.filter import window import wx import gnuradio.wxgui.plot as plot import numpy import os import math default_fftsink_size = (640,240) default_fft_rate = gr.prefs().get_long('wxgui', 'fft_rate', 15) class waterfall_sink_base(object): def __init__(self, input_is_real=False, baseband_freq=0, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title=''): # initialize common attributes self.baseband_freq = baseband_freq self.sample_rate = sample_rate self.fft_size = fft_size self.fft_rate = fft_rate self.average = average if avg_alpha is None: self.avg_alpha = 2.0 / fft_rate else: self.avg_alpha = avg_alpha self.title = title self.input_is_real = input_is_real self.msgq = gr.msg_queue(2) # queue up to 2 messages def set_average(self, average): self.average = average if average: self.avg.set_taps(self.avg_alpha) else: self.avg.set_taps(1.0) def set_avg_alpha(self, avg_alpha): self.avg_alpha = avg_alpha def set_baseband_freq(self, baseband_freq): self.baseband_freq = baseband_freq def set_sample_rate(self, sample_rate): self.sample_rate = sample_rate self._set_n() def _set_n(self): self.one_in_n.set_n(max(1, int(self.sample_rate/self.fft_size/self.fft_rate))) def set_callback(self, callb): return class waterfall_sink_f(gr.hier_block2, waterfall_sink_base): def __init__(self, parent, baseband_freq=0, y_per_div=10, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='', size=default_fftsink_size, **kwargs): gr.hier_block2.__init__(self, "waterfall_sink_f", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(0,0,0)) waterfall_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq, sample_rate=sample_rate, fft_size=fft_size, fft_rate=fft_rate, average=average, avg_alpha=avg_alpha, title=title) self.s2p = blocks.stream_to_vector(gr.sizeof_float, self.fft_size) self.one_in_n = blocks.keep_one_in_n(gr.sizeof_float * self.fft_size, max(1, int(self.sample_rate/self.fft_size/self.fft_rate))) mywindow = window.blackmanharris(self.fft_size) self.fft = fft.fft_vfc(self.fft_size, True, mywindow) self.c2mag = blocks.complex_to_mag(self.fft_size) self.avg = filter.single_pole_iir_filter_ff(1.0, self.fft_size) self.log = blocks.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size)) self.sink = blocks.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True) self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink) self.win = waterfall_window(self, parent, size=size) self.set_average(self.average) class waterfall_sink_c(gr.hier_block2, waterfall_sink_base): def __init__(self, parent, baseband_freq=0, y_per_div=10, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='', size=default_fftsink_size, **kwargs): gr.hier_block2.__init__(self, "waterfall_sink_f", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0,0,0)) waterfall_sink_base.__init__(self, input_is_real=False, baseband_freq=baseband_freq, sample_rate=sample_rate, fft_size=fft_size, fft_rate=fft_rate, average=average, avg_alpha=avg_alpha, title=title) self.s2p = blocks.stream_to_vector(gr.sizeof_gr_complex, self.fft_size) self.one_in_n = blocks.keep_one_in_n(gr.sizeof_gr_complex * self.fft_size, max(1, int(self.sample_rate/self.fft_size/self.fft_rate))) mywindow = window.blackmanharris(self.fft_size) self.fft = fft.fft_vcc(self.fft_size, True, mywindow) self.c2mag = blocks.complex_to_mag(self.fft_size) self.avg = filter.single_pole_iir_filter_ff(1.0, self.fft_size) self.log = blocks.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size)) self.sink = blocks.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True) self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink) self.win = waterfall_window(self, parent, size=size) self.set_average(self.average) # ------------------------------------------------------------------------ myDATA_EVENT = wx.NewEventType() EVT_DATA_EVENT = wx.PyEventBinder (myDATA_EVENT, 0) class DataEvent(wx.PyEvent): def __init__(self, data): wx.PyEvent.__init__(self) self.SetEventType (myDATA_EVENT) self.data = data def Clone (self): self.__class__ (self.GetId()) class input_watcher (gru.msgq_runner): def __init__ (self, msgq, fft_size, event_receiver, **kwds): self.fft_size = fft_size self.event_receiver = event_receiver gru.msgq_runner.__init__(self, msgq, self.handle_msg) def handle_msg(self, msg): itemsize = int(msg.arg1()) nitems = int(msg.arg2()) s = msg.to_string() # get the body of the msg as a string # There may be more than one FFT frame in the message. # If so, we take only the last one if nitems > 1: start = itemsize * (nitems - 1) s = s[start:start+itemsize] complex_data = numpy.fromstring (s, numpy.float32) de = DataEvent (complex_data) wx.PostEvent (self.event_receiver, de) del de class waterfall_window (wx.Panel): def __init__ (self, fftsink, parent, id = -1, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = ""): wx.Panel.__init__(self, parent, id, pos, size, style, name) self.set_baseband_freq = fftsink.set_baseband_freq self.fftsink = fftsink self.bm = wx.EmptyBitmap(self.fftsink.fft_size, 300, -1) self.scale_factor = 5.0 # FIXME should autoscale, or set this dc1 = wx.MemoryDC() dc1.SelectObject(self.bm) dc1.Clear() self.pens = self.make_pens() wx.EVT_PAINT( self, self.OnPaint ) wx.EVT_CLOSE (self, self.on_close_window) EVT_DATA_EVENT (self, self.set_data) self.build_popup_menu() wx.EVT_CLOSE (self, self.on_close_window) self.Bind(wx.EVT_RIGHT_UP, self.on_right_click) self.input_watcher = input_watcher(fftsink.msgq, fftsink.fft_size, self) def on_close_window (self, event): print "waterfall_window: on_close_window" self.keep_running = False def const_list(self,const,len): return [const] * len def make_colormap(self): r = [] r.extend(self.const_list(0,96)) r.extend(range(0,255,4)) r.extend(self.const_list(255,64)) r.extend(range(255,128,-4)) g = [] g.extend(self.const_list(0,32)) g.extend(range(0,255,4)) g.extend(self.const_list(255,64)) g.extend(range(255,0,-4)) g.extend(self.const_list(0,32)) b = range(128,255,4) b.extend(self.const_list(255,64)) b.extend(range(255,0,-4)) b.extend(self.const_list(0,96)) return (r,g,b) def make_pens(self): (r,g,b) = self.make_colormap() pens = [] for i in range(0,256): colour = wx.Colour(r[i], g[i], b[i]) pens.append( wx.Pen(colour, 2, wx.SOLID)) return pens def OnPaint(self, event): dc = wx.PaintDC(self) self.DoDrawing(dc) def DoDrawing(self, dc=None): if dc is None: dc = wx.ClientDC(self) dc.DrawBitmap(self.bm, 0, 0, False ) def const_list(self,const,len): a = [const] for i in range(1,len): a.append(const) return a def set_data (self, evt): dB = evt.data L = len (dB) dc1 = wx.MemoryDC() dc1.SelectObject(self.bm) dc1.Blit(0,1,self.fftsink.fft_size,300,dc1,0,0,wx.COPY,False,-1,-1) x = max(abs(self.fftsink.sample_rate), abs(self.fftsink.baseband_freq)) if x >= 1e9: sf = 1e-9 units = "GHz" elif x >= 1e6: sf = 1e-6 units = "MHz" else: sf = 1e-3 units = "kHz" if self.fftsink.input_is_real: # only plot 1/2 the points d_max = L/2 p_width = 2 else: d_max = L/2 p_width = 1 scale_factor = self.scale_factor if self.fftsink.input_is_real: # real fft for x_pos in range(0, d_max): value = int(dB[x_pos] * scale_factor) value = min(255, max(0, value)) dc1.SetPen(self.pens[value]) dc1.DrawRectangle(x_pos*p_width, 0, p_width, 2) else: # complex fft for x_pos in range(0, d_max): # positive freqs value = int(dB[x_pos] * scale_factor) value = min(255, max(0, value)) dc1.SetPen(self.pens[value]) dc1.DrawRectangle(x_pos*p_width + d_max, 0, p_width, 2) for x_pos in range(0 , d_max): # negative freqs value = int(dB[x_pos+d_max] * scale_factor) value = min(255, max(0, value)) dc1.SetPen(self.pens[value]) dc1.DrawRectangle(x_pos*p_width, 0, p_width, 2) del dc1 self.DoDrawing (None) def on_average(self, evt): # print "on_average" self.fftsink.set_average(evt.IsChecked()) def on_right_click(self, event): menu = self.popup_menu for id, pred in self.checkmarks.items(): item = menu.FindItemById(id) item.Check(pred()) self.PopupMenu(menu, event.GetPosition()) def build_popup_menu(self): self.id_incr_ref_level = wx.NewId() self.id_decr_ref_level = wx.NewId() self.id_incr_y_per_div = wx.NewId() self.id_decr_y_per_div = wx.NewId() self.id_y_per_div_1 = wx.NewId() self.id_y_per_div_2 = wx.NewId() self.id_y_per_div_5 = wx.NewId() self.id_y_per_div_10 = wx.NewId() self.id_y_per_div_20 = wx.NewId() self.id_average = wx.NewId() self.Bind(wx.EVT_MENU, self.on_average, id=self.id_average) #self.Bind(wx.EVT_MENU, self.on_incr_ref_level, id=self.id_incr_ref_level) #self.Bind(wx.EVT_MENU, self.on_decr_ref_level, id=self.id_decr_ref_level) #self.Bind(wx.EVT_MENU, self.on_incr_y_per_div, id=self.id_incr_y_per_div) #self.Bind(wx.EVT_MENU, self.on_decr_y_per_div, id=self.id_decr_y_per_div) #self.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_1) #self.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_2) #self.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_5) #self.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_10) #self.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_20) # make a menu menu = wx.Menu() self.popup_menu = menu menu.AppendCheckItem(self.id_average, "Average") # menu.Append(self.id_incr_ref_level, "Incr Ref Level") # menu.Append(self.id_decr_ref_level, "Decr Ref Level") # menu.Append(self.id_incr_y_per_div, "Incr dB/div") # menu.Append(self.id_decr_y_per_div, "Decr dB/div") # menu.AppendSeparator() # we'd use RadioItems for these, but they're not supported on Mac #menu.AppendCheckItem(self.id_y_per_div_1, "1 dB/div") #menu.AppendCheckItem(self.id_y_per_div_2, "2 dB/div") #menu.AppendCheckItem(self.id_y_per_div_5, "5 dB/div") #menu.AppendCheckItem(self.id_y_per_div_10, "10 dB/div") #menu.AppendCheckItem(self.id_y_per_div_20, "20 dB/div") self.checkmarks = { self.id_average : lambda : self.fftsink.average #self.id_y_per_div_1 : lambda : self.fftsink.y_per_div == 1, #self.id_y_per_div_2 : lambda : self.fftsink.y_per_div == 2, #self.id_y_per_div_5 : lambda : self.fftsink.y_per_div == 5, #self.id_y_per_div_10 : lambda : self.fftsink.y_per_div == 10, #self.id_y_per_div_20 : lambda : self.fftsink.y_per_div == 20, } def next_up(v, seq): """ Return the first item in seq that is > v. """ for s in seq: if s > v: return s return v def next_down(v, seq): """ Return the last item in seq that is < v. """ rseq = list(seq[:]) rseq.reverse() for s in rseq: if s < v: return s return v # ---------------------------------------------------------------- # Standalone test app # ---------------------------------------------------------------- class test_top_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) fft_size = 512 # build our flow graph input_rate = 20.000e3 # Generate a complex sinusoid self.src1 = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 5.75e3, 1000) #src1 = analog.sig_source_c(input_rate, analog.GR_CONST_WAVE, 5.75e3, 1000) # We add these throttle blocks so that this demo doesn't # suck down all the CPU available. Normally you wouldn't use these. self.thr1 = blocks.throttle(gr.sizeof_gr_complex, input_rate) sink1 = waterfall_sink_c(panel, title="Complex Data", fft_size=fft_size, sample_rate=input_rate, baseband_freq=100e3) self.connect(self.src1, self.thr1, sink1) vbox.Add(sink1.win, 1, wx.EXPAND) # generate a real sinusoid self.src2 = analog.sig_source_f(input_rate, analog.GR_SIN_WAVE, 5.75e3, 1000) self.thr2 = blocks.throttle(gr.sizeof_float, input_rate) sink2 = waterfall_sink_f(panel, title="Real Data", fft_size=fft_size, sample_rate=input_rate, baseband_freq=100e3) self.connect(self.src2, self.thr2, sink2) vbox.Add(sink2.win, 1, wx.EXPAND) def main (): app = stdgui2.stdapp(test_top_block, "Waterfall Sink Test App") app.MainLoop() if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/histo_window.py0000664000175000017500000001157512207440367022666 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import plotter import common import wx import numpy import math import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## DEFAULT_WIN_SIZE = (600, 300) ################################################## # histo window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the plotter and histo sink. """ def __init__(self, parent): """ Create a new control panel. Args: parent: the wx parent window """ self.parent = parent wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER) parent[SHOW_CONTROL_PANEL_KEY] = True parent.subscribe(SHOW_CONTROL_PANEL_KEY, self.Show) control_box = wx.BoxSizer(wx.VERTICAL) SIZE = (100, -1) control_box = forms.static_box_sizer( parent=self, label='Options', bold=True, orient=wx.VERTICAL, ) #num bins control_box.AddStretchSpacer() forms.text_box( sizer=control_box, parent=self, label='Num Bins', converter=forms.int_converter(), ps=parent, key=NUM_BINS_KEY, ) #frame size control_box.AddStretchSpacer() forms.text_box( sizer=control_box, parent=self, label='Frame Size', converter=forms.int_converter(), ps=parent, key=FRAME_SIZE_KEY, ) #run/stop control_box.AddStretchSpacer() forms.toggle_button( sizer=control_box, parent=self, true_label='Stop', false_label='Run', ps=parent, key=RUNNING_KEY, ) #set sizer self.SetSizerAndFit(control_box) ################################################## # histo window with plotter and control panel ################################################## class histo_window(wx.Panel, pubsub.pubsub): def __init__( self, parent, controller, size, title, maximum_key, minimum_key, num_bins_key, frame_size_key, msg_key, ): pubsub.pubsub.__init__(self) #setup self.samples = list() #proxy the keys self.proxy(MAXIMUM_KEY, controller, maximum_key) self.proxy(MINIMUM_KEY, controller, minimum_key) self.proxy(NUM_BINS_KEY, controller, num_bins_key) self.proxy(FRAME_SIZE_KEY, controller, frame_size_key) self.proxy(MSG_KEY, controller, msg_key) #initialize values self[RUNNING_KEY] = True self[X_DIVS_KEY] = 8 self[Y_DIVS_KEY] = 4 #init panel and plot wx.Panel.__init__(self, parent, style=wx.SIMPLE_BORDER) self.plotter = plotter.bar_plotter(self) self.plotter.SetSize(wx.Size(*size)) self.plotter.SetSizeHints(*size) self.plotter.set_title(title) self.plotter.enable_point_label(True) self.plotter.enable_grid_lines(False) #setup the box with plot and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer(wx.HORIZONTAL) main_box.Add(self.plotter, 1, wx.EXPAND) main_box.Add(self.control_panel, 0, wx.EXPAND) self.SetSizerAndFit(main_box) #register events self.subscribe(MSG_KEY, self.handle_msg) self.subscribe(X_DIVS_KEY, self.update_grid) self.subscribe(Y_DIVS_KEY, self.update_grid) def handle_msg(self, msg): """ Handle the message from the fft sink message queue. Args: msg: the frame as a character array """ if not self[RUNNING_KEY]: return #convert to floating point numbers self.samples = 100*numpy.fromstring(msg, numpy.float32)[:self[NUM_BINS_KEY]] #only take first frame self.plotter.set_bars( bars=self.samples, bar_width=0.6, color_spec=(0, 0, 1), ) self.update_grid() def update_grid(self): if not len(self.samples): return #calculate the maximum y value y_off = math.ceil(numpy.max(self.samples)) y_off = min(max(y_off, 1.0), 100.0) #between 1% and 100% #update the x grid self.plotter.set_x_grid( self[MINIMUM_KEY], self[MAXIMUM_KEY], common.get_clean_num((self[MAXIMUM_KEY] - self[MINIMUM_KEY])/self[X_DIVS_KEY]), ) self.plotter.set_x_label('Counts') #update the y grid self.plotter.set_y_grid(0, y_off, y_off/self[Y_DIVS_KEY]) self.plotter.set_y_label('Frequency', '%') self.plotter.update() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/slider.py0000664000175000017500000000261212226272446021425 0ustar jcorganjcorgan#!/usr/bin/env python import wx def slider(parent, min, max, callback): """ Return a wx.Slider object. Args: min: minimum slider value (float) max: maximum slider value (float) callback: function of one arg invoked when slider moves. @rtype: wx.Slider """ new_id = wx.NewId() s = wx.Slider(parent, new_id, (max+min)/2, min, max, wx.DefaultPosition, wx.Size(250,-1), wx.SL_HORIZONTAL | wx.SL_LABELS) wx.EVT_COMMAND_SCROLL(parent, new_id, lambda evt : callback(evt.GetInt())) return s # ---------------------------------------------------------------- # Demo app # ---------------------------------------------------------------- if __name__ == '__main__': from gnuradio.wxgui import stdgui2 class demo_graph(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) vbox.Add(slider(panel, 23, 47, self.my_callback1), 1, wx.ALIGN_CENTER) vbox.Add(slider(panel, -100, 100, self.my_callback2), 1, wx.ALIGN_CENTER) def my_callback1(self, val): print "cb1 = ", val def my_callback2(self, val): print "cb2 = ", val def main (): app = stdgui2.stdapp (demo_graph, "Slider Demo") app.MainLoop () main () gnuradio-3.7.2.1/gr-wxgui/python/wxgui/termsink.py0000664000175000017500000000421412207440367021775 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gru import wx DEFAULT_WIN_SIZE = (600, 300) APPEND_EVENT = wx.NewEventType() EVT_APPEND_EVENT = wx.PyEventBinder(APPEND_EVENT, 0) class AppendEvent(wx.PyEvent): def __init__(self, text): wx.PyEvent.__init__(self) self.SetEventType(APPEND_EVENT) self.text = text def Clone(self): self.__class__(self.GetId()) class termsink(wx.Panel): def __init__(self, parent, msgq, size=DEFAULT_WIN_SIZE, ): wx.Panel.__init__(self, parent, size=size, style=wx.SIMPLE_BORDER, ) self.text_ctrl = wx.TextCtrl(self, wx.ID_ANY, value="", size=size, style=wx.TE_MULTILINE|wx.TE_READONLY, ) main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(self.text_ctrl, 1, wx.EXPAND) self.SetSizerAndFit(main_sizer) EVT_APPEND_EVENT(self, self.evt_append) self.runner = gru.msgq_runner(msgq, self.handle_msg) def handle_msg(self, msg): # This gets called in the queue runner thread context # For now, just add whatever the user sends to the text control text = msg.to_string() # Create a wxPython event and post it to the event queue evt = AppendEvent(text) wx.PostEvent(self, evt) del evt def evt_append(self, evt): # This gets called by the wxPython event queue runner self.text_ctrl.AppendText(evt.text) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/waterfallsink_gl.py0000664000175000017500000001271712207440367023500 0ustar jcorganjcorgan# # Copyright 2008,2009,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import waterfall_window import common from gnuradio import gr, fft from gnuradio import analog from gnuradio import blocks from gnuradio.fft import logpwrfft from pubsub import pubsub from constants import * ################################################## # Waterfall sink block (wrapper for old wxgui) ################################################## class _waterfall_sink_base(gr.hier_block2, common.wxgui_hb): """ An fft block with real/complex inputs and a gui window. """ def __init__( self, parent, baseband_freq=0, ref_level=50, sample_rate=1, fft_size=512, fft_rate=waterfall_window.DEFAULT_FRAME_RATE, average=False, avg_alpha=None, title='', size=waterfall_window.DEFAULT_WIN_SIZE, ref_scale=2.0, dynamic_range=80, num_lines=256, win=None, **kwargs #do not end with a comma ): #ensure avg alpha if avg_alpha is None: avg_alpha = 2.0/fft_rate #init gr.hier_block2.__init__( self, "waterfall_sink", gr.io_signature(1, 1, self._item_size), gr.io_signature(0, 0, 0), ) #blocks fft = self._fft_chain( sample_rate=sample_rate, fft_size=fft_size, frame_rate=fft_rate, ref_scale=ref_scale, avg_alpha=avg_alpha, average=average, win=win, ) msgq = gr.msg_queue(2) sink = blocks.message_sink(gr.sizeof_float*fft_size, msgq, True) #controller self.controller = pubsub() self.controller.subscribe(AVERAGE_KEY, fft.set_average) self.controller.publish(AVERAGE_KEY, fft.average) self.controller.subscribe(AVG_ALPHA_KEY, fft.set_avg_alpha) self.controller.publish(AVG_ALPHA_KEY, fft.avg_alpha) self.controller.subscribe(SAMPLE_RATE_KEY, fft.set_sample_rate) self.controller.publish(SAMPLE_RATE_KEY, fft.sample_rate) self.controller.subscribe(DECIMATION_KEY, fft.set_decimation) self.controller.publish(DECIMATION_KEY, fft.decimation) self.controller.subscribe(FRAME_RATE_KEY, fft.set_vec_rate) self.controller.publish(FRAME_RATE_KEY, fft.frame_rate) #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY) #create window self.win = waterfall_window.waterfall_window( parent=parent, controller=self.controller, size=size, title=title, real=self._real, fft_size=fft_size, num_lines=num_lines, baseband_freq=baseband_freq, decimation_key=DECIMATION_KEY, sample_rate_key=SAMPLE_RATE_KEY, frame_rate_key=FRAME_RATE_KEY, dynamic_range=dynamic_range, ref_level=ref_level, average_key=AVERAGE_KEY, avg_alpha_key=AVG_ALPHA_KEY, msg_key=MSG_KEY, ) common.register_access_methods(self, self.win) setattr(self.win, 'set_baseband_freq', getattr(self, 'set_baseband_freq')) #BACKWARDS #connect self.wxgui_connect(self, fft, sink) def set_callback(self,callb): self.win.set_callback(callb) class waterfall_sink_f(_waterfall_sink_base): _fft_chain = logpwrfft.logpwrfft_f _item_size = gr.sizeof_float _real = True class waterfall_sink_c(_waterfall_sink_base): _fft_chain = logpwrfft.logpwrfft_c _item_size = gr.sizeof_gr_complex _real = False # ---------------------------------------------------------------- # Standalone test app # ---------------------------------------------------------------- import wx from gnuradio.wxgui import stdgui2 class test_top_block(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) fft_size = 512 # build our flow graph input_rate = 20.000e3 # Generate a complex sinusoid self.src1 = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 5.75e3, 1000) #src1 = analog.sig_source_c(input_rate, analog.GR_CONST_WAVE, 5.75e3, 1000) # We add these throttle blocks so that this demo doesn't # suck down all the CPU available. Normally you wouldn't use these. self.thr1 = blocks.throttle(gr.sizeof_gr_complex, input_rate) sink1 = waterfall_sink_c(panel, title="Complex Data", fft_size=fft_size, sample_rate=input_rate, baseband_freq=100e3) self.connect(self.src1, self.thr1, sink1) vbox.Add(sink1.win, 1, wx.EXPAND) # generate a real sinusoid self.src2 = analog.sig_source_f(input_rate, analog.GR_SIN_WAVE, 5.75e3, 1000) self.thr2 = blocks.throttle(gr.sizeof_float, input_rate) sink2 = waterfall_sink_f(panel, title="Real Data", fft_size=fft_size, sample_rate=input_rate, baseband_freq=100e3) self.connect(self.src2, self.thr2, sink2) vbox.Add(sink2.win, 1, wx.EXPAND) def main (): app = stdgui2.stdapp(test_top_block, "Waterfall Sink Test App") app.MainLoop() if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-wxgui/python/wxgui/powermate.py0000664000175000017500000003557012207440367022155 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Handler for Griffin PowerMate, Contour ShuttlePro & ShuttleXpress USB knobs This is Linux and wxPython specific. """ import os import sys import struct import exceptions import threading import wx from gnuradio import gru imported_ok = True try: import select import fcntl except ImportError: imported_ok = False # First a little bit of background: # # The Griffin PowerMate has # * a single knob which rotates # * a single button (pressing the knob) # # The Contour ShuttleXpress (aka SpaceShuttle) has # * "Jog Wheel" -- the knob (rotary encoder) on the inside # * "Shuttle Ring" -- the spring loaded rubber covered ring # * 5 buttons # # The Contour ShuttlePro has # * "Jog Wheel" -- the knob (rotary encoder) on the inside # * "Shuttle Ring" -- the spring loaded rubber covered ring # * 13 buttons # # The Contour ShuttlePro V2 has # *"Jog Wheel" -- the knob (rotary encoder) on the inside # * "Shuttle Ring" -- the spring loaded rubber covered ring # * 15 buttons # We remap all the buttons on the devices so that they start at zero. # For the ShuttleXpress the buttons are 0 to 4 (left to right) # For the ShuttlePro, we number the buttons immediately above # the ring 0 to 4 (left to right) so that they match our numbering # on the ShuttleXpress. The top row is 5, 6, 7, 8. The first row below # the ring is 9, 10, and the bottom row is 11, 12. # For the ShuttlePro V2, buttons 13 & 14 are to the # left and right of the wheel respectively. # We generate 3 kinds of events: # # button press/release (button_number, press/release) # knob rotation (relative_clicks) # typically -1, +1 # shuttle position (absolute_position) # -7,-6,...,0,...,6,7 # ---------------------------------------------------------------- # Our ID's for the devices: # Not to be confused with anything related to magic hardware numbers. ID_POWERMATE = 'powermate' ID_SHUTTLE_XPRESS = 'shuttle xpress' ID_SHUTTLE_PRO = 'shuttle pro' ID_SHUTTLE_PRO_V2 = 'shuttle pro v2' # ------------------------------------------------------------------------ # format of messages that we read from /dev/input/event* # See /usr/include/linux/input.h for more info # #struct input_event { # struct timeval time; = {long seconds, long microseconds} # unsigned short type; # unsigned short code; # unsigned int value; #}; input_event_struct = "@llHHi" input_event_size = struct.calcsize(input_event_struct) # ------------------------------------------------------------------------ # input_event types # ------------------------------------------------------------------------ IET_SYN = 0x00 # aka RESET IET_KEY = 0x01 # key or button press/release IET_REL = 0x02 # relative movement (knob rotation) IET_ABS = 0x03 # absolute position (graphics pad, etc) IET_MSC = 0x04 IET_LED = 0x11 IET_SND = 0x12 IET_REP = 0x14 IET_FF = 0x15 IET_PWR = 0x16 IET_FF_STATUS = 0x17 IET_MAX = 0x1f # ------------------------------------------------------------------------ # input_event codes (there are a zillion of them, we only define a few) # ------------------------------------------------------------------------ # these are valid for IET_KEY IEC_BTN_0 = 0x100 IEC_BTN_1 = 0x101 IEC_BTN_2 = 0x102 IEC_BTN_3 = 0x103 IEC_BTN_4 = 0x104 IEC_BTN_5 = 0x105 IEC_BTN_6 = 0x106 IEC_BTN_7 = 0x107 IEC_BTN_8 = 0x108 IEC_BTN_9 = 0x109 IEC_BTN_10 = 0x10a IEC_BTN_11 = 0x10b IEC_BTN_12 = 0x10c IEC_BTN_13 = 0x10d IEC_BTN_14 = 0x10e IEC_BTN_15 = 0x10f # these are valid for IET_REL (Relative axes) IEC_REL_X = 0x00 IEC_REL_Y = 0x01 IEC_REL_Z = 0x02 IEC_REL_HWHEEL = 0x06 IEC_REL_DIAL = 0x07 # rotating the knob IEC_REL_WHEEL = 0x08 # moving the shuttle ring IEC_REL_MISC = 0x09 IEC_REL_MAX = 0x0f # ------------------------------------------------------------------------ class powermate(threading.Thread): """ Interface to Griffin PowerMate and Contour Shuttles """ def __init__(self, event_receiver=None, filename=None, **kwargs): self.event_receiver = event_receiver self.handle = -1 if not imported_ok: raise exceptions.RuntimeError, 'powermate not supported on this platform' if filename: if not self._open_device(filename): raise exceptions.RuntimeError, 'Unable to find powermate' else: ok = False for d in range(0, 16): if self._open_device("/dev/input/event%d" % d): ok = True break if not ok: raise exceptions.RuntimeError, 'Unable to find powermate' threading.Thread.__init__(self, **kwargs) self.setDaemon (1) self.keep_running = True self.start () def __del__(self): self.keep_running = False if self.handle >= 0: os.close(self.handle) self.handle = -1 def _open_device(self, filename): try: self.handle = os.open(filename, os.O_RDWR) if self.handle < 0: return False # read event device name name = fcntl.ioctl(self.handle, gru.hexint(0x80ff4506), chr(0) * 256) name = name.replace(chr(0), '') # do we see anything we recognize? if name == 'Griffin PowerMate' or name == 'Griffin SoundKnob': self.id = ID_POWERMATE self.mapper = _powermate_remapper() elif name == 'CAVS SpaceShuttle A/V' or name == 'Contour Design ShuttleXpress': self.id = ID_SHUTTLE_XPRESS self.mapper = _contour_remapper() elif name == 'Contour Design ShuttlePRO': self.id = ID_SHUTTLE_PRO self.mapper = _contour_remapper() elif name == 'Contour Design ShuttlePRO v2': self.id = ID_SHUTTLE_PRO_V2 self.mapper = _contour_remapper() else: os.close(self.handle) self.handle = -1 return False # get exclusive control of the device, using ioctl EVIOCGRAB # there may be an issue with this on non x86 platforms and if # the _IOW,_IOC,... macros in are changed fcntl.ioctl(self.handle,gru.hexint(0x40044590), 1) return True except exceptions.OSError: return False def set_event_receiver(self, obj): self.event_receiver = obj def set_led_state(self, static_brightness, pulse_speed=0, pulse_table=0, pulse_on_sleep=0, pulse_on_wake=0): """ What do these magic values mean... """ if self.id != ID_POWERMATE: return False static_brightness &= 0xff; if pulse_speed < 0: pulse_speed = 0 if pulse_speed > 510: pulse_speed = 510 if pulse_table < 0: pulse_table = 0 if pulse_table > 2: pulse_table = 2 pulse_on_sleep = not not pulse_on_sleep # not not = convert to 0/1 pulse_on_wake = not not pulse_on_wake magic = (static_brightness | (pulse_speed << 8) | (pulse_table << 17) | (pulse_on_sleep << 19) | (pulse_on_wake << 20)) data = struct.pack(input_event_struct, 0, 0, 0x04, 0x01, magic) os.write(self.handle, data) return True def run (self): while (self.keep_running): s = os.read (self.handle, input_event_size) if not s: self.keep_running = False break raw_input_event = struct.unpack(input_event_struct,s) sec, usec, type, code, val = self.mapper(raw_input_event) if self.event_receiver is None: continue if type == IET_SYN: # ignore pass elif type == IET_MSC: # ignore (seems to be PowerMate reporting led brightness) pass elif type == IET_REL and code == IEC_REL_DIAL: #print "Dial: %d" % (val,) wx.PostEvent(self.event_receiver, PMRotateEvent(val)) elif type == IET_REL and code == IEC_REL_WHEEL: #print "Shuttle: %d" % (val,) wx.PostEvent(self.event_receiver, PMShuttleEvent(val)) elif type == IET_KEY: #print "Key: Btn%d %d" % (code - IEC_BTN_0, val) wx.PostEvent(self.event_receiver, PMButtonEvent(code - IEC_BTN_0, val)) else: print "powermate: unrecognized event: type = 0x%x code = 0x%x val = %d" % (type, code, val) class _powermate_remapper(object): def __init__(self): pass def __call__(self, event): """ Notice how nice and simple this is... """ return event class _contour_remapper(object): def __init__(self): self.prev = None def __call__(self, event): """ ...and how screwed up this is """ sec, usec, type, code, val = event if type == IET_REL and code == IEC_REL_WHEEL: # === Shuttle ring === # First off, this really ought to be IET_ABS, not IET_REL! # They never generate a zero value so you can't # tell when the shuttle ring is back in the center. # We kludge around this by calling both -1 and 1 zero. if val == -1 or val == 1: return (sec, usec, type, code, 0) return event if type == IET_REL and code == IEC_REL_DIAL: # === Jog knob (rotary encoder) === # Dim wits got it wrong again! This one should return a # a relative value, e.g., -1, +1. Instead they return # a total that runs modulo 256 (almost!). For some # reason they count like this 253, 254, 255, 1, 2, 3 if self.prev is None: # first time call self.prev = val return (sec, usec, IET_SYN, 0, 0) # will be ignored above diff = val - self.prev if diff == 0: # sometimes it just sends stuff... return (sec, usec, IET_SYN, 0, 0) # will be ignored above if abs(diff) > 100: # crossed into the twilight zone if self.prev > val: # we've wrapped going forward self.prev = val return (sec, usec, type, code, +1) else: # we've wrapped going backward self.prev = val return (sec, usec, type, code, -1) self.prev = val return (sec, usec, type, code, diff) if type == IET_KEY: # remap keys so that all 3 gadgets have buttons 0 to 4 in common return (sec, usec, type, (IEC_BTN_5, IEC_BTN_6, IEC_BTN_7, IEC_BTN_8, IEC_BTN_0, IEC_BTN_1, IEC_BTN_2, IEC_BTN_3, IEC_BTN_4, IEC_BTN_9, IEC_BTN_10, IEC_BTN_11, IEC_BTN_12, IEC_BTN_13, IEC_BTN_14)[code - IEC_BTN_0], val) return event # ------------------------------------------------------------------------ # new wxPython event classes # ------------------------------------------------------------------------ grEVT_POWERMATE_BUTTON = wx.NewEventType() grEVT_POWERMATE_ROTATE = wx.NewEventType() grEVT_POWERMATE_SHUTTLE = wx.NewEventType() EVT_POWERMATE_BUTTON = wx.PyEventBinder(grEVT_POWERMATE_BUTTON, 0) EVT_POWERMATE_ROTATE = wx.PyEventBinder(grEVT_POWERMATE_ROTATE, 0) EVT_POWERMATE_SHUTTLE = wx.PyEventBinder(grEVT_POWERMATE_SHUTTLE, 0) class PMButtonEvent(wx.PyEvent): def __init__(self, button, value): wx.PyEvent.__init__(self) self.SetEventType(grEVT_POWERMATE_BUTTON) self.button = button self.value = value def Clone (self): self.__class__(self.GetId()) class PMRotateEvent(wx.PyEvent): def __init__(self, delta): wx.PyEvent.__init__(self) self.SetEventType (grEVT_POWERMATE_ROTATE) self.delta = delta def Clone (self): self.__class__(self.GetId()) class PMShuttleEvent(wx.PyEvent): def __init__(self, position): wx.PyEvent.__init__(self) self.SetEventType (grEVT_POWERMATE_SHUTTLE) self.position = position def Clone (self): self.__class__(self.GetId()) # ------------------------------------------------------------------------ # Example usage # ------------------------------------------------------------------------ if __name__ == '__main__': class Frame(wx.Frame): def __init__(self,parent=None,id=-1,title='Title', pos=wx.DefaultPosition, size=(400,200)): wx.Frame.__init__(self,parent,id,title,pos,size) EVT_POWERMATE_BUTTON(self, self.on_button) EVT_POWERMATE_ROTATE(self, self.on_rotate) EVT_POWERMATE_SHUTTLE(self, self.on_shuttle) self.brightness = 128 self.pulse_speed = 0 try: self.pm = powermate(self) except: sys.stderr.write("Unable to find PowerMate or Contour Shuttle\n") sys.exit(1) self.pm.set_led_state(self.brightness, self.pulse_speed) def on_button(self, evt): print "Button %d %s" % (evt.button, ("Released", "Pressed")[evt.value]) def on_rotate(self, evt): print "Rotated %d" % (evt.delta,) if 0: new = max(0, min(255, self.brightness + evt.delta)) if new != self.brightness: self.brightness = new self.pm.set_led_state(self.brightness, self.pulse_speed) def on_shuttle(self, evt): print "Shuttle %d" % (evt.position,) class App(wx.App): def OnInit(self): title='PowerMate Demo' self.frame = Frame(parent=None,id=-1,title=title) self.frame.Show() self.SetTopWindow(self.frame) return True app = App() app.MainLoop () gnuradio-3.7.2.1/gr-wxgui/python/wxgui/forms/0000775000175000017500000000000012207440367020714 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/python/wxgui/forms/forms.py0000664000175000017500000006274412207440367022431 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ The forms module contains general purpose wx-gui forms for gnuradio apps. The forms follow a layered model: * internal layer * deals with the wxgui objects directly * implemented in event handler and update methods * translation layer * translates the between the external and internal layers * handles parsing errors between layers * external layer * provided external access to the user * set_value, get_value, and optional callback * set and get through optional pubsub and key Known problems: * An empty label in the radio box still consumes space. * The static text cannot resize the parent at runtime. """ EXT_KEY = 'external' INT_KEY = 'internal' import wx import sys from gnuradio.gr.pubsub import pubsub import converters EVT_DATA = wx.PyEventBinder(wx.NewEventType()) class DataEvent(wx.PyEvent): def __init__(self, data): wx.PyEvent.__init__(self, wx.NewId(), EVT_DATA.typeId) self.data = data def make_bold(widget): font = widget.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) widget.SetFont(font) ######################################################################## # Base Class Form ######################################################################## class _form_base(pubsub, wx.BoxSizer): def __init__(self, parent=None, sizer=None, proportion=0, flag=wx.EXPAND, ps=None, key='', value=None, callback=None, converter=converters.identity_converter()): pubsub.__init__(self) wx.BoxSizer.__init__(self, wx.HORIZONTAL) self._parent = parent self._key = key self._converter = converter self._callback = callback self._widgets = list() #add to the sizer if provided if sizer: sizer.Add(self, proportion, flag) #proxy the pubsub and key into this form if ps is not None: assert key self.proxy(EXT_KEY, ps, key) #no pubsub passed, must set initial value else: self.set_value(value) def __str__(self): return "Form: %s -> %s"%(self.__class__, self._key) def _add_widget(self, widget, label='', flag=0, label_prop=0, widget_prop=1): """ Add the main widget to this object sizer. If label is passed, add a label as well. Register the widget and the label in the widgets list (for enable/disable). Bind the update handler to the widget for data events. This ensures that the gui thread handles updating widgets. Setup the pusub triggers for external and internal. Args: widget: the main widget label: the optional label flag: additional flags for widget label_prop: the proportion for the label widget_prop: the proportion for the widget """ #setup data event widget.Bind(EVT_DATA, lambda x: self._update(x.data)) update = lambda x: wx.PostEvent(widget, DataEvent(x)) #register widget self._widgets.append(widget) #create optional label if not label: self.Add(widget, widget_prop, wx.ALIGN_CENTER_VERTICAL | flag) else: label_text = wx.StaticText(self._parent, label='%s: '%label) self._widgets.append(label_text) self.Add(label_text, label_prop, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT) self.Add(widget, widget_prop, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | flag) #initialize without triggering pubsubs self._translate_external_to_internal(self[EXT_KEY]) update(self[INT_KEY]) #subscribe all the functions self.subscribe(INT_KEY, update) self.subscribe(INT_KEY, self._translate_internal_to_external) self.subscribe(EXT_KEY, self._translate_external_to_internal) def _translate_external_to_internal(self, external): try: internal = self._converter.external_to_internal(external) #prevent infinite loop between internal and external pubsub keys by only setting if changed if self[INT_KEY] != internal: self[INT_KEY] = internal except Exception, e: self._err_msg(external, e) self[INT_KEY] = self[INT_KEY] #reset to last good setting def _translate_internal_to_external(self, internal): try: external = self._converter.internal_to_external(internal) #prevent infinite loop between internal and external pubsub keys by only setting if changed if self[EXT_KEY] != external: self[EXT_KEY] = external except Exception, e: self._err_msg(internal, e) self[EXT_KEY] = self[EXT_KEY] #reset to last good setting if self._callback: self._callback(self[EXT_KEY]) def _err_msg(self, value, e): print >> sys.stderr, self, 'Error translating value: "%s"\n\t%s\n\t%s'%(value, e, self._converter.help()) #override in subclasses to handle the wxgui object def _update(self, value): raise NotImplementedError def _handle(self, event): raise NotImplementedError #provide a set/get interface for this form def get_value(self): return self[EXT_KEY] def set_value(self, value): self[EXT_KEY] = value def Disable(self, disable=True): self.Enable(not disable) def Enable(self, enable=True): if enable: for widget in self._widgets: widget.Enable() else: for widget in self._widgets: widget.Disable() ######################################################################## # Base Class Chooser Form ######################################################################## class _chooser_base(_form_base): def __init__(self, choices=[], labels=None, **kwargs): _form_base.__init__(self, converter=converters.chooser_converter(choices), **kwargs) self._choices = choices self._labels = map(str, labels or choices) ######################################################################## # Base Class Slider Form ######################################################################## class _slider_base(_form_base): def __init__(self, label='', length=-1, converter=None, num_steps=100, style=wx.SL_HORIZONTAL, **kwargs): _form_base.__init__(self, converter=converter, **kwargs) if style & wx.SL_HORIZONTAL: slider_size = wx.Size(length, -1) elif style & wx.SL_VERTICAL: slider_size = wx.Size(-1, length) else: raise NotImplementedError self._slider = wx.Slider(self._parent, minValue=0, maxValue=num_steps, size=slider_size, style=style) self._slider.Bind(wx.EVT_SCROLL, self._handle) self._add_widget(self._slider, label, flag=wx.EXPAND) def _handle(self, event): self[INT_KEY] = self._slider.GetValue() def _update(self, value): self._slider.SetValue(int(round(value))) ######################################################################## # Static Text Form ######################################################################## class static_text(_form_base): """ A text box form. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) label: title label for this widget (optional) width: the width of the form in px bold: true to bold-ify the text (default=False) units: a suffix to add after the text converter: forms.str_converter(), int_converter(), float_converter()... """ def __init__(self, label='', width=-1, bold=False, units='', converter=converters.str_converter(), **kwargs): self._units = units _form_base.__init__(self, converter=converter, **kwargs) self._static_text = wx.StaticText(self._parent, size=wx.Size(width, -1)) if bold: make_bold(self._static_text) self._add_widget(self._static_text, label) def _update(self, label): if self._units: label += ' ' + self._units self._static_text.SetLabel(label); self._parent.Layout() ######################################################################## # Text Box Form ######################################################################## class text_box(_form_base): """ A text box form. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) label: title label for this widget (optional) width: the width of the form in px converter: forms.str_converter(), int_converter(), float_converter()... """ def __init__(self, label='', width=-1, converter=converters.eval_converter(), **kwargs): _form_base.__init__(self, converter=converter, **kwargs) self._text_box = wx.TextCtrl(self._parent, size=wx.Size(width, -1), style=wx.TE_PROCESS_ENTER) self._default_bg_colour = self._text_box.GetBackgroundColour() self._text_box.Bind(wx.EVT_TEXT_ENTER, self._handle) self._text_box.Bind(wx.EVT_TEXT, self._update_color) self._add_widget(self._text_box, label) def _update_color(self, *args): if self._text_box.GetValue() == self[INT_KEY]: self._text_box.SetBackgroundColour(self._default_bg_colour) else: self._text_box.SetBackgroundColour('#EEDDDD') def _handle(self, event): self[INT_KEY] = self._text_box.GetValue() def _update(self, value): self._text_box.SetValue(value); self._update_color() ######################################################################## # Slider Form # Linear Slider # Logarithmic Slider ######################################################################## class slider(_slider_base): """ A generic linear slider. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) label: title label for this widget (optional) length: the length of the slider in px (optional) style: wx.SL_HORIZONTAL or wx.SL_VERTICAL (default=horizontal) minimum: the minimum value maximum: the maximum value num_steps: the number of slider steps (or specify step_size) step_size: the step between slider jumps (or specify num_steps) cast: a cast function, int, or float (default=float) """ def __init__(self, minimum=-100, maximum=100, num_steps=100, step_size=None, cast=float, **kwargs): assert step_size or num_steps if step_size is not None: num_steps = (maximum - minimum)/step_size converter = converters.slider_converter(minimum=minimum, maximum=maximum, num_steps=num_steps, cast=cast) _slider_base.__init__(self, converter=converter, num_steps=num_steps, **kwargs) class log_slider(_slider_base): """ A generic logarithmic slider. The sliders min and max values are base**min_exp and base**max_exp. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) label: title label for this widget (optional) length: the length of the slider in px (optional) style: wx.SL_HORIZONTAL or wx.SL_VERTICAL (default=horizontal) min_exp: the minimum exponent max_exp: the maximum exponent base: the exponent base in base**exp num_steps: the number of slider steps (or specify step_size) step_size: the exponent step size (or specify num_steps) """ def __init__(self, min_exp=0, max_exp=1, base=10, num_steps=100, step_size=None, **kwargs): assert step_size or num_steps if step_size is not None: num_steps = (max_exp - min_exp)/step_size converter = converters.log_slider_converter(min_exp=min_exp, max_exp=max_exp, num_steps=num_steps, base=base) _slider_base.__init__(self, converter=converter, num_steps=num_steps, **kwargs) ######################################################################## # Gauge Form ######################################################################## class gauge(_form_base): """ A gauge bar. The gauge displays floating point values between the minimum and maximum. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) label: title label for this widget (optional) length: the length of the slider in px (optional) style: wx.GA_HORIZONTAL or wx.GA_VERTICAL (default=horizontal) minimum: the minimum value maximum: the maximum value num_steps: the number of slider steps (or specify step_size) step_size: the step between slider jumps (or specify num_steps) """ def __init__(self, label='', length=-1, minimum=-100, maximum=100, num_steps=100, step_size=None, style=wx.GA_HORIZONTAL, **kwargs): assert step_size or num_steps if step_size is not None: num_steps = (maximum - minimum)/step_size converter = converters.slider_converter(minimum=minimum, maximum=maximum, num_steps=num_steps, cast=float) _form_base.__init__(self, converter=converter, **kwargs) if style & wx.SL_HORIZONTAL: gauge_size = wx.Size(length, -1) elif style & wx.SL_VERTICAL: gauge_size = wx.Size(-1, length) else: raise NotImplementedError self._gauge = wx.Gauge(self._parent, range=num_steps, size=gauge_size, style=style) self._add_widget(self._gauge, label, flag=wx.EXPAND) def _update(self, value): self._gauge.SetValue(value) ######################################################################## # Check Box Form ######################################################################## class check_box(_form_base): """ Create a check box form. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) true: the value for form when checked (default=True) false: the value for form when unchecked (default=False) label: title label for this widget (optional) """ def __init__(self, label='', true=True, false=False, **kwargs): _form_base.__init__(self, converter=converters.bool_converter(true=true, false=false), **kwargs) self._check_box = wx.CheckBox(self._parent, style=wx.CHK_2STATE, label=label) self._check_box.Bind(wx.EVT_CHECKBOX, self._handle) self._add_widget(self._check_box) def _handle(self, event): self[INT_KEY] = self._check_box.IsChecked() def _update(self, checked): self._check_box.SetValue(checked) ######################################################################## # Drop Down Chooser Form ######################################################################## class drop_down(_chooser_base): """ Create a drop down menu form. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) choices: list of possible values labels: list of labels for each choice (default=choices) label: title label for this widget (optional) width: the form width in px (optional) """ def __init__(self, label='', width=-1, **kwargs): _chooser_base.__init__(self, **kwargs) self._drop_down = wx.Choice(self._parent, choices=self._labels, size=wx.Size(width, -1)) self._drop_down.Bind(wx.EVT_CHOICE, self._handle) self._add_widget(self._drop_down, label, widget_prop=0, label_prop=1) def _handle(self, event): self[INT_KEY] = self._drop_down.GetSelection() def _update(self, i): self._drop_down.SetSelection(i) ######################################################################## # Button Chooser Form # Circularly move through the choices with each click. # Can be a single-click button with one choice. # Can be a 2-state button with two choices. ######################################################################## class button(_chooser_base): """ Create a multi-state button. parent the parent widget sizer add this widget to sizer if provided (optional) proportion the proportion when added to the sizer (default=0) flag the flag argument when added to the sizer (default=wx.EXPAND) ps the pubsub object (optional) key the pubsub key (optional) value the default value (optional) choices list of possible values labels list of labels for each choice (default=choices) width the width of the button in pixels (optional) style style arguments (optional) label title label for this widget (optional) """ def __init__(self, label='', style=0, width=-1, **kwargs): _chooser_base.__init__(self, **kwargs) self._button = wx.Button(self._parent, size=wx.Size(width, -1), style=style) self._button.Bind(wx.EVT_BUTTON, self._handle) self._add_widget(self._button, label, widget_prop=((not style&wx.BU_EXACTFIT) and 1 or 0)) def _handle(self, event): self[INT_KEY] = (self[INT_KEY] + 1)%len(self._choices) #circularly increment index def _update(self, i): self._button.SetLabel(self._labels[i]); self.Layout() class toggle_button(button): """ Create a dual-state button. This button will alternate between True and False when clicked. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) width: the width of the button in pixels (optional) style: style arguments (optional) true_label: the button's label in the true state false_label: the button's label in the false state """ def __init__(self, true_label='On (click to stop)', false_label='Off (click to start)', **kwargs): button.__init__(self, choices=[True, False], labels=[true_label, false_label], **kwargs) class single_button(toggle_button): """ Create a single state button. This button will callback() when clicked. For use when state holding is not important. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value: the default value (optional) width: the width of the button in pixels (optional) style: style arguments (optional) label: the button's label """ def __init__(self, label='click for callback', **kwargs): toggle_button.__init__(self, true_label=label, false_label=label, value=True, **kwargs) ######################################################################## # Radio Buttons Chooser Form ######################################################################## class radio_buttons(_chooser_base): """ Create a radio button form. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) ps: the pubsub object (optional) key: the pubsub key (optional) value the default value (optional) choices: list of possible values labels: list of labels for each choice (default=choices) major_dimension: the number of rows/cols (default=auto) label: title label for this widget (optional) style: useful style args: wx.RA_HORIZONTAL, wx.RA_VERTICAL, wx.NO_BORDER (default=wx.RA_HORIZONTAL) """ def __init__(self, style=wx.RA_HORIZONTAL, label='', major_dimension=0, **kwargs): _chooser_base.__init__(self, **kwargs) #create radio buttons self._radio_buttons = wx.RadioBox(self._parent, choices=self._labels, style=style, label=label, majorDimension=major_dimension) self._radio_buttons.Bind(wx.EVT_RADIOBOX, self._handle) self._add_widget(self._radio_buttons) def _handle(self, event): self[INT_KEY] = self._radio_buttons.GetSelection() def _update(self, i): self._radio_buttons.SetSelection(i) ######################################################################## # Notebook Chooser Form # The notebook pages/tabs are for selecting between choices. # A page must be added to the notebook for each choice. ######################################################################## class notebook(_chooser_base): def __init__(self, pages, notebook, **kwargs): _chooser_base.__init__(self, **kwargs) assert len(pages) == len(self._choices) self._notebook = notebook self._notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self._handle) #add pages, setting the label on each tab for i, page in enumerate(pages): self._notebook.AddPage(page, self._labels[i]) self._add_widget(self._notebook) def _handle(self, event): self[INT_KEY] = self._notebook.GetSelection() # SetSelection triggers a page change event (deprecated, breaks on Windows) and ChangeSelection does not def _update(self, i): self._notebook.ChangeSelection(i) # ---------------------------------------------------------------- # Stand-alone test application # ---------------------------------------------------------------- import wx from gnuradio.wxgui import gui class app_gui (object): def __init__(self, frame, panel, vbox, top_block, options, args): def callback(v): print v radio_buttons( sizer=vbox, parent=panel, choices=[2, 4, 8, 16], labels=['two', 'four', 'eight', 'sixteen'], value=4, style=wx.RA_HORIZONTAL, label='test radio long string', callback=callback, #major_dimension = 2, ) radio_buttons( sizer=vbox, parent=panel, choices=[2, 4, 8, 16], labels=['two', 'four', 'eight', 'sixteen'], value=4, style=wx.RA_VERTICAL, label='test radio long string', callback=callback, #major_dimension = 2, ) radio_buttons( sizer=vbox, parent=panel, choices=[2, 4, 8, 16], labels=['two', 'four', 'eight', 'sixteen'], value=4, style=wx.RA_VERTICAL | wx.NO_BORDER, callback=callback, #major_dimension = 2, ) button( sizer=vbox, parent=panel, choices=[2, 4, 8, 16], labels=['two', 'four', 'eight', 'sixteen'], value=2, label='button value', callback=callback, #width=100, ) drop_down( sizer=vbox, parent=panel, choices=[2, 4, 8, 16], value=2, label='Choose One', callback=callback, ) check_box( sizer=vbox, parent=panel, value=False, label='check me', callback=callback, ) text_box( sizer=vbox, parent=panel, value=3, label='text box', callback=callback, width=200, ) static_text( sizer=vbox, parent=panel, value='bob', label='static text', width=-1, bold=True, ) slider( sizer=vbox, parent=panel, value=12, label='slider', callback=callback, ) log_slider( sizer=vbox, parent=panel, value=12, label='slider', callback=callback, ) slider( sizer=vbox, parent=panel, value=12, label='slider', callback=callback, style=wx.SL_VERTICAL, length=30, ) toggle_button( sizer=vbox, parent=panel, value=True, label='toggle it', callback=callback, ) single_button( sizer=vbox, parent=panel, label='sig test', callback=callback, ) if __name__ == "__main__": try: # Create the GUI application app = gui.app( gui=app_gui, # User interface class title="Test Forms", # Top window title ) # And run it app.MainLoop() except RuntimeError, e: print e sys.exit(1) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/forms/__init__.py0000664000175000017500000000777612207440367023046 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ The following classes will be available through gnuradio.wxgui.forms: """ ######################################################################## # External Converters ######################################################################## from converters import \ eval_converter, str_converter, \ float_converter, int_converter ######################################################################## # External Forms ######################################################################## from forms import \ radio_buttons, drop_down, notebook, \ button, toggle_button, single_button, \ check_box, text_box, static_text, \ slider, log_slider, gauge, \ make_bold, DataEvent, EVT_DATA ######################################################################## # Helpful widgets ######################################################################## import wx class static_box_sizer(wx.StaticBoxSizer): """ A box sizer with label and border. Args: parent: the parent widget sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) label: title label for this widget (optional) bold: true to boldify the label orient: the sizer orientation wx.VERTICAL or wx.HORIZONTAL (default=wx.VERTICAL) """ def __init__(self, parent, label='', bold=False, sizer=None, orient=wx.VERTICAL, proportion=0, flag=wx.EXPAND): box = wx.StaticBox(parent=parent, label=label) if bold: make_bold(box) wx.StaticBoxSizer.__init__(self, box=box, orient=orient) if sizer: sizer.Add(self, proportion, flag) class incr_decr_buttons(wx.BoxSizer): """ A horizontal box sizer with a increment and a decrement button. Args: parent: the parent widget on_incr: the callback for pressing the + button on_decr: the callback for pressing the - button label: title label for this widget (optional) sizer: add this widget to sizer if provided (optional) proportion: the proportion when added to the sizer (default=0) flag: the flag argument when added to the sizer (default=wx.EXPAND) """ def __init__(self, parent, on_incr, on_decr, label='', sizer=None, proportion=0, flag=wx.EXPAND): wx.BoxSizer.__init__(self, wx.HORIZONTAL) buttons_box = wx.BoxSizer(wx.HORIZONTAL) self._incr_button = wx.Button(parent, label='+', style=wx.BU_EXACTFIT) self._incr_button.Bind(wx.EVT_BUTTON, on_incr) buttons_box.Add(self._incr_button, 0, wx.ALIGN_CENTER_VERTICAL) self._decr_button = wx.Button(parent, label=' - ', style=wx.BU_EXACTFIT) self._decr_button.Bind(wx.EVT_BUTTON, on_decr) buttons_box.Add(self._decr_button, 0, wx.ALIGN_CENTER_VERTICAL) if label: #add label self.Add(wx.StaticText(parent, label='%s: '%label), 1, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT) self.Add(buttons_box, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT) else: self.Add(buttons_box, 0, wx.ALIGN_CENTER_VERTICAL) if sizer: sizer.Add(self, proportion, flag) def Disable(self, disable=True): self.Enable(not disable) def Enable(self, enable=True): if enable: self._incr_button.Enable() self._decr_button.Enable() else: self._incr_button.Disable() self._decr_button.Disable() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/forms/converters.py0000664000175000017500000001210412207440367023456 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import eng_notation import math class abstract_converter(object): def external_to_internal(self, v): """ Convert from user specified value to value acceptable to underlying primitive. The underlying primitive usually expects strings. """ raise NotImplementedError def internal_to_external(self, s): """ Convert from underlying primitive value to user specified value. The underlying primitive usually expects strings. """ raise NotImplementedError def help(self): return "Any string is acceptable" class identity_converter(abstract_converter): def external_to_internal(self,v): return v def internal_to_external(self, s): return s ######################################################################## # Commonly used converters ######################################################################## class chooser_converter(abstract_converter): """ Convert between a set of possible choices and an index. Used in the chooser base and all sub-classes. """ def __init__(self, choices): #choices must be a list because tuple does not have .index() in python2.5 self._choices = list(choices) def external_to_internal(self, choice): return self._choices.index(choice) def internal_to_external(self, index): return self._choices[index] def help(self): return 'Enter a possible value in choices: "%s"'%str(self._choices) class bool_converter(abstract_converter): """ The internal representation is boolean. The external representation is specified. Used in the check box form. """ def __init__(self, true, false): self._true = true self._false = false def external_to_internal(self, v): if v == self._true: return True if v == self._false: return False raise Exception, 'Value "%s" is not a possible option.'%v def internal_to_external(self, v): if v: return self._true else: return self._false def help(self): return "Value must be in (%s, %s)."%(self._true, self._false) class eval_converter(abstract_converter): """ A catchall converter when int and float are not enough. Evaluate the internal representation with python's eval(). Possible uses, set a complex number, constellation points. Used in text box. """ def __init__(self, formatter=lambda x: '%s'%(x)): self._formatter = formatter def external_to_internal(self, v): return self._formatter(v) def internal_to_external(self, s): return eval(s) def help(self): return "Value must be evaluatable by python's eval." class str_converter(abstract_converter): def __init__(self, formatter=lambda x: '%s'%(x)): self._formatter = formatter def external_to_internal(self, v): return self._formatter(v) def internal_to_external(self, s): return str(s) class int_converter(abstract_converter): def __init__(self, formatter=lambda x: '%d'%round(x)): self._formatter = formatter def external_to_internal(self, v): return self._formatter(v) def internal_to_external(self, s): return int(s, 0) def help(self): return "Enter an integer. Leading 0x indicates hex" class float_converter(abstract_converter): def __init__(self, formatter=eng_notation.num_to_str): self._formatter = formatter def external_to_internal(self, v): return self._formatter(v) def internal_to_external(self, s): return eng_notation.str_to_num(s) def help(self): return "Enter a float with optional scale suffix. E.g., 100.1M" class slider_converter(abstract_converter): """ Scale values to and from the slider. """ def __init__(self, minimum, maximum, num_steps, cast): assert minimum < maximum assert num_steps > 0 self._offset = minimum self._scaler = float(maximum - minimum)/num_steps self._cast = cast def external_to_internal(self, v): return (v - self._offset)/self._scaler def internal_to_external(self, v): return self._cast(v*self._scaler + self._offset) def help(self): return "Value should be within slider range" class log_slider_converter(slider_converter): def __init__(self, min_exp, max_exp, num_steps, base): assert min_exp < max_exp assert num_steps > 0 self._base = base slider_converter.__init__(self, minimum=min_exp, maximum=max_exp, num_steps=num_steps, cast=float) def external_to_internal(self, v): return slider_converter.external_to_internal(self, math.log(v, self._base)) def internal_to_external(self, v): return self._base**slider_converter.internal_to_external(self, v) gnuradio-3.7.2.1/gr-wxgui/python/wxgui/form.py0000664000175000017500000003221712207440367021110 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from gnuradio import eng_notation # ---------------------------------------------------------------- # Wrappers for certain widgets # ---------------------------------------------------------------- def button_with_callback(parent, label, callback): new_id = wx.NewId() btn = wx.Button(parent, new_id, label) wx.EVT_BUTTON(parent, new_id, lambda evt: callback()) return btn # ---------------------------------------------------------------- # Format converters # ---------------------------------------------------------------- class abstract_converter(object): def value_to_prim(self, v): """ Convert from user specified value to value acceptable to underlying primitive. The underlying primitive usually expects strings. """ raise NotImplementedError def prim_to_value(self, s): """ Convert from underlying primitive value to user specified value. The underlying primitive usually expects strings. """ raise NotImplementedError def help(self): return "Any string is acceptable" class identity_converter(abstract_converter): def value_to_prim(self,v): return v def prim_to_value(self, s): return s class int_converter(abstract_converter): def value_to_prim(self, v): return str(v) def prim_to_value(self, s): return int(s, 0) def help(self): return "Enter an integer. Leading 0x indicates hex" class float_converter(abstract_converter): def value_to_prim(self, v): return eng_notation.num_to_str(v) def prim_to_value(self, s): return eng_notation.str_to_num(s) def help(self): return "Enter a float with optional scale suffix. E.g., 100.1M" # ---------------------------------------------------------------- # Various types of data entry fields # ---------------------------------------------------------------- class field(object): """ A field in a form. """ def __init__(self, converter, value): self.converter = converter if value is not None: self.set_value(value) def set_value(self, v): self._set_prim_value(self.converter.value_to_prim(v)) def get_value(self): return self.converter.prim_to_value(self._get_prim_value()) def get_value_with_check(self): """ Returns (value, error_msg), where error_msg is not None if there was problem """ try: return (self.get_value(), None) except: return (None, self._error_msg()) def _set_prim_value(self, v): raise NotImplementedError def _get_prim_value(self): raise NotImplementedError def _pair_with_label(self, widget, parent=None, sizer=None, label=None, weight=1): self.label = label if label is None: sizer.Add (widget, weight, wx.EXPAND) return widget elif 0: hbox = wx.BoxSizer(wx.HORIZONTAL) label_widget = wx.StaticText(parent, -1, label + ': ') hbox.Add(label_widget, 0, wx.EXPAND) hbox.Add(widget, 1, wx.EXPAND) sizer.Add(hbox, weight, wx.EXPAND) return widget else: label_widget = wx.StaticText(parent, -1, label + ': ') sizer.Add(label_widget, 0, wx.EXPAND) sizer.Add(widget, weight, wx.EXPAND) return widget def _error_msg(self): prefix = '' if self.label: prefix = self.label + ': ' return "%s%s is invalid. %s" % (prefix, self._get_prim_value(), self.converter.help()) # static (display-only) text fields class static_text_field(field): def __init__(self, parent=None, sizer=None, label=None, value=None, converter=identity_converter(), weight=0): self.f = self._pair_with_label(wx.StaticText(parent, -1, ""), parent=parent, sizer=sizer, label=label, weight=weight) field.__init__(self, converter, value) def _get_prim_value(self): return self.f.GetLabel() def _set_prim_value(self, v): self.f.SetLabel(v) class static_int_field(static_text_field): def __init__(self, parent=None, sizer=None, label=None, value=None, weight=0): static_text_field.__init__(self, parent, sizer, label, value, int_converter(), weight) class static_float_field(static_text_field): def __init__(self, parent=None, sizer=None, label=None, value=None, weight=0): static_text_field.__init__(self, parent, sizer, label, value, float_converter(), weight) # editable text fields class text_field(field): def __init__(self, parent=None, sizer=None, label=None, value=None, converter=identity_converter(), callback=None, weight=1): style = 0 if callback: style = wx.TE_PROCESS_ENTER new_id = wx.NewId() w = wx.TextCtrl(parent, new_id, "", style=style) self.f = self._pair_with_label(w, parent=parent, sizer=sizer, label=label, weight=weight) if callback: wx.EVT_TEXT_ENTER(w, new_id, lambda evt: callback()) field.__init__(self, converter, value) def _get_prim_value(self): return self.f.GetValue() def _set_prim_value(self, v): self.f.SetValue(v) class int_field(text_field): def __init__(self, parent=None, sizer=None, label=None, value=None, callback=None, weight=1): text_field.__init__(self, parent, sizer, label, value, int_converter(), callback, weight) class float_field(text_field): def __init__(self, parent=None, sizer=None, label=None, value=None, callback=None, weight=1): text_field.__init__(self, parent, sizer, label, value, float_converter(), callback, weight) # other fields class slider_field(field): def __init__(self, parent=None, sizer=None, label=None, value=None, converter=identity_converter(), callback=None, min=0, max=100, weight=1): new_id = wx.NewId() w = wx.Slider(parent, new_id, (max+min)/2, min, max, size=wx.Size(250, -1), style=wx.SL_HORIZONTAL | wx.SL_LABELS) self.f = self._pair_with_label(w, parent=parent, sizer=sizer, label=label, weight=weight) if callback: wx.EVT_COMMAND_SCROLL(w, new_id, lambda evt: callback(evt.GetInt())) field.__init__(self, converter, value) def _get_prim_value(self): return self.f.GetValue() def _set_prim_value(self, v): self.f.SetValue(int(v)) class quantized_slider_field(field): def __init__(self, parent=None, sizer=None, label=None, value=None, converter=identity_converter(), callback=None, range=None, weight=1): if not isinstance(range, (tuple, list)) or len(range) != 3: raise ValueError, range self.min = range[0] self.max = range[1] self.step_size = float(range[2]) nsteps = int((self.max-self.min)/self.step_size) new_id = wx.NewId() w = wx.Slider(parent, new_id, 0, 0, nsteps, size=wx.Size(250, -1), style=wx.SL_HORIZONTAL) self.f = self._pair_with_label(w, parent=parent, sizer=sizer, label=label, weight=weight) if callback: wx.EVT_COMMAND_SCROLL(w, new_id, lambda evt: callback(self._map_out(evt.GetInt()))) field.__init__(self, converter, value) def _get_prim_value(self): return self._map_out(self.f.GetValue()) def _set_prim_value(self, v): self.f.SetValue(self._map_in(v)) def _map_in(self, x): return int((x-self.min) / self.step_size) def _map_out(self, x): return x * self.step_size + self.min class checkbox_field(field): def __init__(self, parent=None, sizer=None, label=None, value=None, converter=identity_converter(), callback=None, weight=1): new_id = wx.NewId() w = wx.CheckBox(parent, new_id, label, style=wx.CHK_2STATE) self.f = self._pair_with_label(w, parent=parent, sizer=sizer, label=None, weight=weight) if callback: wx.EVT_CHECKBOX(w, new_id, lambda evt: callback(evt.GetInt())) field.__init__(self, converter, value) def _get_prim_value(self): return self.f.GetValue() def _set_prim_value(self, v): self.f.SetValue(int(v)) class radiobox_field(field): def __init__(self, parent=None, sizer=None, label=None, value=None, converter=identity_converter(), callback=None, weight=1, choices=None, major_dimension=1, specify_rows=False): new_id = wx.NewId() if specify_rows: style=wx.RA_SPECIFY_ROWS | wx.RA_HORIZONTAL else: style=wx.RA_SPECIFY_COLS | wx.RA_HORIZONTAL w = wx.RadioBox(parent, new_id, label=label, style=style, majorDimension=major_dimension, choices=choices) self.f = self._pair_with_label(w, parent=parent, sizer=sizer, label=None, weight=weight) if callback: wx.EVT_RADIOBOX(w, new_id, lambda evt: callback(evt.GetString())) field.__init__(self, converter, value) def _get_prim_value(self): return self.f.GetStringSelection() def _set_prim_value(self, v): self.f.SetStringSelection(str(v)) # ---------------------------------------------------------------- # the form class # ---------------------------------------------------------------- class form(dict): def __init__(self): dict.__init__(self) def check_input_for_errors(self): """ Returns list of error messages if there's trouble, else empty list. """ vals = [f.get_value_with_check() for f in self.values()] return [t[1] for t in vals if t[1] is not None] def get_key_vals(self): d = {} for (key, f) in self.items(): d[key] = f.get_value() return d def _nop(*args): pass def check_input_and_call(self, callback, status_handler=_nop): """ Return a function that checks the form for errors, and then if it's OK, invokes the user specified callback, passing it the form key/value dictionary. status_handler is called with a string indicating results. """ def doit_callback(*ignore): errors = self.check_input_for_errors() if errors: status_handler(errors[0]) #print '\n'.join(tuple(errors)) else: kv = self.get_key_vals() if callback(kv): status_handler("OK") else: status_handler("Failed") return doit_callback # ---------------------------------------------------------------- # Stand-alone example code # ---------------------------------------------------------------- import sys from gnuradio.wxgui import stdgui2 class demo_app_flow_graph (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) self.frame = frame self.panel = panel def _print_kv(kv): print "kv =", kv return True self.form = form() self.form['static1'] = \ static_text_field(parent=panel, sizer=vbox, label="Static Text", value="The Static Value") self.form['text1'] = \ text_field(parent=panel, sizer=vbox, label="TextCtrl", value="The Editable Value") self.form['int1'] = \ int_field(parent=panel, sizer=vbox, label="Int Field", value=1234) self.form['float1'] = \ float_field(parent=panel, sizer=vbox, label="Float Field", value=3.14159) self.doit = button_with_callback( panel, "Do It!", self.form.check_input_and_call(_print_kv, self._set_status_msg)) vbox.Add(self.doit, 0, wx.CENTER) def _set_status_msg(self, msg): self.frame.GetStatusBar().SetStatusText(msg, 0) def main (): app = stdgui2.stdapp(demo_app_flow_graph, "wxgui form demo", nstatus=1) app.MainLoop () if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-wxgui/python/wxgui/fftsink_gl.py0000664000175000017500000001457212207440367022277 0ustar jcorganjcorgan# # Copyright 2008-2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from __future__ import division ################################################## # Imports ################################################## import fft_window import common from gnuradio import gr, fft from gnuradio import analog from gnuradio import blocks from gnuradio.fft import logpwrfft from pubsub import pubsub from constants import * import math ################################################## # FFT sink block (wrapper for old wxgui) ################################################## class _fft_sink_base(gr.hier_block2, common.wxgui_hb): """ An fft block with real/complex inputs and a gui window. """ def __init__( self, parent, baseband_freq=0, ref_scale=2.0, y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512, fft_rate=fft_window.DEFAULT_FRAME_RATE, average=False, avg_alpha=None, title='', size=fft_window.DEFAULT_WIN_SIZE, peak_hold=False, win=None, use_persistence=False, persist_alpha=None, **kwargs #do not end with a comma ): #ensure avg alpha if avg_alpha is None: avg_alpha = 2.0/fft_rate #ensure analog alpha if persist_alpha is None: actual_fft_rate=float(sample_rate/fft_size)/float(max(1,int(float((sample_rate/fft_size)/fft_rate)))) #print "requested_fft_rate ",fft_rate #print "actual_fft_rate ",actual_fft_rate analog_cutoff_freq=0.5 # Hertz #calculate alpha from wanted cutoff freq persist_alpha = 1.0 - math.exp(-2.0*math.pi*analog_cutoff_freq/actual_fft_rate) #init gr.hier_block2.__init__( self, "fft_sink", gr.io_signature(1, 1, self._item_size), gr.io_signature(0, 0, 0), ) #blocks fft = self._fft_chain( sample_rate=sample_rate, fft_size=fft_size, frame_rate=fft_rate, ref_scale=ref_scale, avg_alpha=avg_alpha, average=average, win=win, ) msgq = gr.msg_queue(2) sink = blocks.message_sink(gr.sizeof_float*fft_size, msgq, True) #controller self.controller = pubsub() self.controller.subscribe(AVERAGE_KEY, fft.set_average) self.controller.publish(AVERAGE_KEY, fft.average) self.controller.subscribe(AVG_ALPHA_KEY, fft.set_avg_alpha) self.controller.publish(AVG_ALPHA_KEY, fft.avg_alpha) self.controller.subscribe(SAMPLE_RATE_KEY, fft.set_sample_rate) self.controller.publish(SAMPLE_RATE_KEY, fft.sample_rate) #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY) #create window self.win = fft_window.fft_window( parent=parent, controller=self.controller, size=size, title=title, real=self._real, fft_size=fft_size, baseband_freq=baseband_freq, sample_rate_key=SAMPLE_RATE_KEY, y_per_div=y_per_div, y_divs=y_divs, ref_level=ref_level, average_key=AVERAGE_KEY, avg_alpha_key=AVG_ALPHA_KEY, peak_hold=peak_hold, msg_key=MSG_KEY, use_persistence=use_persistence, persist_alpha=persist_alpha, ) common.register_access_methods(self, self.win) setattr(self.win, 'set_baseband_freq', getattr(self, 'set_baseband_freq')) #BACKWARDS setattr(self.win, 'set_peak_hold', getattr(self, 'set_peak_hold')) #BACKWARDS #connect self.wxgui_connect(self, fft, sink) def set_callback(self,callb): self.win.set_callback(callb) class fft_sink_f(_fft_sink_base): _fft_chain = logpwrfft.logpwrfft_f _item_size = gr.sizeof_float _real = True class fft_sink_c(_fft_sink_base): _fft_chain = logpwrfft.logpwrfft_c _item_size = gr.sizeof_gr_complex _real = False # ---------------------------------------------------------------- # Standalone test app # ---------------------------------------------------------------- import wx from gnuradio.wxgui import stdgui2 class test_app_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) fft_size = 256 # build our flow graph input_rate = 2048.0e3 #Generate some noise noise = analog.noise_source_c(analog.GR_UNIFORM, 1.0/10) # Generate a complex sinusoid #src1 = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 2e3, 1) src1 = analog.sig_source_c(input_rate, analog.GR_CONST_WAVE, 57.50e3, 1) # We add these throttle blocks so that this demo doesn't # suck down all the CPU available. Normally you wouldn't use these. thr1 = blocks.throttle(gr.sizeof_gr_complex, input_rate) sink1 = fft_sink_c(panel, title="Complex Data", fft_size=fft_size, sample_rate=input_rate, baseband_freq=100e3, ref_level=0, y_per_div=20, y_divs=10) vbox.Add(sink1.win, 1, wx.EXPAND) combine1 = blocks.add_cc() self.connect(src1, (combine1,0)) self.connect(noise,(combine1,1)) self.connect(combine1,thr1, sink1) #src2 = analog.sig_source_f(input_rate, analog.GR_SIN_WAVE, 2e3, 1) src2 = analog.sig_source_f (input_rate, analog.GR_CONST_WAVE, 57.50e3, 1) thr2 = blocks.throttle(gr.sizeof_float, input_rate) sink2 = fft_sink_f(panel, title="Real Data", fft_size=fft_size*2, sample_rate=input_rate, baseband_freq=100e3, ref_level=0, y_per_div=20, y_divs=10) vbox.Add(sink2.win, 1, wx.EXPAND) combine2 = blocks.add_ff() c2f2 = blocks.complex_to_float() self.connect(src2, (combine2,0)) self.connect(noise,c2f2,(combine2,1)) self.connect(combine2, thr2,sink2) def main (): app = stdgui2.stdapp(test_app_block, "FFT Sink Test App") app.MainLoop() if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/common.py0000664000175000017500000001773312207440367021443 0ustar jcorganjcorgan# # Copyright 2008, 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # conditional disconnections of wx flow graph ################################################## import wx from gnuradio import gr from gnuradio import blocks RUN_ALWAYS = gr.prefs().get_bool ('wxgui', 'run_always', False) class wxgui_hb(object): """ The wxgui hier block helper/wrapper class: A hier block should inherit from this class to make use of the wxgui connect method. To use, call wxgui_connect in place of regular connect; self.win must be defined. The implementation will conditionally enable the copy block after the source (self). This condition depends on weather or not the window is visible with the parent notebooks. This condition will be re-checked on every ui update event. """ def wxgui_connect(self, *points): """ Use wxgui connect when the first point is the self source of the hb. The win property of this object should be set to the wx window. When this method tries to connect self to the next point, it will conditionally make this connection based on the visibility state. All other points will be connected normally. """ try: assert points[0] == self or points[0][0] == self copy = blocks.copy(self._hb.input_signature().sizeof_stream_item(0)) handler = self._handler_factory(copy.set_enabled) if RUN_ALWAYS == False: handler(False) #initially disable the copy block else: handler(True) #initially enable the copy block self._bind_to_visible_event(win=self.win, handler=handler) points = list(points) points.insert(1, copy) #insert the copy block into the chain except (AssertionError, IndexError): pass self.connect(*points) #actually connect the blocks @staticmethod def _handler_factory(handler): """ Create a function that will cache the visibility flag, and only call the handler when that flag changes. Args: handler: the function to call on a change Returns: a function of 1 argument """ cache = [None] def callback(visible): if cache[0] == visible: return cache[0] = visible #print visible, handler if RUN_ALWAYS == False: handler(visible) else: handler(True) return callback @staticmethod def _bind_to_visible_event(win, handler): """ Bind a handler to a window when its visibility changes. Specifically, call the handler when the window visibility changes. This condition is checked on every update ui event. Args: win: the wx window handler: a function of 1 param """ #is the window visible in the hierarchy def is_wx_window_visible(my_win): while True: parent = my_win.GetParent() if not parent: return True #reached the top of the hierarchy #if we are hidden, then finish, otherwise keep traversing up if isinstance(parent, wx.Notebook) and parent.GetCurrentPage() != my_win: return False my_win = parent #call the handler, the arg is shown or not def handler_factory(my_win, my_handler): def callback(evt): my_handler(is_wx_window_visible(my_win)) evt.Skip() #skip so all bound handlers are called return callback handler = handler_factory(win, handler) #bind the handler to all the parent notebooks win.Bind(wx.EVT_UPDATE_UI, handler) ################################################## # Helpful Functions ################################################## #A macro to apply an index to a key index_key = lambda key, i: "%s_%d"%(key, i+1) def _register_access_method(destination, controller, key): """ Helper function for register access methods. This helper creates distinct set and get methods for each key and adds them to the destination object. """ def set(value): controller[key] = value setattr(destination, 'set_'+key, set) def get(): return controller[key] setattr(destination, 'get_'+key, get) def register_access_methods(destination, controller): """ Register setter and getter functions in the destination object for all keys in the controller. Args: destination: the object to get new setter and getter methods controller: the pubsub controller """ for key in controller.keys(): _register_access_method(destination, controller, key) ################################################## # Input Watcher Thread ################################################## from gnuradio import gru class input_watcher(gru.msgq_runner): """ Input watcher thread runs forever. Read messages from the message queue. Forward messages to the message handler. """ def __init__ (self, msgq, controller, msg_key, arg1_key='', arg2_key=''): self._controller = controller self._msg_key = msg_key self._arg1_key = arg1_key self._arg2_key = arg2_key gru.msgq_runner.__init__(self, msgq, self.handle_msg) def handle_msg(self, msg): if self._arg1_key: self._controller[self._arg1_key] = msg.arg1() if self._arg2_key: self._controller[self._arg2_key] = msg.arg2() self._controller[self._msg_key] = msg.to_string() ################################################## # Shared Functions ################################################## import numpy import math def get_exp(num): """ Get the exponent of the number in base 10. Args: num: the floating point number Returns: the exponent as an integer """ if num == 0: return 0 return int(math.floor(math.log10(abs(num)))) def get_clean_num(num): """ Get the closest clean number match to num with bases 1, 2, 5. Args: num: the number Returns: the closest number """ if num == 0: return 0 sign = num > 0 and 1 or -1 exp = get_exp(num) nums = numpy.array((1, 2, 5, 10))*(10**exp) return sign*nums[numpy.argmin(numpy.abs(nums - abs(num)))] def get_clean_incr(num): """ Get the next higher clean number with bases 1, 2, 5. Args: num: the number Returns: the next higher number """ num = get_clean_num(num) exp = get_exp(num) coeff = int(round(num/10**exp)) return { -5: -2, -2: -1, -1: -.5, 1: 2, 2: 5, 5: 10, }[coeff]*(10**exp) def get_clean_decr(num): """ Get the next lower clean number with bases 1, 2, 5. Args: num: the number Returns: the next lower number """ num = get_clean_num(num) exp = get_exp(num) coeff = int(round(num/10**exp)) return { -5: -10, -2: -5, -1: -2, 1: .5, 2: 1, 5: 2, }[coeff]*(10**exp) def get_min_max(samples): """ Get the minimum and maximum bounds for an array of samples. Args: samples: the array of real values Returns: a tuple of min, max """ factor = 2.0 mean = numpy.average(samples) std = numpy.std(samples) fft = numpy.abs(numpy.fft.fft(samples - mean)) envelope = 2*numpy.max(fft)/len(samples) ampl = max(std, envelope) or 0.1 return mean - factor*ampl, mean + factor*ampl def get_min_max_fft(fft_samps): """ Get the minimum and maximum bounds for an array of fft samples. Args: samples: the array of real values Returns: a tuple of min, max """ #get the peak level (max of the samples) peak_level = numpy.max(fft_samps) #separate noise samples noise_samps = numpy.sort(fft_samps)[:len(fft_samps)/2] #get the noise floor noise_floor = numpy.average(noise_samps) #get the noise deviation noise_dev = numpy.std(noise_samps) #determine the maximum and minimum levels max_level = peak_level min_level = noise_floor - abs(2*noise_dev) return min_level, max_level gnuradio-3.7.2.1/gr-wxgui/python/wxgui/histosink_gl.py0000664000175000017500000000662012207440367022641 0ustar jcorganjcorgan# # Copyright 2009,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import histo_window import common from gnuradio import gr from gnuradio import analog from gnuradio import blocks from gnuradio import wxgui from pubsub import pubsub from constants import * ################################################## # histo sink block (wrapper for old wxgui) ################################################## class histo_sink_f(gr.hier_block2, common.wxgui_hb): """ A histogram block and a gui window. """ def __init__( self, parent, size=histo_window.DEFAULT_WIN_SIZE, title='', num_bins=11, frame_size=1000, ): #init gr.hier_block2.__init__( self, "histo_sink", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(0, 0, 0), ) #blocks msgq = gr.msg_queue(2) histo = wxgui.histo_sink_f(msgq) histo.set_num_bins(num_bins) histo.set_frame_size(frame_size) #controller self.controller = pubsub() self.controller.subscribe(NUM_BINS_KEY, histo.set_num_bins) self.controller.publish(NUM_BINS_KEY, histo.get_num_bins) self.controller.subscribe(FRAME_SIZE_KEY, histo.set_frame_size) self.controller.publish(FRAME_SIZE_KEY, histo.get_frame_size) #start input watcher common.input_watcher(msgq, self.controller, MSG_KEY, arg1_key=MINIMUM_KEY, arg2_key=MAXIMUM_KEY) #create window self.win = histo_window.histo_window( parent=parent, controller=self.controller, size=size, title=title, maximum_key=MAXIMUM_KEY, minimum_key=MINIMUM_KEY, num_bins_key=NUM_BINS_KEY, frame_size_key=FRAME_SIZE_KEY, msg_key=MSG_KEY, ) common.register_access_methods(self, self.win) #connect self.wxgui_connect(self, histo) # ---------------------------------------------------------------- # Standalone test app # ---------------------------------------------------------------- import wx from gnuradio.wxgui import stdgui2 class test_app_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) # build our flow graph input_rate = 20.48e3 src2 = analog.sig_source_f(input_rate, analog.GR_SIN_WAVE, 2e3, 1) #src2 = analog.sig_source_f(input_rate, analog.GR_CONST_WAVE, 5.75e3, 1) thr2 = blocks.throttle(gr.sizeof_float, input_rate) sink2 = histo_sink_f(panel, title="Data", num_bins=31, frame_size=1000) vbox.Add(sink2.win, 1, wx.EXPAND) self.connect(src2, thr2, sink2) def main (): app = stdgui2.stdapp(test_app_block, "Histo Sink Test App") app.MainLoop() if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/scopesink_nongl.py0000664000175000017500000005436012207440367023343 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2003,2004,2006,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, eng_notation from gnuradio import analog from gnuradio import blocks from gnuradio import wxgui from gnuradio.wxgui import stdgui2 import wx import gnuradio.wxgui.plot as plot import numpy import struct default_scopesink_size = (640, 240) default_v_scale = 1000 default_frame_decim = gr.prefs().get_long('wxgui', 'frame_decim', 1) class scope_sink_f(gr.hier_block2): def __init__(self, parent, title='', sample_rate=1, size=default_scopesink_size, frame_decim=default_frame_decim, v_scale=default_v_scale, t_scale=None, num_inputs=1, **kwargs): gr.hier_block2.__init__(self, "scope_sink_f", gr.io_signature(num_inputs, num_inputs, gr.sizeof_float), gr.io_signature(0,0,0)) msgq = gr.msg_queue(2) # message queue that holds at most 2 messages self.guts = wxgui.oscope_sink_f(sample_rate, msgq) for i in range(num_inputs): self.connect((self, i), (self.guts, i)) self.win = scope_window(win_info(msgq, sample_rate, frame_decim, v_scale, t_scale, self.guts, title), parent) def set_sample_rate(self, sample_rate): self.guts.set_sample_rate(sample_rate) self.win.info.set_sample_rate(sample_rate) class scope_sink_c(gr.hier_block2): def __init__(self, parent, title='', sample_rate=1, size=default_scopesink_size, frame_decim=default_frame_decim, v_scale=default_v_scale, t_scale=None, num_inputs=1, xy_mode=False, **kwargs): gr.hier_block2.__init__(self, "scope_sink_c", gr.io_signature(num_inputs, num_inputs, gr.sizeof_gr_complex), gr.io_signature(0,0,0)) msgq = gr.msg_queue(2) # message queue that holds at most 2 messages self.guts = wxgui.oscope_sink_f(sample_rate, msgq) for i in range(num_inputs): c2f = blocks.complex_to_float() self.connect((self, i), c2f) self.connect((c2f, 0),(self.guts, 2*i+0)) self.connect((c2f, 1),(self.guts, 2*i+1)) self.win = scope_window(win_info(msgq, sample_rate, frame_decim, v_scale, t_scale, self.guts, title), parent) self.win.info.xy = xy_mode def set_sample_rate(self, sample_rate): self.guts.set_sample_rate(sample_rate) self.win.info.set_sample_rate(sample_rate) class constellation_sink(scope_sink_c): def __init__(self, parent, title='Constellation', sample_rate=1, size=default_scopesink_size, frame_decim=default_frame_decim): scope_sink_c.__init__(self, parent=parent, title=title, sample_rate=sample_rate, size=size, frame_decim=frame_decim) self.win.info.xy = True #constellation mode # ======================================================================== time_base_list = [ # time / division 1.0e-7, # 100ns / div 2.5e-7, 5.0e-7, 1.0e-6, # 1us / div 2.5e-6, 5.0e-6, 1.0e-5, # 10us / div 2.5e-5, 5.0e-5, 1.0e-4, # 100us / div 2.5e-4, 5.0e-4, 1.0e-3, # 1ms / div 2.5e-3, 5.0e-3, 1.0e-2, # 10ms / div 2.5e-2, 5.0e-2 ] v_scale_list = [ # counts / div, LARGER gains are SMALLER /div, appear EARLIER 2.0e-3, # 2m / div, don't call it V/div it's actually counts/div 5.0e-3, 1.0e-2, 2.0e-2, 5.0e-2, 1.0e-1, 2.0e-1, 5.0e-1, 1.0e+0, 2.0e+0, 5.0e+0, 1.0e+1, 2.0e+1, 5.0e+1, 1.0e+2, 2.0e+2, 5.0e+2, 1.0e+3, 2.0e+3, 5.0e+3, 1.0e+4 # 10000 /div, USRP full scale is -/+ 32767 ] wxDATA_EVENT = wx.NewEventType() def EVT_DATA_EVENT(win, func): win.Connect(-1, -1, wxDATA_EVENT, func) class DataEvent(wx.PyEvent): def __init__(self, data): wx.PyEvent.__init__(self) self.SetEventType(wxDATA_EVENT) self.data = data def Clone(self): self.__class__(self.GetId()) class win_info(object): __slots__ = ['msgq', 'sample_rate', 'frame_decim', 'v_scale', 'scopesink', 'title', 'time_scale_cursor', 'v_scale_cursor', 'marker', 'xy', 'autorange', 'running'] def __init__(self, msgq, sample_rate, frame_decim, v_scale, t_scale, scopesink, title = "Oscilloscope", xy=False): self.msgq = msgq self.sample_rate = sample_rate self.frame_decim = frame_decim self.scopesink = scopesink self.title = title; self.time_scale_cursor = gru.seq_with_cursor(time_base_list, initial_value = t_scale) self.v_scale_cursor = gru.seq_with_cursor(v_scale_list, initial_value = v_scale) self.marker = 'line' self.xy = xy self.autorange = not v_scale self.running = True def get_time_per_div(self): return self.time_scale_cursor.current() def get_volts_per_div(self): return self.v_scale_cursor.current() def set_sample_rate(self, sample_rate): self.sample_rate = sample_rate def get_sample_rate(self): return self.sample_rate def get_decimation_rate(self): return 1.0 def set_marker(self, s): self.marker = s def get_marker(self): return self.marker class input_watcher(gru.msgq_runner): def __init__(self, msgq, event_receiver, frame_decim, **kwds): self.event_receiver = event_receiver self.frame_decim = frame_decim self.iscan = 0 gru.msgq_runner.__init__(self, msgq, self.handle_msg) def handle_msg(self, msg): if self.iscan == 0: # only display at frame_decim self.iscan = self.frame_decim nchan = int(msg.arg1()) # number of channels of data in msg nsamples = int(msg.arg2()) # number of samples in each channel s = msg.to_string() # get the body of the msg as a string bytes_per_chan = nsamples * gr.sizeof_float records = [] for ch in range(nchan): start = ch * bytes_per_chan chan_data = s[start:start+bytes_per_chan] rec = numpy.fromstring(chan_data, numpy.float32) records.append(rec) # print "nrecords = %d, reclen = %d" % (len (records),nsamples) de = DataEvent(records) wx.PostEvent(self.event_receiver, de) records = [] del de self.iscan -= 1 class scope_window(wx.Panel): def __init__(self, info, parent, id = -1, pos = wx.DefaultPosition, size = wx.DefaultSize, name = ""): wx.Panel.__init__(self, parent, -1) self.info = info vbox = wx.BoxSizer(wx.VERTICAL) self.graph = graph_window(info, self, -1) vbox.Add(self.graph, 1, wx.EXPAND) vbox.Add(self.make_control_box(), 0, wx.EXPAND) vbox.Add(self.make_control2_box(), 0, wx.EXPAND) self.sizer = vbox self.SetSizer(self.sizer) self.SetAutoLayout(True) self.sizer.Fit(self) self.set_autorange(self.info.autorange) # second row of control buttons etc. appears BELOW control_box def make_control2_box(self): ctrlbox = wx.BoxSizer(wx.HORIZONTAL) self.inc_v_button = wx.Button(self, 1101, " < ", style=wx.BU_EXACTFIT) self.inc_v_button.SetToolTipString("Increase vertical range") wx.EVT_BUTTON(self, 1101, self.incr_v_scale) # ID matches button ID above self.dec_v_button = wx.Button(self, 1100, " > ", style=wx.BU_EXACTFIT) self.dec_v_button.SetToolTipString("Decrease vertical range") wx.EVT_BUTTON(self, 1100, self.decr_v_scale) self.v_scale_label = wx.StaticText(self, 1002, "None") # vertical /div self.update_v_scale_label() self.autorange_checkbox = wx.CheckBox(self, 1102, "Autorange") self.autorange_checkbox.SetToolTipString("Select autorange on/off") wx.EVT_CHECKBOX(self, 1102, self.autorange_checkbox_event) ctrlbox.Add((5,0) ,0) # left margin space ctrlbox.Add(self.inc_v_button, 0, wx.EXPAND) ctrlbox.Add(self.dec_v_button, 0, wx.EXPAND) ctrlbox.Add(self.v_scale_label, 0, wx.ALIGN_CENTER) ctrlbox.Add((20,0) ,0) # spacer ctrlbox.Add(self.autorange_checkbox, 0, wx.ALIGN_CENTER) return ctrlbox def make_control_box(self): ctrlbox = wx.BoxSizer(wx.HORIZONTAL) tb_left = wx.Button(self, 1001, " < ", style=wx.BU_EXACTFIT) tb_left.SetToolTipString("Increase time base") wx.EVT_BUTTON(self, 1001, self.incr_timebase) tb_right = wx.Button(self, 1000, " > ", style=wx.BU_EXACTFIT) tb_right.SetToolTipString("Decrease time base") wx.EVT_BUTTON(self, 1000, self.decr_timebase) self.time_base_label = wx.StaticText(self, 1002, "") self.update_timebase_label() ctrlbox.Add((5,0) ,0) # ctrlbox.Add(wx.StaticText(self, -1, "Horiz Scale: "), 0, wx.ALIGN_CENTER) ctrlbox.Add(tb_left, 0, wx.EXPAND) ctrlbox.Add(tb_right, 0, wx.EXPAND) ctrlbox.Add(self.time_base_label, 0, wx.ALIGN_CENTER) ctrlbox.Add((10,0) ,1) # stretchy space ctrlbox.Add(wx.StaticText(self, -1, "Trig: "), 0, wx.ALIGN_CENTER) self.trig_chan_choice = wx.Choice(self, 1004, choices = ['Ch1', 'Ch2', 'Ch3', 'Ch4']) self.trig_chan_choice.SetToolTipString("Select channel for trigger") wx.EVT_CHOICE(self, 1004, self.trig_chan_choice_event) ctrlbox.Add(self.trig_chan_choice, 0, wx.ALIGN_CENTER) self.trig_mode_choice = wx.Choice(self, 1005, choices = ['Free', 'Auto', 'Norm']) self.trig_mode_choice.SetSelection(1) self.trig_mode_choice.SetToolTipString("Select trigger slope or Auto (untriggered roll)") wx.EVT_CHOICE(self, 1005, self.trig_mode_choice_event) ctrlbox.Add(self.trig_mode_choice, 0, wx.ALIGN_CENTER) trig_level50 = wx.Button(self, 1006, "50%") trig_level50.SetToolTipString("Set trigger level to 50%") wx.EVT_BUTTON(self, 1006, self.set_trig_level50) ctrlbox.Add(trig_level50, 0, wx.EXPAND) run_stop = wx.Button(self, 1007, "Run/Stop") run_stop.SetToolTipString("Toggle Run/Stop mode") wx.EVT_BUTTON(self, 1007, self.run_stop) ctrlbox.Add(run_stop, 0, wx.EXPAND) ctrlbox.Add((10, 0) ,1) # stretchy space ctrlbox.Add(wx.StaticText(self, -1, "Fmt: "), 0, wx.ALIGN_CENTER) self.marker_choice = wx.Choice(self, 1002, choices = self._marker_choices) self.marker_choice.SetToolTipString("Select plotting with lines, pluses or dots") wx.EVT_CHOICE(self, 1002, self.marker_choice_event) ctrlbox.Add(self.marker_choice, 0, wx.ALIGN_CENTER) self.xy_choice = wx.Choice(self, 1003, choices = ['X:t', 'X:Y']) self.xy_choice.SetToolTipString("Select X vs time or X vs Y display") wx.EVT_CHOICE(self, 1003, self.xy_choice_event) ctrlbox.Add(self.xy_choice, 0, wx.ALIGN_CENTER) return ctrlbox _marker_choices = ['line', 'plus', 'dot'] def update_timebase_label(self): time_per_div = self.info.get_time_per_div() s = ' ' + eng_notation.num_to_str(time_per_div) + 's/div' self.time_base_label.SetLabel(s) def decr_timebase(self, evt): self.info.time_scale_cursor.prev() self.update_timebase_label() def incr_timebase(self, evt): self.info.time_scale_cursor.next() self.update_timebase_label() def update_v_scale_label(self): volts_per_div = self.info.get_volts_per_div() s = ' ' + eng_notation.num_to_str(volts_per_div) + '/div' # Not V/div self.v_scale_label.SetLabel(s) def decr_v_scale(self, evt): self.info.v_scale_cursor.prev() self.update_v_scale_label() def incr_v_scale(self, evt): self.info.v_scale_cursor.next() self.update_v_scale_label() def marker_choice_event(self, evt): s = evt.GetString() self.set_marker(s) def set_autorange(self, on): if on: self.v_scale_label.SetLabel(" (auto)") self.info.autorange = True self.autorange_checkbox.SetValue(True) self.inc_v_button.Enable(False) self.dec_v_button.Enable(False) else: if self.graph.y_range: (l,u) = self.graph.y_range # found by autorange self.info.v_scale_cursor.set_index_by_value((u-l)/8.0) self.update_v_scale_label() self.info.autorange = False self.autorange_checkbox.SetValue(False) self.inc_v_button.Enable(True) self.dec_v_button.Enable(True) def autorange_checkbox_event(self, evt): if evt.Checked(): self.set_autorange(True) else: self.set_autorange(False) def set_marker(self, s): self.info.set_marker(s) # set info for drawing routines i = self.marker_choice.FindString(s) assert i >= 0, "Hmmm, set_marker problem" self.marker_choice.SetSelection(i) def set_format_line(self): self.set_marker('line') def set_format_dot(self): self.set_marker('dot') def set_format_plus(self): self.set_marker('plus') def xy_choice_event(self, evt): s = evt.GetString() self.info.xy = s == 'X:Y' def trig_chan_choice_event(self, evt): s = evt.GetString() ch = int(s[-1]) - 1 self.info.scopesink.set_trigger_channel(ch) def trig_mode_choice_event(self, evt): sink = self.info.scopesink s = evt.GetString() if s == 'Norm': sink.set_trigger_mode(wxgui.TRIG_MODE_NORM) elif s == 'Auto': sink.set_trigger_mode(wxgui.TRIG_MODE_AUTO) elif s == 'Free': sink.set_trigger_mode(wxgui.TRIG_MODE_FREE) else: assert 0, "Bad trig_mode_choice string" def set_trig_level50(self, evt): self.info.scopesink.set_trigger_level_auto() def run_stop(self, evt): self.info.running = not self.info.running class graph_window(plot.PlotCanvas): channel_colors = ['BLUE', 'RED', 'CYAN', 'MAGENTA', 'GREEN', 'YELLOW'] def __init__(self, info, parent, id = -1, pos = wx.DefaultPosition, size = (640, 240), style = wx.DEFAULT_FRAME_STYLE, name = ""): plot.PlotCanvas.__init__(self, parent, id, pos, size, style, name) self.SetXUseScopeTicks(True) self.SetEnableGrid(True) self.SetEnableZoom(True) self.SetEnableLegend(True) # self.SetBackgroundColour('black') self.info = info; self.y_range = None self.x_range = None self.avg_y_min = None self.avg_y_max = None self.avg_x_min = None self.avg_x_max = None EVT_DATA_EVENT(self, self.format_data) self.input_watcher = input_watcher(info.msgq, self, info.frame_decim) def channel_color(self, ch): return self.channel_colors[ch % len(self.channel_colors)] def format_data(self, evt): if not self.info.running: return if self.info.xy: self.format_xy_data(evt) return info = self.info records = evt.data nchannels = len(records) npoints = len(records[0]) objects = [] Ts = 1.0 / (info.get_sample_rate() / info.get_decimation_rate()) x_vals = Ts * numpy.arange(-npoints/2, npoints/2) # preliminary clipping based on time axis here, instead of in graphics code time_per_window = self.info.get_time_per_div() * 10 n = int(time_per_window / Ts + 0.5) n = n & ~0x1 # make even n = max(2, min(n, npoints)) self.SetXUseScopeTicks(True) # use 10 divisions, no labels for ch in range(nchannels): r = records[ch] # plot middle n points of record lb = npoints/2 - n/2 ub = npoints/2 + n/2 # points = zip(x_vals[lb:ub], r[lb:ub]) points = numpy.zeros((ub-lb, 2), numpy.float64) points[:,0] = x_vals[lb:ub] points[:,1] = r[lb:ub] m = info.get_marker() if m == 'line': objects.append(plot.PolyLine(points, colour=self.channel_color(ch), legend=('Ch%d' % (ch+1,)))) else: objects.append(plot.PolyMarker(points, marker=m, colour=self.channel_color(ch), legend=('Ch%d' % (ch+1,)))) graphics = plot.PlotGraphics(objects, title=self.info.title, xLabel = '', yLabel = '') time_per_div = info.get_time_per_div() x_range = (-5.0 * time_per_div, 5.0 * time_per_div) # ranges are tuples! volts_per_div = info.get_volts_per_div() if not self.info.autorange: self.y_range = (-4.0 * volts_per_div, 4.0 * volts_per_div) self.Draw(graphics, xAxis=x_range, yAxis=self.y_range) self.update_y_range() # autorange to self.y_range def format_xy_data(self, evt): info = self.info records = evt.data nchannels = len(records) npoints = len(records[0]) if nchannels < 2: return objects = [] # points = zip(records[0], records[1]) points = numpy.zeros((len(records[0]), 2), numpy.float32) points[:,0] = records[0] points[:,1] = records[1] self.SetXUseScopeTicks(False) m = info.get_marker() if m == 'line': objects.append(plot.PolyLine(points, colour=self.channel_color(0))) else: objects.append(plot.PolyMarker(points, marker=m, colour=self.channel_color(0))) graphics = plot.PlotGraphics(objects, title=self.info.title, xLabel = 'I', yLabel = 'Q') self.Draw(graphics, xAxis=self.x_range, yAxis=self.y_range) self.update_y_range() self.update_x_range() def update_y_range(self): alpha = 1.0/25 graphics = self.last_draw[0] p1, p2 = graphics.boundingBox() # min, max points of graphics if self.avg_y_min: # prevent vertical scale from jumping abruptly --? self.avg_y_min = p1[1] * alpha + self.avg_y_min * (1 - alpha) self.avg_y_max = p2[1] * alpha + self.avg_y_max * (1 - alpha) else: # initial guess self.avg_y_min = p1[1] # -500.0 workaround, sometimes p1 is ~ 10^35 self.avg_y_max = p2[1] # 500.0 self.y_range = self._axisInterval('auto', self.avg_y_min, self.avg_y_max) # print "p1 %s p2 %s y_min %s y_max %s y_range %s" \ # % (p1, p2, self.avg_y_min, self.avg_y_max, self.y_range) def update_x_range(self): alpha = 1.0/25 graphics = self.last_draw[0] p1, p2 = graphics.boundingBox() # min, max points of graphics if self.avg_x_min: self.avg_x_min = p1[0] * alpha + self.avg_x_min * (1 - alpha) self.avg_x_max = p2[0] * alpha + self.avg_x_max * (1 - alpha) else: self.avg_x_min = p1[0] self.avg_x_max = p2[0] self.x_range = self._axisInterval('auto', self.avg_x_min, self.avg_x_max) # ---------------------------------------------------------------- # Stand-alone test application # ---------------------------------------------------------------- class test_top_block(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) if len(argv) > 1: frame_decim = int(argv[1]) else: frame_decim = 1 if len(argv) > 2: v_scale = float(argv[2]) # start up at this v_scale value else: v_scale = None # start up in autorange mode, default if len(argv) > 3: t_scale = float(argv[3]) # start up at this t_scale value else: t_scale = None # old behavior print "frame decim %s v_scale %s t_scale %s" % (frame_decim,v_scale,t_scale) input_rate = 1e6 # Generate a complex sinusoid self.src0 = analog.sig_source_c(input_rate, analog.GR_SIN_WAVE, 25.1e3, 1e3) # We add this throttle block so that this demo doesn't suck down # all the CPU available. You normally wouldn't use it... self.thr = blocks.throttle(gr.sizeof_gr_complex, input_rate) scope = scope_sink_c(panel,"Secret Data",sample_rate=input_rate, frame_decim=frame_decim, v_scale=v_scale, t_scale=t_scale) vbox.Add(scope.win, 1, wx.EXPAND) # Ultimately this will be # self.connect("src0 throttle scope") self.connect(self.src0, self.thr, scope) def main(): app = stdgui2.stdapp(test_top_block, "O'Scope Test App") app.MainLoop() if __name__ == '__main__': main() # ---------------------------------------------------------------- gnuradio-3.7.2.1/gr-wxgui/python/wxgui/stdgui2.py0000664000175000017500000000714212232637747021535 0ustar jcorganjcorgan# # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # '''A simple wx gui for GNU Radio applications''' import ctypes import os import wx import sys from gnuradio import gr class stdapp (wx.App): def __init__ (self, top_block_maker, title="GNU Radio", nstatus=2, max_noutput_items=None): self.top_block_maker = top_block_maker self.title = title self._nstatus = nstatus self._max_noutput_items = max_noutput_items # If we're on Linux, also enable multi-threading Xlib access if os.name == 'posix': try: x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: print "Warning: failed to XInitThreads()" # All our initialization must come before calling wx.App.__init__. # OnInit is called from somewhere in the guts of __init__. wx.App.__init__ (self, redirect=False) def OnInit (self): frame = stdframe (self.top_block_maker, self.title, self._nstatus, self._max_noutput_items) frame.Show (True) self.SetTopWindow (frame) return True class stdframe (wx.Frame): def __init__ (self, top_block_maker, title="GNU Radio", nstatus=2, max_nouts=None): # print "stdframe.__init__" wx.Frame.__init__(self, None, -1, title) self.CreateStatusBar (nstatus) mainmenu = wx.MenuBar () menu = wx.Menu () item = menu.Append (200, 'E&xit', 'Exit') self.Bind (wx.EVT_MENU, self.OnCloseWindow, item) mainmenu.Append (menu, "&File") self.SetMenuBar (mainmenu) self.Bind (wx.EVT_CLOSE, self.OnCloseWindow) self.panel = stdpanel (self, self, top_block_maker, max_nouts) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.panel, 1, wx.EXPAND) self.SetSizer(vbox) self.SetAutoLayout(True) vbox.Fit(self) def OnCloseWindow (self, event): self.top_block().stop() self.top_block().wait() self.Destroy () def top_block (self): return self.panel.top_block class stdpanel (wx.Panel): def __init__ (self, parent, frame, top_block_maker, max_nouts=None): # print "stdpanel.__init__" wx.Panel.__init__ (self, parent, -1) self.frame = frame vbox = wx.BoxSizer (wx.VERTICAL) self.top_block = top_block_maker (frame, self, vbox, sys.argv) self.SetSizer (vbox) self.SetAutoLayout (True) vbox.Fit (self) if(max_nouts is not None): self.top_block.start (max_nouts) else: self.top_block.start () class std_top_block (gr.top_block): def __init__ (self, parent, panel, vbox, argv): # Call the hier_block2 constructor # Top blocks have no inputs and outputs gr.top_block.__init__(self, "std_top_block") gnuradio-3.7.2.1/gr-wxgui/python/wxgui/scopesink2.py0000664000175000017500000000264712207440367022231 0ustar jcorganjcorgan# # Copyright 2008,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr p = gr.prefs() style = p.get_string('wxgui', 'style', 'auto') if style == 'auto' or style == 'gl': try: import wx.glcanvas from OpenGL.GL import * from scopesink_gl import scope_sink_f, scope_sink_c except ImportError: if style == 'gl': raise RuntimeError("Unable to import OpenGL. Are Python wrappers for OpenGL installed?") else: # Fall backto non-gl sinks from scopesink_nongl import scope_sink_f, scope_sink_c elif style == 'nongl': from scopesink_nongl import scope_sink_f, scope_sink_c else: raise RuntimeError("Unknown wxgui style") gnuradio-3.7.2.1/gr-wxgui/python/wxgui/number_window.py0000664000175000017500000001524112207440367023022 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import common import numpy import wx import pubsub from constants import * from gnuradio import gr #for gr.prefs import forms ################################################## # Constants ################################################## NEG_INF = float('-inf') SLIDER_STEPS = 100 AVG_ALPHA_MIN_EXP, AVG_ALPHA_MAX_EXP = -3, 0 DEFAULT_NUMBER_RATE = gr.prefs().get_long('wxgui', 'number_rate', 5) DEFAULT_WIN_SIZE = (300, 300) DEFAULT_GAUGE_RANGE = 1000 VALUE_REPR_KEY = 'value_repr' VALUE_REAL_KEY = 'value_real' VALUE_IMAG_KEY = 'value_imag' ################################################## # Number window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the averaging. """ def __init__(self, parent): """ Create a new control panel. Args: parent: the wx parent window """ self.parent = parent wx.Panel.__init__(self, parent) parent[SHOW_CONTROL_PANEL_KEY] = True parent.subscribe(SHOW_CONTROL_PANEL_KEY, self.Show) control_box = wx.BoxSizer(wx.VERTICAL) #checkboxes for average and peak hold control_box.AddStretchSpacer() options_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Options', bold=True, orient=wx.VERTICAL, ) forms.check_box( sizer=options_box, parent=self, label='Peak Hold', ps=parent, key=PEAK_HOLD_KEY, ) forms.check_box( sizer=options_box, parent=self, label='Average', ps=parent, key=AVERAGE_KEY, ) #static text and slider for averaging avg_alpha_text = forms.static_text( sizer=options_box, parent=self, label='Avg Alpha', converter=forms.float_converter(lambda x: '%.4f'%x), ps=parent, key=AVG_ALPHA_KEY, width=50, ) avg_alpha_slider = forms.log_slider( sizer=options_box, parent=self, min_exp=AVG_ALPHA_MIN_EXP, max_exp=AVG_ALPHA_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=AVG_ALPHA_KEY, ) for widget in (avg_alpha_text, avg_alpha_slider): parent.subscribe(AVERAGE_KEY, widget.Enable) widget.Enable(parent[AVERAGE_KEY]) #run/stop control_box.AddStretchSpacer() forms.toggle_button( sizer=control_box, parent=self, true_label='Stop', false_label='Run', ps=parent, key=RUNNING_KEY, ) #set sizer self.SetSizerAndFit(control_box) ################################################## # Numbersink window with label and gauges ################################################## class number_window(wx.Panel, pubsub.pubsub): def __init__( self, parent, controller, size, title, units, show_gauge, real, minval, maxval, decimal_places, average_key, avg_alpha_key, peak_hold, msg_key, sample_rate_key, ): pubsub.pubsub.__init__(self) wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER) #setup self.peak_val_real = NEG_INF self.peak_val_imag = NEG_INF self.real = real self.units = units self.decimal_places = decimal_places #proxy the keys self.proxy(MSG_KEY, controller, msg_key) self.proxy(AVERAGE_KEY, controller, average_key) self.proxy(AVG_ALPHA_KEY, controller, avg_alpha_key) self.proxy(SAMPLE_RATE_KEY, controller, sample_rate_key) #initialize values self[PEAK_HOLD_KEY] = peak_hold self[RUNNING_KEY] = True self[VALUE_REAL_KEY] = minval self[VALUE_IMAG_KEY] = minval #setup the box with display and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer(wx.HORIZONTAL) sizer = forms.static_box_sizer( parent=self, sizer=main_box, label=title, bold=True, orient=wx.VERTICAL, proportion=1, ) main_box.Add(self.control_panel, 0, wx.EXPAND) sizer.AddStretchSpacer() forms.static_text( parent=self, sizer=sizer, ps=self, key=VALUE_REPR_KEY, width=size[0], converter=forms.str_converter(), ) sizer.AddStretchSpacer() self.gauge_real = forms.gauge( parent=self, sizer=sizer, style=wx.GA_HORIZONTAL, ps=self, key=VALUE_REAL_KEY, length=size[0], minimum=minval, maximum=maxval, num_steps=DEFAULT_GAUGE_RANGE, ) self.gauge_imag = forms.gauge( parent=self, sizer=sizer, style=wx.GA_HORIZONTAL, ps=self, key=VALUE_IMAG_KEY, length=size[0], minimum=minval, maximum=maxval, num_steps=DEFAULT_GAUGE_RANGE, ) #hide/show gauges self.show_gauges(show_gauge) self.SetSizerAndFit(main_box) #register events self.subscribe(MSG_KEY, self.handle_msg) def show_gauges(self, show_gauge): """ Show or hide the gauges. If this is real, never show the imaginary gauge. Args: show_gauge: true to show """ self.gauge_real.ShowItems(show_gauge) self.gauge_imag.ShowItems(show_gauge and not self.real) def handle_msg(self, msg): """ Handle a message from the message queue. Convert the string based message into a float or complex. If more than one number was read, only take the last number. Perform peak hold operations, set the gauges and display. Args: event: event.data is the number sample as a character array """ if not self[RUNNING_KEY]: return format_string = "%%.%df"%self.decimal_places if self.real: sample = numpy.fromstring(msg, numpy.float32)[-1] if self[PEAK_HOLD_KEY]: sample = self.peak_val_real = max(self.peak_val_real, sample) label_text = "%s %s"%(format_string%sample, self.units) self[VALUE_REAL_KEY] = sample else: sample = numpy.fromstring(msg, numpy.complex64)[-1] if self[PEAK_HOLD_KEY]: self.peak_val_real = max(self.peak_val_real, sample.real) self.peak_val_imag = max(self.peak_val_imag, sample.imag) sample = self.peak_val_real + self.peak_val_imag*1j label_text = "%s + %sj %s"%(format_string%sample.real, format_string%sample.imag, self.units) self[VALUE_REAL_KEY] = sample.real self[VALUE_IMAG_KEY] = sample.imag #set label text self[VALUE_REPR_KEY] = label_text #clear peak hold if not self[PEAK_HOLD_KEY]: self.peak_val_real = NEG_INF self.peak_val_imag = NEG_INF gnuradio-3.7.2.1/gr-wxgui/python/wxgui/fftsink_nongl.py0000664000175000017500000006375512207440367023021 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2003-2007,2009,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, fft import gnuradio.filter as grfilter from gnuradio import blocks from gnuradio import analog from gnuradio.wxgui import stdgui2 from gnuradio.filter import window import wx import plot import numpy import math DIV_LEVELS = (1, 2, 5, 10, 20) default_fftsink_size = (640,240) default_fft_rate = gr.prefs().get_long('wxgui', 'fft_rate', 15) class fft_sink_base(object): def __init__(self, input_is_real=False, baseband_freq=0, y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='', peak_hold=False, use_persistence=False, persist_alpha=0.2): # initialize common attributes self.baseband_freq = baseband_freq self.y_per_div=y_per_div self.y_divs = y_divs self.ref_level = ref_level self.sample_rate = sample_rate self.fft_size = fft_size self.fft_rate = fft_rate self.average = average if avg_alpha is None: self.avg_alpha = 2.0 / fft_rate else: self.avg_alpha = avg_alpha self.use_persistence = use_persistence self.persist_alpha = persist_alpha self.title = title self.peak_hold = peak_hold self.input_is_real = input_is_real self.msgq = gr.msg_queue(2) # queue that holds a maximum of 2 messages def set_y_per_div(self, y_per_div): self.y_per_div = y_per_div def set_ref_level(self, ref_level): self.ref_level = ref_level def set_average(self, average): self.average = average if average: self.avg.set_taps(self.avg_alpha) else: self.avg.set_taps(1.0) self.win.peak_vals = None def set_peak_hold(self, enable): self.peak_hold = enable self.win.set_peak_hold(enable) def set_use_persistence(self, enable): self.use_persistence = enable self.win.set_use_persistence(enable) def set_persist_alpha(self, persist_alpha): self.persist_alpha = persist_alpha self.win.set_persist_alpha(persist_alpha) def set_avg_alpha(self, avg_alpha): self.avg_alpha = avg_alpha def set_baseband_freq(self, baseband_freq): self.baseband_freq = baseband_freq def set_sample_rate(self, sample_rate): self.sample_rate = sample_rate self._set_n() def _set_n(self): self.one_in_n.set_n(max(1, int(self.sample_rate/self.fft_size/self.fft_rate))) def set_callback(self, callb): return class fft_sink_f(gr.hier_block2, fft_sink_base): def __init__(self, parent, baseband_freq=0, ref_scale=2.0, y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='', size=default_fftsink_size, peak_hold=False, use_persistence=False, persist_alpha=0.2, **kwargs): gr.hier_block2.__init__(self, "fft_sink_f", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(0,0,0)) fft_sink_base.__init__(self, input_is_real=True, baseband_freq=baseband_freq, y_per_div=y_per_div, y_divs=y_divs, ref_level=ref_level, sample_rate=sample_rate, fft_size=fft_size, fft_rate=fft_rate, average=average, avg_alpha=avg_alpha, title=title, peak_hold=peak_hold, use_persistence=use_persistence, persist_alpha=persist_alpha) self.s2p = blocks.stream_to_vector(gr.sizeof_float, self.fft_size) self.one_in_n = blocks.keep_one_in_n(gr.sizeof_float * self.fft_size, max(1, int(self.sample_rate/self.fft_size/self.fft_rate))) mywindow = window.blackmanharris(self.fft_size) self.fft = fft.fft_vfc(self.fft_size, True, mywindow) power = 0 for tap in mywindow: power += tap*tap self.c2mag = blocks.complex_to_mag(self.fft_size) self.avg = grfilter.single_pole_iir_filter_ff(1.0, self.fft_size) # FIXME We need to add 3dB to all bins but the DC bin self.log = blocks.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size) # Adjust for number of bins -10*math.log10(power/self.fft_size) # Adjust for windowing loss -20*math.log10(ref_scale/2)) # Adjust for reference scale self.sink = blocks.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True) self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink) self.win = fft_window(self, parent, size=size) self.set_average(self.average) self.set_peak_hold(self.peak_hold) self.set_use_persistence(self.use_persistence) self.set_persist_alpha(self.persist_alpha) class fft_sink_c(gr.hier_block2, fft_sink_base): def __init__(self, parent, baseband_freq=0, ref_scale=2.0, y_per_div=10, y_divs=8, ref_level=50, sample_rate=1, fft_size=512, fft_rate=default_fft_rate, average=False, avg_alpha=None, title='', size=default_fftsink_size, peak_hold=False, use_persistence=False, persist_alpha=0.2, **kwargs): gr.hier_block2.__init__(self, "fft_sink_c", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0,0,0)) fft_sink_base.__init__(self, input_is_real=False, baseband_freq=baseband_freq, y_per_div=y_per_div, y_divs=y_divs, ref_level=ref_level, sample_rate=sample_rate, fft_size=fft_size, fft_rate=fft_rate, average=average, avg_alpha=avg_alpha, title=title, peak_hold=peak_hold, use_persistence=use_persistence, persist_alpha=persist_alpha) self.s2p = blocks.stream_to_vector(gr.sizeof_gr_complex, self.fft_size) self.one_in_n = blocks.keep_one_in_n(gr.sizeof_gr_complex * self.fft_size, max(1, int(self.sample_rate/self.fft_size/self.fft_rate))) mywindow = window.blackmanharris(self.fft_size) self.fft = fft.fft_vcc(self.fft_size, True, mywindow) power = 0 for tap in mywindow: power += tap*tap self.c2mag = blocks.complex_to_mag(self.fft_size) self.avg = grfilter.single_pole_iir_filter_ff(1.0, self.fft_size) # FIXME We need to add 3dB to all bins but the DC bin self.log = blocks.nlog10_ff(20, self.fft_size, -20*math.log10(self.fft_size) # Adjust for number of bins -10*math.log10(power/self.fft_size) # Adjust for windowing loss -20*math.log10(ref_scale/2)) # Adjust for reference scale self.sink = blocks.message_sink(gr.sizeof_float * self.fft_size, self.msgq, True) self.connect(self, self.s2p, self.one_in_n, self.fft, self.c2mag, self.avg, self.log, self.sink) self.win = fft_window(self, parent, size=size) self.set_average(self.average) self.set_use_persistence(self.use_persistence) self.set_persist_alpha(self.persist_alpha) self.set_peak_hold(self.peak_hold) # ------------------------------------------------------------------------ myDATA_EVENT = wx.NewEventType() EVT_DATA_EVENT = wx.PyEventBinder (myDATA_EVENT, 0) class DataEvent(wx.PyEvent): def __init__(self, data): wx.PyEvent.__init__(self) self.SetEventType (myDATA_EVENT) self.data = data def Clone (self): self.__class__ (self.GetId()) class input_watcher (gru.msgq_runner): def __init__ (self, msgq, fft_size, event_receiver, **kwds): self.fft_size = fft_size self.event_receiver = event_receiver gru.msgq_runner.__init__(self, msgq, self.handle_msg) def handle_msg(self, msg): itemsize = int(msg.arg1()) nitems = int(msg.arg2()) s = msg.to_string() # get the body of the msg as a string # There may be more than one FFT frame in the message. # If so, we take only the last one if nitems > 1: start = itemsize * (nitems - 1) s = s[start:start+itemsize] complex_data = numpy.fromstring (s, numpy.float32) de = DataEvent (complex_data) wx.PostEvent (self.event_receiver, de) del de class control_panel(wx.Panel): class LabelText(wx.StaticText): def __init__(self, window, label): wx.StaticText.__init__(self, window, -1, label) font = self.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) font.SetUnderlined(True) self.SetFont(font) def __init__(self, parent): self.parent = parent wx.Panel.__init__(self, parent, -1, style=wx.SIMPLE_BORDER) control_box = wx.BoxSizer(wx.VERTICAL) #checkboxes for average and peak hold control_box.AddStretchSpacer() control_box.Add(self.LabelText(self, 'Options'), 0, wx.ALIGN_CENTER) self.average_check_box = wx.CheckBox(parent=self, style=wx.CHK_2STATE, label="Average") self.average_check_box.Bind(wx.EVT_CHECKBOX, parent.on_average) control_box.Add(self.average_check_box, 0, wx.EXPAND) self.use_persistence_check_box = wx.CheckBox(parent=self, style=wx.CHK_2STATE, label="Persistence") self.use_persistence_check_box.Bind(wx.EVT_CHECKBOX, parent.on_use_persistence) control_box.Add(self.use_persistence_check_box, 0, wx.EXPAND) self.peak_hold_check_box = wx.CheckBox(parent=self, style=wx.CHK_2STATE, label="Peak Hold") self.peak_hold_check_box.Bind(wx.EVT_CHECKBOX, parent.on_peak_hold) control_box.Add(self.peak_hold_check_box, 0, wx.EXPAND) #radio buttons for div size control_box.AddStretchSpacer() control_box.Add(self.LabelText(self, 'Set dB/div'), 0, wx.ALIGN_CENTER) radio_box = wx.BoxSizer(wx.VERTICAL) self.radio_buttons = list() for y_per_div in DIV_LEVELS: radio_button = wx.RadioButton(self, -1, "%d dB/div"%y_per_div) radio_button.Bind(wx.EVT_RADIOBUTTON, self.on_radio_button_change) self.radio_buttons.append(radio_button) radio_box.Add(radio_button, 0, wx.ALIGN_LEFT) control_box.Add(radio_box, 0, wx.EXPAND) #ref lvl buttons control_box.AddStretchSpacer() control_box.Add(self.LabelText(self, 'Adj Ref Lvl'), 0, wx.ALIGN_CENTER) control_box.AddSpacer(2) button_box = wx.BoxSizer(wx.HORIZONTAL) self.ref_plus_button = wx.Button(self, -1, '+', style=wx.BU_EXACTFIT) self.ref_plus_button.Bind(wx.EVT_BUTTON, parent.on_incr_ref_level) button_box.Add(self.ref_plus_button, 0, wx.ALIGN_CENTER) self.ref_minus_button = wx.Button(self, -1, ' - ', style=wx.BU_EXACTFIT) self.ref_minus_button.Bind(wx.EVT_BUTTON, parent.on_decr_ref_level) button_box.Add(self.ref_minus_button, 0, wx.ALIGN_CENTER) control_box.Add(button_box, 0, wx.ALIGN_CENTER) control_box.AddStretchSpacer() #set sizer self.SetSizerAndFit(control_box) #update self.update() def update(self): """ Read the state of the fft plot settings and update the control panel. """ #update checkboxes self.average_check_box.SetValue(self.parent.fftsink.average) self.use_persistence_check_box.SetValue(self.parent.fftsink.use_persistence) self.peak_hold_check_box.SetValue(self.parent.fftsink.peak_hold) #update radio buttons try: index = list(DIV_LEVELS).index(self.parent.fftsink.y_per_div) self.radio_buttons[index].SetValue(True) except: pass def on_radio_button_change(self, evt): selected_radio_button = filter(lambda rb: rb.GetValue(), self.radio_buttons)[0] index = self.radio_buttons.index(selected_radio_button) self.parent.fftsink.set_y_per_div(DIV_LEVELS[index]) class fft_window (wx.Panel): def __init__ (self, fftsink, parent, id = -1, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, name = ""): self.fftsink = fftsink #init panel and plot wx.Panel.__init__(self, parent, -1) self.plot = plot.PlotCanvas(self, id, pos, size, style, name) #setup the box with plot and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer (wx.HORIZONTAL) main_box.Add (self.plot, 1, wx.EXPAND) main_box.Add (self.control_panel, 0, wx.EXPAND) self.SetSizerAndFit(main_box) self.peak_hold = False self.peak_vals = None self.use_persistence=False self.persist_alpha=0.2 self.plot.SetEnableGrid (True) # self.SetEnableZoom (True) # self.SetBackgroundColour ('black') self.build_popup_menu() self.set_baseband_freq(self.fftsink.baseband_freq) EVT_DATA_EVENT (self, self.set_data) wx.EVT_CLOSE (self, self.on_close_window) self.plot.Bind(wx.EVT_RIGHT_UP, self.on_right_click) self.plot.Bind(wx.EVT_MOTION, self.evt_motion) self.input_watcher = input_watcher(fftsink.msgq, fftsink.fft_size, self) def set_scale(self, freq): x = max(abs(self.fftsink.sample_rate), abs(self.fftsink.baseband_freq)) if x >= 1e9: self._scale_factor = 1e-9 self._units = "GHz" self._format = "%3.6f" elif x >= 1e6: self._scale_factor = 1e-6 self._units = "MHz" self._format = "%3.3f" else: self._scale_factor = 1e-3 self._units = "kHz" self._format = "%3.3f" def set_baseband_freq(self, baseband_freq): if self.peak_hold: self.peak_vals = None self.set_scale(baseband_freq) self.fftsink.set_baseband_freq(baseband_freq) def on_close_window (self, event): print "fft_window:on_close_window" self.keep_running = False def set_data (self, evt): dB = evt.data L = len (dB) if self.peak_hold: if self.peak_vals is None: self.peak_vals = dB else: self.peak_vals = numpy.maximum(dB, self.peak_vals) if self.fftsink.input_is_real: # only plot 1/2 the points x_vals = ((numpy.arange (L/2) * (self.fftsink.sample_rate * self._scale_factor / L)) + self.fftsink.baseband_freq * self._scale_factor) self._points = numpy.zeros((len(x_vals), 2), numpy.float64) self._points[:,0] = x_vals self._points[:,1] = dB[0:L/2] if self.peak_hold: self._peak_points = numpy.zeros((len(x_vals), 2), numpy.float64) self._peak_points[:,0] = x_vals self._peak_points[:,1] = self.peak_vals[0:L/2] else: # the "negative freqs" are in the second half of the array x_vals = ((numpy.arange (-L/2, L/2) * (self.fftsink.sample_rate * self._scale_factor / L)) + self.fftsink.baseband_freq * self._scale_factor) self._points = numpy.zeros((len(x_vals), 2), numpy.float64) self._points[:,0] = x_vals self._points[:,1] = numpy.concatenate ((dB[L/2:], dB[0:L/2])) if self.peak_hold: self._peak_points = numpy.zeros((len(x_vals), 2), numpy.float64) self._peak_points[:,0] = x_vals self._peak_points[:,1] = numpy.concatenate ((self.peak_vals[L/2:], self.peak_vals[0:L/2])) lines = [plot.PolyLine (self._points, colour='BLUE'),] if self.peak_hold: lines.append(plot.PolyLine (self._peak_points, colour='GREEN')) graphics = plot.PlotGraphics (lines, title=self.fftsink.title, xLabel = self._units, yLabel = "dB") x_range = x_vals[0], x_vals[-1] ymax = self.fftsink.ref_level ymin = self.fftsink.ref_level - self.fftsink.y_per_div * self.fftsink.y_divs y_range = ymin, ymax self.plot.Draw (graphics, xAxis=x_range, yAxis=y_range, step=self.fftsink.y_per_div) def set_use_persistence(self, enable): self.use_persistence = enable self.plot.set_use_persistence( enable) def set_persist_alpha(self, persist_alpha): self.persist_alpha = persist_alpha self.plot.set_persist_alpha(persist_alpha) def set_peak_hold(self, enable): self.peak_hold = enable self.peak_vals = None def on_average(self, evt): # print "on_average" self.fftsink.set_average(evt.IsChecked()) self.control_panel.update() def on_use_persistence(self, evt): # print "on_analog" self.fftsink.set_use_persistence(evt.IsChecked()) self.control_panel.update() def on_peak_hold(self, evt): # print "on_peak_hold" self.fftsink.set_peak_hold(evt.IsChecked()) self.control_panel.update() def on_incr_ref_level(self, evt): # print "on_incr_ref_level" self.fftsink.set_ref_level(self.fftsink.ref_level + self.fftsink.y_per_div) def on_decr_ref_level(self, evt): # print "on_decr_ref_level" self.fftsink.set_ref_level(self.fftsink.ref_level - self.fftsink.y_per_div) def on_incr_y_per_div(self, evt): # print "on_incr_y_per_div" self.fftsink.set_y_per_div(next_up(self.fftsink.y_per_div, DIV_LEVELS)) self.control_panel.update() def on_decr_y_per_div(self, evt): # print "on_decr_y_per_div" self.fftsink.set_y_per_div(next_down(self.fftsink.y_per_div, DIV_LEVELS)) self.control_panel.update() def on_y_per_div(self, evt): # print "on_y_per_div" Id = evt.GetId() if Id == self.id_y_per_div_1: self.fftsink.set_y_per_div(1) elif Id == self.id_y_per_div_2: self.fftsink.set_y_per_div(2) elif Id == self.id_y_per_div_5: self.fftsink.set_y_per_div(5) elif Id == self.id_y_per_div_10: self.fftsink.set_y_per_div(10) elif Id == self.id_y_per_div_20: self.fftsink.set_y_per_div(20) self.control_panel.update() def on_right_click(self, event): menu = self.popup_menu for id, pred in self.checkmarks.items(): item = menu.FindItemById(id) item.Check(pred()) self.plot.PopupMenu(menu, event.GetPosition()) def evt_motion(self, event): if not hasattr(self, "_points"): return # Got here before first window data update # Clip to plotted values (ux, uy) = self.plot.GetXY(event) # Scaled position x_vals = numpy.array(self._points[:,0]) if ux < x_vals[0] or ux > x_vals[-1]: tip = self.GetToolTip() if tip: tip.Enable(False) return # Get nearest X value (is there a better way)? ind = numpy.argmin(numpy.abs(x_vals-ux)) x_val = x_vals[ind] db_val = self._points[ind, 1] text = (self._format+" %s dB=%3.3f") % (x_val, self._units, db_val) # Display the tooltip tip = wx.ToolTip(text) tip.Enable(True) tip.SetDelay(0) self.SetToolTip(tip) def build_popup_menu(self): self.id_incr_ref_level = wx.NewId() self.id_decr_ref_level = wx.NewId() self.id_incr_y_per_div = wx.NewId() self.id_decr_y_per_div = wx.NewId() self.id_y_per_div_1 = wx.NewId() self.id_y_per_div_2 = wx.NewId() self.id_y_per_div_5 = wx.NewId() self.id_y_per_div_10 = wx.NewId() self.id_y_per_div_20 = wx.NewId() self.id_average = wx.NewId() self.id_use_persistence = wx.NewId() self.id_peak_hold = wx.NewId() self.plot.Bind(wx.EVT_MENU, self.on_average, id=self.id_average) self.plot.Bind(wx.EVT_MENU, self.on_use_persistence, id=self.id_use_persistence) self.plot.Bind(wx.EVT_MENU, self.on_peak_hold, id=self.id_peak_hold) self.plot.Bind(wx.EVT_MENU, self.on_incr_ref_level, id=self.id_incr_ref_level) self.plot.Bind(wx.EVT_MENU, self.on_decr_ref_level, id=self.id_decr_ref_level) self.plot.Bind(wx.EVT_MENU, self.on_incr_y_per_div, id=self.id_incr_y_per_div) self.plot.Bind(wx.EVT_MENU, self.on_decr_y_per_div, id=self.id_decr_y_per_div) self.plot.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_1) self.plot.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_2) self.plot.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_5) self.plot.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_10) self.plot.Bind(wx.EVT_MENU, self.on_y_per_div, id=self.id_y_per_div_20) # make a menu menu = wx.Menu() self.popup_menu = menu menu.AppendCheckItem(self.id_average, "Average") menu.AppendCheckItem(self.id_use_persistence, "Persistence") menu.AppendCheckItem(self.id_peak_hold, "Peak Hold") menu.Append(self.id_incr_ref_level, "Incr Ref Level") menu.Append(self.id_decr_ref_level, "Decr Ref Level") # menu.Append(self.id_incr_y_per_div, "Incr dB/div") # menu.Append(self.id_decr_y_per_div, "Decr dB/div") menu.AppendSeparator() # we'd use RadioItems for these, but they're not supported on Mac menu.AppendCheckItem(self.id_y_per_div_1, "1 dB/div") menu.AppendCheckItem(self.id_y_per_div_2, "2 dB/div") menu.AppendCheckItem(self.id_y_per_div_5, "5 dB/div") menu.AppendCheckItem(self.id_y_per_div_10, "10 dB/div") menu.AppendCheckItem(self.id_y_per_div_20, "20 dB/div") self.checkmarks = { self.id_average : lambda : self.fftsink.average, self.id_use_persistence : lambda : self.fftsink.use_persistence, self.id_peak_hold : lambda : self.fftsink.peak_hold, self.id_y_per_div_1 : lambda : self.fftsink.y_per_div == 1, self.id_y_per_div_2 : lambda : self.fftsink.y_per_div == 2, self.id_y_per_div_5 : lambda : self.fftsink.y_per_div == 5, self.id_y_per_div_10 : lambda : self.fftsink.y_per_div == 10, self.id_y_per_div_20 : lambda : self.fftsink.y_per_div == 20, } def next_up(v, seq): """ Return the first item in seq that is > v. """ for s in seq: if s > v: return s return v def next_down(v, seq): """ Return the last item in seq that is < v. """ rseq = list(seq[:]) rseq.reverse() for s in rseq: if s < v: return s return v # ---------------------------------------------------------------- # Standalone test app # ---------------------------------------------------------------- class test_app_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) fft_size = 256 # build our flow graph input_rate = 100*20.48e3 # Generate a complex sinusoid #src1 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 100*2e3, 1) src1 = gr.sig_source_c (input_rate, gr.GR_CONST_WAVE, 100*5.75e3, 1) noise1 = analog.noise_source_c(analog.GR_UNIFORM, 1.0/10) add1 = blocks.add_cc() # We add these throttle blocks so that this demo doesn't # suck down all the CPU available. Normally you wouldn't use these. thr1 = blocks.throttle(gr.sizeof_gr_complex, input_rate) sink1 = fft_sink_c(panel, title="Complex Data", fft_size=fft_size, sample_rate=input_rate, baseband_freq=100e3, ref_level=0, y_per_div=20, y_divs=10) vbox.Add(sink1.win, 1, wx.EXPAND) self.connect(src1, (add1,0)) self.connect(noise1, (add1,1)) self.connect(add1, thr1, sink1) #src2 = gr.sig_source_f (input_rate, gr.GR_SIN_WAVE, 100*2e3, 1) src2 = gr.sig_source_f (input_rate, gr.GR_CONST_WAVE, 100*5.75e3, 1) noise2 = analog.noise_source_f(analog.GR_UNIFORM, 1.0/10) add2 = blocks.add_ff() thr2 = gr.throttle(gr.sizeof_float, input_rate) sink2 = fft_sink_f (panel, title="Real Data", fft_size=fft_size*2, sample_rate=input_rate, baseband_freq=100e3, ref_level=0, y_per_div=20, y_divs=10) vbox.Add (sink2.win, 1, wx.EXPAND) self.connect(src2, (add2,0)) self.connect(noise2, (add2,1)) self.connect(add2, thr2, sink2) def main (): app = stdgui2.stdapp(test_app_block, "FFT Sink Test App") app.MainLoop() if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-wxgui/python/wxgui/__init__.py0000664000175000017500000000205012214652673021677 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Provides a GUI interface using the Wx backend. ''' try: from wxgui_swig import * except ImportError: import os dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from wxgui_swig import * gnuradio-3.7.2.1/gr-wxgui/python/wxgui/scope_window.py0000664000175000017500000006221112207440367022642 0ustar jcorganjcorgan# # Copyright 2008,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ################################################## # Imports ################################################## import plotter import common import wx import numpy import time import pubsub from constants import * from gnuradio import gr #for gr.prefs, trigger modes from gnuradio import wxgui import forms ################################################## # Constants ################################################## DEFAULT_FRAME_RATE = gr.prefs().get_long('wxgui', 'scope_rate', 30) PERSIST_ALPHA_MIN_EXP, PERSIST_ALPHA_MAX_EXP = -2, 0 SLIDER_STEPS = 100 DEFAULT_TRIG_MODE = gr.prefs().get_long('wxgui', 'trig_mode', wxgui.TRIG_MODE_AUTO) DEFAULT_WIN_SIZE = (600, 300) COUPLING_MODES = ( ('DC', False), ('AC', True), ) TRIGGER_MODES = ( ('Freerun', wxgui.TRIG_MODE_FREE), ('Auto', wxgui.TRIG_MODE_AUTO), ('Normal', wxgui.TRIG_MODE_NORM), ('Stripchart', wxgui.TRIG_MODE_STRIPCHART), ) TRIGGER_SLOPES = ( ('Pos +', wxgui.TRIG_SLOPE_POS), ('Neg -', wxgui.TRIG_SLOPE_NEG), ) CHANNEL_COLOR_SPECS = ( (0.3, 0.3, 1.0), (0.0, 0.8, 0.0), (1.0, 0.0, 0.0), (0.8, 0.0, 0.8), (0.7, 0.7, 0.0), (0.15, 0.90, 0.98), ) TRIGGER_COLOR_SPEC = (1.0, 0.4, 0.0) AUTORANGE_UPDATE_RATE = 0.5 #sec MARKER_TYPES = ( ('Line Link', None), ('Dot Large', 3.0), ('Dot Med', 2.0), ('Dot Small', 1.0), ('None', 0.0), ) DEFAULT_MARKER_TYPE = None ################################################## # Scope window control panel ################################################## class control_panel(wx.Panel): """ A control panel with wx widgits to control the plotter and scope block. """ def __init__(self, parent): """ Create a new control panel. Args: parent: the wx parent window """ WIDTH = 90 self.parent = parent wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER) parent[SHOW_CONTROL_PANEL_KEY] = True parent.subscribe(SHOW_CONTROL_PANEL_KEY, self.Show) control_box = wx.BoxSizer(wx.VERTICAL) ################################################## # Persistence ################################################## forms.check_box( sizer=control_box, parent=self, label='Persistence', ps=parent, key=USE_PERSISTENCE_KEY, ) #static text and slider for analog alpha persist_alpha_text = forms.static_text( sizer=control_box, parent=self, label='Analog Alpha', converter=forms.float_converter(lambda x: '%.4f'%x), ps=parent, key=PERSIST_ALPHA_KEY, width=50, ) persist_alpha_slider = forms.log_slider( sizer=control_box, parent=self, min_exp=PERSIST_ALPHA_MIN_EXP, max_exp=PERSIST_ALPHA_MAX_EXP, num_steps=SLIDER_STEPS, ps=parent, key=PERSIST_ALPHA_KEY, ) for widget in (persist_alpha_text, persist_alpha_slider): parent.subscribe(USE_PERSISTENCE_KEY, widget.Enable) widget.Enable(parent[USE_PERSISTENCE_KEY]) parent.subscribe(USE_PERSISTENCE_KEY, widget.ShowItems) #allways show initially, so room is reserved for them widget.ShowItems(True) # (parent[USE_PERSISTENCE_KEY]) parent.subscribe(USE_PERSISTENCE_KEY, self._update_layout) ################################################## # Axes Options ################################################## control_box.AddStretchSpacer() axes_options_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Axes Options', bold=True, orient=wx.VERTICAL, ) ################################################## # Scope Mode Box ################################################## scope_mode_box = wx.BoxSizer(wx.VERTICAL) axes_options_box.Add(scope_mode_box, 0, wx.EXPAND) #x axis divs forms.incr_decr_buttons( parent=self, sizer=scope_mode_box, label='Secs/Div', on_incr=self._on_incr_t_divs, on_decr=self._on_decr_t_divs, ) #y axis divs y_buttons_scope = forms.incr_decr_buttons( parent=self, sizer=scope_mode_box, label='Counts/Div', on_incr=self._on_incr_y_divs, on_decr=self._on_decr_y_divs, ) #y axis ref lvl y_off_buttons_scope = forms.incr_decr_buttons( parent=self, sizer=scope_mode_box, label='Y Offset', on_incr=self._on_incr_y_off, on_decr=self._on_decr_y_off, ) #t axis ref lvl scope_mode_box.AddSpacer(5) forms.slider( parent=self, sizer=scope_mode_box, ps=parent, key=T_FRAC_OFF_KEY, label='T Offset', minimum=0, maximum=1, num_steps=1000, ) scope_mode_box.AddSpacer(5) ################################################## # XY Mode Box ################################################## xy_mode_box = wx.BoxSizer(wx.VERTICAL) axes_options_box.Add(xy_mode_box, 0, wx.EXPAND) #x div controls x_buttons = forms.incr_decr_buttons( parent=self, sizer=xy_mode_box, label='X/Div', on_incr=self._on_incr_x_divs, on_decr=self._on_decr_x_divs, ) #y div controls y_buttons = forms.incr_decr_buttons( parent=self, sizer=xy_mode_box, label='Y/Div', on_incr=self._on_incr_y_divs, on_decr=self._on_decr_y_divs, ) #x offset controls x_off_buttons = forms.incr_decr_buttons( parent=self, sizer=xy_mode_box, label='X Off', on_incr=self._on_incr_x_off, on_decr=self._on_decr_x_off, ) #y offset controls y_off_buttons = forms.incr_decr_buttons( parent=self, sizer=xy_mode_box, label='Y Off', on_incr=self._on_incr_y_off, on_decr=self._on_decr_y_off, ) for widget in (y_buttons_scope, y_off_buttons_scope, x_buttons, y_buttons, x_off_buttons, y_off_buttons): parent.subscribe(AUTORANGE_KEY, widget.Disable) widget.Disable(parent[AUTORANGE_KEY]) xy_mode_box.ShowItems(False) #autorange check box forms.check_box( parent=self, sizer=axes_options_box, label='Autorange', ps=parent, key=AUTORANGE_KEY, ) ################################################## # Channel Options ################################################## TRIGGER_PAGE_INDEX = parent.num_inputs XY_PAGE_INDEX = parent.num_inputs+1 control_box.AddStretchSpacer() chan_options_box = forms.static_box_sizer( parent=self, sizer=control_box, label='Channel Options', bold=True, orient=wx.VERTICAL, ) options_notebook = wx.Notebook(self) options_notebook_args = list() CHANNELS = [('Ch %d'%(i+1), i) for i in range(parent.num_inputs)] ################################################## # Channel Menu Boxes ################################################## for i in range(parent.num_inputs): channel_menu_panel = wx.Panel(options_notebook) options_notebook_args.append((channel_menu_panel, i, 'Ch%d'%(i+1))) channel_menu_box = wx.BoxSizer(wx.VERTICAL) channel_menu_panel.SetSizer(channel_menu_box) #ac couple check box channel_menu_box.AddStretchSpacer() forms.drop_down( parent=channel_menu_panel, sizer=channel_menu_box, ps=parent, key=common.index_key(AC_COUPLE_KEY, i), choices=map(lambda x: x[1], COUPLING_MODES), labels=map(lambda x: x[0], COUPLING_MODES), label='Coupling', width=WIDTH, ) #marker channel_menu_box.AddStretchSpacer() forms.drop_down( parent=channel_menu_panel, sizer=channel_menu_box, ps=parent, key=common.index_key(MARKER_KEY, i), choices=map(lambda x: x[1], MARKER_TYPES), labels=map(lambda x: x[0], MARKER_TYPES), label='Marker', width=WIDTH, ) channel_menu_box.AddStretchSpacer() ################################################## # Trigger Menu Box ################################################## trigger_menu_panel = wx.Panel(options_notebook) options_notebook_args.append((trigger_menu_panel, TRIGGER_PAGE_INDEX, 'Trig')) trigger_menu_box = wx.BoxSizer(wx.VERTICAL) trigger_menu_panel.SetSizer(trigger_menu_box) #trigger mode forms.drop_down( parent=trigger_menu_panel, sizer=trigger_menu_box, ps=parent, key=TRIGGER_MODE_KEY, choices=map(lambda x: x[1], TRIGGER_MODES), labels=map(lambda x: x[0], TRIGGER_MODES), label='Mode', width=WIDTH, ) #trigger slope trigger_slope_chooser = forms.drop_down( parent=trigger_menu_panel, sizer=trigger_menu_box, ps=parent, key=TRIGGER_SLOPE_KEY, choices=map(lambda x: x[1], TRIGGER_SLOPES), labels=map(lambda x: x[0], TRIGGER_SLOPES), label='Slope', width=WIDTH, ) #trigger channel trigger_channel_chooser = forms.drop_down( parent=trigger_menu_panel, sizer=trigger_menu_box, ps=parent, key=TRIGGER_CHANNEL_KEY, choices=map(lambda x: x[1], CHANNELS), labels=map(lambda x: x[0], CHANNELS), label='Channel', width=WIDTH, ) #trigger level hbox = wx.BoxSizer(wx.HORIZONTAL) trigger_menu_box.Add(hbox, 0, wx.EXPAND) hbox.Add(wx.StaticText(trigger_menu_panel, label='Level:'), 1, wx.ALIGN_CENTER_VERTICAL) trigger_level_button = forms.single_button( parent=trigger_menu_panel, sizer=hbox, label='50%', callback=parent.set_auto_trigger_level, style=wx.BU_EXACTFIT, ) hbox.AddSpacer(WIDTH-60) trigger_level_buttons = forms.incr_decr_buttons( parent=trigger_menu_panel, sizer=hbox, on_incr=self._on_incr_trigger_level, on_decr=self._on_decr_trigger_level, ) def disable_all(trigger_mode): for widget in (trigger_slope_chooser, trigger_channel_chooser, trigger_level_buttons, trigger_level_button): widget.Disable(trigger_mode == wxgui.TRIG_MODE_FREE) parent.subscribe(TRIGGER_MODE_KEY, disable_all) disable_all(parent[TRIGGER_MODE_KEY]) ################################################## # XY Menu Box ################################################## if parent.num_inputs > 1: xy_menu_panel = wx.Panel(options_notebook) options_notebook_args.append((xy_menu_panel, XY_PAGE_INDEX, 'XY')) xy_menu_box = wx.BoxSizer(wx.VERTICAL) xy_menu_panel.SetSizer(xy_menu_box) #x and y channel choosers xy_menu_box.AddStretchSpacer() forms.drop_down( parent=xy_menu_panel, sizer=xy_menu_box, ps=parent, key=X_CHANNEL_KEY, choices=map(lambda x: x[1], CHANNELS), labels=map(lambda x: x[0], CHANNELS), label='Channel X', width=WIDTH, ) xy_menu_box.AddStretchSpacer() forms.drop_down( parent=xy_menu_panel, sizer=xy_menu_box, ps=parent, key=Y_CHANNEL_KEY, choices=map(lambda x: x[1], CHANNELS), labels=map(lambda x: x[0], CHANNELS), label='Channel Y', width=WIDTH, ) #marker xy_menu_box.AddStretchSpacer() forms.drop_down( parent=xy_menu_panel, sizer=xy_menu_box, ps=parent, key=XY_MARKER_KEY, choices=map(lambda x: x[1], MARKER_TYPES), labels=map(lambda x: x[0], MARKER_TYPES), label='Marker', width=WIDTH, ) xy_menu_box.AddStretchSpacer() ################################################## # Setup Options Notebook ################################################## forms.notebook( parent=self, sizer=chan_options_box, notebook=options_notebook, ps=parent, key=CHANNEL_OPTIONS_KEY, pages=map(lambda x: x[0], options_notebook_args), choices=map(lambda x: x[1], options_notebook_args), labels=map(lambda x: x[2], options_notebook_args), ) #gui handling for channel options changing def options_notebook_changed(chan_opt): try: parent[TRIGGER_SHOW_KEY] = chan_opt == TRIGGER_PAGE_INDEX parent[XY_MODE_KEY] = chan_opt == XY_PAGE_INDEX except wx.PyDeadObjectError: pass parent.subscribe(CHANNEL_OPTIONS_KEY, options_notebook_changed) #gui handling for xy mode changing def xy_mode_changed(mode): #ensure xy tab is selected if mode and parent[CHANNEL_OPTIONS_KEY] != XY_PAGE_INDEX: parent[CHANNEL_OPTIONS_KEY] = XY_PAGE_INDEX #ensure xy tab is not selected elif not mode and parent[CHANNEL_OPTIONS_KEY] == XY_PAGE_INDEX: parent[CHANNEL_OPTIONS_KEY] = 0 #show/hide control buttons scope_mode_box.ShowItems(not mode) xy_mode_box.ShowItems(mode) control_box.Layout() parent.subscribe(XY_MODE_KEY, xy_mode_changed) xy_mode_changed(parent[XY_MODE_KEY]) ################################################## # Run/Stop Button ################################################## #run/stop control_box.AddStretchSpacer() forms.toggle_button( sizer=control_box, parent=self, true_label='Stop', false_label='Run', ps=parent, key=RUNNING_KEY, ) #set sizer self.SetSizerAndFit(control_box) #mouse wheel event def on_mouse_wheel(event): if not parent[XY_MODE_KEY]: if event.GetWheelRotation() < 0: self._on_incr_t_divs(event) else: self._on_decr_t_divs(event) parent.plotter.Bind(wx.EVT_MOUSEWHEEL, on_mouse_wheel) ################################################## # Event handlers ################################################## #trigger level def _on_incr_trigger_level(self, event): self.parent[TRIGGER_LEVEL_KEY] += self.parent[Y_PER_DIV_KEY]/3. def _on_decr_trigger_level(self, event): self.parent[TRIGGER_LEVEL_KEY] -= self.parent[Y_PER_DIV_KEY]/3. #incr/decr divs def _on_incr_t_divs(self, event): self.parent[T_PER_DIV_KEY] = common.get_clean_incr(self.parent[T_PER_DIV_KEY]) def _on_decr_t_divs(self, event): self.parent[T_PER_DIV_KEY] = common.get_clean_decr(self.parent[T_PER_DIV_KEY]) def _on_incr_x_divs(self, event): self.parent[X_PER_DIV_KEY] = common.get_clean_incr(self.parent[X_PER_DIV_KEY]) def _on_decr_x_divs(self, event): self.parent[X_PER_DIV_KEY] = common.get_clean_decr(self.parent[X_PER_DIV_KEY]) def _on_incr_y_divs(self, event): self.parent[Y_PER_DIV_KEY] = common.get_clean_incr(self.parent[Y_PER_DIV_KEY]) def _on_decr_y_divs(self, event): self.parent[Y_PER_DIV_KEY] = common.get_clean_decr(self.parent[Y_PER_DIV_KEY]) #incr/decr offset def _on_incr_x_off(self, event): self.parent[X_OFF_KEY] = self.parent[X_OFF_KEY] + self.parent[X_PER_DIV_KEY] def _on_decr_x_off(self, event): self.parent[X_OFF_KEY] = self.parent[X_OFF_KEY] - self.parent[X_PER_DIV_KEY] def _on_incr_y_off(self, event): self.parent[Y_OFF_KEY] = self.parent[Y_OFF_KEY] + self.parent[Y_PER_DIV_KEY] def _on_decr_y_off(self, event): self.parent[Y_OFF_KEY] = self.parent[Y_OFF_KEY] - self.parent[Y_PER_DIV_KEY] ################################################## # subscriber handlers ################################################## def _update_layout(self,key): # Just ignore the key value we get # we only need to now that the visability or size of something has changed self.parent.Layout() #self.parent.Fit() ################################################## # Scope window with plotter and control panel ################################################## class scope_window(wx.Panel, pubsub.pubsub): def __init__( self, parent, controller, size, title, frame_rate, num_inputs, sample_rate_key, t_scale, v_scale, v_offset, xy_mode, ac_couple_key, trigger_level_key, trigger_mode_key, trigger_slope_key, trigger_channel_key, decimation_key, msg_key, use_persistence, persist_alpha, trig_mode, y_axis_label, ): pubsub.pubsub.__init__(self) #check num inputs assert num_inputs <= len(CHANNEL_COLOR_SPECS) #setup self.sampleses = None self.num_inputs = num_inputs autorange = not v_scale self.autorange_ts = 0 v_scale = v_scale or 1 self.frame_rate_ts = 0 #proxy the keys self.proxy(MSG_KEY, controller, msg_key) self.proxy(SAMPLE_RATE_KEY, controller, sample_rate_key) self.proxy(TRIGGER_LEVEL_KEY, controller, trigger_level_key) self.proxy(TRIGGER_MODE_KEY, controller, trigger_mode_key) self.proxy(TRIGGER_SLOPE_KEY, controller, trigger_slope_key) self.proxy(TRIGGER_CHANNEL_KEY, controller, trigger_channel_key) self.proxy(DECIMATION_KEY, controller, decimation_key) #initialize values self[RUNNING_KEY] = True self[XY_MARKER_KEY] = 2.0 self[CHANNEL_OPTIONS_KEY] = 0 self[XY_MODE_KEY] = xy_mode self[X_CHANNEL_KEY] = 0 self[Y_CHANNEL_KEY] = self.num_inputs-1 self[AUTORANGE_KEY] = autorange self[T_PER_DIV_KEY] = t_scale self[X_PER_DIV_KEY] = v_scale self[Y_PER_DIV_KEY] = v_scale self[T_OFF_KEY] = 0 self[X_OFF_KEY] = v_offset self[Y_OFF_KEY] = v_offset self[T_DIVS_KEY] = 8 self[X_DIVS_KEY] = 8 self[Y_DIVS_KEY] = 8 self[Y_AXIS_LABEL] = y_axis_label self[FRAME_RATE_KEY] = frame_rate self[TRIGGER_LEVEL_KEY] = 0 self[TRIGGER_CHANNEL_KEY] = 0 self[TRIGGER_MODE_KEY] = trig_mode self[TRIGGER_SLOPE_KEY] = wxgui.TRIG_SLOPE_POS self[T_FRAC_OFF_KEY] = 0.5 self[USE_PERSISTENCE_KEY] = use_persistence self[PERSIST_ALPHA_KEY] = persist_alpha if self[TRIGGER_MODE_KEY] == wxgui.TRIG_MODE_STRIPCHART: self[T_FRAC_OFF_KEY] = 0.0 for i in range(num_inputs): self.proxy(common.index_key(AC_COUPLE_KEY, i), controller, common.index_key(ac_couple_key, i)) #init panel and plot wx.Panel.__init__(self, parent, style=wx.SIMPLE_BORDER) self.plotter = plotter.channel_plotter(self) self.plotter.SetSize(wx.Size(*size)) self.plotter.SetSizeHints(*size) self.plotter.set_title(title) self.plotter.enable_legend(True) self.plotter.enable_point_label(True) self.plotter.enable_grid_lines(True) self.plotter.set_use_persistence(use_persistence) self.plotter.set_persist_alpha(persist_alpha) #setup the box with plot and controls self.control_panel = control_panel(self) main_box = wx.BoxSizer(wx.HORIZONTAL) main_box.Add(self.plotter, 1, wx.EXPAND) main_box.Add(self.control_panel, 0, wx.EXPAND) self.SetSizerAndFit(main_box) #register events for message self.subscribe(MSG_KEY, self.handle_msg) #register events for grid for key in [common.index_key(MARKER_KEY, i) for i in range(self.num_inputs)] + [ TRIGGER_LEVEL_KEY, TRIGGER_MODE_KEY, T_PER_DIV_KEY, X_PER_DIV_KEY, Y_PER_DIV_KEY, T_OFF_KEY, X_OFF_KEY, Y_OFF_KEY, T_DIVS_KEY, X_DIVS_KEY, Y_DIVS_KEY, XY_MODE_KEY, AUTORANGE_KEY, T_FRAC_OFF_KEY, TRIGGER_SHOW_KEY, XY_MARKER_KEY, X_CHANNEL_KEY, Y_CHANNEL_KEY, ]: self.subscribe(key, self.update_grid) #register events for plotter settings self.subscribe(USE_PERSISTENCE_KEY, self.plotter.set_use_persistence) self.subscribe(PERSIST_ALPHA_KEY, self.plotter.set_persist_alpha) #initial update self.update_grid() def handle_msg(self, msg): """ Handle the message from the scope sink message queue. Plot the list of arrays of samples onto the grid. Each samples array gets its own channel. Args: msg: the time domain data as a character array """ if not self[RUNNING_KEY]: return #check time elapsed if time.time() - self.frame_rate_ts < 1.0/self[FRAME_RATE_KEY]: return #convert to floating point numbers samples = numpy.fromstring(msg, numpy.float32) #extract the trigger offset self.trigger_offset = samples[-1] samples = samples[:-1] samps_per_ch = len(samples)/self.num_inputs self.sampleses = [samples[samps_per_ch*i:samps_per_ch*(i+1)] for i in range(self.num_inputs)] #handle samples self.handle_samples() self.frame_rate_ts = time.time() def set_auto_trigger_level(self, *args): """ Use the current trigger channel and samples to calculate the 50% level. """ if not self.sampleses: return samples = self.sampleses[self[TRIGGER_CHANNEL_KEY]] self[TRIGGER_LEVEL_KEY] = (numpy.max(samples)+numpy.min(samples))/2 def handle_samples(self): """ Handle the cached samples from the scope input. Perform ac coupling, triggering, and auto ranging. """ if not self.sampleses: return sampleses = self.sampleses if self[XY_MODE_KEY]: self[DECIMATION_KEY] = 1 x_samples = sampleses[self[X_CHANNEL_KEY]] y_samples = sampleses[self[Y_CHANNEL_KEY]] #autorange if self[AUTORANGE_KEY] and time.time() - self.autorange_ts > AUTORANGE_UPDATE_RATE: x_min, x_max = common.get_min_max(x_samples) y_min, y_max = common.get_min_max(y_samples) #adjust the x per div x_per_div = common.get_clean_num((x_max-x_min)/self[X_DIVS_KEY]) if x_per_div != self[X_PER_DIV_KEY]: self[X_PER_DIV_KEY] = x_per_div; return #adjust the x offset x_off = x_per_div*round((x_max+x_min)/2/x_per_div) if x_off != self[X_OFF_KEY]: self[X_OFF_KEY] = x_off; return #adjust the y per div y_per_div = common.get_clean_num((y_max-y_min)/self[Y_DIVS_KEY]) if y_per_div != self[Y_PER_DIV_KEY]: self[Y_PER_DIV_KEY] = y_per_div; return #adjust the y offset y_off = y_per_div*round((y_max+y_min)/2/y_per_div) if y_off != self[Y_OFF_KEY]: self[Y_OFF_KEY] = y_off; return self.autorange_ts = time.time() #plot xy channel self.plotter.set_waveform( channel='XY', samples=(x_samples, y_samples), color_spec=CHANNEL_COLOR_SPECS[0], marker=self[XY_MARKER_KEY], ) #turn off each waveform for i, samples in enumerate(sampleses): self.plotter.clear_waveform(channel='Ch%d'%(i+1)) else: #autorange if self[AUTORANGE_KEY] and time.time() - self.autorange_ts > AUTORANGE_UPDATE_RATE: bounds = [common.get_min_max(samples) for samples in sampleses] y_min = numpy.min([bound[0] for bound in bounds]) y_max = numpy.max([bound[1] for bound in bounds]) #adjust the y per div y_per_div = common.get_clean_num((y_max-y_min)/self[Y_DIVS_KEY]) if y_per_div != self[Y_PER_DIV_KEY]: self[Y_PER_DIV_KEY] = y_per_div; return #adjust the y offset y_off = y_per_div*round((y_max+y_min)/2/y_per_div) if y_off != self[Y_OFF_KEY]: self[Y_OFF_KEY] = y_off; return self.autorange_ts = time.time() #number of samples to scale to the screen actual_rate = self.get_actual_rate() time_span = self[T_PER_DIV_KEY]*self[T_DIVS_KEY] num_samps = int(round(time_span*actual_rate)) #handle the time offset t_off = self[T_FRAC_OFF_KEY]*(len(sampleses[0])/actual_rate - time_span) if t_off != self[T_OFF_KEY]: self[T_OFF_KEY] = t_off; return samps_off = int(round(actual_rate*self[T_OFF_KEY])) #adjust the decim so that we use about half the samps self[DECIMATION_KEY] = int(round( time_span*self[SAMPLE_RATE_KEY]/(0.5*len(sampleses[0])) ) ) #num samps too small, auto increment the time if num_samps < 2: self[T_PER_DIV_KEY] = common.get_clean_incr(self[T_PER_DIV_KEY]) #num samps in bounds, plot each waveform elif num_samps <= len(sampleses[0]): for i, samples in enumerate(sampleses): #plot samples self.plotter.set_waveform( channel='Ch%d'%(i+1), samples=samples[samps_off:num_samps+samps_off], color_spec=CHANNEL_COLOR_SPECS[i], marker=self[common.index_key(MARKER_KEY, i)], trig_off=self.trigger_offset, ) #turn XY channel off self.plotter.clear_waveform(channel='XY') #keep trigger level within range if self[TRIGGER_LEVEL_KEY] > self.get_y_max(): self[TRIGGER_LEVEL_KEY] = self.get_y_max(); return if self[TRIGGER_LEVEL_KEY] < self.get_y_min(): self[TRIGGER_LEVEL_KEY] = self.get_y_min(); return #disable the trigger channel if not self[TRIGGER_SHOW_KEY] or self[XY_MODE_KEY] or self[TRIGGER_MODE_KEY] == wxgui.TRIG_MODE_FREE: self.plotter.clear_waveform(channel='Trig') else: #show trigger channel trigger_level = self[TRIGGER_LEVEL_KEY] trigger_point = (len(self.sampleses[0])-1)/self.get_actual_rate()/2.0 self.plotter.set_waveform( channel='Trig', samples=( [self.get_t_min(), trigger_point, trigger_point, trigger_point, trigger_point, self.get_t_max()], [trigger_level, trigger_level, self.get_y_max(), self.get_y_min(), trigger_level, trigger_level] ), color_spec=TRIGGER_COLOR_SPEC, ) #update the plotter self.plotter.update() def get_actual_rate(self): return 1.0*self[SAMPLE_RATE_KEY]/self[DECIMATION_KEY] def get_t_min(self): return self[T_OFF_KEY] def get_t_max(self): return self[T_PER_DIV_KEY]*self[T_DIVS_KEY] + self[T_OFF_KEY] def get_x_min(self): return -1*self[X_PER_DIV_KEY]*self[X_DIVS_KEY]/2.0 + self[X_OFF_KEY] def get_x_max(self): return self[X_PER_DIV_KEY]*self[X_DIVS_KEY]/2.0 + self[X_OFF_KEY] def get_y_min(self): return -1*self[Y_PER_DIV_KEY]*self[Y_DIVS_KEY]/2.0 + self[Y_OFF_KEY] def get_y_max(self): return self[Y_PER_DIV_KEY]*self[Y_DIVS_KEY]/2.0 + self[Y_OFF_KEY] def update_grid(self, *args): """ Update the grid to reflect the current settings: xy divisions, xy offset, xy mode setting """ if self[T_FRAC_OFF_KEY] < 0: self[T_FRAC_OFF_KEY] = 0; return if self[T_FRAC_OFF_KEY] > 1: self[T_FRAC_OFF_KEY] = 1; return if self[XY_MODE_KEY]: #update the x axis self.plotter.set_x_label('Ch%d'%(self[X_CHANNEL_KEY]+1)) self.plotter.set_x_grid(self.get_x_min(), self.get_x_max(), self[X_PER_DIV_KEY]) #update the y axis self.plotter.set_y_label('Ch%d'%(self[Y_CHANNEL_KEY]+1)) self.plotter.set_y_grid(self.get_y_min(), self.get_y_max(), self[Y_PER_DIV_KEY]) else: #update the t axis self.plotter.set_x_label('Time', 's') self.plotter.set_x_grid(self.get_t_min(), self.get_t_max(), self[T_PER_DIV_KEY], True) #update the y axis self.plotter.set_y_label(self[Y_AXIS_LABEL]) self.plotter.set_y_grid(self.get_y_min(), self.get_y_max(), self[Y_PER_DIV_KEY]) #redraw current sample self.handle_samples() gnuradio-3.7.2.1/gr-wxgui/python/wxgui/waterfallsink2.py0000664000175000017500000000271312207440367023073 0ustar jcorganjcorgan# # Copyright 2008,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr p = gr.prefs() style = p.get_string('wxgui', 'style', 'auto') if style == 'auto' or style == 'gl': try: import wx.glcanvas from OpenGL.GL import * from waterfallsink_gl import waterfall_sink_f, waterfall_sink_c except ImportError: if style == 'gl': raise RuntimeError("Unable to import OpenGL. Are Python wrappers for OpenGL installed?") else: # Fall backto non-gl sinks from waterfallsink_nongl import waterfall_sink_f, waterfall_sink_c elif style == 'nongl': from waterfallsink_nongl import waterfall_sink_f, waterfall_sink_c else: raise RuntimeError("Unknown wxgui style") gnuradio-3.7.2.1/gr-wxgui/lib/0000775000175000017500000000000012207440367015650 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/lib/CMakeLists.txt0000664000175000017500000000447012207440367020415 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/../include ${GR_WXGUI_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND gr_wxgui_sources histo_sink_f_impl.cc oscope_guts.cc oscope_sink_x.cc oscope_sink_f_impl.cc ) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-wxgui.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-wxgui.rc @ONLY) list(APPEND gr_wxgui_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-wxgui.rc ) ENDIF(MSVC) list(APPEND wxgui_libs gnuradio-runtime volk ${Boost_LIBRARIES} ${BLOCKS_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_library(gnuradio-wxgui SHARED ${gr_wxgui_sources}) target_link_libraries(gnuradio-wxgui ${wxgui_libs}) GR_LIBRARY_FOO(gnuradio-wxgui RUNTIME_COMPONENT "wxgui_runtime" DEVEL_COMPONENT "wxgui_devel") gnuradio-3.7.2.1/gr-wxgui/lib/gnuradio-wxgui.rc.in0000664000175000017500000000332512207440367021557 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-blocks" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-blocks.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-blocks.dll" VALUE "ProductName", "gnuradio-blocks" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-wxgui/lib/histo_sink_f_impl.cc0000664000175000017500000001350012207440367021656 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "histo_sink_f_impl.h" #include #include namespace gr { namespace wxgui { static float get_clean_num(float num) { if(num == 0) return 0; /* extract sign and exponent from num */ int sign = (num < 0) ? -1 : 1; num = fabs(num); float exponent = floor(log10(num)); /* search for closest number with base 1, 2, 5, 10 */ float closest_num = 10*pow(10, exponent); if(fabs(num - 1*pow(10, exponent)) < fabs(num - closest_num)) closest_num = 1*pow(10, exponent); if(fabs(num - 2*pow(10, exponent)) < fabs(num - closest_num)) closest_num = 2*pow(10, exponent); if(fabs(num - 5*pow(10, exponent)) < fabs(num - closest_num)) closest_num = 5*pow(10, exponent); return sign*closest_num; } histo_sink_f::sptr histo_sink_f::make(msg_queue::sptr msgq) { return gnuradio::get_initial_sptr (new histo_sink_f_impl(msgq)); } histo_sink_f_impl::histo_sink_f_impl(msg_queue::sptr msgq) : sync_block("histo_sink_f", io_signature::make(1, 1, sizeof(float)), io_signature::make(0, 0, 0)), d_msgq(msgq), d_num_bins(11), d_frame_size(1000), d_sample_count(0), d_bins(NULL), d_samps(NULL) { //allocate arrays and clear set_num_bins(d_num_bins); set_frame_size(d_frame_size); } histo_sink_f_impl::~histo_sink_f_impl(void) { delete [] d_samps; delete [] d_bins; } int histo_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function for(unsigned int i = 0; i < (unsigned int)noutput_items; i++) { d_samps[d_sample_count] = in[i]; d_sample_count++; /* processed a frame? */ if(d_sample_count == d_frame_size) { send_frame(); clear(); } } return noutput_items; } void histo_sink_f_impl::send_frame(void) { /* output queue full, drop the data */ if(d_msgq->full_p()) return; /* find the minimum and maximum */ float minimum = d_samps[0]; float maximum = d_samps[0]; for(unsigned int i = 0; i < d_frame_size; i++) { if(d_samps[i] < minimum) minimum = d_samps[i]; if(d_samps[i] > maximum) maximum = d_samps[i]; } minimum = get_clean_num(minimum); maximum = get_clean_num(maximum); if(minimum == maximum || minimum > maximum) return; //useless data or screw up? /* load the bins */ int index; float bin_width = (maximum - minimum)/(d_num_bins-1); for(unsigned int i = 0; i < d_sample_count; i++) { index = boost::math::iround((d_samps[i] - minimum)/bin_width); /* ensure the index range in case a small floating point error is involed */ if(index < 0) index = 0; if(index >= (int)d_num_bins) index = d_num_bins-1; d_bins[index]++; } /* Build a message to hold the output records */ message::sptr msg = message::make(0, minimum, maximum, d_num_bins*sizeof(float)); float *out = (float *)msg->msg(); // get pointer to raw message buffer /* normalize the bins and put into message */ for(unsigned int i = 0; i < d_num_bins; i++) { out[i] = ((float)d_bins[i])/d_frame_size; } /* send the message */ d_msgq->handle(msg); } void histo_sink_f_impl::clear(void) { d_sample_count = 0; /* zero the bins */ for(unsigned int i = 0; i < d_num_bins; i++) { d_bins[i] = 0; } } /************************************************** * Getters **************************************************/ unsigned int histo_sink_f_impl::get_frame_size(void) { return d_frame_size; } unsigned int histo_sink_f_impl::get_num_bins(void) { return d_num_bins; } /************************************************** * Setters **************************************************/ void histo_sink_f_impl::set_frame_size(unsigned int frame_size) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function d_frame_size = frame_size; /* allocate a new sample array */ delete [] d_samps; d_samps = new float[d_frame_size]; clear(); } void histo_sink_f_impl::set_num_bins(unsigned int num_bins) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function d_num_bins = num_bins; /* allocate a new bin array */ delete [] d_bins; d_bins = new unsigned int[d_num_bins]; clear(); } } /* namespace wxgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-wxgui/lib/oscope_sink_f_impl.h0000664000175000017500000000274212207440367021670 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003-2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_OSCOPE_SINK_F_IMPL_H #define INCLUDED_GR_OSCOPE_SINK_F_IMPL_H #include namespace gr { namespace wxgui { class oscope_sink_f_impl : public oscope_sink_f { private: msg_queue::sptr d_msgq; public: oscope_sink_f_impl(double sampling_rate, msg_queue::sptr msgq); ~oscope_sink_f_impl(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_OSCOPE_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-wxgui/lib/oscope_sink_x.cc0000664000175000017500000000721212207440367021024 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace wxgui { oscope_sink_x::oscope_sink_x(const std::string name, gr::io_signature::sptr input_sig, double sampling_rate) : sync_block(name, input_sig, io_signature::make(0, 0, 0)), d_sampling_rate(sampling_rate), d_guts(0) { } oscope_sink_x::~oscope_sink_x() { delete d_guts; } // ---------------------------------------------------------------- bool oscope_sink_x::set_update_rate(double update_rate) { return d_guts->set_update_rate(update_rate); } bool oscope_sink_x::set_decimation_count(int decimation_count) { return d_guts->set_decimation_count(decimation_count); } bool oscope_sink_x::set_trigger_channel(int channel) { return d_guts->set_trigger_channel(channel); } bool oscope_sink_x::set_trigger_mode(trigger_mode mode) { return d_guts->set_trigger_mode(mode); } bool oscope_sink_x::set_trigger_slope(trigger_slope slope) { return d_guts->set_trigger_slope(slope); } bool oscope_sink_x::set_trigger_level(double trigger_level) { return d_guts->set_trigger_level(trigger_level); } bool oscope_sink_x::set_trigger_level_auto() { return d_guts->set_trigger_level_auto(); } bool oscope_sink_x::set_sample_rate(double sample_rate) { return d_guts->set_sample_rate(sample_rate); } bool oscope_sink_x::set_num_channels(int nchannels) { return d_guts->set_num_channels(nchannels); } // ACCESSORS int oscope_sink_x::num_channels() const { return d_guts->num_channels(); } double oscope_sink_x::sample_rate() const { return d_guts->sample_rate(); } double oscope_sink_x::update_rate() const { return d_guts->update_rate(); } int oscope_sink_x::get_decimation_count() const { return d_guts->get_decimation_count(); } int oscope_sink_x::get_trigger_channel() const { return d_guts->get_trigger_channel(); } trigger_mode oscope_sink_x::get_trigger_mode() const { return d_guts->get_trigger_mode(); } trigger_slope oscope_sink_x::get_trigger_slope() const { return d_guts->get_trigger_slope(); } double oscope_sink_x::get_trigger_level() const { return d_guts->get_trigger_level(); } int oscope_sink_x::get_samples_per_output_record() const { return d_guts->get_samples_per_output_record(); } } /* namespace wxgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-wxgui/lib/oscope_sink_f_impl.cc0000664000175000017500000000463312207440367022027 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003-2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "oscope_sink_f_impl.h" #include #include #include namespace gr { namespace wxgui { oscope_sink_f::sptr oscope_sink_f::make(double sampling_rate, msg_queue::sptr msgq) { return gnuradio::get_initial_sptr (new oscope_sink_f_impl(sampling_rate, msgq)); } oscope_sink_f_impl::oscope_sink_f_impl(double sampling_rate, msg_queue::sptr msgq) : oscope_sink_x("oscope_sink_f", io_signature::make(1, oscope_guts::MAX_CHANNELS, sizeof(float)), sampling_rate), d_msgq(msgq) { d_guts = new oscope_guts(d_sampling_rate, d_msgq); } oscope_sink_f_impl::~oscope_sink_f_impl() { } bool oscope_sink_f_impl::check_topology(int ninputs, int noutputs) { return d_guts->set_num_channels(ninputs); } int oscope_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ni = input_items.size(); float tmp[oscope_guts::MAX_CHANNELS]; for(int i = 0; i < noutput_items; i++) { // FIXME for now, copy the data. Fix later if reqd for(int ch = 0; ch < ni; ch++) tmp[ch] = ((const float*)input_items[ch])[i]; d_guts->process_sample(tmp); } return noutput_items; } } /* namespace wxgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-wxgui/lib/oscope_guts.cc0000664000175000017500000002611512207440367020516 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include namespace gr { namespace wxgui { /* * Bad performance if it's large, and flaky triggering if it's too small */ static const int OUTPUT_RECORD_SIZE = 1024; // Must be power of 2 /* * For (slow-updated) STRIPCHART triggering, we make the record * size larger, since we potentially want to be able to "see" * hours of data. This works as long as the update rates to a * STRIPCHART are low, which they generally are--that's rather * what a stripchart is all about! */ static const int SCHART_MULT = 8; static inline int wrap_bi(int buffer_index, int mx) // wrap buffer index { return buffer_index & (mx - 1); } static inline int incr_bi(int buffer_index, int mx) // increment buffer index { return wrap_bi(buffer_index + 1, mx); } static inline int decr_bi(int buffer_index, int mx) // decrement buffer index { return wrap_bi(buffer_index - 1, mx); } oscope_guts::oscope_guts(double sample_rate, msg_queue::sptr msgq) : d_nchannels(1), d_msgq(msgq), d_trigger_mode(TRIG_MODE_AUTO), d_trigger_slope(TRIG_SLOPE_POS), d_trigger_channel(0), d_sample_rate(sample_rate), d_update_rate(20), d_trigger_level(0), d_obi(0), d_state(HOLD_OFF), d_decimator_count(0), d_decimator_count_init(1), d_hold_off_count(0), d_hold_off_count_init(OUTPUT_RECORD_SIZE/2-1), d_pre_trigger_count(0), d_post_trigger_count(0), d_post_trigger_count_init(OUTPUT_RECORD_SIZE/2) { for(int i = 0; i < MAX_CHANNELS; i++) d_buffer[i] = 0; for(int i = 0; i < MAX_CHANNELS; i++) { d_buffer[i] = new float[OUTPUT_RECORD_SIZE*SCHART_MULT]; for(int j = 0; j < OUTPUT_RECORD_SIZE*SCHART_MULT; j++) d_buffer[i][j] = 0.0; } // be sure buffer is full before first write enter_hold_off(); update_rate_or_decimation_changed(); } oscope_guts::~oscope_guts() { for(int i = 0; i < MAX_CHANNELS; i++) delete [] d_buffer[i]; } // MANIPULATORS void oscope_guts::process_sample(const float *channel_data) { d_decimator_count--; if(d_decimator_count > 0) return; d_decimator_count = d_decimator_count_init; if(d_trigger_mode != TRIG_MODE_STRIPCHART) { for(int i = 0; i < d_nchannels; i++) d_buffer[i][d_obi] = channel_data[i]; // copy data into buffer switch(d_state) { case HOLD_OFF: d_hold_off_count--; if(d_hold_off_count <= 0) enter_look_for_trigger (); break; case LOOK_FOR_TRIGGER: if(found_trigger()) enter_post_trigger(); break; case POST_TRIGGER: d_post_trigger_count--; if(d_post_trigger_count <= 0) { write_output_records(); enter_hold_off(); } break; default: assert(0); } d_obi = incr_bi(d_obi, OUTPUT_RECORD_SIZE); } else { for(int i = 0; i < d_nchannels; i++) { for(int j = (OUTPUT_RECORD_SIZE*SCHART_MULT)-1; j > 0; j--) { d_buffer[i][j] = d_buffer[i][j-1]; } d_buffer[i][0] = channel_data[i]; } d_trigger_off = 0; write_output_records(); } } /* * Functions called on state entry */ void oscope_guts::enter_hold_off() { d_state = HOLD_OFF; d_hold_off_count = d_hold_off_count_init; } void oscope_guts::enter_look_for_trigger() { d_pre_trigger_count = 0; d_state = LOOK_FOR_TRIGGER; } void oscope_guts::enter_post_trigger() { d_state = POST_TRIGGER; d_post_trigger_count = d_post_trigger_count_init; //ensure that the trigger offset is no more than than half a sample if(d_trigger_off > .5) d_trigger_off -= 1; else d_post_trigger_count--; } // ---------------------------------------------------------------- // returns true if trigger found bool oscope_guts::found_trigger() { int mx = d_trigger_mode == TRIG_MODE_STRIPCHART ? OUTPUT_RECORD_SIZE*SCHART_MULT : OUTPUT_RECORD_SIZE; float prev_sample = d_buffer[d_trigger_channel][decr_bi(d_obi, mx)]; float new_sample = d_buffer[d_trigger_channel][d_obi]; switch(d_trigger_mode) { case TRIG_MODE_AUTO: //too many samples without a trigger d_pre_trigger_count++; if(d_pre_trigger_count > OUTPUT_RECORD_SIZE/2) return true; case TRIG_MODE_NORM: //look for trigger switch(d_trigger_slope) { case TRIG_SLOPE_POS: //trigger point in pos slope? if(new_sample < d_trigger_level || prev_sample >= d_trigger_level) return false; break; case TRIG_SLOPE_NEG: //trigger point in neg slope? if(new_sample > d_trigger_level || prev_sample <= d_trigger_level) return false; break; } //calculate the trigger offset in % sample d_trigger_off = (d_trigger_level - prev_sample)/(new_sample - prev_sample); return true; case TRIG_MODE_FREE: //free run mode, always trigger d_trigger_off = 0; return true; default: assert(0); return false; } } // ---------------------------------------------------------------- // write output records (duh!) void oscope_guts::write_output_records() { int mx; mx = d_trigger_mode == TRIG_MODE_STRIPCHART ? OUTPUT_RECORD_SIZE*SCHART_MULT : OUTPUT_RECORD_SIZE; // if the output queue if full, drop the data like its hot. if(d_msgq->full_p()) return; // Build a message to hold the output records message::sptr msg = message::make(0, // msg type d_nchannels, // arg1 for other side mx, // arg2 for other side ((d_nchannels * mx) + 1) * sizeof(float)); // sizeof payload float *out = (float *)msg->msg(); // get pointer to raw message buffer for(int ch = 0; ch < d_nchannels; ch++) { // note that d_obi + 1 points at the oldest sample in the buffer for(int i = 0; i < mx; i++) { out[i] = d_buffer[ch][wrap_bi(d_obi + 1 + i, mx)]; } out += mx; } //Set the last sample as the trigger offset: // The non gl scope sink will not look at this last sample. // The gl scope sink will use this last sample as an offset. out[0] = d_trigger_off; d_msgq->handle(msg); // send the msg } // ---------------------------------------------------------------- bool oscope_guts::set_update_rate(double update_rate) { d_update_rate = std::min(std::max (1./10., update_rate), d_sample_rate); update_rate_or_decimation_changed(); return true; } bool oscope_guts::set_decimation_count(int decimator_count) { decimator_count = std::max(1, decimator_count); d_decimator_count_init = decimator_count; update_rate_or_decimation_changed(); return true; } bool oscope_guts::set_sample_rate(double sample_rate) { d_sample_rate = sample_rate; return set_update_rate(update_rate()); } void oscope_guts::update_rate_or_decimation_changed() { d_hold_off_count_init = (int)rint(d_sample_rate / d_update_rate / d_decimator_count_init); } bool oscope_guts::set_trigger_channel(int channel) { if(channel >= 0 && channel < d_nchannels) { d_trigger_channel = channel; trigger_changed (); return true; } return false; } bool oscope_guts::set_trigger_mode(trigger_mode mode) { d_trigger_mode = mode; trigger_changed(); return true; } bool oscope_guts::set_trigger_slope(trigger_slope slope) { d_trigger_slope = slope; trigger_changed(); return true; } bool oscope_guts::set_trigger_level(double trigger_level) { d_trigger_level = trigger_level; trigger_changed(); return true; } bool oscope_guts::set_trigger_level_auto() { // find the level 1/2 way between the min and the max float min_v = d_buffer[d_trigger_channel][0]; float max_v = d_buffer[d_trigger_channel][0]; for(int i = 1; i < OUTPUT_RECORD_SIZE; i++) { min_v = std::min (min_v, d_buffer[d_trigger_channel][i]); max_v = std::max (max_v, d_buffer[d_trigger_channel][i]); } return set_trigger_level((min_v + max_v) * 0.5); } bool oscope_guts::set_num_channels(int nchannels) { if(nchannels > 0 && nchannels <= MAX_CHANNELS) { d_nchannels = nchannels; return true; } return false; } void oscope_guts::trigger_changed() { enter_look_for_trigger(); } // ACCESSORS int oscope_guts::num_channels() const { return d_nchannels; } double oscope_guts::sample_rate() const { return d_sample_rate; } double oscope_guts::update_rate() const { return d_update_rate; } int oscope_guts::get_decimation_count() const { return d_decimator_count_init; } int oscope_guts::get_trigger_channel() const { return d_trigger_channel; } trigger_mode oscope_guts::get_trigger_mode() const { return d_trigger_mode; } trigger_slope oscope_guts::get_trigger_slope() const { return d_trigger_slope; } double oscope_guts::get_trigger_level() const { return d_trigger_level; } int oscope_guts::get_samples_per_output_record() const { int mx; mx = OUTPUT_RECORD_SIZE; if(d_trigger_mode == TRIG_MODE_STRIPCHART) { mx = OUTPUT_RECORD_SIZE*SCHART_MULT; } return mx; } } /* namespace wxgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-wxgui/lib/histo_sink_f_impl.h0000664000175000017500000000345512207440367021530 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_HISTO_SINK_F_IMPL_H #define INCLUDED_GR_HISTO_SINK_F_IMPL_H #include namespace gr { namespace wxgui { class histo_sink_f_impl : public histo_sink_f { private: msg_queue::sptr d_msgq; unsigned int d_num_bins; unsigned int d_frame_size; unsigned int d_sample_count; unsigned int *d_bins; float *d_samps; gr::thread::mutex d_mutex; void send_frame(void); void clear(void); public: histo_sink_f_impl(msg_queue::sptr msgq); ~histo_sink_f_impl(void); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int get_frame_size(void); unsigned int get_num_bins(void); void set_frame_size(unsigned int frame_size); void set_num_bins(unsigned int num_bins); }; } /* namespace wxgui */ } /* namespace gr */ #endif /* INCLUDED_GR_HISTO_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-wxgui/README.gl0000644000175000017500000000170611700377701016363 0ustar jcorganjcorganTo use the OpenGL versions of the graphical display sinks, you must ensure that you have Python wrappers for OpenGL installed and are using a version of wxPython that supports it. Then you must enable this mode by creating or editing an entry in the GNU Radio preferences file at: ~/.gnuradio/config.conf [wxgui] style=gl fft_rate=30 waterfall_rate=30 scope_rate=30 number_rate=5 const_rate=5 const_size=2048 >>>The style parameter accepts 'nongl', 'gl', and 'auto', and defaults to 'auto'. 'nongl' forces the use of the non-GL (current) sinks. 'gl' forces the use of the new GL based sinks, and will raise an exception if the appropriate GL support does not exist. 'auto' currently equates to 'nongl'; however, in release 3.2, this will change to use GL if possible and if not, fallback to the non-GL versions. >>>The *_rate parameter sets the frame rate for various gl sinks. >>>The const_size parameter sets the number of constellation points per frame. gnuradio-3.7.2.1/gr-wxgui/swig/0000775000175000017500000000000012207440367016053 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wxgui/swig/CMakeLists.txt0000664000175000017500000000356312207440367020622 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/../include ${GR_WXGUI_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/wxgui_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/wxgui) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_TARGET_DEPS wxgui_generated_includes) set(GR_SWIG_LIBRARIES gnuradio-wxgui) GR_SWIG_MAKE(wxgui_swig wxgui_swig.i) GR_SWIG_INSTALL( TARGETS wxgui_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/wxgui COMPONENT "wxgui_python" ) install( FILES wxgui_swig.i ${CMAKE_CURRENT_BINARY_DIR}/wxgui_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "wxgui_swig" ) gnuradio-3.7.2.1/gr-wxgui/swig/wxgui_swig.i0000664000175000017500000000244312207440367020424 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define WXGUI_API %include "gnuradio.i" //load generated python docstrings %include "wxgui_swig_doc.i" %include "gnuradio/wxgui/trigger_mode.h" %{ #include "gnuradio/wxgui/oscope_sink_x.h" #include "gnuradio/wxgui/histo_sink_f.h" #include "gnuradio/wxgui/oscope_sink_f.h" %} %include "gnuradio/wxgui/oscope_sink_x.h" %include "gnuradio/wxgui/histo_sink_f.h" %include "gnuradio/wxgui/oscope_sink_f.h" GR_SWIG_BLOCK_MAGIC2(wxgui, histo_sink_f); GR_SWIG_BLOCK_MAGIC2(wxgui, oscope_sink_f); gnuradio-3.7.2.1/gr-wxgui/README0000644000175000017500000000010611700377701015753 0ustar jcorganjcorganThis requires wxPython 2.5.2.7 or later. See http://www.wxpython.org gnuradio-3.7.2.1/gr-wxgui/gr-wxgui.pc.in0000664000175000017500000000032512207440367017604 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gr-wxgui Description: A simple wx gui for GNU Radio applications Requires: gnuradio-runtime Version: @LIBVER@ Libs: Cflags: gnuradio-3.7.2.1/gr-qtgui/0000755000175000017500000000000012207440367015066 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/CMakeLists.txt0000664000175000017500000001000612207440367017625 0ustar jcorganjcorgan# Copyright 2010-2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) find_package(Qt4 4.2.0 COMPONENTS QtCore QtGui) find_package(Qwt) find_package(PythonLibs 2) include(GrPython) GR_PYTHON_CHECK_MODULE("PyQt4" PyQt4 True PYQT4_FOUND) ######################################################################## # Register component ######################################################################## include(GrComponent) if(NOT CMAKE_CROSSCOMPILING) set(qt_gui_python_deps PYQT4_FOUND #we could check for pyqwt, but its not strictly required ) endif(NOT CMAKE_CROSSCOMPILING) GR_REGISTER_COMPONENT("gr-qtgui" ENABLE_GR_QTGUI Boost_FOUND QT4_FOUND QWT_FOUND ENABLE_VOLK ENABLE_GNURADIO_RUNTIME ENABLE_GR_FFT ENABLE_GR_FILTER PYTHONLIBS_FOUND ${qt_gui_python_deps} ) GR_SET_GLOBAL(GR_QTGUI_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_BINARY_DIR}/lib ) SET(GR_PKG_QTGUI_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/qt-gui) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_QTGUI) # populate the environment with QT variables include(GrSetupQt4) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_QTGUI_DESCRIPTION "GNU Radio QtGUI Blocks") CPACK_COMPONENT("qtgui_runtime" GROUP "QtGUI" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("qtgui_devel" GROUP "QtGUI" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("qtgui_python" GROUP "QtGUI" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;qtgui_runtime" ) CPACK_COMPONENT("qtgui_swig" GROUP "QtGUI" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;qtgui_python;qtgui_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/qtgui) add_subdirectory(lib) add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(grc) add_subdirectory(swig) add_subdirectory(python/qtgui) add_subdirectory(examples) add_subdirectory(apps) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-qtgui.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-qtgui.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-qtgui.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "qtgui_devel" ) endif(ENABLE_GR_QTGUI) gnuradio-3.7.2.1/gr-qtgui/include/0000775000175000017500000000000012207440367016513 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/include/gnuradio/0000775000175000017500000000000012207440367020323 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/0000775000175000017500000000000012245466767021472 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/DisplayPlot.h0000664000175000017500000002576212237515112024077 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef DOMAIN_DISPLAY_PLOT_H #define DOMAIN_DISPLAY_PLOT_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if QWT_VERSION >= 0x060000 #include #endif typedef QList QColorList; Q_DECLARE_METATYPE ( QColorList ) /*! * \brief QWidget base plot to build QTGUI plotting tools. * \ingroup qtgui_blk */ class DisplayPlot:public QwtPlot{ Q_OBJECT Q_PROPERTY ( QColor line_color1 READ getLineColor1 WRITE setLineColor1 ) Q_PROPERTY ( QColor line_color2 READ getLineColor2 WRITE setLineColor2 ) Q_PROPERTY ( QColor line_color3 READ getLineColor3 WRITE setLineColor3 ) Q_PROPERTY ( QColor line_color4 READ getLineColor4 WRITE setLineColor4 ) Q_PROPERTY ( QColor line_color5 READ getLineColor5 WRITE setLineColor5 ) Q_PROPERTY ( QColor line_color6 READ getLineColor6 WRITE setLineColor6 ) Q_PROPERTY ( QColor line_color7 READ getLineColor7 WRITE setLineColor7 ) Q_PROPERTY ( QColor line_color8 READ getLineColor8 WRITE setLineColor8 ) Q_PROPERTY ( QColor line_color9 READ getLineColor9 WRITE setLineColor9 ) Q_PROPERTY ( int line_width1 READ getLineWidth1 WRITE setLineWidth1 ) Q_PROPERTY ( int line_width2 READ getLineWidth2 WRITE setLineWidth2 ) Q_PROPERTY ( int line_width3 READ getLineWidth3 WRITE setLineWidth3 ) Q_PROPERTY ( int line_width4 READ getLineWidth4 WRITE setLineWidth4 ) Q_PROPERTY ( int line_width5 READ getLineWidth5 WRITE setLineWidth5 ) Q_PROPERTY ( int line_width6 READ getLineWidth6 WRITE setLineWidth6 ) Q_PROPERTY ( int line_width7 READ getLineWidth7 WRITE setLineWidth7 ) Q_PROPERTY ( int line_width8 READ getLineWidth8 WRITE setLineWidth8 ) Q_PROPERTY ( int line_width9 READ getLineWidth9 WRITE setLineWidth9 ) Q_PROPERTY ( Qt::PenStyle line_style1 READ getLineStyle1 WRITE setLineStyle1 ) Q_PROPERTY ( Qt::PenStyle line_style2 READ getLineStyle2 WRITE setLineStyle2 ) Q_PROPERTY ( Qt::PenStyle line_style3 READ getLineStyle3 WRITE setLineStyle3 ) Q_PROPERTY ( Qt::PenStyle line_style4 READ getLineStyle4 WRITE setLineStyle4 ) Q_PROPERTY ( Qt::PenStyle line_style5 READ getLineStyle5 WRITE setLineStyle5 ) Q_PROPERTY ( Qt::PenStyle line_style6 READ getLineStyle6 WRITE setLineStyle6 ) Q_PROPERTY ( Qt::PenStyle line_style7 READ getLineStyle7 WRITE setLineStyle7 ) Q_PROPERTY ( Qt::PenStyle line_style8 READ getLineStyle8 WRITE setLineStyle8 ) Q_PROPERTY ( Qt::PenStyle line_style9 READ getLineStyle9 WRITE setLineStyle9 ) typedef QwtSymbol::Style QwtSymbolStyle; Q_ENUMS ( QwtSymbolStyle ) Q_PROPERTY ( QwtSymbolStyle line_marker1 READ getLineMarker1 WRITE setLineMarker1 ) Q_PROPERTY ( QwtSymbolStyle line_marker2 READ getLineMarker2 WRITE setLineMarker2 ) Q_PROPERTY ( QwtSymbolStyle line_marker3 READ getLineMarker3 WRITE setLineMarker3 ) Q_PROPERTY ( QwtSymbolStyle line_marker4 READ getLineMarker4 WRITE setLineMarker4 ) Q_PROPERTY ( QwtSymbolStyle line_marker5 READ getLineMarker5 WRITE setLineMarker5 ) Q_PROPERTY ( QwtSymbolStyle line_marker6 READ getLineMarker6 WRITE setLineMarker6 ) Q_PROPERTY ( QwtSymbolStyle line_marker7 READ getLineMarker7 WRITE setLineMarker7 ) Q_PROPERTY ( QwtSymbolStyle line_marker8 READ getLineMarker8 WRITE setLineMarker8 ) Q_PROPERTY ( QwtSymbolStyle line_marker9 READ getLineMarker9 WRITE setLineMarker9 ) Q_PROPERTY ( int marker_alpha1 READ getMarkerAlpha1 WRITE setMarkerAlpha1 ) Q_PROPERTY ( int marker_alpha2 READ getMarkerAlpha2 WRITE setMarkerAlpha2 ) Q_PROPERTY ( int marker_alpha3 READ getMarkerAlpha3 WRITE setMarkerAlpha3 ) Q_PROPERTY ( int marker_alpha4 READ getMarkerAlpha4 WRITE setMarkerAlpha4 ) Q_PROPERTY ( int marker_alpha5 READ getMarkerAlpha5 WRITE setMarkerAlpha5 ) Q_PROPERTY ( int marker_alpha6 READ getMarkerAlpha6 WRITE setMarkerAlpha6 ) Q_PROPERTY ( int marker_alpha7 READ getMarkerAlpha7 WRITE setMarkerAlpha7 ) Q_PROPERTY ( int marker_alpha8 READ getMarkerAlpha8 WRITE setMarkerAlpha8 ) Q_PROPERTY ( int marker_alpha9 READ getMarkerAlpha9 WRITE setMarkerAlpha9 ) Q_PROPERTY ( QColor zoomer_color READ getZoomerColor WRITE setZoomerColor ) Q_PROPERTY ( QColor palette_color READ getPaletteColor WRITE setPaletteColor ) Q_PROPERTY ( int yaxis_label_font_size READ getYaxisLabelFontSize WRITE setYaxisLabelFontSize ) Q_PROPERTY ( int xaxis_label_font_size READ getXaxisLabelFontSize WRITE setXaxisLabelFontSize ) Q_PROPERTY ( int axes_label_font_size READ getAxesLabelFontSize WRITE setAxesLabelFontSize ) public: DisplayPlot(int nplots, QWidget*); virtual ~DisplayPlot(); virtual void replot() = 0; const QColor getLineColor1 () const; const QColor getLineColor2 () const; const QColor getLineColor3 () const; const QColor getLineColor4 () const; const QColor getLineColor5 () const; const QColor getLineColor6 () const; const QColor getLineColor7 () const; const QColor getLineColor8 () const; const QColor getLineColor9 () const; int getLineWidth1 () const; int getLineWidth2 () const; int getLineWidth3 () const; int getLineWidth4 () const; int getLineWidth5 () const; int getLineWidth6 () const; int getLineWidth7 () const; int getLineWidth8 () const; int getLineWidth9 () const; const Qt::PenStyle getLineStyle1 () const; const Qt::PenStyle getLineStyle2 () const; const Qt::PenStyle getLineStyle3 () const; const Qt::PenStyle getLineStyle4 () const; const Qt::PenStyle getLineStyle5 () const; const Qt::PenStyle getLineStyle6 () const; const Qt::PenStyle getLineStyle7 () const; const Qt::PenStyle getLineStyle8 () const; const Qt::PenStyle getLineStyle9 () const; const QwtSymbol::Style getLineMarker1 () const; const QwtSymbol::Style getLineMarker2 () const; const QwtSymbol::Style getLineMarker3 () const; const QwtSymbol::Style getLineMarker4 () const; const QwtSymbol::Style getLineMarker5 () const; const QwtSymbol::Style getLineMarker6 () const; const QwtSymbol::Style getLineMarker7 () const; const QwtSymbol::Style getLineMarker8 () const; const QwtSymbol::Style getLineMarker9 () const; int getMarkerAlpha1 () const; int getMarkerAlpha2 () const; int getMarkerAlpha3 () const; int getMarkerAlpha4 () const; int getMarkerAlpha5 () const; int getMarkerAlpha6 () const; int getMarkerAlpha7 () const; int getMarkerAlpha8 () const; int getMarkerAlpha9 () const; QColor getZoomerColor() const; QColor getPaletteColor() const; int getAxisLabelFontSize(int axisId) const; int getYaxisLabelFontSize() const; int getXaxisLabelFontSize() const; int getAxesLabelFontSize() const; // Make sure to create your won PlotNewData method in the derived // class: // void PlotNewData(...); public slots: virtual void setYaxis(double min, double max); virtual void setXaxis(double min, double max); virtual void setLineLabel(int which, QString label); virtual QString getLineLabel(int which); virtual void setLineColor(int which, QColor color); virtual QColor getLineColor(int which) const; virtual void setLineWidth(int which, int width); virtual int getLineWidth(int which) const; virtual void setLineStyle(int which, Qt::PenStyle style); virtual const Qt::PenStyle getLineStyle(int which) const; virtual void setLineMarker(int which, QwtSymbol::Style marker); virtual const QwtSymbol::Style getLineMarker(int which) const; virtual void setMarkerAlpha(int which, int alpha); virtual int getMarkerAlpha(int which) const; // Need a function for each curve for setting via stylesheet. // Can't use preprocessor directives because we're inside a Q_OBJECT. void setLineColor1 (QColor); void setLineColor2 (QColor); void setLineColor3 (QColor); void setLineColor4 (QColor); void setLineColor5 (QColor); void setLineColor6 (QColor); void setLineColor7 (QColor); void setLineColor8 (QColor); void setLineColor9 (QColor); void setLineWidth1 (int); void setLineWidth2 (int); void setLineWidth3 (int); void setLineWidth4 (int); void setLineWidth5 (int); void setLineWidth6 (int); void setLineWidth7 (int); void setLineWidth8 (int); void setLineWidth9 (int); void setLineStyle1 (Qt::PenStyle); void setLineStyle2 (Qt::PenStyle); void setLineStyle3 (Qt::PenStyle); void setLineStyle4 (Qt::PenStyle); void setLineStyle5 (Qt::PenStyle); void setLineStyle6 (Qt::PenStyle); void setLineStyle7 (Qt::PenStyle); void setLineStyle8 (Qt::PenStyle); void setLineStyle9 (Qt::PenStyle); void setLineMarker1 (QwtSymbol::Style); void setLineMarker2 (QwtSymbol::Style); void setLineMarker3 (QwtSymbol::Style); void setLineMarker4 (QwtSymbol::Style); void setLineMarker5 (QwtSymbol::Style); void setLineMarker6 (QwtSymbol::Style); void setLineMarker7 (QwtSymbol::Style); void setLineMarker8 (QwtSymbol::Style); void setLineMarker9 (QwtSymbol::Style); void setMarkerAlpha1 (int); void setMarkerAlpha2 (int); void setMarkerAlpha3 (int); void setMarkerAlpha4 (int); void setMarkerAlpha5 (int); void setMarkerAlpha6 (int); void setMarkerAlpha7 (int); void setMarkerAlpha8 (int); void setMarkerAlpha9 (int); void setZoomerColor(QColor c); void setPaletteColor(QColor c); void setAxisLabelFontSize(int axisId, int fs); void setYaxisLabelFontSize(int fs); void setXaxisLabelFontSize(int fs); void setAxesLabelFontSize(int fs); void setStop(bool on); void resizeSlot(QSize *s); // Because of the preprocessing of slots in QT, these are not // easily separated by the version check. Make one for each // version until it's worked out. void onPickerPointSelected(const QwtDoublePoint & p); void onPickerPointSelected6(const QPointF & p); signals: void plotPointSelected(const QPointF p); protected slots: virtual void legendEntryChecked(QwtPlotItem *plotItem, bool on); protected: int d_nplots; std::vector d_plot_curve; QwtPlotPanner* d_panner; QwtPlotZoomer* d_zoomer; QwtDblClickPlotPicker *d_picker; QwtPlotMagnifier *d_magnifier; int64_t d_numPoints; bool d_stop; QList d_trace_colors; bool d_autoscale_state; }; #endif /* DOMAIN_DISPLAY_PLOT_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/CMakeLists.txt0000664000175000017500000000344412237515112024213 0ustar jcorganjcorgan# Copyright 2010-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install the header files ######################################################################## install(FILES api.h CMakeLists.txt constellationdisplayform.h ConstellationDisplayPlot.h const_sink_c.h displayform.h DisplayPlot.h form_menus.h freqdisplayform.h freq_sink_c.h freq_sink_f.h FrequencyDisplayPlot.h histogram_sink_f.h histogramdisplayform.h HistogramDisplayPlot.h plot_raster.h plot_waterfall.h qtgui_types.h sink_c.h sink_f.h spectrumdisplayform.h SpectrumGUIClass.h spectrumUpdateEvents.h timedisplayform.h TimeDomainDisplayPlot.h timerasterdisplayform.h TimeRasterDisplayPlot.h timeRasterGlobalData.h time_raster_sink_b.h time_raster_sink_f.h time_sink_c.h time_sink_f.h trigger_mode.h utils.h waterfalldisplayform.h WaterfallDisplayPlot.h waterfallGlobalData.h waterfall_sink_c.h waterfall_sink_f.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/qtgui COMPONENT "qtgui_devel" ) gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/ConstellationDisplayPlot.h0000664000175000017500000000401612237515112026623 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef CONSTELLATION_DISPLAY_PLOT_H #define CONSTELLATION_DISPLAY_PLOT_H #include #include #include #include /*! * \brief QWidget for displaying constellaton (I&Q) plots. * \ingroup qtgui_blk */ class ConstellationDisplayPlot : public DisplayPlot { Q_OBJECT public: ConstellationDisplayPlot(int nplots, QWidget*); virtual ~ConstellationDisplayPlot(); void plotNewData(const std::vector realDataPoints, const std::vector imagDataPoints, const int64_t numDataPoints, const double timeInterval); // Old method to be removed void plotNewData(const double* realDataPoints, const double* imagDataPoints, const int64_t numDataPoints, const double timeInterval); void replot(); void set_xaxis(double min, double max); void set_yaxis(double min, double max); void set_axis(double xmin, double xmax, double ymin, double ymax); void set_pen_size(int size); public slots: void setAutoScale(bool state); private: void _autoScale(double bottom, double top); std::vector d_real_data; std::vector d_imag_data; int64_t d_pen_size; }; #endif /* CONSTELLATION_DISPLAY_PLOT_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/spectrumdisplayform.h0000664000175000017500000001042412207440367025742 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef SPECTRUM_DISPLAY_FORM_H #define SPECTRUM_DISPLAY_FORM_H #include class SpectrumGUIClass; #include #include #include #include #include #include #include #include #include class SpectrumDisplayForm : public QWidget, public Ui::SpectrumDisplayForm { Q_OBJECT public: SpectrumDisplayForm(QWidget* parent = 0); ~SpectrumDisplayForm(); void setSystem(SpectrumGUIClass * newSystem, const uint64_t numFFTDataPoints, const uint64_t numTimeDomainDataPoints); int getAverageCount(); void setAverageCount(const int newCount); void reset(); void averageDataReset(); void resizeBuffers(const uint64_t numFFTDataPoints, const uint64_t numTimeDomainDataPoints); public slots: void resizeEvent(QResizeEvent * e); void customEvent(QEvent * e); void avgLineEdit_valueChanged(int valueString); void maxHoldCheckBox_toggled(bool newState); void minHoldCheckBox_toggled(bool newState); void minHoldResetBtn_clicked(); void maxHoldResetBtn_clicked(); void tabChanged(int index); void setFrequencyRange(const double newCenterFrequency, const double newStartFrequency, const double newStopFrequency); void closeEvent(QCloseEvent * e); void windowTypeChanged(int newItem); void useRFFrequenciesCB(bool useRFFlag); void waterfallMaximumIntensityChangedCB(double); void waterfallMinimumIntensityChangedCB(double); void waterfallIntensityColorTypeChanged(int); void waterfallAutoScaleBtnCB(); void fftComboBoxSelectedCB(const QString&); void toggleTabFrequency(const bool state); void toggleTabWaterfall(const bool state); void toggleTabTime(const bool state); void toggleTabConstellation(const bool state); void setTimeDomainAxis(double min, double max); void setConstellationAxis(double xmin, double xmax, double ymin, double ymax); void setConstellationPenSize(int size); void setFrequencyAxis(double min, double max); void setUpdateTime(double t); private slots: void newFrequencyData(const SpectrumUpdateEvent*); void updateGuiTimer(); void onFFTPlotPointSelected(const QPointF p); void onWFallPlotPointSelected(const QPointF p); void onTimePlotPointSelected(const QPointF p); void onConstPlotPointSelected(const QPointF p); signals: void plotPointSelected(const QPointF p, int type); private: void _averageHistory(const double * newBuffer); int _historyEntryCount; int _historyEntry; std::vector* _historyVector; double* _averagedValues; uint64_t _numRealDataPoints; double* _realFFTDataPoints; QIntValidator* _intValidator; FrequencyDisplayPlot* _frequencyDisplayPlot; WaterfallDisplayPlot* _waterfallDisplayPlot; TimeDomainDisplayPlot* _timeDomainDisplayPlot; ConstellationDisplayPlot* _constellationDisplayPlot; SpectrumGUIClass* _system; bool _systemSpecifiedFlag; double _centerFrequency; double _startFrequency; double _noiseFloorAmplitude; double _peakFrequency; double _peakAmplitude; double _stopFrequency; //SpectrumUpdateEvent _lastSpectrumEvent; // whether or not to use a particular display int d_plot_fft; int d_plot_waterfall; int d_plot_time; int d_plot_constellation; QTimer *displayTimer; double d_update_time; }; #endif /* SPECTRUM_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/waterfallGlobalData.h0000664000175000017500000000424512207440367025526 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef WATERFALL_GLOBAL_DATA_HPP #define WATERFALL_GLOBAL_DATA_HPP #include #include #if QWT_VERSION >= 0x060000 #include // doesn't seem necessary, but is... #include #endif class WaterfallData: public QwtRasterData { public: WaterfallData(const double, const double, const uint64_t, const unsigned int); virtual ~WaterfallData(); virtual void reset(); virtual void copy(const WaterfallData*); virtual void resizeData(const double, const double, const uint64_t); virtual QwtRasterData *copy() const; #if QWT_VERSION < 0x060000 virtual QwtDoubleInterval range() const; virtual void setRange(const QwtDoubleInterval&); #endif virtual double value(double x, double y) const; virtual uint64_t getNumFFTPoints()const; virtual void addFFTData(const double*, const uint64_t, const int); virtual double* getSpectrumDataBuffer()const; virtual void setSpectrumDataBuffer(const double*); virtual int getNumLinesToUpdate()const; virtual void setNumLinesToUpdate(const int); virtual void incrementNumLinesToUpdate(); protected: double* _spectrumData; uint64_t _fftPoints; uint64_t _historyLength; int _numLinesToUpdate; #if QWT_VERSION < 0x060000 QwtDoubleInterval _intensityRange; #else QwtInterval _intensityRange; #endif private: }; #endif /* WATERFALL_GLOBAL_DATA_HPP */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/histogram_sink_f.h0000664000175000017500000001141112237515112025143 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_HISTOGRAM_SINK_F_H #define INCLUDED_QTGUI_HISTOGRAM_SINK_F_H #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display a histogram. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the displays a histogram of * the data. * * This histogram allows you to set and change at runtime the * number of points to plot at once and the number of bins in the * histogram. Both x and y-axis have their own auto-scaling * behavior. By default, auto-scaling the y-axis is turned on and * continuously updates the y-axis max value based on the * currently plotted histogram. * * The x-axis auto-scaling function only updates once when * clicked. This resets the x-axis to the current range of minimum * and maximum values represented in the histogram. It resets any * values currently displayed because the location and width of * the bins may have changed. * * The histogram also has an accumulate function that simply * accumulates the data between calls to work. When accumulate is * activated, the y-axis autoscaling is turned on by default as * the values will quickly grow in the this direction. */ class QTGUI_API histogram_sink_f : virtual public sync_block { public: // gr::qtgui::histogram_sink_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Build floating point histogram sink * * \param size number of points to plot at once * \param bins number of bins to sort the data into * \param xmin minimum x-axis value * \param xmax maximum x-axis value * \param name title for the plot * \param nconnections number of signals connected to sink * \param parent a QWidget parent object, if any */ static sptr make(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; public: virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; virtual void enable_autoscale(bool en=true) = 0; virtual void enable_semilogx(bool en=true) = 0; virtual void enable_semilogy(bool en=true) = 0; virtual void enable_accumulate(bool en=true) = 0; virtual void autoscalex() = 0; virtual int nsamps() const = 0; virtual int bins() const = 0; virtual void reset() = 0; QApplication *d_qApplication; virtual void set_y_axis(double min, double max) = 0; virtual void set_x_axis(double min, double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &line) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, int style) = 0; virtual void set_line_marker(int which, int marker) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_nsamps(const int newsize) = 0; virtual void set_bins(const int bins) = 0; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_HISTOGRAM_SINK_F_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/timedisplayform.h0000664000175000017500000000622712237515112025036 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIME_DISPLAY_FORM_H #define TIME_DISPLAY_FORM_H #include #include #include #include #include /*! * \brief DisplayForm child for managing time domain plots. * \ingroup qtgui_blk */ class TimeDisplayForm : public DisplayForm { Q_OBJECT public: TimeDisplayForm(int nplots=1, QWidget* parent = 0); ~TimeDisplayForm(); TimeDomainDisplayPlot* getPlot(); int getNPoints() const; gr::qtgui::trigger_mode getTriggerMode() const; gr::qtgui::trigger_slope getTriggerSlope() const; float getTriggerLevel() const; float getTriggerDelay() const; int getTriggerChannel() const; std::string getTriggerTagKey() const; public slots: void customEvent(QEvent * e); void setSampleRate(const double samprate); void setSampleRate(const QString &samprate); void setYaxis(double min, double max); void setNPoints(const int); void setStem(bool en); void autoScale(bool en); void setSemilogx(bool en); void setSemilogy(bool en); void tagMenuSlot(bool en); void setTagMenu(int which, bool en); void updateTrigger(gr::qtgui::trigger_mode mode); void setTriggerMode(gr::qtgui::trigger_mode mode); void setTriggerSlope(gr::qtgui::trigger_slope slope); void setTriggerLevel(QString s); void setTriggerLevel(float level); void setTriggerDelay(QString s); void setTriggerDelay(float delay); void setTriggerChannel(int chan); void setTriggerTagKey(QString s); void setTriggerTagKey(const std::string &s); private slots: void newData(const QEvent*); private: QIntValidator* d_int_validator; double d_start_frequency; double d_stop_frequency; int d_npoints; bool d_stem; bool d_semilogx; bool d_semilogy; NPointsMenu *d_nptsmenu; QAction *d_stemmenu; QAction *d_semilogxmenu; QAction *d_semilogymenu; std::vector d_tagsmenu; QMenu *d_triggermenu; TriggerModeMenu *d_tr_mode_menu; TriggerSlopeMenu *d_tr_slope_menu; PopupMenu *d_tr_level_act; PopupMenu *d_tr_delay_act; TriggerChannelMenu *d_tr_channel_menu; PopupMenu *d_tr_tag_key_act; gr::qtgui::trigger_mode d_trig_mode; gr::qtgui::trigger_slope d_trig_slope; float d_trig_level; float d_trig_delay; int d_trig_channel; std::string d_trig_tag_key; }; #endif /* TIME_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/time_raster_sink_f.h0000664000175000017500000001024712207440367025500 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_RASTER_SINK_F_H #define INCLUDED_QTGUI_TIME_RASTER_SINK_F_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals on a * time_raster plot. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink that takes set of a floating * point streams and plots a time_raster (spectrogram) plot. * */ class QTGUI_API time_raster_sink_f : virtual public sync_block { public: // gr::qtgui::time_raster_sink_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a floating point time raster sink. * * \param samp_rate sample rate of signal * \param cols number of cols to plot * \param rows number of rows to plot * \param mult vector of floats as a scaling multiplier for each input stream * \param offset vector of floats as an offset for each input stream * \param name title for the plot * \param nconnections number of streams connected * \param parent a QWidget parent object, if any */ static sptr make(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &lable) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, Qt::PenStyle style) = 0; virtual void set_line_marker(int which, QwtSymbol::Style marker) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_color_map(int which, const int color) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual int color_map(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void set_samp_rate(const double samp_rate) = 0; virtual void set_num_rows(double rows) = 0; virtual void set_num_cols(double cols) = 0; virtual double num_rows() = 0; virtual double num_cols() = 0; virtual void set_multiplier(const std::vector &mult) = 0; virtual void set_offset(const std::vector &offset) = 0; virtual void set_intensity_range(float min, float max) = 0; virtual void enable_menu(bool en) = 0; virtual void enable_grid(bool en) = 0; virtual void enable_autoscale(bool en) = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_RASTER_SINK_F_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/waterfall_sink_f.h0000664000175000017500000001036312207440367025142 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_WATERFALL_SINK_F_H #define INCLUDED_QTGUI_WATERFALL_SINK_F_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals on a * waterfall (spectrogram) plot. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a floating * point streams and plots a waterfall (spectrogram) plot. * * Note that unlike the other qtgui sinks, this one does not * support multiple input streams. We have yet to figure out a * good way to display multiple, independent signals on this kind * of a plot. If there are any suggestions or examples of this, we * would love to see them. Otherwise, to display multiple signals * here, it's probably best to sum the signals together and * connect that here. */ class QTGUI_API waterfall_sink_f : virtual public sync_block { public: // gr::qtgui::waterfall_sink_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a floating point waterfall sink. * * \param size size of the FFT to compute and display * \param wintype type of window to apply (see gnuradio/filter/firdes.h) * \param fc center frequency of signal (use for x-axis labels) * \param bw bandwidth of signal (used to set x-axis labels) * \param name title for the plot * \param nconnections number of signals to be connected to the sink * \param parent a QWidget parent object, if any */ static sptr make(int size, int wintype, double fc, double bw, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void clear_data() = 0; virtual void set_fft_size(const int fftsize) = 0; virtual int fft_size() const = 0; virtual void set_fft_average(const float fftavg) = 0; virtual float fft_average() const = 0; virtual void set_fft_window(const gr::filter::firdes::win_type win) = 0; virtual gr::filter::firdes::win_type fft_window() = 0; virtual void set_frequency_range(const double centerfreq, const double bandwidth) = 0; virtual void set_intensity_range(const double min, const double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &line) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_color_map(int which, const int color) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual double line_alpha(int which) = 0; virtual int color_map(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void auto_scale() = 0; virtual double min_intensity(int which) = 0; virtual double max_intensity(int which) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_WATERFALL_SINK_F_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/HistogramDisplayPlot.h0000664000175000017500000000404112237515112025740 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef HISTOGRAM_DISPLAY_PLOT_H #define HISTOGRAM_DISPLAY_PLOT_H #include #include #include #include /*! * \brief QWidget for displaying time domain plots. * \ingroup qtgui_blk */ class HistogramDisplayPlot: public DisplayPlot { Q_OBJECT public: HistogramDisplayPlot(int nplots, QWidget*); virtual ~HistogramDisplayPlot(); void plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double timeInterval); void replot(); public slots: void setAutoScale(bool state); void setAutoScaleX(); void setSemilogx(bool en); void setSemilogy(bool en); void setAccumulate(bool en); void setMarkerAlpha(int which, int alpha); int getMarkerAlpha(int which) const; void setLineColor(int which, QColor color); void setNumBins(int bins); void setXaxis(double min, double max); private: void _resetXAxisPoints(double left, double right); void _autoScaleY(double bottom, double top); double* d_xdata; std::vector d_ydata; int d_bins; bool d_accum; double d_xmin, d_xmax, d_left, d_right; double d_width; bool d_semilogx; bool d_semilogy; bool d_autoscalex_state; }; #endif /* HISTOGRAM_DISPLAY_PLOT_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/SpectrumGUIClass.h0000664000175000017500000000705212207440367024766 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef SPECTRUM_GUI_CLASS_HPP #define SPECTRUM_GUI_CLASS_HPP #include #include #include #include #include #include class SpectrumDisplayForm; #include #include #include #include #include /*! * \brief QWidget class for controlling plotting. * \ingroup qtgui_blk */ class SpectrumGUIClass { public: SpectrumGUIClass(const uint64_t maxDataSize, const uint64_t fftSize, const double newCenterFrequency, const double newStartFrequency, const double newStopFrequency); ~SpectrumGUIClass(); void reset(); void openSpectrumWindow(QWidget*, const bool frequency=true, const bool waterfall=true, const bool time=true, const bool constellation=true); void setDisplayTitle(const std::string); bool getWindowOpenFlag(); void setWindowOpenFlag(const bool); void setFrequencyRange(const double, const double, const double); double getStartFrequency(); double getStopFrequency(); double getCenterFrequency(); void updateWindow(const bool, const float*, const uint64_t, const float*, const uint64_t, const float*, const uint64_t, const gr::high_res_timer_type, const bool); float getPowerValue(); void setPowerValue(const float); int getWindowType(); void setWindowType(const int); int getFFTSize(); int getFFTSizeIndex(); void setFFTSize(const int); gr::high_res_timer_type getLastGUIUpdateTime(); void setLastGUIUpdateTime(const gr::high_res_timer_type); unsigned int getPendingGUIUpdateEvents(); void incrementPendingGUIUpdateEvents(); void decrementPendingGUIUpdateEvents(); void resetPendingGUIUpdateEvents(); static const long MAX_FFT_SIZE; static const long MIN_FFT_SIZE; QWidget* qwidget(); void setTimeDomainAxis(double min, double max); void setConstellationAxis(double xmin, double xmax, double ymin, double ymax); void setConstellationPenSize(int size); void setFrequencyAxis(double min, double max); void setUpdateTime(double t); protected: private: gr::thread::mutex d_mutex; int64_t _dataPoints; std::string _title; double _centerFrequency; double _startFrequency; double _stopFrequency; float _powerValue; bool _windowOpennedFlag; int _windowType; int64_t _lastDataPointCount; int _fftSize; gr::high_res_timer_type _lastGUIUpdateTime; unsigned int _pendingGUIUpdateEventsCount; int _droppedEntriesCount; bool _fftBuffersCreatedFlag; double _updateTime; SpectrumDisplayForm* _spectrumDisplayForm; float* _fftPoints; double* _realTimeDomainPoints; double* _imagTimeDomainPoints; }; #endif /* SPECTRUM_GUI_CLASS_HPP */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/freqdisplayform.h0000664000175000017500000000414112245466767025052 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef FREQ_DISPLAY_FORM_H #define FREQ_DISPLAY_FORM_H #include #include #include #include #include #include /*! * \brief DisplayForm child for managing frequency (PSD) plots. * \ingroup qtgui_blk */ class FreqDisplayForm : public DisplayForm { Q_OBJECT public: FreqDisplayForm(int nplots=1, QWidget* parent = 0); ~FreqDisplayForm(); FrequencyDisplayPlot* getPlot(); int getFFTSize() const; float getFFTAverage() const; gr::filter::firdes::win_type getFFTWindowType() const; public slots: void customEvent(QEvent *e); void setSampleRate(const QString &samprate); void setFFTSize(const int); void setFFTAverage(const float); void setFFTWindowType(const gr::filter::firdes::win_type); void setFrequencyRange(const double centerfreq, const double bandwidth); void setYaxis(double min, double max); void autoScale(bool en); private slots: void newData(const QEvent *updateEvent); private: uint64_t d_num_real_data_points; QIntValidator* d_int_validator; double d_samp_rate, d_center_freq; int d_fftsize; float d_fftavg; gr::filter::firdes::win_type d_fftwintype; }; #endif /* FREQ_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/form_menus.h0000664000175000017500000010141012245466767024012 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef FORM_MENUS_H #define FORM_MENUS_H #include #include #include #include #include #include #include class LineColorMenu: public QMenu { Q_OBJECT public: LineColorMenu(int which, QWidget *parent) : QMenu("Line Color", parent), d_which(which) { d_act.push_back(new QAction("Blue", this)); d_act.push_back(new QAction("Red", this)); d_act.push_back(new QAction("Green", this)); d_act.push_back(new QAction("Black", this)); d_act.push_back(new QAction("Cyan", this)); d_act.push_back(new QAction("Magenta", this)); d_act.push_back(new QAction("Yellow", this)); d_act.push_back(new QAction("Gray", this)); d_act.push_back(new QAction("Dark Red", this)); d_act.push_back(new QAction("Dark Green", this)); d_act.push_back(new QAction("Dark Blue", this)); d_act.push_back(new QAction("Dark Gray", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getBlue())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getRed())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getGreen())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getBlack())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getCyan())); connect(d_act[5], SIGNAL(triggered()), this, SLOT(getMagenta())); connect(d_act[6], SIGNAL(triggered()), this, SLOT(getYellow())); connect(d_act[7], SIGNAL(triggered()), this, SLOT(getGray())); connect(d_act[8], SIGNAL(triggered()), this, SLOT(getDarkRed())); connect(d_act[9], SIGNAL(triggered()), this, SLOT(getDarkGreen())); connect(d_act[10], SIGNAL(triggered()), this, SLOT(getDarkBlue())); connect(d_act[11], SIGNAL(triggered()), this, SLOT(getDarkGray())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~LineColorMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("LineColorMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int which, const QString &name); public slots: void getBlue() { emit whichTrigger(d_which, "blue"); } void getRed() { emit whichTrigger(d_which, "red"); } void getGreen() { emit whichTrigger(d_which, "green"); } void getBlack() { emit whichTrigger(d_which, "black"); } void getCyan() { emit whichTrigger(d_which, "cyan"); } void getMagenta() { emit whichTrigger(d_which, "magenta"); } void getYellow() { emit whichTrigger(d_which, "yellow"); } void getGray() { emit whichTrigger(d_which, "gray"); } void getDarkRed() { emit whichTrigger(d_which, "darkred"); } void getDarkGreen() { emit whichTrigger(d_which, "darkgreen"); } void getDarkBlue() { emit whichTrigger(d_which, "darkblue"); } void getDarkGray() { emit whichTrigger(d_which, "darkgray"); } private: QList d_act; int d_which; }; /********************************************************************/ class LineWidthMenu: public QMenu { Q_OBJECT public: LineWidthMenu(int which, QWidget *parent) : QMenu("Line Width", parent), d_which(which) { d_act.push_back(new QAction("1", this)); d_act.push_back(new QAction("2", this)); d_act.push_back(new QAction("3", this)); d_act.push_back(new QAction("4", this)); d_act.push_back(new QAction("5", this)); d_act.push_back(new QAction("6", this)); d_act.push_back(new QAction("7", this)); d_act.push_back(new QAction("8", this)); d_act.push_back(new QAction("9", this)); d_act.push_back(new QAction("10", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getOne())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getTwo())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getThree())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getFour())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getFive())); connect(d_act[5], SIGNAL(triggered()), this, SLOT(getSix())); connect(d_act[6], SIGNAL(triggered()), this, SLOT(getSeven())); connect(d_act[7], SIGNAL(triggered()), this, SLOT(getEight())); connect(d_act[8], SIGNAL(triggered()), this, SLOT(getNine())); connect(d_act[9], SIGNAL(triggered()), this, SLOT(getTen())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~LineWidthMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("LineWidthMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int which, int width); public slots: void getOne() { emit whichTrigger(d_which, 1); } void getTwo() { emit whichTrigger(d_which, 2); } void getThree() { emit whichTrigger(d_which, 3); } void getFour() { emit whichTrigger(d_which, 4); } void getFive() { emit whichTrigger(d_which, 5); } void getSix() { emit whichTrigger(d_which, 6); } void getSeven() { emit whichTrigger(d_which, 7); } void getEight() { emit whichTrigger(d_which, 8); } void getNine() { emit whichTrigger(d_which, 9); } void getTen() { emit whichTrigger(d_which, 10); } private: QList d_act; int d_which; }; /********************************************************************/ class LineStyleMenu: public QMenu { Q_OBJECT public: LineStyleMenu(int which, QWidget *parent) : QMenu("Line Style", parent), d_which(which) { d_act.push_back(new QAction("None", this)); d_act.push_back(new QAction("Solid", this)); d_act.push_back(new QAction("Dash", this)); d_act.push_back(new QAction("Dots", this)); d_act.push_back(new QAction("Dash-Dot", this)); d_act.push_back(new QAction("Dash-Dot-Dot", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getNone())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getSolid())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getDash())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getDots())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getDashDot())); connect(d_act[5], SIGNAL(triggered()), this, SLOT(getDashDotDot())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~LineStyleMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("LineStyleMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int which, Qt::PenStyle); public slots: void getNone() { emit whichTrigger(d_which, Qt::NoPen); } void getSolid() { emit whichTrigger(d_which, Qt::SolidLine); } void getDash() { emit whichTrigger(d_which, Qt::DashLine); } void getDots() { emit whichTrigger(d_which, Qt::DotLine); } void getDashDot() { emit whichTrigger(d_which, Qt::DashDotLine); } void getDashDotDot() { emit whichTrigger(d_which, Qt::DashDotDotLine); } private: QList d_act; int d_which; }; /********************************************************************/ class LineMarkerMenu: public QMenu { Q_OBJECT public: LineMarkerMenu(int which, QWidget *parent) : QMenu("Line Marker", parent), d_which(which) { d_act.push_back(new QAction("None", this)); d_act.push_back(new QAction("Circle", this)); d_act.push_back(new QAction("Rectangle", this)); d_act.push_back(new QAction("Diamond", this)); d_act.push_back(new QAction("Triangle", this)); d_act.push_back(new QAction("Down Triangle", this)); d_act.push_back(new QAction("Left Triangle", this)); d_act.push_back(new QAction("Right Triangle", this)); d_act.push_back(new QAction("Cross", this)); d_act.push_back(new QAction("X-Cross", this)); d_act.push_back(new QAction("Horiz. Line", this)); d_act.push_back(new QAction("Vert. Line", this)); d_act.push_back(new QAction("Star 1", this)); d_act.push_back(new QAction("Star 2", this)); d_act.push_back(new QAction("Hexagon", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getNone())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getCircle())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getRect())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getDiamond())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getTriangle())); connect(d_act[5], SIGNAL(triggered()), this, SLOT(getDTriangle())); connect(d_act[6], SIGNAL(triggered()), this, SLOT(getLTriangle())); connect(d_act[7], SIGNAL(triggered()), this, SLOT(getRTriangle())); connect(d_act[8], SIGNAL(triggered()), this, SLOT(getCross())); connect(d_act[9], SIGNAL(triggered()), this, SLOT(getXCross())); connect(d_act[10], SIGNAL(triggered()), this, SLOT(getHLine())); connect(d_act[11], SIGNAL(triggered()), this, SLOT(getVLine())); connect(d_act[12], SIGNAL(triggered()), this, SLOT(getStar1())); connect(d_act[13], SIGNAL(triggered()), this, SLOT(getStar2())); connect(d_act[14], SIGNAL(triggered()), this, SLOT(getHexagon())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~LineMarkerMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("LineMarkerMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int which, QwtSymbol::Style); public slots: void getNone() { emit whichTrigger(d_which, QwtSymbol::NoSymbol); } void getCircle() { emit whichTrigger(d_which, QwtSymbol::Ellipse); } void getRect() { emit whichTrigger(d_which, QwtSymbol::Rect); } void getDiamond() { emit whichTrigger(d_which, QwtSymbol::Diamond); } void getTriangle() { emit whichTrigger(d_which, QwtSymbol::Triangle); } void getDTriangle() { emit whichTrigger(d_which, QwtSymbol::DTriangle); } void getLTriangle() { emit whichTrigger(d_which, QwtSymbol::LTriangle); } void getRTriangle() { emit whichTrigger(d_which, QwtSymbol::RTriangle); } void getCross() { emit whichTrigger(d_which, QwtSymbol::Cross); } void getXCross() { emit whichTrigger(d_which, QwtSymbol::XCross); } void getHLine() { emit whichTrigger(d_which, QwtSymbol::HLine); } void getVLine() { emit whichTrigger(d_which, QwtSymbol::VLine); } void getStar1() { emit whichTrigger(d_which, QwtSymbol::Star1); } void getStar2() { emit whichTrigger(d_which, QwtSymbol::Star2); } void getHexagon() { emit whichTrigger(d_which, QwtSymbol::Hexagon); } private: QList d_act; int d_which; }; /********************************************************************/ class MarkerAlphaMenu: public QMenu { Q_OBJECT public: MarkerAlphaMenu(int which, QWidget *parent) : QMenu("Line Transparency", parent), d_which(which) { d_act.push_back(new QAction("None", this)); d_act.push_back(new QAction("Low", this)); d_act.push_back(new QAction("Medium", this)); d_act.push_back(new QAction("High", this)); d_act.push_back(new QAction("Off", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getNone())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getLow())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getMedium())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getHigh())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getOff())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~MarkerAlphaMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("MarkerAlphaMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int which, int); public slots: void getNone() { emit whichTrigger(d_which, 255); } void getLow() { emit whichTrigger(d_which, 200); } void getMedium() { emit whichTrigger(d_which, 125); } void getHigh() { emit whichTrigger(d_which, 50); } void getOff() { emit whichTrigger(d_which, 0); } private: QList d_act; int d_which; }; /********************************************************************/ class LineTitleAction: public QAction { Q_OBJECT public: LineTitleAction(int which, QWidget *parent) : QAction("Line Title", parent), d_which(which) { d_diag = new QDialog(parent); d_diag->setModal(true); d_text = new QLineEdit(); QGridLayout *layout = new QGridLayout(d_diag); QPushButton *btn_ok = new QPushButton(tr("OK")); QPushButton *btn_cancel = new QPushButton(tr("Cancel")); layout->addWidget(d_text, 0, 0, 1, 2); layout->addWidget(btn_ok, 1, 0); layout->addWidget(btn_cancel, 1, 1); connect(btn_ok, SIGNAL(clicked()), this, SLOT(getText())); connect(btn_cancel, SIGNAL(clicked()), d_diag, SLOT(close())); connect(this, SIGNAL(triggered()), this, SLOT(getTextDiag())); } ~LineTitleAction() {} signals: void whichTrigger(int which, const QString &text); public slots: void getTextDiag() { d_diag->exec(); } private slots: void getText() { emit whichTrigger(d_which, d_text->text()); d_diag->accept(); } private: int d_which; QDialog *d_diag; QLineEdit *d_text; }; /********************************************************************/ class OtherAction: public QAction { Q_OBJECT public: OtherAction(QWidget *parent) : QAction("Other", parent) { d_diag = new QDialog(parent); d_diag->setWindowTitle("Other"); d_diag->setModal(true); d_text = new QLineEdit(); QGridLayout *layout = new QGridLayout(d_diag); QPushButton *btn_ok = new QPushButton(tr("OK")); QPushButton *btn_cancel = new QPushButton(tr("Cancel")); layout->addWidget(d_text, 0, 0, 1, 2); layout->addWidget(btn_ok, 1, 0); layout->addWidget(btn_cancel, 1, 1); connect(btn_ok, SIGNAL(clicked()), this, SLOT(getText())); connect(btn_cancel, SIGNAL(clicked()), d_diag, SLOT(close())); connect(this, SIGNAL(triggered()), this, SLOT(getTextDiag())); } ~OtherAction() {} signals: void whichTrigger(const QString &text); public slots: void getTextDiag() { d_diag->exec(); } private slots: void getText() { emit whichTrigger(d_text->text()); d_diag->accept(); } private: QDialog *d_diag; QLineEdit *d_text; }; /********************************************************************/ class OtherDualAction: public QAction { Q_OBJECT public: OtherDualAction(QString label0, QString label1, QWidget *parent) : QAction("Other", parent) { d_diag = new QDialog(parent); d_diag->setWindowTitle("Other"); d_diag->setModal(true); d_text0 = new QLineEdit(); d_text1 = new QLineEdit(); QLabel *_label0 = new QLabel(label0); QLabel *_label1 = new QLabel(label1); QGridLayout *layout = new QGridLayout(d_diag); QPushButton *btn_ok = new QPushButton(tr("OK")); QPushButton *btn_cancel = new QPushButton(tr("Cancel")); layout->addWidget(_label0, 0, 0, 1, 2); layout->addWidget(_label1, 1, 0, 1, 2); layout->addWidget(d_text0, 0, 1, 1, 2); layout->addWidget(d_text1, 1, 1, 1, 2); layout->addWidget(btn_ok, 2, 0); layout->addWidget(btn_cancel, 2, 1); connect(btn_ok, SIGNAL(clicked()), this, SLOT(getText())); connect(btn_cancel, SIGNAL(clicked()), d_diag, SLOT(close())); connect(this, SIGNAL(triggered()), this, SLOT(getTextDiag())); } ~OtherDualAction() {} signals: void whichTrigger(const QString &text0, const QString &text1); public slots: void getTextDiag() { d_diag->exec(); } private slots: void getText() { emit whichTrigger(d_text0->text(), d_text1->text()); d_diag->accept(); } private: QDialog *d_diag; QLineEdit *d_text0; QLineEdit *d_text1; }; /********************************************************************/ class FFTSizeMenu: public QMenu { Q_OBJECT public: FFTSizeMenu(QWidget *parent) : QMenu("FFT Size", parent) { d_act.push_back(new QAction("32", this)); d_act.push_back(new QAction("64", this)); d_act.push_back(new QAction("128", this)); d_act.push_back(new QAction("256", this)); d_act.push_back(new QAction("512", this)); d_act.push_back(new QAction("1024", this)); d_act.push_back(new QAction("2048", this)); d_act.push_back(new QAction("4096", this)); d_act.push_back(new QAction("8192", this)); d_act.push_back(new QAction("16384", this)); d_act.push_back(new QAction("32768", this)); d_act.push_back(new OtherAction(this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(get05())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(get06())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(get07())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(get08())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(get09())); connect(d_act[5], SIGNAL(triggered()), this, SLOT(get10())); connect(d_act[6], SIGNAL(triggered()), this, SLOT(get11())); connect(d_act[7], SIGNAL(triggered()), this, SLOT(get12())); connect(d_act[8], SIGNAL(triggered()), this, SLOT(get13())); connect(d_act[9], SIGNAL(triggered()), this, SLOT(get14())); connect(d_act[10], SIGNAL(triggered()), this, SLOT(get15())); connect(d_act[11], SIGNAL(whichTrigger(const QString&)), this, SLOT(getOther(const QString&))); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~FFTSizeMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("FFTSizeMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int size); public slots: void get05() { emit whichTrigger(32); } void get06() { emit whichTrigger(64); } void get07() { emit whichTrigger(128); } void get08() { emit whichTrigger(256); } void get09() { emit whichTrigger(512); } void get10() { emit whichTrigger(1024); } void get11() { emit whichTrigger(2048); } void get12() { emit whichTrigger(4096); } void get13() { emit whichTrigger(8192); } void get14() { emit whichTrigger(16384); } void get15() { emit whichTrigger(32768); } void getOther(const QString &str) { int value = str.toInt(); emit whichTrigger(value); } private: QList d_act; OtherAction *d_other; }; /********************************************************************/ class FFTAverageMenu: public QMenu { Q_OBJECT public: FFTAverageMenu(QWidget *parent) : QMenu("FFT Average", parent) { d_act.push_back(new QAction("Off", this)); d_act.push_back(new QAction("High", this)); d_act.push_back(new QAction("Medium", this)); d_act.push_back(new QAction("Low", this)); d_act.push_back(new OtherAction(this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getOff())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getHigh())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getMedium())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getLow())); connect(d_act[4], SIGNAL(whichTrigger(const QString&)), this, SLOT(getOther(const QString&))); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~FFTAverageMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("FFTSizeMenu::getAction: which out of range.\n"); } signals: void whichTrigger(float alpha); public slots: void getOff() { emit whichTrigger(1.0); } void getHigh() { emit whichTrigger(0.05); } void getMedium() { emit whichTrigger(0.1); } void getLow() { emit whichTrigger(0.2); } void getOther(const QString &str) { float value = str.toFloat(); emit whichTrigger(value); } private: QList d_act; OtherAction *d_other; }; /********************************************************************/ class FFTWindowMenu: public QMenu { Q_OBJECT public: FFTWindowMenu(QWidget *parent) : QMenu("FFT Window", parent) { d_act.push_back(new QAction("None", this)); d_act.push_back(new QAction("Hamming", this)); d_act.push_back(new QAction("Hann", this)); d_act.push_back(new QAction("Blackman", this)); d_act.push_back(new QAction("Blackman-harris", this)); d_act.push_back(new QAction("Rectangular", this)); d_act.push_back(new QAction("Kaiser", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getNone())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getHamming())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getHann())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getBlackman())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getBlackmanharris())); connect(d_act[5], SIGNAL(triggered()), this, SLOT(getRectangular())); connect(d_act[6], SIGNAL(triggered()), this, SLOT(getKaiser())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } } ~FFTWindowMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("FFTWindowMenu::getAction: which out of range.\n"); } signals: void whichTrigger(const gr::filter::firdes::win_type type); public slots: void getNone() { emit whichTrigger(gr::filter::firdes::WIN_NONE); } void getHamming() { emit whichTrigger(gr::filter::firdes::WIN_HAMMING); } void getHann() { emit whichTrigger(gr::filter::firdes::WIN_HANN); } void getBlackman() { emit whichTrigger(gr::filter::firdes::WIN_BLACKMAN); } void getBlackmanharris() { emit whichTrigger(gr::filter::firdes::WIN_BLACKMAN_hARRIS); } void getRectangular() { emit whichTrigger(gr::filter::firdes::WIN_RECTANGULAR); } void getKaiser() { emit whichTrigger(gr::filter::firdes::WIN_KAISER); } private: QList d_act; int d_which; }; /********************************************************************/ class NPointsMenu: public QAction { Q_OBJECT public: NPointsMenu(QWidget *parent) : QAction("Number of Points", parent) { d_diag = new QDialog(parent); d_diag->setWindowTitle("Number of Points"); d_diag->setModal(true); d_text = new QLineEdit(); QGridLayout *layout = new QGridLayout(d_diag); QPushButton *btn_ok = new QPushButton(tr("OK")); QPushButton *btn_cancel = new QPushButton(tr("Cancel")); layout->addWidget(d_text, 0, 0, 1, 2); layout->addWidget(btn_ok, 1, 0); layout->addWidget(btn_cancel, 1, 1); connect(btn_ok, SIGNAL(clicked()), this, SLOT(getText())); connect(btn_cancel, SIGNAL(clicked()), d_diag, SLOT(close())); connect(this, SIGNAL(triggered()), this, SLOT(getTextDiag())); } ~NPointsMenu() {} void setDiagText(const int npts) { d_text->setText(QString().setNum(npts)); } signals: void whichTrigger(const int npts); public slots: void getTextDiag() { d_diag->show(); } private slots: void getText() { emit whichTrigger(d_text->text().toInt()); d_diag->accept(); } private: QDialog *d_diag; QLineEdit *d_text; }; /********************************************************************/ class ColorMapMenu: public QMenu { Q_OBJECT public: ColorMapMenu(int which, QWidget *parent) : QMenu("Color Map", parent), d_which(which) { d_act.push_back(new QAction("Multi-Color", this)); d_act.push_back(new QAction("White Hot", this)); d_act.push_back(new QAction("Black Hot", this)); d_act.push_back(new QAction("Incandescent", this)); d_act.push_back(new QAction("Other", this)); //d_act.push_back(new OtherDualAction("Min Intensity: ", "Max Intensity: ", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getMultiColor())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getWhiteHot())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getBlackHot())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getIncandescent())); connect(d_act[4], SIGNAL(triggered()), this, SLOT(getOther())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); addAction(a); } d_max_value = QColor("white"); d_min_value = QColor("white"); } ~ColorMapMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("ColorMapMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int which, const int type, const QColor &min_color=QColor(), const QColor &max_color=QColor()); public slots: void getMultiColor() { emit whichTrigger(d_which, INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR); } void getWhiteHot() { emit whichTrigger(d_which, INTENSITY_COLOR_MAP_TYPE_WHITE_HOT); } void getBlackHot() { emit whichTrigger(d_which, INTENSITY_COLOR_MAP_TYPE_BLACK_HOT); } void getIncandescent() { emit whichTrigger(d_which, INTENSITY_COLOR_MAP_TYPE_INCANDESCENT); } //void getOther(d_which, const QString &min_str, const QString &max_str) void getOther() { QMessageBox::information(this, "Set low and high intensities", "In the next windows, select the low and then the high intensity colors.", QMessageBox::Ok); d_min_value = QColorDialog::getColor(d_min_value, this); d_max_value = QColorDialog::getColor(d_max_value, this); emit whichTrigger(d_which, INTENSITY_COLOR_MAP_TYPE_USER_DEFINED, d_min_value, d_max_value); } private: QList d_act; OtherDualAction *d_other; QColor d_max_value, d_min_value; int d_which; }; /********************************************************************/ class TriggerModeMenu: public QMenu { Q_OBJECT public: TriggerModeMenu(QWidget *parent) : QMenu("Mode", parent) { d_grp = new QActionGroup(this); d_act.push_back(new QAction("Free", this)); d_act.push_back(new QAction("Auto", this)); d_act.push_back(new QAction("Normal", this)); d_act.push_back(new QAction("Tag", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getFree())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getAuto())); connect(d_act[2], SIGNAL(triggered()), this, SLOT(getNorm())); connect(d_act[3], SIGNAL(triggered()), this, SLOT(getTag())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); a->setCheckable(true); a->setActionGroup(d_grp); addAction(a); } } ~TriggerModeMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("TriggerModeMenu::getAction: which out of range.\n"); } QAction * getAction(gr::qtgui::trigger_mode mode) { switch(mode) { case gr::qtgui::TRIG_MODE_FREE: return d_act[0]; break; case gr::qtgui::TRIG_MODE_AUTO: return d_act[1]; break; case gr::qtgui::TRIG_MODE_NORM: return d_act[2]; break; case gr::qtgui::TRIG_MODE_TAG: return d_act[3]; break; default: throw std::runtime_error("TriggerModeMenu::getAction: unknown trigger mode.\n"); } } signals: void whichTrigger(gr::qtgui::trigger_mode mode); public slots: void getFree() { emit whichTrigger(gr::qtgui::TRIG_MODE_FREE); } void getAuto() { emit whichTrigger(gr::qtgui::TRIG_MODE_AUTO); } void getNorm() { emit whichTrigger(gr::qtgui::TRIG_MODE_NORM); } void getTag() { emit whichTrigger(gr::qtgui::TRIG_MODE_TAG); } private: QList d_act; QActionGroup *d_grp; }; /********************************************************************/ class TriggerSlopeMenu: public QMenu { Q_OBJECT public: TriggerSlopeMenu(QWidget *parent) : QMenu("Slope", parent) { d_grp = new QActionGroup(this); d_act.push_back(new QAction("Positive", this)); d_act.push_back(new QAction("Negative", this)); connect(d_act[0], SIGNAL(triggered()), this, SLOT(getPos())); connect(d_act[1], SIGNAL(triggered()), this, SLOT(getNeg())); QListIterator i(d_act); while(i.hasNext()) { QAction *a = i.next(); a->setCheckable(true); a->setActionGroup(d_grp); addAction(a); } } ~TriggerSlopeMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("TriggerSlopeMenu::getAction: which out of range.\n"); } QAction * getAction(gr::qtgui::trigger_slope slope) { switch(slope) { case gr::qtgui::TRIG_SLOPE_POS: return d_act[0]; break; case gr::qtgui::TRIG_SLOPE_NEG: return d_act[1]; break; default: throw std::runtime_error("TriggerSlopeMenu::getAction: unknown trigger slope.\n"); } } signals: void whichTrigger(gr::qtgui::trigger_slope slope); public slots: void getPos() { emit whichTrigger(gr::qtgui::TRIG_SLOPE_POS); } void getNeg() { emit whichTrigger(gr::qtgui::TRIG_SLOPE_NEG); } private: QList d_act; QActionGroup *d_grp; }; /********************************************************************/ class TriggerChannelMenu: public QMenu { Q_OBJECT public: TriggerChannelMenu(int nchans, QWidget *parent) : QMenu("Channel", parent) { d_grp = new QActionGroup(this); for(int i = 0; i < nchans; i++) { d_act.push_back(new QAction(QString().setNum(i), this)); d_act[i]->setCheckable(true); d_act[i]->setActionGroup(d_grp); addAction(d_act[i]); connect(d_act[i], SIGNAL(triggered()), this, SLOT(getChannel())); } } ~TriggerChannelMenu() {} int getNumActions() const { return d_act.size(); } QAction * getAction(int which) { if(which < d_act.size()) return d_act[which]; else throw std::runtime_error("TriggerChannelMenu::getAction: which out of range.\n"); } signals: void whichTrigger(int n); public slots: void getChannel() { QAction *a = d_grp->checkedAction(); int which = a->text().toInt(); emit whichTrigger(which); } private: QList d_act; QActionGroup *d_grp; }; /********************************************************************/ class PopupMenu: public QAction { Q_OBJECT public: PopupMenu(QString desc, QWidget *parent) : QAction(desc, parent) { d_diag = new QDialog(parent); d_diag->setWindowTitle(desc); d_diag->setModal(true); d_text = new QLineEdit(); QGridLayout *layout = new QGridLayout(d_diag); QPushButton *btn_ok = new QPushButton(tr("OK")); QPushButton *btn_cancel = new QPushButton(tr("Cancel")); layout->addWidget(d_text, 0, 0, 1, 2); layout->addWidget(btn_ok, 1, 0); layout->addWidget(btn_cancel, 1, 1); connect(btn_ok, SIGNAL(clicked()), this, SLOT(getText())); connect(btn_cancel, SIGNAL(clicked()), d_diag, SLOT(close())); connect(this, SIGNAL(triggered()), this, SLOT(getTextDiag())); } ~PopupMenu() {} void setText(QString s) { d_text->setText(s); } signals: void whichTrigger(const QString data); public slots: void getTextDiag() { d_diag->show(); } private slots: void getText() { emit whichTrigger(d_text->text()); d_diag->accept(); } private: QDialog *d_diag; QLineEdit *d_text; }; /********************************************************************/ #endif /* FORM_MENUS_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/constellationdisplayform.h0000664000175000017500000000346412237515112026756 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef CONSTELLATION_DISPLAY_FORM_H #define CONSTELLATION_DISPLAY_FORM_H #include #include #include #include #include #include /*! * \brief DisplayForm child for managing constellaton (I&Q) plots. * \ingroup qtgui_blk */ class QTGUI_API ConstellationDisplayForm : public DisplayForm { Q_OBJECT public: ConstellationDisplayForm(int nplots=1, QWidget* parent = 0); ~ConstellationDisplayForm(); ConstellationDisplayPlot* getPlot(); int getNPoints() const; public slots: void customEvent(QEvent * e); void setNPoints(const int); void setSampleRate(const QString &samprate); void setYaxis(double min, double max); void setXaxis(double min, double max); void autoScale(bool en); private slots: void newData(const QEvent*); private: QIntValidator* d_int_validator; int d_npoints; }; #endif /* CONSTELLATION_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/trigger_mode.h0000664000175000017500000000231312237515112024265 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TRIGGER_MODE_H #define INCLUDED_QTGUI_TRIGGER_MODE_H namespace gr { namespace qtgui { enum trigger_mode { TRIG_MODE_FREE, TRIG_MODE_AUTO, TRIG_MODE_NORM, TRIG_MODE_TAG, }; enum trigger_slope { TRIG_SLOPE_POS, TRIG_SLOPE_NEG, }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TRIGGER_MODE_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/plot_raster.h0000664000175000017500000000505212207440367024165 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef PLOT_TIMERASTER_H #define PLOT_TIMERASTER_H #include #include #include #if QWT_VERSION >= 0x060000 #include // doesn't seem necessary, but is... #include #endif class QwtColorMap; /*! * \brief A plot item, which displays a time raster. * \ingroup qtgui_blk * * \details * A time raster displays threedimenional data, where the 3rd dimension * (the intensity) is displayed using colors. The colors are calculated * from the values using a color map. * * \sa QwtRasterData, QwtColorMap */ class PlotTimeRaster: public QwtPlotRasterItem { public: explicit PlotTimeRaster(const QString &title = QString::null); virtual ~PlotTimeRaster(); const TimeRasterData* data()const; void setData(TimeRasterData *data); void setColorMap(const QwtColorMap *map); const QwtColorMap &colorMap() const; #if QWT_VERSION < 0x060000 virtual QwtDoubleRect boundingRect() const; virtual QSize rasterHint(const QwtDoubleRect &) const; virtual QwtDoubleInterval interval(Qt::Axis ax) const; #else virtual QwtInterval interval(Qt::Axis ax) const; #endif virtual int rtti() const; virtual void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &rect) const; protected: #if QWT_VERSION < 0x060000 QImage renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtDoubleRect &rect) const; #else QImage renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &rect, const QSize &size=QSize(0,0)) const; #endif private: class PrivateData; PrivateData *d_data; }; #endif gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/waterfalldisplayform.h0000664000175000017500000000502212245466767026075 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef WATERFALL_DISPLAY_FORM_H #define WATERFALL_DISPLAY_FORM_H #include #include #include #include #include #include /*! * \brief DisplayForm child for managing waterfall (spectrogram) plots. * \ingroup qtgui_blk */ class WaterfallDisplayForm : public DisplayForm { Q_OBJECT public: WaterfallDisplayForm(int nplots=1, QWidget* parent = 0); ~WaterfallDisplayForm(); WaterfallDisplayPlot* getPlot(); int getFFTSize() const; float getFFTAverage() const; gr::filter::firdes::win_type getFFTWindowType() const; int getColorMap(int which); int getAlpha(int which); double getMinIntensity(int which); double getMaxIntensity(int which); void clearData(); public slots: void customEvent(QEvent *e); void setSampleRate(const QString &samprate); void setFFTSize(const int); void setFFTAverage(const float); void setFFTWindowType(const gr::filter::firdes::win_type); void setFrequencyRange(const double centerfreq, const double bandwidth); void setIntensityRange(const double minIntensity, const double maxIntensity); void setAlpha(int which, int alpha); void setColorMap(int which, const int newType, const QColor lowColor=QColor("white"), const QColor highColor=QColor("white")); void autoScale(bool en=false); private slots: void newData(const QEvent *updateEvent); private: QIntValidator* d_int_validator; double d_samp_rate, d_center_freq; int d_fftsize; float d_fftavg; gr::filter::firdes::win_type d_fftwintype; double d_min_val; double d_max_val; }; #endif /* WATERFALL_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/const_sink_c.h0000664000175000017500000000655412207440367024313 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_CONST_SINK_C_H #define INCLUDED_QTGUI_CONST_SINK_C_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display the IQ constellation of multiple signals. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a complex * streams and plots them on an IQ constellation plot. */ class QTGUI_API const_sink_c : virtual public sync_block { public: // gr::qtgui::const_sink_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a complex PSD sink. * * \param size number of points to plot at once * \param name title for the plot * \param nconnections number of signals connected to sink * \param parent a QWidget parent object, if any */ static sptr make(int size, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_y_axis(double min, double max) = 0; virtual void set_x_axis(double min, double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &label) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, int style) = 0; virtual void set_line_marker(int which, int marker) = 0; virtual void set_nsamps(const int newsize) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_autoscale(bool en) = 0; virtual int nsamps() const = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_CONST_SINK_C_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/WaterfallDisplayPlot.h0000664000175000017500000000724512237515112025735 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef WATERFALL_DISPLAY_PLOT_H #define WATERFALL_DISPLAY_PLOT_H #include #include #include #include #include #include #include #if QWT_VERSION < 0x060000 #include #else #include #endif /*! * \brief QWidget for displaying waterfall (spectrogram) plots. * \ingroup qtgui_blk */ class WaterfallDisplayPlot: public DisplayPlot { Q_OBJECT Q_PROPERTY ( int intensity_color_map_type1 READ getIntensityColorMapType1 WRITE setIntensityColorMapType1 ) Q_PROPERTY ( QColor low_intensity_color READ getUserDefinedLowIntensityColor WRITE setUserDefinedLowIntensityColor ) Q_PROPERTY ( QColor high_intensity_color READ getUserDefinedHighIntensityColor WRITE setUserDefinedHighIntensityColor ) public: WaterfallDisplayPlot(int nplots, QWidget*); virtual ~WaterfallDisplayPlot(); void resetAxis(); void setFrequencyRange(const double, const double, const double units=1000.0, const std::string &strunits = "kHz"); double getStartFrequency() const; double getStopFrequency() const; void plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double timePerFFT, const gr::high_res_timer_type timestamp, const int droppedFrames); // to be removed void plotNewData(const double* dataPoints, const int64_t numDataPoints, const double timePerFFT, const gr::high_res_timer_type timestamp, const int droppedFrames); void setIntensityRange(const double minIntensity, const double maxIntensity); double getMinIntensity(int which) const; double getMaxIntensity(int which) const; void replot(void); void clearData(); int getIntensityColorMapType(int) const; int getIntensityColorMapType1() const; const QColor getUserDefinedLowIntensityColor() const; const QColor getUserDefinedHighIntensityColor() const; int getAlpha(int which); void setAlpha(int which, int alpha); public slots: void setIntensityColorMapType(const int, const int, const QColor, const QColor); void setIntensityColorMapType1(int); void setUserDefinedLowIntensityColor(QColor); void setUserDefinedHighIntensityColor(QColor); signals: void updatedLowerIntensityLevel(const double); void updatedUpperIntensityLevel(const double); private: void _updateIntensityRangeDisplay(); double d_start_frequency; double d_stop_frequency; int d_xaxis_multiplier; std::vector d_data; #if QWT_VERSION < 0x060000 std::vector d_spectrogram; #else std::vector d_spectrogram; #endif std::vector d_intensity_color_map_type; QColor d_user_defined_low_intensity_color; QColor d_user_defined_high_intensity_color; }; #endif /* WATERFALL_DISPLAY_PLOT_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/TimeRasterDisplayPlot.h0000664000175000017500000000557712207440367026107 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIMERASTER_DISPLAY_PLOT_H #define TIMERASTER_DISPLAY_PLOT_H #include #include #include #include #include #include #include #include #if QWT_VERSION < 0x060000 #include #else #include #endif /*! * \brief QWidget for time raster (time vs. time) plots. * \ingroup qtgui_blk */ class TimeRasterDisplayPlot: public DisplayPlot { Q_OBJECT public: TimeRasterDisplayPlot(int nplots, double samp_rate, double rows, double cols, QWidget*); virtual ~TimeRasterDisplayPlot(); void reset(); void setNumRows(double rows); void setNumCols(double cols); void setAlpha(int which, int alpha); void setSampleRate(double samprate); double numRows() const; double numCols() const; int getAlpha(int which); void setPlotDimensions(const double rows, const double cols, const double units, const std::string &strunits); void plotNewData(const std::vector dataPoints, const int64_t numDataPoints); void plotNewData(const double* dataPoints, const int64_t numDataPoints); void setIntensityRange(const double minIntensity, const double maxIntensity); void replot(void); int getIntensityColorMapType(int) const; void setIntensityColorMapType(const int, const int, const QColor, const QColor); const QColor getUserDefinedLowIntensityColor() const; const QColor getUserDefinedHighIntensityColor() const; double getMinIntensity(int which) const; double getMaxIntensity(int which) const; signals: void updatedLowerIntensityLevel(const double); void updatedUpperIntensityLevel(const double); private: void _updateIntensityRangeDisplay(); std::vector d_data; std::vector d_raster; double d_samp_rate; double d_rows, d_cols; std::vector d_color_map_type; QColor d_low_intensity; QColor d_high_intensity; }; #endif /* TIMERASTER_DISPLAY_PLOT_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/displayform.h0000664000175000017500000000652112237515112024154 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef DISPLAY_FORM_H #define DISPLAY_FORM_H #include #include #include #include #include #include #include #include /*! * \brief Base class for setting up and managing QTGUI plot forms. * \ingroup qtgui_blk */ class QTGUI_API DisplayForm : public QWidget { Q_OBJECT public: DisplayForm(int nplots=1, QWidget* parent = 0); ~DisplayForm(); virtual DisplayPlot* getPlot() = 0; void Reset(); bool isClosed() const; void enableMenu(bool en=true); public slots: void resizeEvent( QResizeEvent * e ); void mousePressEvent( QMouseEvent * e); virtual void customEvent( QEvent * e ) = 0; void closeEvent( QCloseEvent * e ); void setUpdateTime(double t); void setTitle(const QString &title); void setLineLabel(int which, const QString &label); void setLineColor(int which, const QString &color); void setLineWidth(int which, int width); void setLineStyle(int which, Qt::PenStyle style); void setLineMarker(int which, QwtSymbol::Style style); void setMarkerAlpha(int which, int alpha); QString title(); QString lineLabel(int which); QString lineColor(int which); int lineWidth(int which); Qt::PenStyle lineStyle(int which); QwtSymbol::Style lineMarker(int which); int markerAlpha(int which); virtual void setSampleRate(const QString &rate); void setStop(bool on); void setStop(); void setGrid(bool on); void saveFigure(); private slots: virtual void newData(const QEvent*) = 0; virtual void autoScale(bool) = 0; void updateGuiTimer(); void onPlotPointSelected(const QPointF p); signals: void plotPointSelected(const QPointF p, int type); protected: bool d_isclosed; int d_nplots; QGridLayout *d_layout; DisplayPlot* d_display_plot; bool d_system_specified_flag; QwtPlotGrid *d_grid; bool d_menu_on; QMenu *d_menu; QAction *d_stop_act; bool d_stop_state; QAction *d_grid_act; bool d_grid_state; QAction *d_autoscale_act; bool d_autoscale_state; QList d_lines_menu; QList d_line_title_act; QList d_line_color_menu; QList d_line_width_menu; QList d_line_style_menu; QList d_line_marker_menu; QList d_marker_alpha_menu; PopupMenu *d_samp_rate_act; QAction *d_save_act; QTimer *d_display_timer; double d_update_time; }; #endif /* DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/timerasterdisplayform.h0000664000175000017500000000451212237515112026252 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIMERASTER_DISPLAY_FORM_H #define TIMERASTER_DISPLAY_FORM_H #include #include #include #include #include #include /*! * \brief DisplayForm child for managing time raster plots. * \ingroup qtgui_blk */ class TimeRasterDisplayForm : public DisplayForm { Q_OBJECT public: TimeRasterDisplayForm(int nplots=1, double samp_rate=1, double rows=1, double cols=1, double zmax=1, QWidget* parent = 0); ~TimeRasterDisplayForm(); TimeRasterDisplayPlot* getPlot(); double numRows(); double numCols(); int getColorMap(int which); int getAlpha(int which); double getMinIntensity(int which); double getMaxIntensity(int which); public slots: void customEvent(QEvent *e); void setNumRows(double rows); void setNumCols(double cols); void setNumRows(QString rows); void setNumCols(QString cols); void setSampleRate(const double samprate); void setSampleRate(const QString &rate); void setIntensityRange(const double minIntensity, const double maxIntensity); void setColorMap(int which, const int newType, const QColor lowColor=QColor("white"), const QColor highColor=QColor("white")); void setAlpha(int which, int alpha); void autoScale(bool en=false); private slots: void newData(const QEvent *updateEvent); private: double d_min_val; double d_max_val; }; #endif /* TIMERASTER_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/sink_c.h0000664000175000017500000000650312207440367023077 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_SINK_C_H #define INCLUDED_QTGUI_SINK_C_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display freq, spec, time, and const plots. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes a complex stream and * plots it. The default action is to plot the signal as a PSD (FFT), * spectrogram (waterfall), time domain I&Q, and constellation (I * vs. Q) plots. The plots may be turned off by setting the * appropriate boolean value in the constructor to False. */ class QTGUI_API sink_c : virtual public block { public: // gr::qtgui::sink_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a complex qtgui sink. * * \param fftsize size of the FFT to compute and display * \param wintype type of window to apply (see gnuradio/filter/firdes.h) * \param fc center frequency of signal (use for x-axis labels) * \param bw bandwidth of signal (used to set x-axis labels) * \param name title for the plot * \param plotfreq Toggle frequency plot on/off * \param plotwaterfall Toggle waterfall plot on/off * \param plottime Toggle time plot on/off * \param plotconst Toggle constellation plot on/off * \param parent a QWidget parent object, if any */ static sptr make(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_fft_size(const int fftsize) = 0; virtual int fft_size() const = 0; virtual void set_frequency_range(const double centerfreq, const double bandwidth) = 0; virtual void set_fft_power_db(double min, double max) = 0; //void set_time_domain_axis(double min, double max); //void set_constellation_axis(double xmin, double xmax, // double ymin, double ymax); //void set_constellation_pen_size(int size); virtual void set_update_time(double t) = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_SINK_C_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/freq_sink_f.h0000664000175000017500000001015312207440367024113 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_FREQ_SINK_F_H #define INCLUDED_QTGUI_FREQ_SINK_F_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals in frequency. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a floating * point streams and plots the PSD. Each signal is plotted with a * different color, and the \a set_title and \a set_color * functions can be used to change the lable and color for a given * input number. */ class QTGUI_API freq_sink_f : virtual public sync_block { public: // gr::qtgui::freq_sink_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a floating point PSD sink. * * \param fftsize size of the FFT to compute and display * \param wintype type of window to apply (see gnuradio/filter/firdes.h) * \param fc center frequency of signal (use for x-axis labels) * \param bw bandwidth of signal (used to set x-axis labels) * \param name title for the plot * \param nconnections number of signals connected to sink * \param parent a QWidget parent object, if any */ static sptr make(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_fft_size(const int fftsize) = 0; virtual int fft_size() const = 0; virtual void set_fft_average(const float fftavg) = 0; virtual float fft_average() const = 0; virtual void set_fft_window(const gr::filter::firdes::win_type win) = 0; virtual gr::filter::firdes::win_type fft_window() = 0; virtual void set_frequency_range(const double centerfreq, const double bandwidth) = 0; virtual void set_y_axis(double min, double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &label) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, int style) = 0; virtual void set_line_marker(int which, int marker) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; virtual void enable_autoscale(bool en=true) = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_FREQ_SINK_F_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/waterfall_sink_c.h0000664000175000017500000001035412207440367025137 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_WATERFALL_SINK_C_H #define INCLUDED_QTGUI_WATERFALL_SINK_C_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals on a * waterfall (spectrogram) plot. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a complex * streams and plots a waterfall (spectrogram) plot. * * Note that unlike the other qtgui sinks, this one does not * support multiple input streams. We have yet to figure out a * good way to display multiple, independent signals on this kind * of a plot. If there are any suggestions or examples of this, we * would love to see them. Otherwise, to display multiple signals * here, it's probably best to sum the signals together and * connect that here. */ class QTGUI_API waterfall_sink_c : virtual public sync_block { public: // gr::qtgui::waterfall_sink_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a complex waterfall sink. * * \param size size of the FFT to compute and display * \param wintype type of window to apply (see gnuradio/filter/firdes.h) * \param fc center frequency of signal (use for x-axis labels) * \param bw bandwidth of signal (used to set x-axis labels) * \param name title for the plot * \param nconnections number of signals to be connected to the sink * \param parent a QWidget parent object, if any */ static sptr make(int size, int wintype, double fc, double bw, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void clear_data() = 0; virtual void set_fft_size(const int fftsize) = 0; virtual int fft_size() const = 0; virtual void set_fft_average(const float fftavg) = 0; virtual float fft_average() const = 0; virtual void set_fft_window(const gr::filter::firdes::win_type win) = 0; virtual gr::filter::firdes::win_type fft_window() = 0; virtual void set_frequency_range(const double centerfreq, const double bandwidth) = 0; virtual void set_intensity_range(const double min, const double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &line) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_color_map(int which, const int color) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual double line_alpha(int which) = 0; virtual int color_map(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void auto_scale() = 0; virtual double min_intensity(int which) = 0; virtual double max_intensity(int which) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_WATERFALL_SINK_C_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/FrequencyDisplayPlot.h0000664000175000017500000001346112237515112025752 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef FREQUENCY_DISPLAY_PLOT_HPP #define FREQUENCY_DISPLAY_PLOT_HPP #include #include #include #include /*! * \brief QWidget for displaying frequency domain (PSD) plots. * \ingroup qtgui_blk */ class FrequencyDisplayPlot: public DisplayPlot { Q_OBJECT Q_PROPERTY ( QColor min_fft_color READ getMinFFTColor WRITE setMinFFTColor ) Q_PROPERTY ( QColor max_fft_color READ getMaxFFTColor WRITE setMaxFFTColor ) Q_PROPERTY ( bool min_fft_visible READ getMinFFTVisible WRITE setMinFFTVisible ) Q_PROPERTY ( bool max_fft_visible READ getMaxFFTVisible WRITE setMaxFFTVisible ) Q_PROPERTY ( QColor marker_lower_intensity_color READ getMarkerLowerIntensityColor WRITE setMarkerLowerIntensityColor ) Q_PROPERTY ( bool marker_lower_intensity_visible READ getMarkerLowerIntensityVisible WRITE setMarkerLowerIntensityVisible ) Q_PROPERTY ( QColor marker_upper_intensity_color READ getMarkerUpperIntensityColor WRITE setMarkerUpperIntensityColor ) Q_PROPERTY ( bool marker_upper_intensity_visible READ getMarkerUpperIntensityVisible WRITE setMarkerUpperIntensityVisible ) Q_PROPERTY ( QColor marker_peak_amplitude_color READ getMarkerPeakAmplitudeColor WRITE setMarkerPeakAmplitudeColor ) Q_PROPERTY ( QColor marker_noise_floor_amplitude_color READ getMarkerNoiseFloorAmplitudeColor WRITE setMarkerNoiseFloorAmplitudeColor ) Q_PROPERTY ( bool marker_noise_floor_amplitude_visible READ getMarkerNoiseFloorAmplitudeVisible WRITE setMarkerNoiseFloorAmplitudeVisible ) Q_PROPERTY ( QColor marker_CF_color READ getMarkerCFColor WRITE setMarkerCFColor ) public: FrequencyDisplayPlot(int nplots, QWidget*); virtual ~FrequencyDisplayPlot(); void setFrequencyRange(const double, const double, const double units=1000.0, const std::string &strunits = "kHz"); double getStartFrequency()const; double getStopFrequency()const; void plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double noiseFloorAmplitude, const double peakFrequency, const double peakAmplitude, const double timeInterval); // Old method to be removed void plotNewData(const double* dataPoints, const int64_t numDataPoints, const double noiseFloorAmplitude, const double peakFrequency, const double peakAmplitude, const double timeInterval); void clearMaxData(); void clearMinData(); void replot(); void setYaxis(double min, double max); void setTraceColour (QColor); void setBGColour (QColor c); void showCFMarker (const bool); const bool getMaxFFTVisible() const; const bool getMinFFTVisible() const; const QColor getMinFFTColor() const; const QColor getMaxFFTColor() const; const QColor getMarkerLowerIntensityColor () const; const bool getMarkerLowerIntensityVisible () const; const QColor getMarkerUpperIntensityColor () const; const bool getMarkerUpperIntensityVisible () const; const QColor getMarkerPeakAmplitudeColor () const; const bool getMarkerNoiseFloorAmplitudeVisible () const; const QColor getMarkerNoiseFloorAmplitudeColor () const; const QColor getMarkerCFColor () const; public slots: void setMaxFFTVisible(const bool); void setMinFFTVisible(const bool); void setMinFFTColor (QColor c); void setMaxFFTColor (QColor c); void setMarkerLowerIntensityColor (QColor c); void setMarkerLowerIntensityVisible (bool visible); void setMarkerUpperIntensityColor (QColor c); void setMarkerUpperIntensityVisible (bool visible); void setMarkerPeakAmplitudeColor (QColor c); void setMarkerNoiseFloorAmplitudeVisible (bool visible); void setMarkerNoiseFloorAmplitudeColor (QColor c); void setMarkerCFColor (QColor c); void setLowerIntensityLevel(const double); void setUpperIntensityLevel(const double); void onPickerPointSelected(const QwtDoublePoint & p); void onPickerPointSelected6(const QPointF & p); void setAutoScale(bool state); private: void _resetXAxisPoints(); void _autoScale(double bottom, double top); std::vector d_ydata; QwtPlotCurve* d_min_fft_plot_curve; QwtPlotCurve* d_max_fft_plot_curve; QColor d_min_fft_color; bool d_min_fft_visible; QColor d_max_fft_color; bool d_max_fft_visible; QColor d_marker_lower_intensity_color; bool d_marker_lower_intensity_visible; QColor d_marker_upper_intensity_color; bool d_marker_upper_intensity_visible; QColor d_marker_peak_amplitude_color; QColor d_marker_noise_floor_amplitude_color; bool d_marker_noise_floor_amplitude_visible; QColor d_marker_cf_color; double d_start_frequency; double d_stop_frequency; double d_ymax; double d_ymin; QwtPlotMarker* d_lower_intensity_marker; QwtPlotMarker* d_upper_intensity_marker; QwtPlotMarker *d_marker_peak_amplitude; QwtPlotMarker *d_marker_noise_floor_amplitude; QwtPlotMarker *d_marker_cf; double* d_xdata; int d_xdata_multiplier; double* d_min_fft_data; double* d_max_fft_data; double d_peak_frequency; double d_peak_amplitude; double d_noise_floor_amplitude; }; #endif /* FREQUENCY_DISPLAY_PLOT_HPP */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/qtgui_types.h0000664000175000017500000000770712207440367024215 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef QTGUI_TYPES_H #define QTGUI_TYPES_H #include #include #include class FreqOffsetAndPrecisionClass { public: FreqOffsetAndPrecisionClass(const int freqPrecision) { _frequencyPrecision = freqPrecision; _centerFrequency = 0; } virtual ~FreqOffsetAndPrecisionClass() { } virtual unsigned int getFrequencyPrecision() const { return _frequencyPrecision; } virtual void setFrequencyPrecision(const unsigned int newPrecision) { _frequencyPrecision = newPrecision; } virtual double getCenterFrequency() const { return _centerFrequency; } virtual void setCenterFrequency(const double newFreq) { _centerFrequency = newFreq; } protected: private: unsigned int _frequencyPrecision; double _centerFrequency; }; class TimeScaleData { public: TimeScaleData() { _zeroTime = 0; _secondsPerLine = 1.0; } virtual ~TimeScaleData() { } virtual gr::high_res_timer_type getZeroTime() const { return _zeroTime; } virtual void setZeroTime(const gr::high_res_timer_type newTime) { _zeroTime = newTime - gr::high_res_timer_epoch(); } virtual void setSecondsPerLine(const double newTime) { _secondsPerLine = newTime; } virtual double getSecondsPerLine() const { return _secondsPerLine; } protected: private: gr::high_res_timer_type _zeroTime; double _secondsPerLine; }; /*********************************************************************** * Text scale widget to provide X (freq) axis text **********************************************************************/ class FreqDisplayScaleDraw: public QwtScaleDraw, FreqOffsetAndPrecisionClass { public: FreqDisplayScaleDraw(const unsigned int precision) : QwtScaleDraw(), FreqOffsetAndPrecisionClass(precision) { } virtual QwtText label(double value) const { return QString("%1").arg(value, 0, 'f', getFrequencyPrecision()); } virtual void initiateUpdate(void) { invalidateCache(); } protected: private: }; enum{ INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR = 0, INTENSITY_COLOR_MAP_TYPE_WHITE_HOT = 1, INTENSITY_COLOR_MAP_TYPE_BLACK_HOT = 2, INTENSITY_COLOR_MAP_TYPE_INCANDESCENT = 3, INTENSITY_COLOR_MAP_TYPE_USER_DEFINED = 4 }; class ColorMap_MultiColor: public QwtLinearColorMap { public: ColorMap_MultiColor(): QwtLinearColorMap(Qt::darkCyan, Qt::white) { addColorStop(0.25, Qt::cyan); addColorStop(0.5, Qt::yellow); addColorStop(0.75, Qt::red); } }; class ColorMap_WhiteHot: public QwtLinearColorMap { public: ColorMap_WhiteHot(): QwtLinearColorMap(Qt::black, Qt::white) { } }; class ColorMap_BlackHot: public QwtLinearColorMap { public: ColorMap_BlackHot(): QwtLinearColorMap(Qt::white, Qt::black) { } }; class ColorMap_Incandescent: public QwtLinearColorMap { public: ColorMap_Incandescent(): QwtLinearColorMap(Qt::black, Qt::white) { addColorStop(0.5, Qt::darkRed); } }; class ColorMap_UserDefined: public QwtLinearColorMap { public: ColorMap_UserDefined(QColor low, QColor high): QwtLinearColorMap(low, high) { } }; #endif //QTGUI_TYPES_H gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/time_sink_c.h0000664000175000017500000001023412237515112024103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_SINK_C_H #define INCLUDED_QTGUI_TIME_SINK_C_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals in time. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a complex * streams and plots them in the time domain. For each signal, both * the signal's I and Q parts are plotted, and they are all plotted * with a different color, and the \a set_title and \a set_color * functions can be used to change the lable and color for a given * input number. */ class QTGUI_API time_sink_c : virtual public sync_block { public: // gr::qtgui::time_sink_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Build complex time sink * * \param size number of points to plot at once * \param samp_rate sample rate (used to set x-axis labels) * \param name title for the plot * \param nconnections number of signals connected to sink * \param parent a QWidget parent object, if any */ static sptr make(int size, double samp_rate, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_y_axis(double min, double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &label) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, int style) = 0; virtual void set_line_marker(int which, int marker) = 0; virtual void set_nsamps(const int newsize) = 0; virtual void set_samp_rate(const double samp_rate) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_trigger_mode(trigger_mode mode, trigger_slope slope, float level, float delay, int channel, const std::string &tag_key="") = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; virtual void enable_autoscale(bool en=true) = 0; virtual void enable_stem_plot(bool en=true) = 0; virtual void enable_semilogx(bool en=true) = 0; virtual void enable_semilogy(bool en=true) = 0; virtual void enable_tags(int which, bool en) = 0; virtual int nsamps() const = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_SINK_C_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/histogramdisplayform.h0000664000175000017500000000412112237515112026064 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef HISTOGRAM_DISPLAY_FORM_H #define HISTOGRAM_DISPLAY_FORM_H #include #include #include #include #include /*! * \brief DisplayForm child for managing histogram domain plots. * \ingroup qtgui_blk */ class HistogramDisplayForm : public DisplayForm { Q_OBJECT public: HistogramDisplayForm(int nplots=1, QWidget* parent = 0); ~HistogramDisplayForm(); HistogramDisplayPlot* getPlot(); int getNPoints() const; public slots: void customEvent(QEvent * e); void setYaxis(double min, double max); void setXaxis(double min, double max); void setNPoints(const int); void autoScale(bool en); void setSemilogx(bool en); void setSemilogy(bool en); void setNumBins(const int); void setAccumulate(bool en); void autoScaleX(); private slots: void newData(const QEvent*); private: QIntValidator* d_int_validator; double d_startFrequency; double d_stopFrequency; int d_npoints; bool d_semilogx; bool d_semilogy; NPointsMenu *d_nptsmenu; NPointsMenu *d_nbinsmenu; QAction *d_semilogxmenu; QAction *d_semilogymenu; QAction *d_autoscalex_act; bool d_autoscalex_state; }; #endif /* HISTOGRAM_DISPLAY_FORM_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/timeRasterGlobalData.h0000664000175000017500000000372312207440367025664 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIMERASTER_GLOBAL_DATA_HPP #define TIMERASTER_GLOBAL_DATA_HPP #include #include #if QWT_VERSION >= 0x060000 #include // doesn't seem necessary, but is... #include #endif class TimeRasterData: public QwtRasterData { public: TimeRasterData(const double rows, const double cols); virtual ~TimeRasterData(); virtual void reset(); virtual void copy(const TimeRasterData*); virtual void resizeData(const double rows, const double cols); virtual QwtRasterData *copy() const; #if QWT_VERSION < 0x060000 virtual QwtDoubleInterval range() const; virtual void setRange(const QwtDoubleInterval&); #endif virtual double value(double x, double y) const; virtual double getNumCols()const; virtual double getNumRows()const; virtual void addData(const double*, const int); void incrementResidual(); protected: double* d_data; double d_rows, d_cols; double d_resid; int d_nitems, d_totalitems, d_data_size; #if QWT_VERSION < 0x060000 QwtDoubleInterval d_intensityRange; #else QwtInterval d_intensityRange; #endif private: }; #endif /* TIMERASTER_GLOBAL_DATA_HPP */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/utils.h0000664000175000017500000000306012207440367022764 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_UTILS_H #define INCLUDED_QTGUI_UTILS_H #include #include #include #include class QTGUI_API QwtDblClickPlotPicker: public QwtPlotPicker { public: QwtDblClickPlotPicker(QwtPlotCanvas *); ~QwtDblClickPlotPicker(); virtual QwtPickerMachine * stateMachine(int) const; }; class QTGUI_API QwtPickerDblClickPointMachine: public QwtPickerMachine { public: QwtPickerDblClickPointMachine(); ~QwtPickerDblClickPointMachine(); #if QWT_VERSION < 0x060000 virtual CommandList #else virtual QList #endif transition( const QwtEventPattern &eventPattern, const QEvent *e); }; #endif /* INCLUDED_QTGUI_UTILS_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/plot_waterfall.h0000664000175000017500000000464112207440367024651 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef PLOT_WATERFALL_H #define PLOT_WATERFALL_H #include #include #include #if QWT_VERSION >= 0x060000 #include // doesn't seem necessary, but is... #include #endif class QwtColorMap; /*! * \brief A plot item, which displays a waterfall spectrogram * \ingroup qtgui_blk * * \details * A waterfall displays threedimenional data, where the 3rd dimension * (the intensity) is displayed using colors. The colors are calculated * from the values using a color map. * * \sa QwtRasterData, QwtColorMap */ class PlotWaterfall: public QwtPlotRasterItem { public: explicit PlotWaterfall(WaterfallData* data, const QString &title = QString::null); virtual ~PlotWaterfall(); const WaterfallData* data()const; void setColorMap(const QwtColorMap &); const QwtColorMap &colorMap() const; #if QWT_VERSION < 0x060000 virtual QwtDoubleRect boundingRect() const; virtual QSize rasterHint(const QwtDoubleRect &) const; #endif virtual int rtti() const; virtual void draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &rect) const; protected: #if QWT_VERSION < 0x060000 QImage renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtDoubleRect &rect) const; #else QImage renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &rect, const QSize &size=QSize(0,0)) const; #endif private: class PrivateData; PrivateData *d_data; }; #endif gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/TimeDomainDisplayPlot.h0000664000175000017500000000422212237515112026032 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIME_DOMAIN_DISPLAY_PLOT_H #define TIME_DOMAIN_DISPLAY_PLOT_H #include #include #include #include #include /*! * \brief QWidget for displaying time domain plots. * \ingroup qtgui_blk */ class TimeDomainDisplayPlot: public DisplayPlot { Q_OBJECT public: TimeDomainDisplayPlot(int nplots, QWidget*); virtual ~TimeDomainDisplayPlot(); void plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double timeInterval, const std::vector< std::vector > &tags \ = std::vector< std::vector >()); void replot(); void stemPlot(bool en); public slots: void setSampleRate(double sr, double units, const std::string &strunits); void setAutoScale(bool state); void setSemilogx(bool en); void setSemilogy(bool en); void legendEntryChecked(QwtPlotItem *plotItem, bool on); void enableTagMarker(int which, bool en); private: void _resetXAxisPoints(); void _autoScale(double bottom, double top); std::vector d_ydata; double* d_xdata; double d_sample_rate; bool d_semilogx; bool d_semilogy; std::vector< std::vector > d_tag_markers; std::vector d_tag_markers_en; }; #endif /* TIME_DOMAIN_DISPLAY_PLOT_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/freq_sink_c.h0000664000175000017500000001013612207440367024111 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_FREQ_SINK_C_H #define INCLUDED_QTGUI_FREQ_SINK_C_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals in frequency. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a complex * streams and plots the PSD. Each signal is plotted with a * different color, and the \a set_title and \a set_color * functions can be used to change the lable and color for a given * input number. */ class QTGUI_API freq_sink_c : virtual public sync_block { public: // gr::qtgui::freq_sink_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a complex PSD sink. * * \param fftsize size of the FFT to compute and display * \param wintype type of window to apply (see gnuradio/filter/firdes.h) * \param fc center frequency of signal (use for x-axis labels) * \param bw bandwidth of signal (used to set x-axis labels) * \param name title for the plot * \param nconnections number of signals connected to sink * \param parent a QWidget parent object, if any */ static sptr make(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_fft_size(const int fftsize) = 0; virtual int fft_size() const = 0; virtual void set_fft_average(const float fftavg) = 0; virtual float fft_average() const = 0; virtual void set_fft_window(const gr::filter::firdes::win_type win) = 0; virtual gr::filter::firdes::win_type fft_window() = 0; virtual void set_frequency_range(const double centerfreq, const double bandwidth) = 0; virtual void set_y_axis(double min, double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &label) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, int style) = 0; virtual void set_line_marker(int which, int marker) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; virtual void enable_autoscale(bool en=true) = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_FREQ_SINK_C_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/api.h0000664000175000017500000000203112207440367022372 0ustar jcorganjcorgan/* * Copyright 2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_API_H #define INCLUDED_QTGUI_API_H #include #ifdef gnuradio_qtgui_EXPORTS # define QTGUI_API __GR_ATTR_EXPORT #else # define QTGUI_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_QTGUI_API_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/time_raster_sink_b.h0000664000175000017500000001045712207440367025477 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_RASTER_SINK_B_H #define INCLUDED_QTGUI_TIME_RASTER_SINK_B_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals on a * time_raster plot. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink that takes in byte * streams and plots a time_raster (spectrogram) plot. * * Input stream: This expects a bit stream (0, 1 in the LSB of a * byte). It will display packed bytes but the display will have * to be autoscaled. */ class QTGUI_API time_raster_sink_b : virtual public sync_block { public: // gr::qtgui::time_raster_sink_b::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a bit time raster sink. * * \param samp_rate sample rate of signal * \param cols number of cols to plot * \param rows number of rows to plot * \param mult vector of floats as a scaling multiplier for each input stream * \param offset vector of floats as an offset for each input stream * \param name title for the plot * \param nconnections number of streams connected * \param parent a QWidget parent object, if any */ static sptr make(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &lable) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, Qt::PenStyle style) = 0; virtual void set_line_marker(int which, QwtSymbol::Style marker) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_color_map(int which, const int color) = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual int color_map(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void set_samp_rate(const double samp_rate) = 0; virtual void set_num_rows(double rows) = 0; virtual void set_num_cols(double cols) = 0; virtual double num_rows() = 0; virtual double num_cols() = 0; virtual void set_multiplier(const std::vector &mult) = 0; virtual void set_offset(const std::vector &offset) = 0; virtual void set_intensity_range(float min, float max) = 0; virtual void enable_menu(bool en) = 0; virtual void enable_grid(bool en) = 0; virtual void enable_autoscale(bool en) = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_RASTER_SINK_B_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/sink_f.h0000664000175000017500000000643612207440367023107 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_SINK_F_H #define INCLUDED_QTGUI_SINK_F_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display freq, spec, and time. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes a float stream and * plots it. The default action is to plot the signal as a PSD (FFT), * spectrogram (waterfall), and time domain plots. The plots may be * turned off by setting the appropriate boolean value in the * constructor to False. */ class QTGUI_API sink_f : virtual public block { public: // gr::qtgui::sink_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a floating point qtgui sink. * * \param fftsize size of the FFT to compute and display * \param wintype type of window to apply (see gnuradio/filter/firdes.h) * \param fc center frequency of signal (use for x-axis labels) * \param bw bandwidth of signal (used to set x-axis labels) * \param name title for the plot * \param plotfreq Toggle frequency plot on/off * \param plotwaterfall Toggle waterfall plot on/off * \param plottime Toggle time plot on/off * \param plotconst Toggle constellation plot on/off * \param parent a QWidget parent object, if any */ static sptr make(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_fft_size(const int fftsize) = 0; virtual int fft_size() const = 0; virtual void set_frequency_range(const double centerfreq, const double bandwidth) = 0; virtual void set_fft_power_db(double min, double max) = 0; //void set_time_domain_axis(double min, double max); //void set_constellation_axis(double xmin, double xmax, // double ymin, double ymax); //void set_constellation_pen_size(int size); virtual void set_update_time(double t) = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_SINK_F_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/spectrumUpdateEvents.h0000664000175000017500000001625612237515112026023 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef SPECTRUM_UPDATE_EVENTS_H #define SPECTRUM_UPDATE_EVENTS_H #include #include #include #include #include #include #include #include static const int SpectrumUpdateEventType = 10005; static const int SpectrumWindowCaptionEventType = 10008; static const int SpectrumWindowResetEventType = 10009; static const int SpectrumFrequencyRangeEventType = 10010; class SpectrumUpdateEvent:public QEvent{ public: SpectrumUpdateEvent(const float* fftPoints, const uint64_t numFFTDataPoints, const double* realTimeDomainPoints, const double* imagTimeDomainPoints, const uint64_t numTimeDomainDataPoints, const gr::high_res_timer_type dataTimestamp, const bool repeatDataFlag, const bool lastOfMultipleUpdateFlag, const gr::high_res_timer_type generatedTimestamp, const int droppedFFTFrames); ~SpectrumUpdateEvent(); const float* getFFTPoints() const; const double* getRealTimeDomainPoints() const; const double* getImagTimeDomainPoints() const; uint64_t getNumFFTDataPoints() const; uint64_t getNumTimeDomainDataPoints() const; gr::high_res_timer_type getDataTimestamp() const; bool getRepeatDataFlag() const; bool getLastOfMultipleUpdateFlag() const; gr::high_res_timer_type getEventGeneratedTimestamp() const; int getDroppedFFTFrames() const; protected: private: float* _fftPoints; double* _realDataTimeDomainPoints; double* _imagDataTimeDomainPoints; uint64_t _numFFTDataPoints; uint64_t _numTimeDomainDataPoints; gr::high_res_timer_type _dataTimestamp; bool _repeatDataFlag; bool _lastOfMultipleUpdateFlag; gr::high_res_timer_type _eventGeneratedTimestamp; int _droppedFFTFrames; }; class SpectrumWindowCaptionEvent:public QEvent{ public: SpectrumWindowCaptionEvent(const QString&); ~SpectrumWindowCaptionEvent(); QString getLabel(); protected: private: QString _labelString; }; class SpectrumWindowResetEvent:public QEvent{ public: SpectrumWindowResetEvent(); ~SpectrumWindowResetEvent(); protected: private: }; class SpectrumFrequencyRangeEvent:public QEvent{ public: SpectrumFrequencyRangeEvent(const double, const double, const double); ~SpectrumFrequencyRangeEvent(); double GetCenterFrequency()const; double GetStartFrequency()const; double GetStopFrequency()const; protected: private: double _centerFrequency; double _startFrequency; double _stopFrequency; }; class TimeUpdateEvent: public QEvent { public: TimeUpdateEvent(const std::vector timeDomainPoints, const uint64_t numTimeDomainDataPoints, const std::vector< std::vector > tags); ~TimeUpdateEvent(); int which() const; const std::vector getTimeDomainPoints() const; uint64_t getNumTimeDomainDataPoints() const; bool getRepeatDataFlag() const; const std::vector< std::vector > getTags() const; static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: size_t _nplots; std::vector _dataTimeDomainPoints; uint64_t _numTimeDomainDataPoints; std::vector< std::vector > _tags; }; /********************************************************************/ class FreqUpdateEvent: public QEvent { public: FreqUpdateEvent(const std::vector dataPoints, const uint64_t numDataPoints); ~FreqUpdateEvent(); int which() const; const std::vector getPoints() const; uint64_t getNumDataPoints() const; bool getRepeatDataFlag() const; static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: size_t _nplots; std::vector _dataPoints; uint64_t _numDataPoints; }; /********************************************************************/ class QTGUI_API ConstUpdateEvent: public QEvent { public: ConstUpdateEvent(const std::vector realDataPoints, const std::vector imagDataPoints, const uint64_t numDataPoints); ~ConstUpdateEvent(); int which() const; const std::vector getRealPoints() const; const std::vector getImagPoints() const; uint64_t getNumDataPoints() const; bool getRepeatDataFlag() const; static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: size_t _nplots; std::vector _realDataPoints; std::vector _imagDataPoints; uint64_t _numDataPoints; }; /********************************************************************/ class WaterfallUpdateEvent: public QEvent { public: WaterfallUpdateEvent(const std::vector dataPoints, const uint64_t numDataPoints, const gr::high_res_timer_type dataTimestamp); ~WaterfallUpdateEvent(); int which() const; const std::vector getPoints() const; uint64_t getNumDataPoints() const; bool getRepeatDataFlag() const; gr::high_res_timer_type getDataTimestamp() const; static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: size_t _nplots; std::vector _dataPoints; uint64_t _numDataPoints; gr::high_res_timer_type _dataTimestamp; }; /********************************************************************/ class TimeRasterUpdateEvent: public QEvent { public: TimeRasterUpdateEvent(const std::vector dataPoints, const uint64_t numDataPoints); ~TimeRasterUpdateEvent(); int which() const; const std::vector getPoints() const; uint64_t getNumDataPoints() const; bool getRepeatDataFlag() const; static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: size_t _nplots; std::vector _dataPoints; uint64_t _numDataPoints; }; /********************************************************************/ class HistogramUpdateEvent: public QEvent { public: HistogramUpdateEvent(const std::vector points, const uint64_t npoints); ~HistogramUpdateEvent(); int which() const; const std::vector getDataPoints() const; uint64_t getNumDataPoints() const; bool getRepeatDataFlag() const; static QEvent::Type Type() { return QEvent::Type(SpectrumUpdateEventType); } protected: private: size_t _nplots; std::vector _points; uint64_t _npoints; }; #endif /* SPECTRUM_UPDATE_EVENTS_H */ gnuradio-3.7.2.1/gr-qtgui/include/gnuradio/qtgui/time_sink_f.h0000664000175000017500000001012212237515112024102 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_SINK_F_H #define INCLUDED_QTGUI_TIME_SINK_F_H #include #include #include #include #include namespace gr { namespace qtgui { /*! * \brief A graphical sink to display multiple signals in time. * \ingroup instrumentation_blk * \ingroup qtgui_blk * * \details * This is a QT-based graphical sink the takes set of a float streams * and plots them in the time domain. Each signal is plotted with a * different color, and the \a set_title and \a set_color functions * can be used to change the lable and color for a given input number. */ class QTGUI_API time_sink_f : virtual public sync_block { public: // gr::qtgui::time_sink_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Build floating point time sink * * \param size number of points to plot at once * \param samp_rate sample rate (used to set x-axis labels) * \param name title for the plot * \param nconnections number of signals connected to sink * \param parent a QWidget parent object, if any */ static sptr make(int size, double samp_rate, const std::string &name, int nconnections=1, QWidget *parent=NULL); virtual void exec_() = 0; virtual PyObject* pyqwidget() = 0; virtual void set_y_axis(double min, double max) = 0; virtual void set_update_time(double t) = 0; virtual void set_title(const std::string &title) = 0; virtual void set_line_label(int which, const std::string &line) = 0; virtual void set_line_color(int which, const std::string &color) = 0; virtual void set_line_width(int which, int width) = 0; virtual void set_line_style(int which, int style) = 0; virtual void set_line_marker(int which, int marker) = 0; virtual void set_nsamps(const int newsize) = 0; virtual void set_samp_rate(const double samp_rate) = 0; virtual void set_line_alpha(int which, double alpha) = 0; virtual void set_trigger_mode(trigger_mode mode, trigger_slope slope, float level, float delay, int channel, const std::string &tag_key="") = 0; virtual std::string title() = 0; virtual std::string line_label(int which) = 0; virtual std::string line_color(int which) = 0; virtual int line_width(int which) = 0; virtual int line_style(int which) = 0; virtual int line_marker(int which) = 0; virtual double line_alpha(int which) = 0; virtual void set_size(int width, int height) = 0; virtual void enable_menu(bool en=true) = 0; virtual void enable_grid(bool en=true) = 0; virtual void enable_autoscale(bool en=true) = 0; virtual void enable_stem_plot(bool en=true) = 0; virtual void enable_semilogx(bool en=true) = 0; virtual void enable_semilogy(bool en=true) = 0; virtual void enable_tags(int which, bool en) = 0; virtual int nsamps() const = 0; virtual void reset() = 0; QApplication *d_qApplication; }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_SINK_F_H */ gnuradio-3.7.2.1/gr-qtgui/grc/0000755000175000017500000000000012245466767015657 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/grc/CMakeLists.txt0000644000175000017500000000170411744612271020403 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "qtgui_python") gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_const_sink_x.xml0000664000175000017500000000501212207440367022275 0ustar jcorganjcorgan QT GUI Constellation Sink qtgui_const_sink_x from PyQt4 import Qt from gnuradio import qtgui import sip #set $win = 'self._%s_win'%$id qtgui.$(type.fcn)( $size, \#size $name, \#name $nconnections \#number of inputs ) self.$(id).set_update_time($update_time) self.$(id).set_y_axis($ymin, $ymax) self.$(id).set_x_axis($xmin, $xmax) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) set_resize($width, $height) set_update_time($update_time) set_title($which, $title) set_color($which, $color) Type type complex enum Name name QT GUI Plot string Number of Points size 1024 int Y min ymin -2 real part Y max ymax 2 real part X min xmin -2 real part X max xmax 2 real part Number of Inputs nconnections 1 int part Update Period update_time 0.10 real part GUI Hint gui_hint gui_hint part in $type $nconnections The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_waterfall_sink_x.xml0000664000175000017500000000567212245466767023162 0ustar jcorganjcorgan QT GUI Waterfall Sink qtgui_waterfall_sink_x from PyQt4 import Qt from gnuradio import qtgui from gnuradio.filter import firdes import sip #set $win = 'self._%s_win'%$id qtgui.$(type.fcn)( $fftsize, \#size $wintype, \#wintype $fc, \#fc $bw, \#bw $name, \#name $nconnections \#number of inputs ) self.$(id).set_update_time($update_time) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) set_frequency_range($fc, $bw) set_update_time($update_time) set_title($which, $title) set_color($which, $color) Type type complex enum Name name QT GUI Plot string FFT Size fftsize 1024 int Window Type wintype firdes.WIN_BLACKMAN_hARRIS int part Center Frequency (Hz) fc 0 real Bandwidth (Hz) bw samp_rate real Number of Inputs nconnections 1 int part Update Period update_time 0.10 real part GUI Hint gui_hint gui_hint part in $type $nconnections The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_check_box.xml0000664000175000017500000000467012207440367021532 0ustar jcorganjcorgan QT GUI Check Box variable_qtgui_check_box from PyQt4 import Qt self.$(id) = $(id) = $value #set $win = '_%s_check_box'%$id #if not $label() #set $label = '"%s"'%$id #end if $win = Qt.QCheckBox($label) self._$(id)_choices = {True: $true, False: $false} self._$(id)_choices_inv = dict((v,k) for k,v in self._$(id)_choices.iteritems()) self._$(id)_callback = lambda i: $(win).setChecked(self._$(id)_choices_inv[i]) self._$(id)_callback(self.$id) $(win).stateChanged.connect(lambda i: self.set_$(id)(self._$(id)_choices[bool(i)])) $(gui_hint()($win)) self.set_$(id)($value) self._$(id)_callback($id) Label label string #if $label() then 'none' else 'part'# Type type int enum part Default Value value True $type True true True $type False false False $type GUI Hint gui_hint gui_hint part $value in ($true, $false) This block creates a variable check box. \ Leave the label blank to use the variable id as the label. A check box selects between two values of similar type. \ Te values do not necessarily need to be of boolean type. The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_block_tree.xml0000664000175000017500000000330212207702530021676 0ustar jcorganjcorgan Instrumentation QT qtgui_freq_sink_x qtgui_time_sink_x qtgui_const_sink_x qtgui_waterfall_sink_x qtgui_time_raster_sink_x qtgui_histogram_sink_x qtgui_sink_x GUI Widgets QT qtgui_tab_widget variable_qtgui_range variable_qtgui_chooser variable_qtgui_check_box variable_qtgui_entry variable_qtgui_label gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_label.xml0000664000175000017500000000414412207440367020660 0ustar jcorganjcorgan QT GUI Label variable_qtgui_label from PyQt4 import Qt from gnuradio import eng_notation self.$(id) = $(id) = $value #set $win = 'self._%s_tool_bar'%$id $win = Qt.QToolBar(self) #if not $label() #set $label = '"%s"'%$id #end if $(win).addWidget(Qt.QLabel($label+": ")) self._$(id)_label = Qt.QLabel(str(self.$id)) self._$(id)_tool_bar.addWidget(self._$(id)_label) $(gui_hint()($win)) self.set_$(id)($value) self._$(id)_label.setText($(type.str)($id)) Label label string #if $label() then 'none' else 'part'# Type type int enum part Default Value value 0 $type GUI Hint gui_hint gui_hint part This block creates a variable with a label widget for text. \ Leave the label blank to use the variable id as the label. The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_time_sink_x.xml0000664000175000017500000001033312237515112022101 0ustar jcorganjcorgan QT GUI Time Sink qtgui_time_sink_x from PyQt4 import Qt from gnuradio import qtgui from gnuradio.filter import firdes import sip #set $win = 'self._%s_win'%$id qtgui.$(type.fcn)( $size, \#size $srate, \#samp_rate $name, \#name $nconnections \#number of inputs ) self.$(id).set_update_time($update_time) self.$(id).set_y_axis($ymin, $ymax) self.$(id).enable_tags(-1, $entags) self.$(id).set_trigger_mode($tr_mode, $tr_slope, $tr_level, $tr_delay, $tr_chan, $tr_tag) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) set_time_domain_axis($min, $max) set_update_time($update_time) set_title($which, $title) set_color($which, $color) set_y_axis($ymin, $ymax) set_samp_rate($srate) Type type complex enum Name name QT GUI Plot string Number of Points size 1024 int Sample Rate srate samp_rate float Y min ymin -1 float part Y max ymax 1 float part Number of Inputs nconnections 1 int part Update Period update_time 0.10 float part Trigger Mode tr_mode qtgui.TRIG_MODE_FREE enum part Trigger Slope tr_slope qtgui.TRIG_MODE_POS enum part Trigger Level tr_level 0.0 float part Trigger Delay tr_delay 0 float part Trigger Channel tr_chan 0 int part Trigger Tag Key tr_tag "" string part Disp. Tags entags True enum part GUI Hint gui_hint gui_hint part $tr_chan < 2*$nconnections in $type $nconnections The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_chooser.xml0000664000175000017500000001655012207440367021247 0ustar jcorganjcorgan QT GUI Chooser variable_qtgui_chooser from PyQt4 import Qt self.$(id) = $(id) = $value #slurp #set $all_options = [$option0, $option1, $option2, $option3, $option4][:int($num_opts())] #set $all_labels = [$label0, $label1, $label2, $label3, $label4][:int($num_opts())] #if not $label() #set $label = '"%s"'%$id #end if ######################################################################## ## Create the options list ######################################################################## #if int($num_opts()) self._$(id)_options = (#slurp #for $ch in $all_options $ch, #slurp #end for ) #else self._$(id)_options = $options #end if ######################################################################## ## Create the labels list ######################################################################## #if int($num_opts()) self._$(id)_labels = (#slurp #for i, $lbl in enumerate($all_labels) #if $lbl() $lbl, #slurp #else str(self._$(id)_options[$i]), #slurp #end if #end for ) #elif $labels() self._$(id)_labels = $labels #else self._$(id)_labels = map(str, self._$(id)_options) #end if ######################################################################## ## Create the combo box ######################################################################## #if $widget() == 'combo_box' #set $win = 'self._%s_tool_bar'%$id $win = Qt.QToolBar(self) $(win).addWidget(Qt.QLabel($label+": ")) self._$(id)_combo_box = Qt.QComboBox() $(win).addWidget(self._$(id)_combo_box) for label in self._$(id)_labels: self._$(id)_combo_box.addItem(label) self._$(id)_callback = lambda i: self._$(id)_combo_box.setCurrentIndex(self._$(id)_options.index(i)) self._$(id)_callback(self.$id) self._$(id)_combo_box.currentIndexChanged.connect( lambda i: self.set_$(id)(self._$(id)_options[i])) #end if ######################################################################## ## Create the radio buttons ######################################################################## #if $widget() == 'radio_buttons' #set $win = 'self._%s_group_box'%$id $win = Qt.QGroupBox($label) self._$(id)_box = $(orient)() self._$(id)_button_group = Qt.QButtonGroup() $(win).setLayout(self._$(id)_box) for i, label in enumerate(self._$(id)_labels): radio_button = Qt.QRadioButton(label) self._$(id)_box.addWidget(radio_button) self._$(id)_button_group.addButton(radio_button, i) self._$(id)_callback = lambda i: self._$(id)_button_group.button(self._$(id)_options.index(i)).setChecked(True) self._$(id)_callback(self.$id) self._$(id)_button_group.buttonClicked[int].connect( lambda i: self.set_$(id)(self._$(id)_options[i])) #end if $(gui_hint()($win)) self.set_$(id)($value) self._$(id)_callback($id) Label label string #if $label() then 'none' else 'part'# Type type int enum part Num Options num_opts 3 enum Default Value value 0 $type Options options [0, 1, 2] raw #if int($num_opts()) then 'all' else 'none'# Labels labels [] raw #if int($num_opts()) then 'all' else 'none'# Option 0 option0 0 $type #if int($num_opts()) > 0 then 'none' else 'all'# Label 0 label0 string $((int($num_opts()) > 0) and ($label0() and 'none' or 'part') or 'all') Option 1 option1 1 $type #if int($num_opts()) > 1 then 'none' else 'all'# Label 1 label1 string $((int($num_opts()) > 1) and ($label1() and 'none' or 'part') or 'all') Option 2 option2 2 $type #if int($num_opts()) > 2 then 'none' else 'all'# Label 2 label2 string $((int($num_opts()) > 2) and ($label2() and 'none' or 'part') or 'all') Option 3 option3 3 $type #if int($num_opts()) > 3 then 'none' else 'all'# Label 3 label3 string $((int($num_opts()) > 3) and ($label3() and 'none' or 'part') or 'all') Option 4 option4 4 $type #if int($num_opts()) > 4 then 'none' else 'all'# Label 4 label4 string $((int($num_opts()) > 4) and ($label4() and 'none' or 'part') or 'all') Widget widget combo_box enum part Orientation orient Qt.QVBoxLayout enum #if $widget() == 'radio_buttons' then 'part' else 'all'# GUI Hint gui_hint gui_hint part This block creates a variable with enumerated options. \ The gui widget is implemented as a combo box or radio button group. \ Leave the label blank to use the variable id as the label. Choose the number of options available to your chooser. \ When the label is left blank, the option will be used as the label. \ Set the number of options to "list" to enter a single list of options and labels. \ When the labels is an empty list, the options will be used as the label. The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_time_raster_x.xml0000664000175000017500000000506312207440367022447 0ustar jcorganjcorgan QT GUI Time Raster Sink qtgui_time_raster_sink_x from PyQt4 import Qt from gnuradio import qtgui import sip #set $win = 'self._%s_win'%$id qtgui.$(type.fcn)( $samp_rate, $nrows, $ncols, $mult, $offset, $name, $nconnections, ) self.$(id).set_update_time($update_time) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) set_num_rows($nrows) set_num_cols($ncols) set_multiplier($mult) set_offset($offset) set_update_time($update_time) set_title($which, $title) set_color($which, $color) Type type complex enum Name name QT GUI Plot string Sample Rate samp_rate samp_rate real Num. Rows nrows int Num. Cols ncols int Multiplier mult [] real_vector part Offset offset [] real_vector part Number of Inputs nconnections 1 int part Update Period update_time 0.10 real part GUI Hint gui_hint gui_hint part in $type $nconnections The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_freq_sink_x.xml0000664000175000017500000000626612245466767022136 0ustar jcorganjcorgan QT GUI Frequency Sink qtgui_freq_sink_x from PyQt4 import Qt from gnuradio import qtgui from gnuradio.filter import firdes import sip #set $win = 'self._%s_win'%$id qtgui.$(type.fcn)( $fftsize, \#size $wintype, \#wintype $fc, \#fc $bw, \#bw $name, \#name $nconnections \#number of inputs ) self.$(id).set_update_time($update_time) self.$(id).set_y_axis($ymin, $ymax) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) set_frequency_range($fc, $bw) set_update_time($update_time) set_title($which, $title) set_color($which, $color) Type type complex enum Name name QT GUI Plot string FFT Size fftsize 1024 int Window Type wintype firdes.WIN_BLACKMAN_hARRIS int part Center Frequency (Hz) fc 0 real Bandwidth (Hz) bw samp_rate real Y min ymin -140 real part Y max ymax 10 real part Number of Inputs nconnections 1 int part Update Period update_time 0.10 real part GUI Hint gui_hint gui_hint part in $type $nconnections The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_range.xml0000664000175000017500000001561012207440367020675 0ustar jcorganjcorgan QT GUI Range variable_qtgui_range from PyQt4 import Qt import PyQt4.Qwt5 as Qwt self.$(id) = $(id) = $value #set $win = 'self._%s_layout'%$id #if not $label() #set $label = '"%s"'%$id #end if ######################################################################## #if $widget() == "knob" ######################################################################## $win = Qt.QVBoxLayout() self._$(id)_knob = Qwt.QwtKnob() self._$(id)_knob.setRange($start, $stop, $step) self._$(id)_knob.setValue(self.$id) self._$(id)_knob.valueChanged.connect(self.set_$(id)) $(win).addWidget(self._$(id)_knob) self._$(id)_label = Qt.QLabel($label) self._$(id)_label.setAlignment(Qt.Qt.AlignTop | Qt.Qt.AlignHCenter) $(win).addWidget(self._$(id)_label) #end if ######################################################################## #if $widget() == "thermo" ######################################################################## $win = Qt.QVBoxLayout() self._$(id)_label = Qt.QLabel($label) self._$(id)_thermo = Qwt.QwtThermo() self._$(id)_thermo.setScalePosition(Qwt.QwtThermo.$orient.scalepos) self._$(id)_thermo.setRange($start, $stop) self._$(id)_thermo.setValue(self.$id) self._$(id)_thermo.$(orient.minfcn)($min_len) #if 'horizontal' in $orient().lower() self._$(id)_label.setAlignment(Qt.Qt.AlignBottom | Qt.Qt.AlignHCenter) $(win).addWidget(self._$(id)_label) $(win).addWidget(self._$(id)_thermo) #elif 'vertical' in $orient().lower() self._$(id)_label.setAlignment(Qt.Qt.AlignTop) $(win).addWidget(self._$(id)_thermo) $(win).addWidget(self._$(id)_label) #end if #end if ######################################################################## #if $widget() == "counter" ######################################################################## $win = Qt.QHBoxLayout() $(win).addWidget(Qt.QLabel($label+": ")) self._$(id)_counter = Qwt.QwtCounter() self._$(id)_counter.setRange($start, $stop, $step) self._$(id)_counter.setNumButtons(2) self._$(id)_counter.setMinimumWidth($min_len) self._$(id)_counter.setValue(self.$id) $(win).addWidget(self._$(id)_counter) self._$(id)_counter.valueChanged.connect(self.set_$(id)) #end if ######################################################################## #if $widget() == "slider" ######################################################################## $win = Qt.QVBoxLayout() self._$(id)_label = Qt.QLabel($label) self._$(id)_slider = Qwt.QwtSlider(None, Qt.$orient, Qwt.QwtSlider.$orient.scalepos, Qwt.QwtSlider.BgSlot) self._$(id)_slider.setRange($start, $stop, $step) self._$(id)_slider.setValue(self.$id) self._$(id)_slider.$(orient.minfcn)($min_len) self._$(id)_slider.valueChanged.connect(self.set_$(id)) #if 'horizontal' in $orient().lower() self._$(id)_label.setAlignment(Qt.Qt.AlignBottom | Qt.Qt.AlignHCenter) $(win).addWidget(self._$(id)_label) $(win).addWidget(self._$(id)_slider) #elif 'vertical' in $orient().lower() self._$(id)_label.setAlignment(Qt.Qt.AlignTop) $(win).addWidget(self._$(id)_slider) $(win).addWidget(self._$(id)_label) #end if #end if ######################################################################## #if $widget() == "counter_slider" ######################################################################## $win = Qt.QVBoxLayout() self._$(id)_tool_bar = Qt.QToolBar(self) $(win).addWidget(self._$(id)_tool_bar) self._$(id)_tool_bar.addWidget(Qt.QLabel($label+": ")) self._$(id)_counter = Qwt.QwtCounter() self._$(id)_counter.setRange($start, $stop, $step) self._$(id)_counter.setNumButtons(2) self._$(id)_counter.setValue(self.$id) self._$(id)_tool_bar.addWidget(self._$(id)_counter) self._$(id)_counter.valueChanged.connect(self.set_$(id)) self._$(id)_slider = Qwt.QwtSlider(None, Qt.Qt.Horizontal, Qwt.QwtSlider.BottomScale, Qwt.QwtSlider.BgSlot) self._$(id)_slider.setRange($start, $stop, $step) self._$(id)_slider.setValue(self.$id) self._$(id)_slider.setMinimumWidth($min_len) self._$(id)_slider.valueChanged.connect(self.set_$(id)) $(win).addWidget(self._$(id)_slider) #end if $(gui_hint()($win)) self.set_$(id)($value) #if $widget() == "knob" self._$(id)_knob.setValue($id) #end if #if $widget() == "thermo" self._$(id)_thermo.setValue($id) #end if #if $widget() == "counter" self._$(id)_counter.setValue($id) #end if #if $widget() == "slider" self._$(id)_slider.setValue($id) #end if #if $widget() == "counter_slider" self._$(id)_counter.setValue($id) self._$(id)_slider.setValue($id) #end if Label label string #if $label() then 'none' else 'part'# Default Value value 50 real Start start 0 real Stop stop 100 real Step step 1 real Widget widget counter_slider enum part Orientation orient Qt.Horizontal enum #if $widget() in ("slider", "thermo") then 'part' else 'all'# Minimum Length min_len 200 int #if $widget().split('_')[0] in ("slider", "counter", "thermo") then 'part' else 'all'# GUI Hint gui_hint gui_hint part $start <= $value <= $stop $start < $stop This block creates a variable with a slider. \ Leave the label blank to use the variable id as the label. \ The value must be a real number. \ The value must be between the start and the stop. The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_sink_x.xml0000664000175000017500000000765712207440367021110 0ustar jcorganjcorgan QT GUI Sink qtgui_sink_x from PyQt4 import Qt from gnuradio import qtgui from gnuradio.filter import firdes import sip #set $win = 'self._%s_win'%$id qtgui.$(type.fcn)( $fftsize, \#fftsize $wintype, \#wintype $fc, \#fc $bw, \#bw $name, \#name $plotfreq, \#plotfreq $plotwaterfall, \#plotwaterfall $plottime, \#plottime $plotconst, \#plotconst ) self.$(id).set_update_time(1.0/$rate) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) #if $freqchangevar() is not None def $(id)_callback(p, num): if num == 1 or num == 2: self.set_$(freqchangevar)(p.x()) Qt.QObject.connect(self._$(id)_win, Qt.SIGNAL("plotPointSelected(QPointF, int)"), $(id)_callback ) #end if set_frequency_range($fc, $bw) Type type complex enum Name name QT GUI Plot string FFT Size fftsize 1024 int Window Type wintype firdes.WIN_BLACKMAN_hARRIS int part Center Frequency (Hz) fc 0 real Bandwidth (Hz) bw samp_rate real Update Rate rate 10 real Plot Frequency plotfreq True bool part Plot Waterfall plotwaterfall True bool part Plot Time plottime True bool part Plot Const plotconst True bool part GUI Hint gui_hint gui_hint part Clicked freq variable freqchangevar None raw part in $type $num_inputs The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_tab_widget.xml0000664000175000017500000000463012207440367021712 0ustar jcorganjcorgan QT GUI Tab Widget qtgui_tab_widget from PyQt4 import Qt #set $win = 'self.%s'%$id Qt.QTabWidget() #set $all_labels = [$label0, $label1, $label2, $label3, $label4][:int($num_tabs())] #for i, label in enumerate($all_labels) self.$(id)_widget_$(i) = Qt.QWidget() self.$(id)_layout_$(i) = Qt.QBoxLayout(Qt.QBoxLayout.TopToBottom, self.$(id)_widget_$(i)) self.$(id)_grid_layout_$(i) = Qt.QGridLayout() self.$(id)_layout_$(i).addLayout(self.$(id)_grid_layout_$(i)) $(win).addTab(self.$(id)_widget_$(i), $label) #end for $(gui_hint()($win)) Num Tabs num_tabs 1 enum Label 0 label0 Tab 0 string #if int($num_tabs()) > 0 then 'none' else 'all'# Label 1 label1 Tab 1 string #if int($num_tabs()) > 1 then 'none' else 'all'# Label 2 label2 Tab 2 string #if int($num_tabs()) > 2 then 'none' else 'all'# Label 3 label3 Tab 3 string #if int($num_tabs()) > 3 then 'none' else 'all'# Label 4 label4 Tab 4 string #if int($num_tabs()) > 4 then 'none' else 'all'# GUI Hint gui_hint gui_hint part This block creates a tabbed widget to organize other widgets. \ The ID of this block can be used as the tab_id in the GUI hints of other widgets. The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_histogram_sink_x.xml0000664000175000017500000000407212207702530023142 0ustar jcorganjcorgan QT GUI Histogram Sink qtgui_histogram_sink_x from PyQt4 import Qt from gnuradio import qtgui import sip #set $win = 'self._%s_win'%$id qtgui.histogram_sink_f( $size, $bins, $xmin, $xmax, $name, $nconnections ) self.$(id).set_update_time($update_time) self._$(id)_win = sip.wrapinstance(self.$(id).pyqwidget(), Qt.QWidget) $(gui_hint()($win)) set_update_time($update_time) set_title($which, $title) set_color($which, $color) set_bins($bins) set_x_axis($bins) Name name QT GUI Plot string Number of Points size 1024 int Number of Bins bins 100 int Min x-axis xmin -1 real Max x-axis xmax 1 real Number of Inputs nconnections 1 int part Update Period update_time 0.10 float part GUI Hint gui_hint gui_hint part in float $nconnections The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/grc/qtgui_entry.xml0000664000175000017500000000434512207440367020745 0ustar jcorganjcorgan QT GUI Entry variable_qtgui_entry from PyQt4 import Qt from gnuradio import eng_notation self.$(id) = $(id) = $value #set $win = 'self._%s_tool_bar'%$id $win = Qt.QToolBar(self) #if not $label() #set $label = '"%s"'%$id #end if $(win).addWidget(Qt.QLabel($label+": ")) self._$(id)_line_edit = Qt.QLineEdit(str(self.$id)) self._$(id)_tool_bar.addWidget(self._$(id)_line_edit) self._$(id)_line_edit.returnPressed.connect( lambda: self.set_$(id)($(type.conv)(self._$(id)_line_edit.text().toAscii()))) $(gui_hint()($win)) self.set_$(id)($value) self._$(id)_line_edit.setText($(type.str)($id)) Label label string #if $label() then 'none' else 'part'# Type type int enum part Default Value value 0 $type GUI Hint gui_hint gui_hint part This block creates a variable with a text entry box. \ Leave the label blank to use the variable id as the label. The GUI hint can be used to position the widget within the application. \ The hint is of the form [tab_id@tab_index]: [row, col, row_span, col_span]. \ Both the tab specification and the grid position are optional. gnuradio-3.7.2.1/gr-qtgui/doc/0000755000175000017500000000000012237515112015625 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/doc/CMakeLists.txt0000644000175000017500000000151711744612271020377 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.qtgui DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-qtgui/doc/qtgui.dox0000664000175000017500000001633012237515112017477 0ustar jcorganjcorgan/*! \page page_qtgui QT Graphical User Interface \section Introduction This is the gr-qtgui package. It contains various QT-based graphical user interface blocks that add graphical sinks to a GNU Radio flowgraph. The Python namespaces is in gnuradio.qtgui, which would be normally imported as: \code from gnuradio import qtgui \endcode See the Doxygen documentation for details about the blocks available in this package. The relevant blocks are listed in the \ref qtgui_blk group. A quick listing of the details can be found in Python after importing by using: \code help(qtgui) \endcode \subsection Blocks There are a number of available QTGUI blocks for different plotting purposes. These include: \li Time Domain (gr::qtgui::time_sink_c and gr::qtgui::time_sink_f): x-axis is time, y-axis is amplitude. \li Frequency Domain or PSD (gr::qtgui::freq_sink_c and gr::qtgui::freq_sink_f): x-axis is frequency, y-axis is magnitude in dB. \li Waterfall or spectrogram (gr::qtgui::waterfall_sink_c and gr::qtgui::waterfall_sink_f): x-axis is frequency, y-axis is time,z-axis is intensity related to magnitude in dB. \li Constellation (gr::qtgui::const_sink_c): polar plot of real vs. imaginary. \li Time Raster (gr::qtgui::time_raster_sink_f and gr::qtgui::time_raster_sink_b): time vs. time with the z-axis being intensity basedon value of the sample. \li Histogram (gr::qtgui::histogram_sink_f): Displays a histogram of the data stream. \li Combined Sink (gr::qtgui::sink_c and gr::qtgui::sink_f): combines time, frequency, waterfall, and constellation plots into one widget. The time domain, frequency domain, and waterfall have both a complex and a floating point block. The constellation plot only makes sense with complex inputs. The time raster plots accept bits and floats. Because the time raster plots are designed to show structure over time in a signal, frame, packet, etc., they never drop samples. This is a fairly taxing job and performance can be an issue. Since it is expected that this block will work on a frame or packet structure, we tend to be at the lowest possible rate at this point, so that will help. Expect performance issues at high data rates. Note: There seem to be extra performance issue with the raster plotters in QWT version 5 that were fixed with QWT version 6. As such, the time raster plots have incredibly poor performance with QWT5 to the point of almost being unusable. In the future, we may restrict compilation and installation of these plots only if QWT6 or higher is discovered. For now, just be aware of this limitation. \section qtgui_menu Drop-Down Menu and Interacting with Plots All QTGUI sinks have interactive capabilities. \li Zooming is done simply by clicking the left mouse button and dragging a rectangle around the area to zoom. \li Zooming can be done in multiple steps. \li A right mouse click will zoom out one step. \li Ctrl+Right mouse click will zoom all the way out. \li Ctrl+Middle mouse click and hold can drag the canvas around. \li Mouse wheel up/down will zoom out/in on y axis (both axes in constellation plot). \li Middle mouse button brings up a context menu. Each type of graph has a different set of menu items in the context menu. Most have some way to change the appearance of the lines or surfaces, such as changing the line width color, marker, and transparency. Other common features can set the sampling rate, turn a grid on an off, pause and unpause (stop/start) the display update, and save the current figure. Specific feature are things like setting the number of points to display, setting the FFT size, FFT window, and any FFT averaging. \subsection qtgui_menu_trigger Triggering Menu for Time Plots The time plots have triggering capabilities. Triggering can happen when the signal of a specific channel crosses (positive or negative slope) a certain level threshold. Or triggering can be done off a specific stream tag such that whenever a tag of a given key is found, the scope will trigger. In the signal level mode, the trigger can be either 'auto' or 'normal' where the latter will only trigger when the even is seen. The 'auto' mode will trigger on the event or every so often even if no trigger is found. The 'free' mode ignores ignores triggering and continuously plots. By default, the triggers plot the triggering event at the x=0 (i.e., the left-most point in the plot). A delay can be set to delay the signal along the x-axis to observe any signal before the triggering event. The delay feature works the same for both level and tag triggers. The delay is set according to time in seconds, not samples. So the delay can be calculated as the number of samples divided by the sample rate given to the block. All trigger settings (mode, slope, level, delay, channel, and tag key) are settable in the GRC properties boxes to easily set up a repeatable environment. A note on the trigger delay setting. This value is limited by the buffer size and/or the number of points being display. It is capped by the minimum of these two values. The buffer size issue is generally only a problem when plotting a large number of samples. However, if the delay is set large to begin with (in the GRC properties box or before top_block.start() is called), then the buffers are resized accordingly offering more freedom. This should be a problem in a limited number of scenarios, but a log INFO level message is produced when asking for the delay outside of the available range. \section Dependencies The QT GUI blocks require the following dependencies. \li QtCore (version >= 4.4) \li QtGui (version >= 4.4) \li QtOpenGL (version >= 4.4) \li PyQt4 for Qt4 (version >= 4.4) \li Qwt (version >= 5.2) \li PyQwt5 for Qt4 (version >= 5.2) \section Usage To use the qtgui interface, a bit of boiler-plate lines must be included. First, the sink is defined, then it must be exposed from C++ into Python using the "sip.wrapinstance" command, and finally, the "show" method is run on the new Python object. This sets up the QT environment to show the widget, but the qApplication must also be launched. In the "main" function of the code, the qApp is retrieved. Then, after the GNU Radio top block is started (remember that start() is a non-blocking call to launch the main thread of the flowgraph), the qapp's "exec_()" function is called. This function is a blocking call while the GUI is alive. \code from PyQt4 import Qt from gnuradio import qtgui import sys, sip class grclass(gr.top_block): .... self.snk = qtgui.sink_c(1024, #fftsize samp_rate, #bw "QT GUI Plot") #name self.snk_win = sip.wrapinstance(self.snk.pyqwidget(), Qt.QWidget) self.snk_win.show() def main(): qapp = Qt.QApplication(sys.argv) tb = grclass() tb.start() qapp.exec_() tb.stop() \endcode There are graphical controls in all but the combined plotting tools. In the margins of the GUIs (that is, not on the canvas showing the signal itself), right-clicking the mouse will pull up a drop-down menu that will allow you to change difference parameters of the plots. These include things like the look of the lines (width, color, style, markers, etc.), the ability to start and stop the display, the ability to save to a file, and other plot-specific controls (FFT size for the frequency and waterfall plots, etc.). */ gnuradio-3.7.2.1/gr-qtgui/doc/README.qtgui0000644000175000017500000000066711744612271017654 0ustar jcorganjcorganThis is the gr-qtgui package. It contains various QT-based graphical user interface blocks that add graphical sinks to a GNU Radio flowgraph. The Python namespaces is in gnuradio.qtgui, which would be normally imported as: from gnuradio import qtgui See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(qtgui) gnuradio-3.7.2.1/gr-qtgui/python/0000775000175000017500000000000012207440367016411 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/python/qtgui/0000775000175000017500000000000012207702530017533 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/python/qtgui/CMakeLists.txt0000664000175000017500000000316412207440367022306 0ustar jcorganjcorgan# Copyright 2010-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/qtgui COMPONENT "qtgui_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-qtgui/python/qtgui/qa_qtgui.py0000775000175000017500000000534612207702530021732 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, qtgui class test_qtgui(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None # Tests to make sure we can instantiate the sink. # We use '5' in place of filter.firdes.WIN_BLACKMAN_hARRIS so we # don't have to worry about importing filter just for this one # constant. def test01(self): self.qtsnk = qtgui.sink_c(1024, 5, 0, 1, "Test", True, True, True, True) def test02(self): self.qtsnk = qtgui.sink_f(1024, 5, 0, 1, "Test", True, True, True, True) def test03(self): self.qtsnk = qtgui.time_sink_c(1024, 1, "Test", 1) def test04(self): self.qtsnk = qtgui.time_sink_f(1024, 1, "Test", 1) def test05(self): self.qtsnk = qtgui.freq_sink_c(1024, 5, 0, 1, "Test", 1) def test06(self): self.qtsnk = qtgui.freq_sink_f(1024, 5, 0, 1, "Test", 1) def test07(self): self.qtsnk = qtgui.waterfall_sink_c(1024, 5, 0, 1, "Test") def test08(self): self.qtsnk = qtgui.waterfall_sink_f(1024, 5, 0, 1, "Test") def test09(self): self.qtsnk = qtgui.const_sink_c(1024, "Test", 1) def test10(self): self.qtsnk = qtgui.time_raster_sink_b(1024, 100, 100.5, [], [], "Test", 1) def test11(self): self.qtsnk = qtgui.time_raster_sink_f(1024, 100, 100.5, [], [], "Test", 1) def test12(self): self.qtsnk = qtgui.histogram_sink_f(1024, 100, -1, 1, "Test", 1) if __name__ == '__main__': gr_unittest.run(test_qtgui, "test_qtgui.xml") gnuradio-3.7.2.1/gr-qtgui/python/qtgui/__init__.py0000664000175000017500000000215412207440367021655 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Provides a GUI interface using the QT backend. ''' # The presence of this file turns this directory into a Python package import os try: from qtgui_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from qtgui_swig import * gnuradio-3.7.2.1/gr-qtgui/lib/0000755000175000017500000000000012245466767015652 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/lib/freq_sink_c_impl.h0000664000175000017500000000751712237515112021317 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_FREQ_SINK_C_IMPL_H #define INCLUDED_QTGUI_FREQ_SINK_C_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API freq_sink_c_impl : public freq_sink_c { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); gr::thread::mutex d_mutex; int d_fftsize; float d_fftavg; filter::firdes::win_type d_wintype; std::vector d_window; double d_center_freq; double d_bandwidth; std::string d_name; int d_nconnections; bool d_shift; fft::fft_complex *d_fft; int d_index; std::vector d_residbufs; std::vector d_magbufs; float *d_fbuf; int d_argc; char *d_argv; QWidget *d_parent; FreqDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; void windowreset(); void buildwindow(); void fftresize(); void fft(float *data_out, const gr_complex *data_in, int size); public: freq_sink_c_impl(int size, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent=NULL); ~freq_sink_c_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_fft_size(const int fftsize); int fft_size() const; void set_fft_average(const float fftavg); float fft_average() const; void set_fft_window(const filter::firdes::win_type win); filter::firdes::win_type fft_window(); void set_frequency_range(const double centerfreq, const double bandwidth); void set_y_axis(double min, double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, int style); void set_line_marker(int which, int marker); void set_line_alpha(int which, double alpha); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); void set_size(int width, int height); void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_FREQ_SINK_C_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/time_sink_c_impl.h0000664000175000017500000001017712237515112021314 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_SINK_C_IMPL_H #define INCLUDED_QTGUI_TIME_SINK_C_IMPL_H #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API time_sink_c_impl : public time_sink_c { private: void initialize(); gr::thread::mutex d_mutex; int d_size, d_buffer_size; double d_samp_rate; std::string d_name; int d_nconnections; int d_index, d_start, d_end; std::vector d_buffers; std::vector< std::vector > d_tags; int d_argc; char *d_argv; QWidget *d_parent; TimeDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; // Members used for triggering scope trigger_mode d_trigger_mode; trigger_slope d_trigger_slope; float d_trigger_level; int d_trigger_channel; int d_trigger_delay; pmt::pmt_t d_trigger_tag_key; bool d_triggered; int d_trigger_count; int d_initial_delay; // used for limiting d_trigger_delay void _reset(); void _npoints_resize(); void _adjust_tags(int adj); void _gui_update_trigger(); void _test_trigger_tags(int nitems); void _test_trigger_norm(int nitems, gr_vector_const_void_star inputs); bool _test_trigger_slope(const gr_complex *in) const; public: time_sink_c_impl(int size, double samp_rate, const std::string &name, int nconnections, QWidget *parent=NULL); ~time_sink_c_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_y_axis(double min, double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, int style); void set_line_marker(int which, int marker); void set_nsamps(const int size); void set_samp_rate(const double samp_rate); void set_line_alpha(int which, double alpha); void set_trigger_mode(trigger_mode mode, trigger_slope slope, float level, float delay, int channel, const std::string &tag_key=""); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); void set_size(int width, int height); int nsamps() const; void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void enable_stem_plot(bool en); void enable_semilogx(bool en); void enable_semilogy(bool en); void enable_tags(int which, bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_SINK_C_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/CMakeLists.txt0000664000175000017500000001172612207702530020376 0ustar jcorganjcorgan# Copyright 2010-2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the QT file generations stuff ######################################################################## set(qtgui_mod_includedir ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/qtgui) set(qtgui_moc_hdrs ${qtgui_mod_includedir}/spectrumdisplayform.h ${qtgui_mod_includedir}/displayform.h ${qtgui_mod_includedir}/timedisplayform.h ${qtgui_mod_includedir}/timerasterdisplayform.h ${qtgui_mod_includedir}/freqdisplayform.h ${qtgui_mod_includedir}/constellationdisplayform.h ${qtgui_mod_includedir}/waterfalldisplayform.h ${qtgui_mod_includedir}/histogramdisplayform.h ${qtgui_mod_includedir}/form_menus.h ${qtgui_mod_includedir}/DisplayPlot.h ${qtgui_mod_includedir}/FrequencyDisplayPlot.h ${qtgui_mod_includedir}/TimeDomainDisplayPlot.h ${qtgui_mod_includedir}/TimeRasterDisplayPlot.h ${qtgui_mod_includedir}/WaterfallDisplayPlot.h ${qtgui_mod_includedir}/ConstellationDisplayPlot.h ${qtgui_mod_includedir}/HistogramDisplayPlot.h ) QT4_WRAP_CPP(qtgui_moc_srcs ${qtgui_moc_hdrs}) QT4_WRAP_UI(qtgui_ui_hdrs spectrumdisplayform.ui) #FIXME the sources expect .ui.h, but the macros generate ui_foo.h #avoid changing the sources by generating the header with the include set(spectrum_ui_hdr ${CMAKE_CURRENT_BINARY_DIR}/spectrumdisplayform.ui.h) if(NOT EXISTS ${spectrum_ui_hdr}) file(WRITE ${spectrum_ui_hdr} "#include \n") endif(NOT EXISTS ${spectrum_ui_hdr}) set(qtgui_srcs ${qtgui_moc_srcs} ${qtgui_ui_hdrs} DisplayPlot.cc FrequencyDisplayPlot.cc TimeDomainDisplayPlot.cc TimeRasterDisplayPlot.cc timeRasterGlobalData.cc WaterfallDisplayPlot.cc waterfallGlobalData.cc ConstellationDisplayPlot.cc HistogramDisplayPlot.cc spectrumdisplayform.cc displayform.cc timedisplayform.cc timerasterdisplayform.cc freqdisplayform.cc constellationdisplayform.cc histogramdisplayform.cc waterfalldisplayform.cc SpectrumGUIClass.cc spectrumUpdateEvents.cc plot_waterfall.cc plot_raster.cc sink_c_impl.cc sink_f_impl.cc time_sink_c_impl.cc time_sink_f_impl.cc time_raster_sink_b_impl.cc time_raster_sink_f_impl.cc freq_sink_c_impl.cc freq_sink_f_impl.cc const_sink_c_impl.cc waterfall_sink_c_impl.cc waterfall_sink_f_impl.cc histogram_sink_f_impl.cc qtgui_util.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-qtgui.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-qtgui.rc @ONLY) list(APPEND qtgui_srcs ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-qtgui.rc ) endif(MSVC) ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_QTGUI_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${QWT_INCLUDE_DIRS} ${QT_INCLUDE_DIRS} ${FFTW3F_INCLUDE_DIRS} ${LOG4CPP_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} ) link_directories( ${QWT_LIBRARY_DIRS} ${FFTW3F_LIBRARY_DIRS} ${LOG4CPP_LIBRARY_DIRS} ${Boost_LIBRARY_DIRS} ) include_directories(${PYTHON_INCLUDE_PATH}) #deprecated for dirs (cmake 2.6) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND qtgui_libs gnuradio-runtime gnuradio-fft gnuradio-filter volk ${QWT_LIBRARIES} ${QT_LIBRARIES} ${PYTHON_LIBRARIES} ${FFTW3F_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_definitions(-DQWT_DLL) #setup QWT library linkage add_library(gnuradio-qtgui SHARED ${qtgui_srcs}) target_link_libraries(gnuradio-qtgui ${qtgui_libs}) GR_LIBRARY_FOO(gnuradio-qtgui RUNTIME_COMPONENT "qtgui_runtime" DEVEL_COMPONENT "qtgui_devel") gnuradio-3.7.2.1/gr-qtgui/lib/timedisplayform.cc0000664000175000017500000002200512237515112021346 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include TimeDisplayForm::TimeDisplayForm(int nplots, QWidget* parent) : DisplayForm(nplots, parent) { d_stem = false; d_semilogx = false; d_semilogy = false; d_int_validator = new QIntValidator(this); d_int_validator->setBottom(0); d_layout = new QGridLayout(this); d_display_plot = new TimeDomainDisplayPlot(nplots, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); d_nptsmenu = new NPointsMenu(this); d_menu->addAction(d_nptsmenu); connect(d_nptsmenu, SIGNAL(whichTrigger(int)), this, SLOT(setNPoints(const int))); d_stemmenu = new QAction("Stem Plot", this); d_stemmenu->setCheckable(true); d_menu->addAction(d_stemmenu); connect(d_stemmenu, SIGNAL(triggered(bool)), this, SLOT(setStem(bool))); d_semilogxmenu = new QAction("Semilog X", this); d_semilogxmenu->setCheckable(true); d_menu->addAction(d_semilogxmenu); connect(d_semilogxmenu, SIGNAL(triggered(bool)), this, SLOT(setSemilogx(bool))); d_semilogymenu = new QAction("Semilog Y", this); d_semilogymenu->setCheckable(true); d_menu->addAction(d_semilogymenu); connect(d_semilogymenu, SIGNAL(triggered(bool)), this, SLOT(setSemilogy(bool))); for(int i = 0; i < d_nplots; i++) { d_tagsmenu.push_back(new QAction("Show Tag Makers", this)); d_tagsmenu[i]->setCheckable(true); d_tagsmenu[i]->setChecked(true); connect(d_tagsmenu[i], SIGNAL(triggered(bool)), this, SLOT(tagMenuSlot(bool))); d_lines_menu[i]->addAction(d_tagsmenu[i]); } // Set up the trigger menu d_triggermenu = new QMenu("Trigger", this); d_tr_mode_menu = new TriggerModeMenu(this); d_tr_slope_menu = new TriggerSlopeMenu(this); d_tr_level_act = new PopupMenu("Level", this); d_tr_delay_act = new PopupMenu("Delay", this); d_tr_channel_menu = new TriggerChannelMenu(nplots, this); d_tr_tag_key_act = new PopupMenu("Tag Key", this); d_triggermenu->addMenu(d_tr_mode_menu); d_triggermenu->addMenu(d_tr_slope_menu); d_triggermenu->addAction(d_tr_level_act); d_triggermenu->addAction(d_tr_delay_act); d_triggermenu->addMenu(d_tr_channel_menu); d_triggermenu->addAction(d_tr_tag_key_act); d_menu->addMenu(d_triggermenu); setTriggerMode(gr::qtgui::TRIG_MODE_FREE); connect(d_tr_mode_menu, SIGNAL(whichTrigger(gr::qtgui::trigger_mode)), this, SLOT(setTriggerMode(gr::qtgui::trigger_mode))); // updates trigger state by calling set level or set tag key. connect(d_tr_mode_menu, SIGNAL(whichTrigger(gr::qtgui::trigger_mode)), this, SLOT(updateTrigger(gr::qtgui::trigger_mode))); setTriggerSlope(gr::qtgui::TRIG_SLOPE_POS); connect(d_tr_slope_menu, SIGNAL(whichTrigger(gr::qtgui::trigger_slope)), this, SLOT(setTriggerSlope(gr::qtgui::trigger_slope))); setTriggerLevel(0); connect(d_tr_level_act, SIGNAL(whichTrigger(QString)), this, SLOT(setTriggerLevel(QString))); setTriggerDelay(0); connect(d_tr_delay_act, SIGNAL(whichTrigger(QString)), this, SLOT(setTriggerDelay(QString))); setTriggerChannel(0); connect(d_tr_channel_menu, SIGNAL(whichTrigger(int)), this, SLOT(setTriggerChannel(int))); setTriggerTagKey(std::string("")); connect(d_tr_tag_key_act, SIGNAL(whichTrigger(QString)), this, SLOT(setTriggerTagKey(QString))); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } TimeDisplayForm::~TimeDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete d_int_validator; } TimeDomainDisplayPlot* TimeDisplayForm::getPlot() { return ((TimeDomainDisplayPlot*)d_display_plot); } void TimeDisplayForm::newData(const QEvent* updateEvent) { TimeUpdateEvent *tevent = (TimeUpdateEvent*)updateEvent; const std::vector dataPoints = tevent->getTimeDomainPoints(); const uint64_t numDataPoints = tevent->getNumTimeDomainDataPoints(); const std::vector< std::vector > tags = tevent->getTags(); getPlot()->plotNewData(dataPoints, numDataPoints, d_update_time, tags); } void TimeDisplayForm::customEvent(QEvent * e) { if(e->type() == TimeUpdateEvent::Type()) { newData(e); } } void TimeDisplayForm::setSampleRate(const QString &samprate) { setSampleRate(samprate.toDouble()); } void TimeDisplayForm::setSampleRate(const double samprate) { if(samprate > 0) { std::string strtime[4] = {"sec", "ms", "us", "ns"}; double units10 = floor(log10(samprate)); double units3 = std::max(floor(units10 / 3.0), 0.0); double units = pow(10, (units10-fmod(units10, 3.0))); int iunit = static_cast(units3); getPlot()->setSampleRate(samprate, units, strtime[iunit]); } else { throw std::runtime_error("TimeDisplayForm: samprate must be > 0.\n"); } } void TimeDisplayForm::setYaxis(double min, double max) { getPlot()->setYaxis(min, max); } int TimeDisplayForm::getNPoints() const { return d_npoints; } void TimeDisplayForm::setNPoints(const int npoints) { d_npoints = npoints; d_nptsmenu->setDiagText(d_npoints); } void TimeDisplayForm::setStem(bool en) { d_stem = en; d_stemmenu->setChecked(en); getPlot()->stemPlot(d_stem); getPlot()->replot(); } void TimeDisplayForm::autoScale(bool en) { d_autoscale_state = en; d_autoscale_act->setChecked(en); getPlot()->setAutoScale(d_autoscale_state); getPlot()->replot(); } void TimeDisplayForm::setSemilogx(bool en) { d_semilogx = en; d_semilogxmenu->setChecked(en); getPlot()->setSemilogx(d_semilogx); getPlot()->replot(); } void TimeDisplayForm::setSemilogy(bool en) { d_semilogy = en; d_semilogymenu->setChecked(en); getPlot()->setSemilogy(d_semilogy); getPlot()->replot(); } void TimeDisplayForm::setTagMenu(int which, bool en) { getPlot()->enableTagMarker(which, en); d_tagsmenu[which]->setChecked(en); } void TimeDisplayForm::tagMenuSlot(bool en) { for(size_t i = 0; i < d_tagsmenu.size(); i++) { getPlot()->enableTagMarker(i, d_tagsmenu[i]->isChecked()); } } /******************************************************************** * TRIGGER METHODS *******************************************************************/ void TimeDisplayForm::setTriggerMode(gr::qtgui::trigger_mode mode) { d_trig_mode = mode; d_tr_mode_menu->getAction(mode)->setChecked(true); } void TimeDisplayForm::updateTrigger(gr::qtgui::trigger_mode mode) { // If auto or normal mode, popup trigger level box to set if((d_trig_mode == gr::qtgui::TRIG_MODE_AUTO) || (d_trig_mode == gr::qtgui::TRIG_MODE_NORM)) d_tr_level_act->activate(QAction::Trigger); // if tag mode, popup tag key box to set if(d_trig_mode == gr::qtgui::TRIG_MODE_TAG) d_tr_tag_key_act->activate(QAction::Trigger); } gr::qtgui::trigger_mode TimeDisplayForm::getTriggerMode() const { return d_trig_mode; } void TimeDisplayForm::setTriggerSlope(gr::qtgui::trigger_slope slope) { d_trig_slope = slope; d_tr_slope_menu->getAction(slope)->setChecked(true); } gr::qtgui::trigger_slope TimeDisplayForm::getTriggerSlope() const { return d_trig_slope; } void TimeDisplayForm::setTriggerLevel(QString s) { d_trig_level = s.toFloat(); } void TimeDisplayForm::setTriggerLevel(float level) { d_trig_level = level; d_tr_level_act->setText(QString().setNum(d_trig_level)); } float TimeDisplayForm::getTriggerLevel() const { return d_trig_level; } void TimeDisplayForm::setTriggerDelay(QString s) { d_trig_delay = s.toFloat(); } void TimeDisplayForm::setTriggerDelay(float delay) { d_trig_delay = delay; d_tr_delay_act->setText(QString().setNum(d_trig_delay)); } float TimeDisplayForm::getTriggerDelay() const { return d_trig_delay; } void TimeDisplayForm::setTriggerChannel(int channel) { d_trig_channel = channel; d_tr_channel_menu->getAction(d_trig_channel)->setChecked(true); } int TimeDisplayForm::getTriggerChannel() const { return d_trig_channel; } void TimeDisplayForm::setTriggerTagKey(QString s) { d_trig_tag_key = s.toStdString(); } void TimeDisplayForm::setTriggerTagKey(const std::string &key) { d_trig_tag_key = key; d_tr_tag_key_act->setText(QString().fromStdString(d_trig_tag_key)); } std::string TimeDisplayForm::getTriggerTagKey() const { return d_trig_tag_key; } gnuradio-3.7.2.1/gr-qtgui/lib/plot_waterfall.cc0000664000175000017500000002034012207440367021163 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include "qwt_painter.h" #include "qwt_scale_map.h" #include "qwt_color_map.h" #include #if QWT_VERSION < 0x060000 #include "qwt_double_interval.h" #endif typedef QVector QwtColorTable; class PlotWaterfallImage: public QImage { // This class hides some Qt3/Qt4 API differences public: PlotWaterfallImage(const QSize &size, QwtColorMap::Format format): QImage(size, format == QwtColorMap::RGB ? QImage::Format_ARGB32 : QImage::Format_Indexed8 ) { } PlotWaterfallImage(const QImage &other): QImage(other) { } void initColorTable(const QImage& other) { setColorTable(other.colorTable()); } }; class PlotWaterfall::PrivateData { public: PrivateData() { data = NULL; colorMap = new QwtLinearColorMap(); } ~PrivateData() { delete colorMap; } WaterfallData *data; QwtColorMap *colorMap; }; /*! Sets the following item attributes: - QwtPlotItem::AutoScale: true - QwtPlotItem::Legend: false The z value is initialized by 8.0. \param title Title \sa QwtPlotItem::setItemAttribute(), QwtPlotItem::setZ() */ PlotWaterfall::PlotWaterfall(WaterfallData* data, const QString &title): QwtPlotRasterItem(title) { d_data = new PrivateData(); d_data->data = data; // setCachePolicy(QwtPlotRasterItem::PaintCache); setItemAttribute(QwtPlotItem::AutoScale, true); setItemAttribute(QwtPlotItem::Legend, false); setZ(8.0); } //! Destructor PlotWaterfall::~PlotWaterfall() { delete d_data; } const WaterfallData* PlotWaterfall::data()const{ return d_data->data; } //! \return QwtPlotItem::Rtti_PlotSpectrogram int PlotWaterfall::rtti() const { return QwtPlotItem::Rtti_PlotSpectrogram; } /*! Change the color map Often it is useful to display the mapping between intensities and colors as an additional plot axis, showing a color bar. \param colorMap Color Map \sa colorMap(), QwtScaleWidget::setColorBarEnabled(), QwtScaleWidget::setColorMap() */ void PlotWaterfall::setColorMap(const QwtColorMap &colorMap) { delete d_data->colorMap; #if QWT_VERSION < 0x060000 d_data->colorMap = colorMap.copy(); #endif invalidateCache(); itemChanged(); } /*! \return Color Map used for mapping the intensity values to colors \sa setColorMap() */ const QwtColorMap &PlotWaterfall::colorMap() const { return *d_data->colorMap; } /*! \return Bounding rect of the data \sa QwtRasterData::boundingRect */ #if QWT_VERSION < 0x060000 QwtDoubleRect PlotWaterfall::boundingRect() const { return d_data->data->boundingRect(); } #endif /*! \brief Returns the recommended raster for a given rect. F.e the raster hint is used to limit the resolution of the image that is rendered. \param rect Rect for the raster hint \return data().rasterHint(rect) */ #if QWT_VERSION < 0x060000 QSize PlotWaterfall::rasterHint(const QwtDoubleRect &rect) const { return d_data->data->rasterHint(rect); } #endif /*! \brief Render an image from the data and color map. The area is translated into a rect of the paint device. For each pixel of this rect the intensity is mapped into a color. \param xMap X-Scale Map \param yMap Y-Scale Map \param area Area that should be rendered in scale coordinates. \return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending on the color map. \sa QwtRasterData::intensity(), QwtColorMap::rgb(), QwtColorMap::colorIndex() */ #if QWT_VERSION < 0x060000 QImage PlotWaterfall::renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtDoubleRect &area) const #else QImage PlotWaterfall::renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &area, const QSize &size) const #endif { if ( area.isEmpty() ) return QImage(); #if QWT_VERSION < 0x060000 QRect rect = transform(xMap, yMap, area); const QSize res = d_data->data->rasterHint(area); #else QRect rect(0,0,0,0); const QSize res(0,0); #endif QwtScaleMap xxMap = xMap; QwtScaleMap yyMap = yMap; if ( res.isValid() ) { /* It is useless to render an image with a higher resolution than the data offers. Of course someone will have to scale this image later into the size of the given rect, but f.e. in case of postscript this will done on the printer. */ rect.setSize(rect.size().boundedTo(res)); int px1 = rect.x(); int px2 = rect.x() + rect.width(); if ( xMap.p1() > xMap.p2() ) qSwap(px1, px2); double sx1 = area.x(); double sx2 = area.x() + area.width(); if ( xMap.s1() > xMap.s2() ) qSwap(sx1, sx2); int py1 = rect.y(); int py2 = rect.y() + rect.height(); if ( yMap.p1() > yMap.p2() ) qSwap(py1, py2); double sy1 = area.y(); double sy2 = area.y() + area.height(); if ( yMap.s1() > yMap.s2() ) qSwap(sy1, sy2); xxMap.setPaintInterval(px1, px2); xxMap.setScaleInterval(sx1, sx2); yyMap.setPaintInterval(py1, py2); yyMap.setScaleInterval(sy1, sy2); } PlotWaterfallImage image(rect.size(), d_data->colorMap->format()); #if QWT_VERSION < 0x060000 const QwtDoubleInterval intensityRange = d_data->data->range(); #else const QwtInterval intensityRange = d_data->data->interval(Qt::ZAxis); #endif if ( !intensityRange.isValid() ) return image; d_data->data->initRaster(area, rect.size()); if ( d_data->colorMap->format() == QwtColorMap::RGB ) { for ( int y = rect.top(); y <= rect.bottom(); y++ ) { const double ty = yyMap.invTransform(y); QRgb *line = (QRgb *)image.scanLine(y - rect.top()); for ( int x = rect.left(); x <= rect.right(); x++ ) { const double tx = xxMap.invTransform(x); *line++ = d_data->colorMap->rgb(intensityRange, d_data->data->value(tx, ty)); } } } else if ( d_data->colorMap->format() == QwtColorMap::Indexed ) { image.setColorTable(d_data->colorMap->colorTable(intensityRange)); for ( int y = rect.top(); y <= rect.bottom(); y++ ) { const double ty = yyMap.invTransform(y); unsigned char *line = image.scanLine(y - rect.top()); for ( int x = rect.left(); x <= rect.right(); x++ ) { const double tx = xxMap.invTransform(x); *line++ = d_data->colorMap->colorIndex(intensityRange, d_data->data->value(tx, ty)); } } } d_data->data->discardRaster(); // Mirror the image in case of inverted maps const bool hInvert = xxMap.p1() > xxMap.p2(); const bool vInvert = yyMap.p1() < yyMap.p2(); if ( hInvert || vInvert ) { image = image.mirrored(hInvert, vInvert); } return image; } /*! \brief Draw the spectrogram \param painter Painter \param xMap Maps x-values into pixel coordinates. \param yMap Maps y-values into pixel coordinates. \param canvasRect Contents rect of the canvas in painter coordinates \sa setDisplayMode, renderImage, QwtPlotRasterItem::draw, drawContourLines */ void PlotWaterfall::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &canvasRect) const { QwtPlotRasterItem::draw(painter, xMap, yMap, canvasRect); } gnuradio-3.7.2.1/gr-qtgui/lib/time_raster_sink_b_impl.h0000664000175000017500000000730112237515112022666 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_RASTER_SINK_B_IMPL_H #define INCLUDED_QTGUI_TIME_RASTER_SINK_B_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API time_raster_sink_b_impl : public time_raster_sink_b { private: void initialize(); std::string d_name; int d_nconnections; int d_index; std::vector d_residbufs; float d_scale; float *d_tmpflt; int d_argc; char *d_argv; QWidget *d_parent; TimeRasterDisplayForm *d_main_gui; int d_icols; double d_rows, d_cols; std::vector d_mult; std::vector d_offset; double d_samp_rate; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; public: time_raster_sink_b_impl(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections, QWidget *parent=NULL); ~time_raster_sink_b_impl(); bool check_topology (int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, Qt::PenStyle style); void set_line_marker(int which, QwtSymbol::Style marker); void set_line_alpha(int which, double alpha); void set_color_map(int which, const int color); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); int color_map(int which); void set_size(int width, int height); void set_samp_rate(const double samp_rate); void set_num_rows(double rows); void set_num_cols(double cols); double num_rows(); double num_cols(); void set_multiplier(const std::vector &mult); void set_offset(const std::vector &offset); void set_intensity_range(float min, float max); void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_RASTER_SINK_B_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/freq_sink_c_impl.cc0000664000175000017500000002724312237515112021453 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "freq_sink_c_impl.h" #include #include #include #include namespace gr { namespace qtgui { freq_sink_c::sptr freq_sink_c::make(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new freq_sink_c_impl(fftsize, wintype, fc, bw, name, nconnections, parent)); } freq_sink_c_impl::freq_sink_c_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) : sync_block("freq_sink_c", io_signature::make(1, -1, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_fftsize(fftsize), d_fftavg(1.0), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex(d_fftsize, true); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_complex(d_fftsize)); d_magbufs.push_back(fft::malloc_double(d_fftsize)); memset(d_residbufs[i], 0, d_fftsize*sizeof(gr_complex)); memset(d_magbufs[i], 0, d_fftsize*sizeof(double)); } buildwindow(); initialize(); } freq_sink_c_impl::~freq_sink_c_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); } delete d_fft; fft::free(d_fbuf); delete d_argv; } bool freq_sink_c_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void freq_sink_c_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void freq_sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new FreqDisplayForm(d_nconnections, d_parent); set_fft_window(d_wintype); set_fft_size(d_fftsize); set_frequency_range(d_center_freq, d_bandwidth); // initialize update time to 10 times a second set_update_time(0.1); } void freq_sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* freq_sink_c_impl::qwidget() { return d_main_gui; } PyObject* freq_sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void freq_sink_c_impl::set_fft_size(const int fftsize) { d_main_gui->setFFTSize(fftsize); } int freq_sink_c_impl::fft_size() const { return d_fftsize; } void freq_sink_c_impl::set_fft_average(const float fftavg) { d_main_gui->setFFTAverage(fftavg); } float freq_sink_c_impl::fft_average() const { return d_fftavg; } void freq_sink_c_impl::set_fft_window(const filter::firdes::win_type win) { d_main_gui->setFFTWindowType(win); } filter::firdes::win_type freq_sink_c_impl::fft_window() { return d_wintype; } void freq_sink_c_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->setFrequencyRange(d_center_freq, d_bandwidth); } void freq_sink_c_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void freq_sink_c_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void freq_sink_c_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void freq_sink_c_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void freq_sink_c_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void freq_sink_c_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void freq_sink_c_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void freq_sink_c_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void freq_sink_c_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void freq_sink_c_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string freq_sink_c_impl::title() { return d_main_gui->title().toStdString(); } std::string freq_sink_c_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string freq_sink_c_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int freq_sink_c_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int freq_sink_c_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int freq_sink_c_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double freq_sink_c_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void freq_sink_c_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void freq_sink_c_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void freq_sink_c_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void freq_sink_c_impl::reset() { d_index = 0; } void freq_sink_c_impl::fft(float *data_out, const gr_complex *data_in, int size) { if(d_window.size()) { volk_32fc_32f_multiply_32fc_a(d_fft->get_inbuf(), data_in, &d_window.front(), size); } else { memcpy(d_fft->get_inbuf(), data_in, sizeof(gr_complex)*size); } d_fft->execute(); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); // Perform shift operation unsigned int len = (unsigned int)(floor(size/2.0)); float *tmp = (float*)malloc(sizeof(float)*len); memcpy(tmp, &data_out[0], sizeof(float)*len); memcpy(&data_out[0], &data_out[len], sizeof(float)*(size - len)); memcpy(&data_out[size - len], tmp, sizeof(float)*len); free(tmp); } void freq_sink_c_impl::windowreset() { filter::firdes::win_type newwintype; newwintype = d_main_gui->getFFTWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void freq_sink_c_impl::buildwindow() { d_window.clear(); if(d_wintype != filter::firdes::WIN_NONE) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void freq_sink_c_impl::fftresize() { gr::thread::scoped_lock lock(d_mutex); int newfftsize = d_main_gui->getFFTSize(); d_fftavg = d_main_gui->getFFTAverage(); if(newfftsize != d_fftsize) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); d_residbufs[i] = fft::malloc_complex(newfftsize); d_magbufs[i] = fft::malloc_double(newfftsize); memset(d_residbufs[i], 0, newfftsize*sizeof(gr_complex)); memset(d_magbufs[i], 0, newfftsize*sizeof(double)); } // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex(d_fftsize, true); fft::free(d_fbuf); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); } } int freq_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const gr_complex *in = (const gr_complex*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; // If we have enough input for one full FFT, do it if(datasize >= resid) { if(gr::high_res_timer_now() - d_last_time > d_update_time) { for(int n = 0; n < d_nconnections; n++) { // Fill up residbuf with d_fftsize number of items in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*resid); fft(d_fbuf, d_residbufs[n], d_fftsize); for(int x = 0; x < d_fftsize; x++) { d_magbufs[n][x] = (double)((1.0-d_fftavg)*d_magbufs[n][x] + (d_fftavg)*d_fbuf[x]); } //volk_32f_convert_64f_a(d_magbufs[n], d_fbuf, d_fftsize); } d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new FreqUpdateEvent(d_magbufs, d_fftsize)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbuf for next time else { for(int n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/SpectrumGUIClass.cc0000664000175000017500000002777012207440367021317 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef SPECTRUM_GUI_CLASS_CPP #define SPECTRUM_GUI_CLASS_CPP #include //Added by qt3to4: #include #include #include const long SpectrumGUIClass::MAX_FFT_SIZE = 32768; const long SpectrumGUIClass::MIN_FFT_SIZE = 256; SpectrumGUIClass::SpectrumGUIClass(const uint64_t maxDataSize, const uint64_t fftSize, const double newCenterFrequency, const double newStartFrequency, const double newStopFrequency) { _dataPoints = maxDataSize; if(_dataPoints < 2){ _dataPoints = 2; } _lastDataPointCount = _dataPoints; _fftSize = fftSize; _pendingGUIUpdateEventsCount = 0; _droppedEntriesCount = 0; _centerFrequency = newCenterFrequency; _startFrequency = newStartFrequency; _stopFrequency = newStopFrequency; _windowType = 5; _lastGUIUpdateTime = 0; _windowOpennedFlag = false; _fftBuffersCreatedFlag = false; _powerValue = 1; } SpectrumGUIClass::~SpectrumGUIClass() { // We don't need to delete this since as a QWidget, it is supposed to be destroyed // with it's parent. Deleting it causes a segmentation fault, and not deleting it // does not leave any extra memory. //if(getWindowOpenFlag()){ //delete _spectrumDisplayForm; //} if(_fftBuffersCreatedFlag){ delete[] _fftPoints; delete[] _realTimeDomainPoints; delete[] _imagTimeDomainPoints; } } void SpectrumGUIClass::openSpectrumWindow(QWidget* parent, const bool frequency, const bool waterfall, const bool time, const bool constellation) { d_mutex.lock(); if(!_windowOpennedFlag) { if(!_fftBuffersCreatedFlag) { _fftPoints = new float[_dataPoints]; _realTimeDomainPoints = new double[_dataPoints]; _imagTimeDomainPoints = new double[_dataPoints]; _fftBuffersCreatedFlag = true; memset(_fftPoints, 0x0, _dataPoints*sizeof(float)); memset(_realTimeDomainPoints, 0x0, _dataPoints*sizeof(double)); memset(_imagTimeDomainPoints, 0x0, _dataPoints*sizeof(double)); } // Called from the Event Thread _spectrumDisplayForm = new SpectrumDisplayForm(parent); // Toggle Windows on/off _spectrumDisplayForm->toggleTabFrequency(frequency); _spectrumDisplayForm->toggleTabWaterfall(waterfall); _spectrumDisplayForm->toggleTabTime(time); _spectrumDisplayForm->toggleTabConstellation(constellation); _windowOpennedFlag = true; _spectrumDisplayForm->setSystem(this, _dataPoints, _fftSize); qApp->processEvents(); } d_mutex.unlock(); setDisplayTitle(_title); reset(); qApp->postEvent(_spectrumDisplayForm, new QEvent(QEvent::Type(QEvent::User+3))); _lastGUIUpdateTime = 0; // Draw Blank Display updateWindow(false, NULL, 0, NULL, 0, NULL, 0, gr::high_res_timer_now(), true); // Set up the initial frequency axis settings setFrequencyRange(_centerFrequency, _startFrequency, _stopFrequency); // GUI Thread only qApp->processEvents(); // Set the FFT Size combo box to display the right number int idx = _spectrumDisplayForm->FFTSizeComboBox->findText(QString("%1").arg(_fftSize)); _spectrumDisplayForm->FFTSizeComboBox->setCurrentIndex(idx); } void SpectrumGUIClass::reset() { if(getWindowOpenFlag()) { qApp->postEvent(_spectrumDisplayForm, new SpectrumFrequencyRangeEvent(_centerFrequency, _startFrequency, _stopFrequency)); qApp->postEvent(_spectrumDisplayForm, new SpectrumWindowResetEvent()); } _droppedEntriesCount = 0; // Call the following function the the Spectrum Window Reset Event window // ResetPendingGUIUpdateEvents(); } void SpectrumGUIClass::setDisplayTitle(const std::string newString) { _title.assign(newString); if(getWindowOpenFlag()){ qApp->postEvent(_spectrumDisplayForm, new SpectrumWindowCaptionEvent(_title.c_str())); } } bool SpectrumGUIClass::getWindowOpenFlag() { gr::thread::scoped_lock lock(d_mutex); bool returnFlag = false; returnFlag = _windowOpennedFlag; return returnFlag; } void SpectrumGUIClass::setWindowOpenFlag(const bool newFlag) { gr::thread::scoped_lock lock(d_mutex); _windowOpennedFlag = newFlag; } void SpectrumGUIClass::setFrequencyRange(const double centerFreq, const double startFreq, const double stopFreq) { gr::thread::scoped_lock lock(d_mutex); _centerFrequency = centerFreq; _startFrequency = startFreq; _stopFrequency = stopFreq; _spectrumDisplayForm->setFrequencyRange(_centerFrequency, _startFrequency, _stopFrequency); } double SpectrumGUIClass::getStartFrequency() { gr::thread::scoped_lock lock(d_mutex); double returnValue = 0.0; returnValue = _startFrequency; return returnValue; } double SpectrumGUIClass::getStopFrequency() { gr::thread::scoped_lock lock(d_mutex); double returnValue = 0.0; returnValue = _stopFrequency; return returnValue; } double SpectrumGUIClass::getCenterFrequency() { gr::thread::scoped_lock lock(d_mutex); double returnValue = 0.0; returnValue = _centerFrequency; return returnValue; } void SpectrumGUIClass::updateWindow(const bool updateDisplayFlag, const float* fftBuffer, const uint64_t inputBufferSize, const float* realTimeDomainData, const uint64_t realTimeDomainDataSize, const float* complexTimeDomainData, const uint64_t complexTimeDomainDataSize, const gr::high_res_timer_type timestamp, const bool lastOfMultipleFFTUpdateFlag) { //gr::thread::scoped_lock lock(d_mutex); int64_t bufferSize = inputBufferSize; bool repeatDataFlag = false; if(bufferSize > _dataPoints){ bufferSize = _dataPoints; } int64_t timeDomainBufferSize = 0; if(updateDisplayFlag) { if((fftBuffer != NULL) && (bufferSize > 0)) { memcpy(_fftPoints, fftBuffer, bufferSize * sizeof(float)); } //ALL OF THIS SHIT SHOULD BE COMBINED WITH THE FFTSHIFT //USE VOLK_32FC_DEINTERLEAVE_64F_X2_A TO GET REAL/IMAG FROM COMPLEX32 // Can't do a memcpy since ths is going from float to double data type if((realTimeDomainData != NULL) && (realTimeDomainDataSize > 0)){ const float* realTimeDomainDataPtr = realTimeDomainData; double* realTimeDomainPointsPtr = _realTimeDomainPoints; timeDomainBufferSize = realTimeDomainDataSize; memset(_imagTimeDomainPoints, 0x0, realTimeDomainDataSize*sizeof(double)); for(uint64_t number = 0; number < realTimeDomainDataSize; number++){ *realTimeDomainPointsPtr++ = *realTimeDomainDataPtr++; } } if((complexTimeDomainData != NULL) && (complexTimeDomainDataSize > 0)) { volk_32fc_deinterleave_64f_x2_a(_realTimeDomainPoints, _imagTimeDomainPoints, (const lv_32fc_t *)complexTimeDomainData, complexTimeDomainDataSize); timeDomainBufferSize = complexTimeDomainDataSize; } } // If bufferSize is zero, then just update the display by sending over the old data if(bufferSize < 1) { bufferSize = _lastDataPointCount; repeatDataFlag = true; } else { // Since there is data this time, update the count _lastDataPointCount = bufferSize; } const gr::high_res_timer_type currentTime = gr::high_res_timer_now(); const gr::high_res_timer_type lastUpdateGUITime = getLastGUIUpdateTime(); if((currentTime - lastUpdateGUITime > (4*_updateTime)*gr::high_res_timer_tps()) && (getPendingGUIUpdateEvents() > 0) && lastUpdateGUITime != 0) { // Do not update the display if too much data is pending to be displayed _droppedEntriesCount++; } else { // Draw the Data incrementPendingGUIUpdateEvents(); qApp->postEvent(_spectrumDisplayForm, new SpectrumUpdateEvent(_fftPoints, bufferSize, _realTimeDomainPoints, _imagTimeDomainPoints, timeDomainBufferSize, timestamp, repeatDataFlag, lastOfMultipleFFTUpdateFlag, currentTime, _droppedEntriesCount)); // Only reset the dropped entries counter if this is not // repeat data since repeat data is dropped by the display systems if(!repeatDataFlag) { _droppedEntriesCount = 0; } } } float SpectrumGUIClass::getPowerValue() { gr::thread::scoped_lock lock(d_mutex); float returnValue = 0; returnValue = _powerValue; return returnValue; } void SpectrumGUIClass::setPowerValue(const float value) { gr::thread::scoped_lock lock(d_mutex); _powerValue = value; } int SpectrumGUIClass::getWindowType() { gr::thread::scoped_lock lock(d_mutex); int returnValue = 0; returnValue = _windowType; return returnValue; } void SpectrumGUIClass::setWindowType(const int newType) { gr::thread::scoped_lock lock(d_mutex); _windowType = newType; } int SpectrumGUIClass::getFFTSize() { int returnValue = 0; returnValue = _fftSize; return returnValue; } int SpectrumGUIClass::getFFTSizeIndex() { gr::thread::scoped_lock lock(d_mutex); int fftsize = getFFTSize(); switch(fftsize) { case(1024): return 0; break; case(2048): return 1; break; case(4096): return 2; break; case(8192): return 3; break; case(16384): return 3; break; case(32768): return 3; break; default: return 0; } } void SpectrumGUIClass::setFFTSize(const int newSize) { gr::thread::scoped_lock lock(d_mutex); _fftSize = newSize; } gr::high_res_timer_type SpectrumGUIClass::getLastGUIUpdateTime() { gr::thread::scoped_lock lock(d_mutex); gr::high_res_timer_type returnValue; returnValue = _lastGUIUpdateTime; return returnValue; } void SpectrumGUIClass::setLastGUIUpdateTime(const gr::high_res_timer_type newTime) { gr::thread::scoped_lock lock(d_mutex); _lastGUIUpdateTime = newTime; } unsigned int SpectrumGUIClass::getPendingGUIUpdateEvents() { gr::thread::scoped_lock lock(d_mutex); unsigned int returnValue = 0; returnValue = _pendingGUIUpdateEventsCount; return returnValue; } void SpectrumGUIClass::incrementPendingGUIUpdateEvents() { gr::thread::scoped_lock lock(d_mutex); _pendingGUIUpdateEventsCount++; } void SpectrumGUIClass::decrementPendingGUIUpdateEvents() { gr::thread::scoped_lock lock(d_mutex); if(_pendingGUIUpdateEventsCount > 0){ _pendingGUIUpdateEventsCount--; } } void SpectrumGUIClass::resetPendingGUIUpdateEvents() { gr::thread::scoped_lock lock(d_mutex); _pendingGUIUpdateEventsCount = 0; } QWidget* SpectrumGUIClass::qwidget() { gr::thread::scoped_lock lock(d_mutex); return (QWidget*)_spectrumDisplayForm; } void SpectrumGUIClass::setTimeDomainAxis(double min, double max) { gr::thread::scoped_lock lock(d_mutex); _spectrumDisplayForm->setTimeDomainAxis(min, max); } void SpectrumGUIClass::setConstellationAxis(double xmin, double xmax, double ymin, double ymax) { gr::thread::scoped_lock lock(d_mutex); _spectrumDisplayForm->setConstellationAxis(xmin, xmax, ymin, ymax); } void SpectrumGUIClass::setConstellationPenSize(int size) { gr::thread::scoped_lock lock(d_mutex); _spectrumDisplayForm->setConstellationPenSize(size); } void SpectrumGUIClass::setFrequencyAxis(double min, double max) { gr::thread::scoped_lock lock(d_mutex); _spectrumDisplayForm->setFrequencyAxis(min, max); } void SpectrumGUIClass::setUpdateTime(double t) { gr::thread::scoped_lock lock(d_mutex); _updateTime = t; _spectrumDisplayForm->setUpdateTime(_updateTime); } #endif /* SPECTRUM_GUI_CLASS_CPP */ gnuradio-3.7.2.1/gr-qtgui/lib/histogram_sink_f_impl.cc0000664000175000017500000002333412237515112022513 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "histogram_sink_f_impl.h" #include #include #include #include #include namespace gr { namespace qtgui { histogram_sink_f::sptr histogram_sink_f::make(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new histogram_sink_f_impl(size, bins, xmin, xmax, name, nconnections, parent)); } histogram_sink_f_impl::histogram_sink_f_impl(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections, QWidget *parent) : sync_block("histogram_sink_f", io_signature::make(nconnections, nconnections, sizeof(float)), io_signature::make(0, 0, 0)), d_size(size), d_bins(bins), d_xmin(xmin), d_xmax(xmax), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_double(d_size)); memset(d_residbufs[i], 0, d_size*sizeof(double)); } // Set alignment properties for VOLK const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); initialize(); } histogram_sink_f_impl::~histogram_sink_f_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); // d_main_gui is a qwidget destroyed with its parent for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); } delete d_argv; } bool histogram_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void histogram_sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new HistogramDisplayForm(d_nconnections, d_parent); d_main_gui->setNumBins(d_bins); d_main_gui->setNPoints(d_size); d_main_gui->setXaxis(d_xmin, d_xmax); // initialize update time to 10 times a second set_update_time(0.1); } void histogram_sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* histogram_sink_f_impl::qwidget() { return d_main_gui; } PyObject* histogram_sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void histogram_sink_f_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void histogram_sink_f_impl::set_x_axis(double min, double max) { d_main_gui->setXaxis(min, max); } void histogram_sink_f_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void histogram_sink_f_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void histogram_sink_f_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void histogram_sink_f_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void histogram_sink_f_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void histogram_sink_f_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void histogram_sink_f_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void histogram_sink_f_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void histogram_sink_f_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string histogram_sink_f_impl::title() { return d_main_gui->title().toStdString(); } std::string histogram_sink_f_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string histogram_sink_f_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int histogram_sink_f_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int histogram_sink_f_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int histogram_sink_f_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double histogram_sink_f_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void histogram_sink_f_impl::set_nsamps(const int newsize) { gr::thread::scoped_lock lock(d_mutex); if(newsize != d_size) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); d_residbufs[i] = fft::malloc_double(newsize); memset(d_residbufs[i], 0, newsize*sizeof(double)); } // Set new size and reset buffer index // (throws away any currently held data, but who cares?) d_size = newsize; d_index = 0; d_main_gui->setNPoints(d_size); } } void histogram_sink_f_impl::set_bins(const int bins) { gr::thread::scoped_lock lock(d_mutex); d_bins = bins; d_main_gui->setNumBins(d_bins); } int histogram_sink_f_impl::nsamps() const { return d_size; } int histogram_sink_f_impl::bins() const { return d_bins; } void histogram_sink_f_impl::npoints_resize() { int newsize = d_main_gui->getNPoints(); set_nsamps(newsize); } void histogram_sink_f_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void histogram_sink_f_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void histogram_sink_f_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void histogram_sink_f_impl::enable_semilogx(bool en) { d_main_gui->setSemilogx(en); } void histogram_sink_f_impl::enable_semilogy(bool en) { d_main_gui->setSemilogy(en); } void histogram_sink_f_impl::enable_accumulate(bool en) { d_main_gui->setAccumulate(en); } void histogram_sink_f_impl::autoscalex() { d_main_gui->autoScaleX(); } void histogram_sink_f_impl::reset() { d_index = 0; } int histogram_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, j=0, idx=0; const float *in = (const float*)input_items[idx]; npoints_resize(); for(int i=0; i < noutput_items; i+=d_size) { unsigned int datasize = noutput_items - i; unsigned int resid = d_size-d_index; idx = 0; // If we have enough input for one full plot, do it if(datasize >= resid) { // Fill up residbufs with d_size number of items for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx++]; volk_32f_convert_64f_u(&d_residbufs[n][d_index], &in[j], resid); } // Update the plot if its time if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new HistogramUpdateEvent(d_residbufs, d_size)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbufs for next time // because we set the output_multiple, this should never need to be called else { for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx++]; volk_32f_convert_64f_u(&d_residbufs[n][d_index], &in[j], datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/time_raster_sink_b_impl.cc0000664000175000017500000002611212237515112023025 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "time_raster_sink_b_impl.h" #include #include #include namespace gr { namespace qtgui { time_raster_sink_b::sptr time_raster_sink_b::make(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new time_raster_sink_b_impl(samp_rate, rows, cols, mult, offset, name, nconnections, parent)); } time_raster_sink_b_impl::time_raster_sink_b_impl(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections, QWidget *parent) : sync_block("time_raster_sink_b", io_signature::make(1, -1, sizeof(char)), io_signature::make(0, 0, 0)), d_name(name), d_nconnections(nconnections), d_parent(parent), d_rows(rows), d_cols(cols), d_mult(std::vector(nconnections,1)), d_offset(std::vector(nconnections,0)), d_samp_rate(samp_rate) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; d_index = 0; d_scale = 1.0f; d_icols = static_cast(ceil(d_cols)); d_tmpflt = fft::malloc_float(d_icols); memset(d_tmpflt, 0, d_icols*sizeof(float)); for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_double(d_icols)); memset(d_residbufs[i], 0, d_icols*sizeof(double)); } set_multiplier(mult); set_offset(offset); initialize(); } time_raster_sink_b_impl::~time_raster_sink_b_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); fft::free(d_tmpflt); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); } delete d_argv; } bool time_raster_sink_b_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void time_raster_sink_b_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } // Create time raster plot; as a bit input, we expect to see 1's // and 0's from each stream, so we set the maximum intensity // (zmax) to the number of connections so after adding the // streams, the max will the the max of 1's from all streams. d_main_gui = new TimeRasterDisplayForm(d_nconnections, d_samp_rate, d_rows, d_cols, 1, d_parent); // initialize update time to 10 times a second set_update_time(0.1); } void time_raster_sink_b_impl::exec_() { d_qApplication->exec(); } QWidget* time_raster_sink_b_impl::qwidget() { return d_main_gui; } PyObject* time_raster_sink_b_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void time_raster_sink_b_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void time_raster_sink_b_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void time_raster_sink_b_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void time_raster_sink_b_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void time_raster_sink_b_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void time_raster_sink_b_impl::set_line_style(int which, Qt::PenStyle style) { d_main_gui->setLineStyle(which, style); } void time_raster_sink_b_impl::set_line_marker(int which, QwtSymbol::Style marker) { d_main_gui->setLineMarker(which, marker); } void time_raster_sink_b_impl::set_color_map(int which, const int color) { d_main_gui->setColorMap(which, color); } void time_raster_sink_b_impl::set_line_alpha(int which, double alpha) { d_main_gui->setAlpha(which, (int)(255.0*alpha)); } void time_raster_sink_b_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } void time_raster_sink_b_impl::set_samp_rate(const double samp_rate) { d_samp_rate = samp_rate; d_main_gui->setSampleRate(d_samp_rate); } void time_raster_sink_b_impl::set_num_rows(double rows) { d_main_gui->setNumRows(rows); } void time_raster_sink_b_impl::set_num_cols(double cols) { d_main_gui->setNumCols(cols); } std::string time_raster_sink_b_impl::title() { return d_main_gui->title().toStdString(); } std::string time_raster_sink_b_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string time_raster_sink_b_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int time_raster_sink_b_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int time_raster_sink_b_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int time_raster_sink_b_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } int time_raster_sink_b_impl::color_map(int which) { return d_main_gui->getColorMap(which); } double time_raster_sink_b_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } double time_raster_sink_b_impl::num_rows() { return d_main_gui->numRows(); } double time_raster_sink_b_impl::num_cols() { return d_main_gui->numCols(); } void time_raster_sink_b_impl::set_multiplier(const std::vector &mult) { if(mult.size() == 0) { for(int i = 0; i < d_nconnections; i++) { d_mult[i] = 1.0f; } } else if(mult.size() == (size_t)d_nconnections) { for(int i = 0; i < d_nconnections; i++) { d_mult[i] = mult[i]; } } else { throw std::runtime_error("time_raster_sink_b_impl::set_multiplier incorrect dimensions.\n"); } } void time_raster_sink_b_impl::set_offset(const std::vector &offset) { if(offset.size() == 0) { for(int i = 0; i < d_nconnections; i++) { d_offset[i] = 0.0f; } } else if(offset.size() == (size_t)d_nconnections) { for(int i = 0; i < d_nconnections; i++) { d_offset[i] = offset[i]; } } else { throw std::runtime_error("time_raster_sink_b_impl::set_offset incorrect dimensions.\n"); } } void time_raster_sink_b_impl::set_intensity_range(float min, float max) { d_main_gui->setIntensityRange(min, max); } void time_raster_sink_b_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void time_raster_sink_b_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void time_raster_sink_b_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void time_raster_sink_b_impl::reset() { d_index = 0; } int time_raster_sink_b_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, j=0, idx=0; const int8_t *in = (const int8_t*)input_items[0]; unsigned int cols = d_main_gui->numCols(); if(d_cols != cols) { d_cols = cols; d_index = 0; d_icols = static_cast(ceil(d_cols)); fft::free(d_tmpflt); d_tmpflt = fft::malloc_float(d_icols); memset(d_tmpflt, 0, d_icols*sizeof(float)); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); d_residbufs[i] = fft::malloc_double(d_icols); memset(d_residbufs[i], 0, d_icols*sizeof(double)); } } for(int i = 0; i < noutput_items; i += d_icols) { unsigned int datasize = noutput_items - i; unsigned int resid = d_icols-d_index; idx = 0; // If we have enough input for one full plot, do it if(datasize >= resid) { // Fill up residbufs with d_size number of items for(n = 0; n < d_nconnections; n++) { in = (const int8_t*)input_items[idx++]; volk_8i_s32f_convert_32f(d_tmpflt, &in[j], d_scale, resid); // Scale and add offset volk_32f_s32f_multiply_32f(d_tmpflt, d_tmpflt, d_mult[n], resid); for(unsigned int s = 0; s < resid; s++) d_tmpflt[s] = d_tmpflt[s] + d_offset[n]; volk_32f_convert_64f_u(&d_residbufs[n][d_index], d_tmpflt, resid); } if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new TimeRasterUpdateEvent(d_residbufs, d_icols)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbufs for next time // because we set the output_multiple, this should never need to be called else { for(n = 0; n < d_nconnections; n++) { in = (const int8_t*)input_items[idx++]; volk_8i_s32f_convert_32f(d_tmpflt, &in[j], d_scale, datasize); // Scale and add offset volk_32f_s32f_multiply_32f(d_tmpflt, d_tmpflt, d_mult[n], datasize); for(unsigned int s = 0; s < datasize; s++) d_tmpflt[s] = d_tmpflt[s] + d_offset[n]; volk_32f_convert_64f(&d_residbufs[n][d_index], d_tmpflt, datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/gnuradio-qtgui.rc.in0000664000175000017500000000332212207440367021530 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-qtgui" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-qtgui.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-qtgui.dll" VALUE "ProductName", "gnuradio-qtgui" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-qtgui/lib/qtgui_util.cc0000664000175000017500000000406312207440367020336 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include QwtPickerDblClickPointMachine::QwtPickerDblClickPointMachine() #if QWT_VERSION < 0x060000 : QwtPickerMachine () #else : QwtPickerMachine (PointSelection) #endif { } QwtPickerDblClickPointMachine::~QwtPickerDblClickPointMachine() { } #if QWT_VERSION < 0x060000 #define CMDLIST_TYPE QwtPickerMachine::CommandList #else #define CMDLIST_TYPE QList #endif CMDLIST_TYPE QwtPickerDblClickPointMachine::transition(const QwtEventPattern &eventPattern, const QEvent *e) { CMDLIST_TYPE cmdList; switch(e->type()) { case QEvent::MouseButtonDblClick: if ( eventPattern.mouseMatch(QwtEventPattern::MouseSelect1, (const QMouseEvent *)e) ) { cmdList += QwtPickerMachine::Begin; cmdList += QwtPickerMachine::Append; cmdList += QwtPickerMachine::End; } break; default: break; } return cmdList; } QwtDblClickPlotPicker::QwtDblClickPlotPicker(QwtPlotCanvas* canvas) : QwtPlotPicker(canvas) { #if QWT_VERSION < 0x060000 setSelectionFlags(QwtPicker::PointSelection); #endif } QwtDblClickPlotPicker::~QwtDblClickPlotPicker() { } QwtPickerMachine* QwtDblClickPlotPicker::stateMachine(int n) const { return new QwtPickerDblClickPointMachine; } gnuradio-3.7.2.1/gr-qtgui/lib/sink_c_impl.cc0000664000175000017500000002075612237515112020440 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "sink_c_impl.h" #include #include #include namespace gr { namespace qtgui { sink_c::sptr sink_c::make(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent) { return gnuradio::get_initial_sptr (new sink_c_impl(fftsize, wintype, fc, bw, name, plotfreq, plotwaterfall, plottime, plotconst, parent)); } sink_c_impl::sink_c_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent) : block("sink_c", io_signature::make(1, -1, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_fftsize(fftsize), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_plotfreq(plotfreq), d_plotwaterfall(plotwaterfall), d_plottime(plottime), d_plotconst(plotconst), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex (d_fftsize, true); d_index = 0; d_residbuf = new gr_complex[d_fftsize]; d_magbuf = new float[d_fftsize]; buildwindow(); initialize(); } sink_c_impl::~sink_c_impl() { delete d_main_gui; delete [] d_residbuf; delete [] d_magbuf; delete d_fft; delete d_argv; } bool sink_c_impl::check_topology(int ninputs, int noutputs) { return ninputs == 1; } void sink_c_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } if(d_center_freq < 0) { throw std::runtime_error("sink_c_impl: Received bad center frequency.\n"); } uint64_t maxBufferSize = 32768; d_main_gui = new SpectrumGUIClass(maxBufferSize, d_fftsize, d_center_freq, -d_bandwidth, d_bandwidth); d_main_gui->setDisplayTitle(d_name); d_main_gui->setWindowType((int)d_wintype); set_fft_size(d_fftsize); d_main_gui->openSpectrumWindow(d_parent, d_plotfreq, d_plotwaterfall, d_plottime, d_plotconst); // initialize update time to 10 times a second set_update_time(0.5); d_last_update = gr::high_res_timer_now(); d_update_active = false; } void sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* sink_c_impl::qwidget() { return d_main_gui->qwidget(); } PyObject* sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui->qwidget()); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void sink_c_impl::set_fft_size(const int fftsize) { d_fftsize = fftsize; d_main_gui->setFFTSize(fftsize); } int sink_c_impl::fft_size() const { return d_fftsize; } void sink_c_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->setFrequencyRange(d_center_freq, -d_bandwidth, d_bandwidth); } void sink_c_impl::set_fft_power_db(double min, double max) { d_main_gui->setFrequencyAxis(min, max); } /* void sink_c_impl::set_time_domain_axis(double min, double max) { d_main_gui->setTimeDomainAxis(min, max); } void sink_c_impl::set_constellation_axis(double xmin, double xmax, double ymin, double ymax) { d_main_gui->setConstellationAxis(xmin, xmax, ymin, ymax); } void sink_c_impl::set_constellation_pen_size(int size) { d_main_gui->setConstellationPenSize(size); } */ void sink_c_impl::set_update_time(double t) { d_update_time = t * gr::high_res_timer_tps(); d_main_gui->setUpdateTime(t); } void sink_c_impl::fft(float *data_out, const gr_complex *data_in, int size) { if (d_window.size()) { volk_32fc_32f_multiply_32fc_a(d_fft->get_inbuf(), data_in, &d_window.front(), size); } else { memcpy (d_fft->get_inbuf(), data_in, sizeof(gr_complex)*size); } d_fft->execute (); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); } void sink_c_impl::windowreset() { filter::firdes::win_type newwintype; newwintype = (filter::firdes::win_type)d_main_gui->getWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void sink_c_impl::buildwindow() { d_window.clear(); if(d_wintype != 0) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void sink_c_impl::fftresize() { int newfftsize = d_main_gui->getFFTSize(); if(newfftsize != d_fftsize) { // Resize residbuf and replace data delete [] d_residbuf; d_residbuf = new gr_complex[newfftsize]; delete [] d_magbuf; d_magbuf = new float[newfftsize]; // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex (d_fftsize, true); } } int sink_c_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const gr_complex *in = (const gr_complex*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; if (!d_update_active && (gr::high_res_timer_now() - d_last_update) < d_update_time) { consume_each(noutput_items); return noutput_items; } else { d_last_update = gr::high_res_timer_now(); d_update_active = true; } // If we have enough input for one full FFT, do it if(datasize >= resid) { const gr::high_res_timer_type currentTime = gr::high_res_timer_now(); // Fill up residbuf with d_fftsize number of items memcpy(d_residbuf+d_index, &in[j], sizeof(gr_complex)*resid); d_index = 0; j += resid; fft(d_magbuf, d_residbuf, d_fftsize); d_main_gui->updateWindow(true, d_magbuf, d_fftsize, NULL, 0, (float*)d_residbuf, d_fftsize, currentTime, true); d_update_active = false; } // Otherwise, copy what we received into the residbuf for next time else { memcpy(d_residbuf+d_index, &in[j], sizeof(gr_complex)*datasize); d_index += datasize; j += datasize; } } consume_each(j); return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/timerasterdisplayform.cc0000664000175000017500000001441712237515112022577 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include TimeRasterDisplayForm::TimeRasterDisplayForm(int nplots, double samp_rate, double rows, double cols, double zmax, QWidget* parent) : DisplayForm(nplots, parent) { #if QWT_VERSION < 0x060000 std::cerr << "Warning: QWT5 has been found which has serious performance issues with raster plots." << std::endl << " Consider updating to QWT version 6 to use the time raster GUIs." << std::endl << std::endl; #endif d_layout = new QGridLayout(this); d_display_plot = new TimeRasterDisplayPlot(nplots, samp_rate, rows, cols, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); d_min_val = 10; d_max_val = -10; // We don't use the normal menus that are part of the displayform. // Clear them out to get rid of their resources. for(int i = 0; i < nplots; i++) { d_lines_menu[i]->clear(); } d_line_title_act.clear(); d_line_color_menu.clear(); d_line_width_menu.clear(); d_line_style_menu.clear(); d_line_marker_menu.clear(); d_marker_alpha_menu.clear(); // Now create our own menus for(int i = 0; i < nplots; i++) { ColorMapMenu *colormap = new ColorMapMenu(i, this); connect(colormap, SIGNAL(whichTrigger(int, const int, const QColor&, const QColor&)), this, SLOT(setColorMap(int, const int, const QColor&, const QColor&))); d_lines_menu[i]->addMenu(colormap); d_marker_alpha_menu.push_back(new MarkerAlphaMenu(i, this)); connect(d_marker_alpha_menu[i], SIGNAL(whichTrigger(int, int)), this, SLOT(setAlpha(int, int))); d_lines_menu[i]->addMenu(d_marker_alpha_menu[i]); } // One scales once when clicked, so no on/off toggling d_autoscale_act->setText(tr("Auto Scale")); d_autoscale_act->setCheckable(false); PopupMenu *colsmenu = new PopupMenu("Num. Columns", this); d_menu->addAction(colsmenu); connect(colsmenu, SIGNAL(whichTrigger(QString)), this, SLOT(setNumCols(QString))); PopupMenu *rowsmenu = new PopupMenu("Num. Rows", this); d_menu->addAction(rowsmenu); connect(rowsmenu, SIGNAL(whichTrigger(QString)), this, SLOT(setNumRows(QString))); getPlot()->setIntensityRange(0, zmax); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } TimeRasterDisplayForm::~TimeRasterDisplayForm() { // Don't worry about deleting Display Plots - they are deleted when // parents are deleted } TimeRasterDisplayPlot* TimeRasterDisplayForm::getPlot() { return ((TimeRasterDisplayPlot*)d_display_plot); } double TimeRasterDisplayForm::numRows() { return getPlot()->numRows(); } double TimeRasterDisplayForm::numCols() { return getPlot()->numCols(); } int TimeRasterDisplayForm::getColorMap(int which) { return getPlot()->getIntensityColorMapType(which); } int TimeRasterDisplayForm::getAlpha(int which) { return getPlot()->getAlpha(which); } double TimeRasterDisplayForm::getMinIntensity(int which) { return getPlot()->getMinIntensity(which); } double TimeRasterDisplayForm::getMaxIntensity(int which) { return getPlot()->getMaxIntensity(which); } void TimeRasterDisplayForm::newData(const QEvent *updateEvent) { TimeRasterUpdateEvent *event = (TimeRasterUpdateEvent*)updateEvent; const std::vector dataPoints = event->getPoints(); const uint64_t numDataPoints = event->getNumDataPoints(); d_min_val = 10; d_max_val = -10; for(size_t i=0; i < dataPoints.size(); i++) { double *min_val = std::min_element(&dataPoints[i][0], &dataPoints[i][numDataPoints-1]); double *max_val = std::max_element(&dataPoints[i][0], &dataPoints[i][numDataPoints-1]); if(*min_val < d_min_val) d_min_val = *min_val; if(*max_val > d_max_val) d_max_val = *max_val; } getPlot()->plotNewData(dataPoints, numDataPoints); } void TimeRasterDisplayForm::customEvent( QEvent * e) { if(e->type() == TimeRasterUpdateEvent::Type()) { newData(e); } } void TimeRasterDisplayForm::setNumRows(double rows) { getPlot()->setNumRows(rows); getPlot()->replot(); } void TimeRasterDisplayForm::setNumRows(QString rows) { getPlot()->setNumRows(rows.toDouble()); getPlot()->replot(); } void TimeRasterDisplayForm::setNumCols(double cols) { getPlot()->setNumCols(cols); getPlot()->replot(); } void TimeRasterDisplayForm::setNumCols(QString cols) { getPlot()->setNumCols(cols.toDouble()); getPlot()->replot(); } void TimeRasterDisplayForm::setSampleRate(const double rate) { getPlot()->setSampleRate(rate); getPlot()->replot(); } void TimeRasterDisplayForm::setSampleRate(const QString &rate) { getPlot()->setSampleRate(rate.toDouble()); getPlot()->replot(); } void TimeRasterDisplayForm::setColorMap(int which, const int newType, const QColor lowColor, const QColor highColor) { getPlot()->setIntensityColorMapType(which, newType, lowColor, highColor); getPlot()->replot(); } void TimeRasterDisplayForm::setAlpha(int which, int alpha) { getPlot()->setAlpha(which, alpha); getPlot()->replot(); } void TimeRasterDisplayForm::setIntensityRange(const double minIntensity, const double maxIntensity) { getPlot()->setIntensityRange(minIntensity, maxIntensity); getPlot()->replot(); } void TimeRasterDisplayForm::autoScale(bool en) { double min_int = d_min_val; double max_int = d_max_val; getPlot()->setIntensityRange(min_int, max_int); getPlot()->replot(); } gnuradio-3.7.2.1/gr-qtgui/lib/waterfalldisplayform.cc0000664000175000017500000001534212245466767022423 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include WaterfallDisplayForm::WaterfallDisplayForm(int nplots, QWidget* parent) : DisplayForm(nplots, parent) { d_int_validator = new QIntValidator(this); d_int_validator->setBottom(0); d_layout = new QGridLayout(this); d_display_plot = new WaterfallDisplayPlot(nplots, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); d_center_freq = 0; d_samp_rate = 0; d_fftsize = 1024; d_fftavg = 1.0; d_min_val = 1000; d_max_val = -1000; // We don't use the normal menus that are part of the displayform. // Clear them out to get rid of their resources. for(int i = 0; i < nplots; i++) { d_lines_menu[i]->clear(); } d_line_title_act.clear(); d_line_color_menu.clear(); d_line_width_menu.clear(); d_line_style_menu.clear(); d_line_marker_menu.clear(); d_marker_alpha_menu.clear(); // Now create our own menus for(int i = 0; i < nplots; i++) { ColorMapMenu *colormap = new ColorMapMenu(i, this); connect(colormap, SIGNAL(whichTrigger(int, const int, const QColor&, const QColor&)), this, SLOT(setColorMap(int, const int, const QColor&, const QColor&))); d_lines_menu[i]->addMenu(colormap); d_marker_alpha_menu.push_back(new MarkerAlphaMenu(i, this)); connect(d_marker_alpha_menu[i], SIGNAL(whichTrigger(int, int)), this, SLOT(setAlpha(int, int))); d_lines_menu[i]->addMenu(d_marker_alpha_menu[i]); } // One scales once when clicked, so no on/off toggling d_autoscale_act->setText(tr("Auto Scale")); d_autoscale_act->setCheckable(false); FFTSizeMenu *sizemenu = new FFTSizeMenu(this); FFTAverageMenu *avgmenu = new FFTAverageMenu(this); FFTWindowMenu *winmenu = new FFTWindowMenu(this); d_menu->addMenu(sizemenu); d_menu->addMenu(avgmenu); d_menu->addMenu(winmenu); connect(sizemenu, SIGNAL(whichTrigger(int)), this, SLOT(setFFTSize(const int))); connect(avgmenu, SIGNAL(whichTrigger(float)), this, SLOT(setFFTAverage(const float))); connect(winmenu, SIGNAL(whichTrigger(gr::filter::firdes::win_type)), this, SLOT(setFFTWindowType(const gr::filter::firdes::win_type))); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } WaterfallDisplayForm::~WaterfallDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete d_int_validator; } WaterfallDisplayPlot* WaterfallDisplayForm::getPlot() { return ((WaterfallDisplayPlot*)d_display_plot); } void WaterfallDisplayForm::newData(const QEvent *updateEvent) { WaterfallUpdateEvent *event = (WaterfallUpdateEvent*)updateEvent; const std::vector dataPoints = event->getPoints(); const uint64_t numDataPoints = event->getNumDataPoints(); const gr::high_res_timer_type dataTimestamp = event->getDataTimestamp(); d_min_val = 1000; d_max_val = -1000; for(size_t i=0; i < dataPoints.size(); i++) { double *min_val = std::min_element(&dataPoints[i][0], &dataPoints[i][numDataPoints-1]); double *max_val = std::max_element(&dataPoints[i][0], &dataPoints[i][numDataPoints-1]); if(*min_val < d_min_val) d_min_val = *min_val; if(*max_val > d_max_val) d_max_val = *max_val; } getPlot()->plotNewData(dataPoints, numDataPoints, d_update_time, dataTimestamp, 0); } void WaterfallDisplayForm::customEvent( QEvent * e) { if(e->type() == WaterfallUpdateEvent::Type()) { newData(e); } } int WaterfallDisplayForm::getFFTSize() const { return d_fftsize; } float WaterfallDisplayForm::getFFTAverage() const { return d_fftavg; } gr::filter::firdes::win_type WaterfallDisplayForm::getFFTWindowType() const { return d_fftwintype; } int WaterfallDisplayForm::getColorMap(int which) { return getPlot()->getIntensityColorMapType(which); } int WaterfallDisplayForm::getAlpha(int which) { return getPlot()->getAlpha(which); } double WaterfallDisplayForm::getMinIntensity(int which) { return getPlot()->getMinIntensity(which); } double WaterfallDisplayForm::getMaxIntensity(int which) { return getPlot()->getMaxIntensity(which); } void WaterfallDisplayForm::setSampleRate(const QString &samprate) { setFrequencyRange(d_center_freq, samprate.toDouble()); } void WaterfallDisplayForm::setFFTSize(const int newsize) { d_fftsize = newsize; } void WaterfallDisplayForm::setFFTAverage(const float newavg) { d_fftavg = newavg; } void WaterfallDisplayForm::setFFTWindowType(const gr::filter::firdes::win_type newwin) { d_fftwintype = newwin; } void WaterfallDisplayForm::setFrequencyRange(const double centerfreq, const double bandwidth) { std::string strunits[4] = {"Hz", "kHz", "MHz", "GHz"}; double units10 = floor(log10(bandwidth)); double units3 = std::max(floor(units10 / 3.0), 0.0); double units = pow(10, (units10-fmod(units10, 3.0))); int iunit = static_cast(units3); d_center_freq = centerfreq; d_samp_rate = bandwidth; getPlot()->setFrequencyRange(centerfreq, bandwidth, units, strunits[iunit]); getPlot()->replot(); } void WaterfallDisplayForm::setColorMap(int which, const int newType, const QColor lowColor, const QColor highColor) { getPlot()->setIntensityColorMapType(which, newType, lowColor, highColor); getPlot()->replot(); } void WaterfallDisplayForm::setAlpha(int which, int alpha) { getPlot()->setAlpha(which, alpha); getPlot()->replot(); } void WaterfallDisplayForm::setIntensityRange(const double minIntensity, const double maxIntensity) { getPlot()->setIntensityRange(minIntensity, maxIntensity); getPlot()->replot(); } void WaterfallDisplayForm::autoScale(bool en) { double min_int = d_min_val - 5; double max_int = d_max_val + 10; getPlot()->setIntensityRange(min_int, max_int); getPlot()->replot(); } void WaterfallDisplayForm::clearData() { getPlot()->clearData(); } gnuradio-3.7.2.1/gr-qtgui/lib/histogram_sink_f_impl.h0000664000175000017500000000671312237515112022357 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_HISTOGRAM_SINK_F_IMPL_H #define INCLUDED_QTGUI_HISTOGRAM_SINK_F_IMPL_H #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API histogram_sink_f_impl : public histogram_sink_f { private: void initialize(); gr::thread::mutex d_mutex; int d_size; int d_bins; double d_xmin, d_xmax; std::string d_name; int d_nconnections; int d_index; std::vector d_residbufs; int d_argc; char *d_argv; QWidget *d_parent; HistogramDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; void npoints_resize(); public: histogram_sink_f_impl(int size, int bins, double xmin, double xmax, const std::string &name, int nconnections, QWidget *parent=NULL); ~histogram_sink_f_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_y_axis(double min, double max); void set_x_axis(double min, double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, int style); void set_line_marker(int which, int marker); void set_line_alpha(int which, double alpha); void set_nsamps(const int newsize); void set_bins(const int bins); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); void set_size(int width, int height); void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void enable_semilogx(bool en); void enable_semilogy(bool en); void enable_accumulate(bool en); void autoscalex(); int nsamps() const; int bins() const; void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_HISTOGRAM_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/TimeRasterDisplayPlot.cc0000664000175000017500000003516512237515112022415 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIMERASTER_DISPLAY_PLOT_C #define TIMERASTER_DISPLAY_PLOT_C #include #include #include #include #include #include #include #include #include #include namespace pt = boost::posix_time; #include /*********************************************************************** * Text scale widget to provide X (time) axis text **********************************************************************/ class QwtXScaleDraw: public QwtScaleDraw, public TimeScaleData { public: QwtXScaleDraw():QwtScaleDraw(),TimeScaleData() { } virtual ~QwtXScaleDraw() { } virtual QwtText label(double value) const { double secs = double(value * getSecondsPerLine()); return QwtText(QString("").sprintf("%.2f", secs)); } virtual void initiateUpdate() { // Do this in one call rather than when zeroTime and secondsPerLine // updates is to prevent the display from being updated too often... invalidateCache(); } }; /*********************************************************************** * Text scale widget to provide Y axis text **********************************************************************/ class QwtYScaleDraw: public QwtScaleDraw { public: QwtYScaleDraw(): QwtScaleDraw(), d_rows(0) { } virtual ~QwtYScaleDraw() { } virtual QwtText label(double value) const { if(d_rows > 0) value = d_rows - value; return QwtText(QString("").sprintf("%.0f", value)); } virtual void initiateUpdate() { // Do this in one call rather than when zeroTime and secondsPerLine // updates is to prevent the display from being updated too often... invalidateCache(); } void setRows(double rows) { rows>0 ? d_rows = rows : d_rows = 0; } private: double d_rows; }; class TimePrecisionClass { public: TimePrecisionClass(const int timePrecision) { d_timePrecision = timePrecision; } virtual ~TimePrecisionClass() { } virtual unsigned int getTimePrecision() const { return d_timePrecision; } virtual void setTimePrecision(const unsigned int newPrecision) { d_timePrecision = newPrecision; } protected: unsigned int d_timePrecision; }; /*********************************************************************** * Widget to provide mouse pointer coordinate text **********************************************************************/ class TimeRasterZoomer: public QwtPlotZoomer, public TimePrecisionClass, public TimeScaleData { public: TimeRasterZoomer(QwtPlotCanvas* canvas, double rows, double cols, const unsigned int timePrecision) : QwtPlotZoomer(canvas), TimePrecisionClass(timePrecision), TimeScaleData(), d_rows(static_cast(rows)), d_cols(static_cast(cols)) { setTrackerMode(QwtPicker::AlwaysOn); } virtual ~TimeRasterZoomer() { } virtual void updateTrackerText() { updateDisplay(); } void setUnitType(const std::string &type) { d_unitType = type; } void setColumns(const double cols) { d_cols = cols; } void setRows(const double rows) { d_rows = rows; } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText( QPoint const &p ) const { QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); double x = dp.x() * getSecondsPerLine(); //double y = dp.y() * getSecondsPerLine() * d_cols; double y = floor(d_rows - dp.y()); QwtText t(QString("%1 %2, %3") .arg(x, 0, 'f', getTimePrecision()) .arg(d_unitType.c_str()) .arg(y, 0, 'f', 0)); return t; } private: std::string d_unitType; double d_rows, d_cols; }; /********************************************************************* * Main time raster plot widget *********************************************************************/ TimeRasterDisplayPlot::TimeRasterDisplayPlot(int nplots, double samp_rate, double rows, double cols, QWidget* parent) : DisplayPlot(nplots, parent) { d_zoomer = NULL; // need this for proper init resize(parent->width(), parent->height()); d_samp_rate = samp_rate; d_cols = cols; d_rows = rows; d_numPoints = d_cols; setAxisScaleDraw(QwtPlot::xBottom, new QwtXScaleDraw()); setAxisScaleDraw(QwtPlot::yLeft, new QwtYScaleDraw()); for(int i = 0; i < d_nplots; i++) { d_data.push_back(new TimeRasterData(d_rows, d_cols)); d_raster.push_back(new PlotTimeRaster("Raster")); d_raster[i]->setData(d_data[i]); // a hack around the fact that we aren't using plot curves for the // raster plots. d_plot_curve.push_back(new QwtPlotCurve(QString("Data"))); d_raster[i]->attach(this); d_color_map_type.push_back(INTENSITY_COLOR_MAP_TYPE_BLACK_HOT); setAlpha(i, 255/d_nplots); } // Set bottom plot with no transparency as a base setAlpha(0, 255); // LeftButton for the zooming // MidButton for the panning // RightButton: zoom out by 1 // Ctrl+RighButton: zoom out to full size d_zoomer = new TimeRasterZoomer(canvas(), d_rows, d_cols, 0); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor c(Qt::red); d_zoomer->setRubberBandPen(c); d_zoomer->setTrackerPen(c); // Set intensity color now (needed d_zoomer before we could do this). // We've made sure the old type is different than here so we'll // force and update. for(int i = 0; i < d_nplots; i++) { setIntensityColorMapType(i, INTENSITY_COLOR_MAP_TYPE_WHITE_HOT, QColor("white"), QColor("white")); } _updateIntensityRangeDisplay(); reset(); } TimeRasterDisplayPlot::~TimeRasterDisplayPlot() { } void TimeRasterDisplayPlot::reset() { for(int i = 0; i < d_nplots; i++) { d_data[i]->resizeData(d_rows, d_cols); d_data[i]->reset(); } // Update zoomer/picker text units std::string strunits[4] = {"sec", "ms", "us", "ns"}; double units10 = floor(log10(d_samp_rate)); double units3 = std::max(floor(units10/3), 0.0); double units = pow(10, (units10-fmod(units10, 3.0))); int iunit = static_cast(units3); double sec_per_samp = units/d_samp_rate; QwtYScaleDraw* yScale = (QwtYScaleDraw*)axisScaleDraw(QwtPlot::yLeft); yScale->setRows(d_rows); QwtXScaleDraw* xScale = (QwtXScaleDraw*)axisScaleDraw(QwtPlot::xBottom); xScale->setSecondsPerLine(sec_per_samp); setAxisTitle(QwtPlot::xBottom, QString("Time (%1)") .arg(strunits[iunit].c_str())); xScale->initiateUpdate(); // Load up the new base zoom settings if(d_zoomer) { double display_units = 4; ((TimeRasterZoomer*)d_zoomer)->setColumns(d_cols); ((TimeRasterZoomer*)d_zoomer)->setRows(d_rows); ((TimeRasterZoomer*)d_zoomer)->setSecondsPerLine(sec_per_samp); ((TimeRasterZoomer*)d_zoomer)->setTimePrecision(display_units); ((TimeRasterZoomer*)d_zoomer)->setUnitType(strunits[iunit]); QwtDoubleRect newSize = d_zoomer->zoomBase(); newSize.setLeft(0); newSize.setWidth(d_cols); newSize.setBottom(0); newSize.setHeight(d_rows); d_zoomer->zoom(newSize); d_zoomer->setZoomBase(newSize); d_zoomer->zoom(0); } } void TimeRasterDisplayPlot::setNumRows(double rows) { d_rows = rows; reset(); } void TimeRasterDisplayPlot::setNumCols(double cols) { d_cols = cols; reset(); } void TimeRasterDisplayPlot::setAlpha(int which, int alpha) { d_raster[which]->setAlpha(alpha); } void TimeRasterDisplayPlot::setSampleRate(double samprate) { d_samp_rate = samprate; reset(); } double TimeRasterDisplayPlot::numRows() const { return d_rows; } double TimeRasterDisplayPlot::numCols() const { return d_cols; } int TimeRasterDisplayPlot::getAlpha(int which) { return d_raster[which]->alpha(); } void TimeRasterDisplayPlot::setPlotDimensions(const double rows, const double cols, const double units, const std::string &strunits) { bool rst = false; if((rows != d_rows) || (cols != d_cols)) rst = true; d_rows = rows; d_cols = cols; if((axisScaleDraw(QwtPlot::xBottom) != NULL) && (d_zoomer != NULL)) { if(rst) { reset(); } } } void TimeRasterDisplayPlot::plotNewData(const std::vector dataPoints, const int64_t numDataPoints) { if(!d_stop) { if(numDataPoints > 0) { for(int i = 0; i < d_nplots; i++) { d_data[i]->addData(dataPoints[i], numDataPoints); d_raster[i]->invalidateCache(); d_raster[i]->itemChanged(); } replot(); } } } void TimeRasterDisplayPlot::plotNewData(const double* dataPoints, const int64_t numDataPoints) { std::vector vecDataPoints; vecDataPoints.push_back((double*)dataPoints); plotNewData(vecDataPoints, numDataPoints); } void TimeRasterDisplayPlot::setIntensityRange(const double minIntensity, const double maxIntensity) { for(int i = 0; i < d_nplots; i++) { #if QWT_VERSION < 0x060000 d_data[i]->setRange(QwtDoubleInterval(minIntensity, maxIntensity)); #else d_data[i]->setInterval(Qt::ZAxis, QwtInterval(minIntensity, maxIntensity)); #endif emit updatedLowerIntensityLevel(minIntensity); emit updatedUpperIntensityLevel(maxIntensity); _updateIntensityRangeDisplay(); } } double TimeRasterDisplayPlot::getMinIntensity(int which) const { #if QWT_VERSION < 0x060000 QwtDoubleInterval r = d_data[which]->range(); #else QwtInterval r = d_data[which]->interval(Qt::ZAxis); #endif return r.minValue(); } double TimeRasterDisplayPlot::getMaxIntensity(int which) const { #if QWT_VERSION < 0x060000 QwtDoubleInterval r = d_data[which]->range(); #else QwtInterval r = d_data[which]->interval(Qt::ZAxis); #endif return r.maxValue(); } void TimeRasterDisplayPlot::replot() { // Update the x-axis display if(axisWidget(QwtPlot::yLeft) != NULL) { axisWidget(QwtPlot::yLeft)->update(); } // Update the y-axis display if(axisWidget(QwtPlot::xBottom) != NULL) { axisWidget(QwtPlot::xBottom)->update(); } if(d_zoomer != NULL) { ((TimeRasterZoomer*)d_zoomer)->updateTrackerText(); } QwtPlot::replot(); } int TimeRasterDisplayPlot::getIntensityColorMapType(int which) const { if(which >= (int)d_color_map_type.size()) throw std::runtime_error("TimerasterDisplayPlot::GetIntesityColorMap: invalid which.\n"); return d_color_map_type[which]; } void TimeRasterDisplayPlot::setIntensityColorMapType(const int which, const int newType, const QColor lowColor, const QColor highColor) { if(which >= (int)d_color_map_type.size()) throw std::runtime_error("TimerasterDisplayPlot::setIntesityColorMap: invalid which.\n"); if((d_color_map_type[which] != newType) || ((newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED) && (lowColor.isValid() && highColor.isValid()))) { switch(newType) { case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR: { d_color_map_type[which] = newType; d_raster[which]->setColorMap(new ColorMap_MultiColor()); if(d_zoomer) d_zoomer->setTrackerPen(QColor(Qt::black)); break; } case INTENSITY_COLOR_MAP_TYPE_WHITE_HOT: { d_color_map_type[which] = newType; d_raster[which]->setColorMap(new ColorMap_WhiteHot()); break; } case INTENSITY_COLOR_MAP_TYPE_BLACK_HOT: { d_color_map_type[which] = newType; d_raster[which]->setColorMap(new ColorMap_BlackHot()); break; } case INTENSITY_COLOR_MAP_TYPE_INCANDESCENT: { d_color_map_type[which] = newType; d_raster[which]->setColorMap(new ColorMap_Incandescent()); break; } case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED: { d_low_intensity = lowColor; d_high_intensity = highColor; d_color_map_type[which] = newType; d_raster[which]->setColorMap(new ColorMap_UserDefined(lowColor, highColor)); break; } default: break; } _updateIntensityRangeDisplay(); } } const QColor TimeRasterDisplayPlot::getUserDefinedLowIntensityColor() const { return d_low_intensity; } const QColor TimeRasterDisplayPlot::getUserDefinedHighIntensityColor() const { return d_high_intensity; } void TimeRasterDisplayPlot::_updateIntensityRangeDisplay() { QwtScaleWidget *rightAxis = axisWidget(QwtPlot::yRight); rightAxis->setTitle("Intensity"); rightAxis->setColorBarEnabled(true); for(int i = 0; i < d_nplots; i++) { #if QWT_VERSION < 0x060000 rightAxis->setColorMap(d_raster[i]->data()->range(), d_raster[i]->colorMap()); setAxisScale(QwtPlot::yRight, d_raster[i]->data()->range().minValue(), d_raster[i]->data()->range().maxValue()); #else QwtInterval intv = d_raster[i]->interval(Qt::ZAxis); switch(d_color_map_type[i]) { case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR: rightAxis->setColorMap(intv, new ColorMap_MultiColor()); break; case INTENSITY_COLOR_MAP_TYPE_WHITE_HOT: rightAxis->setColorMap(intv, new ColorMap_WhiteHot()); break; case INTENSITY_COLOR_MAP_TYPE_BLACK_HOT: rightAxis->setColorMap(intv, new ColorMap_BlackHot()); break; case INTENSITY_COLOR_MAP_TYPE_INCANDESCENT: rightAxis->setColorMap(intv, new ColorMap_Incandescent()); break; case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED: rightAxis->setColorMap(intv, new ColorMap_UserDefined(d_low_intensity, d_high_intensity)); break; default: rightAxis->setColorMap(intv, new ColorMap_MultiColor()); break; } setAxisScale(QwtPlot::yRight, intv.minValue(), intv.maxValue()); #endif enableAxis(QwtPlot::yRight); plotLayout()->setAlignCanvasToScales(true); // Tell the display to redraw everything d_raster[i]->invalidateCache(); d_raster[i]->itemChanged(); } // Draw again replot(); } #endif /* TIMERASTER_DISPLAY_PLOT_C */ gnuradio-3.7.2.1/gr-qtgui/lib/waterfallGlobalData.cc0000664000175000017500000001577612207440367022061 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef WATERFALL_GLOBAL_DATA_CPP #define WATERFALL_GLOBAL_DATA_CPP #include #include WaterfallData::WaterfallData(const double minimumFrequency, const double maximumFrequency, const uint64_t fftPoints, const unsigned int historyExtent) #if QWT_VERSION < 0x060000 : QwtRasterData(QwtDoubleRect(minimumFrequency /* X START */, 0 /* Y START */, maximumFrequency - minimumFrequency /* WIDTH */, static_cast(historyExtent)/* HEIGHT */)) #else : QwtRasterData() #endif { _intensityRange = QwtDoubleInterval(-200.0, 0.0); _fftPoints = fftPoints; _historyLength = historyExtent; _spectrumData = new double[_fftPoints * _historyLength]; #if QWT_VERSION >= 0x060000 setInterval(Qt::XAxis, QwtInterval(minimumFrequency, maximumFrequency)); setInterval(Qt::YAxis, QwtInterval(0, historyExtent)); setInterval(Qt::ZAxis, QwtInterval(-200, 0.0)); #endif reset(); } WaterfallData::~WaterfallData() { delete[] _spectrumData; } void WaterfallData::reset() { memset(_spectrumData, 0x0, _fftPoints*_historyLength*sizeof(double)); _numLinesToUpdate = -1; } void WaterfallData::copy(const WaterfallData* rhs) { #if QWT_VERSION < 0x060000 if((_fftPoints != rhs->getNumFFTPoints()) || (boundingRect() != rhs->boundingRect()) ){ _fftPoints = rhs->getNumFFTPoints(); setBoundingRect(rhs->boundingRect()); delete[] _spectrumData; _spectrumData = new double[_fftPoints * _historyLength]; } #else if(_fftPoints != rhs->getNumFFTPoints()) { _fftPoints = rhs->getNumFFTPoints(); delete[] _spectrumData; _spectrumData = new double[_fftPoints * _historyLength]; } #endif reset(); setSpectrumDataBuffer(rhs->getSpectrumDataBuffer()); setNumLinesToUpdate(rhs->getNumLinesToUpdate()); #if QWT_VERSION < 0x060000 setRange(rhs->range()); #else setInterval(Qt::XAxis, rhs->interval(Qt::XAxis)); setInterval(Qt::YAxis, rhs->interval(Qt::YAxis)); setInterval(Qt::ZAxis, rhs->interval(Qt::ZAxis)); #endif } void WaterfallData::resizeData(const double startFreq, const double stopFreq, const uint64_t fftPoints) { #if QWT_VERSION < 0x060000 if((fftPoints != getNumFFTPoints()) || (boundingRect().width() != (stopFreq - startFreq)) || (boundingRect().left() != startFreq)){ setBoundingRect(QwtDoubleRect(startFreq, 0, stopFreq-startFreq, boundingRect().height())); _fftPoints = fftPoints; delete[] _spectrumData; _spectrumData = new double[_fftPoints * _historyLength]; } #else if((fftPoints != getNumFFTPoints()) || (interval(Qt::XAxis).width() != (stopFreq - startFreq)) || (interval(Qt::XAxis).minValue() != startFreq)){ setInterval(Qt::XAxis, QwtInterval(startFreq, stopFreq)); _fftPoints = fftPoints; delete[] _spectrumData; _spectrumData = new double[_fftPoints * _historyLength]; } #endif reset(); } QwtRasterData *WaterfallData::copy() const { #if QWT_VERSION < 0x060000 WaterfallData* returnData = new WaterfallData(boundingRect().left(), boundingRect().right(), _fftPoints, _historyLength); #else WaterfallData* returnData = new WaterfallData(interval(Qt::XAxis).minValue(), interval(Qt::XAxis).maxValue(), _fftPoints, _historyLength); #endif returnData->copy(this); return returnData; } #if QWT_VERSION < 0x060000 QwtDoubleInterval WaterfallData::range() const { return _intensityRange; } void WaterfallData::setRange(const QwtDoubleInterval& newRange) { _intensityRange = newRange; } #endif double WaterfallData::value(double x, double y) const { double returnValue = 0.0; #if QWT_VERSION < 0x060000 const unsigned int intY = static_cast((1.0 - (y/boundingRect().height())) * static_cast(_historyLength-1)); const unsigned int intX = static_cast((((x - boundingRect().left()) / boundingRect().width()) * static_cast(_fftPoints-1)) + 0.5); #else double height = interval(Qt::YAxis).maxValue(); double left = interval(Qt::XAxis).minValue(); double right = interval(Qt::XAxis).maxValue(); double ylen = static_cast(_historyLength-1); double xlen = static_cast(_fftPoints-1); const unsigned int intY = static_cast((1.0 - y/height) * ylen); const unsigned int intX = static_cast((((x - left) / (right-left)) * xlen) + 0.5); #endif const int location = (intY * _fftPoints) + intX; if((location > -1) && (location < static_cast(_fftPoints * _historyLength))){ returnValue = _spectrumData[location]; } return returnValue; } uint64_t WaterfallData::getNumFFTPoints() const { return _fftPoints; } void WaterfallData::addFFTData(const double* fftData, const uint64_t fftDataSize, const int droppedFrames){ if(fftDataSize == _fftPoints){ int64_t heightOffset = _historyLength - 1 - droppedFrames; uint64_t drawingDroppedFrames = droppedFrames; // Any valid data rolled off the display so just fill in zeros and write new data if(heightOffset < 0){ heightOffset = 0; drawingDroppedFrames = static_cast(_historyLength-1); } // Copy the old data over if any available if(heightOffset > 0){ memmove( _spectrumData, &_spectrumData[(drawingDroppedFrames+1) * _fftPoints], heightOffset * _fftPoints * sizeof(double)) ; } if(drawingDroppedFrames > 0){ // Fill in zeros data for dropped data memset(&_spectrumData[heightOffset * _fftPoints], 0x00, static_cast(drawingDroppedFrames) * _fftPoints * sizeof(double)); } // add the new buffer memcpy(&_spectrumData[(_historyLength - 1) * _fftPoints], fftData, _fftPoints*sizeof(double)); } } double* WaterfallData::getSpectrumDataBuffer() const { return _spectrumData; } void WaterfallData::setSpectrumDataBuffer(const double* newData) { memcpy(_spectrumData, newData, _fftPoints * _historyLength * sizeof(double)); } int WaterfallData::getNumLinesToUpdate() const { return _numLinesToUpdate; } void WaterfallData::setNumLinesToUpdate(const int newNum) { _numLinesToUpdate = newNum; } void WaterfallData::incrementNumLinesToUpdate() { _numLinesToUpdate++; } #endif /* WATERFALL_GLOBAL_DATA_CPP */ gnuradio-3.7.2.1/gr-qtgui/lib/ConstellationDisplayPlot.cc0000664000175000017500000001616512237515112023153 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef CONSTELLATION_DISPLAY_PLOT_C #define CONSTELLATION_DISPLAY_PLOT_C #include #include #include #include #include class ConstellationDisplayZoomer: public QwtPlotZoomer { public: ConstellationDisplayZoomer(QwtPlotCanvas* canvas):QwtPlotZoomer(canvas) { setTrackerMode(QwtPicker::AlwaysOn); } virtual ~ConstellationDisplayZoomer(){ } virtual void updateTrackerText(){ updateDisplay(); } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText( const QPoint& p ) const { QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); QwtText t(QString("(%1, %2)").arg(dp.x(), 0, 'f', 4). arg(dp.y(), 0, 'f', 4)); return t; } }; ConstellationDisplayPlot::ConstellationDisplayPlot(int nplots, QWidget* parent) : DisplayPlot(nplots, parent) { resize(parent->width(), parent->height()); d_numPoints = 1024; d_pen_size = 5; d_zoomer = new ConstellationDisplayZoomer(canvas()); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor c(Qt::darkRed); d_zoomer->setRubberBandPen(c); d_zoomer->setTrackerPen(c); d_magnifier->setAxisEnabled(QwtPlot::xBottom, true); d_magnifier->setAxisEnabled(QwtPlot::yLeft, true); setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); set_xaxis(-2.0, 2.0); setAxisTitle(QwtPlot::xBottom, "In-phase"); setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); set_yaxis(-2.0, 2.0); setAxisTitle(QwtPlot::yLeft, "Quadrature"); updateAxes(); QList colors; colors << QColor(Qt::blue) << QColor(Qt::red) << QColor(Qt::green) << QColor(Qt::black) << QColor(Qt::cyan) << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray); // Setup dataPoints and plot vectors // Automatically deleted when parent is deleted for(int i = 0; i < d_nplots; i++) { d_real_data.push_back(new double[d_numPoints]); d_imag_data.push_back(new double[d_numPoints]); memset(d_real_data[i], 0x0, d_numPoints*sizeof(double)); memset(d_imag_data[i], 0x0, d_numPoints*sizeof(double)); d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); d_plot_curve[i]->attach(this); d_plot_curve[i]->setPen(QPen(colors[i])); QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(colors[i]), QPen(colors[i]), QSize(7,7)); #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_real_data[i], d_imag_data[i], d_numPoints); d_plot_curve[i]->setSymbol(*symbol); #else d_plot_curve[i]->setRawSamples(d_real_data[i], d_imag_data[i], d_numPoints); d_plot_curve[i]->setSymbol(symbol); #endif setLineStyle(i, Qt::NoPen); setLineMarker(i, QwtSymbol::Ellipse); } } ConstellationDisplayPlot::~ConstellationDisplayPlot() { for(int i = 0; i < d_nplots; i++) { delete [] d_real_data[i]; delete [] d_imag_data[i]; } // d_plot_curves deleted when parent deleted // d_zoomer and d_panner deleted when parent deleted } void ConstellationDisplayPlot::set_xaxis(double min, double max) { setXaxis(min, max); } void ConstellationDisplayPlot::set_yaxis(double min, double max) { setYaxis(min, max); } void ConstellationDisplayPlot::set_axis(double xmin, double xmax, double ymin, double ymax) { set_xaxis(xmin, xmax); set_yaxis(ymin, ymax); } void ConstellationDisplayPlot::set_pen_size(int size) { if(size > 0 && size < 30){ d_pen_size = size; for(int i = 0; i < d_nplots; i++) { d_plot_curve[i]->setPen(QPen(Qt::blue, d_pen_size, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); } } } void ConstellationDisplayPlot::replot() { QwtPlot::replot(); } void ConstellationDisplayPlot::plotNewData(const std::vector realDataPoints, const std::vector imagDataPoints, const int64_t numDataPoints, const double timeInterval) { if(!d_stop) { if((numDataPoints > 0)) { if(numDataPoints != d_numPoints) { d_numPoints = numDataPoints; for(int i = 0; i < d_nplots; i++) { delete [] d_real_data[i]; delete [] d_imag_data[i]; d_real_data[i] = new double[d_numPoints]; d_imag_data[i] = new double[d_numPoints]; #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_real_data[i], d_imag_data[i], d_numPoints); #else d_plot_curve[i]->setRawSamples(d_real_data[i], d_imag_data[i], d_numPoints); #endif } } for(int i = 0; i < d_nplots; i++) { memcpy(d_real_data[i], realDataPoints[i], numDataPoints*sizeof(double)); memcpy(d_imag_data[i], imagDataPoints[i], numDataPoints*sizeof(double)); } if(d_autoscale_state) { double bottom=1e20, top=-1e20; for(int n = 0; n < d_nplots; n++) { for(int64_t point = 0; point < numDataPoints; point++) { double b = std::min(realDataPoints[n][point], imagDataPoints[n][point]); double t = std::max(realDataPoints[n][point], imagDataPoints[n][point]); if(b < bottom) { bottom = b; } if(t > top) { top = t; } } } _autoScale(bottom, top); } replot(); } } } void ConstellationDisplayPlot::plotNewData(const double* realDataPoints, const double* imagDataPoints, const int64_t numDataPoints, const double timeInterval) { std::vector vecRealDataPoints; std::vector vecImagDataPoints; vecRealDataPoints.push_back((double*)realDataPoints); vecImagDataPoints.push_back((double*)imagDataPoints); plotNewData(vecRealDataPoints, vecImagDataPoints, numDataPoints, timeInterval); } void ConstellationDisplayPlot::_autoScale(double bottom, double top) { // Auto scale the x- and y-axis with a margin of 20% double b = bottom - fabs(bottom)*0.20; double t = top + fabs(top)*0.20; set_axis(b, t, b, t); } void ConstellationDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } #endif /* CONSTELLATION_DISPLAY_PLOT_C */ gnuradio-3.7.2.1/gr-qtgui/lib/const_sink_c_impl.h0000664000175000017500000000607712237515112021510 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_CONST_SINK_C_IMPL_H #define INCLUDED_QTGUI_CONST_SINK_C_IMPL_H #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API const_sink_c_impl : public const_sink_c { private: void initialize(); gr::thread::mutex d_mutex; int d_size; std::string d_name; int d_nconnections; int d_index; std::vector d_residbufs_real; std::vector d_residbufs_imag; int d_argc; char *d_argv; QWidget *d_parent; ConstellationDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; void npoints_resize(); public: const_sink_c_impl(int size, const std::string &name, int nconnections, QWidget *parent=NULL); ~const_sink_c_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_y_axis(double min, double max); void set_x_axis(double min, double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, int style); void set_line_marker(int which, int marker); void set_nsamps(const int size); void set_line_alpha(int which, double alpha); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); void set_size(int width, int height); int nsamps() const; void enable_menu(bool en); void enable_autoscale(bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_CONST_SINK_C_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/DisplayPlot.cc0000664000175000017500000002515012237515112020406 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include DisplayPlot::DisplayPlot(int nplots, QWidget* parent) : QwtPlot(parent), d_nplots(nplots), d_stop(false) { qRegisterMetaType("QColorList"); resize(parent->width(), parent->height()); d_autoscale_state = false; // Disable polygon clipping #if QWT_VERSION < 0x060000 QwtPainter::setDeviceClipping(false); #else QwtPainter::setPolylineSplitting(false); #endif #if QWT_VERSION < 0x060000 // We don't need the cache here canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false); canvas()->setPaintAttribute(QwtPlotCanvas::PaintPacked, false); #endif QColor default_palette_color = QColor("white"); setPaletteColor(default_palette_color); d_panner = new QwtPlotPanner(canvas()); d_panner->setAxisEnabled(QwtPlot::yRight, false); d_panner->setMouseButton(Qt::MidButton, Qt::ControlModifier); // emit the position of clicks on widget d_picker = new QwtDblClickPlotPicker(canvas()); #if QWT_VERSION < 0x060000 connect(d_picker, SIGNAL(selected(const QwtDoublePoint &)), this, SLOT(onPickerPointSelected(const QwtDoublePoint &))); #else d_picker->setStateMachine(new QwtPickerDblClickPointMachine()); connect(d_picker, SIGNAL(selected(const QPointF &)), this, SLOT(onPickerPointSelected6(const QPointF &))); #endif // Configure magnify on mouse wheel d_magnifier = new QwtPlotMagnifier(canvas()); d_magnifier->setAxisEnabled(QwtPlot::xBottom, false); // Avoid jumping when labels with more/less digits // appear/disappear when scrolling vertically const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); sd->setMinimumExtent( fm.width("100.00") ); QwtLegend* legendDisplay = new QwtLegend(this); legendDisplay->setItemMode(QwtLegend::CheckableItem); insertLegend(legendDisplay); connect(this, SIGNAL(legendChecked(QwtPlotItem *, bool)), this, SLOT(legendEntryChecked(QwtPlotItem *, bool))); } DisplayPlot::~DisplayPlot() { // d_zoomer and d_panner deleted when parent deleted } void DisplayPlot::setYaxis(double min, double max) { setAxisScale(QwtPlot::yLeft, min, max); if(!d_autoscale_state) d_zoomer->setZoomBase(); } void DisplayPlot::setXaxis(double min, double max) { setAxisScale(QwtPlot::xBottom, min, max); d_zoomer->setZoomBase(); } void DisplayPlot::setLineLabel(int which, QString label) { d_plot_curve[which]->setTitle(label); } QString DisplayPlot::getLineLabel(int which) { return d_plot_curve[which]->title().text(); } void DisplayPlot::setLineColor(int which, QColor color) { if (which < d_nplots) { // Set the color of the pen QPen pen(d_plot_curve[which]->pen()); pen.setColor(color); d_plot_curve[which]->setPen(pen); // And set the color of the markers #if QWT_VERSION < 0x060000 //d_plot_curve[which]->setBrush(QBrush(QColor(color))); d_plot_curve[which]->setPen(pen); QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); setLineMarker(which, sym.style()); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); if(sym) { sym->setColor(color); sym->setPen(pen); d_plot_curve[which]->setSymbol(sym); } #endif } } QColor DisplayPlot::getLineColor(int which) const { // If that plot doesn't exist then return black. if (which < d_nplots) return d_plot_curve[which]->pen().color(); return QColor("black"); } // Use a preprocessor macro to create a bunch of hooks for Q_PROPERTY and hence the stylesheet. #define SETUPLINE(i, im1) \ void DisplayPlot::setLineColor ## i (QColor c) {setLineColor(im1, c);} \ const QColor DisplayPlot::getLineColor ## i () const {return getLineColor(im1);} \ void DisplayPlot::setLineWidth ## i (int width) {setLineWidth(im1, width);} \ int DisplayPlot::getLineWidth ## i () const {return getLineWidth(im1);} \ void DisplayPlot::setLineStyle ## i (Qt::PenStyle ps) {setLineStyle(im1, ps);} \ const Qt::PenStyle DisplayPlot::getLineStyle ## i () const {return getLineStyle(im1);} \ void DisplayPlot::setLineMarker ## i (QwtSymbol::Style ms) {setLineMarker(im1, ms);} \ const QwtSymbol::Style DisplayPlot::getLineMarker ## i () const {return getLineMarker(im1);} \ void DisplayPlot::setMarkerAlpha ## i (int alpha) {setMarkerAlpha(im1, alpha);} \ int DisplayPlot::getMarkerAlpha ## i () const {return getMarkerAlpha(im1);} SETUPLINE(1, 0) SETUPLINE(2, 1) SETUPLINE(3, 2) SETUPLINE(4, 3) SETUPLINE(5, 4) SETUPLINE(6, 5) SETUPLINE(7, 6) SETUPLINE(8, 7) SETUPLINE(9, 8) void DisplayPlot::setZoomerColor(QColor c) { d_zoomer->setRubberBandPen(c); d_zoomer->setTrackerPen(c); } QColor DisplayPlot::getZoomerColor() const { return d_zoomer->rubberBandPen().color(); } void DisplayPlot::setPaletteColor(QColor c) { QPalette palette; palette.setColor(canvas()->backgroundRole(), c); canvas()->setPalette(palette); } QColor DisplayPlot::getPaletteColor() const { return canvas()->palette().color(canvas()->backgroundRole()); } void DisplayPlot::setAxisLabelFontSize(int axisId, int fs) { QwtText axis_title = QwtText(axisWidget(axisId)->title()); QFont font = QFont(axis_title.font()); font.setPointSize(fs); axis_title.setFont(font); axisWidget(axisId)->setTitle(axis_title); } int DisplayPlot::getAxisLabelFontSize(int axisId) const { return axisWidget(axisId)->title().font().pointSize(); } void DisplayPlot::setYaxisLabelFontSize(int fs) { setAxisLabelFontSize(QwtPlot::yLeft, fs); } int DisplayPlot::getYaxisLabelFontSize() const { int fs = getAxisLabelFontSize(QwtPlot::yLeft); return fs; } void DisplayPlot::setXaxisLabelFontSize(int fs) { setAxisLabelFontSize(QwtPlot::xBottom, fs); } int DisplayPlot::getXaxisLabelFontSize() const { int fs = getAxisLabelFontSize(QwtPlot::xBottom); return fs; } void DisplayPlot::setAxesLabelFontSize(int fs) { setAxisLabelFontSize(QwtPlot::yLeft, fs); setAxisLabelFontSize(QwtPlot::xBottom, fs); } int DisplayPlot::getAxesLabelFontSize() const { // Returns 0 if all axes do not have the same font size. int fs = getAxisLabelFontSize(QwtPlot::yLeft); if (getAxisLabelFontSize(QwtPlot::xBottom) != fs) return 0; return fs; } void DisplayPlot::setLineWidth(int which, int width) { if(which < d_nplots) { // Set the new line width QPen pen(d_plot_curve[which]->pen()); pen.setWidth(width); d_plot_curve[which]->setPen(pen); // Scale the marker size proportionally #if QWT_VERSION < 0x060000 QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); sym.setSize(7+10*log10(1.0*width), 7+10*log10(1.0*width)); d_plot_curve[which]->setSymbol(sym); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); if(sym) { sym->setSize(7+10*log10(1.0*width), 7+10*log10(1.0*width)); d_plot_curve[which]->setSymbol(sym); } #endif } } int DisplayPlot::getLineWidth(int which) const { if (which < d_nplots) { return d_plot_curve[which]->pen().width(); } else { return 0; } } void DisplayPlot::setLineStyle(int which, Qt::PenStyle style) { if(which < d_nplots) { QPen pen(d_plot_curve[which]->pen()); pen.setStyle(style); d_plot_curve[which]->setPen(pen); } } const Qt::PenStyle DisplayPlot::getLineStyle(int which) const { if(which < d_nplots) { return d_plot_curve[which]->pen().style(); } else { return Qt::SolidLine; } } void DisplayPlot::setLineMarker(int which, QwtSymbol::Style marker) { if(which < d_nplots) { #if QWT_VERSION < 0x060000 QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); QPen pen(d_plot_curve[which]->pen()); QBrush brush(pen.color()); sym.setStyle(marker); sym.setPen(pen); sym.setBrush(brush); d_plot_curve[which]->setSymbol(sym); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); if(sym) { sym->setStyle(marker); d_plot_curve[which]->setSymbol(sym); } #endif } } const QwtSymbol::Style DisplayPlot::getLineMarker(int which) const { if(which < d_nplots) { #if QWT_VERSION < 0x060000 QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); return sym.style(); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); return sym->style(); #endif } else { return QwtSymbol::NoSymbol; } } void DisplayPlot::setMarkerAlpha(int which, int alpha) { if (which < d_nplots) { // Get the pen color QPen pen(d_plot_curve[which]->pen()); QColor color = pen.color(); // Set new alpha and update pen color.setAlpha(alpha); pen.setColor(color); d_plot_curve[which]->setPen(pen); // And set the new color for the markers #if QWT_VERSION < 0x060000 QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); setLineMarker(which, sym.style()); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); if(sym) { sym->setColor(color); sym->setPen(pen); d_plot_curve[which]->setSymbol(sym); } #endif } } int DisplayPlot::getMarkerAlpha(int which) const { if(which < d_nplots) { return d_plot_curve[which]->pen().color().alpha(); } else { return 0; } } void DisplayPlot::setStop(bool on) { d_stop = on; } void DisplayPlot::resizeSlot( QSize *s ) { // -10 is to spare some room for the legend and x-axis label resize(s->width()-10, s->height()-10); } void DisplayPlot::legendEntryChecked(QwtPlotItem* plotItem, bool on) { plotItem->setVisible(!on); replot(); } void DisplayPlot::onPickerPointSelected(const QwtDoublePoint & p) { QPointF point = p; //fprintf(stderr,"onPickerPointSelected %f %f\n", point.x(), point.y()); emit plotPointSelected(point); } void DisplayPlot::onPickerPointSelected6(const QPointF & p) { QPointF point = p; //fprintf(stderr,"onPickerPointSelected %f %f\n", point.x(), point.y()); emit plotPointSelected(point); } gnuradio-3.7.2.1/gr-qtgui/lib/TimeDomainDisplayPlot.cc0000664000175000017500000003410012242716557022364 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIME_DOMAIN_DISPLAY_PLOT_C #define TIME_DOMAIN_DISPLAY_PLOT_C #include #include #include #include #include #include #include class TimePrecisionClass { public: TimePrecisionClass(const int timePrecision) { d_timePrecision = timePrecision; } virtual ~TimePrecisionClass() { } virtual unsigned int getTimePrecision() const { return d_timePrecision; } virtual void setTimePrecision(const unsigned int newPrecision) { d_timePrecision = newPrecision; } protected: unsigned int d_timePrecision; }; class TimeDomainDisplayZoomer: public QwtPlotZoomer, public TimePrecisionClass { public: TimeDomainDisplayZoomer(QwtPlotCanvas* canvas, const unsigned int timePrecision) : QwtPlotZoomer(canvas),TimePrecisionClass(timePrecision) { setTrackerMode(QwtPicker::AlwaysOn); } virtual ~TimeDomainDisplayZoomer() { } virtual void updateTrackerText() { updateDisplay(); } void setUnitType(const std::string &type) { d_unitType = type; } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText( const QPoint& p ) const { QwtText t; QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); if((dp.y() > 0.0001) && (dp.y() < 10000)) { t.setText(QString("%1 %2, %3 V"). arg(dp.x(), 0, 'f', getTimePrecision()). arg(d_unitType.c_str()). arg(dp.y(), 0, 'f', 4)); } else { t.setText(QString("%1 %2, %3 V"). arg(dp.x(), 0, 'f', getTimePrecision()). arg(d_unitType.c_str()). arg(dp.y(), 0, 'e', 4)); } return t; } private: std::string d_unitType; }; /*********************************************************************** * Main Time domain plotter widget **********************************************************************/ TimeDomainDisplayPlot::TimeDomainDisplayPlot(int nplots, QWidget* parent) : DisplayPlot(nplots, parent) { d_numPoints = 1024; d_xdata = new double[d_numPoints]; memset(d_xdata, 0x0, d_numPoints*sizeof(double)); d_zoomer = new TimeDomainDisplayZoomer(canvas(), 0); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor c(Qt::darkRed); d_zoomer->setRubberBandPen(c); d_zoomer->setTrackerPen(c); d_semilogx = false; d_semilogy = false; setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); setXaxis(0, d_numPoints); setAxisTitle(QwtPlot::xBottom, "Time (sec)"); setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setYaxis(-2.0, 2.0); setAxisTitle(QwtPlot::yLeft, "Amplitude"); QList colors; colors << QColor(Qt::blue) << QColor(Qt::red) << QColor(Qt::green) << QColor(Qt::black) << QColor(Qt::cyan) << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray); // Setup dataPoints and plot vectors // Automatically deleted when parent is deleted for(int i = 0; i < d_nplots; i++) { d_ydata.push_back(new double[d_numPoints]); memset(d_ydata[i], 0x0, d_numPoints*sizeof(double)); d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); d_plot_curve[i]->attach(this); d_plot_curve[i]->setPen(QPen(colors[i])); d_plot_curve[i]->setRenderHint(QwtPlotItem::RenderAntialiased); QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(colors[i]), QPen(colors[i]), QSize(7,7)); #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_numPoints); d_plot_curve[i]->setSymbol(*symbol); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_numPoints); d_plot_curve[i]->setSymbol(symbol); #endif } d_sample_rate = 1; _resetXAxisPoints(); d_tag_markers.resize(d_nplots); d_tag_markers_en = std::vector(d_nplots, true); } TimeDomainDisplayPlot::~TimeDomainDisplayPlot() { for(int i = 0; i < d_nplots; i++) delete [] d_ydata[i]; delete[] d_xdata; // d_zoomer and _panner deleted when parent deleted } void TimeDomainDisplayPlot::replot() { QwtPlot::replot(); } void TimeDomainDisplayPlot::plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double timeInterval, const std::vector< std::vector > &tags) { if(!d_stop) { if((numDataPoints > 0)) { if(numDataPoints != d_numPoints){ d_numPoints = numDataPoints; delete[] d_xdata; d_xdata = new double[d_numPoints]; for(int i = 0; i < d_nplots; i++) { delete[] d_ydata[i]; d_ydata[i] = new double[d_numPoints]; #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_numPoints); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_numPoints); #endif } _resetXAxisPoints(); } for(int i = 0; i < d_nplots; i++) { if(d_semilogy) { for(int n = 0; n < numDataPoints; n++) d_ydata[i][n] = fabs(dataPoints[i][n]); } else { memcpy(d_ydata[i], dataPoints[i], numDataPoints*sizeof(double)); } } // Detach and delete any tags that were plotted last time for(int n = 0; n < d_nplots; n++) { for(size_t i = 0; i < d_tag_markers[n].size(); i++) { d_tag_markers[n][i]->detach(); delete d_tag_markers[n][i]; } d_tag_markers[n].clear(); } // Plot and attach any new tags found. // First test if this was a complex input where real/imag get // split here into two stream. if(tags.size() > 0) { bool cmplx = false; int mult = (int)d_nplots / (int)tags.size(); if(mult == 2) cmplx = true; std::vector< std::vector >::const_iterator tag = tags.begin(); for(int i = 0; i < d_nplots; i+=mult) { std::vector::const_iterator t; for(t = tag->begin(); t != tag->end(); t++) { uint64_t offset = (*t).offset; // Ignore tag if its offset is outside our plottable vector. if(offset >= (uint64_t)d_numPoints) { continue; } double sample_offset = double(offset)/d_sample_rate; std::stringstream s; s << (*t).key << ": " << (*t).value; // Select the right input stream to put the tag on. If real, // just use i; if it's a complex stream, find the max of the // real and imaginary parts and put the tag on that one. int which = i; if(cmplx) { bool show0 = d_plot_curve[i]->isVisible(); bool show1 = d_plot_curve[i+1]->isVisible(); // If we are showing both streams, select the inptu stream // with the larger value if(show0 && show1) { if(fabs(d_ydata[i][offset]) < fabs(d_ydata[i+1][offset])) which = i+1; } else { // If show0, we keep which = i; otherwise, use i+1. if(show1) which = i+1; } } double yval = d_ydata[which][offset]; // Find if we already have a marker at this location std::vector::iterator mitr; for(mitr = d_tag_markers[which].begin(); mitr != d_tag_markers[which].end(); mitr++) { if((*mitr)->xValue() == sample_offset) { break; } } // If no matching marker, create a new one if(mitr == d_tag_markers[which].end()) { bool show = d_plot_curve[which]->isVisible(); QwtPlotMarker *m = new QwtPlotMarker(); m->setXValue(sample_offset); m->setYValue(yval); QBrush brush; brush.setColor(QColor(0xC8, 0x2F, 0x1F)); brush.setStyle(Qt::SolidPattern); QPen pen; pen.setColor(Qt::black); pen.setWidth(1); QwtSymbol *sym = new QwtSymbol(QwtSymbol::NoSymbol, brush, pen, QSize(12,12)); if(yval >= 0) { sym->setStyle(QwtSymbol::DTriangle); m->setLabelAlignment(Qt::AlignTop); } else { sym->setStyle(QwtSymbol::UTriangle); m->setLabelAlignment(Qt::AlignBottom); } #if QWT_VERSION < 0x060000 m->setSymbol(*sym); #else m->setSymbol(sym); #endif m->setLabel(QwtText(s.str().c_str())); m->attach(this); if(!(show && d_tag_markers_en[which])) { m->hide(); } d_tag_markers[which].push_back(m); } else { // Prepend the new tag to the existing marker // And set it at the max value if(fabs(yval) < fabs((*mitr)->yValue())) (*mitr)->setYValue(yval); QString orig = (*mitr)->label().text(); s << std::endl; orig.prepend(s.str().c_str()); (*mitr)->setLabel(orig); } } tag++; } } if(d_autoscale_state) { double bottom=1e20, top=-1e20; for(int n = 0; n < d_nplots; n++) { for(int64_t point = 0; point < numDataPoints; point++) { if(d_ydata[n][point] < bottom) { bottom = d_ydata[n][point]; } if(d_ydata[n][point] > top) { top = d_ydata[n][point]; } } } _autoScale(bottom, top); } replot(); } } } void TimeDomainDisplayPlot::legendEntryChecked(QwtPlotItem* plotItem, bool on) { // When line is turned on/off, immediately show/hide tag markers for(int n = 0; n < d_nplots; n++) { if(plotItem == d_plot_curve[n]) { for(size_t i = 0; i < d_tag_markers[n].size(); i++) { if(!(!on && d_tag_markers_en[n])) d_tag_markers[n][i]->hide(); else d_tag_markers[n][i]->show(); } } } DisplayPlot::legendEntryChecked(plotItem, on); } void TimeDomainDisplayPlot::_resetXAxisPoints() { double delt = 1.0/d_sample_rate; for(long loc = 0; loc < d_numPoints; loc++){ d_xdata[loc] = loc*delt; } // Set up zoomer base for maximum unzoom x-axis // and reset to maximum unzoom level QwtDoubleRect zbase = d_zoomer->zoomBase(); if(d_semilogx) { setAxisScale(QwtPlot::xBottom, 1e-1, d_numPoints*delt); zbase.setLeft(1e-1); } else { setAxisScale(QwtPlot::xBottom, 0, d_numPoints*delt); zbase.setLeft(0); } zbase.setRight(d_numPoints*delt); d_zoomer->zoom(zbase); d_zoomer->setZoomBase(zbase); d_zoomer->zoom(0); } void TimeDomainDisplayPlot::_autoScale(double bottom, double top) { // Auto scale the y-axis with a margin of 20% (10 dB for log scale) double _bot = bottom - fabs(bottom)*0.20; double _top = top + fabs(top)*0.20; if(d_semilogy) { if(bottom > 0) { setYaxis(_bot-10, _top+10); } else { setYaxis(1e-3, _top+10); } } else { setYaxis(_bot, _top); } } void TimeDomainDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } void TimeDomainDisplayPlot::setSampleRate(double sr, double units, const std::string &strunits) { double newsr = sr/units; if(newsr != d_sample_rate) { d_sample_rate = sr/units; _resetXAxisPoints(); // While we could change the displayed sigfigs based on the unit being // displayed, I think it looks better by just setting it to 4 regardless. //double display_units = ceil(log10(units)/2.0); double display_units = 4; setAxisTitle(QwtPlot::xBottom, QString("Time (%1)").arg(strunits.c_str())); ((TimeDomainDisplayZoomer*)d_zoomer)->setTimePrecision(display_units); ((TimeDomainDisplayZoomer*)d_zoomer)->setUnitType(strunits); } } void TimeDomainDisplayPlot::stemPlot(bool en) { if(en) { for(int i = 0; i < d_nplots; i++) { d_plot_curve[i]->setStyle(QwtPlotCurve::Sticks); setLineMarker(i, QwtSymbol::Ellipse); } } else { for(int i = 0; i < d_nplots; i++) { d_plot_curve[i]->setStyle(QwtPlotCurve::Lines); setLineMarker(i, QwtSymbol::NoSymbol); } } } void TimeDomainDisplayPlot::setSemilogx(bool en) { d_semilogx = en; if(!d_semilogx) { setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); } else { setAxisScaleEngine(QwtPlot::xBottom, new QwtLog10ScaleEngine); } _resetXAxisPoints(); } void TimeDomainDisplayPlot::setSemilogy(bool en) { if(d_semilogy != en) { d_semilogy = en; double max = axisScaleDiv(QwtPlot::yLeft)->upperBound(); if(!d_semilogy) { setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setYaxis(-pow(10.0, max/10.0), pow(10.0, max/10.0)); } else { setAxisScaleEngine(QwtPlot::yLeft, new QwtLog10ScaleEngine); setYaxis(1e-10, 10.0*log10(max)); } } } void TimeDomainDisplayPlot::enableTagMarker(int which, bool en) { if((size_t)which < d_tag_markers_en.size()) d_tag_markers_en[which] = en; else throw std::runtime_error("TimeDomainDisplayPlot: enabled tag marker does not exist.\n"); } #endif /* TIME_DOMAIN_DISPLAY_PLOT_C */ gnuradio-3.7.2.1/gr-qtgui/lib/waterfall_sink_c_impl.h0000664000175000017500000000725312237515112022340 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_WATERFALL_SINK_C_IMPL_H #define INCLUDED_QTGUI_WATERFALL_SINK_C_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API waterfall_sink_c_impl : public waterfall_sink_c { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); int d_fftsize; float d_fftavg; filter::firdes::win_type d_wintype; std::vector d_window; double d_center_freq; double d_bandwidth; std::string d_name; int d_nconnections; bool d_shift; fft::fft_complex *d_fft; int d_index; std::vector d_residbufs; std::vector d_magbufs; float *d_fbuf; int d_argc; char *d_argv; QWidget *d_parent; WaterfallDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; void windowreset(); void buildwindow(); void fftresize(); void fft(float *data_out, const gr_complex *data_in, int size); public: waterfall_sink_c_impl(int size, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent=NULL); ~waterfall_sink_c_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void clear_data(); void set_fft_size(const int fftsize); int fft_size() const; void set_fft_average(const float fftavg); float fft_average() const; void set_fft_window(const gr::filter::firdes::win_type win); gr::filter::firdes::win_type fft_window(); void set_frequency_range(const double centerfreq, const double bandwidth); void set_intensity_range(const double min, const double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_alpha(int which, double alpha); void set_color_map(int which, const int color); std::string title(); std::string line_label(int which); double line_alpha(int which); int color_map(int which); void set_size(int width, int height); void auto_scale(); double min_intensity(int which); double max_intensity(int which); void enable_menu(bool en); void enable_grid(bool en); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_WATERFALL_SINK_C_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/freq_sink_f_impl.cc0000664000175000017500000002731412237515112021455 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "freq_sink_f_impl.h" #include #include #include #include namespace gr { namespace qtgui { freq_sink_f::sptr freq_sink_f::make(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new freq_sink_f_impl(fftsize, wintype, fc, bw, name, nconnections, parent)); } freq_sink_f_impl::freq_sink_f_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) : sync_block("freq_sink_f", io_signature::make(1, -1, sizeof(float)), io_signature::make(0, 0, 0)), d_fftsize(fftsize), d_fftavg(1.0), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex(d_fftsize, true); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_float(d_fftsize)); d_magbufs.push_back(fft::malloc_double(d_fftsize)); memset(d_residbufs[i], 0, d_fftsize*sizeof(float)); memset(d_magbufs[i], 0, d_fftsize*sizeof(double)); } buildwindow(); initialize(); } freq_sink_f_impl::~freq_sink_f_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); } delete d_fft; fft::free(d_fbuf); delete d_argv; } bool freq_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void freq_sink_f_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void freq_sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new FreqDisplayForm(d_nconnections, d_parent); set_fft_window(d_wintype); set_fft_size(d_fftsize); set_frequency_range(d_center_freq, d_bandwidth/2.0); // initialize update time to 10 times a second set_update_time(0.1); } void freq_sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* freq_sink_f_impl::qwidget() { return d_main_gui; } PyObject* freq_sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void freq_sink_f_impl::set_fft_size(const int fftsize) { d_main_gui->setFFTSize(fftsize); } int freq_sink_f_impl::fft_size() const { return d_fftsize; } void freq_sink_f_impl::set_fft_average(const float fftavg) { d_main_gui->setFFTAverage(fftavg); } float freq_sink_f_impl::fft_average() const { return d_fftavg; } void freq_sink_f_impl::set_fft_window(const filter::firdes::win_type win) { d_main_gui->setFFTWindowType(win); } filter::firdes::win_type freq_sink_f_impl::fft_window() { return d_wintype; } void freq_sink_f_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->setFrequencyRange(d_center_freq, d_bandwidth); } void freq_sink_f_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void freq_sink_f_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void freq_sink_f_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void freq_sink_f_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void freq_sink_f_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void freq_sink_f_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void freq_sink_f_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void freq_sink_f_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void freq_sink_f_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void freq_sink_f_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string freq_sink_f_impl::title() { return d_main_gui->title().toStdString(); } std::string freq_sink_f_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string freq_sink_f_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int freq_sink_f_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int freq_sink_f_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int freq_sink_f_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double freq_sink_f_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void freq_sink_f_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void freq_sink_f_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void freq_sink_f_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void freq_sink_f_impl::reset() { d_index = 0; } void freq_sink_f_impl::fft(float *data_out, const float *data_in, int size) { // float to complex conversion gr_complex *dst = d_fft->get_inbuf(); for (int i = 0; i < size; i++) dst[i] = data_in[i]; if(d_window.size()) { volk_32fc_32f_multiply_32fc_a(d_fft->get_inbuf(), dst, &d_window.front(), size); } d_fft->execute(); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); // Perform shift operation unsigned int len = (unsigned int)(floor(size/2.0)); float *tmp = (float*)malloc(sizeof(float)*len); memcpy(tmp, &data_out[0], sizeof(float)*len); memcpy(&data_out[0], &data_out[len], sizeof(float)*(size - len)); memcpy(&data_out[size - len], tmp, sizeof(float)*len); free(tmp); } void freq_sink_f_impl::windowreset() { gr::thread::scoped_lock lock(d_mutex); filter::firdes::win_type newwintype; newwintype = d_main_gui->getFFTWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void freq_sink_f_impl::buildwindow() { d_window.clear(); if(d_wintype != filter::firdes::WIN_NONE) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void freq_sink_f_impl::fftresize() { gr::thread::scoped_lock lock(d_mutex); int newfftsize = d_main_gui->getFFTSize(); d_fftavg = d_main_gui->getFFTAverage(); if(newfftsize != d_fftsize) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); d_residbufs[i] = fft::malloc_float(newfftsize); d_magbufs[i] = fft::malloc_double(newfftsize); memset(d_residbufs[i], 0, newfftsize*sizeof(float)); memset(d_magbufs[i], 0, newfftsize*sizeof(double)); } // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex(d_fftsize, true); fft::free(d_fbuf); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); } } int freq_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const float *in = (const float*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; // If we have enough input for one full FFT, do it if(datasize >= resid) { if(gr::high_res_timer_now() - d_last_time > d_update_time) { for(int n = 0; n < d_nconnections; n++) { // Fill up residbuf with d_fftsize number of items in = (const float*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(float)*resid); fft(d_fbuf, d_residbufs[n], d_fftsize); for(int x = 0; x < d_fftsize; x++) { d_magbufs[n][x] = (double)((1.0-d_fftavg)*d_magbufs[n][x] + (d_fftavg)*d_fbuf[x]); } //volk_32f_convert_64f_a(d_magbufs[n], d_fbuf, d_fftsize); } d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new FreqUpdateEvent(d_magbufs, d_fftsize)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbuf for next time else { for(int n = 0; n < d_nconnections; n++) { in = (const float*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(float)*datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/timeRasterGlobalData.cc0000664000175000017500000001412712207440367022204 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef TIMERASTER_GLOBAL_DATA_CPP #define TIMERASTER_GLOBAL_DATA_CPP #include #include #include #include TimeRasterData::TimeRasterData(const double rows, const double cols) #if QWT_VERSION < 0x060000 : QwtRasterData(QwtDoubleRect(0, 0, rows, cols)) #else : QwtRasterData() #endif { d_nitems = 0; d_rows = rows; d_cols = cols; d_resid = 0; // We add 1 here so we always have the next row already started // (helps when d_cols is fractional and we have to slide). d_totalitems = static_cast((d_rows+1)*floor(d_cols)); d_data_size = d_totalitems + static_cast(floor(d_cols)); d_intensityRange = QwtDoubleInterval(0.0, 10.0); d_data = new double[d_data_size]; #if QWT_VERSION >= 0x060000 setInterval(Qt::XAxis, QwtInterval(0, cols)); setInterval(Qt::YAxis, QwtInterval(0, rows)); setInterval(Qt::ZAxis, QwtInterval(0.0, 10.0)); #endif reset(); } TimeRasterData::~TimeRasterData() { delete [] d_data; } void TimeRasterData::reset() { d_resid = 0; d_nitems = 0; memset(d_data, 0x0, d_data_size*sizeof(double)); } void TimeRasterData::copy(const TimeRasterData* rhs) { #if QWT_VERSION < 0x060000 if((d_cols != rhs->getNumCols()) || (boundingRect() != rhs->boundingRect()) ){ d_cols = rhs->getNumCols(); d_rows = rhs->getNumRows(); d_totalitems = static_cast((d_rows+1)*floor(d_cols)); d_data_size = d_totalitems + static_cast(floor(d_cols)); setBoundingRect(rhs->boundingRect()); delete [] d_data; d_data = new double[d_data_size]; } #else if((d_cols != rhs->getNumCols()) || (d_rows != rhs->getNumRows())) { d_cols = rhs->getNumCols(); d_rows = rhs->getNumRows(); d_totalitems = static_cast((d_rows+1)*floor(d_cols)); d_data_size = d_totalitems + static_cast(floor(d_cols)); delete [] d_data; d_data = new double[d_data_size]; } #endif reset(); #if QWT_VERSION < 0x060000 setRange(rhs->range()); #else setInterval(Qt::XAxis, rhs->interval(Qt::XAxis)); setInterval(Qt::YAxis, rhs->interval(Qt::YAxis)); setInterval(Qt::ZAxis, rhs->interval(Qt::ZAxis)); #endif } void TimeRasterData::resizeData(const double rows, const double cols) { #if QWT_VERSION < 0x060000 if((cols != getNumCols()) || (boundingRect().width() != cols) || (rows != getNumRows()) || (boundingRect().height() != cols)) { setBoundingRect(QwtDoubleRect(0, 0, cols, rows)); d_cols = cols; d_rows = rows; d_totalitems = static_cast((d_rows+1)*floor(d_cols)); d_data_size = d_totalitems + static_cast(floor(d_cols)); delete [] d_data; d_data = new double[d_data_size]; } #else if((cols != getNumCols()) || (interval(Qt::XAxis).width() != cols) || (rows != getNumRows()) || (interval(Qt::YAxis).width() != rows)) { setInterval(Qt::XAxis, QwtInterval(0, cols)); setInterval(Qt::YAxis, QwtInterval(0, rows)); d_cols = cols; d_rows = rows; d_totalitems = static_cast((d_rows+1)*floor(d_cols)); d_data_size = d_totalitems + static_cast(floor(d_cols)); delete [] d_data; d_data = new double[d_data_size]; } #endif reset(); } QwtRasterData *TimeRasterData::copy() const { #if QWT_VERSION < 0x060000 TimeRasterData* returnData = \ new TimeRasterData(d_cols, d_rows); #else TimeRasterData* returnData = \ new TimeRasterData(d_cols, d_rows); #endif returnData->copy(this); return returnData; } #if QWT_VERSION < 0x060000 QwtDoubleInterval TimeRasterData::range() const { return d_intensityRange; } void TimeRasterData::setRange(const QwtDoubleInterval& newRange) { d_intensityRange = newRange; } #endif double TimeRasterData::value(double x, double y) const { double returnValue = 0.0; #if QWT_VERSION < 0x060000 double top = boundingRect().top(); double bottom = top - boundingRect().height(); double left = boundingRect().left(); double right = left - boundingRect().width(); #else double top = interval(Qt::YAxis).maxValue(); double bottom = interval(Qt::YAxis).minValue(); double left = interval(Qt::XAxis).minValue(); double right = interval(Qt::XAxis).maxValue(); #endif if((x < left) || (x > right) || (y < bottom) || (y > top)) return 0.0; double _y = floor(top - y); double _loc = _y*(d_cols) + x + d_resid; int location = static_cast(_loc); if((location > -1) && (location < d_data_size)) { returnValue = d_data[location]; } return returnValue; } void TimeRasterData::incrementResidual() { // After a full set of rows are drawn, we want to add up the // residual due to any fractional value of d_cols to appropriately // shift the next data in. double icols = floor(d_cols); d_resid = fmod(d_resid + (d_cols - icols) * d_rows, icols); } double TimeRasterData::getNumCols() const { return d_cols; } double TimeRasterData::getNumRows() const { return d_rows; } void TimeRasterData::addData(const double* data, const int dataSize) { int cols = static_cast(d_cols); if(dataSize == cols) { if(d_nitems < d_totalitems) { memcpy(&d_data[d_nitems], data, cols*sizeof(double)); d_nitems += cols; } else { memcpy(&d_data[d_nitems], data, cols*sizeof(double)); memmove(d_data, &d_data[cols], d_totalitems*sizeof(double)); } } } #endif /* TIMERASTER_GLOBAL_DATA_CPP */ gnuradio-3.7.2.1/gr-qtgui/lib/time_raster_sink_c_impl.cc0000664000175000017500000001303412207440367023033 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "time_raster_sink_c_impl.h" #include #include #include namespace gr { namespace qtgui { time_raster_sink_c::sptr time_raster_sink_c::make(unsignedint rows, unsigned int cols, const std::string &name, QWidget *parent) { return gnuradio::get_initial_sptr (new time_raster_sink_c_impl(rows, cols, name, parent)); } time_raster_sink_c_impl::time_raster_sink_c_impl(unsignedint rows, unsigned int cols, const std::string &name, QWidget *parent) : sync_block("time_raster_sink_c", io_signature::make(1, -1, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_name(name), d_nconnections(1), d_parent(parent), d_rows(rows), d_cols(cols) { d_main_gui = NULL; d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_complex(rows)); memset(d_residbufs[i], 0, rows*sizeof(float)); } initialize(); } time_raster_sink_c_impl::~time_raster_sink_c_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); } } void time_raster_sink_c_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_rows, 8191); } } void time_raster_sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { int argc = 0; char **argv = NULL; d_qApplication = new QApplication(argc, argv); } d_main_gui = new TimeRasterDisplayForm(d_nconnections, d_rows, d_cols, d_parent); // initialize update time to 10 times a second set_update_time(0.1); d_last_time = 0; } void time_raster_sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* time_raster_sink_c_impl::qwidget() { return d_main_gui; } PyObject* time_raster_sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void time_raster_sink_c_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); } void time_raster_sink_c_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void time_raster_sink_c_impl::set_line_label(const std::string &label) { d_main_gui->setLineLabel(0, label.c_str()); } void time_raster_sink_c_impl::set_line_color(const std::string &color) { d_main_gui->setLineColor(0, color.c_str()); } void time_raster_sink_c_impl::set_line_width(int width) { d_main_gui->setLineWidth(0, width); } void time_raster_sink_c_impl::set_line_style(Qt::PenStyle style) { d_main_gui->setLineStyle(0, style); } void time_raster_sink_c_impl::set_line_marker(QwtSymbol::Style marker) { d_main_gui->setLineMarker(0, marker); } void time_raster_sink_c_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } int time_raster_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const gr_complex *in = (const gr_complex*)input_items[0]; for(int i=0; i < noutput_items; i+=d_cols) { unsigned int datasize = noutput_items - i; unsigned int resid = d_cols-d_index; // If we have enough input for one full column if(datasize >= resid) { for(int n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*resid); } if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new TimeRasterUpdateEvent(d_residbufs, d_fftsize, d_last_time)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbuf for next time else { for(int n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/spectrumdisplayform.cc0000664000175000017500000005446612207440367022300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include SpectrumDisplayForm::SpectrumDisplayForm(QWidget* parent) : QWidget(parent) { setupUi(this); _systemSpecifiedFlag = false; _intValidator = new QIntValidator(this); _intValidator->setBottom(0); _frequencyDisplayPlot = new FrequencyDisplayPlot(1, FrequencyPlotDisplayFrame); _waterfallDisplayPlot = new WaterfallDisplayPlot(1, WaterfallPlotDisplayFrame); _timeDomainDisplayPlot = new TimeDomainDisplayPlot(2, TimeDomainDisplayFrame); _constellationDisplayPlot = new ConstellationDisplayPlot(1, ConstellationDisplayFrame); _numRealDataPoints = 1024; _realFFTDataPoints = new double[_numRealDataPoints]; _averagedValues = new double[_numRealDataPoints]; _historyVector = new std::vector; _timeDomainDisplayPlot->setLineLabel(0, "real"); _timeDomainDisplayPlot->setLineLabel(1, "imag"); AvgLineEdit->setRange(0, 500); // Set range of Average box value from 0 to 500 minHoldCheckBox_toggled( false ); maxHoldCheckBox_toggled( false ); WaterfallMaximumIntensitySlider->setRange(-200, 0); WaterfallMinimumIntensitySlider->setRange(-200, 0); WaterfallMinimumIntensitySlider->setValue(-200); _peakFrequency = 0; _peakAmplitude = -HUGE_VAL; _noiseFloorAmplitude = -HUGE_VAL; connect(_waterfallDisplayPlot, SIGNAL(updatedLowerIntensityLevel(const double)), _frequencyDisplayPlot, SLOT(setLowerIntensityLevel(const double))); connect(_waterfallDisplayPlot, SIGNAL(updatedUpperIntensityLevel(const double)), _frequencyDisplayPlot, SLOT(setUpperIntensityLevel(const double))); _frequencyDisplayPlot->setLowerIntensityLevel(-200); _frequencyDisplayPlot->setUpperIntensityLevel(-200); // Load up the acceptable FFT sizes... FFTSizeComboBox->clear(); for(long fftSize = SpectrumGUIClass::MIN_FFT_SIZE; fftSize <= SpectrumGUIClass::MAX_FFT_SIZE; fftSize *= 2){ FFTSizeComboBox->insertItem(FFTSizeComboBox->count(), QString("%1").arg(fftSize)); } reset(); toggleTabFrequency(false); toggleTabWaterfall(false); toggleTabTime(false); toggleTabConstellation(false); _historyEntry = 0; _historyEntryCount = 0; // Create a timer to update plots at the specified rate displayTimer = new QTimer(this); connect(displayTimer, SIGNAL(timeout()), this, SLOT(updateGuiTimer())); // Connect double click signals up connect(_frequencyDisplayPlot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onFFTPlotPointSelected(const QPointF))); connect(_waterfallDisplayPlot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onWFallPlotPointSelected(const QPointF))); connect(_timeDomainDisplayPlot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onTimePlotPointSelected(const QPointF))); connect(_constellationDisplayPlot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onConstPlotPointSelected(const QPointF))); } SpectrumDisplayForm::~SpectrumDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete _intValidator; delete[] _realFFTDataPoints; delete[] _averagedValues; for(unsigned int count = 0; count < _historyVector->size(); count++){ delete[] _historyVector->operator[](count); } delete _historyVector; displayTimer->stop(); delete displayTimer; } void SpectrumDisplayForm::setSystem(SpectrumGUIClass * newSystem, const uint64_t numFFTDataPoints, const uint64_t numTimeDomainDataPoints) { resizeBuffers(numFFTDataPoints, numTimeDomainDataPoints); if(newSystem != NULL) { _system = newSystem; _systemSpecifiedFlag = true; } else { _systemSpecifiedFlag = false; } } /*********************************************************************** * This is kind of gross because we're combining three operations: * Conversion from float to double (which is what the plotter wants) * Finding the peak and mean * Doing the "FFT shift" to put 0Hz at the center of the plot * I feel like this might want to be part of the sink block **********************************************************************/ static void fftshift_and_sum(double *outFFT, const float *inFFT, uint64_t num_points, double &sum_mean, double &peak_ampl, int &peak_bin) { const float* inptr = inFFT+num_points/2; double* outptr = outFFT; sum_mean = 0; peak_ampl = -HUGE_VAL; peak_bin = 0; // Run this twice to perform the fftshift operation on the data here as well for(uint64_t point = 0; point < num_points/2; point++) { float pt = (*inptr); *outptr = pt; if(*outptr > peak_ampl) { peak_bin = point; peak_ampl = *outptr; } sum_mean += *outptr; inptr++; outptr++; } // This loop takes the first half of the input data and puts it in the // second half of the plotted data inptr = inFFT; for(uint64_t point = 0; point < num_points/2; point++) { float pt = (*inptr); *outptr = pt; if(*outptr > peak_ampl) { peak_bin = point; peak_ampl = *outptr; } sum_mean += *outptr; inptr++; outptr++; } } void SpectrumDisplayForm::newFrequencyData( const SpectrumUpdateEvent* spectrumUpdateEvent) { //_lastSpectrumEvent = (SpectrumUpdateEvent)(*spectrumUpdateEvent); const float* fftMagDataPoints = spectrumUpdateEvent->getFFTPoints(); const uint64_t numFFTDataPoints = spectrumUpdateEvent->getNumFFTDataPoints(); const uint64_t numTimeDomainDataPoints = spectrumUpdateEvent->getNumTimeDomainDataPoints(); const gr::high_res_timer_type dataTimestamp = spectrumUpdateEvent->getDataTimestamp(); const bool repeatDataFlag = spectrumUpdateEvent->getRepeatDataFlag(); const bool lastOfMultipleUpdatesFlag = spectrumUpdateEvent->getLastOfMultipleUpdateFlag(); const gr::high_res_timer_type generatedTimestamp = spectrumUpdateEvent->getEventGeneratedTimestamp(); double* realTimeDomainDataPoints = (double*)spectrumUpdateEvent->getRealTimeDomainPoints(); double* imagTimeDomainDataPoints = (double*)spectrumUpdateEvent->getImagTimeDomainPoints(); std::vector timeDomainDataPoints; timeDomainDataPoints.push_back(realTimeDomainDataPoints); timeDomainDataPoints.push_back(imagTimeDomainDataPoints); // REMEMBER: The dataTimestamp is NOT valid when the repeat data flag is true... resizeBuffers(numFFTDataPoints, numTimeDomainDataPoints); const double fftBinSize = (_stopFrequency-_startFrequency) / static_cast(numFFTDataPoints); //this does the fftshift, conversion to double, and calculation of sum, peak amplitude, peak freq. double sum_mean, peak_ampl; int peak_bin; fftshift_and_sum(_realFFTDataPoints, fftMagDataPoints, numFFTDataPoints, sum_mean, peak_ampl, peak_bin); double peak_freq = peak_bin * fftBinSize; // Don't update the averaging history if this is repeated data if(!repeatDataFlag){ _averageHistory(_realFFTDataPoints); // Only use the local info if we are not repeating data _peakAmplitude = peak_ampl; _peakFrequency = peak_freq; // calculate the spectral mean // +20 because for the comparison below we only want to throw out bins // that are significantly higher (and would, thus, affect the mean more) const double meanAmplitude = (sum_mean / numFFTDataPoints) + 20.0; // now throw out any bins higher than the mean sum_mean = 0.0; uint64_t newNumDataPoints = numFFTDataPoints; for(uint64_t number = 0; number < numFFTDataPoints; number++){ if (_realFFTDataPoints[number] <= meanAmplitude) sum_mean += _realFFTDataPoints[number]; else newNumDataPoints--; } if (newNumDataPoints == 0) // in the odd case that all _noiseFloorAmplitude = meanAmplitude; // amplitudes are equal! else _noiseFloorAmplitude = sum_mean / newNumDataPoints; } if(lastOfMultipleUpdatesFlag){ int tabindex = SpectrumTypeTab->currentIndex(); if(tabindex == d_plot_fft) { _frequencyDisplayPlot->plotNewData(_averagedValues, numFFTDataPoints, _noiseFloorAmplitude, _peakFrequency, _peakAmplitude, d_update_time); } if(tabindex == d_plot_time) { _timeDomainDisplayPlot->plotNewData(timeDomainDataPoints, numTimeDomainDataPoints, d_update_time); } if(tabindex == d_plot_constellation) { _constellationDisplayPlot->plotNewData(realTimeDomainDataPoints, imagTimeDomainDataPoints, numTimeDomainDataPoints, d_update_time); } // Don't update the repeated data for the waterfall if(!repeatDataFlag){ if(tabindex == d_plot_waterfall) { _waterfallDisplayPlot->plotNewData(_realFFTDataPoints, numFFTDataPoints, d_update_time, dataTimestamp, spectrumUpdateEvent->getDroppedFFTFrames()); } } // Tell the system the GUI has been updated if(_systemSpecifiedFlag){ _system->setLastGUIUpdateTime(generatedTimestamp); _system->decrementPendingGUIUpdateEvents(); } } } void SpectrumDisplayForm::resizeEvent( QResizeEvent *e ) { QSize s; s.setWidth(FrequencyPlotDisplayFrame->width()); s.setHeight(FrequencyPlotDisplayFrame->height()); emit _frequencyDisplayPlot->resizeSlot(&s); s.setWidth(TimeDomainDisplayFrame->width()); s.setHeight(TimeDomainDisplayFrame->height()); emit _timeDomainDisplayPlot->resizeSlot(&s); s.setWidth(WaterfallPlotDisplayFrame->width()); s.setHeight(WaterfallPlotDisplayFrame->height()); emit _waterfallDisplayPlot->resizeSlot(&s); s.setWidth(ConstellationDisplayFrame->width()); s.setHeight(ConstellationDisplayFrame->height()); emit _constellationDisplayPlot->resizeSlot(&s); } void SpectrumDisplayForm::customEvent( QEvent * e) { if(e->type() == QEvent::User+3){ if(_systemSpecifiedFlag){ WindowComboBox->setCurrentIndex(_system->getWindowType()); FFTSizeComboBox->setCurrentIndex(_system->getFFTSizeIndex()); } waterfallMinimumIntensityChangedCB(WaterfallMinimumIntensitySlider->value()); waterfallMaximumIntensityChangedCB(WaterfallMaximumIntensitySlider->value()); // Clear any previous display reset(); } else if(e->type() == SpectrumUpdateEventType) { SpectrumUpdateEvent* spectrumUpdateEvent = (SpectrumUpdateEvent*)e; newFrequencyData(spectrumUpdateEvent); } else if(e->type() == SpectrumWindowCaptionEventType) { setWindowTitle(((SpectrumWindowCaptionEvent*)e)->getLabel()); } else if(e->type() == SpectrumWindowResetEventType) { reset(); if(_systemSpecifiedFlag){ _system->resetPendingGUIUpdateEvents(); } } else if(e->type() == SpectrumFrequencyRangeEventType) { _startFrequency = ((SpectrumFrequencyRangeEvent*)e)->GetStartFrequency(); _stopFrequency = ((SpectrumFrequencyRangeEvent*)e)->GetStopFrequency(); _centerFrequency = ((SpectrumFrequencyRangeEvent*)e)->GetCenterFrequency(); useRFFrequenciesCB(UseRFFrequenciesCheckBox->isChecked()); } } void SpectrumDisplayForm::updateGuiTimer() { // This is called by the displayTimer and redraws the canvases of // all of the plots. _frequencyDisplayPlot->canvas()->update(); _waterfallDisplayPlot->canvas()->update(); _timeDomainDisplayPlot->canvas()->update(); _constellationDisplayPlot->canvas()->update(); } void SpectrumDisplayForm::avgLineEdit_valueChanged( int value ) { setAverageCount(value); } void SpectrumDisplayForm::maxHoldCheckBox_toggled( bool newState ) { MaxHoldResetBtn->setEnabled(newState); _frequencyDisplayPlot->setMaxFFTVisible(newState); maxHoldResetBtn_clicked(); } void SpectrumDisplayForm::minHoldCheckBox_toggled( bool newState ) { MinHoldResetBtn->setEnabled(newState); _frequencyDisplayPlot->setMinFFTVisible(newState); minHoldResetBtn_clicked(); } void SpectrumDisplayForm::minHoldResetBtn_clicked() { _frequencyDisplayPlot->clearMinData(); _frequencyDisplayPlot->replot(); } void SpectrumDisplayForm::maxHoldResetBtn_clicked() { _frequencyDisplayPlot->clearMaxData(); _frequencyDisplayPlot->replot(); } void SpectrumDisplayForm::tabChanged(int index) { // This might be dangerous to call this with NULL resizeEvent(NULL); } void SpectrumDisplayForm::setFrequencyRange(const double newCenterFrequency, const double newStartFrequency, const double newStopFrequency) { double fcenter; if(UseRFFrequenciesCheckBox->isChecked()) { fcenter = newCenterFrequency; } else { fcenter = 0; } double fdiff = std::max(fabs(newStartFrequency), fabs(newStopFrequency)); if(fdiff > 0) { std::string strunits[4] = {"Hz", "kHz", "MHz", "GHz"}; std::string strtime[4] = {"sec", "ms", "us", "ns"}; double units10 = floor(log10(fdiff)); double units3 = std::max(floor(units10 / 3.0), 0.0); double units = pow(10, (units10-fmod(units10, 3.0))); int iunit = static_cast(units3); _startFrequency = newStartFrequency; _stopFrequency = newStopFrequency; _centerFrequency = newCenterFrequency; _frequencyDisplayPlot->setFrequencyRange(fcenter, fdiff, units, strunits[iunit]); _waterfallDisplayPlot->setFrequencyRange(fcenter, fdiff, units, strunits[iunit]); _timeDomainDisplayPlot->setSampleRate((_stopFrequency - _startFrequency)/2.0, units, strtime[iunit]); } } int SpectrumDisplayForm::getAverageCount() { return _historyVector->size(); } void SpectrumDisplayForm::setAverageCount(const int newCount) { if(newCount > -1) { if(newCount != static_cast(_historyVector->size())) { std::vector::iterator pos; while(newCount < static_cast(_historyVector->size())) { pos = _historyVector->begin(); delete[] (*pos); _historyVector->erase(pos); } while(newCount > static_cast(_historyVector->size())) { _historyVector->push_back(new double[_numRealDataPoints]); } averageDataReset(); } } } void SpectrumDisplayForm::_averageHistory(const double* newBuffer) { if(_numRealDataPoints > 0) { if(_historyVector->size() > 0) { memcpy(_historyVector->operator[](_historyEntry), newBuffer, _numRealDataPoints*sizeof(double)); // Increment the next location to store data _historyEntryCount++; if(_historyEntryCount > static_cast(_historyVector->size())) { _historyEntryCount = _historyVector->size(); } _historyEntry += 1; _historyEntry = _historyEntry % _historyVector->size(); // Total up and then average the values double sum; for(uint64_t location = 0; location < _numRealDataPoints; location++) { sum = 0; for(int number = 0; number < _historyEntryCount; number++) { sum += _historyVector->operator[](number)[location]; } _averagedValues[location] = sum/static_cast(_historyEntryCount); } } else { memcpy(_averagedValues, newBuffer, _numRealDataPoints*sizeof(double)); } } } void SpectrumDisplayForm::resizeBuffers(const uint64_t numFFTDataPoints, const uint64_t /*numTimeDomainDataPoints*/) { // Convert from Complex to Real for certain Displays if(_numRealDataPoints != numFFTDataPoints) { _numRealDataPoints = numFFTDataPoints; delete[] _realFFTDataPoints; delete[] _averagedValues; _realFFTDataPoints = new double[_numRealDataPoints]; _averagedValues = new double[_numRealDataPoints]; memset(_realFFTDataPoints, 0x0, _numRealDataPoints*sizeof(double)); const int historySize = _historyVector->size(); setAverageCount(0); // Clear the existing history setAverageCount(historySize); reset(); } } void SpectrumDisplayForm::reset() { averageDataReset(); _waterfallDisplayPlot->resetAxis(); } void SpectrumDisplayForm::averageDataReset() { _historyEntry = 0; _historyEntryCount = 0; memset(_averagedValues, 0x0, _numRealDataPoints*sizeof(double)); maxHoldResetBtn_clicked(); minHoldResetBtn_clicked(); } void SpectrumDisplayForm::closeEvent(QCloseEvent *e) { if(_systemSpecifiedFlag){ _system->setWindowOpenFlag(false); } qApp->processEvents(); QWidget::closeEvent(e); //equivalent to e->accept() } void SpectrumDisplayForm::windowTypeChanged(int newItem) { if(_systemSpecifiedFlag) { _system->setWindowType(newItem); } } void SpectrumDisplayForm::useRFFrequenciesCB(bool useRFFlag) { setFrequencyRange(_centerFrequency, _startFrequency, _stopFrequency); } void SpectrumDisplayForm::waterfallMaximumIntensityChangedCB(double newValue) { if(newValue > WaterfallMinimumIntensitySlider->value()) { WaterfallMaximumIntensityLabel->setText(QString("%1 dB").arg(newValue, 0, 'f', 0)); } else{ WaterfallMinimumIntensitySlider->setValue(newValue - 2); } _waterfallDisplayPlot->setIntensityRange(WaterfallMinimumIntensitySlider->value(), WaterfallMaximumIntensitySlider->value()); } void SpectrumDisplayForm::waterfallMinimumIntensityChangedCB( double newValue ) { if(newValue < WaterfallMaximumIntensitySlider->value()){ WaterfallMinimumIntensityLabel->setText(QString("%1 dB").arg(newValue, 0, 'f', 0)); } else{ WaterfallMaximumIntensitySlider->setValue(newValue + 2); } _waterfallDisplayPlot->setIntensityRange(WaterfallMinimumIntensitySlider->value(), WaterfallMaximumIntensitySlider->value()); } void SpectrumDisplayForm::fftComboBoxSelectedCB(const QString &fftSizeString) { if(_systemSpecifiedFlag){ _system->setFFTSize(fftSizeString.toLong()); } } void SpectrumDisplayForm::waterfallAutoScaleBtnCB() { double minimumIntensity = _noiseFloorAmplitude - 5; if(minimumIntensity < WaterfallMinimumIntensitySlider->minValue()){ minimumIntensity = WaterfallMinimumIntensitySlider->minValue(); } WaterfallMinimumIntensitySlider->setValue(minimumIntensity); double maximumIntensity = _peakAmplitude + 10; if(maximumIntensity > WaterfallMaximumIntensitySlider->maxValue()){ maximumIntensity = WaterfallMaximumIntensitySlider->maxValue(); } WaterfallMaximumIntensitySlider->setValue(maximumIntensity); waterfallMaximumIntensityChangedCB(maximumIntensity); } void SpectrumDisplayForm::waterfallIntensityColorTypeChanged( int newType ) { QColor lowIntensityColor; QColor highIntensityColor; if(newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED){ // Select the Low Intensity Color lowIntensityColor = _waterfallDisplayPlot->getUserDefinedLowIntensityColor(); if(!lowIntensityColor.isValid()){ lowIntensityColor = Qt::black; } QMessageBox::information(this, "Low Intensity Color Selection", "In the next window, select the low intensity color for the waterfall display", QMessageBox::Ok); lowIntensityColor = QColorDialog::getColor(lowIntensityColor, this); // Select the High Intensity Color highIntensityColor = _waterfallDisplayPlot->getUserDefinedHighIntensityColor(); if(!highIntensityColor.isValid()){ highIntensityColor = Qt::white; } QMessageBox::information(this, "High Intensity Color Selection", "In the next window, select the high intensity color for the waterfall display", QMessageBox::Ok); highIntensityColor = QColorDialog::getColor(highIntensityColor, this); } _waterfallDisplayPlot->setIntensityColorMapType(0, newType, lowIntensityColor, highIntensityColor); } void SpectrumDisplayForm::toggleTabFrequency(const bool state) { if(state == true) { if(d_plot_fft == -1) { SpectrumTypeTab->addTab(FrequencyPage, "Frequency Display"); d_plot_fft = SpectrumTypeTab->count()-1; } } else { SpectrumTypeTab->removeTab(SpectrumTypeTab->indexOf(FrequencyPage)); d_plot_fft = -1; } } void SpectrumDisplayForm::toggleTabWaterfall(const bool state) { if(state == true) { if(d_plot_waterfall == -1) { SpectrumTypeTab->addTab(WaterfallPage, "Waterfall Display"); d_plot_waterfall = SpectrumTypeTab->count()-1; } } else { SpectrumTypeTab->removeTab(SpectrumTypeTab->indexOf(WaterfallPage)); d_plot_waterfall = -1; } } void SpectrumDisplayForm::toggleTabTime(const bool state) { if(state == true) { if(d_plot_time == -1) { SpectrumTypeTab->addTab(TimeDomainPage, "Time Domain Display"); d_plot_time = SpectrumTypeTab->count()-1; } } else { SpectrumTypeTab->removeTab(SpectrumTypeTab->indexOf(TimeDomainPage)); d_plot_time = -1; } } void SpectrumDisplayForm::toggleTabConstellation(const bool state) { if(state == true) { if(d_plot_constellation == -1) { SpectrumTypeTab->addTab(ConstellationPage, "Constellation Display"); d_plot_constellation = SpectrumTypeTab->count()-1; } } else { SpectrumTypeTab->removeTab(SpectrumTypeTab->indexOf(ConstellationPage)); d_plot_constellation = -1; } } void SpectrumDisplayForm::setTimeDomainAxis(double min, double max) { _timeDomainDisplayPlot->setYaxis(min, max); } void SpectrumDisplayForm::setConstellationAxis(double xmin, double xmax, double ymin, double ymax) { _constellationDisplayPlot->set_axis(xmin, xmax, ymin, ymax); } void SpectrumDisplayForm::setConstellationPenSize(int size) { _constellationDisplayPlot->set_pen_size( size ); } void SpectrumDisplayForm::setFrequencyAxis(double min, double max) { _frequencyDisplayPlot->setYaxis(min, max); } void SpectrumDisplayForm::setUpdateTime(double t) { d_update_time = t; // QTimer class takes millisecond input displayTimer->start(d_update_time*1000); } void SpectrumDisplayForm::onFFTPlotPointSelected(const QPointF p) { emit plotPointSelected(p, 1); } void SpectrumDisplayForm::onWFallPlotPointSelected(const QPointF p) { emit plotPointSelected(p, 2); } void SpectrumDisplayForm::onTimePlotPointSelected(const QPointF p) { emit plotPointSelected(p, 3); } void SpectrumDisplayForm::onConstPlotPointSelected(const QPointF p) { emit plotPointSelected(p, 4); } gnuradio-3.7.2.1/gr-qtgui/lib/WaterfallDisplayPlot.cc0000664000175000017500000003610412237515112022251 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef WATERFALL_DISPLAY_PLOT_C #define WATERFALL_DISPLAY_PLOT_C #include #include #include #include #include #include #include #include #include #include namespace pt = boost::posix_time; #include /*********************************************************************** * Text scale widget to provide Y (time) axis text **********************************************************************/ class QwtTimeScaleDraw: public QwtScaleDraw, public TimeScaleData { public: QwtTimeScaleDraw():QwtScaleDraw(),TimeScaleData() { } virtual ~QwtTimeScaleDraw() { } virtual QwtText label(double value) const { double secs = double(value * getSecondsPerLine()); return QwtText(QString("").sprintf("%.1f", secs)); } virtual void initiateUpdate() { // Do this in one call rather than when zeroTime and secondsPerLine // updates is to prevent the display from being updated too often... invalidateCache(); } protected: private: }; /*********************************************************************** * Widget to provide mouse pointer coordinate text **********************************************************************/ class WaterfallZoomer: public QwtPlotZoomer, public TimeScaleData, public FreqOffsetAndPrecisionClass { public: WaterfallZoomer(QwtPlotCanvas* canvas, const unsigned int freqPrecision) : QwtPlotZoomer(canvas), TimeScaleData(), FreqOffsetAndPrecisionClass(freqPrecision) { setTrackerMode(QwtPicker::AlwaysOn); } virtual ~WaterfallZoomer() { } virtual void updateTrackerText() { updateDisplay(); } void setUnitType(const std::string &type) { d_unitType = type; } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText( QPoint const &p ) const { QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); double secs = double(dp.y() * getSecondsPerLine()); QwtText t(QString("%1 %2, %3 s") .arg(dp.x(), 0, 'f', getFrequencyPrecision()) .arg(d_unitType.c_str()) .arg(secs, 0, 'f', 2)); return t; } private: std::string d_unitType; }; /********************************************************************* * Main waterfall plot widget *********************************************************************/ WaterfallDisplayPlot::WaterfallDisplayPlot(int nplots, QWidget* parent) : DisplayPlot(nplots, parent) { d_zoomer = NULL; // need this for proper init d_start_frequency = -1; d_stop_frequency = 1; resize(parent->width(), parent->height()); d_numPoints = 1024; setAxisTitle(QwtPlot::xBottom, "Frequency (Hz)"); setAxisScaleDraw(QwtPlot::xBottom, new FreqDisplayScaleDraw(0)); setAxisTitle(QwtPlot::yLeft, "Time (s)"); setAxisScaleDraw(QwtPlot::yLeft, new QwtTimeScaleDraw()); for(int i = 0; i < d_nplots; i++) { d_data.push_back(new WaterfallData(d_start_frequency, d_stop_frequency, d_numPoints, 200)); #if QWT_VERSION < 0x060000 d_spectrogram.push_back(new PlotWaterfall(d_data[i], "Spectrogram")); #else d_spectrogram.push_back(new QwtPlotSpectrogram("Spectrogram")); d_spectrogram[i]->setData(d_data[i]); d_spectrogram[i]->setDisplayMode(QwtPlotSpectrogram::ImageMode, true); d_spectrogram[i]->setColorMap(new ColorMap_MultiColor()); #endif // a hack around the fact that we aren't using plot curves for the // spectrogram plots. d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); d_spectrogram[i]->attach(this); d_intensity_color_map_type.push_back(INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR); setIntensityColorMapType(i, d_intensity_color_map_type[i], QColor("white"), QColor("white")); setAlpha(i, 255/d_nplots); } // Set bottom plot with no transparency as a base setAlpha(0, 255); // LeftButton for the zooming // MidButton for the panning // RightButton: zoom out by 1 // Ctrl+RighButton: zoom out to full size d_zoomer = new WaterfallZoomer(canvas(), 0); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor c(Qt::black); d_zoomer->setRubberBandPen(c); d_zoomer->setTrackerPen(c); _updateIntensityRangeDisplay(); d_xaxis_multiplier = 1; } WaterfallDisplayPlot::~WaterfallDisplayPlot() { } void WaterfallDisplayPlot::resetAxis() { for(int i = 0; i < d_nplots; i++) { d_data[i]->resizeData(d_start_frequency, d_stop_frequency, d_numPoints); d_data[i]->reset(); } setAxisScale(QwtPlot::xBottom, d_start_frequency, d_stop_frequency); // Load up the new base zoom settings QwtDoubleRect zbase = d_zoomer->zoomBase(); d_zoomer->zoom(zbase); d_zoomer->setZoomBase(zbase); d_zoomer->setZoomBase(true); d_zoomer->zoom(0); } void WaterfallDisplayPlot::setFrequencyRange(const double centerfreq, const double bandwidth, const double units, const std::string &strunits) { double startFreq = (centerfreq - bandwidth/2.0f) / units; double stopFreq = (centerfreq + bandwidth/2.0f) / units; d_xaxis_multiplier = units; bool reset = false; if((startFreq != d_start_frequency) || (stopFreq != d_stop_frequency)) reset = true; if(stopFreq > startFreq) { d_start_frequency = startFreq; d_stop_frequency = stopFreq; if((axisScaleDraw(QwtPlot::xBottom) != NULL) && (d_zoomer != NULL)) { double display_units = ceil(log10(units)/2.0); setAxisScaleDraw(QwtPlot::xBottom, new FreqDisplayScaleDraw(display_units)); setAxisTitle(QwtPlot::xBottom, QString("Frequency (%1)").arg(strunits.c_str())); if(reset) { resetAxis(); } ((WaterfallZoomer*)d_zoomer)->setFrequencyPrecision(display_units); ((WaterfallZoomer*)d_zoomer)->setUnitType(strunits); } } } double WaterfallDisplayPlot::getStartFrequency() const { return d_start_frequency; } double WaterfallDisplayPlot::getStopFrequency() const { return d_stop_frequency; } void WaterfallDisplayPlot::plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double timePerFFT, const gr::high_res_timer_type timestamp, const int droppedFrames) { if(!d_stop) { if(numDataPoints > 0){ if(numDataPoints != d_numPoints){ d_numPoints = numDataPoints; resetAxis(); for(int i = 0; i < d_nplots; i++) { d_spectrogram[i]->invalidateCache(); d_spectrogram[i]->itemChanged(); } if(isVisible()) { replot(); } } QwtTimeScaleDraw* timeScale = (QwtTimeScaleDraw*)axisScaleDraw(QwtPlot::yLeft); timeScale->setSecondsPerLine(timePerFFT); timeScale->setZeroTime(timestamp); ((WaterfallZoomer*)d_zoomer)->setSecondsPerLine(timePerFFT); ((WaterfallZoomer*)d_zoomer)->setZeroTime(timestamp); for(int i = 0; i < d_nplots; i++) { d_data[i]->addFFTData(dataPoints[i], numDataPoints, droppedFrames); d_data[i]->incrementNumLinesToUpdate(); d_spectrogram[i]->invalidateCache(); d_spectrogram[i]->itemChanged(); } replot(); } } } void WaterfallDisplayPlot::plotNewData(const double* dataPoints, const int64_t numDataPoints, const double timePerFFT, const gr::high_res_timer_type timestamp, const int droppedFrames) { std::vector vecDataPoints; vecDataPoints.push_back((double*)dataPoints); plotNewData(vecDataPoints, numDataPoints, timePerFFT, timestamp, droppedFrames); } void WaterfallDisplayPlot::setIntensityRange(const double minIntensity, const double maxIntensity) { for(int i = 0; i < d_nplots; i++) { #if QWT_VERSION < 0x060000 d_data[i]->setRange(QwtDoubleInterval(minIntensity, maxIntensity)); #else d_data[i]->setInterval(Qt::ZAxis, QwtInterval(minIntensity, maxIntensity)); #endif emit updatedLowerIntensityLevel(minIntensity); emit updatedUpperIntensityLevel(maxIntensity); _updateIntensityRangeDisplay(); } } double WaterfallDisplayPlot::getMinIntensity(int which) const { #if QWT_VERSION < 0x060000 QwtDoubleInterval r = d_data[which]->range(); #else QwtInterval r = d_data[which]->interval(Qt::ZAxis); #endif return r.minValue(); } double WaterfallDisplayPlot::getMaxIntensity(int which) const { #if QWT_VERSION < 0x060000 QwtDoubleInterval r = d_data[which]->range(); #else QwtInterval r = d_data[which]->interval(Qt::ZAxis); #endif return r.maxValue(); } void WaterfallDisplayPlot::replot() { QwtTimeScaleDraw* timeScale = (QwtTimeScaleDraw*)axisScaleDraw(QwtPlot::yLeft); timeScale->initiateUpdate(); FreqDisplayScaleDraw* freqScale = \ (FreqDisplayScaleDraw*)axisScaleDraw(QwtPlot::xBottom); freqScale->initiateUpdate(); // Update the time axis display if(axisWidget(QwtPlot::yLeft) != NULL){ axisWidget(QwtPlot::yLeft)->update(); } // Update the Frequency Offset Display if(axisWidget(QwtPlot::xBottom) != NULL){ axisWidget(QwtPlot::xBottom)->update(); } if(d_zoomer != NULL){ ((WaterfallZoomer*)d_zoomer)->updateTrackerText(); } QwtPlot::replot(); } void WaterfallDisplayPlot::clearData() { for(int i = 0; i < d_nplots; i++) { d_data[i]->reset(); } } int WaterfallDisplayPlot::getIntensityColorMapType(int which) const { return d_intensity_color_map_type[which]; } void WaterfallDisplayPlot::setIntensityColorMapType(const int which, const int newType, const QColor lowColor, const QColor highColor) { if((d_intensity_color_map_type[which] != newType) || ((newType == INTENSITY_COLOR_MAP_TYPE_USER_DEFINED) && (lowColor.isValid() && highColor.isValid()))){ switch(newType){ case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR:{ d_intensity_color_map_type[which] = newType; #if QWT_VERSION < 0x060000 ColorMap_MultiColor colorMap; d_spectrogram[which]->setColorMap(colorMap); #else d_spectrogram[which]->setColorMap(new ColorMap_MultiColor()); #endif break; } case INTENSITY_COLOR_MAP_TYPE_WHITE_HOT:{ d_intensity_color_map_type[which] = newType; #if QWT_VERSION < 0x060000 ColorMap_WhiteHot colorMap; d_spectrogram[which]->setColorMap(colorMap); #else d_spectrogram[which]->setColorMap(new ColorMap_WhiteHot()); #endif break; } case INTENSITY_COLOR_MAP_TYPE_BLACK_HOT:{ d_intensity_color_map_type[which] = newType; #if QWT_VERSION < 0x060000 ColorMap_BlackHot colorMap; d_spectrogram[which]->setColorMap(colorMap); #else d_spectrogram[which]->setColorMap(new ColorMap_BlackHot()); #endif break; } case INTENSITY_COLOR_MAP_TYPE_INCANDESCENT:{ d_intensity_color_map_type[which] = newType; #if QWT_VERSION < 0x060000 ColorMap_Incandescent colorMap; d_spectrogram[which]->setColorMap(colorMap); #else d_spectrogram[which]->setColorMap(new ColorMap_Incandescent()); #endif break; } case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED:{ d_user_defined_low_intensity_color = lowColor; d_user_defined_high_intensity_color = highColor; d_intensity_color_map_type[which] = newType; #if QWT_VERSION < 0x060000 ColorMap_UserDefined colorMap(lowColor, highColor); d_spectrogram[which]->setColorMap(colorMap); #else d_spectrogram[which]->setColorMap(new ColorMap_UserDefined(lowColor, highColor)); #endif break; } default: break; } _updateIntensityRangeDisplay(); } } void WaterfallDisplayPlot::setIntensityColorMapType1(int newType) { setIntensityColorMapType(0, newType, d_user_defined_low_intensity_color, d_user_defined_high_intensity_color); } int WaterfallDisplayPlot::getIntensityColorMapType1() const { return getIntensityColorMapType(0); } void WaterfallDisplayPlot::setUserDefinedLowIntensityColor(QColor c) { d_user_defined_low_intensity_color = c; } const QColor WaterfallDisplayPlot::getUserDefinedLowIntensityColor() const { return d_user_defined_low_intensity_color; } void WaterfallDisplayPlot::setUserDefinedHighIntensityColor(QColor c) { d_user_defined_high_intensity_color = c; } const QColor WaterfallDisplayPlot::getUserDefinedHighIntensityColor() const { return d_user_defined_high_intensity_color; } int WaterfallDisplayPlot::getAlpha(int which) { return d_spectrogram[which]->alpha(); } void WaterfallDisplayPlot::setAlpha(int which, int alpha) { d_spectrogram[which]->setAlpha(alpha); } void WaterfallDisplayPlot::_updateIntensityRangeDisplay() { QwtScaleWidget *rightAxis = axisWidget(QwtPlot::yRight); rightAxis->setTitle("Intensity (dB)"); rightAxis->setColorBarEnabled(true); for(int i = 0; i < d_nplots; i++) { #if QWT_VERSION < 0x060000 rightAxis->setColorMap(d_spectrogram[i]->data()->range(), d_spectrogram[i]->colorMap()); setAxisScale(QwtPlot::yRight, d_spectrogram[i]->data()->range().minValue(), d_spectrogram[i]->data()->range().maxValue()); #else QwtInterval intv = d_spectrogram[i]->interval(Qt::ZAxis); switch(d_intensity_color_map_type[i]) { case INTENSITY_COLOR_MAP_TYPE_MULTI_COLOR: rightAxis->setColorMap(intv, new ColorMap_MultiColor()); break; case INTENSITY_COLOR_MAP_TYPE_WHITE_HOT: rightAxis->setColorMap(intv, new ColorMap_WhiteHot()); break; case INTENSITY_COLOR_MAP_TYPE_BLACK_HOT: rightAxis->setColorMap(intv, new ColorMap_BlackHot()); break; case INTENSITY_COLOR_MAP_TYPE_INCANDESCENT: rightAxis->setColorMap(intv, new ColorMap_Incandescent()); break; case INTENSITY_COLOR_MAP_TYPE_USER_DEFINED: rightAxis->setColorMap(intv, new ColorMap_UserDefined(d_user_defined_low_intensity_color, d_user_defined_high_intensity_color)); break; default: rightAxis->setColorMap(intv, new ColorMap_MultiColor()); break; } setAxisScale(QwtPlot::yRight, intv.minValue(), intv.maxValue()); #endif enableAxis(QwtPlot::yRight); plotLayout()->setAlignCanvasToScales(true); // Tell the display to redraw everything d_spectrogram[i]->invalidateCache(); d_spectrogram[i]->itemChanged(); } // Draw again replot(); } #endif /* WATERFALL_DISPLAY_PLOT_C */ gnuradio-3.7.2.1/gr-qtgui/lib/waterfall_sink_f_impl.h0000664000175000017500000000724112237515112022340 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_WATERFALL_SINK_F_IMPL_H #define INCLUDED_QTGUI_WATERFALL_SINK_F_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API waterfall_sink_f_impl : public waterfall_sink_f { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); int d_fftsize; float d_fftavg; filter::firdes::win_type d_wintype; std::vector d_window; double d_center_freq; double d_bandwidth; std::string d_name; int d_nconnections; bool d_shift; fft::fft_complex *d_fft; int d_index; std::vector d_residbufs; std::vector d_magbufs; float *d_fbuf; int d_argc; char *d_argv; QWidget *d_parent; WaterfallDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; void windowreset(); void buildwindow(); void fftresize(); void fft(float *data_out, const float *data_in, int size); public: waterfall_sink_f_impl(int size, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent=NULL); ~waterfall_sink_f_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void clear_data(); void set_fft_size(const int fftsize); int fft_size() const; void set_fft_average(const float fftavg); float fft_average() const; void set_fft_window(const gr::filter::firdes::win_type win); gr::filter::firdes::win_type fft_window(); void set_frequency_range(const double centerfreq, const double bandwidth); void set_intensity_range(const double min, const double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_alpha(int which, double alpha); void set_color_map(int which, const int color); std::string title(); std::string line_label(int which); double line_alpha(int which); int color_map(int which); void set_size(int width, int height); void auto_scale(); double min_intensity(int which); double max_intensity(int which); void enable_menu(bool en); void enable_grid(bool en); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_WATERFALL_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/time_raster_sink_f_impl.cc0000664000175000017500000002566012237515112023040 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "time_raster_sink_f_impl.h" #include #include #include namespace gr { namespace qtgui { time_raster_sink_f::sptr time_raster_sink_f::make(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new time_raster_sink_f_impl(samp_rate, rows, cols, mult, offset, name, nconnections, parent)); } time_raster_sink_f_impl::time_raster_sink_f_impl(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections, QWidget *parent) : sync_block("time_raster_sink_f", io_signature::make(1, -1, sizeof(float)), io_signature::make(0, 0, 0)), d_name(name), d_nconnections(nconnections), d_parent(parent), d_rows(rows), d_cols(cols), d_mult(std::vector(nconnections,1)), d_offset(std::vector(nconnections,0)), d_samp_rate(samp_rate) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; d_index = 0; d_icols = static_cast(ceil(d_cols)); d_tmpflt = fft::malloc_float(d_icols); memset(d_tmpflt, 0, d_icols*sizeof(float)); for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_double(d_icols)); memset(d_residbufs[i], 0, d_icols*sizeof(double)); } set_multiplier(mult); set_offset(offset); initialize(); } time_raster_sink_f_impl::~time_raster_sink_f_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); fft::free(d_tmpflt); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); } delete d_argv; } bool time_raster_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void time_raster_sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } // Create time raster plot; as a bit input, we expect to see 1's // and 0's from each stream, so we set the maximum intensity // (zmax) to the number of connections so after adding the // streams, the max will the the max of 1's from all streams. d_main_gui = new TimeRasterDisplayForm(d_nconnections, d_samp_rate, d_rows, d_cols, 1, d_parent); // initialize update time to 10 times a second set_update_time(0.1); } void time_raster_sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* time_raster_sink_f_impl::qwidget() { return d_main_gui; } PyObject* time_raster_sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void time_raster_sink_f_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void time_raster_sink_f_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void time_raster_sink_f_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void time_raster_sink_f_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void time_raster_sink_f_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void time_raster_sink_f_impl::set_line_style(int which, Qt::PenStyle style) { d_main_gui->setLineStyle(which, style); } void time_raster_sink_f_impl::set_line_marker(int which, QwtSymbol::Style marker) { d_main_gui->setLineMarker(which, marker); } void time_raster_sink_f_impl::set_color_map(int which, const int color) { d_main_gui->setColorMap(which, color); } void time_raster_sink_f_impl::set_line_alpha(int which, double alpha) { d_main_gui->setAlpha(which, (int)(255.0*alpha)); } void time_raster_sink_f_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } void time_raster_sink_f_impl::set_samp_rate(const double samp_rate) { d_samp_rate = samp_rate; d_main_gui->setSampleRate(d_samp_rate); } void time_raster_sink_f_impl::set_num_rows(double rows) { d_main_gui->setNumRows(rows); } void time_raster_sink_f_impl::set_num_cols(double cols) { d_main_gui->setNumCols(cols); } std::string time_raster_sink_f_impl::title() { return d_main_gui->title().toStdString(); } std::string time_raster_sink_f_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string time_raster_sink_f_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int time_raster_sink_f_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int time_raster_sink_f_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int time_raster_sink_f_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } int time_raster_sink_f_impl::color_map(int which) { return d_main_gui->getColorMap(which); } double time_raster_sink_f_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } double time_raster_sink_f_impl::num_rows() { return d_main_gui->numRows(); } double time_raster_sink_f_impl::num_cols() { return d_main_gui->numCols(); } void time_raster_sink_f_impl::set_multiplier(const std::vector &mult) { if(mult.size() == 0) { for(int i = 0; i < d_nconnections; i++) { d_mult[i] = 1.0f; } } else if(mult.size() == (size_t)d_nconnections) { for(int i = 0; i < d_nconnections; i++) { d_mult[i] = mult[i]; } } else { throw std::runtime_error("time_raster_sink_f_impl::set_multiplier incorrect dimensions.\n"); } } void time_raster_sink_f_impl::set_offset(const std::vector &offset) { if(offset.size() == 0) { for(int i = 0; i < d_nconnections; i++) { d_offset[i] = 0.0f; } } else if(offset.size() == (size_t)d_nconnections) { for(int i = 0; i < d_nconnections; i++) { d_offset[i] = offset[i]; } } else { throw std::runtime_error("time_raster_sink_f_impl::set_offset incorrect dimensions.\n"); } } void time_raster_sink_f_impl::set_intensity_range(float min, float max) { d_main_gui->setIntensityRange(min, max); } void time_raster_sink_f_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void time_raster_sink_f_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void time_raster_sink_f_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void time_raster_sink_f_impl::reset() { d_index = 0; } int time_raster_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, j=0, idx=0; const float *in = (const float*)input_items[0]; double cols = d_main_gui->numCols(); if(d_cols != cols) { d_cols = cols; d_index = 0; d_icols = static_cast(ceil(d_cols)); fft::free(d_tmpflt); d_tmpflt = fft::malloc_float(d_icols); memset(d_tmpflt, 0, d_icols*sizeof(float)); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); d_residbufs[i] = fft::malloc_double(d_icols); memset(d_residbufs[i], 0, d_icols*sizeof(double)); } } for(int i = 0; i < noutput_items; i += d_icols) { unsigned int datasize = noutput_items - i; unsigned int resid = d_icols-d_index; idx = 0; // If we have enough input for one full plot, do it if(datasize >= resid) { // Fill up residbufs with d_size number of items for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx++]; // Scale and add offset volk_32f_s32f_multiply_32f(d_tmpflt, &in[j], d_mult[n], resid); for(unsigned int s = 0; s < resid; s++) d_tmpflt[s] = d_tmpflt[s] + d_offset[n]; volk_32f_convert_64f_u(&d_residbufs[n][d_index], d_tmpflt, resid); } // Update the plot if its time if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new TimeRasterUpdateEvent(d_residbufs, d_cols)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbufs for next time // because we set the output_multiple, this should never need to be called else { for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx++]; // Scale and add offset volk_32f_s32f_multiply_32f(d_tmpflt, &in[j], d_mult[n], datasize); for(unsigned int s = 0; s < datasize; s++) d_tmpflt[s] = d_tmpflt[s] + d_offset[n]; volk_32f_convert_64f(&d_residbufs[n][d_index], d_tmpflt, datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/sink_f_impl.h0000664000175000017500000000577312237515112020307 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_SINK_F_IMPL_H #define INCLUDED_QTGUI_SINK_F_IMPL_H #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API sink_f_impl : public sink_f { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); int d_fftsize; filter::firdes::win_type d_wintype; std::vector d_window; double d_center_freq; double d_bandwidth; std::string d_name; bool d_shift; fft::fft_complex *d_fft; int d_index; float *d_residbuf; float *d_magbuf; bool d_plotfreq, d_plotwaterfall, d_plottime, d_plotconst; double d_update_time; int d_argc; char *d_argv; QWidget *d_parent; SpectrumGUIClass *d_main_gui; void windowreset(); void buildwindow(); void fftresize(); void fft(float *data_out, const float *data_in, int size); public: sink_f_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent); ~sink_f_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_fft_size(const int fftsize); int fft_size() const; void set_frequency_range(const double centerfreq, const double bandwidth); void set_fft_power_db(double min, double max); //void set_time_domain_axis(double min, double max); //void set_constellation_axis(double xmin, double xmax, // double ymin, double ymax); //void set_constellation_pen_size(int size); void set_update_time(double t); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/freq_sink_f_impl.h0000664000175000017500000000750012237515112021312 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_FREQ_SINK_F_IMPL_H #define INCLUDED_QTGUI_FREQ_SINK_F_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API freq_sink_f_impl : public freq_sink_f { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); gr::thread::mutex d_mutex; int d_fftsize; float d_fftavg; filter::firdes::win_type d_wintype; std::vector d_window; double d_center_freq; double d_bandwidth; std::string d_name; int d_nconnections; bool d_shift; fft::fft_complex *d_fft; int d_index; std::vector d_residbufs; std::vector d_magbufs; float *d_fbuf; int d_argc; char *d_argv; QWidget *d_parent; FreqDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; void windowreset(); void buildwindow(); void fftresize(); void fft(float *data_out, const float *data_in, int size); public: freq_sink_f_impl(int size, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent=NULL); ~freq_sink_f_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_fft_size(const int fftsize); int fft_size() const; void set_fft_average(const float fftavg); float fft_average() const; void set_fft_window(const filter::firdes::win_type win); filter::firdes::win_type fft_window(); void set_frequency_range(const double centerfreq, const double bandwidth); void set_y_axis(double min, double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, int style); void set_line_marker(int which, int marker); void set_line_alpha(int which, double alpha); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); void set_size(int width, int height); void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_FREQ_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/constellationdisplayform.cc0000664000175000017500000000607612237515112023300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include ConstellationDisplayForm::ConstellationDisplayForm(int nplots, QWidget* parent) : DisplayForm(nplots, parent) { d_int_validator = new QIntValidator(this); d_int_validator->setBottom(0); d_layout = new QGridLayout(this); d_display_plot = new ConstellationDisplayPlot(nplots, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); NPointsMenu *nptsmenu = new NPointsMenu(this); d_menu->addAction(nptsmenu); connect(nptsmenu, SIGNAL(whichTrigger(int)), this, SLOT(setNPoints(const int))); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } ConstellationDisplayForm::~ConstellationDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete d_int_validator; } ConstellationDisplayPlot* ConstellationDisplayForm::getPlot() { return ((ConstellationDisplayPlot*)d_display_plot); } void ConstellationDisplayForm::newData(const QEvent* updateEvent) { ConstUpdateEvent *tevent = (ConstUpdateEvent*)updateEvent; const std::vector realDataPoints = tevent->getRealPoints(); const std::vector imagDataPoints = tevent->getImagPoints(); const uint64_t numDataPoints = tevent->getNumDataPoints(); getPlot()->plotNewData(realDataPoints, imagDataPoints, numDataPoints, d_update_time); } void ConstellationDisplayForm::customEvent(QEvent * e) { if(e->type() == ConstUpdateEvent::Type()) { newData(e); } } int ConstellationDisplayForm::getNPoints() const { return d_npoints; } void ConstellationDisplayForm::setNPoints(const int npoints) { d_npoints = npoints; } void ConstellationDisplayForm::setYaxis(double min, double max) { getPlot()->set_yaxis(min, max); } void ConstellationDisplayForm::setXaxis(double min, double max) { getPlot()->set_xaxis(min, max); } void ConstellationDisplayForm::autoScale(bool en) { d_autoscale_state = en; d_autoscale_act->setChecked(en); getPlot()->setAutoScale(d_autoscale_state); getPlot()->replot(); } void ConstellationDisplayForm::setSampleRate(const QString &samprate) { } gnuradio-3.7.2.1/gr-qtgui/lib/waterfall_sink_f_impl.cc0000664000175000017500000002642012237515112022476 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "waterfall_sink_f_impl.h" #include #include #include namespace gr { namespace qtgui { waterfall_sink_f::sptr waterfall_sink_f::make(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new waterfall_sink_f_impl(fftsize, wintype, fc, bw, name, nconnections, parent)); } waterfall_sink_f_impl::waterfall_sink_f_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) : sync_block("waterfall_sink_f", io_signature::make(1, -1, sizeof(float)), io_signature::make(0, 0, 0)), d_fftsize(fftsize), d_fftavg(1.0), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex(d_fftsize, true); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_float(d_fftsize)); d_magbufs.push_back(fft::malloc_double(d_fftsize)); memset(d_residbufs[i], 0, d_fftsize*sizeof(float)); memset(d_magbufs[i], 0, d_fftsize*sizeof(double)); } buildwindow(); initialize(); } waterfall_sink_f_impl::~waterfall_sink_f_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); } delete d_fft; fft::free(d_fbuf); delete d_argv; } bool waterfall_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void waterfall_sink_f_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void waterfall_sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new WaterfallDisplayForm(d_nconnections, d_parent); set_fft_window(d_wintype); set_fft_size(d_fftsize); set_frequency_range(d_center_freq, d_bandwidth); // initialize update time to 10 times a second set_update_time(0.1); } void waterfall_sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* waterfall_sink_f_impl::qwidget() { return d_main_gui; } PyObject* waterfall_sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void waterfall_sink_f_impl::clear_data() { d_main_gui->clearData(); } void waterfall_sink_f_impl::set_fft_size(const int fftsize) { d_main_gui->setFFTSize(fftsize); } int waterfall_sink_f_impl::fft_size() const { return d_fftsize; } void waterfall_sink_f_impl::set_fft_average(const float fftavg) { d_main_gui->setFFTAverage(fftavg); } float waterfall_sink_f_impl::fft_average() const { return d_fftavg; } void waterfall_sink_f_impl::set_fft_window(const filter::firdes::win_type win) { d_main_gui->setFFTWindowType(win); } filter::firdes::win_type waterfall_sink_f_impl::fft_window() { return d_wintype; } void waterfall_sink_f_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->setFrequencyRange(d_center_freq, d_bandwidth); } void waterfall_sink_f_impl::set_intensity_range(const double min, const double max) { d_main_gui->setIntensityRange(min, max); } void waterfall_sink_f_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void waterfall_sink_f_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void waterfall_sink_f_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void waterfall_sink_f_impl::set_color_map(int which, const int color) { d_main_gui->setColorMap(which, color); } void waterfall_sink_f_impl::set_line_alpha(int which, double alpha) { d_main_gui->setAlpha(which, (int)(255.0*alpha)); } void waterfall_sink_f_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string waterfall_sink_f_impl::title() { return d_main_gui->title().toStdString(); } std::string waterfall_sink_f_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } int waterfall_sink_f_impl::color_map(int which) { return d_main_gui->getColorMap(which); } double waterfall_sink_f_impl::line_alpha(int which) { return (double)(d_main_gui->getAlpha(which))/255.0; } void waterfall_sink_f_impl::auto_scale() { d_main_gui->autoScale(); } double waterfall_sink_f_impl::min_intensity(int which) { return d_main_gui->getMinIntensity(which); } double waterfall_sink_f_impl::max_intensity(int which) { return d_main_gui->getMaxIntensity(which); } void waterfall_sink_f_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void waterfall_sink_f_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void waterfall_sink_f_impl::fft(float *data_out, const float *data_in, int size) { // float to complex conversion gr_complex *dst = d_fft->get_inbuf(); for (int i = 0; i < size; i++) dst[i] = data_in[i]; if(d_window.size()) { volk_32fc_32f_multiply_32fc_a(d_fft->get_inbuf(), dst, &d_window.front(), size); } d_fft->execute(); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); // Perform shift operation unsigned int len = (unsigned int)(floor(size/2.0)); float *tmp = (float*)malloc(sizeof(float)*len); memcpy(tmp, &data_out[0], sizeof(float)*len); memcpy(&data_out[0], &data_out[len], sizeof(float)*(size - len)); memcpy(&data_out[size - len], tmp, sizeof(float)*len); free(tmp); } void waterfall_sink_f_impl::windowreset() { filter::firdes::win_type newwintype; newwintype = d_main_gui->getFFTWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void waterfall_sink_f_impl::buildwindow() { d_window.clear(); if(d_wintype != filter::firdes::WIN_NONE) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void waterfall_sink_f_impl::fftresize() { int newfftsize = d_fftsize; if(newfftsize != d_fftsize) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); d_residbufs[i] = fft::malloc_float(newfftsize); d_magbufs[i] = fft::malloc_double(newfftsize); memset(d_residbufs[i], 0, newfftsize*sizeof(float)); memset(d_magbufs[i], 0, newfftsize*sizeof(double)); } // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex(d_fftsize, true); fft::free(d_fbuf); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); } } int waterfall_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const float *in = (const float*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; // If we have enough input for one full FFT, do it if(datasize >= resid) { if(gr::high_res_timer_now() - d_last_time > d_update_time) { for(int n = 0; n < d_nconnections; n++) { // Fill up residbuf with d_fftsize number of items in = (const float*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(float)*resid); fft(d_fbuf, d_residbufs[n], d_fftsize); for(int x = 0; x < d_fftsize; x++) { d_magbufs[n][x] = (double)((1.0-d_fftavg)*d_magbufs[n][x] + (d_fftavg)*d_fbuf[x]); } //volk_32f_convert_64f_a(d_magbufs[n], d_fbuf, d_fftsize); } d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new WaterfallUpdateEvent(d_magbufs, d_fftsize, d_last_time)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbuf for next time else { for(int n = 0; n < d_nconnections; n++) { in = (const float*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(float)*datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/HistogramDisplayPlot.cc0000664000175000017500000002717712237515112022277 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef HISTOGRAM_DISPLAY_PLOT_C #define HISTOGRAM_DISPLAY_PLOT_C #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER #define copysign _copysign #endif class TimePrecisionClass { public: TimePrecisionClass(const int timeprecision) { d_time_precision = timeprecision; } virtual ~TimePrecisionClass() { } virtual unsigned int getTimePrecision() const { return d_time_precision; } virtual void setTimePrecision(const unsigned int newprecision) { d_time_precision = newprecision; } protected: unsigned int d_time_precision; }; class HistogramDisplayZoomer: public QwtPlotZoomer, public TimePrecisionClass { public: HistogramDisplayZoomer(QwtPlotCanvas* canvas, const unsigned int timeprecision) : QwtPlotZoomer(canvas),TimePrecisionClass(timeprecision) { setTrackerMode(QwtPicker::AlwaysOn); } virtual ~HistogramDisplayZoomer() { } virtual void updateTrackerText() { updateDisplay(); } void setUnitType(const std::string &type) { d_unit_type = type; } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText(const QPoint& p) const { QwtText t; QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); if((dp.y() > 0.0001) && (dp.y() < 10000)) { t.setText(QString("%1, %2"). arg(dp.x(), 0, 'f', 4). arg(dp.y(), 0, 'f', 0)); } else { t.setText(QString("%1, %2"). arg(dp.x(), 0, 'f', 4). arg(dp.y(), 0, 'e', 0)); } return t; } private: std::string d_unit_type; }; /*********************************************************************** * Main Time domain plotter widget **********************************************************************/ HistogramDisplayPlot::HistogramDisplayPlot(int nplots, QWidget* parent) : DisplayPlot(nplots, parent) { d_bins = 100; d_accum = false; // Initialize x-axis data array d_xdata = new double[d_bins]; memset(d_xdata, 0x0, d_bins*sizeof(double)); d_zoomer = new HistogramDisplayZoomer(canvas(), 0); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor c(Qt::darkRed); d_zoomer->setRubberBandPen(c); d_zoomer->setTrackerPen(c); d_semilogx = false; d_semilogy = false; d_autoscale_state = true; d_autoscalex_state = false; setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); setXaxis(-1, 1); setAxisTitle(QwtPlot::xBottom, "Value"); setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setYaxis(-2.0, d_bins); setAxisTitle(QwtPlot::yLeft, "Count"); QList colors; colors << QColor(Qt::blue) << QColor(Qt::red) << QColor(Qt::green) << QColor(Qt::black) << QColor(Qt::cyan) << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray); // Setup dataPoints and plot vectors // Automatically deleted when parent is deleted for(int i = 0; i < d_nplots; i++) { d_ydata.push_back(new double[d_bins]); memset(d_ydata[i], 0, d_bins*sizeof(double)); d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); d_plot_curve[i]->attach(this); d_plot_curve[i]->setPen(QPen(colors[i])); d_plot_curve[i]->setRenderHint(QwtPlotItem::RenderAntialiased); // Adjust color's transparency for the brush colors[i].setAlpha(127 / d_nplots); d_plot_curve[i]->setBrush(QBrush(colors[i])); colors[i].setAlpha(255 / d_nplots); QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(colors[i]), QPen(colors[i]), QSize(7,7)); #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_bins); d_plot_curve[i]->setSymbol(*symbol); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_bins); d_plot_curve[i]->setSymbol(symbol); #endif } _resetXAxisPoints(-1, 1); } HistogramDisplayPlot::~HistogramDisplayPlot() { for(int i = 0; i < d_nplots; i++) delete[] d_ydata[i]; delete[] d_xdata; // d_zoomer and _panner deleted when parent deleted } void HistogramDisplayPlot::replot() { QwtPlot::replot(); } void HistogramDisplayPlot::plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double timeInterval) { if(!d_stop) { if((numDataPoints > 0)) { // keep track of the min/max values for when autoscaleX is called. d_xmin = 1e20; d_xmax = -1e20; for(int n = 0; n < d_nplots; n++) { d_xmin = std::min(d_xmin, *std::min_element(dataPoints[n], dataPoints[n]+numDataPoints)); d_xmax = std::max(d_xmax, *std::max_element(dataPoints[n], dataPoints[n]+numDataPoints)); } // If autoscalex has been clicked, clear the data for the new // bin widths and reset the x-axis. if(d_autoscalex_state) { for(int n = 0; n < d_nplots; n++) memset(d_ydata[n], 0, d_bins*sizeof(double)); _resetXAxisPoints(d_xmin, d_xmax); d_autoscalex_state = false; } int index; for(int n = 0; n < d_nplots; n++) { if(!d_accum) memset(d_ydata[n], 0, d_bins*sizeof(double)); for(int64_t point = 0; point < numDataPoints; point++) { index = boost::math::iround(1e-20 + (dataPoints[n][point] - d_left)/d_width); if((index >= 0) && (index < d_bins)) d_ydata[n][static_cast(index)] += 1; } } double height = *std::max_element(d_ydata[0], d_ydata[0]+d_bins); for(int n = 1; n < d_nplots; n++) { height = std::max(height, *std::max_element(d_ydata[n], d_ydata[n]+d_bins)); } if(d_autoscale_state) _autoScaleY(0, height); replot(); } } } void HistogramDisplayPlot::setXaxis(double min, double max) { _resetXAxisPoints(min, max); } void HistogramDisplayPlot::_resetXAxisPoints(double left, double right) { // Something's wrong with the data (NaN, Inf, or something else) if((left == right) || (left > right)) throw std::runtime_error("HistogramDisplayPlot::_resetXAxisPoints left and/or right values are invalid"); d_left = left *(1 - copysign(0.1, left)); d_right = right*(1 + copysign(0.1, right)); d_width = (d_right - d_left)/(d_bins); for(long loc = 0; loc < d_bins; loc++){ d_xdata[loc] = d_left + loc*d_width; } axisScaleDiv(QwtPlot::xBottom)->setInterval(d_left, d_right); // Set up zoomer base for maximum unzoom x-axis // and reset to maximum unzoom level QwtDoubleRect zbase = d_zoomer->zoomBase(); if(d_semilogx) { setAxisScale(QwtPlot::xBottom, 1e-1, d_right); zbase.setLeft(1e-1); } else { setAxisScale(QwtPlot::xBottom, d_left, d_right); zbase.setLeft(d_left); } zbase.setRight(d_right); d_zoomer->zoom(zbase); d_zoomer->setZoomBase(zbase); d_zoomer->zoom(0); } void HistogramDisplayPlot::_autoScaleY(double bottom, double top) { // Auto scale the y-axis with a margin of 20% (10 dB for log scale) double b = bottom - fabs(bottom)*0.20; double t = top + fabs(top)*0.20; if(d_semilogy) { if(bottom > 0) { setYaxis(b-10, t+10); } else { setYaxis(1e-3, t+10); } } else { setYaxis(b, t); } } void HistogramDisplayPlot::setAutoScaleX() { d_autoscalex_state = true; } void HistogramDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } void HistogramDisplayPlot::setSemilogx(bool en) { d_semilogx = en; if(!d_semilogx) { setAxisScaleEngine(QwtPlot::xBottom, new QwtLinearScaleEngine); } else { setAxisScaleEngine(QwtPlot::xBottom, new QwtLog10ScaleEngine); } } void HistogramDisplayPlot::setSemilogy(bool en) { if(d_semilogy != en) { d_semilogy = en; double max = axisScaleDiv(QwtPlot::yLeft)->upperBound(); if(!d_semilogy) { setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setYaxis(-pow(10.0, max/10.0), pow(10.0, max/10.0)); } else { setAxisScaleEngine(QwtPlot::yLeft, new QwtLog10ScaleEngine); setYaxis(1e-10, 10.0*log10(100*max)); } } } void HistogramDisplayPlot::setAccumulate(bool state) { d_accum = state; } void HistogramDisplayPlot::setMarkerAlpha(int which, int alpha) { if(which < d_nplots) { // Get the pen color QPen pen(d_plot_curve[which]->pen()); QBrush brush(d_plot_curve[which]->brush()); QColor color = brush.color(); // Set new alpha and update pen color.setAlpha(alpha); brush.setColor(color); color.setAlpha(std::min(255, static_cast(alpha*1.5))); pen.setColor(color); d_plot_curve[which]->setBrush(brush); d_plot_curve[which]->setPen(pen); // And set the new color for the markers #if QWT_VERSION < 0x060000 QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); setLineMarker(which, sym.style()); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); if(sym) { sym->setColor(color); sym->setPen(pen); d_plot_curve[which]->setSymbol(sym); } #endif } } int HistogramDisplayPlot::getMarkerAlpha(int which) const { if(which < d_nplots) { return d_plot_curve[which]->brush().color().alpha(); } else { return 0; } } void HistogramDisplayPlot::setLineColor(int which, QColor color) { if(which < d_nplots) { // Adjust color's transparency for the brush color.setAlpha(127 / d_nplots); QBrush brush(d_plot_curve[which]->brush()); brush.setColor(color); d_plot_curve[which]->setBrush(brush); // Adjust color's transparency darker for the pen and markers color.setAlpha(255 / d_nplots); QPen pen(d_plot_curve[which]->pen()); pen.setColor(color); d_plot_curve[which]->setPen(pen); #if QWT_VERSION < 0x060000 d_plot_curve[which]->setPen(pen); QwtSymbol sym = (QwtSymbol)d_plot_curve[which]->symbol(); setLineMarker(which, sym.style()); #else QwtSymbol *sym = (QwtSymbol*)d_plot_curve[which]->symbol(); if(sym) { sym->setColor(color); sym->setPen(pen); d_plot_curve[which]->setSymbol(sym); } #endif } } void HistogramDisplayPlot::setNumBins(int bins) { d_bins = bins; delete [] d_xdata; d_xdata = new double[d_bins]; _resetXAxisPoints(d_left, d_right); for(int i = 0; i < d_nplots; i++) { delete [] d_ydata[i]; d_ydata[i] = new double[d_bins]; memset(d_ydata[i], 0, d_bins*sizeof(double)); #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_bins); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_bins); #endif } } #endif /* HISTOGRAM_DISPLAY_PLOT_C */ gnuradio-3.7.2.1/gr-qtgui/lib/sink_c_impl.h0000664000175000017500000000614012237515112020271 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_SINK_C_IMPL_H #define INCLUDED_QTGUI_SINK_C_IMPL_H #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API sink_c_impl : public sink_c { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); int d_fftsize; filter::firdes::win_type d_wintype; std::vector d_window; double d_center_freq; double d_bandwidth; std::string d_name; gr::high_res_timer_type d_last_update; bool d_update_active; bool d_shift; fft::fft_complex *d_fft; int d_index; gr_complex *d_residbuf; float *d_magbuf; bool d_plotfreq, d_plotwaterfall, d_plottime, d_plotconst; gr::high_res_timer_type d_update_time; int d_argc; char *d_argv; QWidget *d_parent; SpectrumGUIClass *d_main_gui; void windowreset(); void buildwindow(); void fftresize(); void fft(float *data_out, const gr_complex *data_in, int size); public: sink_c_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent); ~sink_c_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_fft_size(const int fftsize); int fft_size() const; void set_frequency_range(const double centerfreq, const double bandwidth); void set_fft_power_db(double min, double max); //void set_time_domain_axis(double min, double max); //void set_constellation_axis(double xmin, double xmax, // double ymin, double ymax); //void set_constellation_pen_size(int size); void set_update_time(double t); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_SINK_C_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/spectrumdisplayform.ui0000664000175000017500000005026112220370373022307 0ustar jcorganjcorgan SpectrumDisplayForm 0 0 712 560 Spectrum Display 0 0 120 16777215 1024 2048 4096 8192 16384 32768 FFT Size: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter false Display RF Frequencies 0 0 Window: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter false 0 0 120 0 120 16777215 9 Hamming Hann Blackman Rectangular Kaiser Blackman-harris 0 Frequency Display 0 1 320 200 1 1 QFrame::NoFrame QFrame::Plain Max Hold false Min Hold false 0 0 25 0 Reset 0 0 62 0 Average Qt::AlignCenter false Reset Qt::Horizontal 100 20 Waterfall Display 130 16777215 Intensity Display: false 50 0 true Qt::ClickFocus true 100 16777215 100 dB false 320 200 QFrame::NoFrame QFrame::Plain 50 0 true true Qt::ClickFocus 100 16777215 -100 dB false 80 16777215 Scales the Intensity to the current data extremes. Auto Scale 100 16777215 Color White Hot Black Hot Incandescent User Defined Time Domain Display 320 200 QFrame::NoFrame QFrame::Plain Constellation Display 320 200 QFrame::StyledPanel QFrame::Raised QwtSlider QWidget
qwt_slider.h
SpectrumTypeTab UseRFFrequenciesCheckBox FFTSizeComboBox WaterfallMaximumIntensitySlider WaterfallMinimumIntensitySlider gnuradio/qtgui/SpectrumGUIClass.h gnuradio/qtgui/FrequencyDisplayPlot.h gnuradio/qtgui/WaterfallDisplayPlot.h gnuradio/qtgui/TimeDomainDisplayPlot.h qvalidator.h vector qwt_slider.h MaxHoldCheckBox toggled(bool) SpectrumDisplayForm maxHoldCheckBox_toggled(bool) 22 324 20 20 MaxHoldResetBtn clicked() SpectrumDisplayForm maxHoldResetBtn_clicked() 107 324 20 20 MinHoldCheckBox toggled(bool) SpectrumDisplayForm minHoldCheckBox_toggled(bool) 22 349 20 20 MinHoldResetBtn clicked() SpectrumDisplayForm minHoldResetBtn_clicked() 107 349 20 20 WindowComboBox activated(int) SpectrumDisplayForm windowTypeChanged(int) 20 20 20 20 UseRFFrequenciesCheckBox toggled(bool) SpectrumDisplayForm useRFFrequenciesCB(bool) 20 20 20 20 WaterfallMaximumIntensitySlider valueChanged(double) SpectrumDisplayForm waterfallMaximumIntensityChangedCB(double) 217 44 20 20 WaterfallMinimumIntensitySlider valueChanged(double) SpectrumDisplayForm waterfallMinimumIntensityChangedCB(double) 217 349 20 20 FFTSizeComboBox activated(QString) SpectrumDisplayForm fftComboBoxSelectedCB(QString) 20 20 20 20 WaterfallAutoScaleBtn clicked() SpectrumDisplayForm waterfallAutoScaleBtnCB() 22 349 20 20 WaterfallIntensityComboBox activated(int) SpectrumDisplayForm waterfallIntensityColorTypeChanged(int) 92 44 20 20 SpectrumTypeTab currentChanged(int) SpectrumDisplayForm tabChanged(int) 314 189 316 217 AvgLineEdit valueChanged(int) SpectrumDisplayForm avgLineEdit_valueChanged(int) 604 421 328 260
gnuradio-3.7.2.1/gr-qtgui/lib/sink_f_impl.cc0000664000175000017500000002013112237515112020426 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "sink_f_impl.h" #include #include #include namespace gr { namespace qtgui { sink_f::sptr sink_f::make(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent) { return gnuradio::get_initial_sptr (new sink_f_impl(fftsize, wintype, fc, bw, name, plotfreq, plotwaterfall, plottime, plotconst, parent)); } sink_f_impl::sink_f_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, bool plotfreq, bool plotwaterfall, bool plottime, bool plotconst, QWidget *parent) : block("sink_f", io_signature::make(1, 1, sizeof(float)), io_signature::make (0, 0, 0)), d_fftsize(fftsize), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_plotfreq(plotfreq), d_plotwaterfall(plotwaterfall), d_plottime(plottime), d_plotconst(plotconst), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex (d_fftsize, true); d_index = 0; d_residbuf = new float[d_fftsize]; d_magbuf = new float[d_fftsize]; buildwindow(); initialize(); } sink_f_impl::~sink_f_impl() { delete d_main_gui; delete [] d_residbuf; delete [] d_magbuf; delete d_fft; delete d_argv; } bool sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == 1; } void sink_f_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } uint64_t maxBufferSize = 32768; d_main_gui = new SpectrumGUIClass(maxBufferSize, d_fftsize, d_center_freq, -d_bandwidth, d_bandwidth); d_main_gui->setDisplayTitle(d_name); d_main_gui->setWindowType((int)d_wintype); set_fft_size(d_fftsize); d_main_gui->openSpectrumWindow(d_parent, d_plotfreq, d_plotwaterfall, d_plottime, d_plotconst); // initialize update time to 10 times a second set_update_time(0.1); } void sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* sink_f_impl::qwidget() { return d_main_gui->qwidget(); } PyObject* sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui->qwidget()); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void sink_f_impl::set_fft_size(const int fftsize) { d_fftsize = fftsize; d_main_gui->setFFTSize(fftsize); } int sink_f_impl::fft_size() const { return d_fftsize; } void sink_f_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->setFrequencyRange(d_center_freq, -d_bandwidth, d_bandwidth); } void sink_f_impl::set_fft_power_db(double min, double max) { d_main_gui->setFrequencyAxis(min, max); } /* void sink_f_impl::set_time_domain_axis(double min, double max) { d_main_gui->setTimeDomainAxis(min, max); } void sink_f_impl::set_constellation_axis(double xmin, double xmax, double ymin, double ymax) { d_main_gui->setConstellationAxis(xmin, xmax, ymin, ymax); } void sink_f_impl::set_constellation_pen_size(int size) { d_main_gui->setConstellationPenSize(size); } */ void sink_f_impl::set_update_time(double t) { d_update_time = t; d_main_gui->setUpdateTime(d_update_time); } void sink_f_impl::fft(float *data_out, const float *data_in, int size) { if (d_window.size()) { gr_complex *dst = d_fft->get_inbuf(); for (int i = 0; i < size; i++) // apply window dst[i] = data_in[i] * d_window[i]; } else { gr_complex *dst = d_fft->get_inbuf(); for (int i = 0; i < size; i++) // float to complex conversion dst[i] = data_in[i]; } d_fft->execute (); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); } void sink_f_impl::windowreset() { filter::firdes::win_type newwintype; newwintype = (filter::firdes::win_type)d_main_gui->getWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void sink_f_impl::buildwindow() { d_window.clear(); if(d_wintype != 0) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void sink_f_impl::fftresize() { int newfftsize = d_main_gui->getFFTSize(); if(newfftsize != d_fftsize) { // Resize residbuf and replace data delete [] d_residbuf; d_residbuf = new float[newfftsize]; delete [] d_magbuf; d_magbuf = new float[newfftsize]; // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex (d_fftsize, true); } } int sink_f_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const float *in = (const float*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; // If we have enough input for one full FFT, do it if(datasize >= resid) { const gr::high_res_timer_type currentTime = gr::high_res_timer_now(); // Fill up residbuf with d_fftsize number of items memcpy(d_residbuf+d_index, &in[j], sizeof(float)*resid); d_index = 0; j += resid; fft(d_magbuf, d_residbuf, d_fftsize); d_main_gui->updateWindow(true, d_magbuf, d_fftsize, (float*)d_residbuf, d_fftsize, NULL, 0, currentTime, true); } // Otherwise, copy what we received into the residbuf for next time else { memcpy(d_residbuf+d_index, &in[j], sizeof(float)*datasize); d_index += datasize; j += datasize; } } consume_each(j); return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/freqdisplayform.cc0000664000175000017500000001027712245466767021401 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include FreqDisplayForm::FreqDisplayForm(int nplots, QWidget* parent) : DisplayForm(nplots, parent) { d_int_validator = new QIntValidator(this); d_int_validator->setBottom(0); d_layout = new QGridLayout(this); d_display_plot = new FrequencyDisplayPlot(nplots, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); d_num_real_data_points = 1024; d_fftsize = 1024; d_fftavg = 1.0; FFTSizeMenu *sizemenu = new FFTSizeMenu(this); FFTAverageMenu *avgmenu = new FFTAverageMenu(this); FFTWindowMenu *winmenu = new FFTWindowMenu(this); d_menu->addMenu(sizemenu); d_menu->addMenu(avgmenu); d_menu->addMenu(winmenu); connect(sizemenu, SIGNAL(whichTrigger(int)), this, SLOT(setFFTSize(const int))); connect(avgmenu, SIGNAL(whichTrigger(float)), this, SLOT(setFFTAverage(const float))); connect(winmenu, SIGNAL(whichTrigger(gr::filter::firdes::win_type)), this, SLOT(setFFTWindowType(const gr::filter::firdes::win_type))); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } FreqDisplayForm::~FreqDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete d_int_validator; } FrequencyDisplayPlot* FreqDisplayForm::getPlot() { return ((FrequencyDisplayPlot*)d_display_plot); } void FreqDisplayForm::newData(const QEvent *updateEvent) { FreqUpdateEvent *fevent = (FreqUpdateEvent*)updateEvent; const std::vector dataPoints = fevent->getPoints(); const uint64_t numDataPoints = fevent->getNumDataPoints(); getPlot()->plotNewData(dataPoints, numDataPoints, 0, 0, 0, d_update_time); } void FreqDisplayForm::customEvent( QEvent * e) { if(e->type() == FreqUpdateEvent::Type()) { newData(e); } } int FreqDisplayForm::getFFTSize() const { return d_fftsize; } float FreqDisplayForm::getFFTAverage() const { return d_fftavg; } gr::filter::firdes::win_type FreqDisplayForm::getFFTWindowType() const { return d_fftwintype; } void FreqDisplayForm::setSampleRate(const QString &samprate) { setFrequencyRange(d_center_freq, samprate.toDouble()); } void FreqDisplayForm::setFFTSize(const int newsize) { d_fftsize = newsize; getPlot()->replot(); } void FreqDisplayForm::setFFTAverage(const float newavg) { d_fftavg = newavg; getPlot()->replot(); } void FreqDisplayForm::setFFTWindowType(const gr::filter::firdes::win_type newwin) { d_fftwintype = newwin; getPlot()->replot(); } void FreqDisplayForm::setFrequencyRange(const double centerfreq, const double bandwidth) { std::string strunits[4] = {"Hz", "kHz", "MHz", "GHz"}; double units10 = floor(log10(bandwidth)); double units3 = std::max(floor(units10 / 3.0), 0.0); double units = pow(10, (units10-fmod(units10, 3.0))); int iunit = static_cast(units3); d_center_freq = centerfreq; d_samp_rate = bandwidth; getPlot()->setFrequencyRange(centerfreq, bandwidth, units, strunits[iunit]); } void FreqDisplayForm::setYaxis(double min, double max) { getPlot()->setYaxis(min, max); } void FreqDisplayForm::autoScale(bool en) { if(en) { d_autoscale_state = true; } else { d_autoscale_state = false; } getPlot()->setAutoScale(d_autoscale_state); getPlot()->replot(); } gnuradio-3.7.2.1/gr-qtgui/lib/time_sink_f_impl.cc0000664000175000017500000004174212237515112021457 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "time_sink_f_impl.h" #include #include #include #include #include #include #include namespace gr { namespace qtgui { time_sink_f::sptr time_sink_f::make(int size, double samp_rate, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new time_sink_f_impl(size, samp_rate, name, nconnections, parent)); } time_sink_f_impl::time_sink_f_impl(int size, double samp_rate, const std::string &name, int nconnections, QWidget *parent) : sync_block("time_sink_f", io_signature::make(nconnections, nconnections, sizeof(float)), io_signature::make(0, 0, 0)), d_size(size), d_buffer_size(2*size), d_samp_rate(samp_rate), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; for(int n = 0; n < d_nconnections; n++) { d_buffers.push_back(fft::malloc_double(d_buffer_size)); memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); } // Set alignment properties for VOLK const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); d_tags = std::vector< std::vector >(d_nconnections); initialize(); d_main_gui->setNPoints(d_size); // setup GUI box with size set_trigger_mode(TRIG_MODE_FREE, TRIG_SLOPE_POS, 0, 0, 0); set_history(2); // so we can look ahead for the trigger slope declare_sample_delay(1); // delay the tags for a history of 2 } time_sink_f_impl::~time_sink_f_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); // d_main_gui is a qwidget destroyed with its parent for(int n = 0; n < d_nconnections; n++) { fft::free(d_buffers[n]); } delete d_argv; } bool time_sink_f_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void time_sink_f_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new TimeDisplayForm(d_nconnections, d_parent); d_main_gui->setNPoints(d_size); d_main_gui->setSampleRate(d_samp_rate); // initialize update time to 10 times a second set_update_time(0.1); } void time_sink_f_impl::exec_() { d_qApplication->exec(); } QWidget* time_sink_f_impl::qwidget() { return d_main_gui; } PyObject* time_sink_f_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void time_sink_f_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void time_sink_f_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void time_sink_f_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void time_sink_f_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void time_sink_f_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void time_sink_f_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void time_sink_f_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void time_sink_f_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void time_sink_f_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void time_sink_f_impl::set_trigger_mode(trigger_mode mode, trigger_slope slope, float level, float delay, int channel, const std::string &tag_key) { gr::thread::scoped_lock lock(d_mutex); d_trigger_mode = mode; d_trigger_slope = slope; d_trigger_level = level; d_trigger_delay = static_cast(delay*d_samp_rate); d_trigger_channel = channel; d_trigger_tag_key = pmt::intern(tag_key); d_triggered = false; d_trigger_count = 0; if((d_trigger_delay < 0) || (d_trigger_delay >= d_size)) { GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%).") \ % (d_trigger_delay/d_samp_rate) % ((d_size-1)/d_samp_rate)); d_trigger_delay = std::max(0, std::min(d_size-1, d_trigger_delay)); delay = d_trigger_delay/d_samp_rate; } d_main_gui->setTriggerMode(d_trigger_mode); d_main_gui->setTriggerSlope(d_trigger_slope); d_main_gui->setTriggerLevel(d_trigger_level); d_main_gui->setTriggerDelay(delay); d_main_gui->setTriggerChannel(d_trigger_channel); d_main_gui->setTriggerTagKey(tag_key); _reset(); } void time_sink_f_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string time_sink_f_impl::title() { return d_main_gui->title().toStdString(); } std::string time_sink_f_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string time_sink_f_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int time_sink_f_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int time_sink_f_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int time_sink_f_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double time_sink_f_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void time_sink_f_impl::set_nsamps(const int newsize) { if(newsize != d_size) { gr::thread::scoped_lock lock(d_mutex); // Set new size and reset buffer index // (throws away any currently held data, but who cares?) d_size = newsize; d_buffer_size = 2*d_size; // Resize buffers and replace data for(int n = 0; n < d_nconnections; n++) { fft::free(d_buffers[n]); d_buffers[n] = fft::malloc_double(d_buffer_size); memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); } // If delay was set beyond the new boundary, pull it back. if(d_trigger_delay >= d_size) { GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%). Moving to 50%% point.") \ % (d_trigger_delay/d_samp_rate) % ((d_size-1)/d_samp_rate)); d_trigger_delay = d_size-1; d_main_gui->setTriggerDelay(d_trigger_delay/d_samp_rate); } d_main_gui->setNPoints(d_size); _reset(); } } void time_sink_f_impl::set_samp_rate(const double samp_rate) { gr::thread::scoped_lock lock(d_mutex); d_samp_rate = samp_rate; d_main_gui->setSampleRate(d_samp_rate); } int time_sink_f_impl::nsamps() const { return d_size; } void time_sink_f_impl::enable_stem_plot(bool en) { d_main_gui->setStem(en); } void time_sink_f_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void time_sink_f_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void time_sink_f_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void time_sink_f_impl::enable_semilogx(bool en) { d_main_gui->setSemilogx(en); } void time_sink_f_impl::enable_semilogy(bool en) { d_main_gui->setSemilogy(en); } void time_sink_f_impl::enable_tags(int which, bool en) { if(which == -1) { for(int n = 0; n < d_nconnections; n++) { d_main_gui->setTagMenu(n, en); } } else d_main_gui->setTagMenu(which, en); } void time_sink_f_impl::reset() { gr::thread::scoped_lock lock(d_mutex); _reset(); } void time_sink_f_impl::_reset() { // Move the tail of the buffers to the front. This section // represents data that might have to be plotted again if a // trigger occurs and we have a trigger delay set. The tail // section is between (d_end-d_trigger_delay) and d_end. int n; if(d_trigger_delay) { for(n = 0; n < d_nconnections; n++) { memmove(d_buffers[n], &d_buffers[n][d_size-d_trigger_delay], d_trigger_delay*sizeof(double)); } // Also move the offsets of any tags that occur in the tail // section so they would be plotted again, too. for(n = 0; n < d_nconnections; n++) { std::vector tmp_tags; for(size_t t = 0; t < d_tags[n].size(); t++) { if(d_tags[n][t].offset > (uint64_t)(d_size - d_trigger_delay)) { d_tags[n][t].offset = d_tags[n][t].offset - (d_size - d_trigger_delay); tmp_tags.push_back(d_tags[n][t]); } } d_tags[n] = tmp_tags; } } // Otherwise, just clear the local list of tags. else { for(n = 0; n < d_nconnections; n++) { d_tags[n].clear(); } } // Reset the start and end indices. d_start = 0; d_end = d_size; // Reset the trigger. If in free running mode, ignore the // trigger delay and always set trigger to true. if(d_trigger_mode == TRIG_MODE_FREE) { d_index = 0; d_triggered = true; } else { d_index = d_trigger_delay; d_triggered = false; } } void time_sink_f_impl::_npoints_resize() { int newsize = d_main_gui->getNPoints(); set_nsamps(newsize); } void time_sink_f_impl::_adjust_tags(int adj) { for(size_t n = 0; n < d_tags.size(); n++) { for(size_t t = 0; t < d_tags[n].size(); t++) { d_tags[n][t].offset += adj; } } } void time_sink_f_impl::_gui_update_trigger() { d_trigger_mode = d_main_gui->getTriggerMode(); d_trigger_slope = d_main_gui->getTriggerSlope(); d_trigger_level = d_main_gui->getTriggerLevel(); d_trigger_channel = d_main_gui->getTriggerChannel(); d_trigger_count = 0; float delayf = d_main_gui->getTriggerDelay(); int delay = static_cast(delayf*d_samp_rate); if(delay != d_trigger_delay) { // We restrict the delay to be within the window of time being // plotted. if((delay < 0) || (delay >= d_size)) { GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%).") \ % (delay/d_samp_rate) % ((d_size-1)/d_samp_rate)); delay = std::max(0, std::min(d_size-1, delay)); delayf = delay/d_samp_rate; } d_trigger_delay = delay; d_main_gui->setTriggerDelay(delayf); _reset(); } std::string tagkey = d_main_gui->getTriggerTagKey(); d_trigger_tag_key = pmt::intern(tagkey); } void time_sink_f_impl::_test_trigger_tags(int nitems) { int trigger_index; uint64_t nr = nitems_read(d_trigger_channel); std::vector tags; get_tags_in_range(tags, d_trigger_channel, nr, nr + nitems, d_trigger_tag_key); if(tags.size() > 0) { d_triggered = true; trigger_index = tags[0].offset - nr; d_start = d_index + trigger_index - d_trigger_delay - 1; d_end = d_start + d_size; d_trigger_count = 0; _adjust_tags(-d_start); } } void time_sink_f_impl::_test_trigger_norm(int nitems, gr_vector_const_void_star inputs) { int trigger_index; const float *in = (const float*)inputs[d_trigger_channel]; for(trigger_index = 0; trigger_index < nitems; trigger_index++) { d_trigger_count++; // Test if trigger has occurred based on the input stream, // channel number, and slope direction if(_test_trigger_slope(&in[trigger_index])) { d_triggered = true; d_start = d_index + trigger_index - d_trigger_delay; d_end = d_start + d_size; d_trigger_count = 0; _adjust_tags(-d_start); break; } } // If using auto trigger mode, trigger periodically even // without a trigger event. if((d_trigger_mode == TRIG_MODE_AUTO) && (d_trigger_count > d_size)) { d_triggered = true; d_trigger_count = 0; } } bool time_sink_f_impl::_test_trigger_slope(const float *in) const { float x0, x1; x0 = in[0]; x1 = in[1]; if(d_trigger_slope == TRIG_SLOPE_POS) return ((x0 <= d_trigger_level) && (x1 > d_trigger_level)); else return ((x0 >= d_trigger_level) && (x1 < d_trigger_level)); } int time_sink_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, idx=0; const float *in; _npoints_resize(); _gui_update_trigger(); gr::thread::scoped_lock lock(d_mutex); int nfill = d_end - d_index; // how much room left in buffers int nitems = std::min(noutput_items, nfill); // num items we can put in buffers // If auto, normal, or tag trigger, look for the trigger if((d_trigger_mode != TRIG_MODE_FREE) && !d_triggered) { // trigger off a tag key (first one found) if(d_trigger_mode == TRIG_MODE_TAG) { _test_trigger_tags(nitems); } // Normal or Auto trigger else { _test_trigger_norm(nitems, input_items); } } // Copy data into the buffers. for(n = 0; n < d_nconnections; n++) { in = (const float*)input_items[idx]; volk_32f_convert_64f(&d_buffers[n][d_index], &in[0], nitems); uint64_t nr = nitems_read(idx); std::vector tags; get_tags_in_range(tags, idx, nr, nr + nitems); for(size_t t = 0; t < tags.size(); t++) { tags[t].offset = tags[t].offset - nr + (d_index-d_start); } d_tags[idx].insert(d_tags[idx].end(), tags.begin(), tags.end()); idx++; } d_index += nitems; // If we've have a trigger and a full d_size of items in the buffers, plot. if((d_triggered) && (d_index == d_end)) { // Copy data to be plotted to start of buffers. for(n = 0; n < d_nconnections; n++) { memmove(d_buffers[n], &d_buffers[n][d_start], d_size*sizeof(double)); } // Plot if we are able to update if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new TimeUpdateEvent(d_buffers, d_size, d_tags)); } // We've plotting, so reset the state _reset(); } // If we've filled up the buffers but haven't triggered, reset. if(d_index == d_end) { _reset(); } return nitems; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/time_sink_c_impl.cc0000664000175000017500000004226412237515112021454 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "time_sink_c_impl.h" #include #include #include #include #include namespace gr { namespace qtgui { time_sink_c::sptr time_sink_c::make(int size, double samp_rate, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new time_sink_c_impl(size, samp_rate, name, nconnections, parent)); } time_sink_c_impl::time_sink_c_impl(int size, double samp_rate, const std::string &name, int nconnections, QWidget *parent) : sync_block("time_sink_c", io_signature::make(nconnections, nconnections, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_size(size), d_buffer_size(2*size), d_samp_rate(samp_rate), d_name(name), d_nconnections(2*nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; for(int n = 0; n < d_nconnections; n++) { d_buffers.push_back(fft::malloc_double(d_buffer_size)); memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); } // Set alignment properties for VOLK const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); d_tags = std::vector< std::vector >(d_nconnections/2); initialize(); d_main_gui->setNPoints(d_size); // setup GUI box with size set_trigger_mode(TRIG_MODE_FREE, TRIG_SLOPE_POS, 0, 0, 0); set_history(2); // so we can look ahead for the trigger slope declare_sample_delay(1); // delay the tags for a history of 2 } time_sink_c_impl::~time_sink_c_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); // d_main_gui is a qwidget destroyed with its parent for(int n = 0; n < d_nconnections; n++) { fft::free(d_buffers[n]); } delete d_argv; } bool time_sink_c_impl::check_topology(int ninputs, int noutputs) { return 2*ninputs == d_nconnections; } void time_sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new TimeDisplayForm(d_nconnections, d_parent); d_main_gui->setNPoints(d_size); d_main_gui->setSampleRate(d_samp_rate); // initialize update time to 10 times a second set_update_time(0.1); } void time_sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* time_sink_c_impl::qwidget() { return d_main_gui; } PyObject* time_sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void time_sink_c_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void time_sink_c_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void time_sink_c_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void time_sink_c_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void time_sink_c_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void time_sink_c_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void time_sink_c_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void time_sink_c_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void time_sink_c_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void time_sink_c_impl::set_trigger_mode(trigger_mode mode, trigger_slope slope, float level, float delay, int channel, const std::string &tag_key) { gr::thread::scoped_lock lock(d_mutex); d_trigger_mode = mode; d_trigger_slope = slope; d_trigger_level = level; d_trigger_delay = static_cast(delay*d_samp_rate); d_trigger_channel = channel; d_trigger_tag_key = pmt::intern(tag_key); d_triggered = false; d_trigger_count = 0; if((d_trigger_delay < 0) || (d_trigger_delay >= d_size)) { GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%).") \ % (d_trigger_delay/d_samp_rate) % ((d_size-1)/d_samp_rate)); d_trigger_delay = std::max(0, std::min(d_size-1, d_trigger_delay)); delay = d_trigger_delay/d_samp_rate; } d_main_gui->setTriggerMode(d_trigger_mode); d_main_gui->setTriggerSlope(d_trigger_slope); d_main_gui->setTriggerLevel(d_trigger_level); d_main_gui->setTriggerDelay(delay); d_main_gui->setTriggerChannel(d_trigger_channel); d_main_gui->setTriggerTagKey(tag_key); _reset(); } void time_sink_c_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string time_sink_c_impl::title() { return d_main_gui->title().toStdString(); } std::string time_sink_c_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string time_sink_c_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int time_sink_c_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int time_sink_c_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int time_sink_c_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double time_sink_c_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void time_sink_c_impl::set_nsamps(const int newsize) { if(newsize != d_size) { gr::thread::scoped_lock lock(d_mutex); // Set new size and reset buffer index // (throws away any currently held data, but who cares?) d_size = newsize; d_buffer_size = 2*d_size; // Resize buffers and replace data for(int n = 0; n < d_nconnections; n++) { fft::free(d_buffers[n]); d_buffers[n] = fft::malloc_double(d_buffer_size); memset(d_buffers[n], 0, d_buffer_size*sizeof(double)); } // If delay was set beyond the new boundary, pull it back. if(d_trigger_delay >= d_size) { GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%). Moving to 50%% point.") \ % (d_trigger_delay/d_samp_rate) % ((d_size-1)/d_samp_rate)); d_trigger_delay = d_size/2; d_main_gui->setTriggerDelay(d_trigger_delay/d_samp_rate); } d_main_gui->setNPoints(d_size); _reset(); } } void time_sink_c_impl::set_samp_rate(const double samp_rate) { gr::thread::scoped_lock lock(d_mutex); d_samp_rate = samp_rate; d_main_gui->setSampleRate(d_samp_rate); } int time_sink_c_impl::nsamps() const { return d_size; } void time_sink_c_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void time_sink_c_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void time_sink_c_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void time_sink_c_impl::enable_stem_plot(bool en) { d_main_gui->setStem(en); } void time_sink_c_impl::enable_semilogx(bool en) { d_main_gui->setSemilogx(en); } void time_sink_c_impl::enable_semilogy(bool en) { d_main_gui->setSemilogy(en); } void time_sink_c_impl::enable_tags(int which, bool en) { if(which == -1) { for(int n = 0; n < d_nconnections; n++) { d_main_gui->setTagMenu(n, en); } } else d_main_gui->setTagMenu(which, en); } void time_sink_c_impl::reset() { gr::thread::scoped_lock lock(d_mutex); _reset(); } void time_sink_c_impl::_reset() { // Move the tail of the buffers to the front. This section // represents data that might have to be plotted again if a // trigger occurs and we have a trigger delay set. The tail // section is between (d_end-d_trigger_delay) and d_end. int n; if(d_trigger_delay) { for(n = 0; n < d_nconnections; n++) { memmove(d_buffers[n], &d_buffers[n][d_size-d_trigger_delay], d_trigger_delay*sizeof(double)); } // Also move the offsets of any tags that occur in the tail // section so they would be plotted again, too. for(n = 0; n < d_nconnections/2; n++) { std::vector tmp_tags; for(size_t t = 0; t < d_tags[n].size(); t++) { if(d_tags[n][t].offset > (uint64_t)(d_size - d_trigger_delay)) { d_tags[n][t].offset = d_tags[n][t].offset - (d_size - d_trigger_delay); tmp_tags.push_back(d_tags[n][t]); } } d_tags[n] = tmp_tags; } } // Otherwise, just clear the local list of tags. else { for(n = 0; n < d_nconnections/2; n++) { d_tags[n].clear(); } } // Reset the start and end indices. d_start = 0; d_end = d_size; // Reset the trigger. If in free running mode, ignore the // trigger delay and always set trigger to true. if(d_trigger_mode == TRIG_MODE_FREE) { d_index = 0; d_triggered = true; } else { d_index = d_trigger_delay; d_triggered = false; } } void time_sink_c_impl::_npoints_resize() { int newsize = d_main_gui->getNPoints(); set_nsamps(newsize); } void time_sink_c_impl::_adjust_tags(int adj) { for(size_t n = 0; n < d_tags.size(); n++) { for(size_t t = 0; t < d_tags[n].size(); t++) { d_tags[n][t].offset += adj; } } } void time_sink_c_impl::_gui_update_trigger() { d_trigger_mode = d_main_gui->getTriggerMode(); d_trigger_slope = d_main_gui->getTriggerSlope(); d_trigger_level = d_main_gui->getTriggerLevel(); d_trigger_channel = d_main_gui->getTriggerChannel(); d_trigger_count = 0; float delayf = d_main_gui->getTriggerDelay(); int delay = static_cast(delayf*d_samp_rate); if(delay != d_trigger_delay) { // We restrict the delay to be within the window of time being // plotted. if((delay < 0) || (delay >= d_size)) { GR_LOG_WARN(d_logger, boost::format("Trigger delay (%1%) outside of display range (0:%2%).") \ % (delay/d_samp_rate) % ((d_size-1)/d_samp_rate)); delay = std::max(0, std::min(d_size-1, delay)); delayf = delay/d_samp_rate; } d_trigger_delay = delay; d_main_gui->setTriggerDelay(delayf); _reset(); } std::string tagkey = d_main_gui->getTriggerTagKey(); d_trigger_tag_key = pmt::intern(tagkey); } void time_sink_c_impl::_test_trigger_tags(int nitems) { int trigger_index; uint64_t nr = nitems_read(d_trigger_channel/2); std::vector tags; get_tags_in_range(tags, d_trigger_channel/2, nr, nr + nitems, d_trigger_tag_key); if(tags.size() > 0) { d_triggered = true; trigger_index = tags[0].offset - nr; d_start = d_index + trigger_index - d_trigger_delay - 1; d_end = d_start + d_size; d_trigger_count = 0; _adjust_tags(-d_start); } } void time_sink_c_impl::_test_trigger_norm(int nitems, gr_vector_const_void_star inputs) { int trigger_index; const gr_complex *in = (const gr_complex*)inputs[d_trigger_channel/2]; for(trigger_index = 0; trigger_index < nitems; trigger_index++) { d_trigger_count++; // Test if trigger has occurred based on the input stream, // channel number, and slope direction if(_test_trigger_slope(&in[trigger_index])) { d_triggered = true; d_start = d_index + trigger_index - d_trigger_delay; d_end = d_start + d_size; d_trigger_count = 0; _adjust_tags(-d_start); break; } } // If using auto trigger mode, trigger periodically even // without a trigger event. if((d_trigger_mode == TRIG_MODE_AUTO) && (d_trigger_count > d_size)) { d_triggered = true; d_trigger_count = 0; } } bool time_sink_c_impl::_test_trigger_slope(const gr_complex *in) const { float x0, x1; if(d_trigger_channel % 2 == 0) { x0 = in[0].real(); x1 = in[1].real(); } else { x0 = in[0].imag(); x1 = in[1].imag(); } if(d_trigger_slope == TRIG_SLOPE_POS) return ((x0 <= d_trigger_level) && (x1 > d_trigger_level)); else return ((x0 >= d_trigger_level) && (x1 < d_trigger_level)); } int time_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, idx=0; const gr_complex *in; _npoints_resize(); _gui_update_trigger(); gr::thread::scoped_lock lock(d_mutex); int nfill = d_end - d_index; // how much room left in buffers int nitems = std::min(noutput_items, nfill); // num items we can put in buffers // If auto, normal, or tag trigger, look for the trigger if((d_trigger_mode != TRIG_MODE_FREE) && !d_triggered) { // trigger off a tag key (first one found) if(d_trigger_mode == TRIG_MODE_TAG) { _test_trigger_tags(nitems); } // Normal or Auto trigger else { _test_trigger_norm(nitems, input_items); } } // Copy data into the buffers. for(n = 0; n < d_nconnections; n+=2) { in = (const gr_complex*)input_items[idx]; volk_32fc_deinterleave_64f_x2(&d_buffers[n][d_index], &d_buffers[n+1][d_index], &in[0], nitems); uint64_t nr = nitems_read(idx); std::vector tags; get_tags_in_range(tags, idx, nr, nr + nitems); for(size_t t = 0; t < tags.size(); t++) { tags[t].offset = tags[t].offset - nr + (d_index-d_start); } d_tags[idx].insert(d_tags[idx].end(), tags.begin(), tags.end()); idx++; } d_index += nitems; // If we've have a trigger and a full d_size of items in the buffers, plot. if((d_triggered) && (d_index == d_end)) { // Copy data to be plotted to start of buffers. for(n = 0; n < d_nconnections; n++) { memmove(d_buffers[n], &d_buffers[n][d_start], d_size*sizeof(double)); } // Plot if we are able to update if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new TimeUpdateEvent(d_buffers, d_size, d_tags)); } // We've plotting, so reset the state _reset(); } // If we've filled up the buffers but haven't triggered, reset. if(d_index == d_end) { _reset(); } return nitems; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/plot_raster.cc0000664000175000017500000002016612207440367020510 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include "qwt_painter.h" #include "qwt_scale_map.h" #include "qwt_color_map.h" #include #if QWT_VERSION < 0x060000 #include "qwt_double_interval.h" #endif typedef QVector QwtColorTable; class PlotTimeRasterImage: public QImage { // This class hides some Qt3/Qt4 API differences public: PlotTimeRasterImage(const QSize &size, QwtColorMap::Format format): QImage(size, format == QwtColorMap::RGB ? QImage::Format_ARGB32 : QImage::Format_Indexed8 ) { } PlotTimeRasterImage(const QImage &other): QImage(other) { } void initColorTable(const QImage& other) { setColorTable(other.colorTable()); } }; class PlotTimeRaster::PrivateData { public: PrivateData() { data = NULL; colorMap = new QwtLinearColorMap(); } ~PrivateData() { delete colorMap; } TimeRasterData *data; QwtColorMap *colorMap; }; /*! Sets the following item attributes: - QwtPlotItem::AutoScale: true - QwtPlotItem::Legend: false The z value is initialized to 8.0. \param title Title \sa QwtPlotItem::setItemAttribute(), QwtPlotItem::setZ() */ PlotTimeRaster::PlotTimeRaster(const QString &title) : QwtPlotRasterItem(title) { d_data = new PrivateData(); setItemAttribute(QwtPlotItem::AutoScale, true); setItemAttribute(QwtPlotItem::Legend, false); setZ(1.0); } //! Destructor PlotTimeRaster::~PlotTimeRaster() { delete d_data; } const TimeRasterData* PlotTimeRaster::data()const { return d_data->data; } void PlotTimeRaster::setData(TimeRasterData *data) { d_data->data = data; } //! \return QwtPlotItem::Rtti_PlotSpectrogram int PlotTimeRaster::rtti() const { return QwtPlotItem::Rtti_PlotGrid; } /*! Change the color map Often it is useful to display the mapping between intensities and colors as an additional plot axis, showing a color bar. \param map Color Map \sa colorMap(), QwtScaleWidget::setColorBarEnabled(), QwtScaleWidget::setColorMap() */ void PlotTimeRaster::setColorMap(const QwtColorMap *map) { delete d_data->colorMap; d_data->colorMap = (QwtColorMap*)map; invalidateCache(); itemChanged(); } /*! \return Color Map used for mapping the intensity values to colors \sa setColorMap() */ const QwtColorMap &PlotTimeRaster::colorMap() const { return *d_data->colorMap; } /*! \return Bounding rect of the data \sa QwtRasterData::boundingRect */ #if QWT_VERSION < 0x060000 QwtDoubleRect PlotTimeRaster::boundingRect() const { return d_data->data->boundingRect(); } #endif /*! \brief Returns the recommended raster for a given rect. F.e the raster hint is used to limit the resolution of the image that is rendered. \param rect Rect for the raster hint \return data().rasterHint(rect) */ #if QWT_VERSION < 0x060000 QSize PlotTimeRaster::rasterHint(const QwtDoubleRect &rect) const { return d_data->data->rasterHint(rect); } #endif /*! \brief Render an image from the data and color map. The area is translated into a rect of the paint device. For each pixel of this rect the intensity is mapped into a color. \param xMap X-Scale Map \param yMap Y-Scale Map \param area Area that should be rendered in scale coordinates. \return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending on the color map. \sa QwtRasterData::intensity(), QwtColorMap::rgb(), QwtColorMap::colorIndex() */ #if QWT_VERSION < 0x060000 QImage PlotTimeRaster::renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtDoubleRect &area) const #else QImage PlotTimeRaster::renderImage(const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &area, const QSize &size) const #endif { if(area.isEmpty()) return QImage(); #if QWT_VERSION < 0x060000 QRect rect = transform(xMap, yMap, area); const QSize res = d_data->data->rasterHint(area); #else QRect rect = QwtScaleMap::transform(xMap, yMap, area).toRect(); const QSize res(-1,-1); #endif QwtScaleMap xxMap = xMap; QwtScaleMap yyMap = yMap; if(res.isValid()) { /* It is useless to render an image with a higher resolution than the data offers. Of course someone will have to scale this image later into the size of the given rect, but f.e. in case of postscript this will done on the printer. */ rect.setSize(rect.size().boundedTo(res)); int px1 = rect.x(); int px2 = rect.x() + rect.width(); if(xMap.p1() > xMap.p2()) qSwap(px1, px2); double sx1 = area.x(); double sx2 = area.x() + area.width(); if(xMap.s1() > xMap.s2()) qSwap(sx1, sx2); int py1 = rect.y(); int py2 = rect.y() + rect.height(); if(yMap.p1() > yMap.p2()) qSwap(py1, py2); double sy1 = area.y(); double sy2 = area.y() + area.height(); if(yMap.s1() > yMap.s2()) qSwap(sy1, sy2); xxMap.setPaintInterval(px1, px2); xxMap.setScaleInterval(sx1, sx2); yyMap.setPaintInterval(py1, py2); yyMap.setScaleInterval(sy1, sy2); } PlotTimeRasterImage image(rect.size(), d_data->colorMap->format()); #if QWT_VERSION < 0x060000 const QwtDoubleInterval intensityRange = d_data->data->range(); #else const QwtInterval intensityRange = d_data->data->interval(Qt::ZAxis); #endif if(!intensityRange.isValid()) return image; d_data->data->initRaster(area, rect.size()); if(d_data->colorMap->format() == QwtColorMap::RGB) { for(int y = rect.top(); y <= rect.bottom(); y++) { const double ty = yyMap.invTransform(y); QRgb *line = (QRgb *)image.scanLine(y - rect.top()); for(int x = rect.left(); x <= rect.right(); x++) { const double tx = xxMap.invTransform(x); *line++ = d_data->colorMap->rgb(intensityRange, d_data->data->value(tx, ty)); } } d_data->data->incrementResidual(); } else if(d_data->colorMap->format() == QwtColorMap::Indexed) { image.setColorTable(d_data->colorMap->colorTable(intensityRange)); for(int y = rect.top(); y <= rect.bottom(); y++) { const double ty = yyMap.invTransform(y); unsigned char *line = image.scanLine(y - rect.top()); for(int x = rect.left(); x <= rect.right(); x++) { const double tx = xxMap.invTransform(x); *line++ = d_data->colorMap->colorIndex(intensityRange, d_data->data->value(tx, ty)); } } } d_data->data->discardRaster(); // Mirror the image in case of inverted maps const bool hInvert = xxMap.p1() > xxMap.p2(); const bool vInvert = yyMap.p1() > yyMap.p2(); if(hInvert || vInvert) { image = image.mirrored(hInvert, vInvert); } return image; } #if QWT_VERSION < 0x060000 QwtDoubleInterval PlotTimeRaster::interval(Qt::Axis ax) const { return d_data->data->range(); } #else QwtInterval PlotTimeRaster::interval(Qt::Axis ax) const { return d_data->data->interval(ax); } #endif /*! \brief Draw the raster \param painter Painter \param xMap Maps x-values into pixel coordinates. \param yMap Maps y-values into pixel coordinates. \param canvasRect Contents rect of the canvas in painter coordinates \sa setDisplayMode, renderImage, QwtPlotRasterItem::draw, drawContourLines */ void PlotTimeRaster::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &canvasRect) const { QwtPlotRasterItem::draw(painter, xMap, yMap, canvasRect); } gnuradio-3.7.2.1/gr-qtgui/lib/spectrumUpdateEvents.cc0000664000175000017500000002566112237515112022343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef SPECTRUM_UPDATE_EVENTS_C #define SPECTRUM_UPDATE_EVENTS_C #include SpectrumUpdateEvent::SpectrumUpdateEvent(const float* fftPoints, const uint64_t numFFTDataPoints, const double* realTimeDomainPoints, const double* imagTimeDomainPoints, const uint64_t numTimeDomainDataPoints, const gr::high_res_timer_type dataTimestamp, const bool repeatDataFlag, const bool lastOfMultipleUpdateFlag, const gr::high_res_timer_type generatedTimestamp, const int droppedFFTFrames) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(numFFTDataPoints < 1) { _numFFTDataPoints = 1; } else { _numFFTDataPoints = numFFTDataPoints; } if(numTimeDomainDataPoints < 1) { _numTimeDomainDataPoints = 1; } else { _numTimeDomainDataPoints = numTimeDomainDataPoints; } _fftPoints = new float[_numFFTDataPoints]; _fftPoints[0] = 0; memcpy(_fftPoints, fftPoints, numFFTDataPoints*sizeof(float)); _realDataTimeDomainPoints = new double[_numTimeDomainDataPoints]; memset(_realDataTimeDomainPoints, 0x0, _numTimeDomainDataPoints*sizeof(double)); if(numTimeDomainDataPoints > 0) { memcpy(_realDataTimeDomainPoints, realTimeDomainPoints, numTimeDomainDataPoints*sizeof(double)); } _imagDataTimeDomainPoints = new double[_numTimeDomainDataPoints]; memset(_imagDataTimeDomainPoints, 0x0, _numTimeDomainDataPoints*sizeof(double)); if(numTimeDomainDataPoints > 0) { memcpy(_imagDataTimeDomainPoints, imagTimeDomainPoints, numTimeDomainDataPoints*sizeof(double)); } _dataTimestamp = dataTimestamp; _repeatDataFlag = repeatDataFlag; _lastOfMultipleUpdateFlag = lastOfMultipleUpdateFlag; _eventGeneratedTimestamp = generatedTimestamp; _droppedFFTFrames = droppedFFTFrames; } SpectrumUpdateEvent::~SpectrumUpdateEvent() { delete[] _fftPoints; delete[] _realDataTimeDomainPoints; delete[] _imagDataTimeDomainPoints; } const float* SpectrumUpdateEvent::getFFTPoints() const { return _fftPoints; } const double* SpectrumUpdateEvent::getRealTimeDomainPoints() const { return _realDataTimeDomainPoints; } const double* SpectrumUpdateEvent::getImagTimeDomainPoints() const { return _imagDataTimeDomainPoints; } uint64_t SpectrumUpdateEvent::getNumFFTDataPoints() const { return _numFFTDataPoints; } uint64_t SpectrumUpdateEvent::getNumTimeDomainDataPoints() const { return _numTimeDomainDataPoints; } gr::high_res_timer_type SpectrumUpdateEvent::getDataTimestamp() const { return _dataTimestamp; } bool SpectrumUpdateEvent::getRepeatDataFlag() const { return _repeatDataFlag; } bool SpectrumUpdateEvent::getLastOfMultipleUpdateFlag() const { return _lastOfMultipleUpdateFlag; } gr::high_res_timer_type SpectrumUpdateEvent::getEventGeneratedTimestamp() const { return _eventGeneratedTimestamp; } int SpectrumUpdateEvent::getDroppedFFTFrames() const { return _droppedFFTFrames; } SpectrumWindowCaptionEvent::SpectrumWindowCaptionEvent(const QString& newLbl) : QEvent(QEvent::Type(SpectrumWindowCaptionEventType)) { _labelString = newLbl; } SpectrumWindowCaptionEvent::~SpectrumWindowCaptionEvent() { } QString SpectrumWindowCaptionEvent::getLabel() { return _labelString; } SpectrumWindowResetEvent::SpectrumWindowResetEvent() : QEvent(QEvent::Type(SpectrumWindowResetEventType)) { } SpectrumWindowResetEvent::~SpectrumWindowResetEvent() { } SpectrumFrequencyRangeEvent::SpectrumFrequencyRangeEvent(const double centerFreq, const double startFreq, const double stopFreq) : QEvent(QEvent::Type(SpectrumFrequencyRangeEventType)) { _centerFrequency = centerFreq; _startFrequency = startFreq; _stopFrequency = stopFreq; } SpectrumFrequencyRangeEvent::~SpectrumFrequencyRangeEvent() { } double SpectrumFrequencyRangeEvent::GetCenterFrequency() const { return _centerFrequency; } double SpectrumFrequencyRangeEvent::GetStartFrequency() const { return _startFrequency; } double SpectrumFrequencyRangeEvent::GetStopFrequency() const { return _stopFrequency; } /***************************************************************************/ TimeUpdateEvent::TimeUpdateEvent(const std::vector timeDomainPoints, const uint64_t numTimeDomainDataPoints, const std::vector< std::vector > tags) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(numTimeDomainDataPoints < 1) { _numTimeDomainDataPoints = 1; } else { _numTimeDomainDataPoints = numTimeDomainDataPoints; } _nplots = timeDomainPoints.size(); for(size_t i = 0; i < _nplots; i++) { _dataTimeDomainPoints.push_back(new double[_numTimeDomainDataPoints]); if(numTimeDomainDataPoints > 0) { memcpy(_dataTimeDomainPoints[i], timeDomainPoints[i], _numTimeDomainDataPoints*sizeof(double)); } } _tags = tags; } TimeUpdateEvent::~TimeUpdateEvent() { for(size_t i = 0; i < _nplots; i++) { delete[] _dataTimeDomainPoints[i]; } } const std::vector TimeUpdateEvent::getTimeDomainPoints() const { return _dataTimeDomainPoints; } uint64_t TimeUpdateEvent::getNumTimeDomainDataPoints() const { return _numTimeDomainDataPoints; } const std::vector< std::vector > TimeUpdateEvent::getTags() const { return _tags; } /***************************************************************************/ FreqUpdateEvent::FreqUpdateEvent(const std::vector dataPoints, const uint64_t numDataPoints) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(numDataPoints < 1) { _numDataPoints = 1; } else { _numDataPoints = numDataPoints; } _nplots = dataPoints.size(); for(size_t i = 0; i < _nplots; i++) { _dataPoints.push_back(new double[_numDataPoints]); if(numDataPoints > 0) { memcpy(_dataPoints[i], dataPoints[i], _numDataPoints*sizeof(double)); } } } FreqUpdateEvent::~FreqUpdateEvent() { for(size_t i = 0; i < _nplots; i++) { delete[] _dataPoints[i]; } } const std::vector FreqUpdateEvent::getPoints() const { return _dataPoints; } uint64_t FreqUpdateEvent::getNumDataPoints() const { return _numDataPoints; } /***************************************************************************/ ConstUpdateEvent::ConstUpdateEvent(const std::vector realDataPoints, const std::vector imagDataPoints, const uint64_t numDataPoints) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(numDataPoints < 1) { _numDataPoints = 1; } else { _numDataPoints = numDataPoints; } _nplots = realDataPoints.size(); for(size_t i = 0; i < _nplots; i++) { _realDataPoints.push_back(new double[_numDataPoints]); _imagDataPoints.push_back(new double[_numDataPoints]); if(numDataPoints > 0) { memcpy(_realDataPoints[i], realDataPoints[i], _numDataPoints*sizeof(double)); memcpy(_imagDataPoints[i], imagDataPoints[i], _numDataPoints*sizeof(double)); } } } ConstUpdateEvent::~ConstUpdateEvent() { for(size_t i = 0; i < _nplots; i++) { delete[] _realDataPoints[i]; delete[] _imagDataPoints[i]; } } const std::vector ConstUpdateEvent::getRealPoints() const { return _realDataPoints; } const std::vector ConstUpdateEvent::getImagPoints() const { return _imagDataPoints; } uint64_t ConstUpdateEvent::getNumDataPoints() const { return _numDataPoints; } /***************************************************************************/ WaterfallUpdateEvent::WaterfallUpdateEvent(const std::vector dataPoints, const uint64_t numDataPoints, const gr::high_res_timer_type dataTimestamp) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(numDataPoints < 1) { _numDataPoints = 1; } else { _numDataPoints = numDataPoints; } _nplots = dataPoints.size(); for(size_t i = 0; i < _nplots; i++) { _dataPoints.push_back(new double[_numDataPoints]); if(numDataPoints > 0) { memcpy(_dataPoints[i], dataPoints[i], _numDataPoints*sizeof(double)); } } _dataTimestamp = dataTimestamp; } WaterfallUpdateEvent::~WaterfallUpdateEvent() { for(size_t i = 0; i < _nplots; i++) { delete[] _dataPoints[i]; } } const std::vector WaterfallUpdateEvent::getPoints() const { return _dataPoints; } uint64_t WaterfallUpdateEvent::getNumDataPoints() const { return _numDataPoints; } gr::high_res_timer_type WaterfallUpdateEvent::getDataTimestamp() const { return _dataTimestamp; } /***************************************************************************/ TimeRasterUpdateEvent::TimeRasterUpdateEvent(const std::vector dataPoints, const uint64_t numDataPoints) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(numDataPoints < 1) { _numDataPoints = 1; } else { _numDataPoints = numDataPoints; } _nplots = dataPoints.size(); for(size_t i = 0; i < _nplots; i++) { _dataPoints.push_back(new double[_numDataPoints]); if(numDataPoints > 0) { memcpy(_dataPoints[i], dataPoints[i], _numDataPoints*sizeof(double)); } } } TimeRasterUpdateEvent::~TimeRasterUpdateEvent() { for(size_t i = 0; i < _nplots; i++) { delete[] _dataPoints[i]; } } const std::vector TimeRasterUpdateEvent::getPoints() const { return _dataPoints; } uint64_t TimeRasterUpdateEvent::getNumDataPoints() const { return _numDataPoints; } /***************************************************************************/ HistogramUpdateEvent::HistogramUpdateEvent(const std::vector points, const uint64_t npoints) : QEvent(QEvent::Type(SpectrumUpdateEventType)) { if(npoints < 1) { _npoints = 1; } else { _npoints = npoints; } _nplots = points.size(); for(size_t i = 0; i < _nplots; i++) { _points.push_back(new double[_npoints]); if(npoints > 0) { memcpy(_points[i], points[i], _npoints*sizeof(double)); } } } HistogramUpdateEvent::~HistogramUpdateEvent() { for(size_t i = 0; i < _nplots; i++) { delete[] _points[i]; } } const std::vector HistogramUpdateEvent::getDataPoints() const { return _points; } uint64_t HistogramUpdateEvent::getNumDataPoints() const { return _npoints; } #endif /* SPECTRUM_UPDATE_EVENTS_C */ gnuradio-3.7.2.1/gr-qtgui/lib/time_raster_sink_f_impl.h0000664000175000017500000000725412237515112022701 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_RASTER_SINK_F_IMPL_H #define INCLUDED_QTGUI_TIME_RASTER_SINK_F_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API time_raster_sink_f_impl : public time_raster_sink_f { private: void initialize(); std::string d_name; int d_nconnections; int d_index; std::vector d_residbufs; float *d_tmpflt; int d_argc; char *d_argv; QWidget *d_parent; TimeRasterDisplayForm *d_main_gui; int d_icols; double d_rows, d_cols; std::vector d_mult; std::vector d_offset; double d_samp_rate; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; public: time_raster_sink_f_impl(double samp_rate, double rows, double cols, const std::vector &mult, const std::vector &offset, const std::string &name, int nconnections, QWidget *parent=NULL); ~time_raster_sink_f_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, Qt::PenStyle style); void set_line_marker(int which, QwtSymbol::Style marker); void set_line_alpha(int which, double alpha); void set_color_map(int which, const int color); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); int color_map(int which); void set_size(int width, int height); void set_samp_rate(const double samp_rate); void set_num_rows(double rows); void set_num_cols(double cols); double num_rows(); double num_cols(); void set_multiplier(const std::vector &mult); void set_offset(const std::vector &offset); void set_intensity_range(float min, float max); void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_RASTER_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/waterfall_sink_c_impl.cc0000664000175000017500000002654412237515112022502 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "waterfall_sink_c_impl.h" #include #include #include #include namespace gr { namespace qtgui { waterfall_sink_c::sptr waterfall_sink_c::make(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new waterfall_sink_c_impl(fftsize, wintype, fc, bw, name, nconnections, parent)); } waterfall_sink_c_impl::waterfall_sink_c_impl(int fftsize, int wintype, double fc, double bw, const std::string &name, int nconnections, QWidget *parent) : sync_block("waterfall_sink_c", io_signature::make(1, nconnections, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_fftsize(fftsize), d_fftavg(1.0), d_wintype((filter::firdes::win_type)(wintype)), d_center_freq(fc), d_bandwidth(bw), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; // Perform fftshift operation; // this is usually desired when plotting d_shift = true; d_fft = new fft::fft_complex(d_fftsize, true); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs.push_back(fft::malloc_complex(d_fftsize)); d_magbufs.push_back(fft::malloc_double(d_fftsize)); memset(d_residbufs[i], 0, d_fftsize*sizeof(float)); memset(d_magbufs[i], 0, d_fftsize*sizeof(double)); } buildwindow(); initialize(); } waterfall_sink_c_impl::~waterfall_sink_c_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); } delete d_fft; fft::free(d_fbuf); delete d_argv; } bool waterfall_sink_c_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void waterfall_sink_c_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned int ninputs = ninput_items_required.size(); for (unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = std::min(d_fftsize, 8191); } } void waterfall_sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new WaterfallDisplayForm(d_nconnections, d_parent); set_fft_window(d_wintype); set_fft_size(d_fftsize); set_frequency_range(d_center_freq, d_bandwidth); // initialize update time to 10 times a second set_update_time(0.1); } void waterfall_sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* waterfall_sink_c_impl::qwidget() { return d_main_gui; } PyObject* waterfall_sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void waterfall_sink_c_impl::clear_data() { d_main_gui->clearData(); } void waterfall_sink_c_impl::set_fft_size(const int fftsize) { d_main_gui->setFFTSize(fftsize); } int waterfall_sink_c_impl::fft_size() const { return d_fftsize; } void waterfall_sink_c_impl::set_fft_average(const float fftavg) { d_main_gui->setFFTAverage(fftavg); } float waterfall_sink_c_impl::fft_average() const { return d_fftavg; } void waterfall_sink_c_impl::set_fft_window(const filter::firdes::win_type win) { d_main_gui->setFFTWindowType(win); } filter::firdes::win_type waterfall_sink_c_impl::fft_window() { return d_wintype; } void waterfall_sink_c_impl::set_frequency_range(const double centerfreq, const double bandwidth) { d_center_freq = centerfreq; d_bandwidth = bandwidth; d_main_gui->setFrequencyRange(d_center_freq, d_bandwidth); } void waterfall_sink_c_impl::set_intensity_range(const double min, const double max) { d_main_gui->setIntensityRange(min, max); } void waterfall_sink_c_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void waterfall_sink_c_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void waterfall_sink_c_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void waterfall_sink_c_impl::set_color_map(int which, const int color) { d_main_gui->setColorMap(which, color); } void waterfall_sink_c_impl::set_line_alpha(int which, double alpha) { d_main_gui->setAlpha(which, (int)(255.0*alpha)); } void waterfall_sink_c_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string waterfall_sink_c_impl::title() { return d_main_gui->title().toStdString(); } std::string waterfall_sink_c_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } int waterfall_sink_c_impl::color_map(int which) { return d_main_gui->getColorMap(which); } double waterfall_sink_c_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void waterfall_sink_c_impl::auto_scale() { d_main_gui->autoScale(); } double waterfall_sink_c_impl::min_intensity(int which) { return d_main_gui->getMinIntensity(which); } double waterfall_sink_c_impl::max_intensity(int which) { return d_main_gui->getMaxIntensity(which); } void waterfall_sink_c_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void waterfall_sink_c_impl::enable_grid(bool en) { d_main_gui->setGrid(en); } void waterfall_sink_c_impl::fft(float *data_out, const gr_complex *data_in, int size) { if(d_window.size()) { volk_32fc_32f_multiply_32fc_a(d_fft->get_inbuf(), data_in, &d_window.front(), size); } else { memcpy(d_fft->get_inbuf(), data_in, sizeof(gr_complex)*size); } d_fft->execute(); // compute the fft volk_32fc_s32f_x2_power_spectral_density_32f_a(data_out, d_fft->get_outbuf(), size, 1.0, size); // Perform shift operation unsigned int len = (unsigned int)(floor(size/2.0)); float *tmp = (float*)malloc(sizeof(float)*len); memcpy(tmp, &data_out[0], sizeof(float)*len); memcpy(&data_out[0], &data_out[len], sizeof(float)*(size - len)); memcpy(&data_out[size - len], tmp, sizeof(float)*len); free(tmp); } void waterfall_sink_c_impl::windowreset() { filter::firdes::win_type newwintype; newwintype = d_main_gui->getFFTWindowType(); if(d_wintype != newwintype) { d_wintype = newwintype; buildwindow(); } } void waterfall_sink_c_impl::buildwindow() { d_window.clear(); if(d_wintype != filter::firdes::WIN_NONE) { d_window = filter::firdes::window(d_wintype, d_fftsize, 6.76); } } void waterfall_sink_c_impl::fftresize() { int newfftsize = d_main_gui->getFFTSize(); d_fftavg = d_main_gui->getFFTAverage(); if(newfftsize != d_fftsize) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs[i]); fft::free(d_magbufs[i]); d_residbufs[i] = fft::malloc_complex(newfftsize); d_magbufs[i] = fft::malloc_double(newfftsize); memset(d_residbufs[i], 0, newfftsize*sizeof(gr_complex)); memset(d_magbufs[i], 0, newfftsize*sizeof(double)); } // Set new fft size and reset buffer index // (throws away any currently held data, but who cares?) d_fftsize = newfftsize; d_index = 0; // Reset window to reflect new size buildwindow(); // Reset FFTW plan for new size delete d_fft; d_fft = new fft::fft_complex(d_fftsize, true); fft::free(d_fbuf); d_fbuf = fft::malloc_float(d_fftsize); memset(d_fbuf, 0, d_fftsize*sizeof(float)); } } int waterfall_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int j=0; const gr_complex *in = (const gr_complex*)input_items[0]; // Update the FFT size from the application fftresize(); windowreset(); for(int i=0; i < noutput_items; i+=d_fftsize) { unsigned int datasize = noutput_items - i; unsigned int resid = d_fftsize-d_index; // If we have enough input for one full FFT, do it if(datasize >= resid) { if(gr::high_res_timer_now() - d_last_time > d_update_time) { for(int n = 0; n < d_nconnections; n++) { // Fill up residbuf with d_fftsize number of items in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*resid); fft(d_fbuf, d_residbufs[n], d_fftsize); for(int x = 0; x < d_fftsize; x++) { d_magbufs[n][x] = (double)((1.0-d_fftavg)*d_magbufs[n][x] + (d_fftavg)*d_fbuf[x]); } //volk_32f_convert_64f_a(d_magbufs[n], d_fbuf, d_fftsize); } d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new WaterfallUpdateEvent(d_magbufs, d_fftsize, d_last_time)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbuf for next time else { for(int n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[n]; memcpy(d_residbufs[n]+d_index, &in[j], sizeof(gr_complex)*datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/displayform.cc0000664000175000017500000002220212237515112020466 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include DisplayForm::DisplayForm(int nplots, QWidget* parent) : QWidget(parent), d_nplots(nplots), d_system_specified_flag(false) { d_isclosed = false; // Set the initial plot size resize(QSize(800, 600)); // Set up a grid that can be turned on/off d_grid = new QwtPlotGrid(); d_grid->setPen(QPen(QColor(Qt::gray))); // Create a set of actions for the menu d_stop_act = new QAction("Stop", this); d_stop_act->setStatusTip(tr("Start/Stop")); connect(d_stop_act, SIGNAL(triggered()), this, SLOT(setStop())); d_stop_state = false; d_grid_act = new QAction("Grid", this); d_grid_act->setCheckable(true); d_grid_act->setStatusTip(tr("Toggle Grid on/off")); connect(d_grid_act, SIGNAL(triggered(bool)), this, SLOT(setGrid(bool))); d_grid_state = false; // Create a pop-up menu for manipulating the figure d_menu_on = true; d_menu = new QMenu(this); d_menu->addAction(d_stop_act); d_menu->addAction(d_grid_act); for(int i = 0; i < d_nplots; i++) { d_line_title_act.push_back(new LineTitleAction(i, this)); d_line_color_menu.push_back(new LineColorMenu(i, this)); d_line_width_menu.push_back(new LineWidthMenu(i, this)); d_line_style_menu.push_back(new LineStyleMenu(i, this)); d_line_marker_menu.push_back(new LineMarkerMenu(i, this)); d_marker_alpha_menu.push_back(new MarkerAlphaMenu(i, this)); connect(d_line_title_act[i], SIGNAL(whichTrigger(int, const QString&)), this, SLOT(setLineLabel(int, const QString&))); for(int j = 0; j < d_line_color_menu[i]->getNumActions(); j++) { connect(d_line_color_menu[i], SIGNAL(whichTrigger(int, const QString&)), this, SLOT(setLineColor(int, const QString&))); } for(int j = 0; j < d_line_width_menu[i]->getNumActions(); j++) { connect(d_line_width_menu[i], SIGNAL(whichTrigger(int, int)), this, SLOT(setLineWidth(int, int))); } for(int j = 0; j < d_line_style_menu[i]->getNumActions(); j++) { connect(d_line_style_menu[i], SIGNAL(whichTrigger(int, Qt::PenStyle)), this, SLOT(setLineStyle(int, Qt::PenStyle))); } for(int j = 0; j < d_line_marker_menu[i]->getNumActions(); j++) { connect(d_line_marker_menu[i], SIGNAL(whichTrigger(int, QwtSymbol::Style)), this, SLOT(setLineMarker(int, QwtSymbol::Style))); } for(int j = 0; j < d_marker_alpha_menu[i]->getNumActions(); j++) { connect(d_marker_alpha_menu[i], SIGNAL(whichTrigger(int, int)), this, SLOT(setMarkerAlpha(int, int))); } d_lines_menu.push_back(new QMenu(tr(""), this)); d_lines_menu[i]->addAction(d_line_title_act[i]); d_lines_menu[i]->addMenu(d_line_color_menu[i]); d_lines_menu[i]->addMenu(d_line_width_menu[i]); d_lines_menu[i]->addMenu(d_line_style_menu[i]); d_lines_menu[i]->addMenu(d_line_marker_menu[i]); d_lines_menu[i]->addMenu(d_marker_alpha_menu[i]); d_menu->addMenu(d_lines_menu[i]); } d_samp_rate_act = new PopupMenu("Sample Rate", this); d_samp_rate_act->setStatusTip(tr("Set Sample Rate")); connect(d_samp_rate_act, SIGNAL(whichTrigger(QString)), this, SLOT(setSampleRate(QString))); d_menu->addAction(d_samp_rate_act); d_autoscale_act = new QAction("Auto Scale", this); d_autoscale_act->setStatusTip(tr("Autoscale Plot")); d_autoscale_act->setCheckable(true); connect(d_autoscale_act, SIGNAL(triggered(bool)), this, SLOT(autoScale(bool))); d_autoscale_state = false; d_menu->addAction(d_autoscale_act); d_save_act = new QAction("Save", this); d_save_act->setStatusTip(tr("Save Figure")); connect(d_save_act, SIGNAL(triggered()), this, SLOT(saveFigure())); d_menu->addAction(d_save_act); Reset(); // Create a timer to update plots at the specified rate d_display_timer = new QTimer(this); connect(d_display_timer, SIGNAL(timeout()), this, SLOT(updateGuiTimer())); } DisplayForm::~DisplayForm() { d_isclosed = true; // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted d_display_timer->stop(); delete d_display_timer; } void DisplayForm::resizeEvent( QResizeEvent *e ) { QSize s = size(); emit d_display_plot->resizeSlot(&s); } void DisplayForm::mousePressEvent( QMouseEvent * e) { bool ctrloff = Qt::ControlModifier != QApplication::keyboardModifiers(); if((e->button() == Qt::MidButton) && ctrloff && (d_menu_on)) { if(d_stop_state == false) d_stop_act->setText(tr("Stop")); else d_stop_act->setText(tr("Start")); // Update the line titles if changed externally for(int i = 0; i < d_nplots; i++) { d_lines_menu[i]->setTitle(d_display_plot->getLineLabel(i)); } d_menu->exec(e->globalPos()); } } void DisplayForm::updateGuiTimer() { d_display_plot->canvas()->update(); } void DisplayForm::onPlotPointSelected(const QPointF p) { emit plotPointSelected(p, 3); } void DisplayForm::Reset() { } bool DisplayForm::isClosed() const { return d_isclosed; } void DisplayForm::enableMenu(bool en) { d_menu_on = en; } void DisplayForm::closeEvent(QCloseEvent *e) { d_isclosed = true; qApp->processEvents(); QWidget::closeEvent(e); } void DisplayForm::setUpdateTime(double t) { d_update_time = t; d_display_timer->start(d_update_time); } void DisplayForm::setTitle(const QString &title) { d_display_plot->setTitle(title); } void DisplayForm::setLineLabel(int which, const QString &label) { d_display_plot->setLineLabel(which, label); } void DisplayForm::setLineColor(int which, const QString &color) { QColor c = QColor(color); d_display_plot->setLineColor(which, c); d_display_plot->replot(); } void DisplayForm::setLineWidth(int which, int width) { d_display_plot->setLineWidth(which, width); d_display_plot->replot(); } void DisplayForm::setLineStyle(int which, Qt::PenStyle style) { d_display_plot->setLineStyle(which, style); d_display_plot->replot(); } void DisplayForm::setLineMarker(int which, QwtSymbol::Style marker) { d_display_plot->setLineMarker(which, marker); d_display_plot->replot(); } void DisplayForm::setMarkerAlpha(int which, int alpha) { d_display_plot->setMarkerAlpha(which, alpha); d_display_plot->replot(); } QString DisplayForm::title() { return d_display_plot->title().text(); } QString DisplayForm::lineLabel(int which) { return d_display_plot->getLineLabel(which); } QString DisplayForm::lineColor(int which) { return d_display_plot->getLineColor(which).name(); } int DisplayForm::lineWidth(int which) { return d_display_plot->getLineWidth(which); } Qt::PenStyle DisplayForm::lineStyle(int which) { return d_display_plot->getLineStyle(which); } QwtSymbol::Style DisplayForm::lineMarker(int which) { return d_display_plot->getLineMarker(which); } int DisplayForm::markerAlpha(int which) { return d_display_plot->getMarkerAlpha(which); } void DisplayForm::setSampleRate(const QString &rate) { } void DisplayForm::setStop(bool on) { if(!on) { // will auto-detach if already attached. d_display_plot->setStop(false); d_stop_state = false; } else { d_display_plot->setStop(true); d_stop_state = true; } d_display_plot->replot(); } void DisplayForm::setStop() { if(d_stop_state == false) setStop(true); else setStop(false); } void DisplayForm::setGrid(bool on) { if(on) { // will auto-detach if already attached. d_grid->attach(d_display_plot); d_grid_state = true; } else { d_grid->detach(); d_grid_state = false; } d_display_plot->replot(); } void DisplayForm::saveFigure() { QPixmap qpix = QPixmap::grabWidget(this); QString types = QString(tr("JPEG file (*.jpg);;Portable Network Graphics file (*.png);;Bitmap file (*.bmp);;TIFF file (*.tiff)")); QString filename, filetype; QFileDialog *filebox = new QFileDialog(0, "Save Image", "./", types); filebox->setViewMode(QFileDialog::Detail); if(filebox->exec()) { filename = filebox->selectedFiles()[0]; filetype = filebox->selectedNameFilter(); } else { return; } if(filetype.contains(".jpg")) { qpix.save(filename, "JPEG"); } else if(filetype.contains(".png")) { qpix.save(filename, "PNG"); } else if(filetype.contains(".bmp")) { qpix.save(filename, "BMP"); } else if(filetype.contains(".tiff")) { qpix.save(filename, "TIFF"); } else { qpix.save(filename, "JPEG"); } delete filebox; } gnuradio-3.7.2.1/gr-qtgui/lib/time_raster_sink_c_impl.h0000664000175000017500000000505412207440367022700 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_RASTER_SINK_C_IMPL_H #define INCLUDED_QTGUI_TIME_RASTER_SINK_C_IMPL_H #include #include #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API time_raster_sink_c_impl : public time_raster_sink_c { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); void initialize(); std::string d_name; int d_nconnections; int d_index; std::vector d_residbufs; float *d_fbuf; QWidget *d_parent; TimeRasterDisplayForm *d_main_gui; unsigned int d_rows, d_cols; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; public: time_raster_sink_c_impl(unsignedint rows, unsigned int cols, const std::string &name, QWidget *parent=NULL); ~time_raster_sink_c_impl(); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(const std::string &label); void set_line_color(const std::string &color); void set_line_width(int width); void set_line_style(Qt::PenStyle style); void set_line_marker(QwtSymbol::Style marker); void set_size(int width, int height); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_RASTER_SINK_C_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/time_sink_f_impl.h0000664000175000017500000001016412237515112021313 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QTGUI_TIME_SINK_F_IMPL_H #define INCLUDED_QTGUI_TIME_SINK_F_IMPL_H #include #include #include #include namespace gr { namespace qtgui { class QTGUI_API time_sink_f_impl : public time_sink_f { private: void initialize(); gr::thread::mutex d_mutex; int d_size, d_buffer_size; double d_samp_rate; std::string d_name; int d_nconnections; int d_index, d_start, d_end; std::vector d_buffers; std::vector< std::vector > d_tags; int d_argc; char *d_argv; QWidget *d_parent; TimeDisplayForm *d_main_gui; gr::high_res_timer_type d_update_time; gr::high_res_timer_type d_last_time; // Members used for triggering scope trigger_mode d_trigger_mode; trigger_slope d_trigger_slope; float d_trigger_level; int d_trigger_channel; int d_trigger_delay; pmt::pmt_t d_trigger_tag_key; bool d_triggered; int d_trigger_count; int d_initial_delay; // used for limiting d_trigger_delay void _reset(); void _npoints_resize(); void _adjust_tags(int adj); void _gui_update_trigger(); void _test_trigger_tags(int nitems); void _test_trigger_norm(int nitems, gr_vector_const_void_star inputs); bool _test_trigger_slope(const float *in) const; public: time_sink_f_impl(int size, double samp_rate, const std::string &name, int nconnections, QWidget *parent=NULL); ~time_sink_f_impl(); bool check_topology(int ninputs, int noutputs); void exec_(); QWidget* qwidget(); PyObject* pyqwidget(); void set_y_axis(double min, double max); void set_update_time(double t); void set_title(const std::string &title); void set_line_label(int which, const std::string &label); void set_line_color(int which, const std::string &color); void set_line_width(int which, int width); void set_line_style(int which, int style); void set_line_marker(int which, int marker); void set_nsamps(const int size); void set_samp_rate(const double samp_rate); void set_line_alpha(int which, double alpha); void set_trigger_mode(trigger_mode mode, trigger_slope slope, float level, float delay, int channel, const std::string &tag_key=""); std::string title(); std::string line_label(int which); std::string line_color(int which); int line_width(int which); int line_style(int which); int line_marker(int which); double line_alpha(int which); void set_size(int width, int height); int nsamps() const; void enable_menu(bool en); void enable_grid(bool en); void enable_autoscale(bool en); void enable_stem_plot(bool en); void enable_semilogx(bool en); void enable_semilogy(bool en); void enable_tags(int which, bool en); void reset(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace qtgui */ } /* namespace gr */ #endif /* INCLUDED_QTGUI_TIME_SINK_F_IMPL_H */ gnuradio-3.7.2.1/gr-qtgui/lib/histogramdisplayform.cc0000664000175000017500000001214212237515112022406 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include HistogramDisplayForm::HistogramDisplayForm(int nplots, QWidget* parent) : DisplayForm(nplots, parent) { d_semilogx = false; d_semilogy = false; d_int_validator = new QIntValidator(this); d_int_validator->setBottom(0); d_layout = new QGridLayout(this); d_display_plot = new HistogramDisplayPlot(nplots, this); d_layout->addWidget(d_display_plot, 0, 0); setLayout(d_layout); d_nptsmenu = new NPointsMenu(this); d_menu->addAction(d_nptsmenu); connect(d_nptsmenu, SIGNAL(whichTrigger(int)), this, SLOT(setNPoints(const int))); d_nbinsmenu = new NPointsMenu(this); d_nbinsmenu->setText("Number of Bins"); d_menu->addAction(d_nbinsmenu); connect(d_nbinsmenu, SIGNAL(whichTrigger(int)), this, SLOT(setNumBins(const int))); QAction *accummenu = new QAction("Accumulate", this); accummenu->setCheckable(true); d_menu->addAction(accummenu); connect(accummenu, SIGNAL(triggered(bool)), this, SLOT(setAccumulate(bool))); d_menu->removeAction(d_autoscale_act); d_autoscale_act->setText(tr("Auto Scale Y")); d_autoscale_act->setStatusTip(tr("Autoscale Y-axis")); d_autoscale_act->setCheckable(true); d_autoscale_act->setChecked(true); d_autoscale_state = true; d_menu->addAction(d_autoscale_act); d_autoscalex_act = new QAction("Auto Scale X", this); d_autoscalex_act->setStatusTip(tr("Update X-axis scale")); d_autoscalex_act->setCheckable(false); connect(d_autoscalex_act, SIGNAL(changed()), this, SLOT(autoScaleX())); d_autoscalex_state = false; d_menu->addAction(d_autoscalex_act); // d_semilogxmenu = new QAction("Semilog X", this); // d_semilogxmenu->setCheckable(true); // d_menu->addAction(d_semilogxmenu); // connect(d_semilogxmenu, SIGNAL(triggered(bool)), // this, SLOT(setSemilogx(bool))); // // d_semilogymenu = new QAction("Semilog Y", this); // d_semilogymenu->setCheckable(true); // d_menu->addAction(d_semilogymenu); // connect(d_semilogymenu, SIGNAL(triggered(bool)), // this, SLOT(setSemilogy(bool))); Reset(); connect(d_display_plot, SIGNAL(plotPointSelected(const QPointF)), this, SLOT(onPlotPointSelected(const QPointF))); } HistogramDisplayForm::~HistogramDisplayForm() { // Qt deletes children when parent is deleted // Don't worry about deleting Display Plots - they are deleted when parents are deleted delete d_int_validator; } HistogramDisplayPlot* HistogramDisplayForm::getPlot() { return ((HistogramDisplayPlot*)d_display_plot); } void HistogramDisplayForm::newData(const QEvent* updateEvent) { HistogramUpdateEvent *hevent = (HistogramUpdateEvent*)updateEvent; const std::vector dataPoints = hevent->getDataPoints(); const uint64_t numDataPoints = hevent->getNumDataPoints(); getPlot()->plotNewData(dataPoints, numDataPoints, d_update_time); } void HistogramDisplayForm::customEvent(QEvent * e) { if(e->type() == HistogramUpdateEvent::Type()) { newData(e); } } void HistogramDisplayForm::setYaxis(double min, double max) { getPlot()->setYaxis(min, max); } void HistogramDisplayForm::setXaxis(double min, double max) { getPlot()->setXaxis(min, max); } int HistogramDisplayForm::getNPoints() const { return d_npoints; } void HistogramDisplayForm::setNPoints(const int npoints) { d_npoints = npoints; d_nptsmenu->setDiagText(npoints); } void HistogramDisplayForm::autoScale(bool en) { d_autoscale_state = en; d_autoscale_act->setChecked(en); getPlot()->setAutoScale(d_autoscale_state); getPlot()->replot(); } void HistogramDisplayForm::autoScaleX() { getPlot()->setAutoScaleX(); getPlot()->replot(); } void HistogramDisplayForm::setSemilogx(bool en) { d_semilogx = en; d_semilogxmenu->setChecked(en); getPlot()->setSemilogx(d_semilogx); getPlot()->replot(); } void HistogramDisplayForm::setSemilogy(bool en) { d_semilogy = en; d_semilogymenu->setChecked(en); getPlot()->setSemilogy(d_semilogy); getPlot()->replot(); } void HistogramDisplayForm::setNumBins(const int bins) { getPlot()->setNumBins(bins); getPlot()->replot(); d_nbinsmenu->setDiagText(bins); } void HistogramDisplayForm::setAccumulate(bool en) { // Turn on y-axis autoscaling when turning accumulate on. if(en) { autoScale(true); } getPlot()->setAccumulate(en); getPlot()->replot(); } gnuradio-3.7.2.1/gr-qtgui/lib/const_sink_c_impl.cc0000664000175000017500000002131212237515112021633 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "const_sink_c_impl.h" #include #include #include #include #include namespace gr { namespace qtgui { const_sink_c::sptr const_sink_c::make(int size, const std::string &name, int nconnections, QWidget *parent) { return gnuradio::get_initial_sptr (new const_sink_c_impl(size, name, nconnections, parent)); } const_sink_c_impl::const_sink_c_impl(int size, const std::string &name, int nconnections, QWidget *parent) : sync_block("const_sink_c", io_signature::make(nconnections, nconnections, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_size(size), d_name(name), d_nconnections(nconnections), d_parent(parent) { // Required now for Qt; argc must be greater than 0 and argv // must have at least one valid character. Must be valid through // life of the qApplication: // http://harmattan-dev.nokia.com/docs/library/html/qt4/qapplication.html d_argc = 1; d_argv = new char; d_argv = '\0'; d_main_gui = NULL; d_index = 0; for(int i = 0; i < d_nconnections; i++) { d_residbufs_real.push_back(fft::malloc_double(d_size)); d_residbufs_imag.push_back(fft::malloc_double(d_size)); memset(d_residbufs_real[i], 0, d_size*sizeof(double)); memset(d_residbufs_imag[i], 0, d_size*sizeof(double)); } // Set alignment properties for VOLK const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); initialize(); } const_sink_c_impl::~const_sink_c_impl() { if(!d_main_gui->isClosed()) d_main_gui->close(); // d_main_gui is a qwidget destroyed with its parent for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs_real[i]); fft::free(d_residbufs_imag[i]); } delete d_argv; } bool const_sink_c_impl::check_topology(int ninputs, int noutputs) { return ninputs == d_nconnections; } void const_sink_c_impl::initialize() { if(qApp != NULL) { d_qApplication = qApp; } else { d_qApplication = new QApplication(d_argc, &d_argv); } d_main_gui = new ConstellationDisplayForm(d_nconnections, d_parent); d_main_gui->setNPoints(d_size); // initialize update time to 10 times a second set_update_time(0.1); } void const_sink_c_impl::exec_() { d_qApplication->exec(); } QWidget* const_sink_c_impl::qwidget() { return d_main_gui; } PyObject* const_sink_c_impl::pyqwidget() { PyObject *w = PyLong_FromVoidPtr((void*)d_main_gui); PyObject *retarg = Py_BuildValue("N", w); return retarg; } void const_sink_c_impl::set_y_axis(double min, double max) { d_main_gui->setYaxis(min, max); } void const_sink_c_impl::set_x_axis(double min, double max) { d_main_gui->setXaxis(min, max); } void const_sink_c_impl::set_update_time(double t) { //convert update time to ticks gr::high_res_timer_type tps = gr::high_res_timer_tps(); d_update_time = t * tps; d_main_gui->setUpdateTime(t); d_last_time = 0; } void const_sink_c_impl::set_title(const std::string &title) { d_main_gui->setTitle(title.c_str()); } void const_sink_c_impl::set_line_label(int which, const std::string &label) { d_main_gui->setLineLabel(which, label.c_str()); } void const_sink_c_impl::set_line_color(int which, const std::string &color) { d_main_gui->setLineColor(which, color.c_str()); } void const_sink_c_impl::set_line_width(int which, int width) { d_main_gui->setLineWidth(which, width); } void const_sink_c_impl::set_line_style(int which, int style) { d_main_gui->setLineStyle(which, (Qt::PenStyle)style); } void const_sink_c_impl::set_line_marker(int which, int marker) { d_main_gui->setLineMarker(which, (QwtSymbol::Style)marker); } void const_sink_c_impl::set_line_alpha(int which, double alpha) { d_main_gui->setMarkerAlpha(which, (int)(255.0*alpha)); } void const_sink_c_impl::set_size(int width, int height) { d_main_gui->resize(QSize(width, height)); } std::string const_sink_c_impl::title() { return d_main_gui->title().toStdString(); } std::string const_sink_c_impl::line_label(int which) { return d_main_gui->lineLabel(which).toStdString(); } std::string const_sink_c_impl::line_color(int which) { return d_main_gui->lineColor(which).toStdString(); } int const_sink_c_impl::line_width(int which) { return d_main_gui->lineWidth(which); } int const_sink_c_impl::line_style(int which) { return d_main_gui->lineStyle(which); } int const_sink_c_impl::line_marker(int which) { return d_main_gui->lineMarker(which); } double const_sink_c_impl::line_alpha(int which) { return (double)(d_main_gui->markerAlpha(which))/255.0; } void const_sink_c_impl::set_nsamps(const int newsize) { gr::thread::scoped_lock lock(d_mutex); if(newsize != d_size) { // Resize residbuf and replace data for(int i = 0; i < d_nconnections; i++) { fft::free(d_residbufs_real[i]); fft::free(d_residbufs_imag[i]); d_residbufs_real[i] = fft::malloc_double(newsize); d_residbufs_imag[i] = fft::malloc_double(newsize); memset(d_residbufs_real[i], 0, newsize*sizeof(double)); memset(d_residbufs_imag[i], 0, newsize*sizeof(double)); } // Set new size and reset buffer index // (throws away any currently held data, but who cares?) d_size = newsize; d_index = 0; d_main_gui->setNPoints(d_size); } } void const_sink_c_impl::npoints_resize() { int newsize = d_main_gui->getNPoints(); set_nsamps(newsize); } int const_sink_c_impl::nsamps() const { return d_size; } void const_sink_c_impl::enable_menu(bool en) { d_main_gui->enableMenu(en); } void const_sink_c_impl::enable_autoscale(bool en) { d_main_gui->autoScale(en); } void const_sink_c_impl::reset() { d_index = 0; } int const_sink_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int n=0, j=0, idx=0; const gr_complex *in = (const gr_complex*)input_items[idx]; npoints_resize(); for(int i=0; i < noutput_items; i+=d_size) { unsigned int datasize = noutput_items - i; unsigned int resid = d_size-d_index; idx = 0; // If we have enough input for one full plot, do it if(datasize >= resid) { // Fill up residbufs with d_size number of items for(n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[idx++]; volk_32fc_deinterleave_64f_x2_u(&d_residbufs_real[n][d_index], &d_residbufs_imag[n][d_index], &in[j], resid); } // Update the plot if its time if(gr::high_res_timer_now() - d_last_time > d_update_time) { d_last_time = gr::high_res_timer_now(); d_qApplication->postEvent(d_main_gui, new ConstUpdateEvent(d_residbufs_real, d_residbufs_imag, d_size)); } d_index = 0; j += resid; } // Otherwise, copy what we received into the residbufs for next time else { for(n = 0; n < d_nconnections; n++) { in = (const gr_complex*)input_items[idx++]; volk_32fc_deinterleave_64f_x2_u(&d_residbufs_real[n][d_index], &d_residbufs_imag[n][d_index], &in[j], datasize); } d_index += datasize; j += datasize; } } return j; } } /* namespace qtgui */ } /* namespace gr */ gnuradio-3.7.2.1/gr-qtgui/lib/FrequencyDisplayPlot.cc0000664000175000017500000004461112237515112022273 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef FREQUENCY_DISPLAY_PLOT_C #define FREQUENCY_DISPLAY_PLOT_C #include #include #include #include #include #include #include /*********************************************************************** * Widget to provide mouse pointer coordinate text **********************************************************************/ class FreqDisplayZoomer: public QwtPlotZoomer, public FreqOffsetAndPrecisionClass { public: FreqDisplayZoomer(QwtPlotCanvas* canvas, const unsigned int freqPrecision) : QwtPlotZoomer(canvas), FreqOffsetAndPrecisionClass(freqPrecision) { setTrackerMode(QwtPicker::AlwaysOn); } virtual void updateTrackerText() { updateDisplay(); } void setUnitType(const std::string &type) { d_unitType = type; } protected: using QwtPlotZoomer::trackerText; virtual QwtText trackerText(QPoint const &p) const { QwtDoublePoint dp = QwtPlotZoomer::invTransform(p); QwtText t(QString("%1 %2, %3 dB") .arg(dp.x(), 0, 'f', getFrequencyPrecision()) .arg(d_unitType.c_str()).arg(dp.y(), 0, 'f', 2)); return t; } private: std::string d_unitType; }; /*********************************************************************** * Main frequency display plotter widget **********************************************************************/ FrequencyDisplayPlot::FrequencyDisplayPlot(int nplots, QWidget* parent) : DisplayPlot(nplots, parent) { d_start_frequency = -1; d_stop_frequency = 1; d_numPoints = 1024; d_min_fft_data = new double[d_numPoints]; d_max_fft_data = new double[d_numPoints]; d_xdata = new double[d_numPoints]; setAxisTitle(QwtPlot::xBottom, "Frequency (Hz)"); setAxisScaleDraw(QwtPlot::xBottom, new FreqDisplayScaleDraw(0)); d_ymin = -120; d_ymax = 10; setAxisScaleEngine(QwtPlot::yLeft, new QwtLinearScaleEngine); setAxisScale(QwtPlot::yLeft, d_ymin, d_ymax); setAxisTitle(QwtPlot::yLeft, "Power (dB)"); QList default_colors; default_colors << QColor(Qt::blue) << QColor(Qt::red) << QColor(Qt::green) << QColor(Qt::black) << QColor(Qt::cyan) << QColor(Qt::magenta) << QColor(Qt::yellow) << QColor(Qt::gray) << QColor(Qt::darkRed) << QColor(Qt::darkGreen) << QColor(Qt::darkBlue) << QColor(Qt::darkGray); // Automatically deleted when parent is deleted for(int i = 0; i < d_nplots; i++) { d_ydata.push_back(new double[d_numPoints]); memset(d_ydata[i], 0x0, d_numPoints*sizeof(double)); d_plot_curve.push_back(new QwtPlotCurve(QString("Data %1").arg(i))); d_plot_curve[i]->attach(this); QwtSymbol *symbol = new QwtSymbol(QwtSymbol::NoSymbol, QBrush(default_colors[i]), QPen(default_colors[i]), QSize(7,7)); #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_numPoints); d_plot_curve[i]->setSymbol(*symbol); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_numPoints); d_plot_curve[i]->setSymbol(symbol); #endif setLineColor(i, default_colors[i]); } d_min_fft_plot_curve = new QwtPlotCurve("Minimum Power"); d_min_fft_plot_curve->attach(this); const QColor default_min_fft_color = Qt::magenta; setMinFFTColor(default_min_fft_color); #if QWT_VERSION < 0x060000 d_min_fft_plot_curve->setRawData(d_xdata, d_min_fft_data, d_numPoints); #else d_min_fft_plot_curve->setRawSamples(d_xdata, d_min_fft_data, d_numPoints); #endif d_min_fft_plot_curve->setVisible(false); d_max_fft_plot_curve = new QwtPlotCurve("Maximum Power"); d_max_fft_plot_curve->attach(this); QColor default_max_fft_color = Qt::darkYellow; setMaxFFTColor(default_max_fft_color); #if QWT_VERSION < 0x060000 d_max_fft_plot_curve->setRawData(d_xdata, d_max_fft_data, d_numPoints); #else d_max_fft_plot_curve->setRawSamples(d_xdata, d_max_fft_data, d_numPoints); #endif d_max_fft_plot_curve->setVisible(false); d_lower_intensity_marker= new QwtPlotMarker(); d_lower_intensity_marker->setLineStyle(QwtPlotMarker::HLine); QColor default_marker_lower_intensity_color = Qt::cyan; setMarkerLowerIntensityColor(default_marker_lower_intensity_color); d_lower_intensity_marker->attach(this); d_upper_intensity_marker = new QwtPlotMarker(); d_upper_intensity_marker->setLineStyle(QwtPlotMarker::HLine); QColor default_marker_upper_intensity_color = Qt::green; setMarkerUpperIntensityColor(default_marker_upper_intensity_color); d_upper_intensity_marker->attach(this); memset(d_xdata, 0x0, d_numPoints*sizeof(double)); for(int64_t number = 0; number < d_numPoints; number++){ d_min_fft_data[number] = 200.0; d_max_fft_data[number] = -280.0; } d_marker_peak_amplitude = new QwtPlotMarker(); QColor default_marker_peak_amplitude_color = Qt::yellow; setMarkerPeakAmplitudeColor(default_marker_peak_amplitude_color); /// THIS CAUSES A PROBLEM! //d_marker_peak_amplitude->attach(this); d_marker_noise_floor_amplitude = new QwtPlotMarker(); d_marker_noise_floor_amplitude->setLineStyle(QwtPlotMarker::HLine); QColor d_default_marker_noise_floor_amplitude_color = Qt::darkRed; setMarkerNoiseFloorAmplitudeColor(d_default_marker_noise_floor_amplitude_color); d_marker_noise_floor_amplitude->attach(this); d_marker_cf= new QwtPlotMarker(); d_marker_cf->setLineStyle(QwtPlotMarker::VLine); QColor d_default_marker_cf_color = Qt::lightGray; setMarkerCFColor(d_default_marker_cf_color); d_marker_cf->attach(this); d_marker_cf->hide(); d_peak_frequency = 0; d_peak_amplitude = -HUGE_VAL; d_noise_floor_amplitude = -HUGE_VAL; d_zoomer = new FreqDisplayZoomer(canvas(), 0); #if QWT_VERSION < 0x060000 d_zoomer->setSelectionFlags(QwtPicker::RectSelection | QwtPicker::DragSelection); #endif d_zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); d_zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); const QColor default_zoomer_color(Qt::darkRed); setZoomerColor(default_zoomer_color); // Do this after the zoomer has been built _resetXAxisPoints(); // Turn off min/max hold plots in legend QWidget *w; QwtLegend* legendDisplay = legend(); w = legendDisplay->find(d_min_fft_plot_curve); ((QwtLegendItem*)w)->setChecked(true); w = legendDisplay->find(d_max_fft_plot_curve); ((QwtLegendItem*)w)->setChecked(true); replot(); } FrequencyDisplayPlot::~FrequencyDisplayPlot() { for(int i = 0; i < d_nplots; i++) delete [] d_ydata[i]; delete[] d_max_fft_data; delete[] d_min_fft_data; delete[] d_xdata; } void FrequencyDisplayPlot::setYaxis(double min, double max) { // Get the new max/min values for the plot d_ymin = min; d_ymax = max; // Set the axis max/min to the new values setAxisScale(QwtPlot::yLeft, d_ymin, d_ymax); // Reset the base zoom level to the new axis scale set here. // But don't do it if we set the axis due to auto scaling. if(!d_autoscale_state) d_zoomer->setZoomBase(); } void FrequencyDisplayPlot::setFrequencyRange(const double centerfreq, const double bandwidth, const double units, const std::string &strunits) { double startFreq = (centerfreq - bandwidth/2.0f) / units; double stopFreq = (centerfreq + bandwidth/2.0f) / units; d_xdata_multiplier = units; bool reset = false; if((startFreq != d_start_frequency) || (stopFreq != d_stop_frequency)) reset = true; if(stopFreq > startFreq) { d_start_frequency = startFreq; d_stop_frequency = stopFreq; if((axisScaleDraw(QwtPlot::xBottom) != NULL) && (d_zoomer != NULL)) { double display_units = ceil(log10(units)/2.0); setAxisScaleDraw(QwtPlot::xBottom, new FreqDisplayScaleDraw(display_units)); setAxisTitle(QwtPlot::xBottom, QString("Frequency (%1)").arg(strunits.c_str())); if(reset) { _resetXAxisPoints(); clearMaxData(); clearMinData(); } ((FreqDisplayZoomer*)d_zoomer)->setFrequencyPrecision(display_units); ((FreqDisplayZoomer*)d_zoomer)->setUnitType(strunits); } } } double FrequencyDisplayPlot::getStartFrequency() const { return d_start_frequency; } double FrequencyDisplayPlot::getStopFrequency() const { return d_stop_frequency; } void FrequencyDisplayPlot::replot() { d_marker_noise_floor_amplitude->setYValue(d_noise_floor_amplitude); d_marker_peak_amplitude->setXValue(d_peak_frequency + d_start_frequency); // Make sure to take into account the start frequency // if(d_useCenterFrequencyFlag){ // d_marker_peak_amplitude->setXValue((d_peak_frequency/1000.0) + d_start_frequency); // } // else{ // _markerPeakAmplitude->setXValue(d_peak_frequency + d_start_frequency); // } d_marker_peak_amplitude->setYValue(d_peak_amplitude); QwtPlot::replot(); } void FrequencyDisplayPlot::plotNewData(const std::vector dataPoints, const int64_t numDataPoints, const double noiseFloorAmplitude, const double peakFrequency, const double peakAmplitude, const double timeInterval) { if(!d_stop) { if(numDataPoints > 0) { if(numDataPoints != d_numPoints) { d_numPoints = numDataPoints; delete[] d_min_fft_data; delete[] d_max_fft_data; delete[] d_xdata; d_xdata = new double[d_numPoints]; d_min_fft_data = new double[d_numPoints]; d_max_fft_data = new double[d_numPoints]; for(int i = 0; i < d_nplots; i++) { delete[] d_ydata[i]; d_ydata[i] = new double[d_numPoints]; #if QWT_VERSION < 0x060000 d_plot_curve[i]->setRawData(d_xdata, d_ydata[i], d_numPoints); #else d_plot_curve[i]->setRawSamples(d_xdata, d_ydata[i], d_numPoints); #endif } #if QWT_VERSION < 0x060000 d_min_fft_plot_curve->setRawData(d_xdata, d_min_fft_data, d_numPoints); d_max_fft_plot_curve->setRawData(d_xdata, d_max_fft_data, d_numPoints); #else d_min_fft_plot_curve->setRawSamples(d_xdata, d_min_fft_data, d_numPoints); d_max_fft_plot_curve->setRawSamples(d_xdata, d_max_fft_data, d_numPoints); #endif _resetXAxisPoints(); clearMaxData(); clearMinData(); } double bottom=1e20, top=-1e20; for(int n = 0; n < d_nplots; n++) { memcpy(d_ydata[n], dataPoints[n], numDataPoints*sizeof(double)); for(int64_t point = 0; point < numDataPoints; point++) { if(dataPoints[n][point] < d_min_fft_data[point]) { d_min_fft_data[point] = dataPoints[n][point]; } if(dataPoints[n][point] > d_max_fft_data[point]) { d_max_fft_data[point] = dataPoints[n][point]; } // Find overall top and bottom values in plot. // Used for autoscaling y-axis. if(dataPoints[n][point] < bottom) { bottom = dataPoints[n][point]; } if(dataPoints[n][point] > top) { top = dataPoints[n][point]; } } } if(d_autoscale_state) _autoScale(bottom, top); d_noise_floor_amplitude = noiseFloorAmplitude; d_peak_frequency = peakFrequency; d_peak_amplitude = peakAmplitude; setUpperIntensityLevel(d_peak_amplitude); replot(); } } } void FrequencyDisplayPlot::plotNewData(const double* dataPoints, const int64_t numDataPoints, const double noiseFloorAmplitude, const double peakFrequency, const double peakAmplitude, const double timeInterval) { std::vector vecDataPoints; vecDataPoints.push_back((double*)dataPoints); plotNewData(vecDataPoints, numDataPoints, noiseFloorAmplitude, peakFrequency, peakAmplitude, timeInterval); } void FrequencyDisplayPlot::clearMaxData() { for(int64_t number = 0; number < d_numPoints; number++) { d_max_fft_data[number] = d_ymin; } } void FrequencyDisplayPlot::clearMinData() { for(int64_t number = 0; number < d_numPoints; number++) { d_min_fft_data[number] = d_ymax; } } void FrequencyDisplayPlot::_autoScale(double bottom, double top) { // Auto scale the y-axis with a margin of 10 dB on either side. setYaxis(bottom - 10, top + 10); } void FrequencyDisplayPlot::setAutoScale(bool state) { d_autoscale_state = state; } void FrequencyDisplayPlot::setMaxFFTVisible(const bool visibleFlag) { d_max_fft_visible = visibleFlag; d_max_fft_plot_curve->setVisible(visibleFlag); } const bool FrequencyDisplayPlot::getMaxFFTVisible() const { return d_max_fft_visible; } void FrequencyDisplayPlot::setMinFFTVisible(const bool visibleFlag) { d_min_fft_visible = visibleFlag; d_min_fft_plot_curve->setVisible(visibleFlag); } const bool FrequencyDisplayPlot::getMinFFTVisible() const { return d_min_fft_visible; } void FrequencyDisplayPlot::_resetXAxisPoints() { double fft_bin_size = (d_stop_frequency - d_start_frequency) / static_cast(d_numPoints-1); double freqValue = d_start_frequency; for(int64_t loc = 0; loc < d_numPoints; loc++) { d_xdata[loc] = freqValue; freqValue += fft_bin_size; } setAxisScale(QwtPlot::xBottom, d_start_frequency, d_stop_frequency); // Set up zoomer base for maximum unzoom x-axis // and reset to maximum unzoom level QwtDoubleRect zbase = d_zoomer->zoomBase(); d_zoomer->zoom(zbase); d_zoomer->setZoomBase(zbase); d_zoomer->setZoomBase(true); d_zoomer->zoom(0); } void FrequencyDisplayPlot::setLowerIntensityLevel(const double lowerIntensityLevel) { d_lower_intensity_marker->setYValue(lowerIntensityLevel); } void FrequencyDisplayPlot::setUpperIntensityLevel(const double upperIntensityLevel) { d_upper_intensity_marker->setYValue(upperIntensityLevel); } void FrequencyDisplayPlot::setTraceColour(QColor c) { d_plot_curve[0]->setPen(QPen(c)); } void FrequencyDisplayPlot::setBGColour(QColor c) { QPalette palette; palette.setColor(canvas()->backgroundRole(), c); canvas()->setPalette(palette); } void FrequencyDisplayPlot::showCFMarker(const bool show) { if(show) d_marker_cf->show(); else d_marker_cf->hide(); } void FrequencyDisplayPlot::onPickerPointSelected(const QwtDoublePoint & p) { QPointF point = p; //fprintf(stderr,"onPickerPointSelected %f %f %d\n", point.x(), point.y(), d_xdata_multiplier); point.setX(point.x() * d_xdata_multiplier); emit plotPointSelected(point); } void FrequencyDisplayPlot::onPickerPointSelected6(const QPointF & p) { QPointF point = p; //fprintf(stderr,"onPickerPointSelected %f %f %d\n", point.x(), point.y(), d_xdata_multiplier); point.setX(point.x() * d_xdata_multiplier); emit plotPointSelected(point); } void FrequencyDisplayPlot::setMinFFTColor (QColor c) { d_min_fft_color = c; d_min_fft_plot_curve->setPen(QPen(c)); } const QColor FrequencyDisplayPlot::getMinFFTColor() const { return d_min_fft_color; } void FrequencyDisplayPlot::setMaxFFTColor (QColor c) { d_max_fft_color = c; d_max_fft_plot_curve->setPen(QPen(c)); } const QColor FrequencyDisplayPlot::getMaxFFTColor() const { return d_max_fft_color; } void FrequencyDisplayPlot::setMarkerLowerIntensityColor (QColor c) { d_marker_lower_intensity_color = c; d_lower_intensity_marker->setLinePen(QPen(c)); } const QColor FrequencyDisplayPlot::getMarkerLowerIntensityColor () const { return d_marker_lower_intensity_color; } void FrequencyDisplayPlot::setMarkerLowerIntensityVisible (bool visible) { d_marker_lower_intensity_visible = visible; if(visible) d_lower_intensity_marker->setLineStyle(QwtPlotMarker::HLine); else d_lower_intensity_marker->setLineStyle(QwtPlotMarker::NoLine); } const bool FrequencyDisplayPlot::getMarkerLowerIntensityVisible() const { return d_marker_lower_intensity_visible; } void FrequencyDisplayPlot::setMarkerUpperIntensityColor(QColor c) { d_marker_upper_intensity_color = c; d_upper_intensity_marker->setLinePen(QPen(c, 0, Qt::DotLine)); } const QColor FrequencyDisplayPlot::getMarkerUpperIntensityColor() const { return d_marker_upper_intensity_color; } void FrequencyDisplayPlot::setMarkerUpperIntensityVisible(bool visible) { d_marker_upper_intensity_visible = visible; if(visible) d_upper_intensity_marker->setLineStyle(QwtPlotMarker::HLine); else d_upper_intensity_marker->setLineStyle(QwtPlotMarker::NoLine); } const bool FrequencyDisplayPlot::getMarkerUpperIntensityVisible() const { return d_marker_upper_intensity_visible; } void FrequencyDisplayPlot::setMarkerPeakAmplitudeColor(QColor c) { d_marker_peak_amplitude_color = c; d_marker_peak_amplitude->setLinePen(QPen(c)); QwtSymbol symbol; symbol.setStyle(QwtSymbol::Diamond); symbol.setSize(8); symbol.setPen(QPen(c)); symbol.setBrush(QBrush(c)); #if QWT_VERSION < 0x060000 d_marker_peak_amplitude->setSymbol(symbol); #else d_marker_peak_amplitude->setSymbol(&symbol); #endif } const QColor FrequencyDisplayPlot::getMarkerPeakAmplitudeColor() const { return d_marker_peak_amplitude_color; } void FrequencyDisplayPlot::setMarkerNoiseFloorAmplitudeColor(QColor c) { d_marker_noise_floor_amplitude_color = c; d_marker_noise_floor_amplitude->setLinePen(QPen(c, 0, Qt::DotLine)); } const QColor FrequencyDisplayPlot::getMarkerNoiseFloorAmplitudeColor() const { return d_marker_noise_floor_amplitude_color; } void FrequencyDisplayPlot::setMarkerNoiseFloorAmplitudeVisible(bool visible) { d_marker_noise_floor_amplitude_visible = visible; if(visible) d_marker_noise_floor_amplitude->setLineStyle(QwtPlotMarker::HLine); else d_marker_noise_floor_amplitude->setLineStyle(QwtPlotMarker::NoLine); } const bool FrequencyDisplayPlot::getMarkerNoiseFloorAmplitudeVisible() const { return d_marker_noise_floor_amplitude_visible; } void FrequencyDisplayPlot::setMarkerCFColor(QColor c) { d_marker_cf_color = c; d_marker_cf->setLinePen(QPen(c, 0, Qt::DotLine)); } const QColor FrequencyDisplayPlot::getMarkerCFColor() const { return d_marker_cf_color; } #endif /* FREQUENCY_DISPLAY_PLOT_C */ gnuradio-3.7.2.1/gr-qtgui/swig/0000755000175000017500000000000012237515112016031 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/swig/CMakeLists.txt0000664000175000017500000000357712207440367020615 0ustar jcorganjcorgan# Copyright 2010-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_QTGUI_INCLUDE_DIRS} ${GR_FFT_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${QWT_INCLUDE_DIRS} ${QT_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/qtgui_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/qtgui) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-qtgui) GR_SWIG_MAKE(qtgui_swig qtgui_swig.i) GR_SWIG_INSTALL( TARGETS qtgui_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/qtgui COMPONENT "qtgui_python" ) install(FILES qtgui_swig.i ${CMAKE_CURRENT_BINARY_DIR}/qtgui_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "qtgui_swig" ) gnuradio-3.7.2.1/gr-qtgui/swig/qtgui_swig.i0000664000175000017500000000525712237515112020400 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define QTGUI_API #define FILTER_API %include "gnuradio.i" //load generated python docstrings %include "qtgui_swig_doc.i" %include "gnuradio/qtgui/trigger_mode.h" // So we understand the firdes window types %import "gnuradio/filter/firdes.h" %{ #include "gnuradio/qtgui/form_menus.h" #include "gnuradio/qtgui/DisplayPlot.h" #include "gnuradio/qtgui/displayform.h" #include "gnuradio/qtgui/sink_c.h" #include "gnuradio/qtgui/sink_f.h" #include "gnuradio/qtgui/time_sink_c.h" #include "gnuradio/qtgui/time_sink_f.h" #include "gnuradio/qtgui/time_raster_sink_b.h" #include "gnuradio/qtgui/time_raster_sink_f.h" #include "gnuradio/qtgui/freq_sink_c.h" #include "gnuradio/qtgui/freq_sink_f.h" #include "gnuradio/qtgui/const_sink_c.h" #include "gnuradio/qtgui/waterfall_sink_c.h" #include "gnuradio/qtgui/waterfall_sink_f.h" #include "gnuradio/qtgui/histogram_sink_f.h" %} %include "gnuradio/qtgui/sink_c.h" %include "gnuradio/qtgui/sink_f.h" %include "gnuradio/qtgui/time_sink_c.h" %include "gnuradio/qtgui/time_sink_f.h" %include "gnuradio/qtgui/time_raster_sink_b.h" %include "gnuradio/qtgui/time_raster_sink_f.h" %include "gnuradio/qtgui/freq_sink_c.h" %include "gnuradio/qtgui/freq_sink_f.h" %include "gnuradio/qtgui/const_sink_c.h" %include "gnuradio/qtgui/waterfall_sink_c.h" %include "gnuradio/qtgui/waterfall_sink_f.h" %include "gnuradio/qtgui/histogram_sink_f.h" GR_SWIG_BLOCK_MAGIC2(qtgui, sink_c); GR_SWIG_BLOCK_MAGIC2(qtgui, sink_f); GR_SWIG_BLOCK_MAGIC2(qtgui, time_sink_c); GR_SWIG_BLOCK_MAGIC2(qtgui, time_sink_f); GR_SWIG_BLOCK_MAGIC2(qtgui, time_raster_sink_b); GR_SWIG_BLOCK_MAGIC2(qtgui, time_raster_sink_f); GR_SWIG_BLOCK_MAGIC2(qtgui, freq_sink_c); GR_SWIG_BLOCK_MAGIC2(qtgui, freq_sink_f); GR_SWIG_BLOCK_MAGIC2(qtgui, const_sink_c); GR_SWIG_BLOCK_MAGIC2(qtgui, waterfall_sink_c); GR_SWIG_BLOCK_MAGIC2(qtgui, waterfall_sink_f); GR_SWIG_BLOCK_MAGIC2(qtgui, histogram_sink_f); gnuradio-3.7.2.1/gr-qtgui/apps/0000755000175000017500000000000012207440367016031 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/apps/qt_digital_window.py0000644000175000017500000002356111700377701022120 0ustar jcorganjcorgan# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'qt_digital_window.ui' # # Created: Sat May 1 20:14:02 2010 # by: PyQt4 UI code generator 4.6.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_DigitalWindow(object): def setupUi(self, DigitalWindow): DigitalWindow.setObjectName("DigitalWindow") DigitalWindow.resize(1236, 741) self.centralwidget = QtGui.QWidget(DigitalWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.sinkFrame = QtGui.QFrame(self.centralwidget) self.sinkFrame.setMinimumSize(QtCore.QSize(0, 550)) self.sinkFrame.setFrameShape(QtGui.QFrame.StyledPanel) self.sinkFrame.setFrameShadow(QtGui.QFrame.Raised) self.sinkFrame.setObjectName("sinkFrame") self.horizontalLayout_2 = QtGui.QHBoxLayout(self.sinkFrame) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.sinkLayout = QtGui.QHBoxLayout() self.sinkLayout.setObjectName("sinkLayout") self.horizontalLayout_2.addLayout(self.sinkLayout) self.verticalLayout.addWidget(self.sinkFrame) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.sysBox = QtGui.QGroupBox(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sysBox.sizePolicy().hasHeightForWidth()) self.sysBox.setSizePolicy(sizePolicy) self.sysBox.setMinimumSize(QtCore.QSize(0, 0)) self.sysBox.setMaximumSize(QtCore.QSize(16777215, 120)) self.sysBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.sysBox.setObjectName("sysBox") self.gridLayout_2 = QtGui.QGridLayout(self.sysBox) self.gridLayout_2.setObjectName("gridLayout_2") self.sampleRateEdit = QtGui.QLineEdit(self.sysBox) self.sampleRateEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.sampleRateEdit.setObjectName("sampleRateEdit") self.gridLayout_2.addWidget(self.sampleRateEdit, 0, 3, 1, 1) self.sampleRateLabel = QtGui.QLabel(self.sysBox) self.sampleRateLabel.setObjectName("sampleRateLabel") self.gridLayout_2.addWidget(self.sampleRateLabel, 0, 2, 1, 1) self.horizontalLayout.addWidget(self.sysBox) self.rxBox = QtGui.QGroupBox(self.centralwidget) self.rxBox.setMaximumSize(QtCore.QSize(16777215, 120)) self.rxBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.rxBox.setObjectName("rxBox") self.gridLayout_3 = QtGui.QGridLayout(self.rxBox) self.gridLayout_3.setObjectName("gridLayout_3") self.alphaLabel = QtGui.QLabel(self.rxBox) self.alphaLabel.setObjectName("alphaLabel") self.gridLayout_3.addWidget(self.alphaLabel, 1, 0, 1, 1) self.alphaEdit = QtGui.QLineEdit(self.rxBox) self.alphaEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.alphaEdit.setObjectName("alphaEdit") self.gridLayout_3.addWidget(self.alphaEdit, 1, 1, 1, 1) self.gainMuLabel = QtGui.QLabel(self.rxBox) self.gainMuLabel.setObjectName("gainMuLabel") self.gridLayout_3.addWidget(self.gainMuLabel, 0, 0, 1, 1) self.gainMuEdit = QtGui.QLineEdit(self.rxBox) self.gainMuEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.gainMuEdit.setObjectName("gainMuEdit") self.gridLayout_3.addWidget(self.gainMuEdit, 0, 1, 1, 1) self.horizontalLayout.addWidget(self.rxBox) self.channelModeBox = QtGui.QGroupBox(self.centralwidget) self.channelModeBox.setMaximumSize(QtCore.QSize(16777215, 120)) self.channelModeBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.channelModeBox.setObjectName("channelModeBox") self.gridLayout = QtGui.QGridLayout(self.channelModeBox) self.gridLayout.setSizeConstraint(QtGui.QLayout.SetMinimumSize) self.gridLayout.setObjectName("gridLayout") self.snrLabel = QtGui.QLabel(self.channelModeBox) self.snrLabel.setObjectName("snrLabel") self.gridLayout.addWidget(self.snrLabel, 0, 1, 1, 1) self.snrEdit = QtGui.QLineEdit(self.channelModeBox) self.snrEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.snrEdit.setObjectName("snrEdit") self.gridLayout.addWidget(self.snrEdit, 0, 2, 1, 1) self.freqLabel = QtGui.QLabel(self.channelModeBox) self.freqLabel.setObjectName("freqLabel") self.gridLayout.addWidget(self.freqLabel, 1, 1, 1, 1) self.freqEdit = QtGui.QLineEdit(self.channelModeBox) self.freqEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.freqEdit.setObjectName("freqEdit") self.gridLayout.addWidget(self.freqEdit, 1, 2, 1, 1) self.timeLabel = QtGui.QLabel(self.channelModeBox) self.timeLabel.setObjectName("timeLabel") self.gridLayout.addWidget(self.timeLabel, 2, 1, 1, 1) self.timeEdit = QtGui.QLineEdit(self.channelModeBox) self.timeEdit.setMaximumSize(QtCore.QSize(100, 16777215)) self.timeEdit.setObjectName("timeEdit") self.gridLayout.addWidget(self.timeEdit, 2, 2, 1, 1) self.horizontalLayout.addWidget(self.channelModeBox) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_2.addItem(spacerItem1) self.pauseButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pauseButton.sizePolicy().hasHeightForWidth()) self.pauseButton.setSizePolicy(sizePolicy) self.pauseButton.setMaximumSize(QtCore.QSize(80, 16777215)) self.pauseButton.setObjectName("pauseButton") self.verticalLayout_2.addWidget(self.pauseButton) self.closeButton = QtGui.QPushButton(self.centralwidget) self.closeButton.setMaximumSize(QtCore.QSize(80, 16777215)) self.closeButton.setObjectName("closeButton") self.verticalLayout_2.addWidget(self.closeButton) self.horizontalLayout.addLayout(self.verticalLayout_2) self.verticalLayout.addLayout(self.horizontalLayout) DigitalWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(DigitalWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1236, 23)) self.menubar.setObjectName("menubar") self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") DigitalWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(DigitalWindow) self.statusbar.setObjectName("statusbar") DigitalWindow.setStatusBar(self.statusbar) self.actionExit = QtGui.QAction(DigitalWindow) self.actionExit.setObjectName("actionExit") self.menuFile.addAction(self.actionExit) self.menubar.addAction(self.menuFile.menuAction()) self.retranslateUi(DigitalWindow) QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL("clicked()"), DigitalWindow.close) QtCore.QObject.connect(self.actionExit, QtCore.SIGNAL("triggered()"), DigitalWindow.close) QtCore.QMetaObject.connectSlotsByName(DigitalWindow) DigitalWindow.setTabOrder(self.snrEdit, self.freqEdit) DigitalWindow.setTabOrder(self.freqEdit, self.timeEdit) def retranslateUi(self, DigitalWindow): DigitalWindow.setWindowTitle(QtGui.QApplication.translate("DigitalWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.sysBox.setTitle(QtGui.QApplication.translate("DigitalWindow", "System Parameters", None, QtGui.QApplication.UnicodeUTF8)) self.sampleRateLabel.setText(QtGui.QApplication.translate("DigitalWindow", "Sample Rate (sps)", None, QtGui.QApplication.UnicodeUTF8)) self.rxBox.setTitle(QtGui.QApplication.translate("DigitalWindow", "Receiver Parameters", None, QtGui.QApplication.UnicodeUTF8)) self.alphaLabel.setText(QtGui.QApplication.translate("DigitalWindow", "Alpha", None, QtGui.QApplication.UnicodeUTF8)) self.gainMuLabel.setText(QtGui.QApplication.translate("DigitalWindow", "Gain mu", None, QtGui.QApplication.UnicodeUTF8)) self.channelModeBox.setTitle(QtGui.QApplication.translate("DigitalWindow", "Channel Model Parameters", None, QtGui.QApplication.UnicodeUTF8)) self.snrLabel.setText(QtGui.QApplication.translate("DigitalWindow", "SNR (dB)", None, QtGui.QApplication.UnicodeUTF8)) self.freqLabel.setText(QtGui.QApplication.translate("DigitalWindow", "Frequency Offset (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.timeLabel.setText(QtGui.QApplication.translate("DigitalWindow", "Timing Offset", None, QtGui.QApplication.UnicodeUTF8)) self.pauseButton.setText(QtGui.QApplication.translate("DigitalWindow", "Pause", None, QtGui.QApplication.UnicodeUTF8)) self.closeButton.setText(QtGui.QApplication.translate("DigitalWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("DigitalWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) self.actionExit.setText(QtGui.QApplication.translate("DigitalWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) gnuradio-3.7.2.1/gr-qtgui/apps/uhd_display.py0000775000175000017500000002434612207440367020726 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter from gnuradio import blocks from gnuradio import uhd from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: from usrp_display_qtgui import Ui_MainWindow except ImportError: print "Error: could not find usrp_display_qtgui.py:" print "\t\"pyuic4 usrp_display_qtgui.ui -o usrp_display_qtgui.py\"" sys.exit(1) # //////////////////////////////////////////////////////////////////// # Define the QT Interface and Control Dialog # //////////////////////////////////////////////////////////////////// class main_window(QtGui.QMainWindow): def __init__(self, snk, fg, parent=None): QtGui.QWidget.__init__(self, parent) self.gui = Ui_MainWindow() self.gui.setupUi(self) self.fg = fg # Add the qtsnk widgets to the layout box self.gui.sinkLayout.addWidget(snk) self.gui.dcGainEdit.setText(QtCore.QString("%1").arg(0.001)) # Connect up some signals self.connect(self.gui.pauseButton, QtCore.SIGNAL("clicked()"), self.pauseFg) self.connect(self.gui.frequencyEdit, QtCore.SIGNAL("editingFinished()"), self.frequencyEditText) self.connect(self.gui.gainEdit, QtCore.SIGNAL("editingFinished()"), self.gainEditText) self.connect(self.gui.bandwidthEdit, QtCore.SIGNAL("editingFinished()"), self.bandwidthEditText) self.connect(self.gui.amplifierEdit, QtCore.SIGNAL("editingFinished()"), self.amplifierEditText) self.connect(self.gui.actionSaveData, QtCore.SIGNAL("activated()"), self.saveData) self.gui.actionSaveData.setShortcut(QtGui.QKeySequence.Save) self.connect(self.gui.dcGainEdit, QtCore.SIGNAL("editingFinished()"), self.dcGainEditText) self.connect(self.gui.dcCancelCheckBox, QtCore.SIGNAL("clicked(bool)"), self.dcCancelClicked) def pauseFg(self): if(self.gui.pauseButton.text() == "Pause"): self.fg.stop() self.fg.wait() self.gui.pauseButton.setText("Unpause") else: self.fg.start() self.gui.pauseButton.setText("Pause") # Functions to set the values in the GUI def set_frequency(self, freq): self.freq = freq sfreq = eng_notation.num_to_str(self.freq) self.gui.frequencyEdit.setText(QtCore.QString("%1").arg(sfreq)) def set_gain(self, gain): self.gain = gain self.gui.gainEdit.setText(QtCore.QString("%1").arg(self.gain)) def set_bandwidth(self, bw): self.bw = bw sbw = eng_notation.num_to_str(self.bw) self.gui.bandwidthEdit.setText(QtCore.QString("%1").arg(sbw)) def set_amplifier(self, amp): self.amp = amp self.gui.amplifierEdit.setText(QtCore.QString("%1").arg(self.amp)) # Functions called when signals are triggered in the GUI def frequencyEditText(self): try: freq = eng_notation.str_to_num(self.gui.frequencyEdit.text().toAscii()) self.fg.set_frequency(freq) self.freq = freq except RuntimeError: pass def gainEditText(self): try: gain = float(self.gui.gainEdit.text()) self.fg.set_gain(gain) self.gain = gain except ValueError: pass def bandwidthEditText(self): try: bw = eng_notation.str_to_num(self.gui.bandwidthEdit.text().toAscii()) self.fg.set_bandwidth(bw) self.bw = bw except ValueError: pass def amplifierEditText(self): try: amp = float(self.gui.amplifierEdit.text()) self.fg.set_amplifier_gain(amp) self.amp = amp except ValueError: pass def saveData(self): fileName = QtGui.QFileDialog.getSaveFileName(self, "Save data to file", "."); if(len(fileName)): self.fg.save_to_file(str(fileName)) def dcGainEditText(self): gain = float(self.gui.dcGainEdit.text()) self.fg.set_dc_gain(gain) def dcCancelClicked(self, state): self.dcGainEditText() self.fg.cancel_dc(state) class my_top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) self.options = options self.show_debug_info = True self.qapp = QtGui.QApplication(sys.argv) self.u = uhd.usrp_source(device_addr=options.address, stream_args=uhd.stream_args('fc32')) if(options.antenna): self.u.set_antenna(options.antenna, 0) self.set_bandwidth(options.samp_rate) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 self.set_gain(options.gain) if options.freq is None: # if no freq was specified, use the mid-point r = self.u.get_freq_range() options.freq = float(r.start()+r.stop())/2 self.set_frequency(options.freq) self._fftsize = options.fft_size self.snk = qtgui.sink_c(options.fft_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._freq, self._bandwidth, "UHD Display", True, True, True, False) # Set up internal amplifier self.amp = blocks.multiply_const_cc(0.0) self.set_amplifier_gain(100) # Create a single-pole IIR filter to remove DC # but don't connect it yet self.dc_gain = 0.001 self.dc = filter.single_pole_iir_filter_cc(self.dc_gain) self.dc_sub = blocks.sub_cc() self.connect(self.u, self.amp, self.snk) if self.show_debug_info: print "Bandwidth: ", self.u.get_samp_rate() print "Center Freq: ", self.u.get_center_freq() print "Freq Range: ", self.u.get_freq_range() # Get the reference pointer to the SpectrumDisplayForm QWidget # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget self.pysink = sip.wrapinstance(self.snk.pyqwidget(), QtGui.QWidget) self.main_win = main_window(self.pysink, self) self.main_win.set_frequency(self._freq) self.main_win.set_gain(self._gain) self.main_win.set_bandwidth(self._bandwidth) self.main_win.set_amplifier(self._amp_value) self.main_win.show() def save_to_file(self, name): self.lock() # Add file sink to save data self.file_sink = blocks.file_sink(gr.sizeof_gr_complex, name) self.connect(self.amp, self.file_sink) self.unlock() def set_gain(self, gain): self._gain = gain self.u.set_gain(self._gain) def set_frequency(self, freq): self._freq = freq r = self.u.set_center_freq(freq) try: self.snk.set_frequency_range(self._freq, self._bandwidth) except: pass def set_bandwidth(self, bw): self._bandwidth = bw self.u.set_samp_rate(self._bandwidth) try: self.snk.set_frequency_range(self._freq, self._bandwidth) except: pass def set_amplifier_gain(self, amp): self._amp_value = amp self.amp.set_k(self._amp_value) def set_dc_gain(self, gain): self.dc.set_taps(gain) def cancel_dc(self, state): self.lock() if(state): self.disconnect(self.u, self.amp) self.connect(self.u, (self.dc_sub,0)) self.connect(self.u, self.dc, (self.dc_sub,1)) self.connect(self.dc_sub, self.amp) else: self.disconnect(self.dc_sub, self.amp) self.disconnect(self.dc, (self.dc_sub,1)) self.disconnect(self.u, self.dc) self.disconnect(self.u, (self.dc_sub,0)) self.connect(self.u, self.amp) self.unlock() def main (): parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=2412e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("--fft-size", type="int", default=2048, help="Set number of FFT bins [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) tb = my_top_block(options) tb.start() tb.snk.exec_(); if __name__ == '__main__': try: main () except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/CMakeLists.txt0000664000175000017500000000316612207440367020601 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL( FILES plot_base.py plot_psd_base.py plot_spectrogram_base.py plot_time_base.py plot_time_raster_base.py plot_form.py plot_constellation_form.py plot_psd_form.py plot_spectrogram_form.py plot_time_form.py plot_time_raster_form.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/qtgui COMPONENT "qtgui_python" ) GR_PYTHON_INSTALL( PROGRAMS gr_time_plot_c gr_time_plot_f gr_time_plot_i gr_time_plot_s gr_time_plot_b gr_time_raster_f gr_time_raster_b gr_psd_plot_c gr_psd_plot_f gr_psd_plot_i gr_psd_plot_s gr_psd_plot_b gr_spectrogram_plot_c gr_spectrogram_plot_f gr_spectrogram_plot_i gr_spectrogram_plot_s gr_spectrogram_plot_b gr_constellation_plot DESTINATION ${GR_RUNTIME_DIR} COMPONENT "qtgui_python" ) gnuradio-3.7.2.1/gr-qtgui/apps/plot_time_form.py0000664000175000017500000000521312207440367021425 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from gnuradio import filter try: from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4." sys.exit(1) try: from gnuradio.qtgui.plot_from import plot_form except ImportError: from plot_form import plot_form class plot_time_form(plot_form): def __init__(self, top_block, title='', scale=1): plot_form.__init__(self, top_block, title, scale) self.right_col_layout = QtGui.QVBoxLayout() self.right_col_form = QtGui.QFormLayout() self.right_col_layout.addLayout(self.right_col_form) self.layout.addLayout(self.right_col_layout, 1,4,1,1) self.auto_scale = QtGui.QCheckBox("Auto Scale", self) if(self.top_block._auto_scale): self.auto_scale.setChecked(self.top_block._auto_scale) self.connect(self.auto_scale, QtCore.SIGNAL("stateChanged(int)"), self.set_auto_scale) self.right_col_layout.addWidget(self.auto_scale) self.stem = QtGui.QCheckBox("Stem", self) self.connect(self.stem, QtCore.SIGNAL("stateChanged(int)"), self.enable_stem) self.right_col_layout.addWidget(self.stem) self.add_line_control(self.right_col_layout) def set_auto_scale(self, state): if(state): self.top_block.auto_scale(True) else: self.top_block.auto_scale(False) def enable_stem(self, state): self.top_block.gui_snk.enable_stem_plot(state) if(state): index = self._qwtmarkers['Circle']+1 else: index = self._qwtmarkers['None']+1 for n in xrange(self.top_block._nsigs): self._marker_edit[n].setCurrentIndex(index) def update_samp_rate(self): sr = self.samp_rate_edit.text().toDouble()[0] self.top_block.gui_snk.set_samp_rate(sr) gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_plot_f0000775000175000017500000000464612207440367020764 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import scipy try: import gnuradio.qtgui.plot_time_base as plot_base except ImportError: import plot_time_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_f(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self.read_samples = plot_base.read_samples_f self.dsize = gr.sizeof_float self.src_type = blocks.vector_source_f self.gui_snk = qtgui.time_sink_f(self._nsamps, self._samp_rate, "GNU Radio Time Plot", self._nsigs) self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_f(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, not options.no_auto_scale) main_box = plot_base.plot_time_form(tb, 'GNU Radio Time Plot', 10000.0) main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_plot_i0000775000175000017500000000463712207440367020767 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import scipy try: import gnuradio.qtgui.plot_time_base as plot_base except ImportError: import plot_time_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_i(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self.read_samples = plot_base.read_samples_i self.dsize = gr.sizeof_float # already converted self.src_type = plot_base.source_ints_to_float self.gui_snk = qtgui.time_sink_f(self._nsamps, self._samp_rate, "GNU Radio Time Plot", self._nsigs) self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of integers." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_i(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, not options.no_auto_scale) main_box = plot_base.plot_time_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_spectrogram_plot_b0000775000175000017500000000530012207440367022334 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_spectrogram_base as plot_base except ImportError: import plot_spectrogram_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class spectrogram_plot_b(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_b self.dsize = gr.sizeof_float self.src_type = plot_base.source_chars_to_float self.gui_snk = qtgui.waterfall_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio Spectrogram Plot", self._nsigs) self.setup() def main(): description = "Plots the spectrogram (waterfall) of a list of files. Files are a binary list of chars." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = spectrogram_plot_b(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average); main_box = plot_base.plot_spectrogram_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_raster_f0000775000175000017500000000520512207440367021276 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import scipy try: import gnuradio.qtgui.plot_time_raster_base as plot_base except ImportError: import plot_time_raster_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_raster_f(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, nrows, ncols, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self._nrows = nrows self._ncols = ncols self.read_samples = plot_base.read_samples_f self.dsize = gr.sizeof_float self.src_type = blocks.vector_source_f self.gui_snk = qtgui.time_raster_sink_f(self._samp_rate, self._nrows, self._ncols, [], [], "GNU Radio Time Plot", self._nsigs) self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_raster_f(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, options.nrows, options.ncols, not options.no_auto_scale) main_box = plot_base.plot_time_raster_form(tb, 'GNU Radio Time Plot', 10000.0) main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_psd_plot_f0000775000175000017500000000516112207440367020605 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_psd_base as plot_base except ImportError: import plot_psd_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class psd_plot_f(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0, auto_scale=True): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_f self.dsize = gr.sizeof_float self.src_type = blocks.vector_source_f self.gui_snk = qtgui.freq_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio PSD Plot", self._nsigs) self.setup() def main(): description = "Plots the PSDs of a list of files. Files are a binary list of floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = psd_plot_f(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average) main_box = plot_base.plot_psd_form(tb, 'GNU Radio PSD Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_psd_plot_i0000775000175000017500000000513712207440367020613 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_psd_base as plot_base except ImportError: import plot_psd_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class psd_plot_i(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0, auto_scale=True): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_i self.dsize = gr.sizeof_float self.src_type = plot_base.source_ints_to_float self.gui_snk = qtgui.freq_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio PSD Plot", self._nsigs) self.setup() def main(): description = "Plots the PSDs of a list of files. Files are a binary list of integers." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = psd_plot_i(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average) main_box = plot_base.plot_psd_form(tb, 'GNU Radio PSD Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_spectrogram_plot_s0000775000175000017500000000530212207440367022357 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_spectrogram_base as plot_base except ImportError: import plot_spectrogram_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class spectrogram_plot_s(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_s self.dsize = gr.sizeof_float self.src_type = plot_base.source_shorts_to_float self.gui_snk = qtgui.waterfall_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio Spectrogram Plot", self._nsigs) self.setup() def main(): description = "Plots the spectrogram (waterfall) of a list of files. Files are a binary list of shorts." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = spectrogram_plot_s(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average); main_box = plot_base.plot_spectrogram_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/plot_psd_form.py0000664000175000017500000000763112207440367021263 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from gnuradio import filter try: from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4." sys.exit(1) try: from gnuradio.qtgui.plot_from import plot_form except ImportError: from plot_form import plot_form class plot_psd_form(plot_form): def __init__(self, top_block, title=''): plot_form.__init__(self, top_block, title) self.right_col_layout = QtGui.QVBoxLayout() self.right_col_form = QtGui.QFormLayout() self.right_col_layout.addLayout(self.right_col_form) self.layout.addLayout(self.right_col_layout, 1,4,1,1) self.psd_size_val = QtGui.QIntValidator(0, 2**18, self) self.psd_size_edit = QtGui.QLineEdit(self) self.psd_size_edit.setMinimumWidth(50) self.psd_size_edit.setMaximumWidth(100) self.psd_size_edit.setText(QtCore.QString("%1").arg(top_block._psd_size)) self.psd_size_edit.setValidator(self.psd_size_val) self.right_col_form.addRow("FFT:", self.psd_size_edit) self.connect(self.psd_size_edit, QtCore.SIGNAL("returnPressed()"), self.update_psd_size) self.psd_win_combo = QtGui.QComboBox(self) self.psd_win_combo.addItems(["None", "Hamming", "Hann", "Blackman", "Rectangular", "Kaiser", "Blackman-harris"]) self.psd_win_combo.setCurrentIndex(self.top_block.gui_snk.fft_window()+1) self.right_col_form.addRow("Window:", self.psd_win_combo) self.connect(self.psd_win_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_psd_win) self.psd_avg_val = QtGui.QDoubleValidator(0, 1.0, 4, self) self.psd_avg_edit = QtGui.QLineEdit(self) self.psd_avg_edit.setMinimumWidth(50) self.psd_avg_edit.setMaximumWidth(100) self.psd_avg_edit.setText(QtCore.QString("%1").arg(top_block._avg)) self.psd_avg_edit.setValidator(self.psd_avg_val) self.right_col_form.addRow("Average:", self.psd_avg_edit) self.connect(self.psd_avg_edit, QtCore.SIGNAL("returnPressed()"), self.update_psd_avg) self.add_line_control(self.right_col_layout) def update_psd_size(self): newpsdsize = self.psd_size_edit.text().toInt()[0] if(newpsdsize != self.top_block._psd_size): self.top_block.gui_snk.set_fft_size(newpsdsize) self.top_block._psd_size = newpsdsize self.top_block.reset(self.top_block._start, self.top_block._nsamps) def update_psd_win(self, index): self.top_block.gui_snk.set_fft_window(index-1) self.top_block.reset(self.top_block._start, self.top_block._nsamps) def update_psd_avg(self): newpsdavg = self.psd_avg_edit.text().toDouble()[0] if(newpsdavg != self.top_block._avg): self.top_block.gui_snk.set_fft_average(newpsdavg) self.top_block._avg = newpsdavg self.top_block.reset(self.top_block._start, self.top_block._nsamps) gnuradio-3.7.2.1/gr-qtgui/apps/plot_spectrogram_form.py0000664000175000017500000001560112207440367023017 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from gnuradio import filter try: from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4." sys.exit(1) try: from gnuradio.qtgui.plot_from import plot_form except ImportError: from plot_form import plot_form class plot_spectrogram_form(plot_form): def __init__(self, top_block, title=''): plot_form.__init__(self, top_block, title) self.right_col_layout = QtGui.QVBoxLayout() self.right_col_form = QtGui.QFormLayout() self.right_col_layout.addLayout(self.right_col_form) self.layout.addLayout(self.right_col_layout, 1,4,1,1) self.psd_size_val = QtGui.QIntValidator(0, 2**18, self) self.psd_size_edit = QtGui.QLineEdit(self) self.psd_size_edit.setMinimumWidth(50) self.psd_size_edit.setMaximumWidth(100) self.psd_size_edit.setText(QtCore.QString("%1").arg(top_block._psd_size)) self.psd_size_edit.setValidator(self.psd_size_val) self.right_col_form.addRow("FFT Size:", self.psd_size_edit) self.connect(self.psd_size_edit, QtCore.SIGNAL("returnPressed()"), self.update_psd_size) self.psd_win_combo = QtGui.QComboBox(self) self.psd_win_combo.addItems(["None", "Hamming", "Hann", "Blackman", "Rectangular", "Kaiser", "Blackman-harris"]) self.psd_win_combo.setCurrentIndex(self.top_block.gui_snk.fft_window()+1) self.right_col_form.addRow("Window:", self.psd_win_combo) self.connect(self.psd_win_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_psd_win) self.psd_avg_val = QtGui.QDoubleValidator(0, 1.0, 4, self) self.psd_avg_edit = QtGui.QLineEdit(self) self.psd_avg_edit.setMinimumWidth(50) self.psd_avg_edit.setMaximumWidth(100) self.psd_avg_edit.setText(QtCore.QString("%1").arg(top_block._avg)) self.psd_avg_edit.setValidator(self.psd_avg_val) self.right_col_form.addRow("Average:", self.psd_avg_edit) self.connect(self.psd_avg_edit, QtCore.SIGNAL("returnPressed()"), self.update_psd_avg) self.autoscale_button = QtGui.QPushButton("Auto Scale", self) self.autoscale_button.setMaximumWidth(100) self.right_col_layout.addWidget(self.autoscale_button) self.connect(self.autoscale_button, QtCore.SIGNAL("clicked()"), self.spectrogram_auto_scale) self.add_spectrogram_control(self.right_col_layout) def update_psd_size(self): newpsdsize = self.psd_size_edit.text().toInt()[0] if(newpsdsize != self.top_block._psd_size): self.top_block.gui_snk.set_fft_size(newpsdsize) self.top_block._psd_size = newpsdsize self.top_block.reset(self.top_block._start, self.top_block._nsamps) def update_psd_win(self, index): self.top_block.gui_snk.set_fft_window(index-1) self.top_block.reset(self.top_block._start, self.top_block._nsamps) def update_psd_avg(self): newpsdavg = self.psd_avg_edit.text().toDouble()[0] if(newpsdavg != self.top_block._avg): self.top_block.gui_snk.set_fft_average(newpsdavg) self.top_block._avg = newpsdavg self.top_block.reset(self.top_block._start, self.top_block._nsamps) def add_spectrogram_control(self, layout): self._line_tabs = QtGui.QTabWidget() self._line_pages = [] self._line_forms = [] self._label_edit = [] self._size_edit = [] self._color_edit = [] self._style_edit = [] self._marker_edit = [] self._alpha_edit = [] for n in xrange(self.top_block._nsigs): self._line_pages.append(QtGui.QDialog()) self._line_forms.append(QtGui.QFormLayout(self._line_pages[-1])) label = self.top_block.gui_snk.line_label(n) self._label_edit.append(QtGui.QLineEdit(self)) self._label_edit[-1].setMinimumWidth(125) self._label_edit[-1].setMaximumWidth(125) self._label_edit[-1].setText(QtCore.QString("%1").arg(label)) self._line_forms[-1].addRow("Label:", self._label_edit[-1]) self.connect(self._label_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_label) self._qtcolormaps = ["Multi Color", "White Hot", "Black Hot", "Incandescent"] self._color_edit.append(QtGui.QComboBox(self)) self._color_edit[-1].addItems(self._qtcolormaps) self._line_forms[-1].addRow("Color Map:", self._color_edit[-1]) self.connect(self._color_edit[-1], QtCore.SIGNAL("currentIndexChanged(int)"), self.update_color_map) alpha_val = QtGui.QDoubleValidator(0, 1.0, 2, self) alpha_val.setTop(1.0) alpha = self.top_block.gui_snk.line_alpha(n) self._alpha_edit.append(QtGui.QLineEdit(self)) self._alpha_edit[-1].setMinimumWidth(50) self._alpha_edit[-1].setMaximumWidth(100) self._alpha_edit[-1].setText(QtCore.QString("%1").arg(alpha)) self._alpha_edit[-1].setValidator(alpha_val) self._line_forms[-1].addRow("Alpha:", self._alpha_edit[-1]) self.connect(self._alpha_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_alpha) self._line_tabs.addTab(self._line_pages[-1], "{0}".format(label)) layout.addWidget(self._line_tabs) def update_color_map(self, c_index): index = self._line_tabs.currentIndex() self.top_block.gui_snk.set_color_map(index, c_index) self.update_line_alpha() def spectrogram_auto_scale(self): self.top_block.gui_snk.auto_scale() _min = self.top_block.gui_snk.min_intensity(0) _max = self.top_block.gui_snk.max_intensity(0) if(self.gui_y_axis): self.gui_y_axis(_min, _max) gnuradio-3.7.2.1/gr-qtgui/apps/plot_constellation_form.py0000664000175000017500000000502612207440367023347 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from gnuradio import filter try: from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4." sys.exit(1) try: from gnuradio.qtgui.plot_from import plot_form except ImportError: from plot_form import plot_form class plot_constellation_form(plot_form): def __init__(self, top_block, title='', scale=1): plot_form.__init__(self, top_block, title, scale) self.right_col_layout = QtGui.QVBoxLayout() self.right_col_form = QtGui.QFormLayout() self.right_col_layout.addLayout(self.right_col_form) self.layout.addLayout(self.right_col_layout, 1,4,1,1) # Constellation resizing scales x and y together. # Set the bar to go from 0.001 to max self.ybar.setMinimum(1) self.ybar.setMaximum(self._pos_scale*self.top_block._y_max) self.ybar.setSingleStep(self._pos_scale*(max(self.top_block._y_range/10, 0.010))) self.ybar.setPageStep(self._pos_scale*(max(self.top_block._y_range/2, 0.010))) self.auto_scale = QtGui.QCheckBox("Auto Scale", self) if(self.top_block._auto_scale): self.auto_scale.setChecked(self.top_block._auto_scale) self.set_auto_scale(self.top_block._auto_scale) self.connect(self.auto_scale, QtCore.SIGNAL("stateChanged(int)"), self.set_auto_scale) self.right_col_layout.addWidget(self.auto_scale) self.ybar.setValue(1000*self.top_block._y_value) self.add_line_control(self.right_col_layout) def set_auto_scale(self, state): if(state): self.top_block.auto_scale(True) else: self.top_block.auto_scale(False) def update_samp_rate(self): pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_psd_plot_c0000775000175000017500000000515012207440367020600 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_psd_base as plot_base except ImportError: import plot_psd_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class psd_plot_c(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_c self.dsize = gr.sizeof_gr_complex self.src_type = blocks.vector_source_c self.gui_snk = qtgui.freq_sink_c(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio PSD Plot", self._nsigs) self.setup() def main(): description = "Plots the PSDs of a list of files. Files are a binary list of complex floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = psd_plot_c(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average) main_box = plot_base.plot_psd_form(tb, 'GNU Radio PSD Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/usrp_display_qtgui.ui0000644000175000017500000002527211700377701022325 0ustar jcorganjcorgan MainWindow 0 0 820 774 USRP Display 0 0 240 150 240 16777215 Receiver Parameters 10 20 221 124 Frequency (Hz) RF Gain Bandwidth 0 0 120 26 0 0 120 26 0 0 120 26 Amplifier 0 0 120 26 200 0 QFrame::StyledPanel QFrame::Raised 10 -1 191 151 Cancel DC DC Canceller Gain Qt::Vertical 20 40 Qt::Horizontal 40 20 Qt::Vertical QSizePolicy::Fixed 20 80 0 0 Pause 0 0 75 0 Close 0 1 800 550 QFrame::StyledPanel QFrame::Raised 0 0 820 24 &File E&xit &Save Data closeButton clicked() MainWindow close() 808 739 66 561 actionExit triggered() MainWindow close() -1 -1 617 327 gnuradio-3.7.2.1/gr-qtgui/apps/plot_base.py0000664000175000017500000001330512207440367020357 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import os, sys os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Scipy required (www.scipy.org)." sys.exit(1) try: from gnuradio.qtgui.plot_constellation_form import * from gnuradio.qtgui.plot_psd_form import * from gnuradio.qtgui.plot_spectrogram_form import * from gnuradio.qtgui.plot_time_form import * from gnuradio.qtgui.plot_time_raster_form import * except ImportError: from plot_constellation_form import * from plot_psd_form import * from plot_spectrogram_form import * from plot_time_form import * from plot_time_raster_form import * def read_samples(filename, start, in_size, min_size, dtype, dtype_size): # Read in_size number of samples from file fhandle = open(filename, 'r') fhandle.seek(start*dtype_size, 0) data = scipy.fromfile(fhandle, dtype=dtype, count=in_size) data_min = 1.1*data.min() data_max = 1.1*data.max() data = data.tolist() fhandle.close() if(min_size > 0): if(len(data) < in_size): print "Warning: read in {0} samples but asked for {1} samples.".format( len(data), in_size) else: # If we have to, append 0's to create min_size samples of data if(len(data) < min_size): data += (min_size - len(data)) * [dtype(0)] return data, data_min, data_max def read_samples_f(filename, start, in_size, min_size=0): return read_samples(filename, start, in_size, min_size, scipy.float32, gr.sizeof_float) def read_samples_i(filename, start, in_size, min_size=0): return read_samples(filename, start, in_size, min_size, scipy.int32, gr.sizeof_int) def read_samples_s(filename, start, in_size, min_size=0): return read_samples(filename, start, in_size, min_size, scipy.int16, gr.sizeof_short) def read_samples_b(filename, start, in_size, min_size=0): d,mn,mx = read_samples(filename, start, in_size, min_size, scipy.int8, gr.sizeof_char) # Bit of a hack since we want to read the data as signed ints, but # the blocks.vector_source_b will only accept unsigned. We read in as # signed, do our min/max and things on that, then convert here. d = scipy.array(d, dtype=scipy.uint8).tolist() return d,mn,mx def read_samples_c(filename, start, in_size, min_size=0): # Complex samples are handled differently fhandle = open(filename, 'r') fhandle.seek(start*gr.sizeof_gr_complex, 0) data = scipy.fromfile(fhandle, dtype=scipy.complex64, count=in_size) data_min = 1.1*float(min(data.real.min(), data.imag.min())) data_max = 1.1*float(max(data.real.max(), data.imag.max())) data = data.tolist() fhandle.close() if(min_size > 0): if(len(data) < in_size): print "Warning: read in {0} samples but asked for {1} samples.".format( len(data), in_size) else: # If we have to, append 0's to create min_size samples of data if(len(data) < min_size): data += (min_size - len(data)) * [complex(0,0)] return data, data_min, data_max class source_ints_to_float(gr.hier_block2): def __init__(self, data): gr.hier_block2.__init__(self, "ints_to_floats", gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_float)) self.src = blocks.vector_source_i(data) self.cvt = blocks.int_to_float() self.connect(self.src, self.cvt, self) def set_data(self, data): self.src.set_data(data) class source_shorts_to_float(gr.hier_block2): def __init__(self, data): gr.hier_block2.__init__(self, "shorts_to_floats", gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_float)) self.src = blocks.vector_source_s(data) self.cvt = blocks.short_to_float() self.connect(self.src, self.cvt, self) def set_data(self, data): self.src.set_data(data) class source_chars_to_float(gr.hier_block2): def __init__(self, data): gr.hier_block2.__init__(self, "chars_to_floats", gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_float)) self.src = blocks.vector_source_b(data) self.cvt = blocks.char_to_float() self.connect(self.src, self.cvt, self) def set_data(self, data): self.src.set_data(data) def find_max_nsamples(filelist): # Find the smallest number of samples in all files and use that as # a maximum value possible. filesizes = [] for f in filelist: if(os.path.exists(f)): filesizes.append(os.path.getsize(f) / gr.sizeof_gr_complex) max_nsamples = min(filesizes) return max_nsamples gnuradio-3.7.2.1/gr-qtgui/apps/gr_psd_plot_s0000775000175000017500000000512612207440367020623 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_psd_base as plot_base except ImportError: import plot_psd_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class psd_plot_s(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0, auto_scale=True): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_s self.dsize = gr.sizeof_float self.src_type = plot_base.source_shorts_to_float self.gui_snk = qtgui.freq_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio PSD Plot", self._nsigs) self.setup() def main(): description = "Plots the PSDs of a list of files. Files are a binary list of shorts." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = psd_plot_s(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average) main_box = plot_base.plot_psd_form(tb, 'GNU Radio PSD Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_spectrogram_plot_i0000775000175000017500000000527612207440367022357 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_spectrogram_base as plot_base except ImportError: import plot_spectrogram_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class spectrogram_plot_i(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_i self.dsize = gr.sizeof_float self.src_type = plot_base.source_ints_to_float self.gui_snk = qtgui.waterfall_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio Spectrogram Plot", self._nsigs) self.setup() def main(): description = "Plots the spectrogram (waterfall) of a list of files. Files are a binary list of ints." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = spectrogram_plot_i(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average); main_box = plot_base.plot_spectrogram_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_psd_plot_b0000775000175000017500000000512412207440367020600 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_psd_base as plot_base except ImportError: import plot_psd_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class psd_plot_b(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0, auto_scale=True): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_b self.dsize = gr.sizeof_float self.src_type = plot_base.source_chars_to_float self.gui_snk = qtgui.freq_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio PSD Plot", self._nsigs) self.setup() def main(): description = "Plots the PSDs of a list of files. Files are a binary list of bytes." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = psd_plot_b(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average) main_box = plot_base.plot_psd_form(tb, 'GNU Radio PSD Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_spectrogram_plot_c0000775000175000017500000000535012207440367022342 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_spectrogram_base as plot_base except ImportError: import plot_spectrogram_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class spectrogram_plot_c(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_c self.dsize = gr.sizeof_gr_complex self.src_type = blocks.vector_source_c self.gui_snk = qtgui.waterfall_sink_c(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio Spectrogram Plot", self._nsigs) self.setup() def main(): description = "Plots the spectrogram (waterfall) of a list of files. Files are a binary list of complex floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = spectrogram_plot_c(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average); main_box = plot_base.plot_spectrogram_form(tb, 'GNU Radio Spectrogram Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_plot_s0000775000175000017500000000463712207440367021001 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import scipy try: import gnuradio.qtgui.plot_time_base as plot_base except ImportError: import plot_time_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_s(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self.read_samples = plot_base.read_samples_s self.dsize = gr.sizeof_float # already converted self.src_type = plot_base.source_shorts_to_float self.gui_snk = qtgui.time_sink_f(self._nsamps, self._samp_rate, "GNU Radio Time Plot", self._nsigs) self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of shorts." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_s(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, not options.no_auto_scale) main_box = plot_base.plot_time_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/grc_qt_example.grc0000664000175000017500000002163112207440367021525 0ustar jcorganjcorgan Sat Nov 10 14:58:46 2012 options id grc_qt_example _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (10, 170) _rotation 0 variable_qtgui_range id freq _enabled True label Signal Frequency value 1000 start 0 stop samp_rate/2.0 step samp_rate/100.0 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (169, 187) _rotation 0 variable_qtgui_range id amp _enabled True label Signal Amplitude value 1 start 0 stop 1.0 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (311, 187) _rotation 0 variable_qtgui_range id noise _enabled True label Noise Amplitude value 0.01 start 0 stop 1.0 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (723, 191) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (511, 96) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise freq_offset 0.0 epsilon 1.0 taps 1.0 + 0.0j seed -42 _coordinate (724, 64) _rotation 0 qtgui_sink_x id qtgui_sink_x_0 _enabled True type complex name QT GUI Plot fftsize 1024 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate rate 10 plotfreq True plotwaterfall True plottime True plotconst False gui_hint freqchangevar None _coordinate (958, 64) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq freq amp amp offset 0 _coordinate (297, 64) _rotation 0 analog_sig_source_x_0 blocks_throttle_0 0 0 channels_channel_model_0 qtgui_sink_x_0 0 0 blocks_throttle_0 channels_channel_model_0 0 0 gnuradio-3.7.2.1/gr-qtgui/apps/plot_spectrogram_base.py0000664000175000017500000001255312207440367022771 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import os, sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Scipy required (www.scipy.org)." sys.exit(1) try: from gnuradio.qtgui.plot_form import * from gnuradio.qtgui.plot_base import * except ImportError: from plot_form import * from plot_base import * class plot_base(gr.top_block): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): gr.top_block.__init__(self) self._filelist = filelist self._center_freq = fc self._samp_rate = samp_rate self._psd_size = psdsize self._start = start self._max_nsamps = max_nsamples self._nsigs = len(self._filelist) self._avg = avg self._nsamps = nsamples self._auto_scale = False self._y_min = -200 self._y_max = 400 self._y_range = 130 self._y_value = 10 self._is_setup = False self.qapp = QtGui.QApplication(sys.argv) def setup(self): self.skip = blocks.skiphead(self.dsize, self._start) n = 0 self.srcs = list() self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for f in self._filelist: data,_min,_max = self.read_samples(f, self._start, self._nsamps, self._psd_size) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max self.srcs.append(self.src_type(data)) # Set default labels based on file names fname = f.split("/")[-1] self.gui_snk.set_line_label(n, "{0}".format(fname)) n += 1 self.connect(self.srcs[0], self.skip) self.connect(self.skip, (self.gui_snk, 0)) for i,s in enumerate(self.srcs[1:]): self.connect(s, (self.gui_snk, i+1)) self.gui_snk.set_update_time(0); self.gui_snk.enable_menu(False) self.gui_snk.set_fft_average(self._avg) # Get Python Qt references pyQt = self.gui_snk.pyqwidget() self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self._is_setup = True def is_setup(self): return self._is_setup def set_y_axis(self, y_min, y_max): self.gui_snk.set_intensity_range(y_min, y_max) return y_min, y_max def get_gui(self): if(self.is_setup()): return self.pyWin else: return None def reset(self, newstart, newnsamps): self.stop() self.wait() self.gui_snk.clear_data() self._start = newstart self._nsamps = newnsamps self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for s,f in zip(self.srcs, self._filelist): data,_min,_max = self.read_samples(f, self._start, newnsamps, self._psd_size) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max s.set_data(data) self.start() def setup_options(desc): parser = OptionParser(option_class=eng_option, description=desc, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=1000000, help="Set the number of samples to display [default=%default]") parser.add_option("-S", "--start", type="int", default=0, help="Starting sample number [default=%default]") parser.add_option("-L", "--psd-size", type="int", default=2048, help="Set the FFT size of the PSD [default=%default]") parser.add_option("-f", "--center-frequency", type="eng_float", default=0.0, help="Set the center frequency of the signal [default=%default]") parser.add_option("-r", "--sample-rate", type="eng_float", default=1.0, help="Set the sample rate of the signal [default=%default]") parser.add_option("-a", "--average", type="float", default=1.0, help="Set amount of averaging (smaller=more averaging) [default=%default]") (options, args) = parser.parse_args() if(len(args) < 1): parser.print_help() sys.exit(0) return (options, args) gnuradio-3.7.2.1/gr-qtgui/apps/gr_constellation_plot0000775000175000017500000001326012207440367022367 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import os, sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Scipy required (www.scipy.org)." sys.exit(1) try: from gnuradio.qtgui.plot_constellation_form import * from gnuradio.qtgui.plot_base import * except ImportError: from plot_constellation_form import * from plot_base import * class my_top_block(gr.top_block): def __init__(self, filelist, start, nsamples, max_nsamples): gr.top_block.__init__(self) self._filelist = filelist self._samp_rate = 0 self._center_freq = 0 self._start = start self._max_nsamps = max_nsamples self._nsigs = len(self._filelist) self._nsamps = nsamples self._auto_scale = True self._y_min = -20 self._y_max = 20 self._y_range = 4 self._y_value = 2 self.gui_y_axis = None self.qapp = QtGui.QApplication(sys.argv) self.skip = blocks.skiphead(gr.sizeof_gr_complex, self._start) self.gui_snk = qtgui.const_sink_c(self._nsamps, "GNU Radio Constellation Plot", self._nsigs) n = 0 self.srcs = list() self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for f in filelist: data,_min,_max = read_samples_c(f, self._start, self._nsamps) self.srcs.append(blocks.vector_source_c(data)) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max # Set default labels based on file names fname = f.split("/")[-1] self.gui_snk.set_line_label(n, "{0}".format(fname)) n += 1 self.connect(self.srcs[0], self.skip) self.connect(self.skip, (self.gui_snk, 0)) for i,s in enumerate(self.srcs[1:]): self.connect(s, (self.gui_snk, i+1)) self.gui_snk.enable_menu(False) # Get Python Qt references pyQt = self.gui_snk.pyqwidget() self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) def get_gui(self): return self.pyWin def reset(self, newstart, newnsamps): self.stop() self.wait() self._start = newstart for s,f in zip(self.srcs, self._filelist): data,_min,_max = read_samples_c(f, self._start, newnsamps) s.set_data(data) if(len(data) < newnsamps): newnsamps = len(data) self._nsamps = newnsamps self.gui_snk.set_nsamps(self._nsamps) self.start() def set_y_axis(self, y_min, y_max): y_min = -y_max self.gui_snk.set_y_axis(y_min, y_max) self.gui_snk.set_x_axis(y_min, y_max) return y_min, y_max def auto_scale(self, state): if(state > 0): self.set_y_axis(self._data_min, self._data_max) self._auto_scale = True self._y_value = self._data_max self._y_range = self._data_max - self._data_min self._y_min = 10*self._data_min self._y_max = 10*self._data_max if(self.gui_y_axis): self.gui_y_axis(self._data_min, self._data_max) else: self._auto_scale = False def main(): description = "Plots the constellations of a list of files." parser = OptionParser(option_class=eng_option, description=description, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=1000000, help="Set the number of samples to display [default=%default]") parser.add_option("-S", "--start", type="int", default=0, help="Starting sample number [default=%default]") (options, args) = parser.parse_args() if(len(args) < 1): parser.print_help() sys.exit(0) filelist = list(args) nsamples = options.nsamples # Find the smallest number of samples in all files and use that as # a maximum value possible. filesizes = [] for f in filelist: if(os.path.exists(f)): filesizes.append(os.path.getsize(f) / gr.sizeof_gr_complex) max_nsamples = min(filesizes) tb = my_top_block(filelist, options.start, nsamples, max_nsamples); main_box = plot_constellation_form(tb, 'GNU Radio Constellation Plot', 10000.0) for n in xrange(tb._nsigs): main_box._style_edit[n].setCurrentIndex(0) main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/plot_form.py0000664000175000017500000004176112207440367020417 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # try: from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4." sys.exit(1) import numpy class plot_form(QtGui.QWidget): def __init__(self, top_block, title='', scale=1): QtGui.QWidget.__init__(self, None) self._start = 0 self._end = 0 self._y_min = 0 self._y_max = 0 self._pos_scale = scale self.top_block = top_block self.top_block.gui_y_axis = self.gui_y_axis self.setWindowTitle(title) self.layout = QtGui.QGridLayout(self) self.layout.addWidget(top_block.get_gui(), 1,2,1,2) # Create a save action self.save_act = QtGui.QAction("Save", self) self.save_act.setShortcut(QtGui.QKeySequence.Save) self.connect(self.save_act, QtCore.SIGNAL("triggered()"), self.save_figure) # Create an exit action self.exit_act = QtGui.QAction("Exit", self) self.exit_act.setShortcut(QtGui.QKeySequence.Close) self.connect(self.exit_act, QtCore.SIGNAL("triggered()"), self.close) # Create a menu for the window self.menu = QtGui.QToolBar("Menu", self) self.menu.addAction(self.save_act) self.menu.addAction(self.exit_act) self.layout.addWidget(self.menu, 0,0,1,4) self.left_col_form = QtGui.QFormLayout() self.layout.addLayout(self.left_col_form, 1,0,1,1) self.layout.setColumnStretch(0, 0) self.layout.setColumnStretch(2, 1) # Create Edit boxes for X-axis start/stop self.size_val = QtGui.QIntValidator(0, top_block._max_nsamps, self) self.start_edit = QtGui.QLineEdit(self) self.start_edit.setMinimumWidth(100) self.start_edit.setMaximumWidth(100) self.start_edit.setText(QtCore.QString("%1").arg(top_block._start)) self.start_edit.setValidator(self.size_val) self.left_col_form.addRow("Start:", self.start_edit) self.connect(self.start_edit, QtCore.SIGNAL("returnPressed()"), self.update_xaxis_pos) end = top_block._start + top_block._nsamps self.end_edit = QtGui.QLineEdit(self) self.end_edit.setMinimumWidth(100) self.end_edit.setMaximumWidth(100) self.end_edit.setText(QtCore.QString("%1").arg(end)) self.end_edit.setValidator(self.size_val) self.left_col_form.addRow("End:", self.end_edit) self.connect(self.end_edit, QtCore.SIGNAL("returnPressed()"), self.update_xaxis_pos) # Create a slider to move the position in the file self.posbar = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.posbar.setMaximum(self.top_block._max_nsamps) self.posbar.setPageStep(self.top_block._nsamps) self.connect(self.posbar, QtCore.SIGNAL("valueChanged(int)"), self.update_xaxis_slider) self.layout.addWidget(self.posbar, 2,2,1,1) # Create Edit boxes for Y-axis min/max self.y_max_edit = QtGui.QLineEdit(self) self.y_max_edit.setMinimumWidth(100) self.y_max_edit.setMaximumWidth(100) self.left_col_form.addRow("Y Max:", self.y_max_edit) self.connect(self.y_max_edit, QtCore.SIGNAL("editingFinished()"), self.update_yaxis_pos) self.y_min_edit = QtGui.QLineEdit(self) self.y_min_edit.setMinimumWidth(100) self.y_min_edit.setMaximumWidth(100) self.left_col_form.addRow("Y Min:", self.y_min_edit) self.connect(self.y_min_edit, QtCore.SIGNAL("editingFinished()"), self.update_yaxis_pos) self.grid_check = QtGui.QCheckBox("Grid", self) self.connect(self.grid_check, QtCore.SIGNAL("stateChanged(int)"), self.set_grid_check) self.left_col_form.addWidget(self.grid_check) # Create a slider to move the plot's y-axis offset _ymax = numpy.int32(min(numpy.iinfo(numpy.int32).max, self.top_block._y_max)) _ymin = numpy.int32(max(numpy.iinfo(numpy.int32).min, self.top_block._y_min)) _yrng = numpy.int32(min(numpy.iinfo(numpy.int32).max, self.top_block._y_range)) _yval = numpy.int32(min(numpy.iinfo(numpy.int32).max, self.top_block._y_value)) self.ybar = QtGui.QSlider(QtCore.Qt.Vertical, self) self.ybar.setMinimum(self._pos_scale*_ymin) self.ybar.setMaximum(self._pos_scale*_ymax) self.ybar.setSingleStep(self._pos_scale*(_yrng/10)) self.ybar.setPageStep(self._pos_scale*(_yrng/2)) self.ybar.setValue(self._pos_scale*_ymax) self.connect(self.ybar, QtCore.SIGNAL("valueChanged(int)"), self.update_yaxis_slider) self.layout.addWidget(self.ybar, 1,1,1,1) self.gui_y_axis(top_block._y_value-top_block._y_range, top_block._y_value) # Create an edit box for the Sample Rate sr = top_block._samp_rate self.samp_rate_edit = QtGui.QLineEdit(self) self.samp_rate_edit.setMinimumWidth(100) self.samp_rate_edit.setMaximumWidth(100) self.samp_rate_edit.setText(QtCore.QString("%1").arg(sr)) self.left_col_form.addRow("Sample Rate:", self.samp_rate_edit) self.connect(self.samp_rate_edit, QtCore.SIGNAL("returnPressed()"), self.update_samp_rate) # Create an edit box for the center frequency freq = top_block._center_freq self.freq_edit = QtGui.QLineEdit(self) self.freq_edit.setMinimumWidth(100) self.freq_edit.setMaximumWidth(100) self.freq_edit.setText(QtCore.QString("%1").arg(freq)) self.left_col_form.addRow("Frequency:", self.freq_edit) self.connect(self.freq_edit, QtCore.SIGNAL("returnPressed()"), self.update_samp_rate) self.resize(1000, 500) def add_line_control(self, layout): self._line_tabs = QtGui.QTabWidget() self._line_pages = [] self._line_forms = [] self._label_edit = [] self._size_edit = [] self._color_edit = [] self._style_edit = [] self._marker_edit = [] self._alpha_edit = [] for n in xrange(self.top_block._nsigs): self._line_pages.append(QtGui.QDialog()) self._line_forms.append(QtGui.QFormLayout(self._line_pages[-1])) label = self.top_block.gui_snk.line_label(n) self._label_edit.append(QtGui.QLineEdit(self)) self._label_edit[-1].setMinimumWidth(125) self._label_edit[-1].setMaximumWidth(125) self._label_edit[-1].setText(QtCore.QString("%1").arg(label)) self._line_forms[-1].addRow("Label:", self._label_edit[-1]) self.connect(self._label_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_label) width_val = QtGui.QIntValidator(1, 20, self) self._size_edit.append(QtGui.QLineEdit(self)) self._size_edit[-1].setValidator(width_val) self._size_edit[-1].setMinimumWidth(100) self._size_edit[-1].setMaximumWidth(100) self._size_edit[-1].setText(QtCore.QString("%1").arg(1)) self._line_forms[-1].addRow("Width:", self._size_edit[-1]) self.connect(self._size_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_size) color = self.top_block.gui_snk.line_color(n) self._color_edit.append(QtGui.QLineEdit(self)) self._color_edit[-1].setMinimumWidth(100) self._color_edit[-1].setMaximumWidth(100) self._color_edit[-1].setText(QtCore.QString("%1").arg(color)) self._line_forms[-1].addRow("Color:", self._color_edit[-1]) self.connect(self._color_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_color) self._qtstyles = {"None": QtCore.Qt.NoPen, "Solid": QtCore.Qt.SolidLine, "Dash": QtCore.Qt.DashLine, "Dot": QtCore.Qt.DotLine, "DashDot": QtCore.Qt.DashDotLine, "DashDotDot": QtCore.Qt.DashDotDotLine} self._style_edit.append(QtGui.QComboBox(self)) self._style_edit[-1].addItems(["None", "Solid", "Dash", "Dot", "DashDot", "DashDotDot"]) self._style_edit[-1].setCurrentIndex(1) self._line_forms[-1].addRow("Style:", self._style_edit[-1]) self.connect(self._style_edit[-1], QtCore.SIGNAL("currentIndexChanged(int)"), self.update_line_style) # A bit dangerous, this. If QWT ever changes the lineup, # we will have to adjust this, too. But we also can't # really rely on PyQwt right now. self._qwtmarkers = {"None": -1, "Circle": 0, "Rectangle": 1, "Diamond": 2, "Triangle": 3, "Down Triangle": 4, "Left Triangle": 6, "Right Triangle": 7, "Cross": 8, "X-Cross": 9, "Horiz. Line": 10, "Vert. Line": 11, "Star 1": 12, "Star 2": 13, "Hexagon": 14} self._marker_edit.append(QtGui.QComboBox(self)) self._marker_edit[-1].addItems(["None", "Circle", "Rectangle", "Diamond", "Triangle", "Down Triangle", "Left Triangle", "Right Triangle", "Cross", "X-Cross", "Horiz. Line", "Vert. Line", "Star 1", "Star 2", "Hexagon"]) self._line_forms[-1].addRow("Marker:", self._marker_edit[-1]) self.connect(self._marker_edit[-1], QtCore.SIGNAL("currentIndexChanged(int)"), self.update_line_marker) alpha_val = QtGui.QDoubleValidator(0, 1.0, 2, self) alpha_val.setTop(1.0) alpha = self.top_block.gui_snk.line_alpha(n) self._alpha_edit.append(QtGui.QLineEdit(self)) self._alpha_edit[-1].setMinimumWidth(50) self._alpha_edit[-1].setMaximumWidth(100) self._alpha_edit[-1].setText(QtCore.QString("%1").arg(alpha)) self._alpha_edit[-1].setValidator(alpha_val) self._line_forms[-1].addRow("Alpha:", self._alpha_edit[-1]) self.connect(self._alpha_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_alpha) self._line_tabs.addTab(self._line_pages[-1], "{0}".format(label)) layout.addWidget(self._line_tabs) def update_line_label(self): index = self._line_tabs.currentIndex() label = self._label_edit[index].text() self._line_tabs.setTabText(index, label) self.top_block.gui_snk.set_line_label(index, str(label)) def update_line_size(self): index = self._line_tabs.currentIndex() width = self._size_edit[index].text().toUInt()[0] self.top_block.gui_snk.set_line_width(index, width) self.update_line_alpha() def update_line_color(self): index = self._line_tabs.currentIndex() color = str(self._color_edit[index].text()) self.top_block.gui_snk.set_line_color(index, color) self.update_line_alpha() def update_line_style(self, s_index): index = self._line_tabs.currentIndex() style_str = self._style_edit[index].itemText(s_index) style = self._qtstyles[str(style_str)] self.top_block.gui_snk.set_line_style(index, int(style)) def update_line_marker(self, m_index): index = self._line_tabs.currentIndex() marker_str = self._marker_edit[index].itemText(m_index) marker = self._qwtmarkers[str(marker_str)] self.top_block.gui_snk.set_line_marker(index, int(marker)) def update_line_alpha(self): index = self._line_tabs.currentIndex() alpha = self._alpha_edit[index].text().toDouble()[0] self.top_block.gui_snk.set_line_alpha(index, alpha) def update_xaxis_pos(self): newstart = self.start_edit.text().toUInt()[0] newend = self.end_edit.text().toUInt()[0] if(newstart != self._start or newend != self._end): if(newend < newstart): QtGui.QMessageBox.information( self, "Warning", "End sample is less than start sample.", QtGui.QMessageBox.Ok); else: newnsamps = newend - newstart self.top_block.reset(newstart, newnsamps) self._start = newstart self._end = newend self.posbar.setPageStep(self.top_block._nsamps) self.posbar.setValue(self._start) def update_xaxis_slider(self, value): self._start = value self._end = value + self.posbar.pageStep() self.start_edit.setText("{0}".format(self._start)) self.end_edit.setText("{0}".format(self._end)) if(value != self.top_block._max_nsamps): self.top_block.reset(self._start, self.posbar.pageStep()) def update_yaxis_pos(self): if(not self.top_block._auto_scale): newmin = self.y_min_edit.text().toDouble()[0] newmax = self.y_max_edit.text().toDouble()[0] if(newmin != self._y_min or newmax != self._y_max): self._y_min = newmin self._y_max = newmax self.top_block._y_range = newmax - newmin self.top_block.set_y_axis(self._y_min, self._y_max) self.ybar.setValue(self._y_max*self._pos_scale) else: self.y_min_edit.setText("{0:.2f}".format(self._y_min)) self.y_max_edit.setText("{0:.2f}".format(self._y_max)) def update_yaxis_slider(self, value): if(not self.top_block._auto_scale): value = value/self._pos_scale self.top_block._y_value = value self._y_min = value - self.top_block._y_range self._y_max = value ret = self.top_block.set_y_axis(self._y_min, self._y_max) if(ret): self._y_min = ret[0] self._y_max = ret[1] self.gui_y_axis(self._y_min, self._y_max) else: self.ybar.setValue(self._y_max*self._pos_scale) def update_samp_rate(self): sr = self.samp_rate_edit.text().toDouble()[0] fr = self.freq_edit.text().toDouble()[0] self.top_block.gui_snk.set_frequency_range(fr, sr) self.top_block.reset(self.top_block._start, self.top_block._nsamps) def gui_y_axis(self, ymin, ymax): self.y_min_edit.setText("{0:.2f}".format(ymin)) self.y_max_edit.setText("{0:.2f}".format(ymax)) self._y_min = ymin self._y_max = ymax self.ybar.setValue(self._pos_scale*ymax) def set_grid_check(self, state): if(state): self.top_block.gui_snk.enable_grid(True) else: self.top_block.gui_snk.enable_grid(False) def save_figure(self): qpix = QtGui.QPixmap.grabWidget(self.top_block.pyWin) types = "JPEG file (*.jpg);;" + \ "Portable Network Graphics file (*.png);;" + \ "Bitmap file (*.bmp);;" + \ "TIFF file (*.tiff)" filebox = QtGui.QFileDialog(self, "Save Image", "./", types) filebox.setViewMode(QtGui.QFileDialog.Detail) if(filebox.exec_()): filename = filebox.selectedFiles()[0] filetype = filebox.selectedNameFilter() else: return if(filetype.contains(".jpg")): qpix.save(filename, "JPEG"); elif(filetype.contains(".png")): qpix.save(filename, "PNG"); elif(filetype.contains(".bmp")): qpix.save(filename, "BMP"); elif(filetype.contains(".tiff")): qpix.save(filename, "TIFF"); else: qpix.save(filename, "JPEG"); gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_plot_b0000775000175000017500000000463512207440367020756 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr import scipy try: import gnuradio.qtgui.plot_time_base as plot_base except ImportError: import plot_time_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_b(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self.read_samples = plot_base.read_samples_b self.dsize = gr.sizeof_float # already converted self.src_type = plot_base.source_chars_to_float self.gui_snk = qtgui.time_sink_f(self._nsamps, self._samp_rate, "GNU Radio Time Plot", self._nsigs) self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of chars." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_b(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, not options.no_auto_scale) main_box = plot_base.plot_time_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/usrp_display_qtgui.py0000644000175000017500000002736111700377701022341 0ustar jcorganjcorgan# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'usrp_display_qtgui.ui' # # Created: Thu Jul 16 22:06:24 2009 # by: PyQt4 UI code generator 4.4.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(820, 774) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName("gridLayout_2") self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.groupBox = QtGui.QGroupBox(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth()) self.groupBox.setSizePolicy(sizePolicy) self.groupBox.setMinimumSize(QtCore.QSize(240, 150)) self.groupBox.setMaximumSize(QtCore.QSize(240, 16777215)) self.groupBox.setObjectName("groupBox") self.formLayoutWidget = QtGui.QWidget(self.groupBox) self.formLayoutWidget.setGeometry(QtCore.QRect(10, 20, 221, 124)) self.formLayoutWidget.setObjectName("formLayoutWidget") self.formLayout = QtGui.QFormLayout(self.formLayoutWidget) self.formLayout.setObjectName("formLayout") self.frequencyLabel = QtGui.QLabel(self.formLayoutWidget) self.frequencyLabel.setObjectName("frequencyLabel") self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.frequencyLabel) self.gainLabel = QtGui.QLabel(self.formLayoutWidget) self.gainLabel.setObjectName("gainLabel") self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.gainLabel) self.bandwidthLabel = QtGui.QLabel(self.formLayoutWidget) self.bandwidthLabel.setObjectName("bandwidthLabel") self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.bandwidthLabel) self.frequencyEdit = QtGui.QLineEdit(self.formLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frequencyEdit.sizePolicy().hasHeightForWidth()) self.frequencyEdit.setSizePolicy(sizePolicy) self.frequencyEdit.setMinimumSize(QtCore.QSize(120, 26)) self.frequencyEdit.setObjectName("frequencyEdit") self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.frequencyEdit) self.gainEdit = QtGui.QLineEdit(self.formLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.gainEdit.sizePolicy().hasHeightForWidth()) self.gainEdit.setSizePolicy(sizePolicy) self.gainEdit.setMinimumSize(QtCore.QSize(120, 26)) self.gainEdit.setObjectName("gainEdit") self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.gainEdit) self.bandwidthEdit = QtGui.QLineEdit(self.formLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.bandwidthEdit.sizePolicy().hasHeightForWidth()) self.bandwidthEdit.setSizePolicy(sizePolicy) self.bandwidthEdit.setMinimumSize(QtCore.QSize(120, 26)) self.bandwidthEdit.setObjectName("bandwidthEdit") self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.bandwidthEdit) self.amplifierLabel = QtGui.QLabel(self.formLayoutWidget) self.amplifierLabel.setObjectName("amplifierLabel") self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.amplifierLabel) self.amplifierEdit = QtGui.QLineEdit(self.formLayoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.amplifierEdit.sizePolicy().hasHeightForWidth()) self.amplifierEdit.setSizePolicy(sizePolicy) self.amplifierEdit.setMinimumSize(QtCore.QSize(120, 26)) self.amplifierEdit.setObjectName("amplifierEdit") self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.amplifierEdit) self.horizontalLayout_2.addWidget(self.groupBox) self.frame_2 = QtGui.QFrame(self.centralwidget) self.frame_2.setMinimumSize(QtCore.QSize(200, 0)) self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtGui.QFrame.Raised) self.frame_2.setObjectName("frame_2") self.verticalLayoutWidget = QtGui.QWidget(self.frame_2) self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, -1, 191, 151)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout_3 = QtGui.QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout_3.setObjectName("verticalLayout_3") self.dcCancelCheckBox = QtGui.QCheckBox(self.verticalLayoutWidget) self.dcCancelCheckBox.setObjectName("dcCancelCheckBox") self.verticalLayout_3.addWidget(self.dcCancelCheckBox) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.dcGainLabel = QtGui.QLabel(self.verticalLayoutWidget) self.dcGainLabel.setObjectName("dcGainLabel") self.horizontalLayout.addWidget(self.dcGainLabel) self.dcGainEdit = QtGui.QLineEdit(self.verticalLayoutWidget) self.dcGainEdit.setObjectName("dcGainEdit") self.horizontalLayout.addWidget(self.dcGainEdit) self.verticalLayout_3.addLayout(self.horizontalLayout) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout_3.addItem(spacerItem) self.horizontalLayout_2.addWidget(self.frame_2) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem1) self.verticalLayout = QtGui.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") spacerItem2 = QtGui.QSpacerItem(20, 80, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed) self.verticalLayout.addItem(spacerItem2) self.pauseButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pauseButton.sizePolicy().hasHeightForWidth()) self.pauseButton.setSizePolicy(sizePolicy) self.pauseButton.setObjectName("pauseButton") self.verticalLayout.addWidget(self.pauseButton) self.closeButton = QtGui.QPushButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.closeButton.sizePolicy().hasHeightForWidth()) self.closeButton.setSizePolicy(sizePolicy) self.closeButton.setMinimumSize(QtCore.QSize(75, 0)) self.closeButton.setObjectName("closeButton") self.verticalLayout.addWidget(self.closeButton) self.horizontalLayout_2.addLayout(self.verticalLayout) self.gridLayout_2.addLayout(self.horizontalLayout_2, 1, 0, 1, 1) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.frame = QtGui.QFrame(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.frame.sizePolicy().hasHeightForWidth()) self.frame.setSizePolicy(sizePolicy) self.frame.setMinimumSize(QtCore.QSize(800, 550)) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) self.frame.setFrameShadow(QtGui.QFrame.Raised) self.frame.setObjectName("frame") self.gridLayout = QtGui.QGridLayout(self.frame) self.gridLayout.setObjectName("gridLayout") self.sinkLayout = QtGui.QHBoxLayout() self.sinkLayout.setObjectName("sinkLayout") self.gridLayout.addLayout(self.sinkLayout, 0, 0, 1, 1) self.verticalLayout_2.addWidget(self.frame) self.gridLayout_2.addLayout(self.verticalLayout_2, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 24)) self.menubar.setObjectName("menubar") self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionExit = QtGui.QAction(MainWindow) self.actionExit.setObjectName("actionExit") self.actionSaveData = QtGui.QAction(MainWindow) self.actionSaveData.setObjectName("actionSaveData") self.menuFile.addAction(self.actionSaveData) self.menuFile.addAction(self.actionExit) self.menubar.addAction(self.menuFile.menuAction()) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL("clicked()"), MainWindow.close) QtCore.QObject.connect(self.actionExit, QtCore.SIGNAL("triggered()"), MainWindow.close) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "USRP Display", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox.setTitle(QtGui.QApplication.translate("MainWindow", "Receiver Parameters", None, QtGui.QApplication.UnicodeUTF8)) self.frequencyLabel.setText(QtGui.QApplication.translate("MainWindow", "Frequency (Hz)", None, QtGui.QApplication.UnicodeUTF8)) self.gainLabel.setText(QtGui.QApplication.translate("MainWindow", "RF Gain", None, QtGui.QApplication.UnicodeUTF8)) self.bandwidthLabel.setText(QtGui.QApplication.translate("MainWindow", "Bandwidth", None, QtGui.QApplication.UnicodeUTF8)) self.amplifierLabel.setText(QtGui.QApplication.translate("MainWindow", "Amplifier", None, QtGui.QApplication.UnicodeUTF8)) self.dcCancelCheckBox.setText(QtGui.QApplication.translate("MainWindow", "Cancel DC", None, QtGui.QApplication.UnicodeUTF8)) self.dcGainLabel.setText(QtGui.QApplication.translate("MainWindow", "DC Canceller Gain", None, QtGui.QApplication.UnicodeUTF8)) self.pauseButton.setText(QtGui.QApplication.translate("MainWindow", "Pause", None, QtGui.QApplication.UnicodeUTF8)) self.closeButton.setText(QtGui.QApplication.translate("MainWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "&File", None, QtGui.QApplication.UnicodeUTF8)) self.actionExit.setText(QtGui.QApplication.translate("MainWindow", "E&xit", None, QtGui.QApplication.UnicodeUTF8)) self.actionSaveData.setText(QtGui.QApplication.translate("MainWindow", "&Save Data", None, QtGui.QApplication.UnicodeUTF8)) gnuradio-3.7.2.1/gr-qtgui/apps/plot_psd_base.py0000664000175000017500000001235612207440367021232 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import os, sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Scipy required (www.scipy.org)." sys.exit(1) try: from gnuradio.qtgui.plot_form import * from gnuradio.qtgui.plot_base import * except ImportError: from plot_form import * from plot_base import * class plot_base(gr.top_block): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): gr.top_block.__init__(self) self._filelist = filelist self._center_freq = fc self._samp_rate = samp_rate self._psd_size = psdsize self._start = start self._max_nsamps = max_nsamples self._nsigs = len(self._filelist) self._avg = avg self._nsamps = nsamples self._auto_scale = False self._y_min = -200 self._y_max = 400 self._y_range = 130 self._y_value = 10 self._is_setup = False self.qapp = QtGui.QApplication(sys.argv) def setup(self): self.skip = blocks.skiphead(self.dsize, self._start) n = 0 self.srcs = list() self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for f in self._filelist: data,_min,_max = self.read_samples(f, self._start, self._nsamps, self._psd_size) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max self.srcs.append(self.src_type(data)) # Set default labels based on file names fname = f.split("/")[-1] self.gui_snk.set_line_label(n, "{0}".format(fname)) n += 1 self.connect(self.srcs[0], self.skip) self.connect(self.skip, (self.gui_snk, 0)) for i,s in enumerate(self.srcs[1:]): self.connect(s, (self.gui_snk, i+1)) self.gui_snk.set_update_time(0) self.gui_snk.enable_menu(False) # Get Python Qt references pyQt = self.gui_snk.pyqwidget() self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self._is_setup = True def is_setup(self): return self._is_setup def set_y_axis(self, y_min, y_max): self.gui_snk.set_y_axis(y_min, y_max) return y_min, y_max def get_gui(self): if(self.is_setup()): return self.pyWin else: return None def reset(self, newstart, newnsamps): self.stop() self.wait() self._start = newstart self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for s,f in zip(self.srcs, self._filelist): data,_min,_max = self.read_samples(f, self._start, newnsamps, self._psd_size) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max s.set_data(data) self.start() def setup_options(desc): parser = OptionParser(option_class=eng_option, description=desc, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=1000000, help="Set the number of samples to display [default=prints entire file]") parser.add_option("-S", "--start", type="int", default=0, help="Starting sample number [default=%default]") parser.add_option("-L", "--psd-size", type="int", default=2048, help="Set the FFT size of the PSD [default=%default]") parser.add_option("-f", "--center-frequency", type="eng_float", default=0.0, help="Set the center frequency of the signal [default=%default]") parser.add_option("-r", "--sample-rate", type="eng_float", default=1.0, help="Set the sample rate of the signal [default=%default]") parser.add_option("-a", "--average", type="float", default=1.0, help="Set amount of averaging (smaller=more averaging) [default=%default]") (options, args) = parser.parse_args() if(len(args) < 1): parser.print_help() sys.exit(0) return (options,args) gnuradio-3.7.2.1/gr-qtgui/apps/gr_spectrogram_plot_f0000775000175000017500000000532412207440367022346 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter import scipy try: import gnuradio.qtgui.plot_spectrogram_base as plot_base except ImportError: import plot_spectrogram_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class spectrogram_plot_f(plot_base.plot_base): def __init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg=1.0): plot_base.plot_base.__init__(self, filelist, fc, samp_rate, psdsize, start, nsamples, max_nsamples, avg) self.read_samples = plot_base.read_samples_f self.dsize = gr.sizeof_float self.src_type = blocks.vector_source_f self.gui_snk = qtgui.waterfall_sink_f(self._psd_size, filter.firdes.WIN_BLACKMAN_hARRIS, self._center_freq, self._samp_rate, "GNU Radio Spectrogram Plot", self._nsigs) self.setup() def main(): description = "Plots the spectrogram (waterfall) of a list of files. Files are a binary list of floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = spectrogram_plot_f(filelist, options.center_frequency, options.sample_rate, options.psd_size, options.start, options.nsamples, max_nsamples, options.average); main_box = plot_base.plot_spectrogram_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/plot_time_base.py0000664000175000017500000001345012207440367021376 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import os, sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Scipy required (www.scipy.org)." sys.exit(1) try: from gnuradio.qtgui.plot_form import * from gnuradio.qtgui.plot_base import * except ImportError: from plot_form import * from plot_base import * class plot_base(gr.top_block): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): gr.top_block.__init__(self) self._filelist = filelist self._samp_rate = samp_rate self._center_freq = 0 self._start = start self._max_nsamps = max_nsamples self._nsigs = len(self._filelist) self._auto_scale = auto_scale self._nsamps = nsamples self._is_setup = False self._y_min = -20 self._y_max = 20 self._y_range = 2 self._y_value = 1 self.gui_y_axis = None self.qapp = QtGui.QApplication(sys.argv) def setup(self): self.skip = blocks.skiphead(self.dsize, self._start) n = 0 self.srcs = list() self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for f in self._filelist: data,_min,_max = self.read_samples(f, self._start, self._nsamps) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max self.srcs.append(self.src_type(data)) # Set default labels based on file names fname = f.split("/")[-1] if(type(self.gui_snk) == qtgui.time_sink_c_sptr): self.gui_snk.set_line_label(n, "Re{{{0}}}".format(fname)) self.gui_snk.set_line_label(n+1, "Im{{{0}}}".format(fname)) n += 2 else: self.gui_snk.set_line_label(n, "{0}".format(fname)) n += 1 self.connect(self.srcs[0], self.skip) self.connect(self.skip, (self.gui_snk, 0)) for i,s in enumerate(self.srcs[1:]): self.connect(s, (self.gui_snk, i+1)) self.gui_snk.set_update_time(0) self.gui_snk.enable_menu(False) self.auto_scale(self._auto_scale) # Get Python Qt references pyQt = self.gui_snk.pyqwidget() self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self._is_setup = True def is_setup(self): return self._is_setup def set_y_axis(self, y_min, y_max): self.gui_snk.set_y_axis(y_min, y_max) return y_min, y_max def get_gui(self): if(self.is_setup()): return self.pyWin else: return None def reset(self, newstart, newnsamps): self.stop() self.wait() self._start = newstart self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for s,f in zip(self.srcs, self._filelist): data,_min,_max = self.read_samples(f, self._start, newnsamps) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max s.set_data(data) if(len(data) < newnsamps): newnsamps = len(data) self.auto_scale(self._auto_scale) self._nsamps = newnsamps self.gui_snk.set_nsamps(self._nsamps) self.start() def auto_scale(self, state): if(state > 0): self.gui_snk.set_y_axis(self._data_min, self._data_max) self._auto_scale = True self._y_value = self._data_max self._y_range = self._data_max - self._data_min self._y_min = 10*self._data_min self._y_max = 10*self._data_max if(self.gui_y_axis): self.gui_y_axis(self._data_min, self._data_max) else: self._auto_scale = False def setup_options(desc): parser = OptionParser(option_class=eng_option, description=desc, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=1000000, help="Set the number of samples to display [default=%default]") parser.add_option("-S", "--start", type="int", default=0, help="Starting sample number [default=%default]") parser.add_option("-r", "--sample-rate", type="eng_float", default=1.0, help="Set the sample rate of the signal [default=%default]") parser.add_option("", "--no-auto-scale", action="store_true", default=False, help="Do not auto-scale the plot [default=%default]") (options,args) = parser.parse_args() if(len(args) < 1): parser.print_help() sys.exit(0) return (options,args) gnuradio-3.7.2.1/gr-qtgui/apps/qt_digital_window.ui0000644000175000017500000002247611700377701022111 0ustar jcorganjcorgan DigitalWindow 0 0 1236 741 MainWindow 0 550 QFrame::StyledPanel QFrame::Raised 0 0 0 0 16777215 120 System Parameters Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop 100 16777215 Sample Rate (sps) 16777215 120 Receiver Parameters Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop Alpha 100 16777215 Gain mu 100 16777215 16777215 120 Channel Model Parameters Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop QLayout::SetMinimumSize SNR (dB) 100 16777215 Frequency Offset (Hz) 100 16777215 Timing Offset 100 16777215 Qt::Horizontal 40 20 Qt::Vertical 20 40 0 0 80 16777215 Pause 80 16777215 Close 0 0 1236 23 &File E&xit snrEdit freqEdit timeEdit closeButton clicked() DigitalWindow close() 322 623 66 561 actionExit triggered() DigitalWindow close() -1 -1 617 327 gnuradio-3.7.2.1/gr-qtgui/apps/plot_time_raster_form.py0000664000175000017500000001400412207440367023003 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys, math from gnuradio import filter try: from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4." sys.exit(1) try: from gnuradio.qtgui.plot_from import plot_form except ImportError: from plot_form import plot_form class plot_time_raster_form(plot_form): def __init__(self, top_block, title='', scale=1): plot_form.__init__(self, top_block, title, scale) self.right_col_layout = QtGui.QVBoxLayout() self.right_col_form = QtGui.QFormLayout() self.right_col_layout.addLayout(self.right_col_form) self.layout.addLayout(self.right_col_layout, 1,4,1,1) self.auto_scale = QtGui.QCheckBox("Auto Scale", self) if(self.top_block._auto_scale): self.auto_scale.setChecked(self.top_block._auto_scale) self.connect(self.auto_scale, QtCore.SIGNAL("stateChanged(int)"), self.set_auto_scale) self.right_col_layout.addWidget(self.auto_scale) self.ncols_edit = QtGui.QLineEdit(self) self.ncols_edit.setMinimumWidth(100) self.ncols_edit.setMaximumWidth(100) self.ncols_edit.setText(QtCore.QString("%1").arg(top_block._ncols)) self.right_col_form.addRow("Num. Cols.", self.ncols_edit) self.connect(self.ncols_edit, QtCore.SIGNAL("returnPressed()"), self.ncols_update) self.nrows_edit = QtGui.QLineEdit(self) self.nrows_edit.setMinimumWidth(100) self.nrows_edit.setMaximumWidth(100) self.nrows_edit.setText(QtCore.QString("%1").arg(top_block._nrows)) self.right_col_form.addRow("Num. Rows.", self.nrows_edit) self.connect(self.nrows_edit, QtCore.SIGNAL("returnPressed()"), self.nrows_update) self.add_raster_control(self.right_col_layout) def add_raster_control(self, layout): self._line_tabs = QtGui.QTabWidget() self._line_pages = [] self._line_forms = [] self._label_edit = [] self._size_edit = [] self._color_edit = [] self._style_edit = [] self._marker_edit = [] self._alpha_edit = [] for n in xrange(self.top_block._nsigs): self._line_pages.append(QtGui.QDialog()) self._line_forms.append(QtGui.QFormLayout(self._line_pages[-1])) label = self.top_block.gui_snk.line_label(n) self._label_edit.append(QtGui.QLineEdit(self)) self._label_edit[-1].setMinimumWidth(125) self._label_edit[-1].setMaximumWidth(125) self._label_edit[-1].setText(QtCore.QString("%1").arg(label)) self._line_forms[-1].addRow("Label:", self._label_edit[-1]) self.connect(self._label_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_label) self._qtcolormaps = ["Multi Color", "White Hot", "Black Hot", "Incandescent"] self._color_edit.append(QtGui.QComboBox(self)) self._color_edit[-1].addItems(self._qtcolormaps) self._color_edit[-1].setCurrentIndex(1) self._line_forms[-1].addRow("Color Map:", self._color_edit[-1]) self.connect(self._color_edit[-1], QtCore.SIGNAL("currentIndexChanged(int)"), self.update_color_map) alpha_val = QtGui.QDoubleValidator(0, 1.0, 2, self) alpha_val.setTop(1.0) alpha = self.top_block.gui_snk.line_alpha(n) self._alpha_edit.append(QtGui.QLineEdit(self)) self._alpha_edit[-1].setMinimumWidth(50) self._alpha_edit[-1].setMaximumWidth(100) self._alpha_edit[-1].setText(QtCore.QString("%1").arg(alpha)) self._alpha_edit[-1].setValidator(alpha_val) self._line_forms[-1].addRow("Alpha:", self._alpha_edit[-1]) self.connect(self._alpha_edit[-1], QtCore.SIGNAL("returnPressed()"), self.update_line_alpha) self._line_tabs.addTab(self._line_pages[-1], "{0}".format(label)) layout.addWidget(self._line_tabs) def update_color_map(self, c_index): index = self._line_tabs.currentIndex() self.top_block.gui_snk.set_color_map(index, c_index) self.update_line_alpha() def set_auto_scale(self, state): if(state): self.top_block.auto_scale(True) else: self.top_block.auto_scale(False) def update_samp_rate(self): sr = self.samp_rate_edit.text().toDouble()[0] self.top_block.gui_snk.set_samp_rate(sr) nsamps = int(math.ceil((self.top_block._nrows+1)*self.top_block._ncols)) self.top_block.reset(self._start, nsamps) def ncols_update(self): n = self.ncols_edit.text().toDouble()[0] self.top_block.gui_snk.set_num_cols(n) self.top_block._ncols = n nsamps = int(math.ceil((self.top_block._nrows+1)*n)) self.top_block.reset(self._start, nsamps) def nrows_update(self): n = self.nrows_edit.text().toInt()[0] self.top_block.gui_snk.set_num_rows(n) self.top_block._nrows = n nsamps = int(math.ceil(self.top_block._ncols*(n+1))) self.top_block.reset(self._start, nsamps) gnuradio-3.7.2.1/gr-qtgui/apps/qt_digital.py0000775000175000017500000002317112207440367020535 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, digital from gnuradio import blocks from gnuradio import filter from gnuradio import channels from gnuradio import eng_notation import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) try: from qt_digital_window import Ui_DigitalWindow except ImportError: print "Error: could not find qt_digital_window.py:" print "\t\"Please run: pyuic4 qt_digital_window.ui -o qt_digital_window.py\"" sys.exit(1) class dialog_box(QtGui.QMainWindow): def __init__(self, snkTx, snkRx, fg, parent=None): QtGui.QWidget.__init__(self, parent) self.gui = Ui_DigitalWindow() self.gui.setupUi(self) self.fg = fg self.set_sample_rate(self.fg.sample_rate()) self.set_snr(self.fg.snr()) self.set_frequency(self.fg.frequency_offset()) self.set_time_offset(self.fg.timing_offset()) self.set_gain_mu(self.fg.rx_gain_mu()) self.set_loop_bw(self.fg.loop_bw()) # Add the qtsnk widgets to the hlayout box self.gui.sinkLayout.addWidget(snkTx) self.gui.sinkLayout.addWidget(snkRx) # Connect up some signals self.connect(self.gui.pauseButton, QtCore.SIGNAL("clicked()"), self.pauseFg) self.connect(self.gui.sampleRateEdit, QtCore.SIGNAL("editingFinished()"), self.sampleRateEditText) self.connect(self.gui.snrEdit, QtCore.SIGNAL("editingFinished()"), self.snrEditText) self.connect(self.gui.freqEdit, QtCore.SIGNAL("editingFinished()"), self.freqEditText) self.connect(self.gui.timeEdit, QtCore.SIGNAL("editingFinished()"), self.timeEditText) self.connect(self.gui.gainMuEdit, QtCore.SIGNAL("editingFinished()"), self.gainMuEditText) self.connect(self.gui.alphaEdit, QtCore.SIGNAL("editingFinished()"), self.alphaEditText) def pauseFg(self): if(self.gui.pauseButton.text() == "Pause"): self.fg.stop() self.fg.wait() self.gui.pauseButton.setText("Unpause") else: self.fg.start() self.gui.pauseButton.setText("Pause") # Accessor functions for Gui to manipulate system parameters def set_sample_rate(self, sr): ssr = eng_notation.num_to_str(sr) self.gui.sampleRateEdit.setText(QtCore.QString("%1").arg(ssr)) def sampleRateEditText(self): try: rate = self.gui.sampleRateEdit.text().toAscii() srate = eng_notation.str_to_num(rate) self.fg.set_sample_rate(srate) except RuntimeError: pass # Accessor functions for Gui to manipulate channel model def set_snr(self, snr): self.gui.snrEdit.setText(QtCore.QString("%1").arg(snr)) def set_frequency(self, fo): self.gui.freqEdit.setText(QtCore.QString("%1").arg(fo)) def set_time_offset(self, to): self.gui.timeEdit.setText(QtCore.QString("%1").arg(to)) def snrEditText(self): try: snr = self.gui.snrEdit.text().toDouble()[0] self.fg.set_snr(snr) except RuntimeError: pass def freqEditText(self): try: freq = self.gui.freqEdit.text().toDouble()[0] self.fg.set_frequency_offset(freq) except RuntimeError: pass def timeEditText(self): try: to = self.gui.timeEdit.text().toDouble()[0] self.fg.set_timing_offset(to) except RuntimeError: pass # Accessor functions for Gui to manipulate receiver parameters def set_gain_mu(self, gain): self.gui.gainMuEdit.setText(QtCore.QString("%1").arg(gain)) def set_loop_bw(self, bw): self.gui.alphaEdit.setText(QtCore.QString("%1").arg(bw)) def alphaEditText(self): try: bw = self.gui.alphaEdit.text().toDouble()[0] self.fg.set_loop_bw(bw) except RuntimeError: pass def gainMuEditText(self): try: gain = self.gui.gainMuEdit.text().toDouble()[0] self.fg.set_rx_gain_mu(gain) except RuntimeError: pass class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self.qapp = QtGui.QApplication(sys.argv) self._sample_rate = 2000e3 self.sps = 2 self.excess_bw = 0.35 self.gray_code = digital.mod_codes.GRAY_CODE fftsize = 2048 self.data = scipy.random.randint(0, 255, 1000) self.src = blocks.vector_source_b(self.data.tolist(), True) self.mod = digital.dqpsk_mod(self.gray_code, samples_per_symbol=self.sps, excess_bw=self.excess_bw, verbose=False, log=False) self.rrctaps = filter.firdes.root_raised_cosine(1, self.sps, 1, self.excess_bw, 21) self.rx_rrc = filter.fir_filter_ccf(1, self.rrctaps) # Set up the carrier & clock recovery parameters self.arity = 4 self.mu = 0.5 self.gain_mu = 0.05 self.omega = self.sps self.gain_omega = .25 * self.gain_mu * self.gain_mu self.omega_rel_lim = 0.05 self._loop_bw = 2*scipy.pi/100.0 self.fmin = -1000/self.sample_rate() self.fmax = 1000/self.sample_rate() self.receiver = digital.mpsk_receiver_cc(self.arity, 0, self._loop_bw, self.fmin, self.fmax, self.mu, self.gain_mu, self.omega, self.gain_omega, self.omega_rel_lim) self.snr_dB = 15 noise = self.get_noise_voltage(self.snr_dB) self.fo = 100/self.sample_rate() self.to = 1.0 self.channel = channels.channel_model(noise, self.fo, self.to) self.thr = blocks.throttle(gr.sizeof_char, self._sample_rate) self.snk_tx = qtgui.sink_c(fftsize, filter.firdes.WIN_BLACKMAN_hARRIS, 0, self._sample_rate*self.sps, "Tx", True, True, True, True) self.snk_rx = qtgui.sink_c(fftsize, filter.firdes.WIN_BLACKMAN_hARRIS, 0, self._sample_rate, "Rx", True, True, True, True) self.connect(self.src, self.thr, self.mod, self.channel, self.snk_tx) self.connect(self.channel, self.rx_rrc, self.receiver, self.snk_rx) pyTxQt = self.snk_tx.pyqwidget() pyTx = sip.wrapinstance(pyTxQt, QtGui.QWidget) pyRxQt = self.snk_rx.pyqwidget() pyRx = sip.wrapinstance(pyRxQt, QtGui.QWidget) self.main_box = dialog_box(pyTx, pyRx, self); self.main_box.show() def get_noise_voltage(self, SNR): S = 0 # dBm, assuming signal power normalized N = S - SNR # dBm npwr = pow(10.0, N/10.0) # ratio nv = scipy.sqrt(npwr * self.sps) # convert the noise voltage return nv # System Parameters def sample_rate(self): return self._sample_rate def set_sample_rate(self, sr): self._sample_rate = sr # Channel Model Parameters def snr(self): return self.snr_dB def set_snr(self, snr): self.snr_dB = snr noise = self.get_noise_voltage(self.snr_dB) self.channel.set_noise_voltage(noise) def frequency_offset(self): return self.fo * self.sample_rate() def set_frequency_offset(self, fo): self.fo = fo / self.sample_rate() self.channel.set_frequency_offset(self.fo) def timing_offset(self): return self.to def set_timing_offset(self, to): self.to = to self.channel.set_timing_offset(self.to) # Receiver Parameters def rx_gain_mu(self): return self.gain_mu def rx_gain_omega(self): return self.gain_omega def set_rx_gain_mu(self, gain): self.gain_mu = gain self.gain_omega = .25 * self.gain_mu * self.gain_mu self.receiver.set_gain_mu(self.gain_mu) self.receiver.set_gain_omega(self.gain_omega) def set_loop_bw(self, loop_bw): self._loop_bw = bw self.receiver.set_loop_bw(self._loop_bw) def loop_bw(self): return self._loop_bw if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_raster_b0000775000175000017500000000517212207440367021275 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import scipy try: import gnuradio.qtgui.plot_time_raster_base as plot_base except ImportError: import plot_time_raster_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_raster_b(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, nrows, ncols, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self._nrows = nrows self._ncols = ncols self.read_samples = plot_base.read_samples_b self.dsize = gr.sizeof_char self.src_type = blocks.vector_source_b self.gui_snk = qtgui.time_raster_sink_b(self._samp_rate, self._nrows, self._ncols, [], [], "GNU Radio Time Plot", self._nsigs) self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of chars." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_raster_b(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, options.nrows, options.ncols, not options.no_auto_scale) main_box = plot_base.plot_time_raster_form(tb, 'GNU Radio Time Plot') main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/apps/plot_time_raster_base.py0000664000175000017500000001353112207440367022756 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import os, sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) try: import scipy except ImportError: print "Error: Scipy required (www.scipy.org)." sys.exit(1) try: from gnuradio.qtgui.plot_form import * from gnuradio.qtgui.plot_base import * except ImportError: from plot_form import * from plot_base import * class plot_base(gr.top_block): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): gr.top_block.__init__(self) self._filelist = filelist self._samp_rate = samp_rate self._center_freq = 0 self._start = start self._max_nsamps = max_nsamples self._nsigs = len(self._filelist) self._auto_scale = auto_scale self._nsamps = nsamples self._is_setup = False self._y_min = -20 self._y_max = 20 self._y_range = 2 self._y_value = 1 self.gui_y_axis = None self.qapp = QtGui.QApplication(sys.argv) def setup(self): self.skip = blocks.skiphead(self.dsize, self._start) n = 0 self.srcs = list() self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for f in self._filelist: data,_min,_max = self.read_samples(f, self._start, self._nsamps) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max self.srcs.append(self.src_type(data)) # Set default labels based on file names fname = f.split("/")[-1] #self.gui_snk.set_line_label(n, "{0}".format(fname)) n += 1 self.connect(self.srcs[0], self.skip) self.connect(self.skip, (self.gui_snk, 0)) for i,s in enumerate(self.srcs[1:]): self.connect(s, (self.gui_snk, i+1)) self.gui_snk.set_update_time(0) self.gui_snk.enable_menu(False) self.auto_scale(self._auto_scale) # Get Python Qt references pyQt = self.gui_snk.pyqwidget() self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self._is_setup = True def is_setup(self): return self._is_setup def set_y_axis(self, y_min, y_max): if(not self._auto_scale): self.gui_snk.set_intensity_range(y_min, y_max) return y_min, y_max else: return None def get_gui(self): if(self.is_setup()): return self.pyWin else: return None def reset(self, newstart, newnsamps): self.stop() self.wait() self._start = newstart self._data_min = sys.maxint self._data_max = -sys.maxint - 1 for s,f in zip(self.srcs, self._filelist): data,_min,_max = self.read_samples(f, self._start, newnsamps) if(_min < self._data_min): self._data_min = _min if(_max > self._data_max): self._data_max = _max s.set_data(data) if(len(data) < newnsamps): newnsamps = len(data) self.auto_scale(self._auto_scale) self._nsamps = newnsamps self.start() def auto_scale(self, state): if(state > 0): self.gui_snk.set_intensity_range(self._data_min, self._data_max) self._auto_scale = True self._y_value = self._data_max self._y_range = self._data_max - self._data_min self._y_min = 10*self._data_min self._y_max = 10*self._data_max if(self.gui_y_axis): self.gui_y_axis(self._data_min, self._data_max) else: self._auto_scale = False def setup_options(desc): parser = OptionParser(option_class=eng_option, description=desc, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=1000000, help="Set the number of samples to display [default=%default]") parser.add_option("-S", "--start", type="int", default=0, help="Starting sample number [default=%default]") parser.add_option("-C", "--ncols", type="int", default=100, help="Number of columns [default=%default]") parser.add_option("-R", "--nrows", type="int", default=100, help="Number of rows [default=%default]") parser.add_option("-r", "--sample-rate", type="eng_float", default=1.0, help="Set the sample rate of the signal [default=%default]") parser.add_option("", "--no-auto-scale", action="store_true", default=False, help="Do not auto-scale the plot [default=%default]") (options,args) = parser.parse_args() if(len(args) < 1): parser.print_help() sys.exit(0) return (options,args) gnuradio-3.7.2.1/gr-qtgui/apps/gr_time_plot_c0000775000175000017500000000476412207440367020762 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import scipy try: import gnuradio.qtgui.plot_time_base as plot_base except ImportError: import plot_time_base as plot_base try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class plot_time_c(plot_base.plot_base): def __init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale): plot_base.plot_base.__init__(self, filelist, samp_rate, start, nsamples, max_nsamples, auto_scale) self.read_samples = plot_base.read_samples_c self.dsize = gr.sizeof_gr_complex self.src_type = blocks.vector_source_c self.gui_snk = qtgui.time_sink_c(self._nsamps, self._samp_rate, "GNU Radio Time Plot", self._nsigs) self._nsigs *= 2 # complex plots have real/imag self.setup() def main(): description = "Plots a list of files on a scope plot. Files are a binary list of complex floats." (options, args) = plot_base.setup_options(description) filelist = list(args) max_nsamples = plot_base.find_max_nsamples(filelist) tb = plot_time_c(filelist, options.sample_rate, options.start, options.nsamples, max_nsamples, not options.no_auto_scale) main_box = plot_base.plot_time_form(tb, 'GNU Radio Time Plot', 10000.0) main_box.show() tb.run() tb.qapp.exec_() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-qtgui/gnuradio-qtgui.pc.in0000664000175000017500000000037112207440367020761 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-qtgui Description: GNU Radio blocks for QT GUI Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-qtgui Cflags: -I${includedir} gnuradio-3.7.2.1/gr-qtgui/examples/0000755000175000017500000000000012237515112016676 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-qtgui/examples/CMakeLists.txt0000664000175000017500000000237112237515112021443 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS pyqt_const_c.py pyqt_example_c.py pyqt_example_f.py pyqt_freq_c.py pyqt_freq_f.py pyqt_histogram_f.py pyqt_time_c.py pyqt_time_f.py pyqt_time_raster_b.py pyqt_time_raster_f.py pyqt_waterfall_c.py pyqt_waterfall_f.py DESTINATION ${GR_PKG_QTGUI_EXAMPLES_DIR} COMPONENT "qtgui_python" ) install( FILES dark.qss qtgui_tags_viewing.grc DESTINATION ${GR_PKG_QTGUI_EXAMPLES_DIR} COMPONENT "qtgui_python" ) gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_waterfall_f.py0000775000175000017500000001364312207440367022635 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 2000 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_ff() thr = blocks.throttle(gr.sizeof_float, 100*npts) self.snk1 = qtgui.waterfall_sink_f(npts, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Real Waterfall Example", 2) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, thr, (self.snk1, 0)) self.connect(src1, (self.snk1, 1)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_example_f.py0000775000175000017500000001405112207440367022301 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 1000 f2 = 2000 fftsize = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_ff() thr = blocks.throttle(gr.sizeof_float, 100*fftsize) noise = analog.noise_source_f(analog.GR_GAUSSIAN, 0.001) add = blocks.add_ff() self.snk1 = qtgui.sink_f(fftsize, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Float Signal Example", True, True, True, False) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, thr, (add,0)) self.connect(noise, (add,1)) self.connect(add, self.snk1) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_example_c.py0000775000175000017500000001430312207440367022276 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 1000 f2 = 2000 fftsize = 2048 self.qapp = QtGui.QApplication(sys.argv) ss = open('dark.qss') sstext = ss.read() ss.close() self.qapp.setStyleSheet(sstext) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_cc() channel = channels.channel_model(0.001) thr = blocks.throttle(gr.sizeof_gr_complex, 100*fftsize) self.snk1 = qtgui.sink_c(fftsize, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Signal Example", True, True, True, False) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, self.snk1) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/qtgui_tags_viewing.grc0000664000175000017500000006342612237515112023307 0ustar jcorganjcorgan Wed Nov 6 11:52:40 2013 options id qtgui_tags_viewing _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options run run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (172, 10) _rotation 0 import id import_1 _enabled True import from gnuradio.digital.utils import tagged_streams _coordinate (99, 72) _rotation 0 import id import_0 _enabled True import import scipy _coordinate (9, 71) _rotation 0 import id import_2 _enabled True import import time _coordinate (253, 71) _rotation 0 blocks_delay id blocks_delay_0 _enabled True type complex delay 1000 num_ports 1 vlen 1 affinity minoutbuf 0 _coordinate (300, 240) _rotation 0 blocks_tags_strobe id blocks_tags_strobe_0 _enabled True type complex value pmt.intern("TEST") nsamps 10000 vlen 1 affinity minoutbuf 0 _coordinate (16, 232) _rotation 0 analog_fastnoise_source_x id analog_fastnoise_source_x_0 _enabled True type complex noise_type analog.GR_GAUSSIAN amp 0.004 seed 0 samples 8192 affinity minoutbuf 0 _coordinate (350, 39) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0 _enabled True type complex vector [0.85+0.5j, 0.85, 0.85, 0.85+0.5j] + (10000-4)*[0,] tags tagged_streams.make_lengthtags((1024,), (0,), "testing tags 0") repeat True vlen 1 affinity minoutbuf 0 _coordinate (13, 132) _rotation 0 blocks_add_xx id blocks_add_xx_0 _enabled True type complex num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (482, 193) _rotation 0 blocks_add_xx id blocks_add_xx_1 _enabled True type complex num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (707, 176) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second 50e3 vlen 1 affinity minoutbuf 0 _coordinate (266, 149) _rotation 0 variable_qtgui_range id ntaps _enabled True label Num Taps value 30 start 1 stop 100 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (936, 392) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_1_0 _enabled True type complex name QT GUI Plot size 5100 srate samp_rate ymin -0.1 ymax 1.5 nconnections 1 update_time 0.001 tr_mode qtgui.TRIG_MODE_TAG tr_slope qtgui.TRIG_SLOPE_POS tr_level .5 tr_delay 0.06 tr_chan 0 tr_tag strobe entags True gui_hint 1,1,1,1 affinity _coordinate (857, 173) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0_0 _enabled True type complex vector 1500*[0,] + [0.25+0j,] + (10000-1500-1)*[0,] tags tagged_streams.make_lengthtags((128,), (1500,), "second stream") repeat True vlen 1 affinity minoutbuf 0 _coordinate (15, 315) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0 _enabled True type complex name QT GUI Plot size 18000 srate samp_rate ymin -0.1 ymax 1.5 nconnections 2 update_time 0.10 tr_mode qtgui.TRIG_MODE_NORM tr_slope qtgui.TRIG_SLOPE_POS tr_level 0.1 tr_delay 0 tr_chan 0 tr_tag "" entags True gui_hint affinity _coordinate (860, 298) _rotation 0 fir_filter_xxx id fir_filter_xxx_0 _enabled True type ccc decim 1 taps int(ntaps)*[1,]+[1,] samp_delay int(ntaps) affinity minoutbuf 0 _coordinate (660, 76) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_1 _enabled True type complex name QT GUI Plot size 1000 srate samp_rate ymin -0.1 ymax 4.5 nconnections 2 update_time 0.10 tr_mode qtgui.TRIG_MODE_NORM tr_slope qtgui.TRIG_SLOPE_POS tr_level .1 tr_delay 0.015 tr_chan 0 tr_tag "" entags True gui_hint 1,0,1,1 affinity _coordinate (1072, 77) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_0 _enabled False type float name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 2 update_time 0.10 tr_mode qtgui.TRIG_MODE_TAG tr_slope qtgui.TRIG_SLOPE_POS tr_level 0.0 tr_delay 0 tr_chan 1 tr_tag second stream entags True gui_hint affinity _coordinate (475, 444) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0_0_0 _enabled False type float vector 10*[0,] + [0.5,] + (100-10-1)*[0,] tags tagged_streams.make_lengthtags((128,), (110,), "second stream") repeat True vlen 1 affinity minoutbuf 0 _coordinate (15, 489) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0_1 _enabled False type float vector [-0.85,] + (100-1)*[0,] tags tagged_streams.make_lengthtags((1024,), (0,), "testing tags") repeat True vlen 1 affinity minoutbuf 0 _coordinate (15, 398) _rotation 0 blocks_throttle id blocks_throttle_0_0 _enabled False type float samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (267, 414) _rotation 0 blocks_delay id blocks_delay_0_0 _enabled True type complex delay int(delay) num_ports 1 vlen 1 affinity minoutbuf 0 _coordinate (890, 44) _rotation 0 variable_qtgui_range id delay _enabled True label Delay value 300 start 0 stop 1000 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (814, 390) _rotation 0 blocks_vector_source_x_0 blocks_throttle_0 0 0 blocks_throttle_0 blocks_add_xx_0 0 0 blocks_delay_0 blocks_add_xx_0 0 1 analog_fastnoise_source_x_0 blocks_add_xx_1 0 0 blocks_add_xx_0 blocks_add_xx_1 0 1 blocks_add_xx_0 fir_filter_xxx_0 0 0 fir_filter_xxx_0 blocks_delay_0_0 0 0 blocks_delay_0_0 qtgui_time_sink_x_0_1 0 0 fir_filter_xxx_0 qtgui_time_sink_x_0_1 0 1 blocks_vector_source_x_0_0 qtgui_time_sink_x_0 0 1 blocks_tags_strobe_0 blocks_delay_0 0 0 blocks_add_xx_1 qtgui_time_sink_x_0_1_0 0 0 blocks_add_xx_1 qtgui_time_sink_x_0 0 0 blocks_vector_source_x_0_0_0 qtgui_time_sink_x_0_0 0 1 blocks_throttle_0_0 qtgui_time_sink_x_0_0 0 0 blocks_vector_source_x_0_1 blocks_throttle_0_0 0 0 gnuradio-3.7.2.1/gr-qtgui/examples/dark.qss0000664000175000017500000000423512207440367020363 0ustar jcorganjcorganQWidget { color: white; background-color: black; } QwtPlot { padding: 10px; font-size: 18px; } DisplayPlot { qproperty-zoomer_color: green; qproperty-line_color1: green; qproperty-line_color2: green; qproperty-line_color3: green; qproperty-line_style1: SolidLine; qproperty-line_style2: DashLine; qproperty-line_style3: DotLine; qproperty-axes_label_font_size: 18; } WaterfallDisplayPlot { qproperty-intensity_color_map_type1: 1; qproperty-low_intensity_color: black; qproperty-high_intensity_color: green; } FrequencyDisplayPlot { qproperty-max_fft_color: palegreen; qproperty-min_fft_color: palegreen; qproperty-marker_lower_intensity_color: white; qproperty-marker_upper_intensity_color: red; qproperty-marker_lower_intensity_visible: false; qproperty-marker_upper_intensity_visible: false; qproperty-marker_noise_floor_amplitude_color: red; qproperty-marker_noise_floor_amplitude_visible: false; } QwtPlotCanvas { border: 1px solid White; border-radius: 10px; } QwtScaleWidget { font-size: 14px; } QwtLegend { padding: 3px; margin: 3px; font-size: 14px; } QwtLegendItem { padding: 2px; margin: 2px; } QLineEdit, QPlainTextEdit, QComboBox, QMenu { selection-color: black; selection-background-color: lightgrey; background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 black, stop: 1 rgb(128, 128, 128)); border: 1px solid gray; padding: 2px; border-radius: 3px; } QPushButton, QToolButton { selection-color: black; selection-background-color: white; background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 black, stop: 1 rgb(128, 128, 128)); border: 1px solid gray; padding: 2px; border-radius: 3px; } QTabWidget::pane { border: 1px solid white; } QTabBar { margin: 20px; padding: 20px; } QTabBar::tab { background-color: rgb(100, 100, 100); border: 1px solid white; padding: 5px; } QTabBar::tab:first { border-top-left-radius: 4px; } QTabBar::tab:last { border-top-right-radius: 4px; } QTabBar::tab:selected { background-color: rgb(200, 200, 200); color: black; } gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_time_f.py0000775000175000017500000001473312207440367021613 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_ff() thr = blocks.throttle(gr.sizeof_float, 100*npts) noise = analog.noise_source_f(analog.GR_GAUSSIAN, 0.001) add = blocks.add_ff() self.snk1 = qtgui.time_sink_f(npts, Rs, "Complex Time Example", 3) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, thr, (add,0)) self.connect(noise, (add,1)) self.connect(add, self.snk1) self.connect(src1, (self.snk1, 1)) self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) # Example of using signal/slot to set the title of a curve pyWin.connect(pyWin, QtCore.SIGNAL("setLineLabel(int, QString)"), pyWin, QtCore.SLOT("setLineLabel(int, QString)")) pyWin.emit(QtCore.SIGNAL("setLineLabel(int, QString)"), 0, "sum") self.snk1.set_line_label(1, "src1") self.snk1.set_line_label(2, "src2") # Can also set the color of a curve #self.snk1.set_color(5, "blue") #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_waterfall_c.py0000775000175000017500000001454312207440367022632 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 2000 npts = 2048 taps = filter.firdes.complex_band_pass_2(1, Rs, 1500, 2500, 100, 60) self.qapp = QtGui.QApplication(sys.argv) ss = open('dark.qss') sstext = ss.read() ss.close() self.qapp.setStyleSheet(sstext) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_cc() channel = channels.channel_model(0.01) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) filt = filter.fft_filter_ccc(1, taps) self.snk1 = qtgui.waterfall_sink_c(npts, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Waterfall Example", 2) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, (self.snk1, 0)) self.connect(thr, filt, (self.snk1, 1)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_histogram_f.py0000775000175000017500000001504312237515112022637 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, snk, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.snk = snk self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Sine Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Sine Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Noise Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) # Control the histogram self.hist_npts = QtGui.QLineEdit(self) self.hist_npts.setMinimumWidth(100) self.hist_npts.setValidator(QtGui.QIntValidator(0, 8191)) self.hist_npts.setText("{0}".format(self.snk.nsamps())) self.layout.addRow("Number of Points:", self.hist_npts) self.connect(self.hist_npts, QtCore.SIGNAL("editingFinished()"), self.set_nsamps) self.hist_bins = QtGui.QLineEdit(self) self.hist_bins.setMinimumWidth(100) self.hist_bins.setValidator(QtGui.QIntValidator(0, 1000)) self.hist_bins.setText("{0}".format(self.snk.bins())) self.layout.addRow("Number of Bins:", self.hist_bins) self.connect(self.hist_bins, QtCore.SIGNAL("editingFinished()"), self.set_bins) self.hist_auto = QtGui.QPushButton("scale", self) self.layout.addRow("Autoscale X:", self.hist_auto) self.connect(self.hist_auto, QtCore.SIGNAL("pressed()"), self.autoscalex) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def set_nsamps(self): res = self.hist_npts.text().toInt() if(res[1]): self.snk.set_nsamps(res[0]) def set_bins(self): res = self.hist_bins.text().toInt() if(res[1]): self.snk.set_bins(res[0]) def autoscalex(self): self.snk.autoscalex() class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0, 0) src2 = analog.noise_source_f(analog.GR_GAUSSIAN, 1) src = blocks.add_ff() thr = blocks.throttle(gr.sizeof_float, 100*npts) self.snk1 = qtgui.histogram_sink_f(npts, 200, -5, 5, "Histogram") self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, thr, self.snk1) self.ctrl_win = control_box(self.snk1) self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_time_c.py0000775000175000017500000001547712207440367021616 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) ss = open('dark.qss') sstext = ss.read() ss.close() self.qapp.setStyleSheet(sstext) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_cc() channel = channels.channel_model(0.01) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) self.snk1 = qtgui.time_sink_c(npts, Rs, "Complex Time Example", 1) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, (self.snk1, 0)) #self.connect(src1, (self.snk1, 1)) #self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) # Example of using signal/slot to set the title of a curve pyWin.connect(pyWin, QtCore.SIGNAL("setLineLabel(int, QString)"), pyWin, QtCore.SLOT("setLineLabel(int, QString)")) pyWin.emit(QtCore.SIGNAL("setLineLabel(int, QString)"), 0, "Re{sum}") self.snk1.set_line_label(1, "Im{Sum}") #self.snk1.set_line_label(2, "Re{src1}") #self.snk1.set_line_label(3, "Im{src1}") #self.snk1.set_line_label(4, "Re{src2}") #self.snk1.set_line_label(5, "Im{src2}") # Can also set the color of a curve #self.snk1.set_color(5, "blue") self.snk1.set_update_time(0.5) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_const_c.py0000775000175000017500000001365212207440367021777 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.5, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.5, 0) src = blocks.add_cc() channel = channels.channel_model(0.001) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) self.snk1 = qtgui.const_sink_c(npts, "Constellation Example", 1) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, (self.snk1, 0)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_time_raster_b.py0000775000175000017500000000525612207440367023167 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.resize(800, 500) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self.qapp = QtGui.QApplication(sys.argv) data0 = 10*[0,] + 40*[1,0] + 10*[0,] data0 += 10*[0,] + 40*[0,1] + 10*[0,] data1 = 20*[0,] + [0,0,0,1,1,1,0,0,0,0] + 70*[0,] # Adjust these to change the layout of the plot. # Can be set to fractions. ncols = 100.25 nrows = 100 fs = 200 src0 = blocks.vector_source_b(data0, True) src1 = blocks.vector_source_b(data1, True) thr = blocks.throttle(gr.sizeof_char, 50000) head = blocks.head(gr.sizeof_char, 10000000) self.snk1 = qtgui.time_raster_sink_b(fs, nrows, ncols, [], [], "Time Raster Example", 2) self.connect(src0, thr, (self.snk1, 0)) self.connect(src1, (self.snk1, 1)) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self.main_box = dialog_box(pyWin) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_freq_f.py0000775000175000017500000001367412207440367021615 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_ff() thr = blocks.throttle(gr.sizeof_float, 100*npts) self.snk1 = qtgui.freq_sink_f(npts, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Real freq Example", 3) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, thr, (self.snk1, 0)) self.connect(src1, (self.snk1, 1)) self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_time_raster_f.py0000775000175000017500000000523012207440367023163 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.resize(800, 500) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self.qapp = QtGui.QApplication(sys.argv) data0 = 10*[0,] + 40*[1,0] + 10*[0,] data0 += 10*[0,] + 40*[0,1] + 10*[0,] data1 = 20*[0,] + [0,0,0,1,1,1,0,0,0,0] + 70*[0,] # Adjust these to change the layout of the plot. # Can be set to fractions. ncols = 100.25 nrows = 100 fs = 200 src0 = blocks.vector_source_f(data0, True) src1 = blocks.vector_source_f(data1, True) thr = blocks.throttle(gr.sizeof_float, 50000) hed = blocks.head(gr.sizeof_float, 10000000) self.snk1 = qtgui.time_raster_sink_f(fs, nrows, ncols, [], [], "Float Time Raster Example", 2) self.connect(src0, thr, (self.snk1, 0)) self.connect(src1, (self.snk1, 1)) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) self.main_box = dialog_box(pyWin) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-qtgui/examples/pyqt_freq_c.py0000775000175000017500000001437212207440367021606 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter from gnuradio import blocks import sys try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: sys.stderr.write("Error: Program requires PyQt4 and gr-qtgui.\n") sys.exit(1) try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: from gnuradio import channels except ImportError: sys.stderr.write("Error: Program requires gr-channels.\n") sys.exit(1) class dialog_box(QtGui.QWidget): def __init__(self, display, control): QtGui.QWidget.__init__(self, None) self.setWindowTitle('PyQt Test GUI') self.boxlayout = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self) self.boxlayout.addWidget(display, 1) self.boxlayout.addWidget(control) self.resize(800, 500) class control_box(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Control Panel') self.setToolTip('Control the signals') QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10)) self.layout = QtGui.QFormLayout(self) # Control the first signal self.freq1Edit = QtGui.QLineEdit(self) self.freq1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Frequency:", self.freq1Edit) self.connect(self.freq1Edit, QtCore.SIGNAL("editingFinished()"), self.freq1EditText) self.amp1Edit = QtGui.QLineEdit(self) self.amp1Edit.setMinimumWidth(100) self.layout.addRow("Signal 1 Amplitude:", self.amp1Edit) self.connect(self.amp1Edit, QtCore.SIGNAL("editingFinished()"), self.amp1EditText) # Control the second signal self.freq2Edit = QtGui.QLineEdit(self) self.freq2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Frequency:", self.freq2Edit) self.connect(self.freq2Edit, QtCore.SIGNAL("editingFinished()"), self.freq2EditText) self.amp2Edit = QtGui.QLineEdit(self) self.amp2Edit.setMinimumWidth(100) self.layout.addRow("Signal 2 Amplitude:", self.amp2Edit) self.connect(self.amp2Edit, QtCore.SIGNAL("editingFinished()"), self.amp2EditText) self.quit = QtGui.QPushButton('Close', self) self.quit.setMinimumWidth(100) self.layout.addWidget(self.quit) self.connect(self.quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) def attach_signal1(self, signal): self.signal1 = signal self.freq1Edit.setText(QtCore.QString("%1").arg(self.signal1.frequency())) self.amp1Edit.setText(QtCore.QString("%1").arg(self.signal1.amplitude())) def attach_signal2(self, signal): self.signal2 = signal self.freq2Edit.setText(QtCore.QString("%1").arg(self.signal2.frequency())) self.amp2Edit.setText(QtCore.QString("%1").arg(self.signal2.amplitude())) def freq1EditText(self): try: newfreq = float(self.freq1Edit.text()) self.signal1.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp1EditText(self): try: newamp = float(self.amp1Edit.text()) self.signal1.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" def freq2EditText(self): try: newfreq = float(self.freq2Edit.text()) self.signal2.set_frequency(newfreq) except ValueError: print "Bad frequency value entered" def amp2EditText(self): try: newamp = float(self.amp2Edit.text()) self.signal2.set_amplitude(newamp) except ValueError: print "Bad amplitude value entered" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) Rs = 8000 f1 = 100 f2 = 200 npts = 2048 self.qapp = QtGui.QApplication(sys.argv) ss = open('dark.qss') sstext = ss.read() ss.close() self.qapp.setStyleSheet(sstext) src1 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f1, 0.1, 0) src2 = analog.sig_source_c(Rs, analog.GR_SIN_WAVE, f2, 0.1, 0) src = blocks.add_cc() channel = channels.channel_model(0.01) thr = blocks.throttle(gr.sizeof_gr_complex, 100*npts) self.snk1 = qtgui.freq_sink_c(npts, filter.firdes.WIN_BLACKMAN_hARRIS, 0, Rs, "Complex Freq Example", 3) self.connect(src1, (src,0)) self.connect(src2, (src,1)) self.connect(src, channel, thr, (self.snk1, 0)) self.connect(src1, (self.snk1, 1)) self.connect(src2, (self.snk1, 2)) self.ctrl_win = control_box() self.ctrl_win.attach_signal1(src1) self.ctrl_win.attach_signal2(src2) # Get the reference pointer to the SpectrumDisplayForm QWidget pyQt = self.snk1.pyqwidget() # Wrap the pointer as a PyQt SIP object # This can now be manipulated as a PyQt4.QtGui.QWidget pyWin = sip.wrapinstance(pyQt, QtGui.QWidget) #pyWin.show() self.main_box = dialog_box(pyWin, self.ctrl_win) self.main_box.show() if __name__ == "__main__": tb = my_top_block(); tb.start() tb.qapp.exec_() tb.stop() gnuradio-3.7.2.1/gr-wavelet/0000755000175000017500000000000012207440367015404 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/CMakeLists.txt0000664000175000017500000000672312207440367020156 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) find_package(GSL) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-wavelet" ENABLE_GR_WAVELET Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_BLOCKS ENABLE_GR_ANALOG GSL_FOUND ) GR_SET_GLOBAL(GR_WAVELET_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/include ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_WAVELET) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_WAVELET_DESCRIPTION "GNU Radio Wavelet Blocks") CPACK_COMPONENT("wavelet_runtime" GROUP "WAVELET" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("wavelet_devel" GROUP "WAVELET" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("wavelet_python" GROUP "WAVELET" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;wavelet_runtime" ) CPACK_COMPONENT("wavelet_swig" GROUP "WAVELET" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;wavelet_python;wavelet_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/wavelet) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/wavelet) # add_subdirectory(grc) endif(ENABLE_PYTHON) #add_subdirectory(examples) #add_subdirectory(doc) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-wavelet.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-wavelet.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-wavelet.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "wavelet_devel" ) endif(ENABLE_GR_WAVELET) gnuradio-3.7.2.1/gr-wavelet/gnuradio-wavelet.pc.in0000664000175000017500000000042012207440367021610 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-wavelet Description: Wavelet signal processing blocks for GNU Radio Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-wavelet Cflags: -I${includedir} gnuradio-3.7.2.1/gr-wavelet/include/0000775000175000017500000000000012207440367017031 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/include/gnuradio/0000775000175000017500000000000012207440367020641 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/include/gnuradio/wavelet/0000775000175000017500000000000012207440367022310 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/include/gnuradio/wavelet/CMakeLists.txt0000664000175000017500000000211712207440367025051 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h squash_ff.h wavelet_ff.h wvps_ff.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/wavelet COMPONENT "wavelet_devel" ) gnuradio-3.7.2.1/gr-wavelet/include/gnuradio/wavelet/wvps_ff.h0000664000175000017500000000272712207440367024143 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WAVELET_WVPS_FF_H #define INCLUDED_WAVELET_WVPS_FF_H #include #include class wavelet_wvps_ff; namespace gr { namespace wavelet { /*! * \brief computes the Wavelet Power Spectrum from a set of wavelet coefficients * \ingroup wavelet_blk */ class WAVELET_API wvps_ff : virtual public sync_block { public: // gr::wavelet::wvps_ff::sptr typedef boost::shared_ptr sptr; /*! \param ilen */ static sptr make(int ilen); }; } /* namespace wavelet */ } /* namespace gr */ #endif /* INCLUDED_WAVELET_WVPS_FF_H */ gnuradio-3.7.2.1/gr-wavelet/include/gnuradio/wavelet/squash_ff.h0000664000175000017500000000305212207440367024440 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WAVELET_SQUASH_FF_H #define INCLUDED_WAVELET_SQUASH_FF_H #include #include namespace gr { namespace wavelet { /*! * \brief Implements cheap resampling of spectrum directly from * spectral points, using gsl interpolation * \ingroup misc */ class WAVELET_API squash_ff : virtual public sync_block { public: // gr::wavelet::squash_ff::sptr typedef boost::shared_ptr sptr; /*! * \param igrid * \param ogrid */ static sptr make(const std::vector &igrid, const std::vector &ogrid); }; } /* namespace wavelet */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-wavelet/include/gnuradio/wavelet/api.h0000664000175000017500000000204512207440367023233 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WAVELET_API_H #define INCLUDED_WAVELET_API_H #include #ifdef gnuradio_wavelet_EXPORTS # define WAVELET_API __GR_ATTR_EXPORT #else # define WAVELET_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_WAVELET_API_H */ gnuradio-3.7.2.1/gr-wavelet/include/gnuradio/wavelet/wavelet_ff.h0000664000175000017500000000310012207440367024575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WAVELET_WAVELET_FF_H #define INCLUDED_WAVELET_WAVELET_FF_H #include #include namespace gr { namespace wavelet { /*! * \brief Compute wavelet transform using gsl routines. * \ingroup wavelet_blk */ class WAVELET_API wavelet_ff : virtual public sync_block { public: // gr::wavelet::wavelet_ff:sptr typedef boost::shared_ptr sptr; /*! * \param size * \param order * \param forward */ static sptr make(int size = 1024, int order = 20, bool forward = true); }; } /* namespace wavelet */ } /* namespace gr */ #endif /* INCLUDED_WAVELET_WAVELET_FF_H */ gnuradio-3.7.2.1/gr-wavelet/python/0000775000175000017500000000000012207440367016727 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/python/wavelet/0000775000175000017500000000000012207440367020376 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/python/wavelet/CMakeLists.txt0000664000175000017500000000316512207440367023143 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/wavelet COMPONENT "wavelet_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-wavelet/python/wavelet/__init__.py0000664000175000017500000000204312207440367022506 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Processing blocks for wavelet transforms. ''' import os try: from wavelet_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from wavelet_swig import * gnuradio-3.7.2.1/gr-wavelet/python/wavelet/qa_classify.py0000775000175000017500000001232312207440367023252 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy from gnuradio import gr, gr_unittest, wavelet, analog, blocks import copy #import pygsl.wavelet as wavelet # FIXME: pygsl not checked for in config import math def sqr(x): return x*x def np2(k): m = 0 n = k - 1 while n > 0: m += 1 return m class test_classify(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None # def test_000_(self): # src_data = numpy.zeros(10) # trg_data = numpy.zeros(10) # src = blocks.vector_source_f(src_data) # dst = blocks.vector_sink_f() # self.tb.connect(src, dst) # self.tb.run() # rsl_data = dst.data() # sum = 0 # for (u,v) in zip(trg_data, rsl_data): # w = u - v # sum += w * w # sum /= float(len(trg_data)) # assert sum < 1e-6 def test_001_(self): src_data = numpy.array([-1.0, 1.0, -1.0, 1.0]) trg_data = src_data * 0.5 src = blocks.vector_source_f(src_data) dst = blocks.vector_sink_f() rail = analog.rail_ff(-0.5, 0.5) self.tb.connect(src, rail) self.tb.connect(rail, dst) self.tb.run() rsl_data = dst.data() sum = 0 for (u, v) in zip(trg_data, rsl_data): w = u - v sum += w * w sum /= float(len(trg_data)) assert sum < 1e-6 def test_002_(self): src_data = numpy.array([-1.0, -1.0/2.0, -1.0/3.0, -1.0/4.0, -1.0/5.0]) trg_data = copy.deepcopy(src_data) src = blocks.vector_source_f(src_data, False, len(src_data)) st = blocks.stretch_ff(-1.0/5.0, len(src_data)) dst = blocks.vector_sink_f(len(src_data)) self.tb.connect(src, st) self.tb.connect(st, dst) self.tb.run() rsl_data = dst.data() sum = 0 for (u, v) in zip(trg_data, rsl_data): w = u - v sum += w * w sum /= float(len(trg_data)) assert sum < 1e-6 def test_003_(self): src_grid = (0.0, 1.0, 2.0, 3.0, 4.0) trg_grid = copy.deepcopy(src_grid) src_data = (0.0, 1.0, 0.0, 1.0, 0.0) src = blocks.vector_source_f(src_data, False, len(src_grid)) sq = wavelet.squash_ff(src_grid, trg_grid) dst = blocks.vector_sink_f(len(trg_grid)) self.tb.connect(src, sq) self.tb.connect(sq, dst) self.tb.run() rsl_data = dst.data() sum = 0 for (u, v) in zip(src_data, rsl_data): w = u - v sum += w * w sum /= float(len(src_data)) assert sum < 1e-6 # def test_004_(self): # FIXME: requires pygsl # # n = 256 # o = 4 # ws = wavelet.workspace(n) # w = wavelet.daubechies(o) # # a = numpy.arange(n) # b = numpy.sin(a*numpy.pi/16.0) # c = w.transform_forward(b, ws) # d = w.transform_inverse(c, ws) # # src = gr.vector_source_f(b, False, n) # wv = wavelet.wavelet_ff(n, o, True) # src = blocks.vector_source_f(b, False, n) # wv = wavelet.wavelet_ff(n, o, True) # # dst = blocks.vector_sink_f(n) # self.tb.connect(src, wv) # self.tb.connect(wv, dst) # self.tb.run() # e = dst.data() # # sum = 0 # for (u, v) in zip(c, e): # w = u - v # sum += w * w # sum /= float(len(c)) # assert sum < 1e-6 def test_005_(self): src_data = (1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0) dwav = numpy.array(src_data) wvps = numpy.zeros(3) # wavelet power spectrum scl = 1.0/sqr(dwav[0]) k = 1 for e in range(len(wvps)): wvps[e] = scl*sqr(dwav[k:k+(01< #include #include #include // NB in this version, only Daubechies wavelets // order is wavelet length, even, 2...20 namespace gr { namespace wavelet { wavelet_ff::sptr wavelet_ff::make(int size, int order, bool forward) { return gnuradio::get_initial_sptr(new wavelet_ff_impl(size, order, forward)); } wavelet_ff_impl::wavelet_ff_impl(int size, int order, bool forward) : sync_block("wavelet_ff", io_signature::make(1, 1, size * sizeof(float)), io_signature::make(1, 1, size * sizeof(float))), d_size(size), d_order(order), d_forward(forward) { d_wavelet = gsl_wavelet_alloc(gsl_wavelet_daubechies, d_order); if (d_wavelet == NULL) throw std::runtime_error("can't allocate wavelet"); d_workspace = gsl_wavelet_workspace_alloc(d_size); if (d_workspace == NULL) throw std::runtime_error("can't allocate wavelet workspace"); d_temp = (double *) malloc(d_size*sizeof(double)); if (d_workspace == NULL) throw std::runtime_error("can't allocate wavelet double conversion temp"); } wavelet_ff_impl::~wavelet_ff_impl() { gsl_wavelet_free(d_wavelet); gsl_wavelet_workspace_free(d_workspace); free((char *) d_temp); } int wavelet_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; for (int count = 0; count < noutput_items; count++) { for (int i = 0; i < d_size; i++) d_temp[i] = in[i]; if (d_forward) gsl_wavelet_transform_forward(d_wavelet, d_temp, 1, d_size, d_workspace); else gsl_wavelet_transform_inverse(d_wavelet, d_temp, 1, d_size, d_workspace); for (int i = 0; i < d_size; i++) out[i] = d_temp[i]; in += d_size; out += d_size; } return noutput_items; } } /* namespace wavelet */ } /* namespace gr */ gnuradio-3.7.2.1/gr-wavelet/lib/gnuradio-wavelet.rc.in0000664000175000017500000000164412207440367022371 0ustar jcorganjcorgan#include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-wavelet" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-wavelet.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-wavelet.dll" VALUE "ProductName", "gnuradio-wavelet" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-wavelet/lib/wvps_ff_impl.cc0000664000175000017500000000476512207440367021172 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace wavelet { static int ceil_log2(int k) { int m = 0; for (int n = k-1; n > 0; n >>= 1) m++; return m; } wvps_ff::sptr wvps_ff::make(int ilen) { return gnuradio::get_initial_sptr(new wvps_ff_impl(ilen)); } wvps_ff_impl::wvps_ff_impl(int ilen) : sync_block("wvps_ff", io_signature::make(1, 1, sizeof(float) * ilen), io_signature::make(1, 1, sizeof(float) * ceil_log2(ilen))), d_ilen(ilen), d_olen(ceil_log2(ilen)) { } // input vector assumed to be output from gsl wavelet computation int wvps_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; for (int count = 0; count < noutput_items; count++) { // any power? if (in[0] == 0.0) { for (int i = 0; i < d_olen; i++) out[i] = 0.0; } else { // get power normalization from 0-th wavelet coefficient float scl = 1.0/(in[0]*in[0]); int k = 1; // sum powers over sequences of bins, // sequence lengths in increasing powers of 2 for (int e = 0; e < d_olen; e++) { int m = 01< #include #include #include #include namespace gr { namespace wavelet { class WAVELET_API squash_ff_impl : public squash_ff { size_t d_inum; size_t d_onum; double *d_igrid; double *d_iwork; double *d_ogrid; gsl_interp_accel *d_accel; gsl_spline *d_spline; public: squash_ff_impl(const std::vector &igrid, const std::vector &ogrid); ~squash_ff_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace wavelet */ } /* namespace gr */ #endif /* INCLUDED_WAVELET_WAVELET_FF_IMPL_H */ gnuradio-3.7.2.1/gr-wavelet/lib/wvps_ff_impl.h0000664000175000017500000000250712207440367021024 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WAVELET_WVPS_FF_IMPL_H #define INCLUDED_WAVELET_WVPS_FF_IMPL_H #include namespace gr { namespace wavelet { class WAVELET_API wvps_ff_impl : public wvps_ff { int d_ilen; int d_olen; public: wvps_ff_impl(int ilen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace wavelet */ }/* namespace gr */ #endif /* INCLUDED_WAVELET_WVPS_FF_IMPL_H */ gnuradio-3.7.2.1/gr-wavelet/lib/squash_ff_impl.cc0000664000175000017500000000565112207440367021472 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include // expect input vector of igrid.size y-values, // produce output vector of ogrid.size y-values namespace gr { namespace wavelet { squash_ff::sptr squash_ff::make(const std::vector &igrid, const std::vector &ogrid) { return gnuradio::get_initial_sptr(new squash_ff_impl(igrid, ogrid)); } squash_ff_impl::squash_ff_impl(const std::vector &igrid, const std::vector &ogrid) : sync_block("squash_ff", io_signature::make(1, 1, sizeof(float) * igrid.size()), io_signature::make(1, 1, sizeof(float) * ogrid.size())) { d_inum = igrid.size(); d_onum = ogrid.size(); d_igrid = (double *) malloc(d_inum * sizeof(double)); d_iwork = (double *) malloc(d_inum * sizeof(double)); d_ogrid = (double *) malloc(d_onum * sizeof(double)); for (unsigned int i = 0; i < d_inum; i++) d_igrid[i] = igrid[i]; for (unsigned int i = 0; i < d_onum; i++) d_ogrid[i] = ogrid[i]; d_accel = gsl_interp_accel_alloc(); d_spline = gsl_spline_alloc(gsl_interp_cspline, d_inum); // FIXME check w/ Frank } squash_ff_impl::~squash_ff_impl() { free((char *) d_igrid); free((char *) d_iwork); free((char *) d_ogrid); gsl_interp_accel_free(d_accel); gsl_spline_free(d_spline); } int squash_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; for (int count = 0; count < noutput_items; count++) { for (unsigned int i = 0; i < d_inum; i++) d_iwork[i] = in[i]; gsl_spline_init(d_spline, d_igrid, d_iwork, d_inum); for (unsigned int i = 0; i < d_onum; i++) out[i] = gsl_spline_eval(d_spline, d_ogrid[i], d_accel); in += d_inum; out += d_onum; } return noutput_items; } } /* namespace wavelet */ } /* namespace gr */ gnuradio-3.7.2.1/gr-wavelet/lib/wavelet_ff_impl.h0000664000175000017500000000322212207440367021467 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_WAVELET_WAVELET_FF_IMPL_H #define INCLUDED_WAVELET_WAVELET_FF_IMPL_H #include #include #include namespace gr { namespace wavelet { class WAVELET_API wavelet_ff_impl : public wavelet_ff { int d_size; int d_order; bool d_forward; gsl_wavelet *d_wavelet; gsl_wavelet_workspace *d_workspace; double *d_temp; public: wavelet_ff_impl(int size, int order, bool forward); ~wavelet_ff_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace wavelet */ } /* namespace gr */ #endif /* INCLUDED_WAVELET_WAVELET_FF_IMPL_H */ gnuradio-3.7.2.1/gr-wavelet/swig/0000755000175000017500000000000012207440367016355 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-wavelet/swig/CMakeLists.txt0000664000175000017500000000356412207440367021127 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_WAVELET_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${GSL_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/wavelet_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/wavelet) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-wavelet ${GSL_LDFLAGS}) GR_SWIG_MAKE(wavelet_swig wavelet_swig.i) GR_SWIG_INSTALL( TARGETS wavelet_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/wavelet COMPONENT "wavelet_python" ) install( FILES wavelet_swig.i ${CMAKE_CURRENT_BINARY_DIR}/wavelet_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "wavelet_swig" ) gnuradio-3.7.2.1/gr-wavelet/swig/wavelet_swig.i0000664000175000017500000000242712207440367021236 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define WAVELET_API %include "gnuradio.i" //load generated python docstrings %include "wavelet_swig_doc.i" %{ #include "gnuradio/wavelet/squash_ff.h" #include "gnuradio/wavelet/wavelet_ff.h" #include "gnuradio/wavelet/wvps_ff.h" %} %include "gnuradio/wavelet/squash_ff.h" %include "gnuradio/wavelet/wavelet_ff.h" %include "gnuradio/wavelet/wvps_ff.h" GR_SWIG_BLOCK_MAGIC2(wavelet, squash_ff); GR_SWIG_BLOCK_MAGIC2(wavelet, wavelet_ff); GR_SWIG_BLOCK_MAGIC2(wavelet, wvps_ff); gnuradio-3.7.2.1/gr-channels/0000775000175000017500000000000012207702530015523 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/CMakeLists.txt0000664000175000017500000000714712207702530020274 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-channels" ENABLE_GR_CHANNELS ENABLE_VOLK Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_BLOCKS ENABLE_GR_FFT ENABLE_GR_FILTER ENABLE_GR_ANALOG ) GR_SET_GLOBAL(GR_CHANNELS_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/include ) SET(GR_PKG_CHANNELS_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/channels) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_CHANNELS) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_CHANNELS_DESCRIPTION "GNU Radio Channel Model Blocks") CPACK_COMPONENT("channels_runtime" GROUP "Channel Models" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("channels_devel" GROUP "Channel Models" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("channels_python" GROUP "Channel Models" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;channels_runtime" ) CPACK_COMPONENT("channels_swig" GROUP "Channel Models" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;channels_python;channels_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/channels) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/channels) add_subdirectory(grc) add_subdirectory(examples) endif(ENABLE_PYTHON) add_subdirectory(doc) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-channels.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-channels.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-channels.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "channels_devel" ) endif(ENABLE_GR_CHANNELS) gnuradio-3.7.2.1/gr-channels/include/0000775000175000017500000000000012207440367017155 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/include/gnuradio/0000775000175000017500000000000012207440367020765 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/0000775000175000017500000000000012244272666022566 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/CMakeLists.txt0000664000175000017500000000217312207702530025314 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h channel_model.h channel_model2.h fading_model.h selective_fading_model.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/channels COMPONENT "channels_devel" ) gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/channel_model.h0000664000175000017500000000740712244272666025537 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CHANNEL_MODEL_H #define INCLUDED_CHANNELS_CHANNEL_MODEL_H #include #include #include namespace gr { namespace channels { /*! * \brief Basic channel simulator. * \ingroup channel_models_blk * * \details * This block implements a basic channel model simulator that can * be used to help evaluate, design, and test various signals, * waveforms, and algorithms. * * This model allows the user to set the voltage of an AWGN noise * source (\p noise_voltage), a (normalized) frequency offset (\p * frequency_offset), a sample timing offset (\p epsilon), and a * seed (\p noise_seed) to randomize or make reproducable the AWGN * noise source. * * Multipath can be approximated in this model by using a FIR * filter representation of a multipath delay profile with the * parameter \p taps. * * To simulate a channel with time-variant channel, use * gr::channels::channel_model2. */ class CHANNELS_API channel_model : virtual public hier_block2 { public: // gr::channels::channel_model::sptr typedef boost::shared_ptr sptr; /*! \brief Build the channel simulator. * * \param noise_voltage The AWGN noise level as a voltage (to be * calculated externally to meet, say, a * desired SNR). * \param frequency_offset The normalized frequency offset. 0 is * no offset; 0.25 would be, for a digital * modem, one quarter of the symbol rate. * \param epsilon The sample timing offset to emulate the * different rates between the sample clocks of * the transmitter and receiver. 1.0 is no difference. * \param taps Taps of a FIR filter to emulate a multipath delay profile. * \param noise_seed A random number generator seed for the noise source. * \param block_tags If true, tags will not be able to propagate through this block. */ static sptr make(double noise_voltage=0.0, double frequency_offset=0.0, double epsilon=1.0, const std::vector &taps=std::vector(1,1), double noise_seed=0, bool block_tags=false); virtual void set_noise_voltage(double noise_voltage) = 0; virtual void set_frequency_offset(double frequency_offset) = 0; virtual void set_taps(const std::vector &taps) = 0; virtual void set_timing_offset(double epsilon) = 0; virtual double noise_voltage() const = 0; virtual double frequency_offset() const = 0; virtual std::vector taps() const = 0; virtual double timing_offset() const = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/cfo_model.h0000664000175000017500000000477112237515112024663 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CFO_MODEL_H #define INCLUDED_CHANNELS_CFO_MODEL_H #include #include #include namespace gr { namespace channels { /*! * \brief channel simulator * \ingroup channel_models_blk * * \details * This block implements a carrier frequency offset model that * can be used to simulate carrier frequency drift typically from * mixer LO drift on either transmit or receive hardware. * * A clipped gaussian random walk process is used. */ class CHANNELS_API cfo_model : virtual public sync_block { public: // gr::channels::cfo_model::sptr typedef boost::shared_ptr sptr; /*! \brief Build the carrier frequency offset model * * \param sample_rate_hz Sample rate of the input signal in Hz * \param std_dev_hz Desired standard deviation of the random walk process every sample in Hz * \param max_dev_hz Maximum carrier frequency deviation in Hz. * \param noise_seed A random number generator seed for the noise source. */ static sptr make( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed=0); virtual void set_std_dev(double _dev) = 0; virtual void set_max_dev(double _dev) = 0; virtual void set_samp_rate(double _rate) = 0; virtual double std_dev() const = 0; virtual double max_dev() const = 0; virtual double samp_rate() const = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CFO_MODEL_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/selective_fading_model.h0000664000175000017500000000564512207702530027407 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_SELECTIVE_FADING_MODEL_H #define INCLUDED_CHANNELS_SELECTIVE_FADING_MODEL_H #include #include #include namespace gr { namespace channels { const float default_delays[] = {0.0,0.1,0.5}; const float default_mags[] = {1.0,0.8,0.3}; /*! * \brief fading simulator * \ingroup channel_models_blk * * \details * This block implements a basic fading model simulator that can * be used to help evaluate, design, and test various signals, * waveforms, and algorithms. */ class CHANNELS_API selective_fading_model : virtual public sync_block { public: // gr::channels::channel_model::sptr typedef boost::shared_ptr sptr; /*! \brief Build the channel simulator. * * \param N The number of sinusiods to use in simulating the channel; 8 is a good value * \param fDTs normalized maximum Doppler frequency, fD * Ts * \param LOS include Line-of-Site path? selects between Rayleigh (NLOS) and Rician (LOS) models * \param K Rician factor (ratio of the specular power to the scattered power) * \param seed a random number to seed the noise generators * \param delays A vector of values the specify the time delay of each impulse * \param mags A vector of values that specifies the magnitude of each impulse * \param ntaps The number of filter taps. */ static sptr make(unsigned int N, float fDTs, bool LOS, float K, int seed, std::vector delays, std::vector mags, int ntaps ); virtual float fDTs() = 0; virtual float K() = 0; virtual float step() = 0; virtual void set_fDTs(float fDTs) = 0; virtual void set_K(float K) = 0; virtual void set_step(float step) = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_SELECTIVE_FADING_MODEL_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/sro_model.h0000664000175000017500000000461512237515112024714 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_SRO_MODEL_H #define INCLUDED_CHANNELS_SRO_MODEL_H #include #include #include namespace gr { namespace channels { /*! * \brief Sample Rate Offset Model * \ingroup channel_models_blk * * \details * This block implements a model that varies sample rate offset * with respect to time by performing a random walk on the * interpolation rate. */ class CHANNELS_API sro_model : virtual public block { public: // gr::channels::sro_model::sptr typedef boost::shared_ptr sptr; /*! \brief Build the sample rate offset model * * \param sample_rate_hz Sample rate of the input signal in Hz * \param std_dev_hz Desired standard deviation of the random walk process every sample in Hz * \param max_dev_hz Maximum sample rate deviation from zero in Hz. * \param noise_seed A random number generator seed for the noise source. */ static sptr make( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed=0); virtual void set_std_dev(double _dev) = 0; virtual void set_max_dev(double _dev) = 0; virtual void set_samp_rate(double _rate) = 0; virtual double std_dev() const = 0; virtual double max_dev() const = 0; virtual double samp_rate() const = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_SRO_MODEL_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/fading_model.h0000664000175000017500000000465412207702530025343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_FADING_MODEL_H #define INCLUDED_CHANNELS_FADING_MODEL_H #include #include #include namespace gr { namespace channels { /*! * \brief fading simulator * \ingroup channel_models_blk * * \details * This block implements a basic fading model simulator that can * be used to help evaluate, design, and test various signals, * waveforms, and algorithms. */ class CHANNELS_API fading_model : virtual public sync_block { public: // gr::channels::channel_model::sptr typedef boost::shared_ptr sptr; /*! \brief Build the channel simulator. * * \param N The number of sinusiods to use in simulating the channel; 8 is a good value * \param fDTs normalized maximum Doppler frequency, fD * Ts * \param LOS include Line-of-Site path? selects between Rayleigh (NLOS) and Rician (LOS) models * \param K Rician factor (ratio of the specular power to the scattered power) * \param seed a random number to seed the noise generators */ static sptr make(unsigned int N, float fDTs=0.01, bool LOS=true, float K=4, int seed=0); virtual float fDTs() = 0; virtual float K() = 0; virtual float step() = 0; virtual void set_fDTs(float fDTs) = 0; virtual void set_K(float K) = 0; virtual void set_step(float step) = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_FADING_MODEL_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/channel_model2.h0000664000175000017500000001053712244272666025617 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CHANNEL_MODEL2_H #define INCLUDED_CHANNELS_CHANNEL_MODEL2_H #include #include #include namespace gr { namespace channels { /*! * \brief Basic channel simulator allowing time-varying frequency * and timing inputs. * \ingroup channel_models_blk * * \details * This block implements a basic channel model simulator that can * be used to help evaluate, design, and test various signals, * waveforms, and algorithms. * * This model allows the user to set the voltage of an AWGN noise * source (\p noise_voltage), an initial timing offset (\p * epsilon), and a seed (\p noise_seed) to randomize the AWGN * noise source. * * Multipath can be approximated in this model by using a FIR * filter representation of a multipath delay profile with the * parameter \p taps. * * Unlike gr::channels::channel_model, this block is designed to * enable time-varying frequency and timing offsets. * * Port 0: input signal to be run through the channel. * * Port 1: frequency function. A constant value between -0.5 and * 0.5 here will turn into a constant frequency offset * from -fs/2 to fs/2 (where fs is the sample rate). * * Port 2: timing offset function. Sets the resampling rate of * the channel model. A constant value here produces * that value as the timing offset, so a constant 1.0 * input stream is the same as not having a timing * offset. * * Since the models for frequency and timing offset may vary and * what we are trying to model may be different for different * simulations, we provide the time-varying nature as an input * function that is user-defined. If only constant frequency and * timing offsets are required, it is easier and less expensive to * use gr::channels::channel_model. */ class CHANNELS_API channel_model2 : virtual public hier_block2 { public: // gr::channels::channel_model2::sptr typedef boost::shared_ptr sptr; /*! \brief Build the channel simulator. * * \param noise_voltage The AWGN noise level as a voltage (to be * calculated externally to meet, say, a * desired SNR). * \param epsilon The initial sample timing offset to emulate the * different rates between the sample clocks of * the transmitter and receiver. 1.0 is no difference. * \param taps Taps of a FIR filter to emulate a multipath delay profile. * \param noise_seed A random number generator seed for the noise source. * \param block_tags If true, tags will not be able to propagate through this block. */ static sptr make(double noise_voltage=0.0, double epsilon=1.0, const std::vector &taps=std::vector(1,1), double noise_seed=0, bool block_tags=false); virtual void set_noise_voltage(double noise_voltage) = 0; virtual void set_taps(const std::vector &taps) = 0; virtual void set_timing_offset(double epsilon) = 0; virtual double noise_voltage() const = 0; virtual std::vector taps() const = 0; virtual double timing_offset() const = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL2_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/api.h0000664000175000017500000000205312207440367023502 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_API_H #define INCLUDED_CHANNELS_API_H #include #ifdef gnuradio_channels_EXPORTS # define CHANNELS_API __GR_ATTR_EXPORT #else # define CHANNELS_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_CHANNELS_API_H */ gnuradio-3.7.2.1/gr-channels/include/gnuradio/channels/dynamic_channel_model.h0000664000175000017500000001206112237515112027217 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_DYNAMIC_CHANNEL_MODEL_H #define INCLUDED_CHANNELS_DYNAMIC_CHANNEL_MODEL_H #include #include #include namespace gr { namespace channels { /*! * \brief dynamic channel simulator * \ingroup dynamic_channel_models_blk * * \details * This block implements a dynamic channel model simulator that can * be used to help evaluate, design, and test various signals, * waveforms, and algorithms. * * This model allows the user to set up an AWGN noise cource, a * random walk process to simulate carrier frequency drift, a random * walk process to simulate sample rate offset drive, and a frequency * selective fading channel response that is either Rayleigh or Ricean * for a user specified power delay profile. */ class CHANNELS_API dynamic_channel_model : virtual public hier_block2 { public: // gr::channels::dynamic_channel_model::sptr typedef boost::shared_ptr sptr; /*! \brief Build the dynamic channel simulator. * * \param samp_rate Input sample rate in Hz * \param sro_std_dev sample rate drift process standard deviation per sample in Hz * \param sro_max_dev maximum sample rate offset in Hz * \param cfo_std_dev carrier frequnecy drift process standard deviation per sample in Hz * \param cfo_max_dev maximum carrier frequency offset in Hz * \param N number of sinusoids used in frequency selective fading simulation * \param doppler_freq maximum doppler frequency used in fading simulation in Hz * \param LOS_model defines whether the fading model should include a line of site component. LOS->Rician, NLOS->Rayleigh * \param K Rician K-factor, the ratio of specular to diffuse power in the model * \param delays A list of fractional sample delays making up the power delay profile * \param mags A list of magnitudes corresponding to each delay time in the power delay profile * \param ntaps_mpath The length of the filter to interpolate the power delay profile over. Delays in the PDP must lie between 0 and ntaps_mpath, fractional delays will be sinc-interpolated only to the width of this filter. * \param noise_amp Specifies the standard deviation of the AWGN process * \param noise_seed A random number generator seed for the noise source. */ static sptr make( double samp_rate, double sro_std_dev, double sro_max_dev, double cfo_std_dev, double cfo_max_dev, unsigned int N, double doppler_freq, bool LOS_model, float K, std::vector delays, std::vector mags, int ntaps_mpath, double noise_amp, double noise_seed ); virtual double samp_rate() const = 0; virtual double sro_dev_std() const = 0; virtual double sro_dev_max() const = 0; virtual double cfo_dev_std() const = 0; virtual double cfo_dev_max() const = 0; virtual double noise_amp() const = 0; virtual double doppler_freq() const = 0; virtual double K() const = 0; virtual void set_samp_rate(double) = 0; virtual void set_sro_dev_std(double) = 0; virtual void set_sro_dev_max(double) = 0; virtual void set_cfo_dev_std(double) = 0; virtual void set_cfo_dev_max(double) = 0; virtual void set_noise_amp(double) = 0; virtual void set_doppler_freq(double) = 0; virtual void set_K(double) = 0; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL_H */ gnuradio-3.7.2.1/gr-channels/grc/0000775000175000017500000000000012237515112016277 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/grc/CMakeLists.txt0000664000175000017500000000161012207702530021034 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. file(GLOB xml_files "*.xml") install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "channels_python" ) gnuradio-3.7.2.1/gr-channels/grc/channels_distortion_3_gen.xml0000664000175000017500000000120712207702530024144 0ustar jcorganjcorgan Third Order Distortion channels_distortion_3_gen from gnuradio import channels channels.distortion_3_gen($beta) set_beta($beta) Distortion beta 0 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_channel_model.xml0000664000175000017500000000327112237515112023467 0ustar jcorganjcorgan Channel Model channels_channel_model from gnuradio import channels from gnuradio.filter import firdes channels.channel_model( noise_voltage=$noise_voltage, frequency_offset=$freq_offset, epsilon=$epsilon, taps=$taps, noise_seed=$seed, block_tags=$block_tags ) set_noise_voltage($noise_voltage) set_frequency_offset($freq_offset) set_taps($taps) set_timing_offset($epsilon) Noise Voltage noise_voltage 0.0 real Frequency Offset freq_offset 0.0 real Epsilon epsilon 1.0 real Taps taps 1.0 + 1.0j complex_vector Seed seed 0 int Block Tag Propagation block_tags False enum $block_tags.hide_block in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_sro_model.xml0000664000175000017500000000207012237515112022656 0ustar jcorganjcorgan SRO Model channels_sro_model from gnuradio import channels channels.sro_model( $srate, $stdev, $maxdev, $seed ) set_std_dev($stdev) set_max_dev($maxdev) set_samp_rate($srate) Sample Rate Hz srate samp_rate real SRO Standard Deviation Hz per sample stdev 0.01 real Max SRO Bound Hz maxdev 1e3 real Seed seed 0 int in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_block_tree.xml0000664000175000017500000000336712237515112023016 0ustar jcorganjcorgan Channel Models channels_channel_model channels_channel_model2 channels_conj_fs_iqcorr channels_fading_model channels_dynamic_channel_model channels_selective_fading_model Impairment Models channels_impairments channels_quantizer channels_phase_noise_gen channels_iqbal_gen channels_distortion_2_gen channels_distortion_3_gen channels_amp_bal channels_phase_bal channels_cfo_model channels_sro_model gnuradio-3.7.2.1/gr-channels/grc/channels_channel_model2.xml0000664000175000017500000000314712237515112023553 0ustar jcorganjcorgan Channel Model 2 channels_channel_model2 from gnuradio import channels from gnuradio.filter import firdes channels.channel_model2( noise_voltage=$noise_voltage, epsilon=$epsilon, taps=$taps, noise_seed=$seed, block_tags=$block_tags ) set_noise_voltage($noise_voltage) set_taps($taps) set_timing_offset($epsilon) Noise Voltage noise_voltage 0.0 real Time Offset epsilon 1.0 real Taps taps 1.0 + 1.0j complex_vector Seed seed 0 int Block Tag Propagation block_tags False enum $block_tags.hide_block in complex freq float time float out complex gnuradio-3.7.2.1/gr-channels/grc/channels_fading_model.xml0000664000175000017500000000365212207440367023320 0ustar jcorganjcorgan Fading Model channels_fading_model from gnuradio import channels channels.fading_model( $N, $fDTs, $LOS, $K, $seed ) set_fDTs($fDTs) set_K($K) Num Sinusoids (SoS model) N 8 int Normalized Max Doppler (fD*Ts) fDTs 10.0/samp_rate real LOS Model LOS enum Rician factor (K) K 4.0 real $LOS.hide_K Seed seed 0 int in complex out complex This algorithm implements the method described in Compact Rayleigh and Rician fading simulator based on random walk processes A. Alimohammad S.F. Fard B.F. Cockburn C. Schlegel 26th November 2008 int d_N=8; // number of sinusoids float d_fDTs=0.01 // normalized maximum doppler frequency (f_doppler / f_samprate) float d_K=4; // Rician factor (ratio of the specular power to the scattered power) bool d_LOS=true; // LOS path exists? chooses Rician (LOS) vs Rayleigh (NLOS) model. int seed=0; // noise seed gnuradio-3.7.2.1/gr-channels/grc/channels_dynamic_channel_model.xml0000664000175000017500000000762212237515112025177 0ustar jcorganjcorgan Dynamic Channel Model channels_dynamic_channel_model from gnuradio import channels channels.dynamic_channel_model( $samp_rate, $sro_stdev, $sro_maxdev, $cfo_stdev, $cfo_maxdev, $N, $fD, $LOS, $K, $delays, $mags, $ntaps, $noise_amp, $seed ) set_samp_rate($samp_rate) set_sro_dev_std($sro_stdev) set_sro_dev_max($sro_maxdev) set_cfo_dev_std($cfo_stdev) set_cfo_dev_max($cfo_maxdev) set_noise_amp($noise_amp) set_doppler_freq($fD) set_K($K) Sample Rate Hz samp_rate samp_rate real CFO Standard Deviation Hz per sample cfo_stdev 0.01 real Max CFO Bound Hz cfo_maxdev 1e3 real SRO Standard Deviation Hz per sample sro_stdev 0.01 real Max SRO Bound Hz sro_maxdev 1e3 real White Noise Amplitude noise_amp 1.0 real Num Sinusoids (SoS model) N 8 int Max Doppler Freq (Hz) fD 2.0 real LOS Model LOS enum Rician factor (K) K 4.0 real $LOS.hide_K Seed seed 0 int PDP Delays (samp) delays 0.0,0.1,1.3 real_vector PDP Magnitudes mags 1,0.99,0.97 real_vector Num Taps ntaps 8 int in complex out complex The dynamic channel model is a hier block consisting of the following effects: - Dynamic Frequency Selective Fading Channel - Dynamic Center Frequency Offset Model - Dynamic Sample Rate Offset Model - Additive White Gaussian Noise The desired power delay profile and max doppler frequency may be provided to achieve the desired Ricean or Rayleigh fading scenario. For center frequency and sample rate offset models, a gaussian random walk process is conducted for each. The single sample step variance and maximum deviation for these two processes is specified and may be modified to simulate various desired stability effects. Lastly AWGN is added to simulate a typical receiver/thermal noise floor after propagation, and the variance may be modified here as desired. gnuradio-3.7.2.1/gr-channels/grc/channels_conj_fs_iqcorr.xml0000664000175000017500000000144612207702530023700 0ustar jcorganjcorgan Freq. Selective IQ Correction channels_conj_fs_iqcorr from gnuradio import channels channels.conj_fs_iqcorr($delay, $taps) set_delay($delay) set_taps($taps) Delay delay 0 int Taps taps 0 complex_vector in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_distortion_2_gen.xml0000664000175000017500000000121112207702530024136 0ustar jcorganjcorgan Second Order Distortion channels_distortion_2_gen from gnuradio import channels channels.distortion_2_gen($beta) set_beta($beta) Distortion beta 0 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_phase_bal.xml0000664000175000017500000000113412207702530022610 0ustar jcorganjcorgan Phase Balance channels_phase_bal from gnuradio import channels channels.phase_bal($alpha) set_alpha($alpha) Alpha alpha 0 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_phase_noise_gen.xml0000664000175000017500000000146212207702530024024 0ustar jcorganjcorgan Phase Noise Generator channels_phase_noise_gen from gnuradio import channels channels.phase_noise_gen($noise_mag, $alpha) set_noise_mag($noise_mag) set_alpha($alpha) Noise Magnitude noise_mag 0 float Alpha alpha 0.1 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_iqbal_gen.xml0000664000175000017500000000141612207702530022616 0ustar jcorganjcorgan IQ Imbalance Generator channels_iqbal_gen from gnuradio import channels channels.iqbal_gen($mag, $phase) set_magnitude($mag) set_phase($phase) Magnitude mag 0 float Phase phase 0 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_amp_bal.xml0000664000175000017500000000114012207702530022262 0ustar jcorganjcorgan Amplitude Balance channels_amp_bal from gnuradio import channels channels.amp_bal($alpha) set_alpha($alpha) Alpha alpha 0 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_cfo_model.xml0000664000175000017500000000207012237515112022622 0ustar jcorganjcorgan CFO Model channels_cfo_model from gnuradio import channels channels.cfo_model( $srate, $stdev, $maxdev, $seed ) set_std_dev($stdev) set_max_dev($maxdev) set_samp_rate($srate) Sample Rate Hz srate samp_rate real CFO Standard Deviation Hz per sample stdev 0.01 real Max CFO Bound Hz maxdev 1e3 real Seed seed 0 int in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_selective_fading_model.xml0000664000175000017500000000620112207440367025354 0ustar jcorganjcorgan Frequency Selective Fading Model channels_selective_fading_model from gnuradio import channels channels.selective_fading_model( $N, $fDTs, $LOS, $K, $seed, $delays, $mags, $ntaps ) set_fDTs($fDTs) set_K($K) Num Sinusoids (SoS model) N 8 int Normalized Max Doppler (fD*Ts) fDTs 10.0/samp_rate real LOS Model LOS enum Rician factor (K) K 4.0 real $LOS.hide_K Seed seed 0 int PDP Delays (samp) delays 0.0,0.1,1.3 real_vector PDP Magnitudes mags 1,0.99,0.97 real_vector Num Taps ntaps 8 int in complex out complex int d_N=8; // number of sinusoids used to simulate gain on each ray float d_fDTs=0.01 // normalized maximum doppler frequency (f_doppler / f_samprate) float d_K=4; // Rician factor (ratio of the specular power to the scattered power) bool d_LOS=true; // LOS path exists? chooses Rician (LOS) vs Rayleigh (NLOS) model. int seed=0; // noise seed int ntaps; // Number of FIR taps to use in selective fading model These two vectors comprise the Power Delay Profile of the signal float_vector delays // Time delay in the fir filter (in samples) for each arriving WSSUS Ray float_vector mags // Magnitude corresponding to each WSSUS Ray If using a LOS model, the first delay and mag should correspond with the LOS component References: The flat-fading portion of the algorithm implements the following Compact Rayleigh and Rician fading simulator based on random walk processes A. Alimohammad S.F. Fard B.F. Cockburn C. Schlegel 26th November 2008 The frequency selective extension of the block roughly implements A Low-Complexity Hardware Implementation of Discrete-Time Frequency-Selective Rayleigh Fading Channels F. Ren and Y. Zheng 24-27 May 2009 Implementation by Tim O'Shea gnuradio-3.7.2.1/gr-channels/grc/channels_impairments.xml0000664000175000017500000000355312207702530023231 0ustar jcorganjcorgan HW Impairments channels_impairments from gnuradio import channels channels.impairments($phase_noise_mag, $magbal, $phasebal, $q_ofs, $i_ofs, $freq_offset, $gamma, $beta) set_phase_noise_mag($phase_noise_mag) set_magbal($magbal) set_phasebal($phasebal) set_q_ofs($q_ofs) set_i_ofs($i_ofs) set_freq_offset($freq_offset) set_gamma($gamma) set_beta($beta) Phase Noise Mag. phase_noise_mag 0 float IQ Mag. Imbalance magbal 0 float IQ Phase. Imbalance phasebal 0 float Quadrature Offset q_ofs 0 float Inphase Offset i_ofs 0 float Frequency Offset freq_offset 0 float Second Order Distortion gamma 0 float Third Order Distortion beta 0 float in complex out complex gnuradio-3.7.2.1/gr-channels/grc/channels_quantizer.xml0000664000175000017500000000111512207702530022713 0ustar jcorganjcorgan Quantizer channels_quantizer from gnuradio import channels channels.quantizer($bits) set_bits($bits) Bits bits 16 int in float out float gnuradio-3.7.2.1/gr-channels/gnuradio-channels.pc.in0000664000175000017500000000044612207440367022070 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-channels Description: GNU Radio's channel model blocks Requires: gnuradio-runtime gnuradio-filter Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-channels -lgnuradio-filter Cflags: -I${includedir} gnuradio-3.7.2.1/gr-channels/doc/0000775000175000017500000000000012207702530016270 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/doc/CMakeLists.txt0000664000175000017500000000152212207440367021037 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.channels DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-channels/doc/channels.dox0000664000175000017500000001277212207702530020610 0ustar jcorganjcorgan/*! \page page_channels Channel Model Blocks \section Introduction This is the gr-channels package. It contains signal processing blocks to simulate channel models. The Python namespace is in gnuradio.channels, which would be normally imported as: \code from gnuradio import channels \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(channels) \endcode \section channels_types Available Channel Models \subsection channels_awgn AWGN Channel The basic gr::channels::channel_model block is essentially an additive white Gaussian noise (AWGN) channel with a few extra additions. This channel model simulates AWGN as well as frequency and timing offsets between the transmit and receiver and a simple static multipath environment. The parameters include: \li noise_voltage: The AWGN noise level as a voltage (to be calculated externally to meet, say, a desired SNR). \li frequency_offset The normalized frequency offset. 0 is no offset; 0.25 would be, for a digital modem, one quarter of the symbol rate. \li epsilon The sample timing offset to emulate the different rates between the sample clocks of the transmitter and receiver. 1.0 is no difference. \li taps Taps of a FIR filter to emulate a multipath delay profile. \li noise_seed A random number generator seed for the noise source. \subsection channels_fading Fading Channel Model The gr::channels::fading_model builds a basic fading simulation. This model approximates a fading channel using the sum of sinusoids method for the number of expected multipath components. This block also takes in the Doppler frequency shift as a normalized value, a line-of-sight (LOS) parameter that is either true or false, the Rician K factor, and a random seed to the noise generators. These parameters are provided in the documentation as: \li N The number of sinusiods to use in simulating the channel 8 is a good value \li fDTs normalized maximum Doppler frequency, fD * Ts \li LOS include Line-of-Site path? selects between Rayleigh (NLOS) and Rician (LOS) models \li K Rician factor (ratio of the specular power to the scattered power) \li seed a random number to seed the noise generators \subsection channels_selective_fading Frequency-Selective Fading Model Extending the fading model, the gr::channels::selective_fading_model channel model allows us to specify frequency selective parameters for the model. Starting with the same inputs as the gr::channels::fading_model, this block also takes in power delay profile (PDP). The PDP is given as a vector of the times of the delays and another vector of the corresponding magnitudes of the PDP. We also specify the number of taps in the filter to simulate this. These parameters are provided in the documentation as: \li N The number of sinusiods to use in simulating the channel 8 is a good value \li fDTs normalized maximum Doppler frequency, fD * Ts \li LOS include Line-of-Site path? selects between Rayleigh (NLOS) and Rician (LOS) models \li K Rician factor (ratio of the specular power to the scattered power) \li seed a random number to seed the noise generators \li delays A vector of values the specify the time delay of each impulse \li mags A vector of values that specifies the magnitude of each impulse \li ntaps The number of filter taps. \subsection channels_hw_impairments Hardware Impairments Model GNU Radio also provides a model for incorporating parameters of a radio transmitter and receiver to better simulate signals as they would be transmitted and received through real hardware. This simulation tool can be used to see how a waveform would behave over a known radio, or if designing radio hardware, this block could help understand the requirements and tolerances for the new system. The hardware impairments model is a Python-only hierarchical block, which is declared as digital.impairments(...). The block is also represented in GRC under the "Impairment Models" category. The impairments model is actually made up of a handful of other hierarchical blocks, each of which perform one aspect of the impairments model. Each subsection is usable on its own, and each one can be used in GRC. These subsystems are: \li digital.phase_noise_gen ("Phase Noise Generator") \li digital.iqbal_gen ("IQ Imbalance Generator") \li digital.distortion_3_gen ("Third Order Distortion") \li digital.distortion_2_gen ("Second Order Distortion") There are also a few other blocks that were built to develop and simulate different hardware behaviors \li digital.quantizer ("Quantizer"): quantizes to b number of bits. \li digital.amp_bal ("Amplitude Balance"): corrects IQ amplitude imbalance. \li digital.phase_bal ("Phase Balance"): corrects IQ phase imbalance. The digital.impairments model combines the phase noise, IQ imbalance, and second and third order distortion generators. It also performs I and Q offset imbalance and internal frequency shifting problems. The parameters for using the hardware impairments model are: \li phase_noise_mag: the level of the phase noise (in dB). \li magbal: The level of the magnitude imbalance between I and Q. \li phasebal: The level of the phase imbalance (as an angle). \li q_ofs: Offset value of the quadrature arm (as a magnitude). \li i_ofs: Offset value of the in-phase arm (as a magnitude). \li freq_offset: normalized frequency offset. \li gamma: Level of the 2nd order distortion. \li beta: level of the 3rd order distortion. */ gnuradio-3.7.2.1/gr-channels/doc/README.channels0000664000175000017500000000062412207440367020753 0ustar jcorganjcorganThis is the gr-channels package. It contains signal processing blocks to simulate channel models. The Python namespace is in gnuradio.channels, which would be normally imported as: from gnuradio import channels See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(channels) gnuradio-3.7.2.1/gr-channels/python/0000775000175000017500000000000012207440367017053 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/python/channels/0000775000175000017500000000000012207702530020637 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/python/channels/CMakeLists.txt0000664000175000017500000000345712207702530023410 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py amp_bal.py conj_fs_iqcorr.py distortion_2_gen.py distortion_3_gen.py impairments.py iqbal_gen.py phase_bal.py phase_noise_gen.py quantizer.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/channels COMPONENT "channels_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file (GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-channels/python/channels/quantizer.py0000664000175000017500000000377312207702530023245 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Quantizer # Generated: Thu Aug 1 11:09:51 2013 ################################################## from gnuradio import blocks from gnuradio import gr from gnuradio.filter import firdes class quantizer(gr.hier_block2): def __init__(self, bits=16): gr.hier_block2.__init__( self, "Quantizer", gr.io_signature(1, 1, gr.sizeof_float*1), gr.io_signature(1, 1, gr.sizeof_float*1), ) ################################################## # Parameters ################################################## self.bits = bits ################################################## # Blocks ################################################## self.blocks_short_to_float_0 = blocks.short_to_float(1, 1) self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff((1.0/pow(2.0,bits-1.0), )) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((pow(2,bits-1.0), )) self.blocks_float_to_short_0 = blocks.float_to_short(1, 1) ################################################## # Connections ################################################## self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self, 0)) self.connect((self.blocks_short_to_float_0, 0), (self.blocks_multiply_const_vxx_0_0, 0)) self.connect((self.blocks_float_to_short_0, 0), (self.blocks_short_to_float_0, 0)) self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_float_to_short_0, 0)) self.connect((self, 0), (self.blocks_multiply_const_vxx_0, 0)) # QT sink close method reimplementation def get_bits(self): return self.bits def set_bits(self, bits): self.bits = bits self.blocks_multiply_const_vxx_0_0.set_k((1.0/pow(2.0,self.bits-1.0), )) self.blocks_multiply_const_vxx_0.set_k((pow(2,self.bits-1.0), )) gnuradio-3.7.2.1/gr-channels/python/channels/phase_bal.py0000664000175000017500000000710412207702530023131 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: IQ Phase Balancer # Author: matt@ettus.com # Generated: Thu Aug 1 11:49:41 2013 ################################################## from gnuradio import blocks from gnuradio import filter from gnuradio import gr from gnuradio.filter import firdes class phase_bal(gr.hier_block2): def __init__(self, alpha=0): gr.hier_block2.__init__( self, "IQ Phase Balancer", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.alpha = alpha ################################################## # Blocks ################################################## self.filter_single_pole_iir_filter_xx_0 = filter.single_pole_iir_filter_ff(alpha, 1) self.blocks_sub_xx_1 = blocks.sub_ff(1) self.blocks_sub_xx_0 = blocks.sub_ff(1) self.blocks_multiply_xx_2 = blocks.multiply_vff(1) self.blocks_multiply_xx_1 = blocks.multiply_vff(1) self.blocks_multiply_xx_0 = blocks.multiply_vff(1) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((2, )) self.blocks_float_to_complex_0 = blocks.float_to_complex(1) self.blocks_divide_xx_0 = blocks.divide_ff(1) self.blocks_complex_to_mag_squared_0 = blocks.complex_to_mag_squared(1) self.blocks_complex_to_float_0 = blocks.complex_to_float(1) ################################################## # Connections ################################################## self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_multiply_xx_0, 1)) self.connect((self.blocks_multiply_xx_0, 0), (self.blocks_divide_xx_0, 0)) self.connect((self.blocks_sub_xx_0, 0), (self.blocks_float_to_complex_0, 1)) self.connect((self.blocks_multiply_xx_1, 0), (self.blocks_sub_xx_0, 1)) self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_multiply_xx_1, 1)) self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_multiply_xx_1, 0)) self.connect((self.blocks_multiply_xx_2, 0), (self.blocks_sub_xx_1, 1)) self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_sub_xx_0, 0)) self.connect((self.blocks_sub_xx_1, 0), (self.blocks_float_to_complex_0, 0)) self.connect((self.blocks_complex_to_mag_squared_0, 0), (self.blocks_divide_xx_0, 1)) self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_sub_xx_1, 0)) self.connect((self.blocks_divide_xx_0, 0), (self.blocks_multiply_const_vxx_0, 0)) self.connect((self.blocks_multiply_const_vxx_0, 0), (self.filter_single_pole_iir_filter_xx_0, 0)) self.connect((self, 0), (self.blocks_complex_to_float_0, 0)) self.connect((self, 0), (self.blocks_complex_to_mag_squared_0, 0)) self.connect((self.blocks_float_to_complex_0, 0), (self, 0)) self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_multiply_xx_2, 0)) self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_multiply_xx_2, 1)) # QT sink close method reimplementation def get_alpha(self): return self.alpha def set_alpha(self, alpha): self.alpha = alpha self.filter_single_pole_iir_filter_xx_0.set_taps(self.alpha) gnuradio-3.7.2.1/gr-channels/python/channels/amp_bal.py0000664000175000017500000000464712207702530022617 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Amplitude Balance # Author: mettus # Description: Restores IQ amplitude balance # Generated: Thu Aug 1 11:47:46 2013 ################################################## from gnuradio import blocks from gnuradio import gr from gnuradio.filter import firdes class amp_bal(gr.hier_block2): def __init__(self, alpha=0): gr.hier_block2.__init__( self, "Amplitude Balance", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.alpha = alpha ################################################## # Blocks ################################################## self.blocks_rms_xx0 = blocks.rms_ff(alpha) self.blocks_rms_xx = blocks.rms_ff(alpha) self.blocks_multiply_vxx1 = blocks.multiply_vff(1) self.blocks_float_to_complex = blocks.float_to_complex(1) self.blocks_divide_xx = blocks.divide_ff(1) self.blocks_complex_to_float = blocks.complex_to_float(1) ################################################## # Connections ################################################## self.connect((self.blocks_float_to_complex, 0), (self, 0)) self.connect((self, 0), (self.blocks_complex_to_float, 0)) self.connect((self.blocks_complex_to_float, 0), (self.blocks_rms_xx, 0)) self.connect((self.blocks_complex_to_float, 1), (self.blocks_rms_xx0, 0)) self.connect((self.blocks_rms_xx, 0), (self.blocks_divide_xx, 0)) self.connect((self.blocks_rms_xx0, 0), (self.blocks_divide_xx, 1)) self.connect((self.blocks_complex_to_float, 0), (self.blocks_float_to_complex, 0)) self.connect((self.blocks_complex_to_float, 1), (self.blocks_multiply_vxx1, 1)) self.connect((self.blocks_divide_xx, 0), (self.blocks_multiply_vxx1, 0)) self.connect((self.blocks_multiply_vxx1, 0), (self.blocks_float_to_complex, 1)) # QT sink close method reimplementation def get_alpha(self): return self.alpha def set_alpha(self, alpha): self.alpha = alpha self.blocks_rms_xx.set_alpha(self.alpha) self.blocks_rms_xx0.set_alpha(self.alpha) gnuradio-3.7.2.1/gr-channels/python/channels/phase_noise_gen.py0000664000175000017500000000532112207702530024340 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Phase Noise Generator # Author: mettus # Generated: Thu Aug 1 11:59:39 2013 ################################################## from gnuradio import analog from gnuradio import blocks from gnuradio import filter from gnuradio import gr from gnuradio.filter import firdes class phase_noise_gen(gr.hier_block2): def __init__(self, noise_mag=0, alpha=0.1): gr.hier_block2.__init__( self, "Phase Noise Generator", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.noise_mag = noise_mag self.alpha = alpha ################################################## # Blocks ################################################## self.filter_single_pole_iir_filter_xx_0 = filter.single_pole_iir_filter_ff(alpha, 1) self.blocks_transcendental_0_0 = blocks.transcendental("sin", "float") self.blocks_transcendental_0 = blocks.transcendental("cos", "float") self.blocks_multiply_xx_0 = blocks.multiply_vcc(1) self.blocks_float_to_complex_0 = blocks.float_to_complex(1) self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN, noise_mag, 42) ################################################## # Connections ################################################## self.connect((self.blocks_float_to_complex_0, 0), (self.blocks_multiply_xx_0, 1)) self.connect((self.analog_noise_source_x_0, 0), (self.filter_single_pole_iir_filter_xx_0, 0)) self.connect((self.blocks_multiply_xx_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_transcendental_0, 0)) self.connect((self.filter_single_pole_iir_filter_xx_0, 0), (self.blocks_transcendental_0_0, 0)) self.connect((self.blocks_transcendental_0, 0), (self.blocks_float_to_complex_0, 0)) self.connect((self.blocks_transcendental_0_0, 0), (self.blocks_float_to_complex_0, 1)) # QT sink close method reimplementation def get_noise_mag(self): return self.noise_mag def set_noise_mag(self, noise_mag): self.noise_mag = noise_mag self.analog_noise_source_x_0.set_amplitude(self.noise_mag) def get_alpha(self): return self.alpha def set_alpha(self, alpha): self.alpha = alpha self.filter_single_pole_iir_filter_xx_0.set_taps(self.alpha) gnuradio-3.7.2.1/gr-channels/python/channels/distortion_2_gen.py0000664000175000017500000000461012207702530024462 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Second Order Distortion # Author: mettus # Generated: Thu Aug 1 12:30:23 2013 ################################################## from gnuradio import blocks from gnuradio import gr from gnuradio.filter import firdes import math class distortion_2_gen(gr.hier_block2): def __init__(self, beta=0): gr.hier_block2.__init__( self, "Second Order Distortion", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.beta = beta ################################################## # Blocks ################################################## self.blocks_multiply_xx_0_0 = blocks.multiply_vcc(1) self.blocks_multiply_xx_0 = blocks.multiply_vcc(1) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vcc((beta, )) self.blocks_conjugate_cc_0 = blocks.conjugate_cc() self.blocks_add_xx_0_0 = blocks.add_vcc(1) self.blocks_add_xx_0 = blocks.add_vcc(1) ################################################## # Connections ################################################## self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_add_xx_0, 1)) self.connect((self, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self, 0), (self.blocks_add_xx_0, 0)) self.connect((self.blocks_add_xx_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_conjugate_cc_0, 0)) self.connect((self.blocks_conjugate_cc_0, 0), (self.blocks_multiply_xx_0_0, 1)) self.connect((self, 0), (self.blocks_multiply_xx_0, 1)) self.connect((self, 0), (self.blocks_multiply_xx_0_0, 0)) self.connect((self.blocks_multiply_xx_0_0, 0), (self.blocks_add_xx_0_0, 1)) self.connect((self.blocks_multiply_xx_0, 0), (self.blocks_add_xx_0_0, 0)) self.connect((self.blocks_add_xx_0_0, 0), (self.blocks_multiply_const_vxx_0, 0)) # QT sink close method reimplementation def get_beta(self): return self.beta def set_beta(self, beta): self.beta = beta self.blocks_multiply_const_vxx_0.set_k((self.beta, )) gnuradio-3.7.2.1/gr-channels/python/channels/conj_fs_iqcorr.py0000664000175000017500000000422612207702530024215 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Conj FS IQBal # Author: matt@ettus.com # Description: Frequency Selective Conjugate Method IQ Balance Corrector # Generated: Thu Aug 1 13:00:27 2013 ################################################## from gnuradio import blocks from gnuradio import filter from gnuradio import gr from gnuradio.filter import firdes class conj_fs_iqcorr(gr.hier_block2): def __init__(self, delay=0, taps=[]): gr.hier_block2.__init__( self, "Conj FS IQBal", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.delay = delay self.taps = taps ################################################## # Blocks ################################################## self.filter_fir_filter_xxx_0 = filter.fir_filter_ccc(1, (taps)) self.delay_0 = blocks.delay(gr.sizeof_gr_complex*1, delay) self.blocks_conjugate_cc_0 = blocks.conjugate_cc() self.blocks_add_xx_0 = blocks.add_vcc(1) ################################################## # Connections ################################################## self.connect((self.blocks_add_xx_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_conjugate_cc_0, 0)) self.connect((self.filter_fir_filter_xxx_0, 0), (self.blocks_add_xx_0, 1)) self.connect((self.blocks_conjugate_cc_0, 0), (self.filter_fir_filter_xxx_0, 0)) self.connect((self, 0), (self.delay_0, 0)) self.connect((self.delay_0, 0), (self.blocks_add_xx_0, 0)) # QT sink close method reimplementation def get_delay(self): return self.delay def set_delay(self, delay): self.delay = delay self.delay_0.set_dly(self.delay) def get_taps(self): return self.taps def set_taps(self, taps): self.taps = taps self.filter_fir_filter_xxx_0.set_taps((self.taps)) gnuradio-3.7.2.1/gr-channels/python/channels/distortion_3_gen.py0000664000175000017500000000453712207702530024473 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Third Order Distortion # Author: mettus # Generated: Thu Aug 1 12:37:59 2013 ################################################## from gnuradio import blocks from gnuradio import gr from gnuradio.filter import firdes import math class distortion_3_gen(gr.hier_block2): def __init__(self, beta=0): gr.hier_block2.__init__( self, "Third Order Distortion", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.beta = beta ################################################## # Blocks ################################################## self.blocks_null_source_0 = blocks.null_source(gr.sizeof_float*1) self.blocks_multiply_xx_0 = blocks.multiply_vcc(1) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vcc((beta, )) self.blocks_float_to_complex_0 = blocks.float_to_complex(1) self.blocks_complex_to_mag_squared_0 = blocks.complex_to_mag_squared(1) self.blocks_add_xx_0 = blocks.add_vcc(1) ################################################## # Connections ################################################## self.connect((self.blocks_float_to_complex_0, 0), (self.blocks_multiply_xx_0, 1)) self.connect((self.blocks_null_source_0, 0), (self.blocks_float_to_complex_0, 1)) self.connect((self.blocks_complex_to_mag_squared_0, 0), (self.blocks_float_to_complex_0, 0)) self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_add_xx_0, 1)) self.connect((self.blocks_multiply_xx_0, 0), (self.blocks_multiply_const_vxx_0, 0)) self.connect((self, 0), (self.blocks_complex_to_mag_squared_0, 0)) self.connect((self, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self, 0), (self.blocks_add_xx_0, 0)) self.connect((self.blocks_add_xx_0, 0), (self, 0)) # QT sink close method reimplementation def get_beta(self): return self.beta def set_beta(self, beta): self.beta = beta self.blocks_multiply_const_vxx_0.set_k((self.beta, )) gnuradio-3.7.2.1/gr-channels/python/channels/iqbal_gen.py0000664000175000017500000000476612207702530023147 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: IQ Imbalance Generator # Author: mettus # Generated: Thu Aug 1 12:08:07 2013 ################################################## from gnuradio import blocks from gnuradio import gr from gnuradio.filter import firdes import math class iqbal_gen(gr.hier_block2): def __init__(self, magnitude=0, phase=0): gr.hier_block2.__init__( self, "IQ Imbalance Generator", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.magnitude = magnitude self.phase = phase ################################################## # Blocks ################################################## self.mag = blocks.multiply_const_vff((math.pow(10,magnitude/20.0), )) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((math.sin(phase*math.pi/180.0), )) self.blocks_float_to_complex_0 = blocks.float_to_complex(1) self.blocks_complex_to_float_0 = blocks.complex_to_float(1) self.blocks_add_xx_0 = blocks.add_vff(1) ################################################## # Connections ################################################## self.connect((self.blocks_float_to_complex_0, 0), (self, 0)) self.connect((self, 0), (self.blocks_complex_to_float_0, 0)) self.connect((self.blocks_complex_to_float_0, 0), (self.mag, 0)) self.connect((self.mag, 0), (self.blocks_float_to_complex_0, 0)) self.connect((self.blocks_add_xx_0, 0), (self.blocks_float_to_complex_0, 1)) self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_add_xx_0, 0)) self.connect((self.blocks_complex_to_float_0, 1), (self.blocks_add_xx_0, 1)) self.connect((self.blocks_complex_to_float_0, 0), (self.blocks_multiply_const_vxx_0, 0)) # QT sink close method reimplementation def get_magnitude(self): return self.magnitude def set_magnitude(self, magnitude): self.magnitude = magnitude self.mag.set_k((math.pow(10,self.magnitude/20.0), )) def get_phase(self): return self.phase def set_phase(self, phase): self.phase = phase self.blocks_multiply_const_vxx_0.set_k((math.sin(self.phase*math.pi/180.0), )) gnuradio-3.7.2.1/gr-channels/python/channels/__init__.py0000664000175000017500000000250612207702530022753 0ustar jcorganjcorgan# # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks for channel models and related functions. ''' import os try: from channels_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from channels_swig import * # Blocks for Hardware Impairments from amp_bal import * from conj_fs_iqcorr import * from distortion_2_gen import * from distortion_3_gen import * from iqbal_gen import * from impairments import * from phase_bal import * from phase_noise_gen import * from quantizer import * gnuradio-3.7.2.1/gr-channels/python/channels/impairments.py0000664000175000017500000001122312207702530023540 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Radio Impairments Model # Author: mettus # Generated: Thu Aug 1 12:46:10 2013 ################################################## from gnuradio import analog from gnuradio import blocks from gnuradio import gr from gnuradio.filter import firdes import math #Import locally from phase_noise_gen import * from iqbal_gen import * from distortion_2_gen import * from distortion_3_gen import * class impairments(gr.hier_block2): def __init__(self, phase_noise_mag=0, magbal=0, phasebal=0, q_ofs=0, i_ofs=0, freq_offset=0, gamma=0, beta=0): gr.hier_block2.__init__( self, "Radio Impairments Model", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.phase_noise_mag = phase_noise_mag self.magbal = magbal self.phasebal = phasebal self.q_ofs = q_ofs self.i_ofs = i_ofs self.freq_offset = freq_offset self.gamma = gamma self.beta = beta ################################################## # Blocks ################################################## self.channels_phase_noise_gen_0_0 = phase_noise_gen(math.pow(10.0,phase_noise_mag/20.0), .01) self.channels_iqbal_gen_0 = iqbal_gen(magbal, phasebal) self.channels_distortion_3_gen_0 = distortion_3_gen(beta) self.channels_distortion_2_gen_0 = distortion_2_gen(gamma) self.blocks_multiply_xx_0_0 = blocks.multiply_vcc(1) self.blocks_multiply_xx_0 = blocks.multiply_vcc(1) self.blocks_conjugate_cc_0 = blocks.conjugate_cc() self.blocks_add_const_vxx_0 = blocks.add_const_vcc((i_ofs + q_ofs* 1j, )) self.analog_sig_source_x_0 = analog.sig_source_c(1.0, analog.GR_COS_WAVE, freq_offset, 1, 0) ################################################## # Connections ################################################## self.connect((self.channels_phase_noise_gen_0_0, 0), (self.channels_distortion_3_gen_0, 0)) self.connect((self.blocks_multiply_xx_0, 0), (self, 0)) self.connect((self.blocks_add_const_vxx_0, 0), (self.blocks_multiply_xx_0, 1)) self.connect((self.analog_sig_source_x_0, 0), (self.blocks_multiply_xx_0, 0)) self.connect((self.blocks_multiply_xx_0_0, 0), (self.channels_phase_noise_gen_0_0, 0)) self.connect((self.analog_sig_source_x_0, 0), (self.blocks_conjugate_cc_0, 0)) self.connect((self, 0), (self.blocks_multiply_xx_0_0, 1)) self.connect((self.blocks_conjugate_cc_0, 0), (self.blocks_multiply_xx_0_0, 0)) self.connect((self.channels_iqbal_gen_0, 0), (self.blocks_add_const_vxx_0, 0)) self.connect((self.channels_distortion_3_gen_0, 0), (self.channels_distortion_2_gen_0, 0)) self.connect((self.channels_distortion_2_gen_0, 0), (self.channels_iqbal_gen_0, 0)) # QT sink close method reimplementation def get_phase_noise_mag(self): return self.phase_noise_mag def set_phase_noise_mag(self, phase_noise_mag): self.phase_noise_mag = phase_noise_mag self.channels_phase_noise_gen_0_0.set_noise_mag(math.pow(10.0,self.phase_noise_mag/20.0)) def get_magbal(self): return self.magbal def set_magbal(self, magbal): self.magbal = magbal self.channels_iqbal_gen_0.set_magnitude(self.magbal) def get_phasebal(self): return self.phasebal def set_phasebal(self, phasebal): self.phasebal = phasebal self.channels_iqbal_gen_0.set_phase(self.phasebal) def get_q_ofs(self): return self.q_ofs def set_q_ofs(self, q_ofs): self.q_ofs = q_ofs self.blocks_add_const_vxx_0.set_k((self.i_ofs + self.q_ofs* 1j, )) def get_i_ofs(self): return self.i_ofs def set_i_ofs(self, i_ofs): self.i_ofs = i_ofs self.blocks_add_const_vxx_0.set_k((self.i_ofs + self.q_ofs* 1j, )) def get_freq_offset(self): return self.freq_offset def set_freq_offset(self, freq_offset): self.freq_offset = freq_offset self.analog_sig_source_x_0.set_frequency(self.freq_offset) def get_gamma(self): return self.gamma def set_gamma(self, gamma): self.gamma = gamma self.channels_distortion_2_gen_0.set_beta(self.gamma) def get_beta(self): return self.beta def set_beta(self, beta): self.beta = beta self.channels_distortion_3_gen_0.set_beta(self.beta) gnuradio-3.7.2.1/gr-channels/python/channels/qa_channel_model.py0000775000175000017500000000357512207440367024506 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks, channels import math class test_channel_model(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): N = 1000 # number of samples to use fs = 1000 # baseband sampling rate freq = 100 signal = analog.sig_source_c(fs, analog.GR_SIN_WAVE, freq, 1) head = blocks.head(gr.sizeof_gr_complex, N) op = channels.channel_model(0.0, 0.0, 1.0, [1,], 0) snk = blocks.vector_sink_c() snk1 = blocks.vector_sink_c() op.set_noise_voltage(0.0) op.set_frequency_offset(0.0) op.set_taps([1,]) op.set_timing_offset(1.0) self.tb.connect(signal, head, op, snk) self.tb.connect(op, snk1) self.tb.run() dst_data = snk.data() exp_data = snk1.data() self.assertComplexTuplesAlmostEqual(exp_data, dst_data, 5) if __name__ == '__main__': gr_unittest.run(test_channel_model, "test_channel_model.xml") gnuradio-3.7.2.1/gr-channels/python/channels/qa_fading_model.py0000664000175000017500000000365612207440367024323 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, analog, blocks, channels import math class test_fading_model(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): N = 1000 # number of samples to use fs = 1000 # baseband sampling rate freq = 100 fDTs = 0.01 K = 4 signal = analog.sig_source_c(fs, analog.GR_SIN_WAVE, freq, 1) head = blocks.head(gr.sizeof_gr_complex, N) op = channels.fading_model(8, fDTs=fDTs, LOS=True, K=K, seed=0) snk = blocks.vector_sink_c() snk1 = blocks.vector_sink_c() self.assertAlmostEqual(K, op.K(), 4) self.assertAlmostEqual(fDTs, op.fDTs(), 4) #self.tb.connect(signal, head, op, snk) #self.tb.connect(op, snk1) #self.tb.run() #dst_data = snk.data() #exp_data = snk1.data() #self.assertComplexTuplesAlmostEqual(exp_data, dst_data, 5) if __name__ == '__main__': gr_unittest.run(test_fading_model, "test_fading_model.xml") gnuradio-3.7.2.1/gr-channels/lib/0000775000175000017500000000000012237515112016272 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/lib/CMakeLists.txt0000664000175000017500000000520612237515112021035 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${GR_CHANNELS_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GR_ANALOG_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND channels_sources channel_model_impl.cc channel_model2_impl.cc dynamic_channel_model_impl.cc fading_model_impl.cc selective_fading_model_impl.cc flat_fader_impl.cc cfo_model_impl.cc sro_model_impl.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-channels.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-channels.rc @ONLY) list(APPEND channels_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-channels.rc ) endif(MSVC) list(APPEND channels_libs volk gnuradio-runtime gnuradio-filter gnuradio-analog gnuradio-blocks ${Boost_LIBRARIES} ) add_library(gnuradio-channels SHARED ${channels_sources}) target_link_libraries(gnuradio-channels ${channels_libs}) GR_LIBRARY_FOO(gnuradio-channels RUNTIME_COMPONENT "channels_runtime" DEVEL_COMPONENT "channels_devel") add_dependencies(gnuradio-channels channels_generated_includes channels_generated_swigs gnuradio-runtime gnuradio-filter gnuradio-analog gnuradio-blocks) gnuradio-3.7.2.1/gr-channels/lib/dynamic_channel_model_impl.cc0000664000175000017500000001032412237515112024116 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "dynamic_channel_model_impl.h" #include #include namespace gr { namespace channels { dynamic_channel_model::sptr dynamic_channel_model::make( double samp_rate, double sro_std_dev, double sro_max_dev, double cfo_std_dev, double cfo_max_dev, unsigned int N, double doppler_freq, bool LOS_model, float K, std::vector delays, std::vector mags, int ntaps_mpath, double noise_amp, double noise_seed ) { return gnuradio::get_initial_sptr (new dynamic_channel_model_impl( samp_rate, sro_std_dev, sro_max_dev, cfo_std_dev, cfo_max_dev, N, doppler_freq, LOS_model, K, delays, mags, ntaps_mpath, noise_amp, noise_seed)); } // Hierarchical block constructor dynamic_channel_model_impl::dynamic_channel_model_impl( double samp_rate, double sro_std_dev, double sro_max_dev, double cfo_std_dev, double cfo_max_dev, unsigned int N, double doppler_freq, bool LOS_model, float K, std::vector delays, std::vector mags, int ntaps_mpath, double noise_amp, double noise_seed) : hier_block2("dynamic_channel_model", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))) { d_noise_adder = blocks::add_cc::make(); d_noise = analog::fastnoise_source_c::make(analog::GR_GAUSSIAN, noise_amp, noise_seed, 1024*8); d_sro_model = channels::sro_model::make(samp_rate, sro_std_dev, sro_max_dev, noise_seed); d_cfo_model = channels::cfo_model::make(samp_rate, cfo_std_dev, cfo_max_dev, noise_seed); d_fader = channels::selective_fading_model::make(N, doppler_freq / samp_rate, LOS_model, K, noise_seed, delays, mags, ntaps_mpath); connect(self(), 0, d_sro_model, 0); connect(d_sro_model, 0, d_cfo_model, 0); connect(d_cfo_model, 0, d_fader, 0); connect(d_fader, 0, d_noise_adder, 1); connect(d_noise, 0, d_noise_adder, 0); connect(d_noise_adder, 0, self(), 0); } dynamic_channel_model_impl::~dynamic_channel_model_impl() { } void dynamic_channel_model_impl::setup_rpc() { #ifdef GR_CTRLPORT #endif /* GR_CTRLPORT */ } } /* namespace channels */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/cfo_model_impl.cc0000664000175000017500000000703312237515112021554 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "cfo_model_impl.h" #include #include namespace gr { namespace channels { cfo_model::sptr cfo_model::make( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed ) { return gnuradio::get_initial_sptr (new cfo_model_impl(sample_rate_hz, std_dev_hz, max_dev_hz, noise_seed)); } cfo_model_impl::cfo_model_impl( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed) : sync_block("cfo_model", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_samp_rate(sample_rate_hz), d_max_dev_hz(max_dev_hz), d_table(8*1024), d_noise(gr::analog::fastnoise_source_f::make(analog::GR_GAUSSIAN, std_dev_hz, noise_seed)), d_cfo(0), d_angle(0), d_noise_seed(noise_seed) { } cfo_model_impl::~cfo_model_impl() { } int cfo_model_impl::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items){ const gr_complex* in = (const gr_complex*) input_items[0]; gr_complex* out = (gr_complex*) output_items[0]; for(int i=0; isample_unbiased(); d_cfo = std::min( d_cfo, d_max_dev_hz ); d_cfo = std::max( d_cfo, -d_max_dev_hz ); // update and wrap angle d_angle += 2*M_PI*d_cfo/d_samp_rate; d_angle = d_angle > 2*M_PI ? d_angle - 2*M_PI : d_angle; d_angle = d_angle < -2*M_PI ? d_angle + 2*M_PI : d_angle; out[i] = in[i] * gr_complex(d_table.cos(d_angle), d_table.sin(d_angle)); } return noutput_items; } void cfo_model_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_variable( alias(), "cfo", &d_cfo, pmt::mp(-10.0f), pmt::mp(10.0f), pmt::mp(0.0f), "", "Current CFO in Hz", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_variable( alias(), "cfo_max", &d_max_dev_hz, pmt::mp(-10.0f), pmt::mp(10.0f), pmt::mp(0.0f), "", "Max CFO in Hz", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } } /* namespace channels */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/channel_model2_impl.h0000664000175000017500000000461112237515112022340 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CHANNEL_MODEL2_IMPL_H #define INCLUDED_CHANNELS_CHANNEL_MODEL2_IMPL_H #include #include #include #include #include #include #include #include #include namespace gr { namespace channels { class CHANNELS_API channel_model2_impl : public channel_model2 { private: blocks::add_cc::sptr d_noise_adder; blocks::multiply_cc::sptr d_mixer_offset; blocks::vco_c::sptr d_freq_gen; analog::fastnoise_source_c::sptr d_noise; filter::fractional_resampler_cc::sptr d_timing_offset; filter::fir_filter_ccc::sptr d_multipath; std::vector d_taps; public: channel_model2_impl(double noise_voltage, double epsilon, const std::vector &taps, double noise_seed, bool block_tags); ~channel_model2_impl(); void setup_rpc(); void set_noise_voltage(double noise_voltage); void set_taps(const std::vector &taps); void set_timing_offset(double epsilon); double noise_voltage() const; std::vector taps() const; double timing_offset() const; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL2_IMPL_H */ gnuradio-3.7.2.1/gr-channels/lib/flat_fader_impl.cc0000664000175000017500000000757212207440367021732 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include namespace gr { namespace channels { flat_fader_impl::flat_fader_impl(unsigned int N, float fDTs, bool LOS, float K, int seed ) : seed_1((int)seed), dist_1(-M_PI, M_PI), rv_1( seed_1, dist_1 ), // U(-pi,pi) seed_2((int)seed+1), dist_2(0, 1), rv_2( seed_2, dist_2 ), // U(0,1) d_N(N), d_fDTs(fDTs), d_theta(rv_1()), d_theta_los(rv_1()), d_step( powf(0.00125*fDTs, 1.1) ), // max step size approximated from Table 2 d_m(0), d_K(K), d_LOS(LOS), d_psi(d_N+1, 0), d_phi(d_N+1, 0), d_table(8*1024), scale_sin(sqrtf(2.0/d_N)), scale_los(sqrtf(d_K)/sqrtf(d_K+1)), scale_nlos(1/sqrtf(d_K+1)) { // generate initial phase values for(int i=0; i M_PI){ d_theta = M_PI; d_step = -d_step; } else if(d_theta < -M_PI){ d_theta = -M_PI; d_step = -d_step; } } } /* namespace channels */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/fading_model_impl.h0000664000175000017500000000424012207440367022102 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H #define INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H #include #include #include "flat_fader_impl.h" //#include #include #include #include #include namespace gr { namespace channels { class CHANNELS_API fading_model_impl : public fading_model { private: gr::channels::flat_fader_impl d_fader; public: fading_model_impl(unsigned int N, float fDTs, bool LOS, float K, int seed); ~fading_model_impl(); void setup_rpc(); int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); virtual float fDTs(){ return d_fader.d_fDTs; } virtual float K(){ return d_fader.d_K; } virtual float step(){ return d_fader.d_step; } virtual void set_fDTs(float fDTs){ d_fader.d_fDTs = fDTs; d_fader.d_step = powf(0.00125*fDTs, 1.1); } virtual void set_K(float K){ d_fader.d_K = K; d_fader.scale_los = sqrtf(d_fader.d_K)/sqrtf(d_fader.d_K+1); d_fader.scale_nlos = (1/sqrtf(d_fader.d_K+1)); } virtual void set_step(float step){ d_fader.d_step = step; } }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H */ gnuradio-3.7.2.1/gr-channels/lib/channel_model2_impl.cc0000664000175000017500000001255212237515112022501 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define _USE_MATH_DEFINES #include "channel_model2_impl.h" #include #include namespace gr { namespace channels { channel_model2::sptr channel_model2::make(double noise_voltage, double epsilon, const std::vector &taps, double noise_seed, bool block_tags) { return gnuradio::get_initial_sptr (new channel_model2_impl(noise_voltage, epsilon, taps, noise_seed, block_tags)); } // Hierarchical block constructor channel_model2_impl::channel_model2_impl(double noise_voltage, double epsilon, const std::vector &taps, double noise_seed, bool block_tags) : hier_block2("channel_model2", io_signature::make2(3, 3, sizeof(gr_complex), sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))) { d_taps = taps; while(d_taps.size() < 2) { d_taps.push_back(0); } d_timing_offset = filter::fractional_resampler_cc::make(0, epsilon); d_multipath = filter::fir_filter_ccc::make(1, d_taps); d_noise_adder = blocks::add_cc::make(); d_noise = analog::fastnoise_source_c::make(analog::GR_GAUSSIAN, noise_voltage, noise_seed); d_freq_gen = blocks::vco_c::make(1.0, 2*M_PI, 1.0); d_mixer_offset = blocks::multiply_cc::make(); connect(self(), 0, d_timing_offset, 0); connect(self(), 2, d_timing_offset, 1); connect(d_timing_offset, 0, d_multipath, 0); connect(d_multipath, 0, d_mixer_offset, 0); connect(self(), 1, d_freq_gen, 0); connect(d_freq_gen, 0, d_mixer_offset, 1); connect(d_mixer_offset, 0, d_noise_adder, 1); connect(d_noise, 0, d_noise_adder, 0); connect(d_noise_adder, 0, self(), 0); if (block_tags) { d_timing_offset->set_tag_propagation_policy(gr::block::TPP_DONT); } } channel_model2_impl::~channel_model2_impl() { } void channel_model2_impl::set_noise_voltage(double noise_voltage) { d_noise->set_amplitude(noise_voltage); } void channel_model2_impl::set_taps(const std::vector &taps) { d_taps = taps; while(d_taps.size() < 2) { d_taps.push_back(0); } d_multipath->set_taps(d_taps); } void channel_model2_impl::set_timing_offset(double epsilon) { d_timing_offset->set_resamp_ratio(epsilon); } double channel_model2_impl::noise_voltage() const { return d_noise->amplitude(); } std::vector channel_model2_impl::taps() const { return d_multipath->taps(); } double channel_model2_impl::timing_offset() const { return d_timing_offset->resamp_ratio(); } void channel_model2_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "noise", &channel_model2::noise_voltage, pmt::mp(-10.0f), pmt::mp(10.0f), pmt::mp(0.0f), "", "Noise Voltage", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "timing", &channel_model2::timing_offset, pmt::mp(0.0), pmt::mp(2.0), pmt::mp(0.0), "", "Timing Offset", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "taps", &channel_model2::taps, pmt::make_c32vector(0,-10), pmt::make_c32vector(0,10), pmt::make_c32vector(0,0), "", "Multipath taps", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTCPLX | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "noise", &channel_model2::set_noise_voltage, pmt::mp(-10.0), pmt::mp(10.0), pmt::mp(0.0), "V", "Noise Voltage", RPC_PRIVLVL_MIN, DISPNULL))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "timing", &channel_model2::set_timing_offset, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Timing Offset", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace channels */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/dynamic_channel_model_impl.h0000664000175000017500000000774112237515112023771 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H #define INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H #include #include #include #include #include #include #include #include #include #include #include namespace gr { namespace channels { class CHANNELS_API dynamic_channel_model_impl : public dynamic_channel_model { private: channels::sro_model::sptr d_sro_model; channels::cfo_model::sptr d_cfo_model; channels::selective_fading_model::sptr d_fader; blocks::add_cc::sptr d_noise_adder; analog::fastnoise_source_c::sptr d_noise; public: dynamic_channel_model_impl( double samp_rate, double sro_std_dev, double sro_max_dev, double cfo_std_dev, double cfo_max_dev, unsigned int N, double doppler_freq, bool LOS_model, float K, std::vector delays, std::vector mags, int ntaps_mpath, double noise_amp, double noise_seed); ~dynamic_channel_model_impl(); void setup_rpc(); double samp_rate() const { return d_sro_model->samp_rate(); } double sro_dev_std() const { return d_sro_model->std_dev(); } double sro_dev_max() const { return d_sro_model->max_dev(); } double cfo_dev_std() const { return d_cfo_model->std_dev(); } double cfo_dev_max() const { return d_cfo_model->max_dev(); } double noise_amp() const { return d_noise->amplitude(); } double doppler_freq() const { return d_fader->fDTs()*samp_rate(); } double K() const { return d_fader->K(); } void set_samp_rate(double sr) { d_fader->set_fDTs( doppler_freq()/samp_rate() ); d_sro_model->set_samp_rate(sr); d_cfo_model->set_samp_rate(sr); } void set_sro_dev_std(double dev) { d_sro_model->set_max_dev(dev); } void set_sro_dev_max(double dev) { d_sro_model->set_max_dev(dev); } void set_cfo_dev_std(double dev) { d_cfo_model->set_std_dev(dev); } void set_cfo_dev_max(double dev) { d_cfo_model->set_max_dev(dev); } void set_noise_amp(double amp) { d_noise->set_amplitude(amp); } void set_doppler_freq(double f){ d_fader->set_fDTs(f/samp_rate()); } void set_K(double K){ d_fader->set_K(K); } }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H */ gnuradio-3.7.2.1/gr-channels/lib/channel_model_impl.h0000664000175000017500000000463512237515112022264 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H #define INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H #include #include #include #include #include #include #include #include namespace gr { namespace channels { class CHANNELS_API channel_model_impl : public channel_model { private: blocks::add_cc::sptr d_noise_adder; blocks::multiply_cc::sptr d_mixer_offset; analog::sig_source_c::sptr d_freq_offset; analog::fastnoise_source_c::sptr d_noise; filter::fractional_resampler_cc::sptr d_timing_offset; filter::fir_filter_ccc::sptr d_multipath; std::vector d_taps; public: channel_model_impl(double noise_voltage, double frequency_offset, double epsilon, const std::vector &taps, double noise_seed, bool block_tags); ~channel_model_impl(); void setup_rpc(); void set_noise_voltage(double noise_voltage); void set_frequency_offset(double frequency_offset); void set_taps(const std::vector &taps); void set_timing_offset(double epsilon); double noise_voltage() const; double frequency_offset() const; std::vector taps() const; double timing_offset() const; }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CHANNEL_MODEL_IMPL_H */ gnuradio-3.7.2.1/gr-channels/lib/fading_model_impl.cc0000664000175000017500000001042112207440367022236 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "fading_model_impl.h" #include #include #include #include #include #include // FASTSINCOS: 0 = slow native, 1 = gr::fxpt impl, 2 = sincostable.h #define FASTSINCOS 2 namespace gr { namespace channels { fading_model::sptr fading_model::make( unsigned int N, float fDTs, bool LOS, float K, int seed ) { return gnuradio::get_initial_sptr (new fading_model_impl( N, fDTs, LOS, K, seed)); } // Block constructor fading_model_impl::fading_model_impl( unsigned int N, float fDTs, bool LOS, float K, int seed ) : sync_block("fading_model", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_fader(N,fDTs, LOS, K, seed) { } fading_model_impl::~fading_model_impl() { } void fading_model_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "fDTs", &fading_model::fDTs, pmt::mp(0), pmt::mp(1), pmt::mp(0.01), "Hz*Sec", "normalized maximum doppler frequency (fD*Ts)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "fDTs", &fading_model::set_fDTs, pmt::mp(0), pmt::mp(1), pmt::mp(0.01), "Hz*Sec", "normalized maximum doppler frequency (fD*Ts)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "K", &fading_model::K, pmt::mp(0), pmt::mp(8), pmt::mp(4), "Ratio", "Rician factor (ratio of the specular power to the scattered power)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "K", &fading_model::set_K, pmt::mp(0), pmt::mp(8), pmt::mp(4), "Ratio", "Rician factor (ratio of the specular power to the scattered power)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "step", &fading_model::step, pmt::mp(0), pmt::mp(8), pmt::mp(4), "radians", "Maximum step size for random walk angle per sample", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "step", &fading_model::set_step, pmt::mp(0), pmt::mp(1), pmt::mp(0.00001), "radians", "Maximum step size for random walk angle per sample", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } int fading_model_impl::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex* in = (const gr_complex*) input_items[0]; gr_complex* out = (gr_complex*) output_items[0]; for(int i=0; i #include #include #include #include #include #include // FASTSINCOS: 0 = slow native, 1 = gr::fxpt impl, 2 = sincostable.h #define FASTSINCOS 2 namespace gr { namespace channels { class flat_fader_impl { private: // initial theta variate generator boost::mt19937 seed_1; boost::uniform_real<> dist_1; // U(-pi,pi) boost::variate_generator > rv_1; // random walk variate boost::mt19937 seed_2; boost::uniform_real<> dist_2; // U(-pi,pi) boost::variate_generator > rv_2; public: int d_N; // number of sinusoids float d_fDTs; // normalized maximum doppler frequency double d_theta; // random walk variable (RWP) float d_theta_los; float d_step; // maximum random walk step size uint64_t d_m; // sample counter float d_K; // Rician factor (ratio of the specular power to the scattered power) bool d_LOS; // LOS path exists? chooses Rician (LOS) vs Rayleigh (NLOS) model. std::vector d_psi; // in-phase initial phase std::vector d_phi; // quadrature initial phase std::vector d_costable; sincostable d_table; float scale_sin, scale_los, scale_nlos; void update_theta(); flat_fader_impl(unsigned int N, float fDTs, bool LOS, float K, int seed); gr_complex next_sample(); }; /* class flat_fader_impl */ } /* namespace channels */ } /* namespace gr */ #endif // FLAT_FADER_IMPL_H gnuradio-3.7.2.1/gr-channels/lib/sro_model_impl.h0000664000175000017500000000513012237515112021446 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_SRO_MODEL_CC_IMPL_H #define INCLUDED_CHANNELS_SRO_MODEL_CC_IMPL_H #include #include #include #include namespace gr { namespace channels { class CHANNELS_API sro_model_impl : public sro_model { private: float d_mu; float d_mu_inc; float d_sro; float d_samp_rate; float d_max_dev_hz; float d_std_dev_hz; gr::filter::mmse_fir_interpolator_cc *d_interp; gr::analog::fastnoise_source_f::sptr d_noise; double d_noise_seed; public: sro_model_impl( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed=0); ~sro_model_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float mu() const; float interp_ratio() const; void set_mu(float mu); void set_interp_ratio(float interp_ratio); void setup_rpc(); void set_std_dev(double _dev){ d_std_dev_hz = _dev; d_noise = gr::analog::fastnoise_source_f::make(analog::GR_GAUSSIAN, _dev, d_noise_seed); } void set_max_dev(double _dev){ d_max_dev_hz = _dev; } void set_samp_rate(double _rate){ d_samp_rate = _rate; } double std_dev() const { return d_std_dev_hz; } double max_dev() const { return d_max_dev_hz; } double samp_rate() const { return d_samp_rate; } }; } /* namespace filter */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-channels/lib/channel_model_impl.cc0000664000175000017500000001356312237515112022422 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "channel_model_impl.h" #include #include namespace gr { namespace channels { channel_model::sptr channel_model::make(double noise_voltage, double frequency_offset, double epsilon, const std::vector &taps, double noise_seed, bool block_tags) { return gnuradio::get_initial_sptr (new channel_model_impl(noise_voltage, frequency_offset, epsilon, taps, noise_seed, block_tags)); } // Hierarchical block constructor channel_model_impl::channel_model_impl(double noise_voltage, double frequency_offset, double epsilon, const std::vector &taps, double noise_seed, bool block_tags ) : hier_block2("channel_model", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))) { d_taps = taps; while(d_taps.size() < 2) { d_taps.push_back(0); } d_timing_offset = filter::fractional_resampler_cc::make(0, epsilon); d_multipath = filter::fir_filter_ccc::make(1, d_taps); d_noise_adder = blocks::add_cc::make(); d_noise = analog::fastnoise_source_c::make(analog::GR_GAUSSIAN, noise_voltage, noise_seed); d_freq_offset = analog::sig_source_c::make(1, analog::GR_SIN_WAVE, frequency_offset, 1.0, 0.0); d_mixer_offset = blocks::multiply_cc::make(); connect(self(), 0, d_timing_offset, 0); connect(d_timing_offset, 0, d_multipath, 0); connect(d_multipath, 0, d_mixer_offset, 0); connect(d_freq_offset, 0, d_mixer_offset, 1); connect(d_mixer_offset, 0, d_noise_adder, 1); connect(d_noise, 0, d_noise_adder, 0); connect(d_noise_adder, 0, self(), 0); if (block_tags) { d_timing_offset->set_tag_propagation_policy(gr::block::TPP_DONT); } } channel_model_impl::~channel_model_impl() { } void channel_model_impl::set_noise_voltage(double noise_voltage) { d_noise->set_amplitude(noise_voltage); } void channel_model_impl::set_frequency_offset(double frequency_offset) { d_freq_offset->set_frequency(frequency_offset); } void channel_model_impl::set_taps(const std::vector &taps) { d_taps = taps; while(d_taps.size() < 2) { d_taps.push_back(0); } d_multipath->set_taps(d_taps); } void channel_model_impl::set_timing_offset(double epsilon) { d_timing_offset->set_resamp_ratio(epsilon); } double channel_model_impl::noise_voltage() const { return d_noise->amplitude(); } double channel_model_impl::frequency_offset() const { return d_freq_offset->frequency(); } std::vector channel_model_impl::taps() const { return d_multipath->taps(); } double channel_model_impl::timing_offset() const { return d_timing_offset->resamp_ratio(); } void channel_model_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "noise", &channel_model::noise_voltage, pmt::mp(-10.0f), pmt::mp(10.0f), pmt::mp(0.0f), "", "Noise Voltage", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "freq", &channel_model::frequency_offset, pmt::mp(-1.0f), pmt::mp(1.0f), pmt::mp(0.0f), "Hz", "Frequency Offset", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "timing", &channel_model::timing_offset, pmt::mp(0.0), pmt::mp(2.0), pmt::mp(0.0), "", "Timing Offset", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "taps", &channel_model::taps, pmt::make_c32vector(0,-10), pmt::make_c32vector(0,10), pmt::make_c32vector(0,0), "", "Multipath taps", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTCPLX | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "noise", &channel_model::set_noise_voltage, pmt::mp(-10.0), pmt::mp(10.0), pmt::mp(0.0), "V", "Noise Voltage", RPC_PRIVLVL_MIN, DISPNULL))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "freq", &channel_model::set_frequency_offset, pmt::mp(-1.0), pmt::mp(1.0), pmt::mp(0.0), "Hz", "Frequency Offset", RPC_PRIVLVL_MIN, DISPNULL))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "timing", &channel_model::set_timing_offset, pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f), "", "Timing Offset", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace channels */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/sincostable.h0000664000175000017500000000137712207440367020767 0ustar jcorganjcorgan#ifndef SINCOSTABLE_H #define SINCOSTABLE_H #define _USE_MATH_DEFINES #include class sincostable { std::vector d_cos; size_t d_sz; float d_scale; public: sincostable(size_t tbl_size) : d_cos(tbl_size,1), d_sz(tbl_size), d_scale(tbl_size/(M_PI*2)) { for(size_t i=0; i #include #include #include #include #include // FASTSINCOS: 0 = slow native, 1 = gr::fxpt impl, 2 = sincostable.h #define FASTSINCOS 2 namespace gr { namespace channels { selective_fading_model::sptr selective_fading_model::make( unsigned int N, float fDTs, bool LOS, float K, int seed, std::vector delays, std::vector mags, int ntaps) { return gnuradio::get_initial_sptr (new selective_fading_model_impl( N, fDTs, LOS, K, seed, delays, mags, ntaps)); } // Block constructor selective_fading_model_impl::selective_fading_model_impl( unsigned int N, float fDTs, bool LOS, float K, int seed, std::vector delays, std::vector mags, int ntaps ) : sync_block("selective_fading_model", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_delays(delays), d_mags(mags), d_sintable(1024) { if(mags.size() != delays.size()) throw std::runtime_error("magnitude and delay vectors must be the same length!"); for(size_t i=0; i= 1"); } set_history(1+ntaps); d_taps.resize(ntaps, gr_complex(0,0)); } selective_fading_model_impl::~selective_fading_model_impl() { for(size_t i=0; inext_sample()); for(size_t k=0; k( alias(), "fDTs", &selective_fading_model::fDTs, pmt::mp(0), pmt::mp(1), pmt::mp(0.01), "Hz*Sec", "normalized maximum doppler frequency (fD*Ts)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "fDTs", &selective_fading_model::set_fDTs, pmt::mp(0), pmt::mp(1), pmt::mp(0.01), "Hz*Sec", "normalized maximum doppler frequency (fD*Ts)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "K", &selective_fading_model::K, pmt::mp(0), pmt::mp(8), pmt::mp(4), "Ratio", "Rician factor (ratio of the specular power to the scattered power)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "K", &selective_fading_model::set_K, pmt::mp(0), pmt::mp(8), pmt::mp(4), "Ratio", "Rician factor (ratio of the specular power to the scattered power)", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "step", &selective_fading_model::step, pmt::mp(0), pmt::mp(8), pmt::mp(4), "radians", "Maximum step size for random walk angle per sample", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "step", &selective_fading_model::set_step, pmt::mp(0), pmt::mp(1), pmt::mp(0.00001), "radians", "Maximum step size for random walk angle per sample", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } } /* namespace channels */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/cfo_model_impl.h0000664000175000017500000000452012237515112021414 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_CFO_MODEL_IMPL_H #define INCLUDED_CHANNELS_CFO_MODEL_IMPL_H #include #include #include #include #include #include #include namespace gr { namespace channels { class CHANNELS_API cfo_model_impl : public cfo_model { private: double d_samp_rate; double d_std_dev_hz; double d_max_dev_hz; sincostable d_table; gr::analog::fastnoise_source_f::sptr d_noise; double d_cfo; float d_angle; double d_noise_seed; public: cfo_model_impl( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed=0 ); ~cfo_model_impl(); void setup_rpc(); int work(int, gr_vector_const_void_star&, gr_vector_void_star&); void set_std_dev(double _dev){ d_std_dev_hz = _dev; d_noise = gr::analog::fastnoise_source_f::make(analog::GR_GAUSSIAN, d_std_dev_hz, d_noise_seed); } void set_max_dev(double _dev){ d_max_dev_hz = _dev; } void set_samp_rate(double _rate){ d_samp_rate = _rate; } double std_dev() const { return d_std_dev_hz; } double max_dev() const { return d_max_dev_hz; } double samp_rate() const { return d_samp_rate; } }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_CFO_MODEL_IMPL_H */ gnuradio-3.7.2.1/gr-channels/lib/sro_model_impl.cc0000664000175000017500000001033512237515112021607 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "sro_model_impl.h" #include namespace gr { namespace channels { sro_model::sptr sro_model::make( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed) { return gnuradio::get_initial_sptr( new sro_model_impl(sample_rate_hz, std_dev_hz, max_dev_hz, noise_seed)); } sro_model_impl::sro_model_impl( double sample_rate_hz, double std_dev_hz, double max_dev_hz, double noise_seed) : block("sro_model", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(gr_complex))), d_mu (0.0), d_mu_inc (1.0), d_sro(0.0), d_samp_rate(sample_rate_hz), d_max_dev_hz(max_dev_hz), d_std_dev_hz(std_dev_hz), d_interp(new gr::filter::mmse_fir_interpolator_cc()), d_noise(gr::analog::fastnoise_source_f::make(analog::GR_GAUSSIAN, std_dev_hz, noise_seed)), d_noise_seed(noise_seed) { //set_relative_rate(1.0 / interp_ratio); set_relative_rate(1.0); } sro_model_impl::~sro_model_impl() { delete d_interp; } void sro_model_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i=0; i < ninputs; i++) { ninput_items_required[i] = (int)ceil((noutput_items * (d_mu_inc + d_max_dev_hz/d_samp_rate)) + d_interp->ntaps()); } } int sro_model_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; gr_complex *out = (gr_complex*)output_items[0]; int ii = 0; // input index int oo = 0; // output index while(oo < noutput_items) { // perform sample rate offset update d_sro += d_noise->sample_unbiased(); d_sro = std::min(d_sro, d_max_dev_hz); d_sro = std::max(d_sro, -d_max_dev_hz); d_mu_inc = 1.0 + d_sro/d_samp_rate; out[oo++] = d_interp->interpolate(&in[ii], d_mu); double s = d_mu + d_mu_inc; double f = floor(s); int incr = (int)f; d_mu = s - f; ii += incr; } consume_each(ii); return noutput_items; } float sro_model_impl::mu() const { return d_mu; } float sro_model_impl::interp_ratio() const { return d_mu_inc; } void sro_model_impl::set_mu(float mu) { d_mu = mu; } void sro_model_impl::set_interp_ratio(float interp_ratio) { d_mu_inc = interp_ratio; } void sro_model_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_variable( alias(), "sro", &d_sro, pmt::mp(-10.0f), pmt::mp(10.0f), pmt::mp(0.0f), "", "Current SRO in Hz", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_variable( alias(), "sro_max", &d_max_dev_hz, pmt::mp(-10.0f), pmt::mp(10.0f), pmt::mp(0.0f), "", "Max SRO in Hz", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } } /* namespace filter */ } /* namespace gr */ gnuradio-3.7.2.1/gr-channels/lib/gnuradio-channels.rc.in0000664000175000017500000000333612207440367022641 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-channels" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-channels.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-channels.dll" VALUE "ProductName", "gnuradio-channels" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-channels/lib/selective_fading_model_impl.h0000664000175000017500000000540412207440367024150 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHANNELS_SELECTIVE_FADING_MODEL_IMPL_H #define INCLUDED_CHANNELS_SELECTIVE_FADING_MODEL_IMPL_H #include #include #include "flat_fader_impl.h" //#include #include #include #include #include namespace gr { namespace channels { class CHANNELS_API selective_fading_model_impl : public selective_fading_model { private: std::vector d_faders; std::vector d_delays; std::vector d_mags; sincostable d_sintable; public: selective_fading_model_impl(unsigned int N, float fDTs, bool LOS, float K, int seed, std::vector delays, std::vector mags, int ntaps); ~selective_fading_model_impl(); void setup_rpc(); int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); std::vector d_taps; virtual float fDTs(){ return d_faders[0]->d_fDTs; } virtual float K(){ return d_faders[0]->d_K; } virtual float step(){ return d_faders[0]->d_step; } virtual void set_fDTs(float fDTs){ BOOST_FOREACH( gr::channels::flat_fader_impl* fader, d_faders ) { fader->d_fDTs = fDTs; fader->d_step = powf(0.00125*fDTs, 1.1); } } virtual void set_K(float K){ BOOST_FOREACH( gr::channels::flat_fader_impl* fader, d_faders ) { fader->d_K = K; fader->scale_los = sqrtf(fader->d_K)/sqrtf(fader->d_K+1); fader->scale_nlos = (1/sqrtf(fader->d_K+1)); } } virtual void set_step(float step){ BOOST_FOREACH( gr::channels::flat_fader_impl* fader, d_faders ) { fader->d_step = step; } } }; } /* namespace channels */ } /* namespace gr */ #endif /* INCLUDED_CHANNELS_SELECTIVE_FADING_MODEL_IMPL_H */ gnuradio-3.7.2.1/gr-channels/swig/0000775000175000017500000000000012237515112016475 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/swig/CMakeLists.txt0000664000175000017500000000353012207440367021244 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_CHANNELS_INCLUDE_DIRS} ${GR_FILTER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/channels_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/channels) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-channels) GR_SWIG_MAKE(channels_swig channels_swig.i) GR_SWIG_INSTALL( TARGETS channels_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/channels COMPONENT "channels_python" ) install( FILES channels_swig.i ${CMAKE_CURRENT_BINARY_DIR}/channels_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "channels_swig" ) gnuradio-3.7.2.1/gr-channels/swig/channels_swig.i0000664000175000017500000000361012237515112021473 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define CHANNELS_API %include "gnuradio.i" //load generated python docstrings %include "channels_swig_doc.i" %{ #include "gnuradio/channels/channel_model.h" #include "gnuradio/channels/channel_model2.h" #include "gnuradio/channels/cfo_model.h" #include "gnuradio/channels/dynamic_channel_model.h" #include "gnuradio/channels/fading_model.h" #include "gnuradio/channels/selective_fading_model.h" #include "gnuradio/channels/sro_model.h" %} %include "gnuradio/channels/channel_model.h" %include "gnuradio/channels/channel_model2.h" %include "gnuradio/channels/cfo_model.h" %include "gnuradio/channels/dynamic_channel_model.h" %include "gnuradio/channels/fading_model.h" %include "gnuradio/channels/selective_fading_model.h" %include "gnuradio/channels/sro_model.h" GR_SWIG_BLOCK_MAGIC2(channels, channel_model); GR_SWIG_BLOCK_MAGIC2(channels, channel_model2); GR_SWIG_BLOCK_MAGIC2(channels, cfo_model); GR_SWIG_BLOCK_MAGIC2(channels, dynamic_channel_model); GR_SWIG_BLOCK_MAGIC2(channels, fading_model); GR_SWIG_BLOCK_MAGIC2(channels, selective_fading_model); GR_SWIG_BLOCK_MAGIC2(channels, sro_model); gnuradio-3.7.2.1/gr-channels/examples/0000775000175000017500000000000012207702530017341 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-channels/examples/CMakeLists.txt0000664000175000017500000000200712207702530022100 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) install( FILES channel_tone_response.grc demo_quantization.grc demo_two_tone.grc demo_spec_an.grc demo_gmsk.grc demo_qam.grc demo_ofdm.grc DESTINATION ${GR_PKG_CHANNELS_EXAMPLES_DIR} COMPONENT "channels_python" ) gnuradio-3.7.2.1/gr-channels/examples/demo_two_tone.grc0000664000175000017500000005653612207702530022717 0ustar jcorganjcorgan Thu Aug 1 13:37:58 2013 options id demo_two_tone _enabled True title author mettus description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (11, 93) _rotation 0 variable id const_size _enabled True value 4 _coordinate (102, 93) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (397, 368) _rotation 0 channels_impairments id channels_impairments_0 _enabled True phase_noise_mag phase_noise_mag magbal magbal phasebal 0 q_ofs q_ofs i_ofs i_ofs freq_offset 0 gamma gamma beta beta affinity minoutbuf 0 _coordinate (578, 312) _rotation 0 blocks_add_xx id blocks_add_xx_0 _enabled True type complex num_inputs 3 vlen 1 affinity minoutbuf 0 _coordinate (287, 338) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq f2 amp pow(10,sig_amp/20.0)*twotones offset 0 affinity minoutbuf 0 _coordinate (24, 336) _rotation 0 analog_sig_source_x id analog_sig_source_x_1 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq f1 amp pow(10,sig_amp/20.0) offset 0 affinity minoutbuf 0 _coordinate (25, 225) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type complex noise_type analog.GR_GAUSSIAN amp .00001 seed 42 affinity minoutbuf 0 _coordinate (24, 446) _rotation 0 import id import_0 _enabled True import import math _coordinate (8, 160) _rotation 0 channels_phase_bal id channels_phase_bal_0 _enabled False alpha 0.00001 affinity minoutbuf 0 _coordinate (822, 329) _rotation 0 channels_amp_bal id channels_amp_bal_0 _enabled True alpha 0.0001 affinity minoutbuf 0 _coordinate (822, 392) _rotation 0 variable_qtgui_range id sig_amp _enabled True label Singal Power (dB) value 0 start -100 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,0,1,1 _coordinate (214, 8) _rotation 0 variable_qtgui_range id phase_noise_mag _enabled True label Phase Noise Mag (dB) value -100 start -100 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,1,1,1 _coordinate (357, 8) _rotation 0 variable_qtgui_range id f1 _enabled True label f1 value samp_rate/7.0 start -samp_rate/2 stop samp_rate/2 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,0,1,1 _coordinate (522, 8) _rotation 0 variable_qtgui_range id f2 _enabled True label f2 value samp_rate/9.0 start -samp_rate/2 stop samp_rate/2 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (670, 9) _rotation 0 variable_qtgui_range id magbal _enabled True label IQ Magnitude Imbalance value 0 start 0 stop 10 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,1 _coordinate (814, 9) _rotation 0 variable_qtgui_range id phasebal _enabled True label IQ Phase Imbalance value 0 start 0 stop 45 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,1,1,1 _coordinate (990, 9) _rotation 0 variable_qtgui_range id gamma _enabled True label k2 (IP2) value 0 start -.1 stop 0 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 4,1,1,1 _coordinate (322, 138) _rotation 0 variable_qtgui_range id beta _enabled True label k3 (IP3) value 0 start -.1 stop 0 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 4,0,1,1 _coordinate (215, 137) _rotation 0 variable_qtgui_check_box id twotones _enabled True label Two Tones? type bool value False true True false False gui_hint 0,0,1,1 _coordinate (650, 143) _rotation 0 variable_qtgui_range id q_ofs _enabled True label Q offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 5,1,1,1 _coordinate (538, 139) _rotation 0 variable_qtgui_range id i_ofs _enabled True label I offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 5,0,1,1 _coordinate (430, 138) _rotation 0 qtgui_freq_sink_x id qtgui_freq_sink_x_0 _enabled True type complex name QT GUI Plot fftsize 1024 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate ymin -140 ymax 10 nconnections 1 update_time 0.10 gui_hint 6,0,1,2 affinity _coordinate (1059, 323) _rotation 0 channels_impairments_0 channels_phase_bal_0 0 0 channels_impairments_0 channels_amp_bal_0 0 0 blocks_throttle_0 channels_impairments_0 0 0 analog_noise_source_x_0 blocks_add_xx_0 0 2 analog_sig_source_x_1 blocks_add_xx_0 0 0 analog_sig_source_x_0 blocks_add_xx_0 0 1 blocks_add_xx_0 blocks_throttle_0 0 0 channels_phase_bal_0 qtgui_freq_sink_x_0 0 0 channels_amp_bal_0 qtgui_freq_sink_x_0 0 0 gnuradio-3.7.2.1/gr-channels/examples/channel_tone_response.grc0000664000175000017500000003575412207440367024436 0ustar jcorganjcorgan Fri Feb 15 15:13:55 2013 import id import_0 _enabled True import import math _coordinate (181, 10) _rotation 0 variable id samp_rate _enabled True value 100e3 _coordinate (273, 10) _rotation 0 ctrlport_monitor id ctrlport_monitor_0 _enabled True en True _coordinate (374, 10) _rotation 0 qtgui_freq_sink_x id qtgui_freq_sink_x_0 _enabled True type complex name QT GUI Plot fftsize 1024 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate ymin -140 ymax 10 nconnections 1 update_time 0.10 gui_hint _coordinate (1011, 21) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage math.pow(10,n/10.0) freq_offset cfo epsilon fso taps 1.0 + 1.0j seed 0 _coordinate (737, 106) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq samp_rate/4 amp math.pow(10,amp/10) offset 0 _coordinate (12, 106) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (218, 138) _rotation 0 qtgui_waterfall_sink_x id qtgui_waterfall_sink_x_0 _enabled True type complex name QT GUI Plot fftsize 1024 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate update_time 0.10 gui_hint _coordinate (1011, 130) _rotation 0 variable_qtgui_range id amp _enabled True label Sine Amplitude (dB) value 0 start -100 stop 100 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (785, 227) _rotation 0 variable_qtgui_range id fso _enabled True label Sampling Frequency Relative Offset value 1.0 start 0.9 stop 1.1 step .001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (621, 227) _rotation 0 variable_qtgui_range id n _enabled True label Noise Level (dB) value -12 start -30 stop 30 step .5 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (342, 226) _rotation 0 variable_qtgui_range id fD _enabled True label Max Doppler Frequency (Hz) value 125 start 0 stop 1000 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (13, 226) _rotation 0 variable_qtgui_range id cfo _enabled True label Frequency Offset value 0 start -20e3 stop 20e3 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (480, 225) _rotation 0 variable_qtgui_range id K _enabled True label K (Rician Factor) value 4 start 0 stop 30 step .1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (195, 226) _rotation 0 options id channel_tone_response _enabled True title Channel Tone Response author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True pre_hook None post_hook None realtime_scheduling _coordinate (10, 10) _rotation 0 channels_fading_model id channels_fading_model_0 _enabled True N 8 fDTs fD/samp_rate LOS True K K seed 0 _coordinate (415, 106) _rotation 0 channels_channel_model_0 qtgui_waterfall_sink_x_0 0 0 channels_channel_model_0 qtgui_freq_sink_x_0 0 0 channels_fading_model_0 channels_channel_model_0 0 0 blocks_throttle_0 channels_fading_model_0 0 0 analog_sig_source_x_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/gr-channels/examples/demo_qam.grc0000664000175000017500000005122212207702530021622 0ustar jcorganjcorgan Thu Aug 1 15:09:47 2013 options id demo_qam _enabled True title author mettus description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (97, 91) _rotation 0 variable id const_size _enabled True value 16 _coordinate (9, 90) _rotation 0 variable id k _enabled True value math.log(const_size)/math.log(2) _coordinate (101, 153) _rotation 0 variable_qtgui_range id q_ofs _enabled True label Q offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (943, 19) _rotation 0 variable_qtgui_range id i_ofs _enabled True label I offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,0,1,1 _coordinate (836, 19) _rotation 0 variable_qtgui_range id magbal _enabled True label IQ Magnitude Imbalance value 0 start 0 stop 10 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,0,1,1 _coordinate (504, 19) _rotation 0 variable_qtgui_range id phasebal _enabled True label IQ Phase Imbalance value 0 start 0 stop 45 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,1,1,1 _coordinate (682, 19) _rotation 0 variable_qtgui_range id freq_offset _enabled True label Frequency Offset value 0 start -0.5 stop 0.5 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0,1,1,1 _coordinate (364, 18) _rotation 0 variable_qtgui_range id phase_noise_mag _enabled True label Phase Noise Mag (dB) value -100 start -100 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0, 0, 1,1 _coordinate (201, 17) _rotation 0 import id import_0 _enabled True import import math _coordinate (11, 154) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_0 _enabled True type complex name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 update_time 0.10 gui_hint 4,1,1,1 affinity _coordinate (1038, 334) _rotation 0 channels_impairments id channels_impairments_0 _enabled True phase_noise_mag phase_noise_mag magbal magbal phasebal phasebal q_ofs q_ofs i_ofs i_ofs freq_offset freq_offset gamma 0 beta beta affinity minoutbuf 0 _coordinate (776, 251) _rotation 0 blocks_float_to_complex id blocks_float_to_complex_0 _enabled True vlen 1 affinity minoutbuf 0 _coordinate (374, 294) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (593, 307) _rotation 0 qtgui_const_sink_x id qtgui_const_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 1 update_time 0.10 gui_hint 4,0,1,1 affinity _coordinate (1038, 261) _rotation 0 variable_qtgui_range id beta _enabled True label k3 (IP3) value 0 start -1 stop 0 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,1 _coordinate (1051, 19) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type int min 0 max int(k) num_samps 10000 repeat True affinity minoutbuf 0 _coordinate (13, 239) _rotation 0 analog_random_source_x id analog_random_source_x_0_0 _enabled True type int min 0 max int(k) num_samps 10000 repeat True affinity minoutbuf 0 _coordinate (13, 332) _rotation 0 blocks_int_to_float id blocks_int_to_float_0 _enabled True vlen 1 scale k-1 affinity minoutbuf 0 _coordinate (190, 263) _rotation 0 blocks_int_to_float id blocks_int_to_float_0_0 _enabled True vlen 1 scale k-1 affinity minoutbuf 0 _coordinate (191, 356) _rotation 0 blocks_add_const_vxx id blocks_add_const_vxx_0 _enabled True type complex const (-1-1j)/2 vlen 1 affinity minoutbuf 0 _coordinate (402, 396) _rotation 0 channels_impairments_0 qtgui_const_sink_x_0 0 0 channels_impairments_0 qtgui_time_sink_x_0_0 0 0 blocks_throttle_0 channels_impairments_0 0 0 analog_random_source_x_0_0 blocks_int_to_float_0_0 0 0 blocks_int_to_float_0_0 blocks_float_to_complex_0 0 1 blocks_int_to_float_0 blocks_float_to_complex_0 0 0 blocks_add_const_vxx_0 blocks_throttle_0 0 0 blocks_float_to_complex_0 blocks_add_const_vxx_0 0 0 analog_random_source_x_0 blocks_int_to_float_0 0 0 gnuradio-3.7.2.1/gr-channels/examples/demo_gmsk.grc0000664000175000017500000004271712207702530022016 0ustar jcorganjcorgan Thu Aug 1 13:51:27 2013 options id demo_gmsk _enabled True title author mettus description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id const_size _enabled True value 4 _coordinate (9, 89) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (98, 90) _rotation 0 import id import_0 _enabled True import import math _coordinate (10, 152) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 256 num_samps 100000 repeat True affinity minoutbuf 0 _coordinate (13, 203) _rotation 0 digital_gmsk_mod id digital_gmsk_mod_0 _enabled True samples_per_symbol 10 bt 0.3 verbose False log False affinity minoutbuf 0 _coordinate (214, 219) _rotation 0 channels_impairments id channels_impairments_0 _enabled True phase_noise_mag phase_noise_mag magbal magbal phasebal phasebal q_ofs q_ofs i_ofs i_ofs freq_offset freq_offset gamma 0 beta beta affinity minoutbuf 0 _coordinate (451, 195) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_0 _enabled True type float name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 update_time 0.10 gui_hint 4,1,1,1 affinity _coordinate (916, 235) _rotation 0 analog_quadrature_demod_cf id analog_quadrature_demod_cf_0 _enabled True gain 1.0 affinity minoutbuf 0 _coordinate (708, 251) _rotation 0 qtgui_const_sink_x id qtgui_const_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 1 update_time 0.10 gui_hint 4,0,1,1 affinity _coordinate (706, 176) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (227, 310) _rotation 0 variable_qtgui_range id q_ofs _enabled True label Q offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (933, 12) _rotation 0 variable_qtgui_range id i_ofs _enabled True label I offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,0,1,1 _coordinate (826, 12) _rotation 0 variable_qtgui_range id phasebal _enabled True label IQ Phase Imbalance value 0 start 0 stop 45 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,1,1,1 _coordinate (672, 12) _rotation 0 variable_qtgui_range id magbal _enabled True label IQ Magnitude Imbalance value 0 start 0 stop 10 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,0,1,1 _coordinate (494, 12) _rotation 0 variable_qtgui_range id freq_offset _enabled True label Frequency Offset value 0 start -0.5 stop 0.5 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0,1,1,1 _coordinate (354, 11) _rotation 0 variable_qtgui_range id phase_noise_mag _enabled True label Phase Noise Mag (dB) value -100 start -100 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0, 0, 1,1 _coordinate (191, 10) _rotation 0 variable_qtgui_range id beta _enabled True label k3 (IP3) value 0 start -.1 stop 0 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,1 _coordinate (1041, 12) _rotation 0 analog_random_source_x_0 digital_gmsk_mod_0 0 0 blocks_throttle_0 channels_impairments_0 0 0 digital_gmsk_mod_0 blocks_throttle_0 0 0 channels_impairments_0 qtgui_const_sink_x_0 0 0 analog_quadrature_demod_cf_0 qtgui_time_sink_x_0_0 0 0 channels_impairments_0 analog_quadrature_demod_cf_0 0 0 gnuradio-3.7.2.1/gr-channels/examples/demo_ofdm.grc0000664000175000017500000007032112207702530021772 0ustar jcorganjcorgan Thu Aug 1 15:11:44 2013 options id demo_ofdm _enabled True title author mettus description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id const_size _enabled True value 64 _coordinate (11, 89) _rotation 0 variable id fft_size _enabled True value 1024 _coordinate (99, 89) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (11, 151) _rotation 0 variable id k _enabled True value math.log(const_size)/math.log(2) _coordinate (100, 151) _rotation 0 import id import_0 _enabled True import import math _coordinate (168, 153) _rotation 0 variable_qtgui_range id q_ofs _enabled True label Q offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (936, 9) _rotation 0 variable_qtgui_range id i_ofs _enabled True label I offset value 0 start -1 stop 1 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,0,1,1 _coordinate (829, 9) _rotation 0 variable_qtgui_range id phasebal _enabled True label IQ Phase Imbalance value 0 start 0 stop 45 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,1,1,1 _coordinate (675, 9) _rotation 0 variable_qtgui_range id magbal _enabled True label IQ Magnitude Imbalance value 0 start 0 stop 10 step 0.1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,0,1,1 _coordinate (497, 9) _rotation 0 variable_qtgui_range id freq_offset _enabled True label Frequency Offset value 0 start -0.5 stop 0.5 step 0.001 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0,1,1,1 _coordinate (357, 8) _rotation 0 variable_qtgui_range id phase_noise_mag _enabled True label Phase Noise Mag (dB) value -100 start -100 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0, 0, 1,1 _coordinate (194, 7) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0_0 _enabled True type complex name QT GUI Plot size 1024 srate samp_rate ymin -1 ymax 1 nconnections 1 update_time 0.10 gui_hint 4,1,1,1 affinity _coordinate (1102, 249) _rotation 0 variable_qtgui_range id beta _enabled True label k3 (IP3) value 0 start -10 stop 0 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 3,0,1,1 _coordinate (1042, 8) _rotation 0 blocks_float_to_complex id blocks_float_to_complex_0 _enabled True vlen 1 affinity minoutbuf 0 _coordinate (237, 424) _rotation 0 fft_vxx id fft_fft_vxx_0_0 _enabled True type complex fft_size fft_size forward True window fft_size*[1.0/math.sqrt(fft_size)] shift False nthreads 1 affinity minoutbuf 0 _coordinate (689, 150) _rotation 0 fft_vxx id fft_fft_vxx_0 _enabled True type complex fft_size fft_size forward False window fft_size*[1.0/math.sqrt(fft_size)] shift False nthreads 1 affinity minoutbuf 0 _coordinate (565, 485) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const 1.0/fft_size vlen 1 affinity minoutbuf 0 _coordinate (854, 571) _rotation 0 blocks_vector_to_stream id blocks_vector_to_stream_0_0 _enabled True type complex num_items fft_size vlen 1 affinity minoutbuf 0 _coordinate (833, 468) _rotation 0 channels_impairments id channels_impairments_0 _enabled True phase_noise_mag phase_noise_mag magbal magbal phasebal phasebal q_ofs q_ofs i_ofs i_ofs freq_offset freq_offset gamma 0 beta beta affinity minoutbuf 0 _coordinate (1074, 460) _rotation 0 blocks_stream_to_vector id blocks_stream_to_vector_0_0 _enabled True type complex num_items fft_size vlen 1 affinity minoutbuf 0 _coordinate (889, 400) _rotation 180 blocks_vector_to_stream id blocks_vector_to_stream_0 _enabled True type complex num_items fft_size vlen 1 affinity minoutbuf 0 _coordinate (806, 315) _rotation 0 blocks_stream_to_vector id blocks_stream_to_vector_0 _enabled True type complex num_items fft_size vlen 1 affinity minoutbuf 0 _coordinate (449, 343) _rotation 180 blocks_add_const_vxx id blocks_add_const_vxx_0 _enabled True type complex const (-1-1j)/2 vlen 1 affinity minoutbuf 0 _coordinate (337, 175) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (438, 243) _rotation 180 qtgui_const_sink_x id qtgui_const_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 1 update_time 0.10 gui_hint 4,0,1,1 affinity _coordinate (1102, 175) _rotation 0 blocks_int_to_float id blocks_int_to_float_0 _enabled True vlen 1 scale k-1 affinity minoutbuf 0 _coordinate (63, 412) _rotation 0 blocks_int_to_float id blocks_int_to_float_0_0 _enabled True vlen 1 scale k-1 affinity minoutbuf 0 _coordinate (63, 462) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type int min 0 max int(k) num_samps 10000 repeat True affinity minoutbuf 0 _coordinate (22, 271) _rotation 0 analog_random_source_x id analog_random_source_x_0_0 _enabled True type int min 0 max int(k) num_samps 10000 repeat True affinity minoutbuf 0 _coordinate (36, 543) _rotation 0 blocks_stream_to_vector_0_0 fft_fft_vxx_0_0 0 0 channels_impairments_0 blocks_stream_to_vector_0_0 0 0 blocks_throttle_0 blocks_stream_to_vector_0 0 0 fft_fft_vxx_0_0 blocks_vector_to_stream_0 0 0 blocks_add_const_vxx_0 blocks_throttle_0 0 0 blocks_float_to_complex_0 blocks_add_const_vxx_0 0 0 analog_random_source_x_0 blocks_int_to_float_0 0 0 blocks_int_to_float_0 blocks_float_to_complex_0 0 0 blocks_int_to_float_0_0 blocks_float_to_complex_0 0 1 analog_random_source_x_0_0 blocks_int_to_float_0_0 0 0 blocks_vector_to_stream_0 qtgui_time_sink_x_0_0 0 0 blocks_vector_to_stream_0 qtgui_const_sink_x_0 0 0 fft_fft_vxx_0 blocks_vector_to_stream_0_0 0 0 blocks_vector_to_stream_0_0 blocks_multiply_const_vxx_0 0 0 blocks_multiply_const_vxx_0 channels_impairments_0 0 0 blocks_stream_to_vector_0 fft_fft_vxx_0 0 0 gnuradio-3.7.2.1/gr-channels/examples/demo_spec_an.grc0000664000175000017500000005320212207702530022454 0ustar jcorganjcorgan Thu Aug 1 13:13:07 2013 blocks_add_xx id blocks_add_xx_0 _enabled True type complex num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (251, 344) _rotation 0 variable id fft_size _enabled True value 1000 _coordinate (17, 84) _rotation 0 variable id samp_rate _enabled True value 100000 _coordinate (10, 170) _rotation 0 import id imp0 _enabled True import import math _coordinate (238, 60) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type complex noise_type analog.GR_GAUSSIAN amp math.pow(10.0,snr/20.0)/math.sqrt(2.0) seed 42 affinity minoutbuf 0 _coordinate (16, 295) _rotation 0 variable_slider id freq_offset _enabled True label Freq_offset value 0 min -5*samp_rate/fft_size max 5*samp_rate/fft_size num_steps 200 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (314, 514) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq float(samp_rate)/float(fft_size)*26+freq_offset amp 1.0 offset 0 affinity minoutbuf 0 _coordinate (16, 386) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (370, 357) _rotation 0 variable_slider id snr _enabled True label "Noise Level" value 0 min -100 max 100 num_steps 200 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (167, 510) _rotation 0 blocks_rms_xx id blocks_rms_xx_0 _enabled True type complex alpha .0001 affinity minoutbuf 0 _coordinate (491, 138) _rotation 0 blocks_rms_xx id blocks_rms_xx_0_0 _enabled True type complex alpha .0001 affinity minoutbuf 0 _coordinate (465, 458) _rotation 0 blocks_divide_xx id blocks_divide_xx_0 _enabled True type float vlen 1 num_inputs 2 affinity minoutbuf 0 _coordinate (680, 630) _rotation 0 blocks_nlog10_ff id blocks_nlog10_ff_0 _enabled True n 20 k 0 vlen 1 affinity minoutbuf 0 _coordinate (813, 640) _rotation 0 wxgui_numbersink2 id snr_disp _enabled True type float title SNR units dB samp_rate samp_rate min_value -100 max_value 100 factor 1.0 decimal_places 5 ref_level 0 number_rate 15 peak_hold False average False avg_alpha 0 show_gauge False win_size grid_pos notebook affinity _coordinate (907, 654) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_0 _enabled True type float title Noise Amplitude units samp_rate samp_rate min_value -100 max_value 100 factor 1.0 decimal_places 5 ref_level 0 number_rate 15 peak_hold False average False avg_alpha 0 show_gauge False win_size grid_pos notebook affinity _coordinate (774, 46) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_0_0 _enabled True type float title Signal Amplitude units samp_rate samp_rate min_value -100 max_value 100 factor 1.0 decimal_places 5 ref_level 0 number_rate 15 peak_hold False average False avg_alpha 0 show_gauge False win_size grid_pos notebook affinity _coordinate (774, 452) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type complex title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts affinity _coordinate (696, 244) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 15 ref_level 0 ref_scale 2.0 fft_size fft_size fft_rate 20 peak_hold False average False avg_alpha 0 win window.flattop win_size grid_pos notebook freqvar None affinity _coordinate (894, 271) _rotation 0 options id demo_spec_an _enabled True title author mettus description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 analog_sig_source_x_0 blocks_add_xx_0 0 1 analog_noise_source_x_0 blocks_add_xx_0 0 0 blocks_add_xx_0 blocks_throttle_0 0 0 blocks_throttle_0 wxgui_fftsink2_0 0 0 analog_noise_source_x_0 blocks_rms_xx_0 0 0 blocks_rms_xx_0 wxgui_numbersink2_0 0 0 analog_sig_source_x_0 blocks_rms_xx_0_0 0 0 blocks_rms_xx_0_0 wxgui_numbersink2_0_0 0 0 blocks_nlog10_ff_0 snr_disp 0 0 blocks_divide_xx_0 blocks_nlog10_ff_0 0 0 blocks_rms_xx_0 blocks_divide_xx_0 0 1 blocks_rms_xx_0_0 blocks_divide_xx_0 0 0 blocks_throttle_0 wxgui_scopesink2_0 0 0 gnuradio-3.7.2.1/gr-channels/examples/demo_quantization.grc0000664000175000017500000004574312207702530023605 0ustar jcorganjcorgan Fri Aug 2 16:57:39 2013 options id demo_quantization _enabled True title author mettus description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 100000 _coordinate (11, 134) _rotation 0 import id import_0 _enabled True import import math _coordinate (11, 88) _rotation 0 variable_qtgui_range id bw _enabled True label BW value samp_rate/2 start samp_rate/100 stop samp_rate/2 step 100 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,2,1,1 _coordinate (873, 11) _rotation 0 variable_qtgui_range id center _enabled True label Center Freq. value samp_rate/11.0 start 0 stop samp_rate/2 step 100 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 2,1,1,1 _coordinate (724, 11) _rotation 0 variable_qtgui_chooser id bits _enabled True label Bits type int num_opts 0 value 16 options [0, 1, 2, 4, 6, 8, 10, 12, 14, 16] labels [] option0 0 label0 option1 1 label1 option2 2 label2 option3 3 label3 option4 4 label4 widget combo_box orient Qt.QVBoxLayout gui_hint 1,2,1,1 _coordinate (570, 10) _rotation 0 variable_qtgui_range id sigfreq _enabled True label Signal Freq value samp_rate*1.0247385/11.0 start 0 stop samp_rate/2 step 100 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 1,1,1,1 _coordinate (427, 9) _rotation 0 variable_qtgui_range id signal_amp _enabled True label Signal Power value -150 start -150 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0,2,1,1 _coordinate (301, 9) _rotation 0 variable_qtgui_range id noise_amp _enabled True label Noise Power value -150 start -150 stop 0 step 1 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint 0,1,1,1 _coordinate (173, 10) _rotation 0 blocks_add_xx id blocks_add_xx_0 _enabled True type float num_inputs 2 vlen 1 affinity minoutbuf 0 _coordinate (489, 297) _rotation 0 channels_quantizer id channels_quantizer_0 _enabled True bits bits affinity minoutbuf 0 _coordinate (827, 203) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type float const pow(2,bits-1) vlen 1 affinity minoutbuf 0 _coordinate (800, 287) _rotation 0 qtgui_freq_sink_x id qtgui_freq_sink_x_0 _enabled True type float name QT GUI Plot fftsize 2048 wintype firdes.WIN_BLACKMAN_hARRIS fc 0 bw samp_rate ymin -140 ymax 10 nconnections 1 update_time 0.10 gui_hint 3,1,1,2 affinity _coordinate (998, 170) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type float samp_rate samp_rate waveform analog.GR_COS_WAVE freq sigfreq amp pow(10.0,signal_amp/20.0) offset 0 affinity minoutbuf 0 _coordinate (7, 295) _rotation 0 band_pass_filter id band_pass_filter_0 _enabled True type fir_filter_fff decim 1 interp 1 gain 1 samp_rate samp_rate low_cutoff_freq max(bw/15.0,center-bw/2.0) high_cutoff_freq min(samp_rate/2.0-bw/15.0,center+bw/2.0) width bw/5.0 win firdes.WIN_HANN beta 6.76 affinity minoutbuf 0 _coordinate (212, 173) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type float noise_type analog.GR_GAUSSIAN amp pow(10.0,noise_amp/20.0) seed 42 affinity minoutbuf 0 _coordinate (9, 213) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type float samples_per_second samp_rate vlen 1 affinity minoutbuf 0 _coordinate (634, 203) _rotation 0 qtgui_histogram_sink_x id qtgui_histogram_sink_x_0 _enabled True name QT GUI Plot size 10240 bins 1000 xmin -10000 xmax 10000 nconnections 1 update_time 0.1 gui_hint affinity _coordinate (998, 271) _rotation 0 blocks_throttle_0 channels_quantizer_0 0 0 channels_quantizer_0 qtgui_freq_sink_x_0 0 0 band_pass_filter_0 blocks_add_xx_0 0 0 blocks_add_xx_0 blocks_throttle_0 0 0 channels_quantizer_0 blocks_multiply_const_vxx_0 0 0 blocks_multiply_const_vxx_0 qtgui_histogram_sink_x_0 0 0 analog_sig_source_x_0 blocks_add_xx_0 0 1 analog_noise_source_x_0 band_pass_filter_0 0 0 gnuradio-3.7.2.1/README.building-boost0000644000175000017500000000323711744612271017134 0ustar jcorganjcorganMost distributions have the required version of Boost (1.35) ready for installation using their standard package installation tools (apt-get, yum, etc.). If running a distribution that requires boost 1.35 (or later) be built from scratch, these instructions explain how to do so, and in a way that allows it to peacefully coexist with earlier versions of boost. Download the latest version of boost from boost.sourceforge.net. (boost_1_49_0.tar.bz2 was the latest when this was written). Different Boost versions often have different installations. If these instructions don't work, check the website www.boost.org for more help. unpack it somewhere cd into the resulting directory $ cd boost_1_49_0 # Pick a prefix to install it into. I used /opt/boost_1_49_0 $ BOOST_PREFIX=/opt/boost_1_49_0 $ ./bootstrap.sh $ sudo ./b2 --prefix=$BOOST_PREFIX --with-thread --with-date_time --with-program_options --with-filesystem --with-system --layout=versioned threading=multi variant=release install # Done! That was easy! Note that you don't have to specify each library, which will then build all Boost libraries and projects. By specifying only those required will just save compilation time. ---------------------------------------------------------------------- Installing GNU Radio with new Boost libraries. Tell cmake to look for the Boost libraries and header files in the new location with the folloing command: $ cd $ cmake -DBOOST_ROOT=$BOOST_PREFIX -DBoost_INCLUDE_DIR=$BOOST_PREFIX/include/boost-1_49/ -DBoost_LIBRARY_DIRS=$BOOST_PREFIX/lib $ make $ make test $ sudo make install See README for more installation details. gnuradio-3.7.2.1/COPYING0000644000175000017500000010451311700377700014363 0ustar jcorganjcorgan GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . gnuradio-3.7.2.1/gr-comedi/0000755000175000017500000000000012207440367015175 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/CMakeLists.txt0000664000175000017500000000705012207440367017741 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) PKG_CHECK_MODULES(COMEDI comedilib) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-comedi" ENABLE_GR_COMEDI COMEDI_FOUND LINUX #comedi uses linux specific device noces Boost_FOUND ENABLE_GNURADIO_RUNTIME ) GR_SET_GLOBAL(GR_COMEDI_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) GR_SET_GLOBAL(GR_COMEDI_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/swig ) SET(GR_PKG_COMEDI_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/comedi) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_COMEDI) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_COMEDI_DESCRIPTION "GNU Radio Comedi Blocks") CPACK_COMPONENT("comedi_runtime" GROUP "Comedi" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("comedi_devel" GROUP "Comedi" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("comedi_python" GROUP "Comedi" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime" DEPENDS "runtime_python;comedi_runtime" ) CPACK_COMPONENT("comedi_swig" GROUP "Comedi" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;comedi_python;comedi_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/comedi) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/comedi) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-comedi.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-comedi.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-comedi.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "comedi_devel" ) endif(ENABLE_GR_COMEDI) gnuradio-3.7.2.1/gr-comedi/include/0000775000175000017500000000000012207440367016622 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/include/gnuradio/0000775000175000017500000000000012207440367020432 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/include/gnuradio/comedi/0000775000175000017500000000000012207440367021672 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/include/gnuradio/comedi/CMakeLists.txt0000664000175000017500000000207212207440367024433 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h sink_s.h source_s.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/comedi COMPONENT "comedi_devel" ) gnuradio-3.7.2.1/gr-comedi/include/gnuradio/comedi/source_s.h0000664000175000017500000000330212207440367023663 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMEDI_SOURCE_S_H #define INCLUDED_COMEDI_SOURCE_S_H #include #include namespace gr { namespace comedi { /*! * \brief source using COMEDI * * The source has one to many input stream of signed short integers. * * Output samples will be in the range [-32768,32767]. */ class COMEDI_API source_s : virtual public sync_block { public: // gr::comedi::source_s::sptr typedef boost::shared_ptr sptr; /*! * \brief make a COMEDI source. * * \param sampling_freq sampling rate in Hz * \param dev COMEDI device name, e.g., "/dev/comedi0" */ static sptr make(int sampling_freq, const std::string dev = "/dev/comedi0"); }; } /* namespace comedi */ } /* namespace gr */ #endif /* INCLUDED_COMEDI_SOURCE_S_H */ gnuradio-3.7.2.1/gr-comedi/include/gnuradio/comedi/sink_s.h0000664000175000017500000000324112207440367023331 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMEDI_SINK_H #define INCLUDED_COMEDI_SINK_H #include #include namespace gr { namespace comedi { /*! * \brief sink using COMEDI * * The sink has one input stream of signed short integers. * * Input samples must be in the range [-32768,32767]. */ class COMEDI_API sink_s : virtual public sync_block { public: // gr::comedi::sink_s::sptr typedef boost::shared_ptr sptr; /*! * \brief make a COMEDI sink. * * \param sampling_freq sampling rate in Hz * \param dev COMEDI device name, e.g., "/dev/comedi0" */ static sptr make(int sampling_freq, const std::string dev = "/dev/comedi0"); }; } /* namespace comedi */ } /* namespace gr */ #endif /* INCLUDED_COMEDI_SINK_H */ gnuradio-3.7.2.1/gr-comedi/include/gnuradio/comedi/api.h0000664000175000017500000000203712207440367022616 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMEDI_API_H #define INCLUDED_COMEDI_API_H #include #ifdef gnuradio_comedi_EXPORTS # define COMEDI_API __GR_ATTR_EXPORT #else # define COMEDI_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_COMEDI_API_H */ gnuradio-3.7.2.1/gr-comedi/gnuradio-comedi.pc.in0000664000175000017500000000040712207440367021177 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-comedi Description: GNU Radio blocks for the comedi library Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-comedi Cflags: -I${includedir} gnuradio-3.7.2.1/gr-comedi/python/0000775000175000017500000000000012207440367016520 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/python/comedi/0000775000175000017500000000000012207440367017760 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/python/comedi/CMakeLists.txt0000664000175000017500000000332312207440367022521 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/comedi COMPONENT "comedi_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-comedi/python/comedi/qa_comedi.py0000775000175000017500000000234712207440367022264 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, comedi class test_comedi(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000_nop(self): """Just see if we can import the module... They may not have COMEDI library, etc. Don't try to run anything""" pass if __name__ == '__main__': gr_unittest.run(test_comedi, "test_comedi.xml") gnuradio-3.7.2.1/gr-comedi/python/comedi/__init__.py0000664000175000017500000000215212207440367022071 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks and utilities for COMEDI devices ''' # The presence of this file turns this directory into a Python package import os try: from comedi_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from comedi_swig import * gnuradio-3.7.2.1/gr-comedi/lib/0000775000175000017500000000000012207440367015745 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/lib/sink_s_impl.cc0000664000175000017500000001471312207440367020571 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "sink_s_impl.h" #include #include #include #include #include namespace gr { namespace comedi { /* * comedi_sink_s is untested because I don't own appropriate hardware. * Feedback is welcome! --SF */ static std::string default_device_name() { return "/dev/comedi0"; } // ---------------------------------------------------------------- sink_s::sptr sink_s::make(int sampling_freq, const std::string dev) { return gnuradio::get_initial_sptr (new sink_s_impl(sampling_freq, dev)); } sink_s_impl::sink_s_impl(int sampling_freq, const std::string device_name) : sync_block("comedi_sink_s", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_freq(sampling_freq), d_device_name(device_name.empty() ? default_device_name() : device_name), d_dev(0), d_subdevice(COMEDI_SUBD_AO), d_n_chan(1), // number of input channels d_map(0), d_buffer_size(0), d_buf_front(0), d_buf_back(0) { int aref=AREF_GROUND; int range=0; d_dev = comedi_open(d_device_name.c_str()); if(d_dev == 0) { comedi_perror(d_device_name.c_str()); throw std::runtime_error("sink_s_impl"); } unsigned int chanlist[256]; for(int i=0; i d_n_chan) throw std::runtime_error("sink_s_impl"); return true; } sink_s_impl::~sink_s_impl() { if(d_map) { munmap(d_map, d_buffer_size); d_map = 0; } comedi_close(d_dev); } int sink_s_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ret; int work_left = noutput_items * sizeof(sampl_t) * d_n_chan; sampl_t *pbuf = (sampl_t*)d_map; do { do { ret = comedi_get_buffer_contents(d_dev, d_subdevice); if(ret < 0) bail("comedi_get_buffer_contents", comedi_errno()); assert(ret % sizeof(sampl_t) == 0); assert(work_left % sizeof(sampl_t) == 0); ret = std::min(ret, work_left); d_buf_front += ret; assert(d_buffer_size%d_n_chan == 0); if(d_buf_front-d_buf_back > (unsigned)d_buffer_size) { d_buf_front+=d_buffer_size; d_buf_back +=d_buffer_size; } if(d_buf_front==d_buf_back){ usleep(1000000*std::min(work_left, d_buffer_size/2)/(d_sampling_freq*sizeof(sampl_t)*d_n_chan)); continue; } } while(d_buf_front==d_buf_back); for(unsigned i = d_buf_back/sizeof(sampl_t); i < d_buf_front/sizeof(sampl_t); i++) { int chan = i%d_n_chan; int i_idx = noutput_items-work_left/d_n_chan/sizeof(sampl_t) + \ (i-d_buf_back/sizeof(sampl_t))/d_n_chan; pbuf[i%(d_buffer_size/sizeof(sampl_t))] = input_items[chan]==0 ? 0 : (int)((short*)(input_items[chan]))[i_idx] + 32767; } // FIXME: how to tell comedi the buffer is *written* ? ret = comedi_mark_buffer_read(d_dev, d_subdevice, d_buf_front-d_buf_back); if(ret < 0) bail("comedi_mark_buffer_read", comedi_errno()); work_left -= d_buf_front-d_buf_back; d_buf_back = d_buf_front; } while(work_left > 0); return noutput_items; } void sink_s_impl::output_error_msg(const char *msg, int err) { fprintf(stderr, "sink_s_impl[%s]: %s: %s\n", d_device_name.c_str(), msg, comedi_strerror(err)); } void sink_s_impl::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("sink_s_impl"); } } /* namespace comedi */ } /* namespace gr */ gnuradio-3.7.2.1/gr-comedi/lib/CMakeLists.txt0000664000175000017500000000355112207440367020511 0ustar jcorganjcorgan# Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_COMEDI_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${LOG4CXX_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${COMEDI_INCLUDE_DIRS} ) link_directories( ${LOG4CXX_LIBRARY_DIRS} ${Boost_LIBRARY_DIRS} ${COMEDI_LIBRARY_DIRS} ) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND comedi_sources sink_s_impl.cc source_s_impl.cc ) list(APPEND comedi_libs gnuradio-runtime ${Boost_LIBRARIES} ${COMEDI_LIBRARIES} ) add_library(gnuradio-comedi SHARED ${comedi_sources}) target_link_libraries(gnuradio-comedi ${comedi_libs}) GR_LIBRARY_FOO(gnuradio-comedi RUNTIME_COMPONENT "comedi_runtime" DEVEL_COMPONENT "comedi_devel") gnuradio-3.7.2.1/gr-comedi/lib/source_s_impl.cc0000664000175000017500000001456512207440367021132 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "source_s_impl.h" #include #include #include #include #include // FIXME these should query some kind of user preference namespace gr { namespace comedi { static std::string default_device_name() { return "/dev/comedi0"; } // ---------------------------------------------------------------- source_s::sptr source_s::make(int sampling_freq, const std::string dev) { return gnuradio::get_initial_sptr (new source_s_impl(sampling_freq, dev)); } source_s_impl::source_s_impl(int sampling_freq, const std::string device_name) : sync_block("comedi_source_s", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_sampling_freq(sampling_freq), d_device_name(device_name.empty() ? default_device_name() : device_name), d_dev(0), d_subdevice(0/*COMEDI_SUBD_AI*/), d_n_chan(1), // number of input channels d_map(0), d_buffer_size(0), d_buf_front(0), d_buf_back(0) { int aref = AREF_GROUND; int range = 0; d_dev = comedi_open(d_device_name.c_str()); if(d_dev == 0) { comedi_perror(d_device_name.c_str()); throw std::runtime_error("source_s_impl"); } unsigned int chanlist[256]; for(int i=0; i d_n_chan) throw std::runtime_error("source_s_impl"); return true; } source_s_impl::~source_s_impl() { if(d_map) { munmap(d_map, d_buffer_size); d_map = 0; } comedi_close(d_dev); } int source_s_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ret; int work_left = noutput_items * sizeof(sampl_t) * d_n_chan; sampl_t *pbuf = (sampl_t*)d_map; do { do { ret = comedi_get_buffer_contents(d_dev, d_subdevice); if(ret < 0) bail("comedi_get_buffer_contents", comedi_errno()); assert(ret % sizeof(sampl_t) == 0); assert(work_left % sizeof(sampl_t) == 0); ret = std::min(ret, work_left); d_buf_front += ret; assert(d_buffer_size%d_n_chan == 0); if(d_buf_front-d_buf_back > (unsigned)d_buffer_size) { d_buf_front+=d_buffer_size; d_buf_back +=d_buffer_size; } if(d_buf_front==d_buf_back) { usleep(1000000*std::min(work_left, d_buffer_size/2)/(d_sampling_freq*sizeof(sampl_t)*d_n_chan)); continue; } } while(d_buf_front == d_buf_back); for(unsigned i=d_buf_back/sizeof(sampl_t); i < d_buf_front/sizeof(sampl_t); i++) { int chan = i%d_n_chan; int o_idx = noutput_items-work_left/d_n_chan/sizeof(sampl_t) + \ (i-d_buf_back/sizeof(sampl_t))/d_n_chan; if(output_items[chan]) ((short*)(output_items[chan]))[o_idx] = (int)pbuf[i%(d_buffer_size/sizeof(sampl_t))] - 32767; } ret = comedi_mark_buffer_read(d_dev,d_subdevice, d_buf_front-d_buf_back); if(ret < 0) bail("comedi_mark_buffer_read", comedi_errno()); work_left -= d_buf_front-d_buf_back; d_buf_back = d_buf_front; } while(work_left > 0); return noutput_items; } void source_s_impl::output_error_msg(const char *msg, int err) { fprintf(stderr, "source_s_impl[%s]: %s: %s\n", d_device_name.c_str(), msg, comedi_strerror(err)); } void source_s_impl::bail(const char *msg, int err) throw (std::runtime_error) { output_error_msg(msg, err); throw std::runtime_error("source_s_impl"); } } /* namespace comedi */ } /* namespace gr */ gnuradio-3.7.2.1/gr-comedi/lib/sink_s_impl.h0000664000175000017500000000412512207440367020427 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMEDI_SINK_IMPL_H #define INCLUDED_COMEDI_SINK_IMPL_H #include #include #include #include namespace gr { namespace comedi { class sink_s_impl : public sink_s { private: // typedef for pointer to class work method typedef int (sink_s::*work_t)(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int d_sampling_freq; std::string d_device_name; comedi_t *d_dev; int d_subdevice; int d_n_chan; void *d_map; int d_buffer_size; unsigned d_buf_front; unsigned d_buf_back; // random stats int d_nunderuns; // count of underruns void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); public: sink_s_impl(int sampling_freq, const std::string device_name); ~sink_s_impl(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace comedi */ } /* namespace gr */ #endif /* INCLUDED_COMEDI_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-comedi/lib/source_s_impl.h0000664000175000017500000000415612207440367020767 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMEDI_SOURCE_S_IMPL_H #define INCLUDED_COMEDI_SOURCE_S_IMPL_H #include #include #include #include namespace gr { namespace comedi { class source_s_impl : public source_s { private: // typedef for pointer to class work method typedef int(source_s::*work_t)(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); unsigned int d_sampling_freq; std::string d_device_name; comedi_t *d_dev; int d_subdevice; int d_n_chan; void *d_map; int d_buffer_size; unsigned d_buf_front; unsigned d_buf_back; // random stats int d_noverruns; // count of overruns void output_error_msg(const char *msg, int err); void bail(const char *msg, int err) throw (std::runtime_error); public: source_s_impl(int sampling_freq, const std::string device_name); ~source_s_impl(); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace comedi */ } /* namespace gr */ #endif /* INCLUDED_COMEDI_SOURCE_S_IMPL_H */ gnuradio-3.7.2.1/gr-comedi/swig/0000775000175000017500000000000012207440367016150 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-comedi/swig/CMakeLists.txt0000664000175000017500000000363712207440367020721 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_COMEDI_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) # Setup swig docs to depend on includes and pull in from build directory set(GR_SWIG_TARGET_DEPS comedi_generated_includes) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/comedi_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/comedi) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-comedi) GR_SWIG_MAKE(comedi_swig comedi_swig.i) GR_SWIG_INSTALL( TARGETS comedi_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/comedi COMPONENT "comedi_python" ) install( FILES comedi_swig.i ${CMAKE_CURRENT_BINARY_DIR}/comedi_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "comedi_swig" ) gnuradio-3.7.2.1/gr-comedi/swig/comedi_swig.i0000664000175000017500000000222612207440367020615 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define COMEDI_API %include "gnuradio.i" //load generated python docstrings %include "comedi_swig_doc.i" %{ #include "gnuradio/comedi/sink_s.h" #include "gnuradio/comedi/source_s.h" %} %include "gnuradio/comedi/sink_s.h" %include "gnuradio/comedi/source_s.h" GR_SWIG_BLOCK_MAGIC2(comedi, sink_s); GR_SWIG_BLOCK_MAGIC2(comedi, source_s); gnuradio-3.7.2.1/gr-comedi/README0000644000175000017500000000012711700377700016052 0ustar jcorganjcorganThis module appears to wrap COMEDI devices for GNU Radio. See http://www.comedi.org/. gnuradio-3.7.2.1/gnuradio-runtime/0000775000175000017500000000000012207551453016621 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/CMakeLists.txt0000664000175000017500000001417412207551453021370 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) include(GrPython) ######################################################################## # Setup compatibility checks and defines ######################################################################## include(${CMAKE_CURRENT_SOURCE_DIR}/ConfigChecks.cmake) GR_CHECK_LINUX_SCHED_AVAIL() ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gnuradio-runtime" ENABLE_GNURADIO_RUNTIME Boost_FOUND ENABLE_VOLK PYTHONINTERP_FOUND ) GR_SET_GLOBAL(GNURADIO_RUNTIME_INCLUDE_DIRS ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR}/gnuradio-runtime/include ${CMAKE_BINARY_DIR}/gnuradio-runtime/include ) GR_SET_GLOBAL(GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${CMAKE_SOURCE_DIR}/gnuradio-runtime/swig ${CMAKE_BINARY_DIR}/gnuradio-runtime/swig ) get_filename_component(GNURADIO_RUNTIME_PYTHONPATH ${CMAKE_SOURCE_DIR}/python ABSOLUTE ) GR_SET_GLOBAL(GNURADIO_RUNTIME_PYTHONPATH ${GNURADIO_RUNTIME_PYTHONPATH}) ######################################################################## # Register controlport component ######################################################################## FIND_PACKAGE(ICE-3.5) # check for ICE 3.5 if(NOT ICE_FOUND) message(STATUS "ICE 3.5 not found. Looking for 3.4") FIND_PACKAGE(ICE) # checks for version 3.4 endif(NOT ICE_FOUND) FIND_PACKAGE(SWIG) if(SWIG_FOUND) set(SWIG_VERSION_CHECK FALSE) if("${SWIG_VERSION}" VERSION_GREATER "2.0.0") set(SWIG_VERSION_CHECK TRUE) else("${SWIG_VERSION}" VERSION_GREATER "2.0.0") message(STATUS "") message(STATUS "Ctrlport requires SWIG version >= 2.0") endif() endif(SWIG_FOUND) GR_REGISTER_COMPONENT("gr-ctrlport" ENABLE_GR_CTRLPORT Boost_FOUND SWIG_FOUND SWIG_VERSION_CHECK ICE_FOUND ENABLE_GNURADIO_RUNTIME ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GNURADIO_RUNTIME) get_filename_component(GR_RUNTIME_PYTHONPATH ${CMAKE_CURRENT_SOURCE_DIR}/python ABSOLUTE ) GR_SET_GLOBAL(GR_RUNTIME_PYTHONPATH ${GR_RUNTIME_PYTHONPATH}) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_RUNTIME_DESCRIPTION "GNU Radio Runtime") CPACK_COMPONENT("runtime_runtime" GROUP "Runtime" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("runtime_devel" GROUP "Runtime" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("runtime_python" GROUP "Runtime" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime" DEPENDS "runtime_python;runtime_runtime" ) CPACK_COMPONENT("runtime_swig" GROUP "Runtime" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;runtime_python;runtime_devel" ) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-runtime.conf.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-runtime.conf @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-runtime.conf DESTINATION ${GR_PREFSDIR} COMPONENT "runtime_runtime" ) if(ENABLE_GR_LOG AND HAVE_LOG4CPP) install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/gr_log_default.conf DESTINATION ${GR_CONF_DIR}/gnuradio COMPONENT "runtime_runtime" ) endif(ENABLE_GR_LOG AND HAVE_LOG4CPP) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include) add_subdirectory(lib) add_subdirectory(apps) #add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python) # add_subdirectory(grc) add_subdirectory(examples) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-runtime.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-runtime.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-runtime.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "runtime_devel" ) ######################################################################## # Setup ControlPort preferences file and installation information ######################################################################## if(ENABLE_GR_CTRLPORT) SET(GR_PKG_CTRL_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/ctrlport) SET(GR_PKG_CTRL_SLICE_DIR ${GR_PKG_DATA_DIR}/ctrlport) file(TO_NATIVE_PATH ${CMAKE_INSTALL_PREFIX}/${GR_PKG_CTRL_SLICE_DIR} slicedir) install( FILES ctrlport.conf.example DESTINATION ${SYSCONFDIR}/${CMAKE_PROJECT_NAME} COMPONENT "gnuradio_runtime" ) endif(ENABLE_GR_CTRLPORT) endif(ENABLE_GNURADIO_RUNTIME) gnuradio-3.7.2.1/gnuradio-runtime/include/0000775000175000017500000000000012207440367020245 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/include/pmt/0000775000175000017500000000000012244272666021053 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/include/pmt/pmt.h0000664000175000017500000007665512244272666022047 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PMT_H #define INCLUDED_PMT_H #include #include #include #include #include #include #include #include #include #include namespace gr { namespace messages { class msg_accepter; } } /*! * This file defines a polymorphic type and the operations on it. * * It draws heavily on the idea of scheme and lisp data types. * The interface parallels that in Guile 1.8, with the notable * exception that these objects are transparently reference counted. */ namespace pmt { /*! * \brief base class of all pmt types */ class pmt_base; /*! * \brief typedef for shared pointer (transparent reference counting). * See http://www.boost.org/libs/smart_ptr/smart_ptr.htm */ typedef boost::intrusive_ptr pmt_t; extern PMT_API void intrusive_ptr_add_ref(pmt_base*); extern PMT_API void intrusive_ptr_release(pmt_base*); class PMT_API exception : public std::logic_error { public: exception(const std::string &msg, pmt_t obj); }; class PMT_API wrong_type : public exception { public: wrong_type(const std::string &msg, pmt_t obj); }; class PMT_API out_of_range : public exception { public: out_of_range(const std::string &msg, pmt_t obj); }; class PMT_API notimplemented : public exception { public: notimplemented(const std::string &msg, pmt_t obj); }; /* * ------------------------------------------------------------------------ * Booleans. Two constants, #t and #f. * * In predicates, anything that is not #f is considered true. * I.e., there is a single false value, #f. * ------------------------------------------------------------------------ */ extern PMT_API const pmt_t PMT_T; //< \#t : boolean true constant extern PMT_API const pmt_t PMT_F; //< \#f : boolean false constant //! Return true if obj is \#t or \#f, else return false. PMT_API bool is_bool(pmt_t obj); //! Return false if obj is \#f, else return true. PMT_API bool is_true(pmt_t obj); //! Return true if obj is \#f, else return true. PMT_API bool is_false(pmt_t obj); //! Return \#f is val is false, else return \#t. PMT_API pmt_t from_bool(bool val); //! Return true if val is pmt::True, return false when val is pmt::PMT_F, // else raise wrong_type exception. PMT_API bool to_bool(pmt_t val); /* * ------------------------------------------------------------------------ * Symbols * ------------------------------------------------------------------------ */ //! Return true if obj is a symbol, else false. PMT_API bool is_symbol(const pmt_t& obj); //! Return the symbol whose name is \p s. PMT_API pmt_t string_to_symbol(const std::string &s); //! Alias for pmt_string_to_symbol PMT_API pmt_t intern(const std::string &s); /*! * If \p is a symbol, return the name of the symbol as a string. * Otherwise, raise the wrong_type exception. */ PMT_API const std::string symbol_to_string(const pmt_t& sym); /* * ------------------------------------------------------------------------ * Numbers: we support integer, real and complex * ------------------------------------------------------------------------ */ //! Return true if obj is any kind of number, else false. PMT_API bool is_number(pmt_t obj); /* * ------------------------------------------------------------------------ * Integers * ------------------------------------------------------------------------ */ //! Return true if \p x is an integer number, else false PMT_API bool is_integer(pmt_t x); //! Return the pmt value that represents the integer \p x. PMT_API pmt_t from_long(long x); /*! * \brief Convert pmt to long if possible. * * When \p x represents an exact integer that fits in a long, * return that integer. Else raise an exception, either wrong_type * when x is not an exact integer, or out_of_range when it doesn't fit. */ PMT_API long to_long(pmt_t x); /* * ------------------------------------------------------------------------ * uint64_t * ------------------------------------------------------------------------ */ //! Return true if \p x is an uint64 number, else false PMT_API bool is_uint64(pmt_t x); //! Return the pmt value that represents the uint64 \p x. PMT_API pmt_t from_uint64(uint64_t x); /*! * \brief Convert pmt to uint64 if possible. * * When \p x represents an exact integer that fits in a uint64, * return that uint64. Else raise an exception, either wrong_type * when x is not an exact uint64, or out_of_range when it doesn't fit. */ PMT_API uint64_t to_uint64(pmt_t x); /* * ------------------------------------------------------------------------ * Reals * ------------------------------------------------------------------------ */ /* * \brief Return true if \p obj is a real number, else false. */ PMT_API bool is_real(pmt_t obj); //! Return the pmt value that represents double \p x. PMT_API pmt_t from_double(double x); /*! * \brief Convert pmt to double if possible. * * Returns the number closest to \p val that is representable * as a double. The argument \p val must be a real or integer, otherwise * a wrong_type exception is raised. */ PMT_API double to_double(pmt_t x); /* * ------------------------------------------------------------------------ * Complex * ------------------------------------------------------------------------ */ /*! * \brief return true if \p obj is a complex number, false otherwise. */ PMT_API bool is_complex(pmt_t obj); //! Return a complex number constructed of the given real and imaginary parts. PMT_API pmt_t make_rectangular(double re, double im); //! Return a complex number constructed of the given real and imaginary parts. PMT_API pmt_t from_complex(double re, double im); //! Return a complex number constructed of the given a complex number. PMT_API pmt_t from_complex(const std::complex &z); //! Return a complex number constructed of the given real and imaginary parts. PMT_API pmt_t pmt_from_complex(double re, double im); //! Return a complex number constructed of the given a complex number. PMT_API pmt_t pmt_from_complex(const std::complex &z); /*! * If \p z is complex, real or integer, return the closest complex. * Otherwise, raise the wrong_type exception. */ PMT_API std::complex to_complex(pmt_t z); /* * ------------------------------------------------------------------------ * Pairs * ------------------------------------------------------------------------ */ extern PMT_API const pmt_t PMT_NIL; //< the empty list //! Return true if \p x is the empty list, otherwise return false. PMT_API bool is_null(const pmt_t& x); //! Return true if \p obj is a pair, else false. PMT_API bool is_pair(const pmt_t& obj); //! Return a newly allocated pair whose car is \p x and whose cdr is \p y. PMT_API pmt_t cons(const pmt_t& x, const pmt_t& y); //! If \p pair is a pair, return the car of the \p pair, otherwise raise wrong_type. PMT_API pmt_t car(const pmt_t& pair); //! If \p pair is a pair, return the cdr of the \p pair, otherwise raise wrong_type. PMT_API pmt_t cdr(const pmt_t& pair); //! Stores \p value in the car field of \p pair. PMT_API void set_car(pmt_t pair, pmt_t value); //! Stores \p value in the cdr field of \p pair. PMT_API void set_cdr(pmt_t pair, pmt_t value); PMT_API pmt_t caar(pmt_t pair); PMT_API pmt_t cadr(pmt_t pair); PMT_API pmt_t cdar(pmt_t pair); PMT_API pmt_t cddr(pmt_t pair); PMT_API pmt_t caddr(pmt_t pair); PMT_API pmt_t cadddr(pmt_t pair); /* * ------------------------------------------------------------------------ * Tuples * * Store a fixed number of objects. Tuples are not modifiable, and thus * are excellent for use as messages. Indexing is zero based. * Access time to an element is O(1). * ------------------------------------------------------------------------ */ //! Return true if \p x is a tuple, othewise false. PMT_API bool is_tuple(pmt_t x); PMT_API pmt_t make_tuple(); PMT_API pmt_t make_tuple(const pmt_t &e0); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8); PMT_API pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8, const pmt_t &e9); /*! * If \p x is a vector or proper list, return a tuple containing the elements of x */ PMT_API pmt_t to_tuple(const pmt_t &x); /*! * Return the contents of position \p k of \p tuple. * \p k must be a valid index of \p tuple. */ PMT_API pmt_t tuple_ref(const pmt_t &tuple, size_t k); /* * ------------------------------------------------------------------------ * Vectors * * These vectors can hold any kind of objects. Indexing is zero based. * ------------------------------------------------------------------------ */ //! Return true if \p x is a vector, othewise false. PMT_API bool is_vector(pmt_t x); //! Make a vector of length \p k, with initial values set to \p fill PMT_API pmt_t make_vector(size_t k, pmt_t fill); /*! * Return the contents of position \p k of \p vector. * \p k must be a valid index of \p vector. */ PMT_API pmt_t vector_ref(pmt_t vector, size_t k); //! Store \p obj in position \p k. PMT_API void vector_set(pmt_t vector, size_t k, pmt_t obj); //! Store \p fill in every position of \p vector PMT_API void vector_fill(pmt_t vector, pmt_t fill); /* * ------------------------------------------------------------------------ * Binary Large Objects (BLOBs) * * Handy for passing around uninterpreted chunks of memory. * ------------------------------------------------------------------------ */ //! Return true if \p x is a blob, othewise false. PMT_API bool is_blob(pmt_t x); /*! * \brief Make a blob given a pointer and length in bytes * * \param buf is the pointer to data to use to create blob * \param len is the size of the data in bytes. * * The data is copied into the blob. */ PMT_API pmt_t make_blob(const void *buf, size_t len); //! Return a pointer to the blob's data PMT_API const void *blob_data(pmt_t blob); //! Return the blob's length in bytes PMT_API size_t blob_length(pmt_t blob); /*! *
 *		       Uniform Numeric Vectors
 *
 * A uniform numeric vector is a vector whose elements are all of single
 * numeric type.  pmt offers uniform numeric vectors for signed and
 * unsigned 8-bit, 16-bit, 32-bit, and 64-bit integers, two sizes of
 * floating point values, and complex floating-point numbers of these
 * two sizes.  Indexing is zero based.
 *
 * The names of the functions include these tags in their names:
 *
 *    u8  unsigned 8-bit integers
 *    s8  signed 8-bit integers
 *   u16  unsigned 16-bit integers
 *   s16  signed 16-bit integers
 *   u32  unsigned 32-bit integers
 *   s32  signed 32-bit integers
 *   u64  unsigned 64-bit integers
 *   s64  signed 64-bit integers
 *   f32  the C++ type float
 *   f64  the C++ type double
 *   c32  the C++ type complex
 *   c64  the C++ type complex
 * 
*/ //! true if \p x is any kind of uniform numeric vector PMT_API bool is_uniform_vector(pmt_t x); PMT_API bool is_u8vector(pmt_t x); PMT_API bool is_s8vector(pmt_t x); PMT_API bool is_u16vector(pmt_t x); PMT_API bool is_s16vector(pmt_t x); PMT_API bool is_u32vector(pmt_t x); PMT_API bool is_s32vector(pmt_t x); PMT_API bool is_u64vector(pmt_t x); PMT_API bool is_s64vector(pmt_t x); PMT_API bool is_f32vector(pmt_t x); PMT_API bool is_f64vector(pmt_t x); PMT_API bool is_c32vector(pmt_t x); PMT_API bool is_c64vector(pmt_t x); PMT_API pmt_t make_u8vector(size_t k, uint8_t fill); PMT_API pmt_t make_s8vector(size_t k, int8_t fill); PMT_API pmt_t make_u16vector(size_t k, uint16_t fill); PMT_API pmt_t make_s16vector(size_t k, int16_t fill); PMT_API pmt_t make_u32vector(size_t k, uint32_t fill); PMT_API pmt_t make_s32vector(size_t k, int32_t fill); PMT_API pmt_t make_u64vector(size_t k, uint64_t fill); PMT_API pmt_t make_s64vector(size_t k, int64_t fill); PMT_API pmt_t make_f32vector(size_t k, float fill); PMT_API pmt_t make_f64vector(size_t k, double fill); PMT_API pmt_t make_c32vector(size_t k, std::complex fill); PMT_API pmt_t make_c64vector(size_t k, std::complex fill); PMT_API pmt_t init_u8vector(size_t k, const uint8_t *data); PMT_API pmt_t init_u8vector(size_t k, const std::vector &data); PMT_API pmt_t init_s8vector(size_t k, const int8_t *data); PMT_API pmt_t init_s8vector(size_t k, const std::vector &data); PMT_API pmt_t init_u16vector(size_t k, const uint16_t *data); PMT_API pmt_t init_u16vector(size_t k, const std::vector &data); PMT_API pmt_t init_s16vector(size_t k, const int16_t *data); PMT_API pmt_t init_s16vector(size_t k, const std::vector &data); PMT_API pmt_t init_u32vector(size_t k, const uint32_t *data); PMT_API pmt_t init_u32vector(size_t k, const std::vector &data); PMT_API pmt_t init_s32vector(size_t k, const int32_t *data); PMT_API pmt_t init_s32vector(size_t k, const std::vector &data); PMT_API pmt_t init_u64vector(size_t k, const uint64_t *data); PMT_API pmt_t init_u64vector(size_t k, const std::vector &data); PMT_API pmt_t init_s64vector(size_t k, const int64_t *data); PMT_API pmt_t init_s64vector(size_t k, const std::vector &data); PMT_API pmt_t init_f32vector(size_t k, const float *data); PMT_API pmt_t init_f32vector(size_t k, const std::vector &data); PMT_API pmt_t init_f64vector(size_t k, const double *data); PMT_API pmt_t init_f64vector(size_t k, const std::vector &data); PMT_API pmt_t init_c32vector(size_t k, const std::complex *data); PMT_API pmt_t init_c32vector(size_t k, const std::vector > &data); PMT_API pmt_t init_c64vector(size_t k, const std::complex *data); PMT_API pmt_t init_c64vector(size_t k, const std::vector > &data); PMT_API uint8_t u8vector_ref(pmt_t v, size_t k); PMT_API int8_t s8vector_ref(pmt_t v, size_t k); PMT_API uint16_t u16vector_ref(pmt_t v, size_t k); PMT_API int16_t s16vector_ref(pmt_t v, size_t k); PMT_API uint32_t u32vector_ref(pmt_t v, size_t k); PMT_API int32_t s32vector_ref(pmt_t v, size_t k); PMT_API uint64_t u64vector_ref(pmt_t v, size_t k); PMT_API int64_t s64vector_ref(pmt_t v, size_t k); PMT_API float f32vector_ref(pmt_t v, size_t k); PMT_API double f64vector_ref(pmt_t v, size_t k); PMT_API std::complex c32vector_ref(pmt_t v, size_t k); PMT_API std::complex c64vector_ref(pmt_t v, size_t k); PMT_API void u8vector_set(pmt_t v, size_t k, uint8_t x); //< v[k] = x PMT_API void s8vector_set(pmt_t v, size_t k, int8_t x); PMT_API void u16vector_set(pmt_t v, size_t k, uint16_t x); PMT_API void s16vector_set(pmt_t v, size_t k, int16_t x); PMT_API void u32vector_set(pmt_t v, size_t k, uint32_t x); PMT_API void s32vector_set(pmt_t v, size_t k, int32_t x); PMT_API void u64vector_set(pmt_t v, size_t k, uint64_t x); PMT_API void s64vector_set(pmt_t v, size_t k, int64_t x); PMT_API void f32vector_set(pmt_t v, size_t k, float x); PMT_API void f64vector_set(pmt_t v, size_t k, double x); PMT_API void c32vector_set(pmt_t v, size_t k, std::complex x); PMT_API void c64vector_set(pmt_t v, size_t k, std::complex x); // Return const pointers to the elements PMT_API const void *uniform_vector_elements(pmt_t v, size_t &len); //< works with any; len is in bytes PMT_API const uint8_t *u8vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const int8_t *s8vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const uint16_t *u16vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const int16_t *s16vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const uint32_t *u32vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const int32_t *s32vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const uint64_t *u64vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const int64_t *s64vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const float *f32vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const double *f64vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const std::complex *c32vector_elements(pmt_t v, size_t &len); //< len is in elements PMT_API const std::complex *c64vector_elements(pmt_t v, size_t &len); //< len is in elements // len is in elements PMT_API const std::vector u8vector_elements(pmt_t v); PMT_API const std::vector s8vector_elements(pmt_t v); PMT_API const std::vector u16vector_elements(pmt_t v); PMT_API const std::vector s16vector_elements(pmt_t v); PMT_API const std::vector u32vector_elements(pmt_t v); PMT_API const std::vector s32vector_elements(pmt_t v); PMT_API const std::vector u64vector_elements(pmt_t v); PMT_API const std::vector s64vector_elements(pmt_t v); PMT_API const std::vector f32vector_elements(pmt_t v); PMT_API const std::vector f64vector_elements(pmt_t v); PMT_API const std::vector > c32vector_elements(pmt_t v); PMT_API const std::vector > c64vector_elements(pmt_t v); // len is in elements PMT_API const std::vector pmt_u8vector_elements(pmt_t v); PMT_API const std::vector pmt_s8vector_elements(pmt_t v); PMT_API const std::vector pmt_u16vector_elements(pmt_t v); PMT_API const std::vector pmt_s16vector_elements(pmt_t v); PMT_API const std::vector pmt_u32vector_elements(pmt_t v); PMT_API const std::vector pmt_s32vector_elements(pmt_t v); PMT_API const std::vector pmt_u64vector_elements(pmt_t v); PMT_API const std::vector pmt_s64vector_elements(pmt_t v); PMT_API const std::vector pmt_f32vector_elements(pmt_t v); PMT_API const std::vector pmt_f64vector_elements(pmt_t v); PMT_API const std::vector > pmt_c32vector_elements(pmt_t v); PMT_API const std::vector > pmt_c64vector_elements(pmt_t v); // Return non-const pointers to the elements PMT_API void *uniform_vector_writable_elements(pmt_t v, size_t &len); //< works with any; len is in bytes PMT_API uint8_t *u8vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API int8_t *s8vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API uint16_t *u16vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API int16_t *s16vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API uint32_t *u32vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API int32_t *s32vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API uint64_t *u64vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API int64_t *s64vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API float *f32vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API double *f64vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API std::complex *c32vector_writable_elements(pmt_t v, size_t &len); //< len is in elements PMT_API std::complex *c64vector_writable_elements(pmt_t v, size_t &len); //< len is in elements /* * ------------------------------------------------------------------------ * Dictionary (a.k.a associative array, hash, map) * * This is a functional data structure that is persistent. Updating a * functional data structure does not destroy the existing version, but * rather creates a new version that coexists with the old. * ------------------------------------------------------------------------ */ //! Return true if \p obj is a dictionary PMT_API bool is_dict(const pmt_t &obj); //! Make an empty dictionary PMT_API pmt_t make_dict(); //! Return a new dictionary with \p key associated with \p value. PMT_API pmt_t dict_add(const pmt_t &dict, const pmt_t &key, const pmt_t &value); //! Return a new dictionary with \p key removed. PMT_API pmt_t dict_delete(const pmt_t &dict, const pmt_t &key); //! Return true if \p key exists in \p dict PMT_API bool dict_has_key(const pmt_t &dict, const pmt_t &key); //! If \p key exists in \p dict, return associated value; otherwise return \p not_found. PMT_API pmt_t dict_ref(const pmt_t &dict, const pmt_t &key, const pmt_t ¬_found); //! Return list of (key . value) pairs PMT_API pmt_t dict_items(pmt_t dict); //! Return list of keys PMT_API pmt_t dict_keys(pmt_t dict); //! Return list of values PMT_API pmt_t dict_values(pmt_t dict); /* * ------------------------------------------------------------------------ * Any (wraps boost::any -- can be used to wrap pretty much anything) * * Cannot be serialized or used across process boundaries. * See http://www.boost.org/doc/html/any.html * ------------------------------------------------------------------------ */ //! Return true if \p obj is an any PMT_API bool is_any(pmt_t obj); //! make an any PMT_API pmt_t make_any(const boost::any &any); //! Return underlying boost::any PMT_API boost::any any_ref(pmt_t obj); //! Store \p any in \p obj PMT_API void any_set(pmt_t obj, const boost::any &any); /* * ------------------------------------------------------------------------ * msg_accepter -- pmt representation of pmt::msg_accepter * ------------------------------------------------------------------------ */ //! Return true if \p obj is a msg_accepter PMT_API bool is_msg_accepter(const pmt_t &obj); //! make a msg_accepter PMT_API pmt_t make_msg_accepter(boost::shared_ptr ma); //! Return underlying msg_accepter PMT_API boost::shared_ptr msg_accepter_ref(const pmt_t &obj); /* * ------------------------------------------------------------------------ * General functions * ------------------------------------------------------------------------ */ //! Return true if x and y are the same object; otherwise return false. PMT_API bool eq(const pmt_t& x, const pmt_t& y); /*! * \brief Return true if x and y should normally be regarded as the same object, else false. * *
 * eqv returns true if:
 *   x and y are the same object.
 *   x and y are both \#t or both \#f.
 *   x and y are both symbols and their names are the same.
 *   x and y are both numbers, and are numerically equal.
 *   x and y are both the empty list (nil).
 *   x and y are pairs or vectors that denote same location in store.
 * 
*/ PMT_API bool eqv(const pmt_t& x, const pmt_t& y); /*! * pmt::equal recursively compares the contents of pairs and vectors, * applying pmt::eqv on other objects such as numbers and symbols. * pmt::equal may fail to terminate if its arguments are circular data * structures. */ PMT_API bool equal(const pmt_t& x, const pmt_t& y); //! Return the number of elements in v PMT_API size_t length(const pmt_t& v); /*! * \brief Find the first pair in \p alist whose car field is \p obj * and return that pair. * * \p alist (for "association list") must be a list of pairs. If no pair * in \p alist has \p obj as its car then \#f is returned. * Uses pmt::eq to compare \p obj with car fields of the pairs in \p alist. */ PMT_API pmt_t assq(pmt_t obj, pmt_t alist); /*! * \brief Find the first pair in \p alist whose car field is \p obj * and return that pair. * * \p alist (for "association list") must be a list of pairs. If no pair * in \p alist has \p obj as its car then \#f is returned. * Uses pmt::eqv to compare \p obj with car fields of the pairs in \p alist. */ PMT_API pmt_t assv(pmt_t obj, pmt_t alist); /*! * \brief Find the first pair in \p alist whose car field is \p obj * and return that pair. * * \p alist (for "association list") must be a list of pairs. If no pair * in \p alist has \p obj as its car then \#f is returned. * Uses pmt::equal to compare \p obj with car fields of the pairs in \p alist. */ PMT_API pmt_t assoc(pmt_t obj, pmt_t alist); /*! * \brief Apply \p proc element-wise to the elements of list and returns * a list of the results, in order. * * \p list must be a list. The dynamic order in which \p proc is * applied to the elements of \p list is unspecified. */ PMT_API pmt_t map(pmt_t proc(const pmt_t&), pmt_t list); /*! * \brief reverse \p list. * * \p list must be a proper list. */ PMT_API pmt_t reverse(pmt_t list); /*! * \brief destructively reverse \p list. * * \p list must be a proper list. */ PMT_API pmt_t reverse_x(pmt_t list); /*! * \brief (acons x y a) == (cons (cons x y) a) */ inline static pmt_t acons(pmt_t x, pmt_t y, pmt_t a) { return cons(cons(x, y), a); } /*! * \brief locates \p nth element of \n list where the car is the 'zeroth' element. */ PMT_API pmt_t nth(size_t n, pmt_t list); /*! * \brief returns the tail of \p list that would be obtained by calling * cdr \p n times in succession. */ PMT_API pmt_t nthcdr(size_t n, pmt_t list); /*! * \brief Return the first sublist of \p list whose car is \p obj. * If \p obj does not occur in \p list, then \#f is returned. * pmt::memq use pmt::eq to compare \p obj with the elements of \p list. */ PMT_API pmt_t memq(pmt_t obj, pmt_t list); /*! * \brief Return the first sublist of \p list whose car is \p obj. * If \p obj does not occur in \p list, then \#f is returned. * pmt::memv use pmt::eqv to compare \p obj with the elements of \p list. */ PMT_API pmt_t memv(pmt_t obj, pmt_t list); /*! * \brief Return the first sublist of \p list whose car is \p obj. * If \p obj does not occur in \p list, then \#f is returned. * pmt::member use pmt::equal to compare \p obj with the elements of \p list. */ PMT_API pmt_t member(pmt_t obj, pmt_t list); /*! * \brief Return true if every element of \p list1 appears in \p list2, and false otherwise. * Comparisons are done with pmt::eqv. */ PMT_API bool subsetp(pmt_t list1, pmt_t list2); /*! * \brief Return a list of length 1 containing \p x1 */ PMT_API pmt_t list1(const pmt_t& x1); /*! * \brief Return a list of length 2 containing \p x1, \p x2 */ PMT_API pmt_t list2(const pmt_t& x1, const pmt_t& x2); /*! * \brief Return a list of length 3 containing \p x1, \p x2, \p x3 */ PMT_API pmt_t list3(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3); /*! * \brief Return a list of length 4 containing \p x1, \p x2, \p x3, \p x4 */ PMT_API pmt_t list4(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4); /*! * \brief Return a list of length 5 containing \p x1, \p x2, \p x3, \p x4, \p x5 */ PMT_API pmt_t list5(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4, const pmt_t& x5); /*! * \brief Return a list of length 6 containing \p x1, \p x2, \p x3, \p x4, \p * x5, \p x6 */ PMT_API pmt_t list6(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4, const pmt_t& x5, const pmt_t& x6); /*! * \brief Return \p list with \p item added to it. */ PMT_API pmt_t list_add(pmt_t list, const pmt_t& item); /*! * \brief Return \p list with \p item removed from it. */ PMT_API pmt_t list_rm(pmt_t list, const pmt_t& item); /*! * \brief Return bool of \p list contains \p item */ PMT_API bool list_has(pmt_t list, const pmt_t& item); /* * ------------------------------------------------------------------------ * read / write * ------------------------------------------------------------------------ */ extern PMT_API const pmt_t PMT_EOF; //< The end of file object //! return true if obj is the EOF object, otherwise return false. PMT_API bool is_eof_object(pmt_t obj); /*! * read converts external representations of pmt objects into the * objects themselves. Read returns the next object parsable from * the given input port, updating port to point to the first * character past the end of the external representation of the * object. * * If an end of file is encountered in the input before any * characters are found that can begin an object, then an end of file * object is returned. The port remains open, and further attempts * to read will also return an end of file object. If an end of file * is encountered after the beginning of an object's external * representation, but the external representation is incomplete and * therefore not parsable, an error is signaled. */ PMT_API pmt_t read(std::istream &port); /*! * Write a written representation of \p obj to the given \p port. */ PMT_API void write(pmt_t obj, std::ostream &port); /*! * Return a string representation of \p obj. * This is the same output as would be generated by pmt::write. */ PMT_API std::string write_string(pmt_t obj); PMT_API std::ostream& operator<<(std::ostream &os, pmt_t obj); /*! * \brief Write pmt string representation to stdout. */ PMT_API void print(pmt_t v); /* * ------------------------------------------------------------------------ * portable byte stream representation * ------------------------------------------------------------------------ */ /*! * \brief Write portable byte-serial representation of \p obj to \p sink */ PMT_API bool serialize(pmt_t obj, std::streambuf &sink); /*! * \brief Create obj from portable byte-serial representation */ PMT_API pmt_t deserialize(std::streambuf &source); PMT_API void dump_sizeof(); // debugging /*! * \brief Provide a simple string generating interface to pmt's serialize function */ PMT_API std::string serialize_str(pmt_t obj); /*! * \brief Provide a simple string generating interface to pmt's deserialize function */ PMT_API pmt_t deserialize_str(std::string str); /*! * \brief Provide a comparator function object to allow pmt use in stl types */ class comparator { public: bool operator()(pmt::pmt_t const& p1, pmt::pmt_t const& p2) const { return pmt::eqv(p1,p2)?false:p1.get()>p2.get(); } }; // FIXME: Remove in 3.8. class comperator { public: bool operator()(pmt::pmt_t const& p1, pmt::pmt_t const& p2) const { return pmt::eqv(p1,p2)?false:p1.get()>p2.get(); } }; } /* namespace pmt */ #include #endif /* INCLUDED_PMT_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/pmt/CMakeLists.txt0000664000175000017500000000206212207440367023605 0ustar jcorganjcorgan# Copyright 2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install the headers ######################################################################## install(FILES api.h pmt.h pmt_pool.h pmt_sugar.h DESTINATION ${GR_INCLUDE_DIR}/pmt COMPONENT "runtime_devel") gnuradio-3.7.2.1/gnuradio-runtime/include/pmt/pmt_pool.h0000664000175000017500000000431412207440367023051 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_PMT_POOL_H #define INCLUDED_PMT_POOL_H #include #include #include #include namespace pmt { /*! * \brief very simple thread-safe fixed-size allocation pool * * FIXME may want to go to global allocation with per-thread free list. * This would eliminate virtually all lock contention. */ class PMT_API pmt_pool { struct PMT_API item { struct item *d_next; }; typedef boost::unique_lock scoped_lock; mutable boost::mutex d_mutex; boost::condition_variable d_cond; size_t d_itemsize; size_t d_alignment; size_t d_allocation_size; size_t d_max_items; size_t d_n_items; item *d_freelist; std::vector d_allocations; public: /*! * \param itemsize size in bytes of the items to be allocated. * \param alignment alignment in bytes of all objects to be allocated (must be power-of-2). * \param allocation_size number of bytes to allocate at a time from the underlying allocator. * \param max_items is the maximum number of items to allocate. If this number is exceeded, * the allocate blocks. 0 implies no limit. */ pmt_pool(size_t itemsize, size_t alignment = 16, size_t allocation_size = 4096, size_t max_items = 0); ~pmt_pool(); void *malloc(); void free(void *p); }; } /* namespace pmt */ #endif /* INCLUDED_PMT_POOL_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/pmt/pmt_sugar.h0000664000175000017500000001011412207440367023214 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_PMT_SUGAR_H #define INCLUDED_PMT_SUGAR_H /*! * This file is included by pmt.h and contains pseudo-constructor * shorthand for making pmt objects */ #include namespace pmt { //! Make pmt symbol static inline pmt_t mp(const std::string &s) { return string_to_symbol(s); } //! Make pmt symbol static inline pmt_t mp(const char *s) { return string_to_symbol(s); } //! Make pmt long static inline pmt_t mp(long x){ return from_long(x); } //! Make pmt long static inline pmt_t mp(long long unsigned x){ return from_long(x); } //! Make pmt long static inline pmt_t mp(int x){ return from_long(x); } //! Make pmt double static inline pmt_t mp(double x){ return from_double(x); } //! Make pmt complex static inline pmt_t mp(std::complex z) { return make_rectangular(z.real(), z.imag()); } //! Make pmt complex static inline pmt_t mp(std::complex z) { return make_rectangular(z.real(), z.imag()); } //! Make pmt msg_accepter static inline pmt_t mp(boost::shared_ptr ma) { return make_msg_accepter(ma); } //! Make pmt Binary Large Object (BLOB) static inline pmt_t mp(const void *data, size_t len_in_bytes) { return make_blob(data, len_in_bytes); } //! Make tuple static inline pmt_t mp(const pmt_t &e0) { return make_tuple(e0); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1) { return make_tuple(e0, e1); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2) { return make_tuple(e0, e1, e2); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3) { return make_tuple(e0, e1, e2, e3); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4) { return make_tuple(e0, e1, e2, e3, e4); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5) { return make_tuple(e0, e1, e2, e3, e4, e5); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6) { return make_tuple(e0, e1, e2, e3, e4, e5, e6); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7) { return make_tuple(e0, e1, e2, e3, e4, e5, e6, e7); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8) { return make_tuple(e0, e1, e2, e3, e4, e5, e6, e7, e8); } //! Make tuple static inline pmt_t mp(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8, const pmt_t &e9) { return make_tuple(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9); } } /* namespace pmt */ #endif /* INCLUDED_PMT_SUGAR_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/pmt/api.h0000664000175000017500000000202212207440367021763 0ustar jcorganjcorgan/* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PMT_API_H #define INCLUDED_PMT_API_H #include #ifdef gnuradio_pmt_EXPORTS # define PMT_API __GR_ATTR_EXPORT #else # define PMT_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_PMT_API_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/CMakeLists.txt0000664000175000017500000000147412207440367023013 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. add_subdirectory(pmt) add_subdirectory(gnuradio) gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/0000775000175000017500000000000012244272666022063 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/fxpt.h0000664000175000017500000000545012207440367023213 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FXPT_H #define INCLUDED_GR_FXPT_H #include #include namespace gr { /*! * \brief fixed point sine and cosine and friends. * \ingroup misc * * fixed pt radians * --------- -------- * -2**31 -pi * 0 0 * 2**31-1 pi - epsilon */ class GR_RUNTIME_API fxpt { static const int WORDBITS = 32; static const int NBITS = 10; static const float s_sine_table[1 << NBITS][2]; static const float PI; static const float TWO_TO_THE_31; public: static gr_int32 float_to_fixed(float x) { // Fold x into -PI to PI. int d = (int)floor(x/2/PI+0.5); x -= d*2*PI; // And convert to an integer. return (gr_int32) ((float) x * TWO_TO_THE_31 / PI); } static float fixed_to_float (gr_int32 x) { return x * (PI / TWO_TO_THE_31); } /*! * \brief Given a fixed point angle x, return float sine (x) */ static float sin(gr_int32 x) { gr_uint32 ux = x; int index = ux >> (WORDBITS - NBITS); return s_sine_table[index][0] * (ux >> 1) + s_sine_table[index][1]; } /* * \brief Given a fixed point angle x, return float cosine (x) */ static float cos (gr_int32 x) { gr_uint32 ux = x + 0x40000000; int index = ux >> (WORDBITS - NBITS); return s_sine_table[index][0] * (ux >> 1) + s_sine_table[index][1]; } /* * \brief Given a fixedpoint angle x, return float cos(x) and sin (x) */ static void sincos(gr_int32 x, float *s, float *c) { gr_uint32 ux = x; int sin_index = ux >> (WORDBITS - NBITS); *s = s_sine_table[sin_index][0] * (ux >> 1) + s_sine_table[sin_index][1]; ux = x + 0x40000000; int cos_index = ux >> (WORDBITS - NBITS); *c = s_sine_table[cos_index][0] * (ux >> 1) + s_sine_table[cos_index][1]; return; } }; } /* namespace gr */ #endif /* INCLUDED_GR_FXPT_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/ice_server_template.h0000664000175000017500000000740112207440367026251 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef ICE_SERVER_TEMPLATE_H #define ICE_SERVER_TEMPLATE_H #include #include #include template class ice_server_template : public ice_application_base { public: ice_server_template(TImplClass* _this, const std::string& contolPortName, const std::string& endpointName); ~ice_server_template(); protected: //virtual bool application_started(); TserverBase* i_impl(); friend class ice_application_base; private: //virtual int run_impl(int, char*[]); Ice::ObjectAdapterPtr d_adapter; TserverBase* d_iceserver; const std::string d_contolPortName, d_endpointName; }; template ice_server_template::ice_server_template (TImplClass* _this, const std::string& controlPortName, const std::string& endpointName) : ice_application_base(_this), d_iceserver(0), d_contolPortName(controlPortName), d_endpointName(endpointName) {;} template ice_server_template::~ice_server_template() { if(d_adapter) { d_adapter->deactivate(); delete(d_iceserver); d_adapter = 0; } } template TserverBase* ice_server_template::i_impl() { if(ice_application_base::d_this->reacquire_sync()) { d_adapter = (ice_application_base::d_this->have_ice_config()) ? ice_application_base::d_this->d_this->d_application->communicator()->createObjectAdapter(d_contolPortName) : ice_application_base::d_this->d_this->d_application->communicator()->createObjectAdapterWithEndpoints(d_contolPortName,"tcp -h *"); TserverClass* server_ice(new TserverClass()); TIceClass obj(server_ice); Ice::Identity id(ice_application_base::d_this->d_this->d_application->communicator()->stringToIdentity(d_endpointName)); d_adapter->add(obj, id); d_adapter->activate(); ice_application_base::d_this->set_endpoint(ice_application_common::communicator()->proxyToString(d_adapter->createDirectProxy(id))); std::cout << std::endl << "Ice Radio Endpoint: " << ice_server_template::endpoints()[0] << std::endl; d_iceserver = (TserverBase*) server_ice; ice_application_base::d_this->sync_reacquire(); } return d_iceserver; } #endif /* ICE_SERVER_TEMPLATE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/misc.h0000664000175000017500000000241712207440367023165 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MISC_H #define INCLUDED_GR_MISC_H #include #include GR_RUNTIME_API unsigned int gr_rounduppow2(unsigned int n); // FIXME should be template GR_RUNTIME_API void gr_zero_vector(std::vector &v); GR_RUNTIME_API void gr_zero_vector(std::vector &v); GR_RUNTIME_API void gr_zero_vector(std::vector &v); GR_RUNTIME_API void gr_zero_vector(std::vector &v); #endif /* INCLUDED_GR_MISC_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/CMakeLists.txt0000664000175000017500000000457012237515111024614 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. add_subdirectory(messages) add_subdirectory(thread) ######################################################################## # Install header files ######################################################################## install(FILES api.h attributes.h basic_block.h block.h block_detail.h block_gateway.h block_registry.h buffer.h constants.h endianness.h expj.h feval.h flowgraph.h fxpt.h fxpt_nco.h fxpt_vco.h gr_complex.h hier_block2.h high_res_timer.h io_signature.h math.h message.h misc.h msg_accepter.h msg_handler.h msg_queue.h nco.h prefs.h py_feval.h pycallback_object.h random.h realtime.h realtime_impl.h runtime_types.h tags.h tagged_stream_block.h top_block.h tpb_detail.h sincos.h sptr_magic.h sync_block.h sync_decimator.h sync_interpolator.h sys_paths.h tag_checker.h types.h sys_pri.h unittests.h ice_application_base.h IcePy_Communicator.h ice_server_template.h rpccallbackregister_base.h rpcmanager_base.h rpcmanager.h rpcpmtconverters_ice.h rpcregisterhelpers.h rpcserver_aggregator.h rpcserver_base.h rpcserver_booter_aggregator.h rpcserver_booter_base.h rpcserver_booter_ice.h rpcserver_ice.h rpcserver_selector.h ${CMAKE_CURRENT_BINARY_DIR}/logger.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio COMPONENT "runtime_devel" ) ########################################################################## # Configure logger ########################################################################## CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/logger.h.in ${CMAKE_CURRENT_BINARY_DIR}/logger.h ) gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sincos.h0000664000175000017500000000217012207440367023524 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SINCOS_H #define INCLUDED_GR_SINCOS_H #include namespace gr { // compute sine and cosine at the same time GR_RUNTIME_API void sincos (double x, double *sin, double *cos); GR_RUNTIME_API void sincosf (float x, float *sin, float *cos); } #endif /* INCLUDED_GR_SINCOS_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/unittests.h0000664000175000017500000000252112207440367024270 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include static std::string get_unittest_path(const std::string &filename){ boost::filesystem::path path = boost::filesystem::current_path() / ".unittests"; if (!boost::filesystem::is_directory(path)) boost::filesystem::create_directory(path); return (path / filename).string(); } gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/thread/0000775000175000017500000000000012207440367023324 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/thread/CMakeLists.txt0000664000175000017500000000210412207440367026061 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES thread.h thread_body_wrapper.h thread_group.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/thread COMPONENT "runtime_devel" ) gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/thread/thread.h0000664000175000017500000001325712207440367024754 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_THREAD_H #define INCLUDED_THREAD_H #include #include #include #include #include #include #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #endif namespace gr { namespace thread { typedef boost::thread thread; typedef boost::mutex mutex; typedef boost::unique_lock scoped_lock; typedef boost::condition_variable condition_variable; /*! \brief a system-dependent typedef for the underlying thread type. */ #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) typedef HANDLE gr_thread_t; #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) typedef pthread_t gr_thread_t; #else typedef pthread_t gr_thread_t; #endif /*! \brief Get the current thread's ID as a gr_thread_t * * We use this when setting the thread affinity or any other * low-level thread settings. Can be called withing a GNU Radio * block to get a reference to its current thread ID. */ GR_RUNTIME_API gr_thread_t get_current_thread_id(); /*! \brief Bind the current thread to a set of cores. * * Wrapper for system-dependent calls to set the affinity of the * current thread to the processor mask. The mask is simply a * 1-demensional vector containing the processor or core number * from 0 to N-1 for N cores. * * Note: this does not work on OSX; it is a nop call since OSX * does not support the concept of thread affinity (and what they * do support in this way since 10.5 is not what we want or can * use in this fashion). */ GR_RUNTIME_API void thread_bind_to_processor(const std::vector &mask); /*! \brief Convineince function to bind the current thread to a single core. * * Wrapper for system-dependent calls to set the affinity of the * current thread to a given core from 0 to N-1 for N cores. * * Note: this does not work on OSX; it is a nop call since OSX * does not support the concept of thread affinity (and what they * do support in this way since 10.5 is not what we want or can * use in this fashion). */ GR_RUNTIME_API void thread_bind_to_processor(int n); /*! \brief Bind a thread to a set of cores. * * Wrapper for system-dependent calls to set the affinity of the * given thread ID to the processor mask. The mask is simply a * 1-demensional vector containing the processor or core number * from 0 to N-1 for N cores. * * Note: this does not work on OSX; it is a nop call since OSX * does not support the concept of thread affinity (and what they * do support in this way since 10.5 is not what we want or can * use in this fashion). */ GR_RUNTIME_API void thread_bind_to_processor(gr_thread_t thread, const std::vector &mask); /*! \brief Convineince function to bind the a thread to a single core. * * Wrapper for system-dependent calls to set the affinity of the * given thread ID to a given core from 0 to N-1 for N cores. * * Note: this does not work on OSX; it is a nop call since OSX * does not support the concept of thread affinity (and what they * do support in this way since 10.5 is not what we want or can * use in this fashion). */ GR_RUNTIME_API void thread_bind_to_processor(gr_thread_t thread, unsigned int n); /*! \brief Remove any thread-processor affinity for the current thread. * * Note: this does not work on OSX; it is a nop call since OSX * does not support the concept of thread affinity (and what they * do support in this way since 10.5 is not what we want or can * use in this fashion). */ GR_RUNTIME_API void thread_unbind(); /*! \brief Remove any thread-processor affinity for a given thread ID. * * Note: this does not work on OSX; it is a nop call since OSX * does not support the concept of thread affinity (and what they * do support in this way since 10.5 is not what we want or can * use in this fashion). */ GR_RUNTIME_API void thread_unbind(gr_thread_t thread); /*! \brief get current thread priority for a given thread ID * * Note: this does not work on OSX */ GR_RUNTIME_API int thread_priority(gr_thread_t thread); /*! \brief get current thread priority for a given thread ID * * Note: this does not work on OSX */ GR_RUNTIME_API int set_thread_priority(gr_thread_t thread, int priority); } /* namespace thread */ } /* namespace gr */ #endif /* INCLUDED_THREAD_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/thread/thread_group.h0000664000175000017500000000230012207440367026153 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright (C) 2001-2003 William E. Kempf * Copyright (C) 2007 Anthony Williams * Copyright 2008,2009 Free Software Foundation, Inc. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /* * This was extracted from Boost 1.35.0 and fixed. */ #ifndef INCLUDED_THREAD_GROUP_H #define INCLUDED_THREAD_GROUP_H #include #include #include #include #include namespace gr { namespace thread { class GR_RUNTIME_API thread_group : public boost::noncopyable { public: thread_group(); ~thread_group(); boost::thread* create_thread(const boost::function0& threadfunc); void add_thread(boost::thread* thrd); void remove_thread(boost::thread* thrd); void join_all(); void interrupt_all(); size_t size() const; private: std::list m_threads; mutable boost::shared_mutex m_mutex; }; } /* namespace thread */ } /* namespace gr */ #endif /* INCLUDED_THREAD_GROUP_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/thread/thread_body_wrapper.h0000664000175000017500000000356512207440367027532 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_THREAD_BODY_WRAPPER_H #define INCLUDED_THREAD_BODY_WRAPPER_H #include #include #include #include namespace gr { namespace thread { GR_RUNTIME_API void mask_signals(); template class thread_body_wrapper { private: F d_f; std::string d_name; public: explicit thread_body_wrapper(F f, const std::string &name="") : d_f(f), d_name(name) {} void operator()() { mask_signals(); try { d_f(); } catch(boost::thread_interrupted const &) { } catch(std::exception const &e) { std::cerr << "thread[" << d_name << "]: " << e.what() << std::endl; } catch(...) { std::cerr << "thread[" << d_name << "]: " << "caught unrecognized exception\n"; } } }; } /* namespace thread */ } /* namespace gr */ #endif /* INCLUDED_THREAD_BODY_WRAPPER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_ice.h0000664000175000017500000001631412207440367025066 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_ICE_H #define RPCSERVER_ICE_H #include #include #include #include #include #include #include #include class rpcserver_ice : public virtual rpcserver_base, public GNURadio::ControlPort { public: rpcserver_ice(); virtual ~rpcserver_ice(); void registerConfigureCallback(const std::string &id, const configureCallback_t callback); void unregisterConfigureCallback(const std::string &id); void registerQueryCallback(const std::string &id, const queryCallback_t callback); void unregisterQueryCallback(const std::string &id); virtual void set(const GNURadio::KnobMap&, const Ice::Current&); GNURadio::KnobMap get(const GNURadio::KnobIDList&, const Ice::Current&); GNURadio::KnobMap getRe(const GNURadio::KnobIDList&, const Ice::Current&); GNURadio::KnobPropMap properties(const GNURadio::KnobIDList&, const Ice::Current&); virtual void shutdown(const Ice::Current&); private: typedef std::map ConfigureCallbackMap_t; ConfigureCallbackMap_t d_setcallbackmap; typedef std::map QueryCallbackMap_t; QueryCallbackMap_t d_getcallbackmap; template struct set_f : public std::unary_function { set_f(const Ice::Current& _c, TMap& _setcallbackmap, const priv_lvl_t& _cur_priv) : c(_c), d_setcallbackmap(_setcallbackmap), cur_priv(_cur_priv) {;} void operator()(const T& p) { ConfigureCallbackMap_t::const_iterator iter(d_setcallbackmap.find(p.first)); if(iter != d_setcallbackmap.end()) { if(cur_priv <= iter->second.priv) { (*iter->second.callback).post(pmt::PMT_NIL, rpcpmtconverter::to_pmt(p.second,c)); } else { std::cout << "Key " << p.first << " requires PRIVLVL <= " << iter->second.priv << " to set, currently at: " << cur_priv << std::endl; } } else { throw IceUtil::NullHandleException(__FILE__, __LINE__); } } const Ice::Current& c; TMap& d_setcallbackmap; const priv_lvl_t& cur_priv; }; template struct get_f : public std::unary_function { get_f(const Ice::Current& _c, TMap& _getcallbackmap, const priv_lvl_t& _cur_priv, GNURadio::KnobMap& _outknobs) : c(_c), d_getcallbackmap(_getcallbackmap), cur_priv(_cur_priv), outknobs(_outknobs) {} void operator()(const T& p) { QueryCallbackMap_t::const_iterator iter(d_getcallbackmap.find(p)); if(iter != d_getcallbackmap.end()) { if(cur_priv <= iter->second.priv) { outknobs[p] = rpcpmtconverter::from_pmt((*iter->second.callback).retrieve(), c); } else { std::cout << "Key " << iter->first << " requires PRIVLVL: <= " << iter->second.priv << " to get, currently at: " << cur_priv << std::endl; } } else { std::stringstream ss; ss << "Ctrlport Key called with unregistered key (" << p << ")\n"; std::cout << ss.str(); throw IceUtil::IllegalArgumentException(__FILE__,__LINE__,ss.str().c_str()); } } const Ice::Current& c; TMap& d_getcallbackmap; const priv_lvl_t& cur_priv; GNURadio::KnobMap& outknobs; }; template struct get_all_f : public std::unary_function { get_all_f(const Ice::Current& _c, TMap& _getcallbackmap, const priv_lvl_t& _cur_priv, TKnobMap& _outknobs) : c(_c), d_getcallbackmap(_getcallbackmap), cur_priv(_cur_priv), outknobs(_outknobs) {;} void operator()(const T& p) { if(cur_priv <= p.second.priv) { outknobs[p.first] = rpcpmtconverter::from_pmt(p.second.callback->retrieve(), c); } else { std::cout << "Key " << p.first << " requires PRIVLVL <= " << p.second.priv << " to get, currently at: " << cur_priv << std::endl; } } const Ice::Current& c; TMap& d_getcallbackmap; const priv_lvl_t& cur_priv; TKnobMap& outknobs; }; template struct properties_all_f : public std::unary_function { properties_all_f(const Ice::Current& _c, QueryCallbackMap_t& _getcallbackmap, const priv_lvl_t& _cur_priv, GNURadio::KnobPropMap& _outknobs) : c(_c), d_getcallbackmap(_getcallbackmap), cur_priv(_cur_priv), outknobs(_outknobs) {;} void operator()(const T& p) { if(cur_priv <= p.second.priv) { GNURadio::KnobProp prop;//(new GNURadio::KnobProp()); prop.type = GNURadio::KNOBDOUBLE; prop.units = p.second.units; prop.description = p.second.description; prop.min = rpcpmtconverter::from_pmt(p.second.min, c); prop.max = rpcpmtconverter::from_pmt(p.second.max, c); prop.display = static_cast(p.second.display); outknobs[p.first] = prop; } else { std::cout << "Key " << p.first << " requires PRIVLVL <= " << p.second.priv << " to get, currently at: " << cur_priv << std::endl; } } const Ice::Current& c; TMap& d_getcallbackmap; const priv_lvl_t& cur_priv; TKnobMap& outknobs; }; template struct properties_f : public std::unary_function { properties_f(const Ice::Current& _c, TMap& _getcallbackmap, const priv_lvl_t& _cur_priv, TKnobMap& _outknobs) : c(_c), d_getcallbackmap(_getcallbackmap), cur_priv(_cur_priv), outknobs(_outknobs) {;} void operator()(const T& p) { typename TMap::const_iterator iter(d_getcallbackmap.find(p)); if(iter != d_getcallbackmap.end()) { if(cur_priv <= iter->second.priv) { GNURadio::KnobProp prop; prop.type = GNURadio::KNOBDOUBLE; prop.units = iter->second.units; prop.description = iter->second.description; prop.min = rpcpmtconverter::from_pmt(iter->second.min, c); prop.max = rpcpmtconverter::from_pmt(iter->second.max, c); prop.display = static_cast(iter->second.display); //outknobs[iter->first] = prop; outknobs[p] = prop; } else { std::cout << "Key " << iter->first << " requires PRIVLVL: <= " << iter->second.priv << " to get, currently at: " << cur_priv << std::endl; } } else { throw IceUtil::NullHandleException(__FILE__, __LINE__); } } const Ice::Current& c; TMap& d_getcallbackmap; const priv_lvl_t& cur_priv; TKnobMap& outknobs; }; }; #endif /* RPCSERVER_ICE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/flowgraph.h0000664000175000017500000002040212207440367024215 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_FLOWGRAPH_H #define INCLUDED_GR_RUNTIME_FLOWGRAPH_H #include #include #include #include namespace gr { /*! * \brief Class representing a specific input or output graph endpoint * \ingroup internal */ class GR_RUNTIME_API endpoint { private: basic_block_sptr d_basic_block; int d_port; public: endpoint() : d_basic_block(), d_port(0) { } endpoint(basic_block_sptr block, int port) { d_basic_block = block; d_port = port; } basic_block_sptr block() const { return d_basic_block; } int port() const { return d_port; } bool operator==(const endpoint &other) const; }; inline bool endpoint::operator==(const endpoint &other) const { return (d_basic_block == other.d_basic_block && d_port == other.d_port); } class GR_RUNTIME_API msg_endpoint { private: basic_block_sptr d_basic_block; pmt::pmt_t d_port; bool d_is_hier; public: msg_endpoint() : d_basic_block(), d_port(pmt::PMT_NIL) { } msg_endpoint(basic_block_sptr block, pmt::pmt_t port, bool is_hier=false) { d_basic_block = block; d_port = port; d_is_hier = is_hier; } basic_block_sptr block() const { return d_basic_block; } pmt::pmt_t port() const { return d_port; } bool is_hier() const { return d_is_hier; } void set_hier(bool h) { d_is_hier = h; } bool operator==(const msg_endpoint &other) const; }; inline bool msg_endpoint::operator==(const msg_endpoint &other) const { return (d_basic_block == other.d_basic_block && pmt::equal(d_port, other.d_port)); } // Hold vectors of gr::endpoint objects typedef std::vector endpoint_vector_t; typedef std::vector::iterator endpoint_viter_t; /*! *\brief Class representing a connection between to graph endpoints */ class GR_RUNTIME_API edge { public: edge() : d_src(), d_dst() { }; edge(const endpoint &src, const endpoint &dst) : d_src(src), d_dst(dst) { } ~edge(); const endpoint &src() const { return d_src; } const endpoint &dst() const { return d_dst; } private: endpoint d_src; endpoint d_dst; }; // Hold vectors of gr::edge objects typedef std::vector edge_vector_t; typedef std::vector::iterator edge_viter_t; /*! *\brief Class representing a msg connection between to graph msg endpoints */ class GR_RUNTIME_API msg_edge { public: msg_edge() : d_src(), d_dst() { }; msg_edge(const msg_endpoint &src, const msg_endpoint &dst) : d_src(src), d_dst(dst) { } ~msg_edge() {} const msg_endpoint &src() const { return d_src; } const msg_endpoint &dst() const { return d_dst; } private: msg_endpoint d_src; msg_endpoint d_dst; }; // Hold vectors of gr::msg_edge objects typedef std::vector msg_edge_vector_t; typedef std::vector::iterator msg_edge_viter_t; // Create a shared pointer to a heap allocated flowgraph // (types defined in runtime_types.h) GR_RUNTIME_API flowgraph_sptr make_flowgraph(); /*! * \brief Class representing a directed, acyclic graph of basic blocks * \ingroup internal */ class GR_RUNTIME_API flowgraph { public: friend GR_RUNTIME_API flowgraph_sptr make_flowgraph(); // Destruct an arbitrary flowgraph ~flowgraph(); // Connect two endpoints void connect(const endpoint &src, const endpoint &dst); // Disconnect two endpoints void disconnect(const endpoint &src, const endpoint &dst); // Connect an output port to an input port (convenience) void connect(basic_block_sptr src_block, int src_port, basic_block_sptr dst_block, int dst_port); // Disconnect an input port from an output port (convenience) void disconnect(basic_block_sptr src_block, int src_port, basic_block_sptr dst_block, int dst_port); // Connect two msg endpoints void connect(const msg_endpoint &src, const msg_endpoint &dst); // Disconnect two msg endpoints void disconnect(const msg_endpoint &src, const msg_endpoint &dst); // Validate connectivity, raise exception if invalid void validate(); // Clear existing flowgraph void clear(); // Return vector of edges const edge_vector_t &edges() const { return d_edges; } // Return vector of msg edges const msg_edge_vector_t &msg_edges() const { return d_msg_edges; } // Return vector of connected blocks basic_block_vector_t calc_used_blocks(); // Return toplogically sorted vector of blocks. All the sources come first. basic_block_vector_t topological_sort(basic_block_vector_t &blocks); // Return vector of vectors of disjointly connected blocks, // topologically sorted. std::vector partition(); protected: basic_block_vector_t d_blocks; edge_vector_t d_edges; msg_edge_vector_t d_msg_edges; flowgraph(); std::vector calc_used_ports(basic_block_sptr block, bool check_inputs); basic_block_vector_t calc_downstream_blocks(basic_block_sptr block, int port); edge_vector_t calc_upstream_edges(basic_block_sptr block); bool has_block_p(basic_block_sptr block); edge calc_upstream_edge(basic_block_sptr block, int port); private: void check_valid_port(gr::io_signature::sptr sig, int port); void check_valid_port(const msg_endpoint &e); void check_dst_not_used(const endpoint &dst); void check_type_match(const endpoint &src, const endpoint &dst); edge_vector_t calc_connections(basic_block_sptr block, bool check_inputs); // false=use outputs void check_contiguity(basic_block_sptr block, const std::vector &used_ports, bool check_inputs); basic_block_vector_t calc_downstream_blocks(basic_block_sptr block); basic_block_vector_t calc_reachable_blocks(basic_block_sptr block, basic_block_vector_t &blocks); void reachable_dfs_visit(basic_block_sptr block, basic_block_vector_t &blocks); basic_block_vector_t calc_adjacent_blocks(basic_block_sptr block, basic_block_vector_t &blocks); basic_block_vector_t sort_sources_first(basic_block_vector_t &blocks); bool source_p(basic_block_sptr block); void topological_dfs_visit(basic_block_sptr block, basic_block_vector_t &output); }; // Convenience functions inline void flowgraph::connect(basic_block_sptr src_block, int src_port, basic_block_sptr dst_block, int dst_port) { connect(endpoint(src_block, src_port), endpoint(dst_block, dst_port)); } inline void flowgraph::disconnect(basic_block_sptr src_block, int src_port, basic_block_sptr dst_block, int dst_port) { disconnect(endpoint(src_block, src_port), endpoint(dst_block, dst_port)); } inline std::ostream& operator <<(std::ostream &os, const endpoint endp) { os << endp.block()->alias() << ":" << endp.port(); return os; } inline std::ostream& operator <<(std::ostream &os, const edge edge) { os << edge.src() << "->" << edge.dst(); return os; } inline std::ostream& operator <<(std::ostream &os, const msg_endpoint endp) { os << endp.block()->alias() << ":" << pmt::symbol_to_string(endp.port()); return os; } inline std::ostream& operator <<(std::ostream &os, const msg_edge edge) { os << edge.src() << "->" << edge.dst(); return os; } } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_FLOWGRAPH_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sys_pri.h0000664000175000017500000000254412207440367023723 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GNURADIO_SYS_PRI_H #define INCLUDED_GNURADIO_SYS_PRI_H #include #include /* * A single place to define real-time priorities used by the system itself */ namespace gr { struct GR_RUNTIME_API sys_pri { static rt_sched_param python(); // python code static rt_sched_param normal(); // normal blocks static rt_sched_param gcell_event_handler(); static rt_sched_param usrp2_backend(); // thread that services the ethernet }; } /* namespace gr */ #endif /* INCLUDED_GNURADIO_SYS_PRI_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcmanager_base.h0000664000175000017500000000241712207440367025343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCMANAGER_BASE_H #define RPCMANAGER_BASE_H #include class rpcserver_booter_base; //class rpcserver_booter_aggregator; class rpcmanager_base { public: typedef boost::shared_ptr rpcserver_booter_base_sptr; rpcmanager_base() {;} ~rpcmanager_base() {;} //static rpcserver_booter_base* get(); //static void register_booter(rpcserver_booter_base_sptr booter); private: }; #endif /* RPCMANAGER_BASE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/ice_application_base.h0000664000175000017500000001527012207440367026350 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef ICE_APPLICATION_BASE_H #define ICE_APPLICATION_BASE_H #ifdef HAVE_WINDOWS_H #include #include #endif #include #include #include #include #include #include #include #include #include #include namespace { static const unsigned int ICEAPPLICATION_ACTIVATION_TIMEOUT_MS(600); }; class GR_RUNTIME_API ice_application_common : public Ice::Application { public: template friend class ice_application_base; static boost::shared_ptr Instance(); ~ice_application_common() {;} static int d_reacquire_attributes; protected: static bool d_main_called; static bool d_have_ice_config; static std::string d_endpointStr; static boost::shared_ptr d_thread; ice_application_common() {;} int run(int, char*[]); }; template class ice_application_base { public: boost::shared_ptr d_application; ice_application_base(TserverClass* _this); ~ice_application_base() {;} static TserverBase* i(); static const std::vector endpoints(); protected: bool have_ice_config() { return d_application->d_have_ice_config; } void set_endpoint(const std::string& endpoint) { d_application->d_endpointStr = endpoint;} //this one is the key... overwrite in templated/inherited variants virtual TserverBase* i_impl() = 0; //tools for the i_impl... //tell it when it has to resync with the communicator virtual bool reacquire_sync(); virtual void sync_reacquire(); static TserverClass* d_this; int d_reacquire; //static int d_reacquire_attributes; private: void starticeexample(); bool application_started(); int run(int, char*[]); static void kickoff(); }; template TserverClass* ice_application_base::d_this(0); //template //int ice_application_base::d_reacquire_attributes(0); template ice_application_base::ice_application_base(TserverClass* _this) : d_reacquire(0) { //d_reacquire_attributes = 0; d_this = _this; d_application = ice_application_common::Instance(); } template void ice_application_base::starticeexample() { char* argv[2]; argv[0] = (char*)""; std::string conffile = gr::prefs::singleton()->get_string("ControlPort", "config", ""); if(conffile.size() > 0) { std::stringstream iceconf; ice_application_common::d_have_ice_config = true; ice_application_common::d_main_called = true; iceconf << conffile; d_application->main(0, argv, iceconf.str().c_str()); } else { ice_application_common::d_have_ice_config = false; ice_application_common::d_main_called = true; d_application->main(0, argv); } } template void ice_application_base::kickoff() { static bool run_once = false; //if(!d_this->application_started()) { if(!run_once) { ++d_this->d_application->d_reacquire_attributes; ice_application_common::d_thread = boost::shared_ptr (new boost::thread(boost::bind(&ice_application_base::starticeexample, d_this))); ::timespec timer_ts, rem_ts; timer_ts.tv_sec = 0; timer_ts.tv_nsec = ICEAPPLICATION_ACTIVATION_TIMEOUT_MS*1000; int iter = 0; while(!d_this->application_started()) { #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) ::Sleep(timer_ts.tv_nsec / 1000000); #else ::nanosleep(&timer_ts, &rem_ts); #endif if(!d_this->application_started()) std::cout << "@"; if(iter++ > 100) { std::cout << "ice_application_base::kickoff(), timeout waiting to get communicator() d_application->main() might have failed?!" << std::endl;; break; } } run_once = true; } return; } template bool ice_application_base::reacquire_sync() { return (d_this->d_reacquire != d_application->d_reacquire_attributes); } template void ice_application_base::sync_reacquire() { d_this->d_reacquire = d_application->d_reacquire_attributes; } template const std::vector ice_application_base::endpoints() { std::vector ep; ep.push_back(d_this->d_application->d_endpointStr); return ep; } template TserverBase* ice_application_base::i() { //printf("indacall\n"); assert(d_this != 0); if(!d_this->application_started()) { //printf("anotherkickoff\n"); kickoff(); } //printf("donekickedoff\n"); /*else if(!d_proxy) { d_proxy = d_this->i_impl(); assert(d_proxy != 0); }*/ return d_this->i_impl(); } /*template int ice_application_base::run(int argc, char* argv[]) { int implreturn(run_impl(argc, argv)); ice_application_base::communicator()->waitForShutdown(); return implreturn; }*/ template bool ice_application_base::application_started() { return ice_application_base::d_this->d_application->communicator(); } /*template int ice_application_base::run_impl(int argc, char* argv[]) { return EXIT_SUCCESS; } */ #endif gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcregisterhelpers.h0000664000175000017500000006111112207702530026133 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCREGISTERHELPERS_H #define RPCREGISTERHELPERS_H #include #include #include #include #include #include #include #include // Base classes template class rpcextractor_base : public virtual gr::messages::msg_accepter { public: rpcextractor_base(T* source, void (T::*func)(Tto)) : _source(source), _func(func) {;} ~rpcextractor_base() {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { throw std::runtime_error("rpcextractor_base: no post defined for this data type.\n"); } protected: T* _source; void (T::*_func)(Tto); }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(Tto)) : rpcextractor_base(source, func) {;} }; template class rpcinserter_base : public virtual gr::messages::msg_producer { public: rpcinserter_base(T* source, Tfrom (T::*func)()) : _source(source), _func(func) {;} rpcinserter_base() {;} pmt::pmt_t retrieve() { assert(0); return pmt::pmt_t(); } protected: T* _source; Tfrom (T::*_func)(); }; template class rpcbasic_inserter : public virtual rpcinserter_base { public: rpcbasic_inserter(T* source, Tfrom (T::*func)()const) : rpcinserter_base(source, func) {;} rpcbasic_inserter(T* source, Tfrom (T::*func)()) : rpcinserter_base(source, func) {;} pmt::pmt_t retrieve() { return pmt::mp((rpcinserter_base:: _source->*rpcinserter_base::_func)()); } }; // Specialized Extractor Templates template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(char)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (static_cast(pmt::to_long(msg))); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(short)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (static_cast(pmt::to_long(msg))); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(double)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (pmt::to_double(msg)); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(float)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (pmt::to_double(msg)); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(long)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (pmt::to_long(msg)); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(int)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (pmt::to_long(msg)); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(bool)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base::_source->*rpcextractor_base::_func) (pmt::to_bool(msg)); } }; template class rpcbasic_extractor > : public virtual rpcextractor_base > { public: rpcbasic_extractor(T* source, void (T::*func)(std::complex)) : rpcextractor_base >(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { std::complex k = static_cast >(pmt::to_complex(msg)); (rpcextractor_base >:: _source->*rpcextractor_base >::_func)(k); } }; template class rpcbasic_extractor > : public virtual rpcextractor_base > { public: rpcbasic_extractor(T* source, void (T::*func)(std::complex)) : rpcextractor_base >(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base >:: _source->*rpcextractor_base >::_func)(pmt::to_complex(msg)); } }; template class rpcbasic_extractor : public virtual rpcextractor_base { public: rpcbasic_extractor(T* source, void (T::*func)(std::string)) : rpcextractor_base(source, func) {;} void post(pmt::pmt_t which_port, pmt::pmt_t msg) { (rpcextractor_base:: _source->*rpcextractor_base::_func)(pmt::symbol_to_string(msg)); } }; template class rpcbasic_inserter : public virtual rpcinserter_base { public: rpcbasic_inserter(T* source, uint64_t (T::*func)() const) : rpcinserter_base(source, func) {;} rpcbasic_inserter(T* source, uint64_t (T::*func)()) : rpcinserter_base(source, func) {;} pmt::pmt_t retrieve() { return pmt::from_uint64((rpcinserter_base:: _source->*rpcinserter_base::_func)()); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::vector< signed char > (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::vector< signed char > (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::vector< signed char > vec((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::init_s8vector(vec.size(), &vec[0]); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::vector< short > (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::vector< short > (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::vector< short > vec((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::init_s16vector(vec.size(), &vec[0]); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::vector (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::vector (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::vector< int > vec((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::init_s32vector(vec.size(), &vec[0]); } }; template class rpcbasic_inserter > > : public virtual rpcinserter_base > > { public: rpcbasic_inserter(T* source, std::vector > (T::*func)() const) : rpcinserter_base > >(source, func) {;} rpcbasic_inserter(T* source, std::vector > (T::*func)()) : rpcinserter_base > >(source, func) {;} pmt::pmt_t retrieve() { std::vector< std::complex > vec((rpcinserter_base > >:: _source->*rpcinserter_base > >::_func)()); return pmt::init_c32vector(vec.size(), &vec[0]); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::vector (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::vector (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::vector< float > vec((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::init_f32vector(vec.size(), &vec[0]); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::vector (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::vector (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::vector< uint8_t > vec((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::init_u8vector(vec.size(), &vec[0]); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::complex (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::complex (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::complex k((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::from_complex(k); } }; template class rpcbasic_inserter > : public virtual rpcinserter_base > { public: rpcbasic_inserter(T* source, std::complex (T::*func)() const) : rpcinserter_base >(source, func) {;} rpcbasic_inserter(T* source, std::complex (T::*func)()) : rpcinserter_base >(source, func) {;} pmt::pmt_t retrieve() { std::complex k((rpcinserter_base >:: _source->*rpcinserter_base >::_func)()); return pmt::from_complex(k); } }; template struct rpc_register_base { rpc_register_base() {count++;} protected: static int count; }; // Base class to inherit from and create universal shared pointers. class rpcbasic_base { public: rpcbasic_base() {} virtual ~rpcbasic_base() {}; }; typedef boost::shared_ptr rpcbasic_sptr; template struct rpcbasic_register_set : public rpcbasic_base { // Function used to add a 'set' RPC call using a basic_block's alias. rpcbasic_register_set(const std::string& block_alias, const char* functionbase, void (T::*function)(Tto), const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_ = DISPNULL) { d_min = min; d_max = max; d_def = def; d_units = units_; d_desc = desc_; d_minpriv = minpriv_; d_display = display_; d_object = dynamic_cast(global_block_registry.block_lookup(pmt::intern(block_alias)).get()); #ifdef RPCSERVER_ENABLED callbackregister_base::configureCallback_t extractor(new rpcbasic_extractor(d_object, function), minpriv_, std::string(units_), display_, std::string(desc_), min, max, def); std::ostringstream oss(std::ostringstream::out); oss << block_alias << "::" << functionbase; d_id = oss.str(); //std::cerr << "REGISTERING SET: " << d_id << " " << desc_ << std::endl; rpcmanager::get()->i()->registerConfigureCallback(d_id, extractor); #endif } // Function used to add a 'set' RPC call using a name and the object rpcbasic_register_set(const std::string& name, const char* functionbase, T* obj, void (T::*function)(Tto), const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_ = DISPNULL) { d_min = min; d_max = max; d_def = def; d_units = units_; d_desc = desc_; d_minpriv = minpriv_; d_display = display_; d_object = obj; #ifdef RPCSERVER_ENABLED callbackregister_base::configureCallback_t extractor(new rpcbasic_extractor(d_object, function), minpriv_, std::string(units_), display_, std::string(desc_), min, max, def); std::ostringstream oss(std::ostringstream::out); oss << name << "::" << functionbase; d_id = oss.str(); //std::cerr << "REGISTERING SET: " << d_id << " " << desc_ << std::endl; rpcmanager::get()->i()->registerConfigureCallback(d_id, extractor); #endif } ~rpcbasic_register_set() { #ifdef RPCSERVER_ENABLED rpcmanager::get()->i()->unregisterConfigureCallback(d_id); #endif } pmt::pmt_t min() const { return d_min; } pmt::pmt_t max() const { return d_max; } pmt::pmt_t def() const { return d_def; } std::string units() const { return d_units; } std::string description() const { return d_desc; } priv_lvl_t privilege_level() const { return d_minpriv; } DisplayType default_display() const { return d_display; } void set_min(pmt::pmt_t p) { d_min = p; } void set_max(pmt::pmt_t p) { d_max = p; } void set_def(pmt::pmt_t p) { d_def = p; } void units(std::string u) { d_units = u; } void description(std::string d) { d_desc = d; } void privilege_level(priv_lvl_t p) { d_minpriv = p; } void default_display(DisplayType d) { d_display = d; } private: std::string d_id; pmt::pmt_t d_min, d_max, d_def; std::string d_units, d_desc; priv_lvl_t d_minpriv; DisplayType d_display; T *d_object; }; template class rpcbasic_register_get : public rpcbasic_base { public: // Function used to add a 'set' RPC call using a basic_block's alias. // primary constructor to allow for T get() functions rpcbasic_register_get(const std::string& block_alias, const char* functionbase, Tfrom (T::*function)(), const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_ = DISPNULL) { d_min = min; d_max = max; d_def = def; d_units = units_; d_desc = desc_; d_minpriv = minpriv_; d_display = display_; d_object = dynamic_cast(global_block_registry.block_lookup(pmt::intern(block_alias)).get()); #ifdef RPCSERVER_ENABLED callbackregister_base::queryCallback_t inserter(new rpcbasic_inserter(d_object, function), minpriv_, std::string(units_), display_, std::string(desc_), min, max, def); std::ostringstream oss(std::ostringstream::out); oss << block_alias << "::" << functionbase; d_id = oss.str(); //std::cerr << "REGISTERING GET: " << d_id << " " << desc_ << std::endl; rpcmanager::get()->i()->registerQueryCallback(d_id, inserter); #endif } // alternate constructor to allow for T get() const functions rpcbasic_register_get(const std::string& block_alias, const char* functionbase, Tfrom (T::*function)() const, const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_ = DISPNULL) { d_min = min; d_max = max; d_def = def; d_units = units_; d_desc = desc_; d_minpriv = minpriv_; d_display = display_; d_object = dynamic_cast(global_block_registry.block_lookup(pmt::intern(block_alias)).get()); #ifdef RPCSERVER_ENABLED callbackregister_base::queryCallback_t inserter(new rpcbasic_inserter(d_object, (Tfrom (T::*)())function), minpriv_, std::string(units_), display_, std::string(desc_), min, max, def); std::ostringstream oss(std::ostringstream::out); oss << block_alias << "::" << functionbase; d_id = oss.str(); //std::cerr << "REGISTERING GET CONST: " << d_id << " " << desc_ << " " << display_ << std::endl; rpcmanager::get()->i()->registerQueryCallback(d_id, inserter); #endif } // Function used to add a 'set' RPC call using a name and the object // primary constructor to allow for T get() functions rpcbasic_register_get(const std::string& name, const char* functionbase, T* obj, Tfrom (T::*function)(), const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_ = DISPNULL) { d_min = min; d_max = max; d_def = def; d_units = units_; d_desc = desc_; d_minpriv = minpriv_; d_display = display_; d_object = obj; #ifdef RPCSERVER_ENABLED callbackregister_base::queryCallback_t inserter(new rpcbasic_inserter(d_object, function), minpriv_, std::string(units_), display_, std::string(desc_), min, max, def); std::ostringstream oss(std::ostringstream::out); oss << name << "::" << functionbase; d_id = oss.str(); //std::cerr << "REGISTERING GET: " << d_id << " " << desc_ << std::endl; rpcmanager::get()->i()->registerQueryCallback(d_id, inserter); #endif } // alternate constructor to allow for T get() const functions rpcbasic_register_get(const std::string& name, const char* functionbase, T* obj, Tfrom (T::*function)() const, const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_ = DISPNULL) { d_min = min; d_max = max; d_def = def; d_units = units_; d_desc = desc_; d_minpriv = minpriv_; d_display = display_; d_object = obj; #ifdef RPCSERVER_ENABLED callbackregister_base::queryCallback_t inserter(new rpcbasic_inserter(d_object, (Tfrom (T::*)())function), minpriv_, std::string(units_), display_, std::string(desc_), min, max, def); std::ostringstream oss(std::ostringstream::out); oss << name << "::" << functionbase; d_id = oss.str(); //std::cerr << "REGISTERING GET CONST: " << d_id << " " << desc_ << " " << display_ << std::endl; rpcmanager::get()->i()->registerQueryCallback(d_id, inserter); #endif } ~rpcbasic_register_get() { #ifdef RPCSERVER_ENABLED rpcmanager::get()->i()->unregisterQueryCallback(d_id); #endif } pmt::pmt_t min() const { return d_min; } pmt::pmt_t max() const { return d_max; } pmt::pmt_t def() const { return d_def; } std::string units() const { return d_units; } std::string description() const { return d_desc; } priv_lvl_t privilege_level() const { return d_minpriv; } DisplayType default_display() const { return d_display; } void set_min(pmt::pmt_t p) { d_min = p; } void set_max(pmt::pmt_t p) { d_max = p; } void set_def(pmt::pmt_t p) { d_def = p; } void units(std::string u) { d_units = u; } void description(std::string d) { d_desc = d; } void privilege_level(priv_lvl_t p) { d_minpriv = p; } void default_display(DisplayType d) { d_display = d; } private: std::string d_id; pmt::pmt_t d_min, d_max, d_def; std::string d_units, d_desc; priv_lvl_t d_minpriv; DisplayType d_display; T *d_object; }; /* * This class can wrap a pre-existing variable type for you * it will define the getter and rpcregister call for you. * * It should be used for read-only getters. * */ template class rpcbasic_register_variable : public rpcbasic_base { protected: rpcbasic_register_get< rpcbasic_register_variable, Tfrom > d_rpc_reg; Tfrom *d_variable; Tfrom get() { return *d_variable; } public: // empty constructor which should never be called but needs to exist for ues in varous STL data structures void setptr(Tfrom* _variable){ rpcbasic_register_variable::d_variable = _variable; } rpcbasic_register_variable() : d_rpc_reg("FAIL", "FAIL", this, &rpcbasic_register_variable::get, pmt::PMT_NIL, pmt::PMT_NIL, pmt::PMT_NIL, DISPNULL, "FAIL", "FAIL", RPC_PRIVLVL_MIN), d_variable(NULL) { throw std::runtime_error("ERROR: rpcbasic_register_variable called with no args. If this happens, someone has tried to use rpcbasic_register_variable incorrectly."); }; rpcbasic_register_variable(const std::string& namebase, const char* functionbase, Tfrom *variable, const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv_ = RPC_PRIVLVL_MIN, DisplayType display_=DISPNULL) : d_rpc_reg(namebase, functionbase, this, &rpcbasic_register_variable::get, min, max, def, units_, desc_, minpriv_, display_), d_variable(variable) { //std::cerr << "REGISTERING VAR: " << " " << desc_ << std::endl; } }; template class rpcbasic_register_variable_rw : public rpcbasic_register_variable { private: rpcbasic_register_set< rpcbasic_register_variable_rw, Tfrom > d_rpc_regset; public: // empty constructor which should never be called but needs to exist for ues in varous STL data structures rpcbasic_register_variable_rw() : d_rpc_regset("FAIL","FAIL",this,&rpcbasic_register_variable::get,pmt::PMT_NIL,pmt::PMT_NIL,pmt::PMT_NIL,DISPNULL,"FAIL","FAIL",RPC_PRIVLVL_MIN) { throw std::runtime_error("ERROR: rpcbasic_register_variable_rw called with no args. if this happens someone used rpcbasic_register_variable_rw incorrectly.\n"); }; void set(Tfrom _variable){ *(rpcbasic_register_variable::d_variable) = _variable; } rpcbasic_register_variable_rw( const std::string& namebase, const char* functionbase, Tfrom *variable, const pmt::pmt_t &min, const pmt::pmt_t &max, const pmt::pmt_t &def, const char* units_ = "", const char* desc_ = "", priv_lvl_t minpriv = RPC_PRIVLVL_MIN, DisplayType display_=DISPNULL) : rpcbasic_register_variable(namebase,functionbase,variable,min,max,def,units_,desc_), d_rpc_regset(namebase,functionbase,this,&rpcbasic_register_variable_rw::set,min,max,def,units_,desc_,minpriv,display_) { // no action } }; #endif gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/runtime_types.h0000664000175000017500000000346612207440367025146 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_TYPES_H #define INCLUDED_GR_RUNTIME_TYPES_H #include #include namespace gr { /* * typedefs for smart pointers we use throughout the runtime system */ class basic_block; class block; class block_detail; class buffer; class buffer_reader; class hier_block2; class flat_flowgraph; class flowgraph; class top_block; typedef boost::shared_ptr basic_block_sptr; typedef boost::shared_ptr block_sptr; typedef boost::shared_ptr block_detail_sptr; typedef boost::shared_ptr buffer_sptr; typedef boost::shared_ptr buffer_reader_sptr; typedef boost::shared_ptr hier_block2_sptr; typedef boost::shared_ptr flat_flowgraph_sptr; typedef boost::shared_ptr flowgraph_sptr; typedef boost::shared_ptr top_block_sptr; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_TYPES_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/buffer.h0000664000175000017500000002456012237515111023477 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_BUFFER_H #define INCLUDED_GR_RUNTIME_BUFFER_H #include #include #include #include #include #include namespace gr { class vmcircbuf; /*! * \brief Allocate a buffer that holds at least \p nitems of size \p sizeof_item. * * The total size of the buffer will be rounded up to a system * dependent boundary. This is typically the system page size, but * under MS windows is 64KB. * * \param nitems is the minimum number of items the buffer will hold. * \param sizeof_item is the size of an item in bytes. * \param link is the block that writes to this buffer. */ GR_RUNTIME_API buffer_sptr make_buffer(int nitems, size_t sizeof_item, block_sptr link=block_sptr()); /*! * \brief Single writer, multiple reader fifo. * \ingroup internal */ class GR_RUNTIME_API buffer { public: virtual ~buffer(); /*! * \brief return number of items worth of space available for writing */ int space_available(); /*! * \brief return size of this buffer in items */ int bufsize() const { return d_bufsize; } /*! * \brief return pointer to write buffer. * * The return value points at space that can hold at least * space_available() items. */ void *write_pointer(); /*! * \brief tell buffer that we wrote \p nitems into it */ void update_write_pointer(int nitems); void set_done(bool done); bool done() const { return d_done; } /*! * \brief Return the block that writes to this buffer. */ block_sptr link() { return block_sptr(d_link); } size_t nreaders() const { return d_readers.size(); } buffer_reader* reader(size_t index) { return d_readers[index]; } gr::thread::mutex *mutex() { return &d_mutex; } uint64_t nitems_written() { return d_abs_write_offset; } size_t get_sizeof_item() { return d_sizeof_item; } /*! * \brief Adds a new tag to the buffer. * * \param tag the new tag */ void add_item_tag(const tag_t &tag); /*! * \brief Removes an existing tag from the buffer. * * If no such tag is found, does nothing. * Note: Doesn't actually physically delete the tag, but * marks it as deleted. For the user, this has the same effect: * Any subsequent calls to get_tags_in_range() will not return * the tag. * * \param tag the tag that needs to be removed * \param id the unique ID of the block calling this function */ void remove_item_tag(const tag_t &tag, long id); /*! * \brief Removes all tags before \p max_time from buffer * * \param max_time the time (item number) to trim up until. */ void prune_tags(uint64_t max_time); std::deque::iterator get_tags_begin() { return d_item_tags.begin(); } std::deque::iterator get_tags_end() { return d_item_tags.end(); } // ------------------------------------------------------------------------- private: friend class buffer_reader; friend GR_RUNTIME_API buffer_sptr make_buffer(int nitems, size_t sizeof_item, block_sptr link); friend GR_RUNTIME_API buffer_reader_sptr buffer_add_reader (buffer_sptr buf, int nzero_preload, block_sptr link, int delay); protected: char *d_base; // base address of buffer unsigned int d_bufsize; // in items // Keep track of maximum sample delay of any reader; Only prune tags past this. unsigned d_max_reader_delay; private: gr::vmcircbuf *d_vmcircbuf; size_t d_sizeof_item; // in bytes std::vector d_readers; boost::weak_ptr d_link; // block that writes to this buffer // // The mutex protects d_write_index, d_abs_write_offset, d_done, d_item_tags // and the d_read_index's and d_abs_read_offset's in the buffer readers. // gr::thread::mutex d_mutex; unsigned int d_write_index; // in items [0,d_bufsize) uint64_t d_abs_write_offset; // num items written since the start bool d_done; std::deque d_item_tags; uint64_t d_last_min_items_read; unsigned index_add(unsigned a, unsigned b) { unsigned s = a + b; if(s >= d_bufsize) s -= d_bufsize; assert(s < d_bufsize); return s; } unsigned index_sub(unsigned a, unsigned b) { int s = a - b; if(s < 0) s += d_bufsize; assert((unsigned) s < d_bufsize); return s; } virtual bool allocate_buffer(int nitems, size_t sizeof_item); /*! * \brief constructor is private. Use gr_make_buffer to create instances. * * Allocate a buffer that holds at least \p nitems of size \p sizeof_item. * * \param nitems is the minimum number of items the buffer will hold. * \param sizeof_item is the size of an item in bytes. * \param link is the block that writes to this buffer. * * The total size of the buffer will be rounded up to a system * dependent boundary. This is typically the system page size, but * under MS windows is 64KB. */ buffer(int nitems, size_t sizeof_item, block_sptr link); /*! * \brief disassociate \p reader from this buffer */ void drop_reader(buffer_reader *reader); }; /*! * \brief Create a new gr::buffer_reader and attach it to buffer \p buf * \param buf is the buffer the \p gr::buffer_reader reads from. * \param nzero_preload -- number of zero items to "preload" into buffer. * \param link is the block that reads from the buffer using this gr::buffer_reader. * \param delay Optional setting to declare the buffer's sample delay. */ GR_RUNTIME_API buffer_reader_sptr buffer_add_reader(buffer_sptr buf, int nzero_preload, block_sptr link=block_sptr(), int delay=0); //! returns # of buffers currently allocated GR_RUNTIME_API long buffer_ncurrently_allocated(); // --------------------------------------------------------------------------- /*! * \brief How we keep track of the readers of a gr::buffer. * \ingroup internal */ class GR_RUNTIME_API buffer_reader { public: ~buffer_reader(); /*! * Declares the sample delay for this reader. * * See gr::block::declare_sample_delay for details. * * \param delay The new sample delay */ void declare_sample_delay(unsigned delay); /*! * Gets the sample delay for this reader. * * See gr::block::sample_delay for details. */ unsigned sample_delay() const; /*! * \brief Return number of items available for reading. */ int items_available() const; /*! * \brief Return buffer this reader reads from. */ buffer_sptr buffer() const { return d_buffer; } /*! * \brief Return maximum number of items that could ever be available for reading. * This is used as a sanity check in the scheduler to avoid looping forever. */ int max_possible_items_available() const { return d_buffer->d_bufsize - 1; } /*! * \brief return pointer to read buffer. * * The return value points to items_available() number of items */ const void *read_pointer(); /* * \brief tell buffer we read \p items from it */ void update_read_pointer(int nitems); void set_done(bool done) { d_buffer->set_done(done); } bool done() const { return d_buffer->done(); } gr::thread::mutex *mutex() { return d_buffer->mutex(); } uint64_t nitems_read() { return d_abs_read_offset; } size_t get_sizeof_item() { return d_buffer->get_sizeof_item(); } /*! * \brief Return the block that reads via this reader. * */ block_sptr link() { return block_sptr(d_link); } /*! * \brief Given a [start,end), returns a vector all tags in the range. * * Get a vector of tags in given range. Range of counts is from start to end-1. * * Tags are tuples of: * (item count, source id, key, value) * * \param v a vector reference to return tags into * \param abs_start a uint64 count of the start of the range of interest * \param abs_end a uint64 count of the end of the range of interest * \param id the unique ID of the block to make sure already deleted tags are not returned */ void get_tags_in_range(std::vector &v, uint64_t abs_start, uint64_t abs_end, long id); // ------------------------------------------------------------------------- private: friend class buffer; friend GR_RUNTIME_API buffer_reader_sptr buffer_add_reader(buffer_sptr buf, int nzero_preload, block_sptr link, int delay); buffer_sptr d_buffer; unsigned int d_read_index; // in items [0,d->buffer.d_bufsize) uint64_t d_abs_read_offset; // num items seen since the start boost::weak_ptr d_link; // block that reads via this buffer reader unsigned d_attr_delay; // sample delay attribute for tag propagation //! constructor is private. Use gr::buffer::add_reader to create instances buffer_reader(buffer_sptr buffer, unsigned int read_index, block_sptr link); }; //! returns # of buffer_readers currently allocated GR_RUNTIME_API long buffer_reader_ncurrently_allocated (); } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_BUFFER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/tagged_stream_block.h0000664000175000017500000001277112207440367026216 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_TAGGED_STREAM_BLOCK_H #define INCLUDED_GR_RUNTIME_TAGGED_STREAM_BLOCK_H #include #include namespace gr { /*! * \brief Block that operates on PDUs in form of tagged streams * \ingroup base_blk * * Override work to provide the signal processing implementation. */ class GR_RUNTIME_API tagged_stream_block : public block { private: pmt::pmt_t d_length_tag_key; //!< This is the key for the tag that stores the PDU length gr_vector_int d_n_input_items_reqd; //!< How many input items do I need to process the next PDU? protected: std::string d_length_tag_key_str; tagged_stream_block(void) {} // allows pure virtual interface sub-classes tagged_stream_block(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature, const std::string &length_tag_key); /*! * \brief Parse all tags on the first sample of a PDU, return the * number of items per input and prune the length tags. * * In most cases, you don't need to override this, unless the * number of items read is not directly coded in one single tag. * * Default behaviour: * - Go through all input ports * - On every input port, search for the tag with the key specified in \p length_tag_key * - Copy that value as an int to the corresponding position in \p n_input_items_reqd * - Remove the length tag. * * \param[in] tags All the tags found on the first item of every input port. * \param[out] n_input_items_reqd Number of items which will be read from every input */ virtual void parse_length_tags(const std::vector > &tags, gr_vector_int &n_input_items_reqd); /*! * \brief Calculate the number of output items. * * This is basically the inverse function to forecast(): Given a * number of input items, it returns the maximum number of output * items. * * You most likely need to override this function, unless your * block is a sync block or integer interpolator/decimator. */ virtual int calculate_output_stream_length(const gr_vector_int &ninput_items); /*! * \brief Set the new length tags on the output stream * * Default behaviour: Set a tag with key \p length_tag_key and the * number of produced items on every output port. * * For anything else, override this. * * \param n_produced Length of the new PDU * \param n_ports Number of output ports */ virtual void update_length_tags(int n_produced, int n_ports); public: /*! \brief Don't override this. */ void /* final */ forecast (int noutput_items, gr_vector_int &ninput_items_required); /*! * - Reads the number of input items from the tags using parse_length_tags() * - Checks there's enough data on the input and output buffers * - If not, inform the scheduler and do nothing * - Calls work() with the exact number of items per PDU * - Updates the tags using update_length_tags() */ int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); /*! * \brief Just like gr::block::general_work, but makes sure the input is valid * * The user must override work to define the signal processing * code. Check the documentation for general_work() to see what * happens here. * * Like gr::sync_block, this calls consume() for you (it consumes * ninput_items[i] items from the i-th port). * * A note on tag propagation: The PDU length tags are handled by * other functions, but all other tags are handled just as in any * other \p gr::block. So, most likely, you either set the tag * propagation policy to TPP_DONT and handle the tag propagation * manually, or you propagate tags through the scheduler and don't * do anything here. * * \param noutput_items The size of the writable output buffer * \param ninput_items The exact size of the items on every input for this particular PDU. * These will be consumed if a length tag key is provided! * \param input_items See gr::block * \param output_items See gr::block */ virtual int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) = 0; }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_TAGGED_STREAM_BLOCK_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/nco.h0000664000175000017500000001153012207440367023005 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _GR_NCO_H_ #define _GR_NCO_H_ #include #include #include #include namespace gr { /*! * \brief base class template for Numerically Controlled Oscillator (NCO) * \ingroup misc */ template class nco { public: nco() : phase(0), phase_inc(0) {} virtual ~nco() {} // radians void set_phase(double angle) { phase = angle; } void adjust_phase(double delta_phase) { phase += delta_phase; } // angle_rate is in radians / step void set_freq(double angle_rate) { phase_inc = angle_rate; } // angle_rate is a delta in radians / step void adjust_freq(double delta_angle_rate) { phase_inc += delta_angle_rate; } // increment current phase angle void step() { phase += phase_inc; if(fabs(phase) > M_PI) { while(phase > M_PI) phase -= 2*M_PI; while(phase < -M_PI) phase += 2*M_PI; } } void step(int n) { phase += phase_inc * n; if(fabs(phase) > M_PI){ while(phase > M_PI) phase -= 2*M_PI; while(phase < -M_PI) phase += 2*M_PI; } } // units are radians / step double get_phase() const { return phase; } double get_freq() const { return phase_inc; } // compute sin and cos for current phase angle void sincos(float *sinx, float *cosx) const; // compute cos or sin for current phase angle float cos() const { return std::cos(phase); } float sin() const { return std::sin(phase); } // compute a block at a time void sin(float *output, int noutput_items, double ampl = 1.0); void cos(float *output, int noutput_items, double ampl = 1.0); void sincos(gr_complex *output, int noutput_items, double ampl = 1.0); void sin(short *output, int noutput_items, double ampl = 1.0); void cos(short *output, int noutput_items, double ampl = 1.0); void sin(int *output, int noutput_items, double ampl = 1.0); void cos(int *output, int noutput_items, double ampl = 1.0); protected: double phase; double phase_inc; }; template void nco::sincos(float *sinx, float *cosx) const { gr::sincosf(phase, sinx, cosx); } template void nco::sin(float *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = (float)(sin () * ampl); step(); } } template void nco::cos(float *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = (float)(cos() * ampl); step(); } } template void nco::sin(short *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = (short)(sin() * ampl); step(); } } template void nco::cos(short *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = (short)(cos() * ampl); step(); } } template void nco::sin(int *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = (int)(sin() * ampl); step(); } } template void nco::cos(int *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = (int)(cos() * ampl); step(); } } template void nco::sincos(gr_complex *output, int noutput_items, double ampl) { for(int i = 0; i < noutput_items; i++) { float cosx, sinx; nco::sincos(&sinx, &cosx); output[i] = gr_complex(cosx * ampl, sinx * ampl); step(); } } } /* namespace gr */ #endif /* _NCO_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/prefs.h0000664000175000017500000001124512207440367023350 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PREFS_H #define INCLUDED_GR_PREFS_H #include #include #include #include namespace gr { typedef std::map< std::string, std::map > config_map_t; typedef std::map< std::string, std::map >::iterator config_map_itr; typedef std::map config_map_elem_t; typedef std::map::iterator config_map_elem_itr; /*! * \brief Base class for representing user preferences a la windows INI files. * \ingroup misc * * The real implementation is in Python, and is accessable from C++ * via the magic of SWIG directors. */ class GR_RUNTIME_API prefs { public: static prefs *singleton(); static void set_singleton(prefs *p); prefs(); virtual ~prefs(); /*! * \brief Returns the configuration options as a string. */ std::string to_string(); /*! * \brief Saves the configuration settings to * ${HOME}/.gnuradio/config.conf. * * WARNING: this will overwrite your current config.conf file. */ void save(); /*! * \brief Does \p section exist? */ virtual bool has_section(const std::string §ion); /*! * \brief Does \p option exist? */ virtual bool has_option(const std::string §ion, const std::string &option); /*! * \brief If option exists return associated value; else * default_val. */ virtual const std::string get_string(const std::string §ion, const std::string &option, const std::string &default_val); /*! * \brief Set or add a string \p option to \p section with value * \p val. */ virtual void set_string(const std::string §ion, const std::string &option, const std::string &val); /*! * \brief If option exists and value can be converted to bool, * return it; else default_val. */ virtual bool get_bool(const std::string §ion, const std::string &option, bool default_val); /*! * \brief Set or add a bool \p option to \p section with value \p val. */ virtual void set_bool(const std::string §ion, const std::string &option, bool val); /*! * \brief If option exists and value can be converted to long, * return it; else default_val. */ virtual long get_long(const std::string §ion, const std::string &option, long default_val); /*! * \brief Set or add a long \p option to \p section with value \p val. */ virtual void set_long(const std::string §ion, const std::string &option, long val); /*! * \brief If option exists and value can be converted to double, * return it; else default_val. */ virtual double get_double(const std::string §ion, const std::string &option, double default_val); /*! * \brief Set or add a double \p option to \p section with value \p val. */ virtual void set_double(const std::string §ion, const std::string &option, double val); protected: virtual std::vector _sys_prefs_filenames(); virtual void _read_files(); virtual void _convert_to_map(const std::string &conf); virtual char * option_to_env(std::string section, std::string option); private: gr::thread::mutex d_mutex; config_map_t d_config_map; }; } /* namespace gr */ #endif /* INCLUDED_GR_PREFS_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/feval.h0000664000175000017500000001205412207440367023325 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FEVAL_H #define INCLUDED_GR_FEVAL_H #include #include #include namespace gr { /*! * \brief base class for evaluating a function: double -> double * \ingroup misc * * This class is designed to be subclassed in Python or C++ and is * callable from both places. It uses SWIG's "director" feature to * implement the magic. * * It's slow. Don't use it in a performance critical path. * * Override eval to define the behavior. * Use calleval to invoke eval (this kludge is required to allow a * python specific "shim" to be inserted. */ class GR_RUNTIME_API feval_dd { protected: /*! * \brief override this to define the function */ virtual double eval(double x); public: feval_dd() {} virtual ~feval_dd(); virtual double calleval(double x); // invoke "eval" }; /*! * \brief base class for evaluating a function: complex -> complex * \ingroup misc * * This class is designed to be subclassed in Python or C++ and is * callable from both places. It uses SWIG's "director" feature to * implement the magic. * * It's slow. Don't use it in a performance critical path. * * Override eval to define the behavior. * Use calleval to invoke eval (this kludge is required to allow a * python specific "shim" to be inserted. */ class GR_RUNTIME_API feval_cc { protected: /*! * \brief override this to define the function */ virtual gr_complex eval(gr_complex x); public: feval_cc() {} virtual ~feval_cc(); virtual gr_complex calleval(gr_complex x); // invoke "eval" }; /*! * \brief base class for evaluating a function: long -> long * \ingroup misc * * This class is designed to be subclassed in Python or C++ and is * callable from both places. It uses SWIG's "director" feature to * implement the magic. * * It's slow. Don't use it in a performance critical path. * * Override eval to define the behavior. * Use calleval to invoke eval (this kludge is required to allow a * python specific "shim" to be inserted. */ class GR_RUNTIME_API feval_ll { protected: /*! * \brief override this to define the function */ virtual long eval(long x); public: feval_ll() {} virtual ~feval_ll(); virtual long calleval(long x); // invoke "eval" }; /*! * \brief base class for evaluating a function: void -> void * \ingroup misc * * This class is designed to be subclassed in Python or C++ and is * callable from both places. It uses SWIG's "director" feature to * implement the magic. * * It's slow. Don't use it in a performance critical path. * * Override eval to define the behavior. * Use calleval to invoke eval (this kludge is required to allow a * python specific "shim" to be inserted. */ class GR_RUNTIME_API feval { protected: /*! * \brief override this to define the function */ virtual void eval(); public: feval() {} virtual ~feval(); virtual void calleval(); // invoke "eval" }; /*! * \brief base class for evaluating a function: pmt -> void * \ingroup misc * * This class is designed to be subclassed in Python or C++ and is * callable from both places. It uses SWIG's "director" feature to * implement the magic. * * It's slow. Don't use it in a performance critical path. * * Override eval to define the behavior. * Use calleval to invoke eval (this kludge is required to allow a * python specific "shim" to be inserted. */ class GR_RUNTIME_API feval_p { protected: /*! * \brief override this to define the function */ virtual void eval(pmt::pmt_t x); public: feval_p() {} virtual ~feval_p(); virtual void calleval(pmt::pmt_t x); // invoke "eval" }; /*! * \brief trivial examples / test cases showing C++ calling Python code */ GR_RUNTIME_API double feval_dd_example(feval_dd *f, double x); GR_RUNTIME_API gr_complex feval_cc_example(feval_cc *f, gr_complex x); GR_RUNTIME_API long feval_ll_example(feval_ll *f, long x); GR_RUNTIME_API void feval_example(feval *f); } /* namespace gr */ #endif /* INCLUDED_GR_FEVAL_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/attributes.h0000664000175000017500000000601312207440367024414 0ustar jcorganjcorgan/* * Copyright 2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GNURADIO_ATTRIBUTES_H #define INCLUDED_GNURADIO_ATTRIBUTES_H //////////////////////////////////////////////////////////////////////// // Cross-platform attribute macros //////////////////////////////////////////////////////////////////////// #if defined __GNUC__ # define __GR_ATTR_ALIGNED(x) __attribute__((aligned(x))) # define __GR_ATTR_UNUSED __attribute__((unused)) # define __GR_ATTR_INLINE __attribute__((always_inline)) # define __GR_ATTR_DEPRECATED __attribute__((deprecated)) # if __GNUC__ >= 4 # define __GR_ATTR_EXPORT __attribute__((visibility("default"))) # define __GR_ATTR_IMPORT __attribute__((visibility("default"))) # else # define __GR_ATTR_EXPORT # define __GR_ATTR_IMPORT # endif #elif _MSC_VER # define __GR_ATTR_ALIGNED(x) __declspec(align(x)) # define __GR_ATTR_UNUSED # define __GR_ATTR_INLINE __forceinline # define __GR_ATTR_DEPRECATED __declspec(deprecated) # define __GR_ATTR_EXPORT __declspec(dllexport) # define __GR_ATTR_IMPORT __declspec(dllimport) #else # define __GR_ATTR_ALIGNED(x) # define __GR_ATTR_UNUSED # define __GR_ATTR_INLINE # define __GR_ATTR_DEPRECATED # define __GR_ATTR_EXPORT # define __GR_ATTR_IMPORT #endif //////////////////////////////////////////////////////////////////////// // define inline when building C //////////////////////////////////////////////////////////////////////// #if defined(_MSC_VER) && !defined(__cplusplus) && !defined(inline) # define inline __inline #endif //////////////////////////////////////////////////////////////////////// // suppress warnings //////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER # pragma warning(disable: 4251) // class 'A' needs to have dll-interface to be used by clients of class 'B' # pragma warning(disable: 4275) // non dll-interface class ... used as base for dll-interface class ... # pragma warning(disable: 4244) // conversion from 'double' to 'float', possible loss of data # pragma warning(disable: 4305) // 'initializing' : truncation from 'double' to 'float' # pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) #endif #endif /* INCLUDED_GNURADIO_ATTRIBUTES_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/pycallback_object.h0000664000175000017500000001335312224021502025647 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include enum pyport_t { PYPORT_STRING, PYPORT_FLOAT }; class Instance { public: static boost::shared_ptr get_application() { return ice_application_common::Instance(); } static Ice::CommunicatorPtr get_swig_communicator() { return get_application()->communicator(); } }; int pycallback_object_count = 500; // a simple to-PMT converter template class-function template class pmt_assist { public: static pmt::pmt_t make(myType _val) { return pmt::mp(_val); } }; /* template specializations for vectors that cant use pmt::mp() */ template<> pmt::pmt_t pmt_assist >::make(std::vector _val) { return pmt::init_f32vector(_val.size(), &_val[0]); } template<> pmt::pmt_t pmt_assist >::make(std::vector _val) { return pmt::init_c32vector(_val.size(), &_val[0]); } template class pycallback_object { public: pycallback_object(std::string name, std::string functionbase, std::string units, std::string desc, myType min, myType max, myType deflt, DisplayType dtype) : d_callback(NULL), d_functionbase(functionbase), d_units(units), d_desc(desc), d_min(min), d_max(max), d_deflt(deflt), d_dtype(dtype), d_name(name), d_id(pycallback_object_count++) { d_callback = NULL; setup_rpc(); } void add_rpc_variable(rpcbasic_sptr s) { d_rpc_vars.push_back(s); } myType get() { myType rVal = d_deflt; if(d_callback == NULL) { printf("WARNING: pycallback_object get() called without py callback set!\n"); return rVal; } else { // obtain PyGIL PyGILState_STATE state = PyGILState_Ensure(); PyObject *func; //PyObject *arglist; PyObject *result; func = (PyObject *) d_callback; // Get Python function //arglist = Py_BuildValue(""); // Build argument list result = PyEval_CallObject(func,NULL); // Call Python //result = PyEval_CallObject(func,arglist); // Call Python //Py_DECREF(arglist); // Trash arglist if(result) { // If no errors, return double rVal = pyCast(result); } Py_XDECREF(result); // release PyGIL PyGILState_Release(state); return rVal; } } void set_callback(PyObject *cb) { d_callback = cb; } void setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( (boost::format("%s%d") % d_name % d_id).str() , d_functionbase.c_str(), this, &pycallback_object::get, pmt_assist::make(d_min), pmt_assist::make(d_max), pmt_assist::make(d_deflt), d_units.c_str(), d_desc.c_str(), RPC_PRIVLVL_MIN, d_dtype))); #endif /* GR_CTRLPORT */ } private: PyObject* d_callback; std::string d_functionbase, d_units, d_desc; myType d_min, d_max, d_deflt; DisplayType d_dtype; /* This is a fall-through converter in case someone tries to call pyCast on an * object type for which there isn't a template specialization (located below * this class) function. This function should never get called, and it is * unknown if changing the return type from myType to 'void' will break * something. */ myType pyCast(PyObject* obj) { printf("TYPE NOT IMPLEMENTED!\n"); assert(0); }; std::vector d_rpc_vars; // container for all RPC variables std::string d_name; int d_id; }; // template specialization conversion functions // get data out of the PyObject and into the real world template<> std::string pycallback_object::pyCast(PyObject* obj) { return std::string(PyString_AsString(obj)); } template<> double pycallback_object::pyCast(PyObject* obj) { return PyFloat_AsDouble(obj); } template<> float pycallback_object::pyCast(PyObject* obj) { return (float)PyFloat_AsDouble(obj); } template<> int pycallback_object::pyCast(PyObject* obj) { return PyInt_AsLong(obj); } template<> std::vector pycallback_object >::pyCast(PyObject* obj) { int size = PyObject_Size(obj); std::vector rval(size); for(int i=0; i std::vector pycallback_object >::pyCast(PyObject* obj) { int size = PyObject_Size(obj); std::vector rval(size); for(int i=0; i #include #include namespace gr { /*! * \brief Message class. * * \ingroup misc * The ideas and method names for adjustable message length were * lifted from the click modular router "Packet" class. */ class GR_RUNTIME_API message { public: typedef boost::shared_ptr sptr; private: sptr d_next; // link field for msg queue long d_type; // type of the message double d_arg1; // optional arg1 double d_arg2; // optional arg2 unsigned char *d_buf_start; // start of allocated buffer unsigned char *d_msg_start; // where the msg starts unsigned char *d_msg_end; // one beyond end of msg unsigned char *d_buf_end; // one beyond end of allocated buffer message(long type, double arg1, double arg2, size_t length); friend class msg_queue; unsigned char *buf_data() const { return d_buf_start; } size_t buf_len() const { return d_buf_end - d_buf_start; } public: /*! * \brief public constructor for message */ static sptr make(long type = 0, double arg1 = 0, double arg2 = 0, size_t length = 0); static sptr make_from_string(const std::string s, long type = 0, double arg1 = 0, double arg2 = 0); ~message(); long type() const { return d_type; } double arg1() const { return d_arg1; } double arg2() const { return d_arg2; } void set_type(long type) { d_type = type; } void set_arg1(double arg1) { d_arg1 = arg1; } void set_arg2(double arg2) { d_arg2 = arg2; } unsigned char *msg() const { return d_msg_start; } size_t length() const { return d_msg_end - d_msg_start; } std::string to_string() const; }; GR_RUNTIME_API long message_ncurrently_allocated(); } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sync_interpolator.h0000664000175000017500000000461412207440367026011 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_SYNC_INTERPOLATOR_H #define INCLUDED_GR_RUNTIME_SYNC_INTERPOLATOR_H #include #include namespace gr { /*! * \brief synchronous 1:N input to output with history * \ingroup base_blk * * Override work to provide the signal processing implementation. */ class GR_RUNTIME_API sync_interpolator : public sync_block { private: unsigned d_interpolation; protected: sync_interpolator(void) {} // allows pure virtual interface sub-classes sync_interpolator(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature, unsigned interpolation); public: unsigned interpolation() const { return d_interpolation; } void set_interpolation(unsigned interpolation) { d_interpolation = interpolation; set_relative_rate(1.0 * interpolation); set_output_multiple(interpolation); } // gr::sync_interpolator overrides these to assist work void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); // derived classes should override work int fixed_rate_ninput_to_noutput(int ninput); int fixed_rate_noutput_to_ninput(int noutput); }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_SYNC_INTERPOLATOR_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/msg_queue.h0000664000175000017500000000525112207440367024223 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MSG_QUEUE_H #define INCLUDED_GR_MSG_QUEUE_H #include #include #include namespace gr { /*! * \brief thread-safe message queue * \ingroup misc */ class GR_RUNTIME_API msg_queue : public msg_handler { gr::thread::mutex d_mutex; gr::thread::condition_variable d_not_empty; gr::thread::condition_variable d_not_full; message::sptr d_head; message::sptr d_tail; unsigned int d_count; // # of messages in queue. unsigned int d_limit; // max # of messages in queue. 0 -> unbounded public: typedef boost::shared_ptr sptr; static sptr make(unsigned int limit=0); msg_queue(unsigned int limit); ~msg_queue(); //! Generic msg_handler method: insert the message. void handle(message::sptr msg) { insert_tail (msg); } /*! * \brief Insert message at tail of queue. * \param msg message * * Block if queue if full. */ void insert_tail(message::sptr msg); /*! * \brief Delete message from head of queue and return it. * Block if no message is available. */ message::sptr delete_head(); /*! * \brief If there's a message in the q, delete it and return it. * If no message is available, return 0. */ message::sptr delete_head_nowait(); //! Delete all messages from the queue void flush(); //! is the queue empty? bool empty_p() const { return d_count == 0; } //! is the queue full? bool full_p() const { return d_limit != 0 && d_count >= d_limit; } //! return number of messages in queue unsigned int count() const { return d_count; } //! return limit on number of message in queue. 0 -> unbounded unsigned int limit() const { return d_limit; } }; } /* namespace gr */ #endif /* INCLUDED_GR_MSG_QUEUE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/basic_block.h0000664000175000017500000003225412244272666024475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2008,2009,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_BASIC_BLOCK_H #define INCLUDED_GR_BASIC_BLOCK_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef GR_CTRLPORT #include #endif namespace gr { /*! * \brief The abstract base class for all signal processing blocks. * \ingroup internal * * Basic blocks are the bare abstraction of an entity that has a * name, a set of inputs and outputs, and a message queue. These * are never instantiated directly; rather, this is the abstract * parent class of both gr_hier_block, which is a recursive * container, and block, which implements actual signal * processing functions. */ class GR_RUNTIME_API basic_block : public msg_accepter, public boost::enable_shared_from_this { typedef boost::function msg_handler_t; private: //msg_handler_t d_msg_handler; typedef std::map d_msg_handlers_t; d_msg_handlers_t d_msg_handlers; typedef std::deque msg_queue_t; typedef std::map msg_queue_map_t; typedef std::map::iterator msg_queue_map_itr; std::map, pmt::comparator> msg_queue_ready; gr::thread::mutex mutex; //< protects all vars protected: friend class flowgraph; friend class flat_flowgraph; // TODO: will be redundant friend class tpb_thread_body; enum vcolor { WHITE, GREY, BLACK }; std::string d_name; gr::io_signature::sptr d_input_signature; gr::io_signature::sptr d_output_signature; long d_unique_id; long d_symbolic_id; std::string d_symbol_name; std::string d_symbol_alias; vcolor d_color; bool d_rpc_set; msg_queue_map_t msg_queue; std::vector d_rpc_vars; // container for all RPC variables basic_block(void) {} // allows pure virtual interface sub-classes //! Protected constructor prevents instantiation by non-derived classes basic_block(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); //! may only be called during constructor void set_input_signature(gr::io_signature::sptr iosig) { d_input_signature = iosig; } //! may only be called during constructor void set_output_signature(gr::io_signature::sptr iosig) { d_output_signature = iosig; } /*! * \brief Allow the flowgraph to set for sorting and partitioning */ void set_color(vcolor color) { d_color = color; } vcolor color() const { return d_color; } /*! * \brief Tests if there is a handler attached to port \p which_port */ virtual bool has_msg_handler(pmt::pmt_t which_port) { return (d_msg_handlers.find(which_port) != d_msg_handlers.end()); } /* * This function is called by the runtime system to dispatch messages. * * The thread-safety guarantees mentioned in set_msg_handler are * implemented by the callers of this method. */ virtual void dispatch_msg(pmt::pmt_t which_port, pmt::pmt_t msg) { // AA Update this if(has_msg_handler(which_port)) { // Is there a handler? d_msg_handlers[which_port](msg); // Yes, invoke it. } } // Message passing interface pmt::pmt_t d_message_subscribers; public: pmt::pmt_t message_subscribers(pmt::pmt_t port); virtual ~basic_block(); long unique_id() const { return d_unique_id; } long symbolic_id() const { return d_symbolic_id; } std::string name() const { return d_name; } std::string symbol_name() const { return d_symbol_name; } gr::io_signature::sptr input_signature() const { return d_input_signature; } gr::io_signature::sptr output_signature() const { return d_output_signature; } basic_block_sptr to_basic_block(); // Needed for Python type coercion bool alias_set() { return !d_symbol_alias.empty(); } std::string alias(){ return alias_set()?d_symbol_alias:symbol_name(); } pmt::pmt_t alias_pmt(){ return pmt::intern(alias()); } void set_block_alias(std::string name); // ** Message passing interface ** void message_port_register_in(pmt::pmt_t port_id); void message_port_register_out(pmt::pmt_t port_id); void message_port_pub(pmt::pmt_t port_id, pmt::pmt_t msg); void message_port_sub(pmt::pmt_t port_id, pmt::pmt_t target); void message_port_unsub(pmt::pmt_t port_id, pmt::pmt_t target); virtual bool message_port_is_hier(pmt::pmt_t port_id) { (void) port_id; std::cout << "is_hier\n"; return false; } virtual bool message_port_is_hier_in(pmt::pmt_t port_id) { (void) port_id; std::cout << "is_hier_in\n"; return false; } virtual bool message_port_is_hier_out(pmt::pmt_t port_id) { (void) port_id; std::cout << "is_hier_out\n"; return false; } /*! * \brief Get input message port names. * * Returns the available input message ports for a block. The * return object is a PMT vector that is filled with PMT symbols. */ pmt::pmt_t message_ports_in(); /*! * \brief Get output message port names. * * Returns the available output message ports for a block. The * return object is a PMT vector that is filled with PMT symbols. */ pmt::pmt_t message_ports_out(); /*! * Accept msg, place in queue, arrange for thread to be awakened if it's not already. */ void _post(pmt::pmt_t which_port, pmt::pmt_t msg); //! is the queue empty? bool empty_p(pmt::pmt_t which_port) { if(msg_queue.find(which_port) == msg_queue.end()) throw std::runtime_error("port does not exist!"); return msg_queue[which_port].empty(); } bool empty_p() { bool rv = true; BOOST_FOREACH(msg_queue_map_t::value_type &i, msg_queue) { rv &= msg_queue[i.first].empty(); } return rv; } //! are all msg ports with handlers empty? bool empty_handled_p(pmt::pmt_t which_port){ return (empty_p(which_port) || !has_msg_handler(which_port)); } bool empty_handled_p() { bool rv = true; BOOST_FOREACH(msg_queue_map_t::value_type &i, msg_queue) { rv &= empty_handled_p(i.first); } return rv; } //! How many messages in the queue? size_t nmsgs(pmt::pmt_t which_port) { if(msg_queue.find(which_port) == msg_queue.end()) throw std::runtime_error("port does not exist!"); return msg_queue[which_port].size(); } //| Acquires and release the mutex void insert_tail( pmt::pmt_t which_port, pmt::pmt_t msg); /*! * \returns returns pmt at head of queue or pmt::pmt_t() if empty. */ pmt::pmt_t delete_head_nowait( pmt::pmt_t which_port); /*! * \returns returns pmt at head of queue or pmt::pmt_t() if empty. */ pmt::pmt_t delete_head_blocking( pmt::pmt_t which_port); msg_queue_t::iterator get_iterator(pmt::pmt_t which_port) { return msg_queue[which_port].begin(); } void erase_msg(pmt::pmt_t which_port, msg_queue_t::iterator it) { msg_queue[which_port].erase(it); } virtual bool has_msg_port(pmt::pmt_t which_port) { if(msg_queue.find(which_port) != msg_queue.end()) { return true; } if(pmt::dict_has_key(d_message_subscribers, which_port)) { return true; } return false; } #ifdef GR_CTRLPORT /*! * \brief Add an RPC variable (get or set). * * Using controlport, we create new getters/setters and need to * store them. Each block has a vector to do this, and these never * need to be accessed again once they are registered with the RPC * backend. This function takes a * boost::shared_sptr so that when the block is * deleted, all RPC registered variables are cleaned up. * * \param s an rpcbasic_sptr of the new RPC variable register to store. */ void add_rpc_variable(rpcbasic_sptr s) { d_rpc_vars.push_back(s); } #endif /* GR_CTRLPORT */ /*! * \brief Set up the RPC registered variables. * * This must be overloaded by a block that wants to use * controlport. This is where rpcbasic_register_{get,set} pointers * are created, which then get wrapped as shared pointers * (rpcbasic_sptr(...)) and stored using add_rpc_variable. */ virtual void setup_rpc() {}; /*! * \brief Ask if this block has been registered to the RPC. * * We can only register a block once, so we use this to protect us * from calling it multiple times. */ bool is_rpc_set() { return d_rpc_set; } /*! * \brief When the block is registered with the RPC, set this. */ void rpc_set() { d_rpc_set = true; } /*! * \brief Confirm that ninputs and noutputs is an acceptable combination. * * \param ninputs number of input streams connected * \param noutputs number of output streams connected * * \returns true if this is a valid configuration for this block. * * This function is called by the runtime system whenever the * topology changes. Most classes do not need to override this. * This check is in addition to the constraints specified by the * input and output gr::io_signatures. */ virtual bool check_topology(int ninputs, int noutputs) { (void)ninputs; (void)noutputs; return true; } /*! * \brief Set the callback that is fired when messages are available. * * \p msg_handler can be any kind of function pointer or function object * that has the signature: *
     *    void msg_handler(pmt::pmt msg);
     * 
* * (You may want to use boost::bind to massage your callable into * the correct form. See gr::blocks::nop for an example that sets * up a class method as the callback.) * * Blocks that desire to handle messages must call this method in * their constructors to register the handler that will be invoked * when messages are available. * * If the block inherits from block, the runtime system will * ensure that msg_handler is called in a thread-safe manner, such * that work and msg_handler will never be called concurrently. * This allows msg_handler to update state variables without * having to worry about thread-safety issues with work, * general_work or another invocation of msg_handler. * * If the block inherits from hier_block2, the runtime system * will ensure that no reentrant calls are made to msg_handler. */ template void set_msg_handler(pmt::pmt_t which_port, T msg_handler) { if(msg_queue.find(which_port) == msg_queue.end()) { throw std::runtime_error("attempt to set_msg_handler() on bad input message port!"); } d_msg_handlers[which_port] = msg_handler_t(msg_handler); } virtual void set_processor_affinity(const std::vector &mask) { throw std::runtime_error("set_processor_affinity not overloaded in child class."); } virtual void unset_processor_affinity() { throw std::runtime_error("unset_processor_affinity not overloaded in child class."); } virtual std::vector processor_affinity() { throw std::runtime_error("processor_affinity not overloaded in child class."); } }; inline bool operator<(basic_block_sptr lhs, basic_block_sptr rhs) { return lhs->unique_id() < rhs->unique_id(); } typedef std::vector basic_block_vector_t; typedef std::vector::iterator basic_block_viter_t; GR_RUNTIME_API long basic_block_ncurrently_allocated(); inline std::ostream &operator << (std::ostream &os, basic_block_sptr basic_block) { os << basic_block->name() << "(" << basic_block->unique_id() << ")"; return os; } } /* namespace gr */ #endif /* INCLUDED_GR_BASIC_BLOCK_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sptr_magic.h0000664000175000017500000000313612207440367024361 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_RUNTIME_SPTR_MAGIC_H #define INCLUDED_GR_RUNTIME_SPTR_MAGIC_H #include #include namespace gr { class basic_block; class hier_block2; } namespace gnuradio { namespace detail { class GR_RUNTIME_API sptr_magic { public: static boost::shared_ptr fetch_initial_sptr(gr::basic_block *p); static void create_and_stash_initial_sptr(gr::hier_block2 *p); }; }; /* * \brief New! Improved! Standard method to get/create the * boost::shared_ptr for a block. */ template boost::shared_ptr get_initial_sptr(T *p) { return boost::dynamic_pointer_cast (detail::sptr_magic::fetch_initial_sptr(p)); } } #endif /* INCLUDED_GR_RUNTIME_SPTR_MAGIC_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/gr_complex.h0000664000175000017500000000331412207440367024366 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_COMPLEX_H #define INCLUDED_GR_COMPLEX_H #include typedef std::complex gr_complex; typedef std::complex gr_complexd; inline bool is_complex (gr_complex x) { (void) x; return true;} inline bool is_complex (gr_complexd x) { (void) x; return true;} inline bool is_complex (float x) { (void) x; return false;} inline bool is_complex (double x) { (void) x; return false;} inline bool is_complex (int x) { (void) x; return false;} inline bool is_complex (char x) { (void) x; return false;} inline bool is_complex (short x) { (void) x; return false;} // this doesn't really belong here, but there are worse places for it... #define CPPUNIT_ASSERT_COMPLEXES_EQUAL(expected,actual,delta) \ CPPUNIT_ASSERT_DOUBLES_EQUAL (expected.real(), actual.real(), delta); \ CPPUNIT_ASSERT_DOUBLES_EQUAL (expected.imag(), actual.imag(), delta); #endif /* INCLUDED_GR_COMPLEX_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sync_block.h0000664000175000017500000000441712207440367024362 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_SYNC_BLOCK_H #define INCLUDED_GR_RUNTIME_SYNC_BLOCK_H #include #include namespace gr { /*! * \brief synchronous 1:1 input to output with history * \ingroup base_blk * * Override work to provide the signal processing implementation. */ class GR_RUNTIME_API sync_block : public block { protected: sync_block(void) {} // allows pure virtual interface sub-classes sync_block(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); public: /*! * \brief just like gr::block::general_work, only this arranges to * call consume_each for you * * The user must override work to define the signal processing code */ virtual int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) = 0; // gr::sync_block overrides these to assist work void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int fixed_rate_ninput_to_noutput(int ninput); int fixed_rate_noutput_to_ninput(int noutput); }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_SYNC_BLOCK_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_base.h0000664000175000017500000000314412207440367025235 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_BASE_H #define RPCSERVER_BASE_H #include class rpcserver_base : public virtual callbackregister_base { public: rpcserver_base() : cur_priv(RPC_PRIVLVL_ALL) {;} virtual ~rpcserver_base() {;} virtual void registerConfigureCallback(const std::string &id, const configureCallback_t callback) = 0; virtual void unregisterConfigureCallback(const std::string &id) = 0; virtual void registerQueryCallback(const std::string &id, const queryCallback_t callback) = 0; virtual void unregisterQueryCallback(const std::string &id) = 0; virtual void setCurPrivLevel(const priv_lvl_t priv) { cur_priv = priv; } typedef boost::shared_ptr rpcserver_base_sptr; protected: priv_lvl_t cur_priv; private: }; #endif /* RPCSERVER_BASE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpccallbackregister_base.h0000664000175000017500000000663212207440367027235 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCCALLBACKREGISTER_BASE_H #define RPCCALLBACKREGISTER_BASE_H #include #include typedef uint32_t DisplayType; // DisplayType Plotting types const uint32_t DISPNULL = 0x0000; const uint32_t DISPTIME = 0x0001; const uint32_t DISPXY = 0x0002; const uint32_t DISPPSD = 0x0004; const uint32_t DISPSPEC = 0x0008; const uint32_t DISPRAST = 0x0010; // DisplayType Options const uint32_t DISPOPTCPLX = 0x0100; const uint32_t DISPOPTLOG = 0x0200; const uint32_t DISPOPTSTEM = 0x0400; const uint32_t DISPOPTSTRIP = 0x0800; const uint32_t DISPOPTSCATTER = 0x1000; enum priv_lvl_t { RPC_PRIVLVL_ALL = 0, RPC_PRIVLVL_MIN = 9, RPC_PRIVLVL_NONE = 10 }; enum KnobType { KNOBBOOL, KNOBCHAR, KNOBINT, KNOBFLOAT, KNOBDOUBLE, KNOBSTRING, KNOBLONG, KNOBVECBOOL, KNOBCOMPLEX, KNOBCOMPLEXD, KNOBVECCHAR, KNOBVECINT, KNOBVECFLOAT, KNOBVECDOUBLE, KNOBVECSTRING, KNOBVECLONG }; struct callbackregister_base { struct callback_base_t { public: callback_base_t(const priv_lvl_t priv_, const std::string& units_, const DisplayType display_, const std::string& desc_, const pmt::pmt_t min_, const pmt::pmt_t max_, const pmt::pmt_t def) : priv(priv_), units(units_), description(desc_), min(min_), max(max_), defaultvalue(def), display(display_) { } priv_lvl_t priv; std::string units, description; pmt::pmt_t min, max, defaultvalue; DisplayType display; }; template class callback_t : public callback_base_t { public: callback_t(T* callback_, priv_lvl_t priv_, const std::string& units_, const DisplayType display_, const:: std::string& desc_, const pmt::pmt_t& min_, const pmt::pmt_t& max_, const pmt::pmt_t& def_) : callback_base_t(priv_, units_, display_, desc_, min_, max_, def_), callback(callback_) { } Tsptr callback; }; typedef callback_t configureCallback_t; typedef callback_t queryCallback_t; callbackregister_base() {;} virtual ~callbackregister_base() {;} virtual void registerConfigureCallback(const std::string &id, const configureCallback_t callback) = 0; virtual void unregisterConfigureCallback(const std::string &id) = 0; virtual void registerQueryCallback(const std::string &id, const queryCallback_t callback) = 0; virtual void unregisterQueryCallback(const std::string &id) = 0; }; #endif /* RPCCALLBACKREGISTER_BASE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/endianness.h0000664000175000017500000000200512207440367024352 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ENDIANNESS_H #define INCLUDED_GR_ENDIANNESS_H namespace gr { typedef enum {GR_MSB_FIRST, GR_LSB_FIRST} endianness_t; } /* namespace gr */ #endif /* INCLUDED_GR_ENDIANNESS_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/tpb_detail.h0000664000175000017500000000474112214652673024346 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_TPB_DETAIL_H #define INCLUDED_GR_TPB_DETAIL_H #include #include #include #include namespace gr { class block_detail; /*! * \brief used by thread-per-block scheduler */ struct GR_RUNTIME_API tpb_detail { gr::thread::mutex mutex; //< protects all vars bool input_changed; gr::thread::condition_variable input_cond; bool output_changed; gr::thread::condition_variable output_cond; public: tpb_detail() : input_changed(false), output_changed(false) { } //! Called by us to tell all our upstream blocks that their output //! may have changed. void notify_upstream(block_detail *d); //! Called by us to tell all our downstream blocks that their //! input may have changed. void notify_downstream(block_detail *d); //! Called by us to notify both upstream and downstream void notify_neighbors(block_detail *d); //! Called by pmt msg posters void notify_msg() { input_cond.notify_one(); output_cond.notify_one(); } //! Called by us void clear_changed() { gr::thread::scoped_lock guard(mutex); input_changed = false; output_changed = false; } private: //! Used by notify_downstream void set_input_changed() { gr::thread::scoped_lock guard(mutex); input_changed = true; input_cond.notify_one(); } //! Used by notify_upstream void set_output_changed() { gr::thread::scoped_lock guard(mutex); output_changed = true; output_cond.notify_one(); } }; } /* namespace gr */ #endif /* INCLUDED_GR_TPB_DETAIL_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/msg_handler.h0000664000175000017500000000247712207440367024523 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MSG_HANDLER_H #define INCLUDED_GR_MSG_HANDLER_H #include #include namespace gr { class msg_handler; typedef boost::shared_ptr msg_handler_sptr; /*! * \brief abstract class of message handlers * \ingroup base */ class GR_RUNTIME_API msg_handler { public: virtual ~msg_handler(); //! handle \p msg virtual void handle(message::sptr msg) = 0; }; } /* namespace gr */ #endif /* INCLUDED_GR_MSG_HANDLER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/block_detail.h0000664000175000017500000002232212237515111024634 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more detail. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_BLOCK_DETAIL_H #define INCLUDED_GR_RUNTIME_BLOCK_DETAIL_H #include #include #include #include #include #include namespace gr { /*! * \brief Implementation details to support the signal processing abstraction * \ingroup internal * * This class contains implementation detail that should be "out of * sight" of almost all users of GNU Radio. This decoupling also * means that we can make changes to the guts without having to * recompile everything. */ class GR_RUNTIME_API block_detail { public: ~block_detail(); int ninputs() const { return d_ninputs; } int noutputs() const { return d_noutputs; } bool sink_p() const { return d_noutputs == 0; } bool source_p() const { return d_ninputs == 0; } void set_done(bool done); bool done() const { return d_done; } void set_input(unsigned int which, buffer_reader_sptr reader); buffer_reader_sptr input(unsigned int which) { if(which >= d_ninputs) throw std::invalid_argument("block_detail::input"); return d_input[which]; } void set_output(unsigned int which, buffer_sptr buffer); buffer_sptr output(unsigned int which) { if(which >= d_noutputs) throw std::invalid_argument("block_detail::output"); return d_output[which]; } /*! * \brief Tell the scheduler \p how_many_items of input stream \p * which_input were consumed. */ void consume(int which_input, int how_many_items); /*! * \brief Tell the scheduler \p how_many_items were consumed on * each input stream. */ void consume_each(int how_many_items); /*! * \brief Tell the scheduler \p how_many_items were produced on * output stream \p which_output. */ void produce(int which_output, int how_many_items); /*! * \brief Tell the scheduler \p how_many_items were produced on * each output stream. */ void produce_each(int how_many_items); // Return the number of items read on input stream which_input uint64_t nitems_read(unsigned int which_input); // Return the number of items written on output stream which_output uint64_t nitems_written(unsigned int which_output); /*! * \brief Adds a new tag to the given output stream. * * Calls gr::buffer::add_item_tag(), * which appends the tag onto its deque. * * \param which_output an integer of which output stream to attach the tag * \param tag the tag object to add */ void add_item_tag(unsigned int which_output, const tag_t &tag); /*! * \brief Removes a tag from the given input stream. * * Calls gr::buffer::remove_item_tag(). * The tag in question will then no longer appear on subsequent calls of get_tags_in_range(). * * \param which_input an integer of which input stream to remove the tag from * \param tag the tag object to add * \param id The unique block ID (use gr::block::unique_id()) */ void remove_item_tag(unsigned int which_input, const tag_t &tag, long id); /*! * \brief Given a [start,end), returns a vector of all tags in the range. * * Pass-through function to gr::buffer_reader to get a vector of * tags in given range. Range of counts is from start to end-1. * * Tags are tuples of: * (item count, source id, key, value) * * \param v a vector reference to return tags into * \param which_input an integer of which input stream to pull from * \param abs_start a uint64 count of the start of the range of interest * \param abs_end a uint64 count of the end of the range of interest * \param id Block ID */ void get_tags_in_range(std::vector &v, unsigned int which_input, uint64_t abs_start, uint64_t abs_end, long id); /*! * \brief Given a [start,end), returns a vector of all tags in the * range with a given key. * * Calls get_tags_in_range(which_input, abs_start, abs_end) to get * a vector of tags from the buffers. This function then provides * a secondary filter to the tags to extract only tags with the * given 'key'. * * Tags are tuples of: * (item count, source id, key, value) * * \param v a vector reference to return tags into * \param which_input an integer of which input stream to pull from * \param abs_start a uint64 count of the start of the range of interest * \param abs_end a uint64 count of the end of the range of interest * \param key a PMT symbol to select only tags of this key * \param id Block ID */ void get_tags_in_range(std::vector &v, unsigned int which_input, uint64_t abs_start, uint64_t abs_end, const pmt::pmt_t &key, long id); /*! * \brief Set core affinity of block to the cores in the vector * mask. * * \param mask a vector of ints of the core numbers available to * this block. */ void set_processor_affinity(const std::vector &mask); /*! * \brief Unset core affinity. */ void unset_processor_affinity(); /*! * \brief Get the current thread priority */ int thread_priority(); /*! * \brief Set the current thread priority * * \param priority the new thread priority to set */ int set_thread_priority(int priority); bool threaded; // set if thread is currently running. gr::thread::gr_thread_t thread; // portable thread handle void start_perf_counters(); void stop_perf_counters(int noutput_items, int nproduced); void reset_perf_counters(); // Calls to get performance counter items float pc_noutput_items(); float pc_nproduced(); float pc_input_buffers_full(size_t which); std::vector pc_input_buffers_full(); float pc_output_buffers_full(size_t which); std::vector pc_output_buffers_full(); float pc_work_time(); float pc_noutput_items_avg(); float pc_nproduced_avg(); float pc_input_buffers_full_avg(size_t which); std::vector pc_input_buffers_full_avg(); float pc_output_buffers_full_avg(size_t which); std::vector pc_output_buffers_full_avg(); float pc_work_time_avg(); float pc_noutput_items_var(); float pc_nproduced_var(); float pc_input_buffers_full_var(size_t which); std::vector pc_input_buffers_full_var(); float pc_output_buffers_full_var(size_t which); std::vector pc_output_buffers_full_var(); float pc_work_time_var(); float pc_work_time_total(); tpb_detail d_tpb; // used by thread-per-block scheduler int d_produce_or; // ---------------------------------------------------------------------------- private: unsigned int d_ninputs; unsigned int d_noutputs; std::vector d_input; std::vector d_output; bool d_done; // Performance counters float d_ins_noutput_items; float d_avg_noutput_items; float d_var_noutput_items; float d_ins_nproduced; float d_avg_nproduced; float d_var_nproduced; std::vector d_ins_input_buffers_full; std::vector d_avg_input_buffers_full; std::vector d_var_input_buffers_full; std::vector d_ins_output_buffers_full; std::vector d_avg_output_buffers_full; std::vector d_var_output_buffers_full; gr::high_res_timer_type d_start_of_work, d_end_of_work; float d_ins_work_time; float d_avg_work_time; float d_var_work_time; float d_total_work_time; float d_pc_counter; block_detail(unsigned int ninputs, unsigned int noutputs); friend struct tpb_detail; friend GR_RUNTIME_API block_detail_sptr make_block_detail(unsigned int ninputs, unsigned int noutputs); }; GR_RUNTIME_API block_detail_sptr make_block_detail(unsigned int ninputs, unsigned int noutputs); GR_RUNTIME_API long block_detail_ncurrently_allocated(); } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_BLOCK_DETAIL_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/0000775000175000017500000000000012207440367023664 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/CMakeLists.txt0000664000175000017500000000215012207440367026422 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES msg_accepter.h msg_accepter_msgq.h msg_passing.h msg_producer.h msg_queue.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/messages COMPONENT "runtime_devel" ) gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/msg_producer.h0000664000175000017500000000266012207440367026532 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_MSG_PRODUCER_H #define INCLUDED_MSG_PRODUCER_H #include #include #include namespace gr { namespace messages { /*! * \brief Virtual base class that produces messages */ class GR_RUNTIME_API msg_producer { public: msg_producer() {} virtual ~msg_producer(); /*! * \brief send \p msg to \p msg_producer */ virtual pmt::pmt_t retrieve() = 0; }; typedef boost::shared_ptr msg_producer_sptr; } /* namespace messages */ } /* namespace gr */ #endif /* INCLUDED_MSG_PRODUCER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/msg_passing.h0000664000175000017500000000740312207440367026353 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_MSG_PASSING_H #define INCLUDED_MSG_PASSING_H /*! * \brief Include this header to use the message passing features */ #include #include #include namespace gr { namespace messages { /*! * \brief send message to msg_accepter * * \param accepter is the target of the send. * \param which_port A pmt symbol describing the port by name. * \param msg is the message to send. It's usually a pmt tuple. * * Sending a message is an asynchronous operation. The \p send * call will not wait for the message either to arrive at the * destination or to be received. * * \returns msg */ static inline pmt::pmt_t send(msg_accepter_sptr accepter, const pmt::pmt_t &which_port, const pmt::pmt_t &msg) { accepter->post(which_port, msg); return msg; } /*! * \brief send message to msg_accepter * * \param accepter is the target of the send. * \param which_port A pmt symbol describing the port by name. * \param msg is the message to send. It's usually a pmt tuple. * * Sending a message is an asynchronous operation. The \p send * call will not wait for the message either to arrive at the * destination or to be received. * * \returns msg */ static inline pmt::pmt_t send(msg_accepter *accepter, const pmt::pmt_t &which_port, const pmt::pmt_t &msg) { accepter->post(which_port, msg); return msg; } /*! * \brief send message to msg_accepter * * \param accepter is the target of the send. * \param which_port A pmt symbol describing the port by name. * \param msg is the message to send. It's usually a pmt tuple. * * Sending a message is an asynchronous operation. The \p send * call will not wait for the message either to arrive at the * destination or to be received. * * \returns msg */ static inline pmt::pmt_t send(msg_accepter &accepter, const pmt::pmt_t &which_port, const pmt::pmt_t &msg) { accepter.post(which_port, msg); return msg; } /*! * \brief send message to msg_accepter * * \param accepter is the target of the send. * aprecond: pmt::is_msg_accepter(accepter) * \param which_port A pmt symbol describing the port by name. * \param msg is the message to send. It's usually a pmt tuple. * * Sending a message is an asynchronous operation. The \p send * call will not wait for the message either to arrive at the * destination or to be received. * * \returns msg */ static inline pmt::pmt_t send(pmt::pmt_t accepter, const pmt::pmt_t &which_port, const pmt::pmt_t &msg) { return send(pmt::msg_accepter_ref(accepter), which_port, msg); } } /* namespace messages */ } /* namespace gr */ #endif /* INCLUDED_MSG_PASSING_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/msg_queue.h0000664000175000017500000000522612207440367026034 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_MSG_QUEUE_H #define INCLUDED_MSG_QUEUE_H #include #include #include #include namespace gr { namespace messages { class msg_queue; typedef boost::shared_ptr msg_queue_sptr; msg_queue_sptr make_msg_queue(unsigned int limit=0); /*! * \brief thread-safe message queue */ class GR_RUNTIME_API msg_queue { private: gr::thread::mutex d_mutex; gr::thread::condition_variable d_not_empty; gr::thread::condition_variable d_not_full; unsigned int d_limit; // max # of messages in queue. 0 -> unbounded std::deque d_msgs; public: msg_queue(unsigned int limit); ~msg_queue(); /*! * \brief Insert message at tail of queue. * \param msg message * * Block if queue if full. */ void insert_tail(pmt::pmt_t msg); /*! * \brief Delete message from head of queue and return it. * Block if no message is available. */ pmt::pmt_t delete_head(); /*! * \brief If there's a message in the q, delete it and return it. * If no message is available, return pmt::pmt_t(). */ pmt::pmt_t delete_head_nowait(); //! Delete all messages from the queue void flush(); //! is the queue empty? bool empty_p() const { return d_msgs.empty(); } //! is the queue full? bool full_p() const { return d_limit != 0 && count() >= d_limit; } //! return number of messages in queue unsigned int count() const { return d_msgs.size(); } //! return limit on number of message in queue. 0 -> unbounded unsigned int limit() const { return d_limit; } }; } /* namespace messages */ } /* namespace gr */ #endif /* INCLUDED_MSG_QUEUE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/msg_accepter_msgq.h0000664000175000017500000000304112207440367027516 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_MSG_ACCEPTER_MSGQ_H #define INCLUDED_MSG_ACCEPTER_MSGQ_H #include #include #include namespace gr { namespace messages { /*! * \brief Concrete class that accepts messages and inserts them * into a message queue. */ class GR_RUNTIME_API msg_accepter_msgq : public msg_accepter { protected: msg_queue_sptr d_msg_queue; public: msg_accepter_msgq(msg_queue_sptr msgq); ~msg_accepter_msgq(); virtual void post(pmt::pmt_t msg); msg_queue_sptr msg_queue() const { return d_msg_queue; } }; } /* namespace messages */ } /* namespace gr */ #endif /* INCLUDED_MSG_ACCEPTER_MSGQ_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/messages/msg_accepter.h0000664000175000017500000000323012207440367026467 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_MSG_ACCEPTER_H #define INCLUDED_MSG_ACCEPTER_H #include #include #include namespace gr { namespace messages { /*! * \brief Virtual base class that accepts messages */ class GR_RUNTIME_API msg_accepter { public: msg_accepter() {}; virtual ~msg_accepter(); /*! * \brief send \p msg to \p msg_accepter on port \p which_port * * Sending a message is an asynchronous operation. The \p post * call will not wait for the message either to arrive at the * destination or to be received. */ virtual void post(pmt::pmt_t which_port, pmt::pmt_t msg) = 0; }; typedef boost::shared_ptr msg_accepter_sptr; } /* namespace messages */ } /* namespace gr */ #endif /* INCLUDED_MSG_ACCEPTER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/hier_block2.h0000664000175000017500000002072612231076123024410 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_HIER_BLOCK2_H #define INCLUDED_GR_RUNTIME_HIER_BLOCK2_H #include #include namespace gr { /*! * \brief public constructor for hier_block2 */ GR_RUNTIME_API hier_block2_sptr make_hier_block2(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); class hier_block2_detail; /*! * \brief Hierarchical container class for gr::block's and gr::hier_block2's * \ingroup container_blk * \ingroup base_blk */ class GR_RUNTIME_API hier_block2 : public basic_block { private: friend class hier_block2_detail; friend GR_RUNTIME_API hier_block2_sptr make_hier_block2(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); /*! * \brief Private implementation details of gr::hier_block2 */ hier_block2_detail *d_detail; protected: hier_block2(void) {} // allows pure virtual interface sub-classes hier_block2(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); public: virtual ~hier_block2(); /*! * \brief typedef for object returned from self(). * * This type is only guaranteed to be passable to connect and * disconnect. No other assumptions should be made about it. */ typedef basic_block_sptr opaque_self; /*! * \brief Return an object, representing the current block, which * can be passed to connect. * * The returned object may only be used as an argument to connect * or disconnect. Any other use of self() results in unspecified * (erroneous) behavior. */ opaque_self self(); /*! * \brief Add a stand-alone (possibly hierarchical) block to * internal graph * * This adds a gr-block or hierarchical block to the internal * graph without wiring it to anything else. */ void connect(basic_block_sptr block); /*! * \brief Add gr-blocks or hierarchical blocks to internal graph * and wire together * * This adds (if not done earlier by another connect) a pair of * gr-blocks or hierarchical blocks to the internal flowgraph, and * wires the specified output port to the specified input port. */ void connect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port); /*! * \brief Add gr-blocks or hierarchical blocks to internal graph * and wire together * * This adds (if not done earlier by another connect) a pair of * gr-blocks or hierarchical blocks to the internal message port * subscription */ void msg_connect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport); void msg_connect(basic_block_sptr src, std::string srcport, basic_block_sptr dst, std::string dstport); void msg_disconnect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport); void msg_disconnect(basic_block_sptr src, std::string srcport, basic_block_sptr dst, std::string dstport); /*! * \brief Remove a gr-block or hierarchical block from the * internal flowgraph. * * This removes a gr-block or hierarchical block from the internal * flowgraph, disconnecting it from other blocks as needed. */ void disconnect(basic_block_sptr block); /*! * \brief Disconnect a pair of gr-blocks or hierarchical blocks in * internal flowgraph. * * This disconnects the specified input port from the specified * output port of a pair of gr-blocks or hierarchical blocks. */ void disconnect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port); /*! * \brief Disconnect all connections in the internal flowgraph. * * This call removes all output port to input port connections in * the internal flowgraph. */ void disconnect_all(); /*! * Lock a flowgraph in preparation for reconfiguration. When an * equal number of calls to lock() and unlock() have occurred, the * flowgraph will be reconfigured. * * N.B. lock() and unlock() may not be called from a flowgraph * thread (E.g., gr::block::work method) or deadlock will occur * when reconfiguration happens. */ virtual void lock(); /*! * Unlock a flowgraph in preparation for reconfiguration. When an * equal number of calls to lock() and unlock() have occurred, the * flowgraph will be reconfigured. * * N.B. lock() and unlock() may not be called from a flowgraph * thread (E.g., gr::block::work method) or deadlock will occur * when reconfiguration happens. */ virtual void unlock(); // This is a public method for ease of code organization, but should be // ignored by the user. flat_flowgraph_sptr flatten() const; hier_block2_sptr to_hier_block2(); // Needed for Python type coercion bool has_msg_port(pmt::pmt_t which_port) { return message_port_is_hier(which_port) || basic_block::has_msg_port(which_port); } bool message_port_is_hier(pmt::pmt_t port_id) { return message_port_is_hier_in(port_id) || message_port_is_hier_out(port_id); } bool message_port_is_hier_in(pmt::pmt_t port_id) { return pmt::list_has(hier_message_ports_in, port_id); } bool message_port_is_hier_out(pmt::pmt_t port_id) { return pmt::list_has(hier_message_ports_out, port_id); } pmt::pmt_t hier_message_ports_in; pmt::pmt_t hier_message_ports_out; void message_port_register_hier_in(pmt::pmt_t port_id) { if(pmt::list_has(hier_message_ports_in, port_id)) throw std::invalid_argument("hier msg in port by this name already registered"); if(msg_queue.find(port_id) != msg_queue.end()) throw std::invalid_argument("block already has a primitive input port by this name"); hier_message_ports_in = pmt::list_add(hier_message_ports_in, port_id); } void message_port_register_hier_out(pmt::pmt_t port_id) { if(pmt::list_has(hier_message_ports_out, port_id)) throw std::invalid_argument("hier msg out port by this name already registered"); if(pmt::dict_has_key(d_message_subscribers, port_id)) throw std::invalid_argument("block already has a primitive output port by this name"); hier_message_ports_out = pmt::list_add(hier_message_ports_out, port_id); } /*! * \brief Set the affinity of all blocks in hier_block2 to processor core \p n. * * \param mask a vector of ints of the core numbers available to this block. */ void set_processor_affinity(const std::vector &mask); /*! * \brief Remove processor affinity for all blocks in hier_block2. */ void unset_processor_affinity(); /*! * \brief Get the current processor affinity. * * \details This returns the processor affinity value for the first * block in the hier_block2's list of blocks with the assumption * that they have always only been set through the hier_block2's * interface. If any block has been individually set, then this * call could be misleading. */ std::vector processor_affinity(); }; inline hier_block2_sptr cast_to_hier_block2_sptr(basic_block_sptr block) { return boost::dynamic_pointer_cast(block); } } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_HIER_BLOCK2_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/realtime.h0000664000175000017500000000224612207440367024034 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_REALTIME_H #define INCLUDED_GR_REALTIME_H #include #include namespace gr { /*! * \brief If possible, enable high-priority "real time" scheduling. * \ingroup misc */ GR_RUNTIME_API rt_status_t enable_realtime_scheduling(); } /* namespace gr */ #endif /* INCLUDED_GR_REALTIME_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/tag_checker.h0000664000175000017500000000361412237515111024462 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_TAG_CHECKER_H #define INCLUDED_GR_RUNTIME_TAG_CHECKER_H #include #include namespace gr { class tag_checker { public: tag_checker(std::vector &tags) { d_tags = tags; std::sort(d_tags.begin(), d_tags.end(), &gr::tag_t::offset_compare); if(d_tags.size() > 0) { d_has_next_tag = true; d_next_tag_index = 0; d_next_tag = tags[0]; } }; ~tag_checker() {}; void get_tags(std::vector &tag_list, unsigned int offset) { while(d_has_next_tag && (offset >= d_next_tag.offset)) { if(offset == d_next_tag.offset) { tag_list.push_back(d_next_tag); } d_next_tag_index += 1; if(d_next_tag_index >= d_tags.size()) { d_has_next_tag = false; } else { d_next_tag = d_tags[d_next_tag_index]; } } }; private: std::vector d_tags; tag_t d_next_tag; unsigned int d_next_tag_index; bool d_has_next_tag; }; } #endif /* INCLUDED_GR_RUNTIME_TAG_CHECKER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/fxpt_vco.h0000664000175000017500000000502512207702530024051 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FXPT_VCO_H #define INCLUDED_GR_FXPT_VCO_H #include #include #include namespace gr { /*! * \brief Voltage Controlled Oscillator (VCO) * \ingroup misc */ class /*GR_RUNTIME_API*/ fxpt_vco { gr_int32 d_phase; public: fxpt_vco () : d_phase(0) {} ~fxpt_vco() {} // radians void set_phase(float angle) { d_phase = fxpt::float_to_fixed(angle); } void adjust_phase(float delta_phase) { d_phase += fxpt::float_to_fixed(delta_phase); } float get_phase() const { return fxpt::fixed_to_float(d_phase); } // compute sin and cos for current phase angle void sincos(float *sinx, float *cosx) const { *sinx = fxpt::sin(d_phase); *cosx = fxpt::cos(d_phase); } // compute complex sine a block at a time void sincos(gr_complex *output, const float *input, int noutput_items, float k, float ampl = 1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = gr_complex((float)(fxpt::cos(d_phase) * ampl), (float)(fxpt::sin(d_phase) * ampl)); adjust_phase(input[i] * k); } } // compute a block at a time void cos(float *output, const float *input, int noutput_items, float k, float ampl = 1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (float)(fxpt::cos(d_phase) * ampl); adjust_phase(input[i] * k); } } // compute cos or sin for current phase angle float cos() const { return fxpt::cos(d_phase); } float sin() const { return fxpt::sin(d_phase); } }; } /* namespace gr */ #endif /* INCLUDED_GR_FXPT_VCO_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_selector.h0000664000175000017500000000173612207440367026150 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_SELECTOR #define RPCSERVER_SELECTOR #define RPCSERVER_ENABLED #define RPCSERVER_ICE //#define RPCSERVER_ERLANG //#define RPCSERVER_XMLRPC #endif gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/realtime_impl.h0000664000175000017500000000570112207440367025054 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GNURADIO_REALTIME_H #define INCLUDED_GNURADIO_REALTIME_H #include #include /*! * \brief System independent way to ask for realtime scheduling * * \sa sys_pri.h */ namespace gr { typedef enum { RT_OK = 0, RT_NOT_IMPLEMENTED, RT_NO_PRIVS, RT_OTHER_ERROR } rt_status_t; enum rt_sched_policy { RT_SCHED_RR = 0, // round robin RT_SCHED_FIFO = 1, // first in first out }; namespace impl { /* * Define the range for our virtual priorities (don't change * these) * * Processes (or threads) with numerically higher priority values * are scheduled before processes with numerically lower priority * values. Thus, the value returned by rt_priority_max() will be * greater than the value returned by rt_priority_min(). */ static inline int rt_priority_min() { return 0; } static inline int rt_priority_max() { return 15; } static inline int rt_priority_default() { return 1; } struct GR_RUNTIME_API rt_sched_param { int priority; rt_sched_policy policy; rt_sched_param() : priority(rt_priority_default()), policy(RT_SCHED_RR){} rt_sched_param(int priority_, rt_sched_policy policy_ = RT_SCHED_RR) { if(priority_ < rt_priority_min() || priority_ > rt_priority_max()) throw std::invalid_argument("rt_sched_param: priority out of range"); priority = priority_; policy = policy_; } }; /*! * \brief If possible, enable "realtime" scheduling. * \ingroup misc * * In general, this means that the code will be scheduled before * any non-realtime (normal) processes. Note that if your code * contains an non-blocking infinite loop and you enable realtime * scheduling, it's possible to hang the system. */ // NOTE: If you change this, you need to change the code in // gnuradio-runtime/swig/realtime.i, see note there. GR_RUNTIME_API rt_status_t enable_realtime_scheduling(rt_sched_param = rt_sched_param()); } /* namespace impl */ } /* namespace gr */ #endif /* INCLUDED_GNURADIO_REALTIME_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/logger.h.in0000664000175000017500000006615012207440367024122 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /******************************************************************************* * Author: Mark Plett * Description: * The gr::logger module wraps the log4cpp library for logging in gnuradio *******************************************************************************/ #ifndef INCLUDED_GR_LOGGER_H #define INCLUDED_GR_LOGGER_H /*! * \ingroup logging * \brief GNU Radio logging wrapper for log4cpp library (C++ port of log4j) * */ #ifndef ENABLE_GR_LOG #cmakedefine ENABLE_GR_LOG #endif #ifndef HAVE_LOG4CPP #cmakedefine HAVE_LOG4CPP #endif #ifdef _MSC_VER typedef unsigned short mode_t; #endif #include #include #include #include #include #include #include #include #ifdef ENABLE_GR_LOG // We have three configurations... first logging to stdout/stderr #ifndef HAVE_LOG4CPP namespace gr { //#warning GR logging Enabled and using std::cout typedef std::string logger_ptr; } /* namespace gr */ #define GR_LOG_DECLARE_LOGPTR(logger) #define GR_LOG_ASSIGN_LOGPTR(logger,name) #define GR_CONFIG_LOGGER(config) #define GR_CONFIG_AND_WATCH_LOGGER(config,period) #define GR_LOG_GETLOGGER(logger, name) #define GR_SET_LEVEL(name, level) #define GR_LOG_SET_LEVEL(logger, level) #define GR_GET_LEVEL(name, level) #define GR_LOG_GET_LEVEL(logger, level) #define GR_ADD_APPENDER(name,appender) #define GR_LOG_ADD_APPENDER(logger,appender) #define GR_ADD_CONSOLE_APPENDER(logger,target,pattern) #define GR_LOG_ADD_CONSOLE_APPENDER(logger,target,pattern) #define GR_ADD_FILE_APPENDER(name,filename,append,pattern) #define GR_LOG_ADD_FILE_APPENDER(logger,filename,append,pattern) #define GR_ADD_ROLLINGFILE_APPENDER(name,filename,filesize,bkup_index,append,mode,pattern) #define GR_LOG_ADD_ROLLINGFILE_APPENDER(logger,filename,filesize,bkup_index,append,mode,pattern) #define GR_GET_LOGGER_NAMES(names) #define GR_RESET_CONFIGURATION() #define GR_DEBUG(name, msg) std::cout<<"DEBUG: "< #include #include #include #include #include namespace gr { /*! * \brief GR_LOG macros * \ingroup logging * * These macros wrap the standard LOG4CPP_LEVEL macros. The availablie macros * are: * LOG_DEBUG * LOG_INFO * LOG_WARN * LOG_TRACE * LOG_ERROR * LOG_ALERT * LOG_CRIT * LOG_FATAL * LOG_EMERG */ typedef log4cpp::Category* logger_ptr; } /* namespace gr */ /* Macros for Programmatic Configuration */ #define GR_LOG_DECLARE_LOGPTR(logger) \ gr::logger_ptr logger; #define GR_LOG_ASSIGN_LOGPTR(logger,name) \ logger = gr::logger_get_logger(name); #define GR_CONFIG_LOGGER(config) \ gr::logger_config::load_config(config) #define GR_CONFIG_AND_WATCH_LOGGER(config,period) \ gr::logger_config::load_config(config,period) #define GR_LOG_GETLOGGER(logger, name) \ gr::logger_ptr logger = gr::logger_get_logger(name); #define GR_SET_LEVEL(name, level) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ gr::logger_set_level(logger,level);} #define GR_LOG_SET_LEVEL(logger, level) \ gr::logger_set_level(logger, level); #define GR_GET_LEVEL(name, level) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ gr::logger_get_level(logger,level);} #define GR_LOG_GET_LEVEL(logger, level) \ gr::logger_get_level(logger,level); #define GR_ADD_APPENDER(name, appender) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ gr::logger_add_appender(logger,appender);} #define GR_LOG_ADD_APPENDER(logger, appender) { \ gr::logger_add_appender(logger, appender);} #define GR_ADD_CONSOLE_APPENDER(name, target, pattern) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ gr::logger_add_console_appender(logger,target,pattern);} #define GR_LOG_ADD_CONSOLE_APPENDER(logger, target, pattern) { \ gr::logger_add_console_appender(logger,target,pattern);} #define GR_ADD_FILE_APPENDER(name, filename, append, pattern) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ gr::logger_add_file_appender(logger,filename,append,pattern);} #define GR_LOG_ADD_FILE_APPENDER(logger, filename, append, pattern) { \ gr::logger_add_file_appender(logger,filename,append,pattern);} #define GR_ADD_ROLLINGFILE_APPENDER(name, filename, filesize, bkup_index, append, mode, pattern) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ gr::logger_add_rollingfile_appender(logger,filename,filesize,bkup_index,append,mode,pattern);} #define GR_LOG_ADD_ROLLINGFILE_APPENDER(logger, filename, filesize, bkup_index, append, mode, pattern) { \ gr::logger_add_rollingfile_appender(logger,filename,filesize,bkup_index,append,mode,pattern);} #define GR_GET_LOGGER_NAMES(names) { \ names = gr::logger_get_logger_names();} #define GR_RESET_CONFIGURATION() \ gr::logger_config::reset_config(); /* Logger name referenced macros */ #define GR_DEBUG(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::DEBUG << msg << log4cpp::eol;} #define GR_INFO(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::INFO << msg << log4cpp::eol;} #define GR_NOTICE(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger << log4cpp::Priority::NOTICE << msg;} #define GR_WARN(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::WARN << msg << log4cpp::eol;} #define GR_ERROR(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::ERROR << msg << log4cpp::eol;} #define GR_CRIT(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::CRIT << msg << log4cpp::eol;} #define GR_ALERT(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::ALERT << msg << log4cpp::eol;} #define GR_FATAL(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::FATAL << msg << log4cpp::eol;} #define GR_EMERG(name, msg) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::EMERG << msg << log4cpp::eol;} #define GR_ERRORIF(name, cond, msg) { \ if((cond)) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::ERROR << msg << log4cpp::eol;} \ } #define GR_ASSERT(name, cond, msg) { \ if(!(cond)) { \ gr::logger_ptr logger = gr::logger_get_logger(name); \ *logger<< log4cpp::Priority::EMERG << msg << log4cpp::eol;} \ assert(0); \ } /* LoggerPtr Referenced Macros */ #define GR_LOG_DEBUG(logger, msg) { \ *logger << log4cpp::Priority::DEBUG << msg << log4cpp::eol;} #define GR_LOG_INFO(logger, msg) { \ *logger << log4cpp::Priority::INFO << msg << log4cpp::eol;} #define GR_LOG_NOTICE(logger, msg) { \ *logger << log4cpp::Priority::NOTICE << msg << log4cpp::eol;} #define GR_LOG_WARN(logger, msg) { \ *logger << log4cpp::Priority::WARN << msg << log4cpp::eol;} #define GR_LOG_ERROR(logger, msg) { \ *logger << log4cpp::Priority::ERROR << msg << log4cpp::eol;} #define GR_LOG_CRIT(logger, msg) { \ *logger << log4cpp::Priority::CRIT << msg << log4cpp::eol;} #define GR_LOG_ALERT(logger, msg) { \ *logger << log4cpp::Priority::ALERT << msg << log4cpp::eol;} #define GR_LOG_FATAL(logger, msg) { \ *logger << log4cpp::Priority::FATAL << msg << log4cpp::eol;} #define GR_LOG_EMERG(logger, msg) { \ *logger << log4cpp::Priority::EMERG << msg << log4cpp::eol;} #define GR_LOG_ERRORIF(logger,cond, msg) { \ if((cond)) { \ *logger<< log4cpp::Priority::ERROR << msg << log4cpp::eol;} \ } #define GR_LOG_ASSERT(logger, cond, msg) { \ if(!(cond)) { \ *logger<< log4cpp::Priority::EMERG << msg << log4cpp::eol; \ assert(0);} \ } namespace gr { /*! * \brief Class to control configuration of logger. * This is a singleton that cna launch a thread to wathc a config file for changes * \ingroup logging */ class logger_config { private: /*! \brief filename of logger config file */ std::string filename; /*! \brief Period (seconds) over which watcher thread checks config file for changes */ unsigned int watch_period; /*! \brief Pointer to watch thread for config file changes */ boost::thread *watch_thread; /*! \brief Watcher thread method * /param filename Name of configuration file * /param watch_period Seconds between checks for changes in config file */ static void watch_file(std::string filename,unsigned int watch_period); static bool logger_configured; logger_config()/*: rpc_get_filename("logger_config", "filename", &logger_config::get_filename4rpc, pmt::mp(""), pmt::mp(""), pmt::mp(""), "", "filename", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP), rpc_get_watchperiod("logger_config", "watch_period", &logger_config::get_watchperiod4rpc, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "watch_period", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP), rpc_get_config("logger_config", "config", &logger_config::get_config4rpc, pmt::mp(""), pmt::mp(""), pmt::mp(""), "", "filename", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP), rpc_set_config("logger_config","config", &logger_config::set_config4rpc, pmt::mp(""), pmt::mp(""), pmt::mp(""), "", "filename", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP) */ { } //!< Constructor /* rpcbasic_register_get rpc_get_filename; rpcbasic_register_get rpc_get_watchperiod; rpcbasic_register_get rpc_get_config; rpcbasic_register_set rpc_set_config; */ logger_config(logger_config const&); //! logger_get_logger_names(void); } /* namespace gr */ #endif /* HAVE_LOG4CPP */ // If Logger disable do nothing #else /* ENABLE_GR_LOG */ namespace gr { typedef void* logger_ptr; } /* namespace gr */ #define GR_LOG_DECLARE_LOGPTR(logger) #define GR_LOG_ASSIGN_LOGPTR(logger,name) #define GR_CONFIG_LOGGER(config) #define GR_CONFIG_AND_WATCH_LOGGER(config,period) #define GR_LOG_GETLOGGER(logger, name) #define GR_SET_LEVEL(name, level) #define GR_LOG_SET_LEVEL(logger, level) #define GR_GET_LEVEL(name, level) #define GR_LOG_GET_LEVEL(logger, level) #define GR_ADD_APPENDER(name,appender) #define GR_LOG_ADD_APPENDER(logger,appender) #define GR_ADD_CONSOLE_APPENDER(logger,target,pattern) #define GR_LOG_ADD_CONSOLE_APPENDER(logger,target,pattern) #define GR_ADD_FILE_APPENDER(name,filename,append,pattern) #define GR_LOG_ADD_FILE_APPENDER(logger,filename,append,pattern) #define GR_ADD_ROLLINGFILE_APPENDER(name,filename,filesize,bkup_index,append,mode,pattern) #define GR_LOG_ADD_ROLLINGFILE_APPENDER(logger,filename,filesize,bkup_index,append,mode,pattern) #define GR_GET_LOGGER_NAMES(names) #define GR_RESET_CONFIGURATION() #define GR_DEBUG(name, msg) #define GR_INFO(name, msg) #define GR_NOTICE(name, msg) #define GR_WARN(name, msg) #define GR_ERROR(name, msg) #define GR_ALERT(name, msg) #define GR_CRIT(name, msg) #define GR_FATAL(name, msg) #define GR_EMERG(name, msg) #define GR_ERRORIF(name, cond, msg) #define GR_ASSERT(name, cond, msg) #define GR_LOG_DEBUG(logger, msg) #define GR_LOG_INFO(logger, msg) #define GR_LOG_NOTICE(logger, msg) #define GR_LOG_WARN(logger, msg) #define GR_LOG_ERROR(logger, msg) #define GR_LOG_ALERT(logger, msg) #define GR_LOG_CRIT(logger, msg) #define GR_LOG_FATAL(logger, msg) #define GR_LOG_EMERG(logger, msg) #define GR_LOG_ERRORIF(logger, cond, msg) #define GR_LOG_ASSERT(logger, cond, msg) #endif /* ENABLE_GR_LOG */ namespace gr { // Even if logger is disabled we'll need for methods below to exist in python. // The macros these call will be disabled if ENABLE_GR_LOG is undefined /********************* Start Classes and Methods for Python ******************/ /*! * \brief Logger class for referencing loggers in python. Not * needed in C++ (use macros) Wraps and manipulates loggers for * python as python has no macros * \ingroup logging * */ class logger { private: /*! \brief logger pointer to logger associated wiith this wrapper class */ logger_ptr d_logger; public: /*! * \brief contructor Provide name of logger to associate with this class * \param logger_name Name of logger associated with class */ logger(std::string logger_name) { GR_LOG_ASSIGN_LOGPTR(d_logger,logger_name); }; /*! \brief Destructor */ ~logger(){;} // Wrappers for logging macros /*! \brief inline function, wrapper to set the logger level */ void set_level(std::string level){GR_LOG_SET_LEVEL(d_logger,level);} /*! \brief inline function, wrapper to get the logger level */ void get_level(std::string &level){GR_LOG_GET_LEVEL(d_logger,level);} /*! \brief inline function, wrapper for LOG4CPP_DEBUG for DEBUG message */ void debug(std::string msg){GR_LOG_DEBUG(d_logger,msg);}; /*! \brief inline function, wrapper for LOG4CPP_INFO for INFO message */ void info(std::string msg){GR_LOG_INFO(d_logger,msg);} /*! \brief inline function, wrapper for NOTICE message */ void notice(std::string msg){GR_LOG_NOTICE(d_logger,msg);} /*! \brief inline function, wrapper for LOG4CPP_WARN for WARN message */ void warn(std::string msg){GR_LOG_WARN(d_logger,msg);} /*! \brief inline function, wrapper for LOG4CPP_ERROR for ERROR message */ void error(std::string msg){GR_LOG_ERROR(d_logger,msg);} /*! \brief inline function, wrapper for NOTICE message */ void crit(std::string msg){GR_LOG_CRIT(d_logger,msg);} /*! \brief inline function, wrapper for ALERT message */ void alert(std::string msg){GR_LOG_ALERT(d_logger,msg);} /*! \brief inline function, wrapper for FATAL message */ void fatal(std::string msg){GR_LOG_FATAL(d_logger,msg);} /*! \brief inline function, wrapper for EMERG message */ void emerg(std::string msg){GR_LOG_EMERG(d_logger,msg);} /*! \brief inline function, wrapper for LOG4CPP_ASSERT for conditional ERROR message */ void errorIF(bool cond,std::string msg){GR_LOG_ERRORIF(d_logger,cond,msg);} /*! \brief inline function, wrapper for LOG4CPP_ASSERT for conditional ERROR message */ void log_assert(bool cond,std::string msg){GR_LOG_ASSERT(d_logger,cond,msg);} /*! \brief inline function, Method to add appender to logger by name (define appender in conf file) */ void add_appender(std::string appender) { GR_LOG_ADD_APPENDER(d_logger, appender); } /*! \brief inline function, Method to add console appender to logger */ void add_console_appender(std::string target,std::string pattern) { GR_LOG_ADD_CONSOLE_APPENDER(d_logger, target, pattern); } /*! \brief inline function, Method to add file appender to logger */ void add_file_appender(std::string filename, bool append, std::string pattern) { GR_LOG_ADD_FILE_APPENDER(d_logger, filename, append, pattern); } /*! \brief inline function, Method to add rolling file appender to logger */ void add_rollingfile_appender(std::string filename, size_t filesize, int bkup_index, bool append, mode_t mode, std::string pattern) { GR_LOG_ADD_ROLLINGFILE_APPENDER(d_logger,filename,filesize, bkup_index,append,mode,pattern); } }; } /* namespace gr */ /**************** Start Configuration Class and Methods for Python ************/ /*! * \brief Function to call configuration macro from python. * Note: Configuration is only updated if filename or watch_period has changed. * \param config_filename Name of configuration file * \param watch_period Seconds to wait between checking for changes in conf file. * Watch_period defaults to 0 in which case the file is not watched for changes */ GR_RUNTIME_API void gr_logger_config(const std::string config_filename, unsigned int watch_period = 0); /*! * \brief Function to return logger names to python * \return Vector of name strings * */ GR_RUNTIME_API std::vector gr_logger_get_logger_names(void); /*! * \brief Function to reset logger configuration from python * */ GR_RUNTIME_API void gr_logger_reset_config(void); #endif /* INCLUDED_GR_LOGGER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_aggregator.h0000664000175000017500000000616512207440367026453 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_AGGREGATOR_H #define RPCSERVER_AGGREGATOR_H #include #include #include #include class rpcserver_aggregator : public virtual rpcserver_base { public: rpcserver_aggregator(); virtual ~rpcserver_aggregator(); void registerConfigureCallback(const std::string &id, const configureCallback_t callback); void unregisterConfigureCallback(const std::string &id); void registerQueryCallback(const std::string &id, const queryCallback_t callback); void unregisterQueryCallback(const std::string &id); void registerServer(rpcmanager_base::rpcserver_booter_base_sptr server); const std::string& type(); const std::vector& registeredServers(); private: template struct registerConfigureCallback_f: public std::unary_function { registerConfigureCallback_f(const std::string &_id, const Tcallback _callback) : id(_id), callback(_callback) {;} void operator()(T& x) { x->i()->registerConfigureCallback(id, callback); } const std::string& id; const Tcallback& callback; }; template struct unregisterConfigureCallback_f: public std::unary_function { unregisterConfigureCallback_f(const std::string &_id) : id(_id) {;} void operator()(T& x) { x->i()->unregisterConfigureCallback(id); } const std::string& id; }; template struct registerQueryCallback_f: public std::unary_function { registerQueryCallback_f(const std::string &_id, const Tcallback _callback) : id(_id), callback(_callback) {;} void operator()(T& x) { x->i()->registerQueryCallback(id, callback); } const std::string& id; const Tcallback& callback; }; template struct unregisterQueryCallback_f: public std::unary_function { unregisterQueryCallback_f(const std::string &_id) : id(_id) {;} void operator()(T& x) { x->i()->unregisterQueryCallback(id); } const std::string& id; }; const std::string d_type; typedef std::vector rpcServerMap_t; std::vector d_registeredServers; rpcServerMap_t d_serverlist; }; #endif /* RPCSERVER_AGGREGATOR_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_booter_aggregator.h0000664000175000017500000000310712207440367030016 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_BOOTER_AGGREGATOR #define RPCSERVER_BOOTER_AGGREGATOR #include #include #include #include #include class rpcserver_server; class GR_RUNTIME_API rpcserver_booter_aggregator : public virtual rpcserver_booter_base { public: rpcserver_booter_aggregator(); ~rpcserver_booter_aggregator(); rpcserver_base* i(); const std::string& type(); const std::vector endpoints(); const std::vector& registeredServers(); protected: friend class rpcmanager; rpcserver_aggregator* agg(); private: std::string d_type; boost::shared_ptr server; }; #endif /* RPCSERVER_BOOTER_AGGREGATOR */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/random.h0000664000175000017500000000406212207440367023510 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RANDOM_H #define INCLUDED_GR_RANDOM_H #include #include // While rand(3) specifies RAND_MAX, random(3) says that the output // ranges from 0 to 2^31-1 but does not specify a macro to denote // this. We define RANDOM_MAX for cleanliness. We must omit the // definition for systems that have made the same choice. (Note that // random(3) is from 4.2BSD, and not specified by POSIX.) #ifndef RANDOM_MAX static const int RANDOM_MAX = 2147483647; // 2^31-1 #endif /* RANDOM_MAX */ #include namespace gr { /*! * \brief pseudo random number generator * \ingroup math_blk */ class GR_RUNTIME_API random { protected: static const int NTAB = 32; long d_seed; long d_iy; long d_iv[NTAB]; int d_iset; float d_gset; public: random(long seed=3021); void reseed(long seed); /*! * \brief uniform random deviate in the range [0.0, 1.0) */ float ran1(); /*! * \brief normally distributed deviate with zero mean and variance 1 */ float gasdev(); float laplacian(); float impulse(float factor); float rayleigh(); gr_complex rayleigh_complex(); }; } /* namespace gr */ #endif /* INCLUDED_GR_RANDOM_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/fxpt_nco.h0000664000175000017500000001043212207440367024046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FXPT_NCO_H #define INCLUDED_GR_FXPT_NCO_H #include #include #include #include namespace gr { /*! * \brief Numerically Controlled Oscillator (NCO) * \ingroup misc */ class /*GR_RUNTIME_API*/ fxpt_nco { uint32_t d_phase; int32_t d_phase_inc; public: fxpt_nco() : d_phase(0), d_phase_inc(0) {} ~fxpt_nco() {} // radians void set_phase(float angle) { d_phase = gr::fxpt::float_to_fixed(angle); } void adjust_phase(float delta_phase) { d_phase += gr::fxpt::float_to_fixed(delta_phase); } // angle_rate is in radians / step void set_freq(float angle_rate){ d_phase_inc = gr::fxpt::float_to_fixed(angle_rate); } // angle_rate is a delta in radians / step void adjust_freq(float delta_angle_rate) { d_phase_inc += gr::fxpt::float_to_fixed(delta_angle_rate); } // increment current phase angle void step() { d_phase += d_phase_inc; } void step(int n) { d_phase += d_phase_inc * n; } // units are radians / step float get_phase() const { return gr::fxpt::fixed_to_float(d_phase); } float get_freq() const { return gr::fxpt::fixed_to_float(d_phase_inc); } // compute sin and cos for current phase angle void sincos(float *sinx, float *cosx) const { *sinx = gr::fxpt::sin(d_phase); *cosx = gr::fxpt::cos(d_phase); } // compute cos and sin for a block of phase angles void sincos(gr_complex *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = gr_complex(gr::fxpt::cos(d_phase) * ampl, gr::fxpt::sin(d_phase) * ampl); step(); } } // compute sin for a block of phase angles void sin(float *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (float)(gr::fxpt::sin(d_phase) * ampl); step(); } } // compute cos for a block of phase angles void cos(float *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (float)(gr::fxpt::cos(d_phase) * ampl); step (); } } // compute sin for a block of phase angles void sin(short *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (short)(gr::fxpt::sin(d_phase) * ampl); step(); } } // compute cos for a block of phase angles void cos(short *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (short)(gr::fxpt::cos(d_phase) * ampl); step(); } } // compute sin for a block of phase angles void sin(int *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (int)(gr::fxpt::sin(d_phase) * ampl); step(); } } // compute cos for a block of phase angles void cos(int *output, int noutput_items, double ampl=1.0) { for(int i = 0; i < noutput_items; i++) { output[i] = (int)(gr::fxpt::cos(d_phase) * ampl); step(); } } // compute cos or sin for current phase angle float cos() const { return gr::fxpt::cos(d_phase); } float sin() const { return gr::fxpt::sin(d_phase); } }; } /* namespace gr */ #endif /* INCLUDED_GR_FXPT_NCO_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_booter_ice.h0000664000175000017500000000271212207440367026435 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_BOOTER_ICE_H #define RPCSERVER_BOOTER_ICE_H #include #include #include class rpcserver_base; class rpcserver_ice; class rpcserver_booter_ice : public virtual rpcserver_booter_base, public virtual ice_server_template { public: rpcserver_booter_ice(); ~rpcserver_booter_ice(); rpcserver_base* i(); const std::string & type() {return d_type;} const std::vector endpoints(); private: std::string d_type; }; #endif /* RPCSERVER_BOOTER_ICE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcpmtconverters_ice.h0000664000175000017500000000217712207440367026475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCPMTCONVERTERS_ICE_H #define RPCPMTCONVERTERS_ICE_H #include #include namespace rpcpmtconverter { pmt::pmt_t to_pmt(const GNURadio::KnobPtr& knob, const Ice::Current& c); GNURadio::KnobPtr from_pmt(const pmt::pmt_t& knob, const Ice::Current& c); } #endif /* RPCPMTCONVERTERS_ICE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/block_gateway.h0000664000175000017500000002175612244272666025062 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_RUNTIME_BLOCK_GATEWAY_H #define INCLUDED_RUNTIME_BLOCK_GATEWAY_H #include #include #include namespace gr { /*! * The work type enum tells the gateway what kind of block to * implement. The choices are familiar gnuradio block overloads * (sync, decim, interp). */ enum block_gw_work_type { GR_BLOCK_GW_WORK_GENERAL, GR_BLOCK_GW_WORK_SYNC, GR_BLOCK_GW_WORK_DECIM, GR_BLOCK_GW_WORK_INTERP, }; enum tag_propagation_policy_t { TPP_DONT = 0, TPP_ALL_TO_ALL = 1, TPP_ONE_TO_ONE = 2 }; /*! * Shared message structure between python and gateway. * Each action type represents a scheduler-called function. */ struct block_gw_message_type { enum action_type { ACTION_GENERAL_WORK, //dispatch work ACTION_WORK, //dispatch work ACTION_FORECAST, //dispatch forecast ACTION_START, //dispatch start ACTION_STOP, //dispatch stop }; action_type action; int general_work_args_noutput_items; std::vector general_work_args_ninput_items; std::vector general_work_args_input_items; //TODO this should be const void*, but swig cant int cast it right std::vector general_work_args_output_items; int general_work_args_return_value; int work_args_ninput_items; int work_args_noutput_items; std::vector work_args_input_items; //TODO this should be const void*, but swig cant int cast it right std::vector work_args_output_items; int work_args_return_value; int forecast_args_noutput_items; std::vector forecast_args_ninput_items_required; bool start_args_return_value; bool stop_args_return_value; }; /*! * The gateway block which performs all the magic. * * The gateway provides access to all the gr::block routines. * The methods prefixed with gr::block__ are renamed * to class methods without the prefix in python. */ class GR_RUNTIME_API block_gateway : virtual public gr::block { public: // gr::block_gateway::sptr typedef boost::shared_ptr sptr; /*! * Make a new gateway block. * \param handler the swig director object with callback * \param name the name of the block (Ex: "Shirley") * \param in_sig the input signature for this block * \param out_sig the output signature for this block * \param work_type the type of block overload to implement * \param factor the decimation or interpolation factor * \return a new gateway block */ static sptr make(gr::feval_ll *handler, const std::string &name, gr::io_signature::sptr in_sig, gr::io_signature::sptr out_sig, const block_gw_work_type work_type, const unsigned factor); //! Provide access to the shared message object virtual block_gw_message_type &block_message(void) = 0; long block__unique_id(void) const { return gr::block::unique_id(); } std::string block__name(void) const { return gr::block::name(); } unsigned block__history(void) const { return gr::block::history(); } void block__set_history(unsigned history) { return gr::block::set_history(history); } void block__set_fixed_rate(bool fixed_rate) { return gr::block::set_fixed_rate(fixed_rate); } bool block__fixed_rate(void) const { return gr::block::fixed_rate(); } void block__set_output_multiple(int multiple) { return gr::block::set_output_multiple(multiple); } int block__output_multiple(void) const { return gr::block::output_multiple(); } void block__consume(int which_input, int how_many_items) { return gr::block::consume(which_input, how_many_items); } void block__consume_each(int how_many_items) { return gr::block::consume_each(how_many_items); } void block__produce(int which_output, int how_many_items) { return gr::block::produce(which_output, how_many_items); } void block__set_relative_rate(double relative_rate) { return gr::block::set_relative_rate(relative_rate); } double block__relative_rate(void) const { return gr::block::relative_rate(); } uint64_t block__nitems_read(unsigned int which_input) { return gr::block::nitems_read(which_input); } uint64_t block__nitems_written(unsigned int which_output) { return gr::block::nitems_written(which_output); } block::tag_propagation_policy_t block__tag_propagation_policy(void) { return gr::block::tag_propagation_policy(); } void block__set_tag_propagation_policy(block::tag_propagation_policy_t p) { return gr::block::set_tag_propagation_policy(p); } void block__add_item_tag(unsigned int which_output, const tag_t &tag) { return gr::block::add_item_tag(which_output, tag); } void block__add_item_tag(unsigned int which_output, uint64_t abs_offset, const pmt::pmt_t &key, const pmt::pmt_t &value, const pmt::pmt_t &srcid=pmt::PMT_F) { return gr::block::add_item_tag(which_output, abs_offset, key, value, srcid); } std::vector block__get_tags_in_range(unsigned int which_input, uint64_t abs_start, uint64_t abs_end) { std::vector tags; gr::block::get_tags_in_range(tags, which_input, abs_start, abs_end); return tags; } std::vector block__get_tags_in_range(unsigned int which_input, uint64_t abs_start, uint64_t abs_end, const pmt::pmt_t &key) { std::vector tags; gr::block::get_tags_in_range(tags, which_input, abs_start, abs_end, key); return tags; } /* Message passing interface */ void block__message_port_register_in(pmt::pmt_t port_id) { gr::basic_block::message_port_register_in(port_id); } void block__message_port_register_out(pmt::pmt_t port_id) { gr::basic_block::message_port_register_out(port_id); } void block__message_port_pub(pmt::pmt_t port_id, pmt::pmt_t msg) { gr::basic_block::message_port_pub(port_id, msg); } void block__message_port_sub(pmt::pmt_t port_id, pmt::pmt_t target) { gr::basic_block::message_port_sub(port_id, target); } void block__message_port_unsub(pmt::pmt_t port_id, pmt::pmt_t target) { gr::basic_block::message_port_unsub(port_id, target); } pmt::pmt_t block__message_subscribers(pmt::pmt_t which_port) { return gr::basic_block::message_subscribers(which_port); } pmt::pmt_t block__message_ports_in() { return gr::basic_block::message_ports_in(); } pmt::pmt_t block__message_ports_out() { return gr::basic_block::message_ports_out(); } void set_msg_handler_feval(pmt::pmt_t which_port, gr::feval_p *msg_handler) { if(msg_queue.find(which_port) == msg_queue.end()) { throw std::runtime_error("attempt to set_msg_handler_feval() on bad input message port!"); } d_msg_handlers_feval[which_port] = msg_handler; } protected: typedef std::map msg_handlers_feval_t; msg_handlers_feval_t d_msg_handlers_feval; bool has_msg_handler(pmt::pmt_t which_port) { return (d_msg_handlers_feval.find(which_port) != d_msg_handlers_feval.end()); } void dispatch_msg(pmt::pmt_t which_port, pmt::pmt_t msg) { // Is there a handler? if(d_msg_handlers_feval.find(which_port) != d_msg_handlers_feval.end()) { d_msg_handlers_feval[which_port]->calleval(msg); // Yes, invoke it. } else { // Pass to generic dispatcher if not found gr::basic_block::dispatch_msg(which_port, msg); } } }; } /* namespace gr */ #endif /* INCLUDED_RUNTIME_BLOCK_GATEWAY_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/top_block.h0000664000175000017500000001132612207440367024205 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TOP_BLOCK_H #define INCLUDED_GR_TOP_BLOCK_H #include #include namespace gr { class top_block_impl; GR_RUNTIME_API top_block_sptr make_top_block(const std::string &name); /*! *\brief Top-level hierarchical block representing a flowgraph * \ingroup container_blk */ class GR_RUNTIME_API top_block : public hier_block2 { private: friend GR_RUNTIME_API top_block_sptr make_top_block(const std::string &name); top_block_impl *d_impl; protected: top_block(const std::string &name); public: ~top_block(); /*! * \brief The simple interface to running a flowgraph. * * Calls start() then wait(). Used to run a flowgraph that will * stop on its own, or when another thread will call stop(). * * \param max_noutput_items the maximum number of output items * allowed for any block in the flowgraph. This passes through to * the start function; see that function for more details. */ void run(int max_noutput_items=100000000); /*! * Start the contained flowgraph. Creates one or more threads to * execute the flow graph. Returns to the caller once the threads * are created. Calling start() on a top_block that is already * started IS an error. * * \param max_noutput_items the maximum number of output items * allowed for any block in the flowgraph; the noutput_items can * always be less than this, but this will cap it as a * maximum. Use this to adjust the maximum latency a flowgraph can * exhibit. */ void start(int max_noutput_items=100000000); /*! * Stop the running flowgraph. Notifies each thread created by the * scheduler to shutdown, then returns to caller. Calling stop() * on a top_block that is already stopped IS NOT an error. */ void stop(); /*! * Wait for a flowgraph to complete. Flowgraphs complete when * either (1) all blocks indicate that they are done (typically * only when using blocks.file_source, or blocks.head, or (2) * after stop() has been called to request shutdown. Calling wait * on a top_block that is not running IS NOT an error (wait * returns w/o blocking). */ void wait(); /*! * Lock a flowgraph in preparation for reconfiguration. When an * equal number of calls to lock() and unlock() have occurred, the * flowgraph will be reconfigured. * * N.B. lock() and unlock() may not be called from a flowgraph * thread (E.g., block::work method) or deadlock will occur * when reconfiguration happens. */ virtual void lock(); /*! * Unlock a flowgraph in preparation for reconfiguration. When an * equal number of calls to lock() and unlock() have occurred, the * flowgraph will be reconfigured. * * N.B. lock() and unlock() may not be called from a flowgraph thread * (E.g., block::work method) or deadlock will occur when * reconfiguration happens. */ virtual void unlock(); /*! * Returns a string that lists the edge connections in the * flattened flowgraph. */ std::string edge_list(); /*! * Returns a string that lists the msg edge connections in the * flattened flowgraph. */ std::string msg_edge_list(); /*! * Displays flattened flowgraph edges and block connectivity */ void dump(); //! Get the number of max noutput_items in the flowgraph int max_noutput_items(); //! Set the maximum number of noutput_items in the flowgraph void set_max_noutput_items(int nmax); top_block_sptr to_top_block(); // Needed for Python type coercion void setup_rpc(); }; inline top_block_sptr cast_to_top_block_sptr(basic_block_sptr block) { return boost::dynamic_pointer_cast(block); } } /* namespce gr */ #endif /* INCLUDED_GR_TOP_BLOCK_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sync_decimator.h0000664000175000017500000000442312207440367025234 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004, 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_SYNC_DECIMATOR_H #define INCLUDED_GR_RUNTIME_SYNC_DECIMATOR_H #include #include namespace gr { /*! * \brief synchronous N:1 input to output with history * \ingroup base_blk * * Override work to provide the signal processing implementation. */ class GR_RUNTIME_API sync_decimator : public sync_block { private: unsigned d_decimation; protected: sync_decimator(void) {} // allows pure virtual interface sub-classes sync_decimator(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature, unsigned decimation); public: unsigned decimation() const { return d_decimation; } void set_decimation(unsigned decimation) { d_decimation = decimation; set_relative_rate(1.0 / decimation); } // gr::sync_decimator overrides these to assist work void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); // derived classes should override work int fixed_rate_ninput_to_noutput(int ninput); int fixed_rate_noutput_to_ninput(int noutput); }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_SYNC_DECIMATOR_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/tags.h0000664000175000017500000000352312207440367023167 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAGS_H #define INCLUDED_GR_TAGS_H #include #include namespace gr { struct GR_RUNTIME_API tag_t { //! the item \p tag occurred at (as a uint64_t) uint64_t offset; //! the key of \p tag (as a PMT symbol) pmt::pmt_t key; //! the value of \p tag (as a PMT) pmt::pmt_t value; //! the source ID of \p tag (as a PMT) pmt::pmt_t srcid; //! Used by gr_buffer to mark a tagged as deleted by a specific block. You can usually ignore this. std::vector marked_deleted; /*! * Comparison function to test which tag, \p x or \p y, came * first in time */ static inline bool offset_compare(const tag_t &x, const tag_t &y) { return x.offset < y.offset; } inline bool operator == (const tag_t &t) const { return (t.key == key) && (t.value == value) && \ (t.srcid == srcid) && (t.offset == offset); } }; } /* namespace gr */ #endif /*INCLUDED_GR_TAGS_H*/ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/io_signature.h0000664000175000017500000000772312207440367024727 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_IO_SIGNATURE_H #define INCLUDED_IO_SIGNATURE_H #include #include namespace gr { /*! * \brief i/o signature for input and output ports. * \brief misc */ class GR_RUNTIME_API io_signature { int d_min_streams; int d_max_streams; std::vector d_sizeof_stream_item; io_signature(int min_streams, int max_streams, const std::vector &sizeof_stream_items); public: typedef boost::shared_ptr sptr; static const int IO_INFINITE = -1; ~io_signature(); /*! * \brief Create an i/o signature * * \ingroup internal * \param min_streams specify minimum number of streams (>= 0) * \param max_streams specify maximum number of streams (>= min_streams or -1 -> infinite) * \param sizeof_stream_item specify the size of the items in each stream */ static sptr make(int min_streams, int max_streams, int sizeof_stream_item); /*! * \brief Create an i/o signature * * \param min_streams specify minimum number of streams (>= 0) * \param max_streams specify maximum number of streams (>= min_streams or -1 -> infinite) * \param sizeof_stream_item1 specify the size of the items in the first stream * \param sizeof_stream_item2 specify the size of the items in the second and subsequent streams */ static sptr make2(int min_streams, int max_streams, int sizeof_stream_item1, int sizeof_stream_item2); /*! * \brief Create an i/o signature * * \param min_streams specify minimum number of streams (>= 0) * \param max_streams specify maximum number of streams (>= min_streams or -1 -> infinite) * \param sizeof_stream_item1 specify the size of the items in the first stream * \param sizeof_stream_item2 specify the size of the items in the second stream * \param sizeof_stream_item3 specify the size of the items in the third and subsequent streams */ static sptr make3(int min_streams, int max_streams, int sizeof_stream_item1, int sizeof_stream_item2, int sizeof_stream_item3); /*! * \brief Create an i/o signature * * \param min_streams specify minimum number of streams (>= 0) * \param max_streams specify maximum number of streams (>= min_streams or -1 -> infinite) * \param sizeof_stream_items specify the size of the items in the streams * * If there are more streams than there are entries in * sizeof_stream_items, the value of the last entry in * sizeof_stream_items is used for the missing values. * sizeof_stream_items must contain at least 1 entry. */ static sptr makev(int min_streams, int max_streams, const std::vector &sizeof_stream_items); int min_streams() const { return d_min_streams; } int max_streams() const { return d_max_streams; } int sizeof_stream_item(int index) const; std::vector sizeof_stream_items() const; }; } /* namespace gr */ #endif /* INCLUDED_IO_SIGNATURE_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/math.h0000664000175000017500000001204412207440367023160 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2005,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * mathematical odds and ends. */ #ifndef _GR_MATH_H_ #define _GR_MATH_H_ #include #include #include namespace gr { static inline bool is_power_of_2(long x) { return x != 0 && (x & (x-1)) == 0; } /*! * \brief Fast arc tangent using table lookup and linear interpolation * \ingroup misc * * \param y component of input vector * \param x component of input vector * \returns float angle angle of vector (x, y) in radians * * This function calculates the angle of the vector (x,y) based on a * table lookup and linear interpolation. The table uses a 256 point * table covering -45 to +45 degrees and uses symetry to determine * the final angle value in the range of -180 to 180 degrees. Note * that this function uses the small angle approximation for values * close to zero. This routine calculates the arc tangent with an * average error of +/- 0.045 degrees. */ GR_RUNTIME_API float fast_atan2f(float y, float x); static inline float fast_atan2f(gr_complex z) { return fast_atan2f(z.imag(), z.real()); } /* This bounds x by +/- clip without a branch */ static inline float branchless_clip(float x, float clip) { float x1 = fabsf(x+clip); float x2 = fabsf(x-clip); x1 -= x2; return 0.5*x1; } static inline float clip(float x, float clip) { float y = x; if(x > clip) y = clip; else if(x < -clip) y = -clip; return y; } // Slicer Functions static inline unsigned int binary_slicer(float x) { if(x >= 0) return 1; else return 0; } static inline unsigned int quad_45deg_slicer(float r, float i) { unsigned int ret = 0; if((r >= 0) && (i >= 0)) ret = 0; else if((r < 0) && (i >= 0)) ret = 1; else if((r < 0) && (i < 0)) ret = 2; else ret = 3; return ret; } static inline unsigned int quad_0deg_slicer(float r, float i) { unsigned int ret = 0; if(fabsf(r) > fabsf(i)) { if(r > 0) ret = 0; else ret = 2; } else { if(i > 0) ret = 1; else ret = 3; } return ret; } static inline unsigned int quad_45deg_slicer(gr_complex x) { return quad_45deg_slicer(x.real(), x.imag()); } static inline unsigned int quad_0deg_slicer(gr_complex x) { return quad_0deg_slicer(x.real(), x.imag()); } // Branchless Slicer Functions static inline unsigned int branchless_binary_slicer(float x) { return (x >= 0); } static inline unsigned int branchless_quad_0deg_slicer(float r, float i) { unsigned int ret = 0; ret = (fabsf(r) > fabsf(i)) * (((r < 0) << 0x1)); // either 0 (00) or 2 (10) ret |= (fabsf(i) > fabsf(r)) * (((i < 0) << 0x1) | 0x1); // either 1 (01) or 3 (11) return ret; } static inline unsigned int branchless_quad_0deg_slicer(gr_complex x) { return branchless_quad_0deg_slicer(x.real(), x.imag()); } static inline unsigned int branchless_quad_45deg_slicer(float r, float i) { char ret = (r <= 0); ret |= ((i <= 0) << 1); return (ret ^ ((ret & 0x2) >> 0x1)); } static inline unsigned int branchless_quad_45deg_slicer(gr_complex x) { return branchless_quad_45deg_slicer(x.real(), x.imag()); } /*! * \param x any value * \param pow2 must be a power of 2 * \returns \p x rounded down to a multiple of \p pow2. */ static inline size_t p2_round_down(size_t x, size_t pow2) { return x & -pow2; } /*! * \param x any value * \param pow2 must be a power of 2 * \returns \p x rounded up to a multiple of \p pow2. */ static inline size_t p2_round_up(size_t x, size_t pow2) { return p2_round_down(x + pow2 - 1, pow2); } /*! * \param x any value * \param pow2 must be a power of 2 * \returns \p x modulo \p pow2. */ static inline size_t p2_modulo(size_t x, size_t pow2) { return x & (pow2 - 1); } /*! * \param x any value * \param pow2 must be a power of 2 * \returns \p pow2 - (\p x modulo \p pow2). */ static inline size_t p2_modulo_neg(size_t x, size_t pow2) { return pow2 - p2_modulo(x, pow2); } } /* namespace gr */ #endif /* _GR_MATH_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/block.h0000664000175000017500000006154212237515111023321 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_BLOCK_H #define INCLUDED_GR_RUNTIME_BLOCK_H #include #include #include #include namespace gr { /*! * \brief The abstract base class for all 'terminal' processing blocks. * \ingroup base_blk * * A signal processing flow is constructed by creating a tree of * hierarchical blocks, which at any level may also contain terminal * nodes that actually implement signal processing functions. This * is the base class for all such leaf nodes. * * Blocks have a set of input streams and output streams. The * input_signature and output_signature define the number of input * streams and output streams respectively, and the type of the data * items in each stream. * * Although blocks may consume data on each input stream at a * different rate, all outputs streams must produce data at the same * rate. That rate may be different from any of the input rates. * * User derived blocks override two methods, forecast and * general_work, to implement their signal processing * behavior. forecast is called by the system scheduler to determine * how many items are required on each input stream in order to * produce a given number of output items. * * general_work is called to perform the signal processing in the * block. It reads the input items and writes the output items. */ class GR_RUNTIME_API block : public basic_block { public: //! Magic return values from general_work enum { WORK_CALLED_PRODUCE = -2, WORK_DONE = -1 }; enum tag_propagation_policy_t { TPP_DONT = 0, TPP_ALL_TO_ALL = 1, TPP_ONE_TO_ONE = 2 }; virtual ~block(); /*! * Assume block computes y_i = f(x_i, x_i-1, x_i-2, x_i-3...) * History is the number of x_i's that are examined to produce one y_i. * This comes in handy for FIR filters, where we use history to * ensure that our input contains the appropriate "history" for the * filter. History should be equal to the number of filter taps. */ unsigned history() const; void set_history(unsigned history); /*! * Declares the block's delay in samples. Since the delay of * blocks like filters is derived from the taps and not the block * itself, we cannot automatically calculate this value and so * leave it as a user-defined property. It defaults to 0 is not * set. * * This does not actively set the delay; it just tells the * scheduler what the delay is. * * This delay is mostly used to adjust the placement of the tags * and is not currently used for any signal processing. When a tag * is passed through a block with internal delay, its location * should be moved based on the delay of the block. This interface * allows us to tell the scheduler this value. * * \param which The buffer on which to set the delay. * \param delay The sample delay of the data stream. */ void declare_sample_delay(int which, unsigned delay); /*! * Convenience wrapper to gr::block::declare_delay(int which, unsigned delay) * to set all ports to the same delay. */ void declare_sample_delay(unsigned delay); /*! * Gets the delay of the block. Since the delay of blocks like * filters is derived from the taps and not the block itself, we * cannot automatically calculate this value and so leave it as a * user-defined property. It defaults to 0 is not set. * * \param which Which port from which to get the sample delay. */ unsigned sample_delay(int which) const; /*! * \brief Return true if this block has a fixed input to output rate. * * If true, then fixed_rate_in_to_out and fixed_rate_out_to_in may be called. */ bool fixed_rate() const { return d_fixed_rate; } // ---------------------------------------------------------------- // override these to define your behavior // ---------------------------------------------------------------- /*! * \brief Estimate input requirements given output request * * \param noutput_items number of output items to produce * \param ninput_items_required number of input items required on each input stream * * Given a request to product \p noutput_items, estimate the * number of data items required on each input stream. The * estimate doesn't have to be exact, but should be close. */ virtual void forecast(int noutput_items, gr_vector_int &ninput_items_required); /*! * \brief compute output items from input items * * \param noutput_items number of output items to write on each output stream * \param ninput_items number of input items available on each input stream * \param input_items vector of pointers to the input items, one entry per input stream * \param output_items vector of pointers to the output items, one entry per output stream * * \returns number of items actually written to each output stream, or -1 on EOF. * It is OK to return a value less than noutput_items. -1 <= return value <= noutput_items * * general_work must call consume or consume_each to indicate how * many items were consumed on each input stream. */ virtual int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); /*! * \brief Called to enable drivers, etc for i/o devices. * * This allows a block to enable an associated driver to begin * transfering data just before we start to execute the scheduler. * The end result is that this reduces latency in the pipeline * when dealing with audio devices, usrps, etc. */ virtual bool start(); /*! * \brief Called to disable drivers, etc for i/o devices. */ virtual bool stop(); // ---------------------------------------------------------------- /*! * \brief Constrain the noutput_items argument passed to forecast and general_work * * set_output_multiple causes the scheduler to ensure that the * noutput_items argument passed to forecast and general_work will * be an integer multiple of \param multiple The default value of * output multiple is 1. */ void set_output_multiple(int multiple); int output_multiple() const { return d_output_multiple; } bool output_multiple_set() const { return d_output_multiple_set; } /*! * \brief Constrains buffers to work on a set item alignment (for SIMD) * * set_alignment_multiple causes the scheduler to ensure that the * noutput_items argument passed to forecast and general_work will * be an integer multiple of \param multiple The default value is * 1. * * This control is similar to the output_multiple setting, except * that if the number of items passed to the block is less than * the output_multiple, this value is ignored and the block can * produce like normal. The d_unaligned value is set to the number * of items the block is off by. In the next call to general_work, * the noutput_items is set to d_unaligned or less until * d_unaligned==0. The buffers are now aligned again and the * aligned calls can be performed again. */ void set_alignment(int multiple); int alignment() const { return d_output_multiple; } void set_unaligned(int na); int unaligned() const { return d_unaligned; } void set_is_unaligned(bool u); bool is_unaligned() const { return d_is_unaligned; } /*! * \brief Tell the scheduler \p how_many_items of input stream \p * which_input were consumed. */ void consume(int which_input, int how_many_items); /*! * \brief Tell the scheduler \p how_many_items were consumed on * each input stream. */ void consume_each(int how_many_items); /*! * \brief Tell the scheduler \p how_many_items were produced on * output stream \p which_output. * * If the block's general_work method calls produce, \p * general_work must return WORK_CALLED_PRODUCE. */ void produce(int which_output, int how_many_items); /*! * \brief Set the approximate output rate / input rate * * Provide a hint to the buffer allocator and scheduler. * The default relative_rate is 1.0 * * decimators have relative_rates < 1.0 * interpolators have relative_rates > 1.0 */ void set_relative_rate(double relative_rate); /*! * \brief return the approximate output rate / input rate */ double relative_rate() const { return d_relative_rate; } /* * The following two methods provide special case info to the * scheduler in the event that a block has a fixed input to output * ratio. sync_block, sync_decimator and * sync_interpolator override these. If you're fixed rate, * subclass one of those. */ /*! * \brief Given ninput samples, return number of output samples that will be produced. * N.B. this is only defined if fixed_rate returns true. * Generally speaking, you don't need to override this. */ virtual int fixed_rate_ninput_to_noutput(int ninput); /*! * \brief Given noutput samples, return number of input samples required to produce noutput. * N.B. this is only defined if fixed_rate returns true. * Generally speaking, you don't need to override this. */ virtual int fixed_rate_noutput_to_ninput(int noutput); /*! * \brief Return the number of items read on input stream which_input */ uint64_t nitems_read(unsigned int which_input); /*! * \brief Return the number of items written on output stream which_output */ uint64_t nitems_written(unsigned int which_output); /*! * \brief Asks for the policy used by the scheduler to moved tags downstream. */ tag_propagation_policy_t tag_propagation_policy(); /*! * \brief Set the policy by the scheduler to determine how tags are moved downstream. */ void set_tag_propagation_policy(tag_propagation_policy_t p); /*! * \brief Return the minimum number of output items this block can * produce during a call to work. * * Should be 0 for most blocks. Useful if we're dealing with * packets and the block produces one packet per call to work. */ int min_noutput_items() const { return d_min_noutput_items; } /*! * \brief Set the minimum number of output items this block can * produce during a call to work. * * \param m the minimum noutput_items this block can produce. */ void set_min_noutput_items(int m) { d_min_noutput_items = m; } /*! * \brief Return the maximum number of output items this block will * handle during a call to work. */ int max_noutput_items(); /*! * \brief Set the maximum number of output items this block will * handle during a call to work. * * \param m the maximum noutput_items this block will handle. */ void set_max_noutput_items(int m); /*! * \brief Clear the switch for using the max_noutput_items value of this block. * * When is_set_max_noutput_items() returns 'true', the scheduler * will use the value returned by max_noutput_items() to limit the * size of the number of items possible for this block's work * function. If is_set_max_notput_items() returns 'false', then * the scheduler ignores the internal value and uses the value set * globally in the top_block. * * Use this value to clear the 'is_set' flag so the scheduler will * ignore this. Use the set_max_noutput_items(m) call to both set * a new value for max_noutput_items and to reenable its use in * the scheduler. */ void unset_max_noutput_items(); /*! * \brief Ask the block if the flag is or is not set to use the * internal value of max_noutput_items during a call to work. */ bool is_set_max_noutput_items(); /* * Used to expand the vectors that hold the min/max buffer sizes. * * Specifically, when -1 is used, the vectors are just initialized * with 1 value; this is used by the flat_flowgraph to expand when * required to add a new value for new ports on these blocks. */ void expand_minmax_buffer(int port); /*! * \brief Returns max buffer size on output port \p i. */ long max_output_buffer(size_t i); /*! * \brief Sets max buffer size on all output ports. */ void set_max_output_buffer(long max_output_buffer); /*! * \brief Sets max buffer size on output port \p port. */ void set_max_output_buffer(int port, long max_output_buffer); /*! * \brief Returns min buffer size on output port \p i. */ long min_output_buffer(size_t i); /*! * \brief Sets min buffer size on all output ports. */ void set_min_output_buffer(long min_output_buffer); /*! * \brief Sets min buffer size on output port \p port. */ void set_min_output_buffer(int port, long min_output_buffer); // --------------- Performance counter functions ------------- /*! * \brief Gets instantaneous noutput_items performance counter. */ float pc_noutput_items(); /*! * \brief Gets average noutput_items performance counter. */ float pc_noutput_items_avg(); /*! * \brief Gets variance of noutput_items performance counter. */ float pc_noutput_items_var(); /*! * \brief Gets instantaneous num items produced performance counter. */ float pc_nproduced(); /*! * \brief Gets average num items produced performance counter. */ float pc_nproduced_avg(); /*! * \brief Gets variance of num items produced performance counter. */ float pc_nproduced_var(); /*! * \brief Gets instantaneous fullness of \p which input buffer. */ float pc_input_buffers_full(int which); /*! * \brief Gets average fullness of \p which input buffer. */ float pc_input_buffers_full_avg(int which); /*! * \brief Gets variance of fullness of \p which input buffer. */ float pc_input_buffers_full_var(int which); /*! * \brief Gets instantaneous fullness of all input buffers. */ std::vector pc_input_buffers_full(); /*! * \brief Gets average fullness of all input buffers. */ std::vector pc_input_buffers_full_avg(); /*! * \brief Gets variance of fullness of all input buffers. */ std::vector pc_input_buffers_full_var(); /*! * \brief Gets instantaneous fullness of \p which input buffer. */ float pc_output_buffers_full(int which); /*! * \brief Gets average fullness of \p which input buffer. */ float pc_output_buffers_full_avg(int which); /*! * \brief Gets variance of fullness of \p which input buffer. */ float pc_output_buffers_full_var(int which); /*! * \brief Gets instantaneous fullness of all output buffers. */ std::vector pc_output_buffers_full(); /*! * \brief Gets average fullness of all output buffers. */ std::vector pc_output_buffers_full_avg(); /*! * \brief Gets variance of fullness of all output buffers. */ std::vector pc_output_buffers_full_var(); /*! * \brief Gets instantaneous clock cycles spent in work. */ float pc_work_time(); /*! * \brief Gets average clock cycles spent in work. */ float pc_work_time_avg(); /*! * \brief Gets average clock cycles spent in work. */ float pc_work_time_var(); /*! * \brief Gets total clock cycles spent in work. */ float pc_work_time_total(); /*! * \brief Resets the performance counters */ void reset_perf_counters(); /*! * \brief Sets up export of perf. counters to ControlPort. Only * called by the scheduler. */ void setup_pc_rpc(); /*! * \brief Checks if this block is already exporting perf. counters * to ControlPort. */ bool is_pc_rpc_set() { return d_pc_rpc_set; } /*! * \brief If the block calls this in its constructor, it's * perf. counters will not be exported. */ void no_pc_rpc() { d_pc_rpc_set = true; } // ---------------------------------------------------------------------------- // Functions to handle thread affinity /*! * \brief Set the thread's affinity to processor core \p n. * * \param mask a vector of ints of the core numbers available to this block. */ void set_processor_affinity(const std::vector &mask); /*! * \brief Remove processor affinity to a specific core. */ void unset_processor_affinity(); /*! * \brief Get the current processor affinity. */ std::vector processor_affinity() { return d_affinity; } /*! * \brief Get the current thread priority in use */ int active_thread_priority(); /*! * \brief Get the current thread priority stored */ int thread_priority(); /*! * \brief Set the current thread priority */ int set_thread_priority(int priority); bool update_rate() const; // ---------------------------------------------------------------------------- private: int d_output_multiple; bool d_output_multiple_set; int d_unaligned; bool d_is_unaligned; double d_relative_rate; // approx output_rate / input_rate block_detail_sptr d_detail; // implementation details unsigned d_history; unsigned d_attr_delay; // the block's sample delay bool d_fixed_rate; bool d_max_noutput_items_set; // if d_max_noutput_items is valid int d_max_noutput_items; // value of max_noutput_items for this block int d_min_noutput_items; tag_propagation_policy_t d_tag_propagation_policy; // policy for moving tags downstream std::vector d_affinity; // thread affinity proc. mask int d_priority; // thread priority level bool d_pc_rpc_set; bool d_update_rate; // should sched update rel rate? protected: block(void) {} // allows pure virtual interface sub-classes block(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); void set_fixed_rate(bool fixed_rate) { d_fixed_rate = fixed_rate; } /*! * \brief Adds a new tag onto the given output buffer. * * \param which_output an integer of which output stream to attach the tag * \param abs_offset a uint64 number of the absolute item number * assicated with the tag. Can get from nitems_written. * \param key the tag key as a PMT symbol * \param value any PMT holding any value for the given key * \param srcid optional source ID specifier; defaults to PMT_F */ inline void add_item_tag(unsigned int which_output, uint64_t abs_offset, const pmt::pmt_t &key, const pmt::pmt_t &value, const pmt::pmt_t &srcid=pmt::PMT_F) { tag_t tag; tag.offset = abs_offset; tag.key = key; tag.value = value; tag.srcid = srcid; this->add_item_tag(which_output, tag); } /*! * \brief Adds a new tag onto the given output buffer. * * \param which_output an integer of which output stream to attach the tag * \param tag the tag object to add */ void add_item_tag(unsigned int which_output, const tag_t &tag); /*! * \brief Removes a tag from the given input buffer. * * \param which_input an integer of which input stream to remove the tag from * \param abs_offset a uint64 number of the absolute item number * assicated with the tag. Can get from nitems_written. * \param key the tag key as a PMT symbol * \param value any PMT holding any value for the given key * \param srcid optional source ID specifier; defaults to PMT_F * * If no such tag is found, does nothing. */ inline void remove_item_tag(unsigned int which_input, uint64_t abs_offset, const pmt::pmt_t &key, const pmt::pmt_t &value, const pmt::pmt_t &srcid=pmt::PMT_F) { tag_t tag; tag.offset = abs_offset; tag.key = key; tag.value = value; tag.srcid = srcid; this->remove_item_tag(which_input, tag); } /*! * \brief Removes a tag from the given input buffer. * * If no such tag is found, does nothing. * * \param which_input an integer of which input stream to remove the tag from * \param tag the tag object to remove */ void remove_item_tag(unsigned int which_input, const tag_t &tag); /*! * \brief Given a [start,end), returns a vector of all tags in the range. * * Range of counts is from start to end-1. * * Tags are tuples of: * (item count, source id, key, value) * * \param v a vector reference to return tags into * \param which_input an integer of which input stream to pull from * \param abs_start a uint64 count of the start of the range of interest * \param abs_end a uint64 count of the end of the range of interest */ void get_tags_in_range(std::vector &v, unsigned int which_input, uint64_t abs_start, uint64_t abs_end); /*! * \brief Given a [start,end), returns a vector of all tags in the * range with a given key. * * Range of counts is from start to end-1. * * Tags are tuples of: * (item count, source id, key, value) * * \param v a vector reference to return tags into * \param which_input an integer of which input stream to pull from * \param abs_start a uint64 count of the start of the range of interest * \param abs_end a uint64 count of the end of the range of interest * \param key a PMT symbol key to filter only tags of this key */ void get_tags_in_range(std::vector &v, unsigned int which_input, uint64_t abs_start, uint64_t abs_end, const pmt::pmt_t &key); void enable_update_rate(bool en); std::vector d_max_output_buffer; std::vector d_min_output_buffer; /*! Used by block's setters and work functions to make * setting/resetting of parameters thread-safe. * * Used by calling gr::thread::scoped_lock l(d_setlock); */ gr::thread::mutex d_setlock; /*! Used by blocks to access the logger system. */ gr::logger_ptr d_logger; gr::logger_ptr d_debug_logger; // These are really only for internal use, but leaving them public avoids // having to work up an ever-varying list of friend GR_RUNTIME_APIs public: block_detail_sptr detail() const { return d_detail; } void set_detail(block_detail_sptr detail) { d_detail = detail; } }; typedef std::vector block_vector_t; typedef std::vector::iterator block_viter_t; inline block_sptr cast_to_block_sptr(basic_block_sptr p) { return boost::dynamic_pointer_cast(p); } std::ostream& operator << (std::ostream& os, const block *m); } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_BLOCK_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/expj.h0000664000175000017500000000217112207440367023175 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_EXPJ_H #define INCLUDED_GR_EXPJ_H #include #include #include static inline gr_complex gr_expj(float phase) { float t_imag, t_real; gr::sincosf(phase, &t_imag, &t_real); return gr_complex(t_real, t_imag); } #endif /* INCLUDED_GR_EXPJ_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/msg_accepter.h0000664000175000017500000000261512207440367024666 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_RUNTIME_MSG_ACCEPTER_H #define INCLUDED_GR_RUNTIME_MSG_ACCEPTER_H #include #include #include namespace gr { /*! * \brief Accepts messages and inserts them into a message queue, * then notifies subclass gr::basic_block there is a message pending. */ class GR_RUNTIME_API msg_accepter : public gr::messages::msg_accepter { public: msg_accepter(); ~msg_accepter(); void post(pmt::pmt_t which_port, pmt::pmt_t msg); }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_MSG_ACCEPTER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/constants.h0000664000175000017500000000323112207440367024241 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_CONSTANTS_H #define INCLUDED_GR_CONSTANTS_H #include #include namespace gr { /*! * \brief return SYSCONFDIR. Typically ${CMAKE_INSTALL_PREFIX}/etc or /etc */ GR_RUNTIME_API const std::string prefix(); /*! * \brief return SYSCONFDIR. Typically ${CMAKE_INSTALL_PREFIX}/etc or /etc */ GR_RUNTIME_API const std::string sysconfdir(); /*! * \brief return preferences file directory. Typically ${SYSCONFDIR}/etc/conf.d */ GR_RUNTIME_API const std::string prefsdir(); /*! * \brief return date/time of build, as set when 'cmake' is run */ GR_RUNTIME_API const std::string build_date(); /*! * \brief return version string defined by cmake (GrVersion.cmake) */ GR_RUNTIME_API const std::string version(); } /* namespace gr */ #endif /* INCLUDED_GR_CONSTANTS_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/high_res_timer.h0000664000175000017500000001275712207440367025232 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GNURADIO_HIGH_RES_TIMER_H #define INCLUDED_GNURADIO_HIGH_RES_TIMER_H #include //////////////////////////////////////////////////////////////////////// // Use architecture defines to determine the implementation //////////////////////////////////////////////////////////////////////// #if defined(linux) || defined(__linux) || defined(__linux__) #define GNURADIO_HRT_USE_CLOCK_GETTIME #include #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #define GNURADIO_HRT_USE_QUERY_PERFORMANCE_COUNTER #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) #define GNURADIO_HRT_USE_MACH_ABSOLUTE_TIME #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) #define GNURADIO_HRT_USE_CLOCK_GETTIME #include #else #define GNURADIO_HRT_USE_MICROSEC_CLOCK #endif //////////////////////////////////////////////////////////////////////// namespace gr { //! Typedef for the timer tick count typedef signed long long high_res_timer_type; //! Get the current time in ticks high_res_timer_type high_res_timer_now(void); //! Get the current time in ticks - for performance monitoring high_res_timer_type high_res_timer_now_perfmon(void); //! Get the number of ticks per second high_res_timer_type high_res_timer_tps(void); //! Get the tick count at the epoch high_res_timer_type high_res_timer_epoch(void); #ifdef GNURADIO_HRT_USE_CLOCK_GETTIME //! storage for high res timer type GR_RUNTIME_API extern clockid_t high_res_timer_source; #endif } /* namespace gr */ //////////////////////////////////////////////////////////////////////// #ifdef GNURADIO_HRT_USE_CLOCK_GETTIME inline gr::high_res_timer_type gr::high_res_timer_now(void){ timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec*high_res_timer_tps() + ts.tv_nsec; } inline gr::high_res_timer_type gr::high_res_timer_now_perfmon(void){ timespec ts; clock_gettime(high_res_timer_source, &ts); return ts.tv_sec*high_res_timer_tps() + ts.tv_nsec; } inline gr::high_res_timer_type gr::high_res_timer_tps(void){ return 1000000000UL; } #endif /* GNURADIO_HRT_USE_CLOCK_GETTIME */ //////////////////////////////////////////////////////////////////////// #ifdef GNURADIO_HRT_USE_MACH_ABSOLUTE_TIME #include inline gr::high_res_timer_type gr::high_res_timer_now(void){ return mach_absolute_time(); } inline gr::high_res_timer_type gr::high_res_timer_now_perfmon(void){ return gr::high_res_timer_now(); } inline gr::high_res_timer_type gr::high_res_timer_tps(void){ mach_timebase_info_data_t info; mach_timebase_info(&info); return gr::high_res_timer_type(info.numer*1000000000UL)/info.denom; } #endif //////////////////////////////////////////////////////////////////////// #ifdef GNURADIO_HRT_USE_QUERY_PERFORMANCE_COUNTER #include inline gr::high_res_timer_type gr::high_res_timer_now(void){ LARGE_INTEGER counts; QueryPerformanceCounter(&counts); return counts.QuadPart; } inline gr::high_res_timer_type gr::high_res_timer_now_perfmon(void){ return gr::high_res_timer_now(); } inline gr::high_res_timer_type gr::high_res_timer_tps(void){ LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); return freq.QuadPart; } #endif //////////////////////////////////////////////////////////////////////// #ifdef GNURADIO_HRT_USE_MICROSEC_CLOCK #include inline gr::high_res_timer_type gr::high_res_timer_now(void){ static const boost::posix_time::ptime epoch(boost::posix_time::from_time_t(0)); return (boost::posix_time::microsec_clock::universal_time() - epoch).ticks(); } inline gr::high_res_timer_type gr::high_res_timer_now_perfmon(void){ return gr::high_res_timer_now(); } inline gr::high_res_timer_type gr::high_res_timer_tps(void){ return boost::posix_time::time_duration::ticks_per_second(); } #endif //////////////////////////////////////////////////////////////////////// #include inline gr::high_res_timer_type gr::high_res_timer_epoch(void){ static const double hrt_ticks_per_utc_ticks = gr::high_res_timer_tps()/double(boost::posix_time::time_duration::ticks_per_second()); boost::posix_time::time_duration utc = boost::posix_time::microsec_clock::universal_time() - boost::posix_time::from_time_t(0); return gr::high_res_timer_now() - utc.ticks()*hrt_ticks_per_utc_ticks; } #endif /* INCLUDED_GNURADIO_HIGH_RES_TIMER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/IcePy_Communicator.h0000664000175000017500000000207612207440367025764 0ustar jcorganjcorgan// ********************************************************************** // // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** #ifndef ICEPY_COMMUNICATOR_H #define ICEPY_COMMUNICATOR_H #include #include namespace IcePy { extern PyTypeObject CommunicatorType; GR_RUNTIME_API bool initCommunicator(PyObject*); GR_RUNTIME_API Ice::CommunicatorPtr getCommunicator(PyObject*); GR_RUNTIME_API PyObject* createCommunicator(const Ice::CommunicatorPtr&); GR_RUNTIME_API PyObject* getCommunicatorWrapper(const Ice::CommunicatorPtr&); } extern "C" PyObject* IcePy_initialize(PyObject*, PyObject*); extern "C" PyObject* IcePy_initializeWithProperties(PyObject*, PyObject*); extern "C" PyObject* IcePy_initializeWithLogger(PyObject*, PyObject*); extern "C" PyObject* IcePy_initializeWithPropertiesAndLogger(PyObject*, PyObject*); #endif gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcserver_booter_base.h0000664000175000017500000000231612207440367026607 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCSERVER_BOOTER_BASE #define RPCSERVER_BOOTER_BASE #include #include class rpcserver_base; class rpcserver_booter_base { public: rpcserver_booter_base() {;} virtual ~rpcserver_booter_base() {;} virtual rpcserver_base* i()=0; virtual const std::vector endpoints()=0; virtual const std::string& type()=0; private: }; #endif /* RPCSERVER_BOOTER_BASE */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/rpcmanager.h0000664000175000017500000000332612207440367024351 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef RPCMANAGER_H #define RPCMANAGER_H #include #include #include #include #include class GR_RUNTIME_API rpcmanager : public virtual rpcmanager_base { public: rpcmanager(); ~rpcmanager(); static rpcserver_booter_base* get(); static void register_booter(rpcserver_booter_base* booter); template class rpcserver_booter_register_helper { public: rpcserver_booter_register_helper() { rpcmanager::register_booter(new T()); } //TODO: unregister }; private: static bool make_aggregator; static bool booter_registered; static bool aggregator_registered; static void rpcserver_booter_base_sptr_dest(rpcserver_booter_base* b) {;} static rpcserver_booter_base* boot; static std::auto_ptr aggregator; }; #endif /* RPCMANAGER_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/types.h0000664000175000017500000000373012207440367023375 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TYPES_H #define INCLUDED_GR_TYPES_H #include #include #include #include // size_t #include typedef std::vector gr_vector_int; typedef std::vector gr_vector_uint; typedef std::vector gr_vector_float; typedef std::vector gr_vector_double; typedef std::vector gr_vector_void_star; typedef std::vector gr_vector_const_void_star; /* * #include must be placed beforehand * in the source file including gnuradio/types.h for * the following to work correctly */ #ifdef HAVE_STDINT_H #include typedef int16_t gr_int16; typedef int32_t gr_int32; typedef int64_t gr_int64; typedef uint16_t gr_uint16; typedef uint32_t gr_uint32; typedef uint64_t gr_uint64; #else /* * Note: these defaults may be wrong on 64-bit systems */ typedef short gr_int16; typedef int gr_int32; typedef long long gr_int64; typedef unsigned short gr_uint16; typedef unsigned int gr_uint32; typedef unsigned long long gr_uint64; #endif /* HAVE_STDINT_H */ #endif /* INCLUDED_GR_TYPES_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/py_feval.h0000664000175000017500000000420112207440367024030 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PY_FEVAL_H #define INCLUDED_GR_PY_FEVAL_H #include #include class ensure_py_gil_state { PyGILState_STATE d_gstate; public: ensure_py_gil_state() { d_gstate = PyGILState_Ensure(); } ~ensure_py_gil_state() { PyGILState_Release(d_gstate); } }; namespace gr { class GR_RUNTIME_API py_feval_dd : public feval_dd { public: double calleval(double x) { ensure_py_gil_state _lock; return eval(x); } virtual ~py_feval_dd() {}; }; class GR_RUNTIME_API py_feval_cc : public feval_cc { public: gr_complex calleval(gr_complex x) { ensure_py_gil_state _lock; return eval(x); } virtual ~py_feval_cc() {}; }; class GR_RUNTIME_API py_feval_ll : public feval_ll { public: long calleval(long x) { ensure_py_gil_state _lock; return eval(x); } virtual ~py_feval_ll() {}; }; class GR_RUNTIME_API py_feval : public feval { public: void calleval() { ensure_py_gil_state _lock; eval(); } virtual ~py_feval() {}; }; class GR_RUNTIME_API py_feval_p : public feval_p { public: void calleval(pmt::pmt_t x) { ensure_py_gil_state _lock; eval(x); } virtual ~py_feval_p() {}; }; } /* namespace gr */ #endif /* INCLUDED_GR_PY_FEVAL_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/sys_paths.h0000664000175000017500000000214112207440367024241 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_SYS_PATHS_H #define GR_SYS_PATHS_H #include namespace gr { //! directory to create temporary files GR_RUNTIME_API const char *tmp_path(); //! directory to store application data GR_RUNTIME_API const char *appdata_path(); } /* namespace gr */ #endif /* GR_SYS_PATHS_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/block_registry.h0000664000175000017500000000375712207440367025264 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_RUNTIME_BLOCK_REGISTRY_H #define GR_RUNTIME_BLOCK_REGISTRY_H #include #include #include namespace gr { #ifndef GR_BASIC_BLOCK_H class basic_block; class block; #endif class GR_RUNTIME_API block_registry { public: block_registry(); long block_register(basic_block* block); void block_unregister(basic_block* block); std::string register_symbolic_name(basic_block* block); void register_symbolic_name(basic_block* block, std::string name); basic_block_sptr block_lookup(pmt::pmt_t symbol); void register_primitive(std::string blk, gr::block* ref); void unregister_primitive(std::string blk); void notify_blk(std::string blk); private: //typedef std::map< long, basic_block_sptr > blocksubmap_t; typedef std::map< long, basic_block* > blocksubmap_t; typedef std::map< std::string, blocksubmap_t > blockmap_t; blockmap_t d_map; pmt::pmt_t d_ref_map; std::map< std::string, block*> primitive_map; gr::thread::mutex d_mutex; }; } /* namespace gr */ GR_RUNTIME_API extern gr::block_registry global_block_registry; #endif /* GR_RUNTIME_BLOCK_REGISTRY_H */ gnuradio-3.7.2.1/gnuradio-runtime/include/gnuradio/api.h0000664000175000017500000000212112207440367022773 0ustar jcorganjcorgan/* * Copyright 2010-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_RUNTIME_API_H #define INCLUDED_GR_RUNTIME_RUNTIME_API_H #include #ifdef gnuradio_runtime_EXPORTS # define GR_RUNTIME_API __GR_ATTR_EXPORT #else # define GR_RUNTIME_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_GR_RUNTIME_RUNTIME_API_H */ gnuradio-3.7.2.1/gnuradio-runtime/ConfigChecks.cmake0000664000175000017500000001402212207440367022151 0ustar jcorganjcorgan# Copyright 2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## INCLUDE(GrMiscUtils) INCLUDE(CheckCXXSourceCompiles) IF(MSVC) #add this directory for our provided headers LIST(APPEND CMAKE_REQUIRED_INCLUDES ${CMAKE_SOURCE_DIR}/msvc) ENDIF(MSVC) GR_CHECK_HDR_N_DEF(netdb.h HAVE_NETDB_H) GR_CHECK_HDR_N_DEF(sys/time.h HAVE_SYS_TIME_H) GR_CHECK_HDR_N_DEF(sys/types.h HAVE_SYS_TYPES_H) GR_CHECK_HDR_N_DEF(sys/select.h HAVE_SYS_SELECT_H) GR_CHECK_HDR_N_DEF(sys/socket.h HAVE_SYS_SOCKET_H) GR_CHECK_HDR_N_DEF(io.h HAVE_IO_H) GR_CHECK_HDR_N_DEF(sys/mman.h HAVE_SYS_MMAN_H) GR_CHECK_HDR_N_DEF(sys/ipc.h HAVE_SYS_IPC_H) GR_CHECK_HDR_N_DEF(sys/shm.h HAVE_SYS_SHM_H) GR_CHECK_HDR_N_DEF(signal.h HAVE_SIGNAL_H) GR_CHECK_HDR_N_DEF(netinet/in.h HAVE_NETINET_IN_H) GR_CHECK_HDR_N_DEF(arpa/inet.h HAVE_ARPA_INET_H) GR_CHECK_HDR_N_DEF(byteswap.h HAVE_BYTESWAP_H) GR_CHECK_HDR_N_DEF(linux/ppdev.h HAVE_LINUX_PPDEV_H) GR_CHECK_HDR_N_DEF(dev/ppbus/ppi.h HAVE_DEV_PPBUS_PPI_H) GR_CHECK_HDR_N_DEF(unistd.h HAVE_UNISTD_H) GR_CHECK_HDR_N_DEF(malloc.h HAVE_MALLOC_H) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){snprintf(0, 0, 0); return 0;} " HAVE_SNPRINTF ) GR_ADD_COND_DEF(HAVE_SNPRINTF) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){sigaction(0, 0, 0); return 0;} " HAVE_SIGACTION ) GR_ADD_COND_DEF(HAVE_SIGACTION) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){select(0, 0, 0, 0, 0); return 0;} " HAVE_SELECT ) GR_ADD_COND_DEF(HAVE_SELECT) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){sysconf(0); return 0;} " HAVE_SYSCONF ) GR_ADD_COND_DEF(HAVE_SYSCONF) CHECK_CXX_SOURCE_COMPILES(" #include int main(){getpagesize(); return 0;} " HAVE_GETPAGESIZE ) GR_ADD_COND_DEF(HAVE_GETPAGESIZE) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){Sleep(0); return 0;} " HAVE_SSLEEP ) GR_ADD_COND_DEF(HAVE_SSLEEP) CHECK_CXX_SOURCE_COMPILES(" #include int main(){nanosleep(0, 0); return 0;} " HAVE_NANOSLEEP ) GR_ADD_COND_DEF(HAVE_NANOSLEEP) CHECK_CXX_SOURCE_COMPILES(" #include int main(){gettimeofday(0, 0); return 0;} " HAVE_GETTIMEOFDAY ) GR_ADD_COND_DEF(HAVE_GETTIMEOFDAY) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){posix_memalign(0, 0, 0); return 0;} " HAVE_POSIX_MEMALIGN ) GR_ADD_COND_DEF(HAVE_POSIX_MEMALIGN) CHECK_CXX_SOURCE_COMPILES(" #include int main(){valloc(0); return 0;} " HAVE_VALLOC ) GR_ADD_COND_DEF(HAVE_VALLOC) ADD_DEFINITIONS(-DALIGNED_MALLOC=0) ######################################################################## SET(CMAKE_REQUIRED_LIBRARIES -lpthread) CHECK_CXX_SOURCE_COMPILES(" #include int main(){pthread_sigmask(0, 0, 0); return 0;} " HAVE_PTHREAD_SIGMASK ) GR_ADD_COND_DEF(HAVE_PTHREAD_SIGMASK) SET(CMAKE_REQUIRED_LIBRARIES) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){ HANDLE handle; int size; LPCTSTR lpName; handle = CreateFileMapping( INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // max. object size size, // buffer size lpName); // name of mapping object return 0; } " HAVE_CREATEFILEMAPPING ) GR_ADD_COND_DEF(HAVE_CREATEFILEMAPPING) ######################################################################## SET(CMAKE_REQUIRED_LIBRARIES -lrt) CHECK_CXX_SOURCE_COMPILES(" #include #include int main(){shm_open(0, 0, 0); return 0;} " HAVE_SHM_OPEN ) GR_ADD_COND_DEF(HAVE_SHM_OPEN) SET(CMAKE_REQUIRED_LIBRARIES) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #define _GNU_SOURCE #include int main(){double x, sin, cos; sincos(x, &sin, &cos); return 0;} " HAVE_SINCOS ) GR_ADD_COND_DEF(HAVE_SINCOS) CHECK_CXX_SOURCE_COMPILES(" #define _GNU_SOURCE #include int main(){float x, sin, cos; sincosf(x, &sin, &cos); return 0;} " HAVE_SINCOSF ) GR_ADD_COND_DEF(HAVE_SINCOSF) CHECK_CXX_SOURCE_COMPILES(" #include int main(){sinf(0); return 0;} " HAVE_SINF ) GR_ADD_COND_DEF(HAVE_SINF) CHECK_CXX_SOURCE_COMPILES(" #include int main(){cosf(0); return 0;} " HAVE_COSF ) GR_ADD_COND_DEF(HAVE_COSF) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){mmap(0, 0, 0, 0, 0, 0); return 0;} " HAVE_MMAP ) GR_ADD_COND_DEF(HAVE_MMAP) gnuradio-3.7.2.1/gnuradio-runtime/gnuradio-runtime.pc.in0000664000175000017500000000040512207440367023043 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-runtime Description: GNU Radio core runtime infrastructure Requires: Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-runtime -lgnuradio-pmt Cflags: -I${includedir} gnuradio-3.7.2.1/gnuradio-runtime/python/0000775000175000017500000000000012207440367020143 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/python/pmt/0000775000175000017500000000000012207440367020743 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/python/pmt/CMakeLists.txt0000664000175000017500000000336712207440367023514 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) ######################################################################## # Install python files ######################################################################## GR_PYTHON_INSTALL(FILES __init__.py pmt_to_python.py DESTINATION ${GR_PYTHON_DIR}/pmt COMPONENT "runtime_python" ) ######################################################################## # Setup unit tests ######################################################################## if(ENABLE_TESTING) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ${CMAKE_BINARY_DIR}/gnuradio-runtime/swig ) set(GR_TEST_TARGET_DEPS gnuradio-runtime) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gnuradio-runtime/python/pmt/qa_pmt.py0000775000175000017500000000603112207440367022601 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import unittest import pmt class test_pmt(unittest.TestCase): def test01(self): a = pmt.intern("a") b = pmt.from_double(123765) d1 = pmt.make_dict() d2 = pmt.dict_add(d1, a, b) print d2 def test02(self): const = 123765 x_pmt = pmt.from_double(const) x_int = pmt.to_double(x_pmt) self.assertEqual(x_int, const) def test03(self): v = pmt.init_f32vector(3, [11, -22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test04(self): v = pmt.init_f64vector(3, [11, -22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test05(self): v = pmt.init_u8vector(3, [11, 22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test06(self): v = pmt.init_s8vector(3, [11, -22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test07(self): v = pmt.init_u16vector(3, [11, 22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test08(self): v = pmt.init_s16vector(3, [11, -22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test09(self): v = pmt.init_u32vector(3, [11, 22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test10(self): v = pmt.init_s32vector(3, [11, -22, 33]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test11(self): v = pmt.init_c32vector(3, [11 + -101j, -22 + 202j, 33 + -303j]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) def test12(self): v = pmt.init_c64vector(3, [11 + -101j, -22 + 202j, 33 + -303j]) s = pmt.serialize_str(v) d = pmt.deserialize_str(s) self.assertTrue(pmt.equal(v, d)) if __name__ == '__main__': unittest.main() gnuradio-3.7.2.1/gnuradio-runtime/python/pmt/__init__.py0000664000175000017500000000342612207440367023061 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # The presence of this file turns this directory into a Python package ''' Polymorphic Types. The type can really be used to store anything, but also has simple conversion methods for common data types such as bool, long, or a vector. The polymorphic type simplifies message passing between blocks, as all of the data is of the same type, including the message. Tags also use PMTs as data type, so a stream tag can be of any logical data type. In a sense, PMTs are a way to extend C++' strict typing with something more flexible. The PMT library supports the following major types: bool, symbol (string), integer, real, complex, null, pair, list, vector, dict, uniform_vector, any (boost::any cast) ''' import os try: from pmt_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from pmt_swig import * from pmt_to_python import pmt_to_python as to_python from pmt_to_python import python_to_pmt as to_pmt gnuradio-3.7.2.1/gnuradio-runtime/python/pmt/pmt_to_python.py0000664000175000017500000000627112207440367024226 0ustar jcorganjcorgan# Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. try: import pmt_swig as pmt except: import pmt import numpy #define missing def pmt_to_tuple(p): elems = list() for i in range(pmt.length(p)): elem = pmt.tuple_ref(p, i) elems.append(pmt_to_python(elem)) return tuple(elems) def pmt_from_tuple(p): args = map(python_to_pmt, p) return pmt.make_tuple(*args) def pmt_to_vector(p): v = list() for i in range(pmt.length(p)): elem = pmt.vector_ref(p, i) v.append(pmt_to_python(elem)) return v def pmt_from_vector(p): v = pmt.make_vector(len(p), pmt.PMT_NIL) for i, elem in enumerate(p): pmt.vector_set(v, i, python_to_pmt(elem)) return v def pmt_to_dict(p): d = dict() items = pmt.dict_items(p) for i in range(pmt.length(items)): pair = pmt.nth(i, items) k = pmt.car(pair) v = pmt.cdr(pair) d[pmt_to_python(k)] = pmt_to_python(v) return d def pmt_from_dict(p): d = pmt.make_dict() for k, v in p.iteritems(): #dict is immutable -> therefore pmt_dict_add returns the new dict d = pmt.dict_add(d, python_to_pmt(k), python_to_pmt(v)) return d def numpy_to_blob(p): p = p.view(numpy.uint8) b = pmt.make_blob(len(p)) pmt.blob_data(b)[:] = p return b THE_TABLE = ( #python type, check pmt type, to python, from python (None, pmt.is_null, lambda x: None, lambda x: pmt.PMT_NIL), (bool, pmt.is_bool, pmt.to_bool, pmt.from_bool), (str, pmt.is_symbol, pmt.symbol_to_string, pmt.string_to_symbol), (int, pmt.is_integer, pmt.to_long, pmt.from_long), (long, pmt.is_uint64, lambda x: long(pmt.to_uint64(x)), pmt.from_uint64), (float, pmt.is_real, pmt.to_double, pmt.from_double), (complex, pmt.is_complex, pmt.to_complex, pmt.from_complex), (tuple, pmt.is_tuple, pmt_to_tuple, pmt_from_tuple), (list, pmt.is_vector, pmt_to_vector, pmt_from_vector), (dict, pmt.is_dict, pmt_to_dict, pmt_from_dict), (numpy.ndarray, pmt.is_blob, pmt.blob_data, numpy_to_blob), ) def pmt_to_python(p): for python_type, pmt_check, to_python, from_python in THE_TABLE: if pmt_check(p): return to_python(p) return p #give up, we return the same def python_to_pmt(p): for python_type, pmt_check, to_python, from_python in THE_TABLE: if python_type is None: if p == None: return from_python(p) elif isinstance(p, python_type): return from_python(p) return p #give up, we return the same gnuradio-3.7.2.1/gnuradio-runtime/python/pmt/qa_pmt_to_python.py0000775000175000017500000000205612207440367024707 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import unittest import pmt class test_pmt_to_python(unittest.TestCase): def test01 (self): b = pmt.from_double(123765) self.assertEqual(pmt.to_python(b), 123765) t = pmt.to_pmt(range(5)) if __name__ == '__main__': unittest.main() gnuradio-3.7.2.1/gnuradio-runtime/python/CMakeLists.txt0000664000175000017500000000163012207440367022703 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) add_subdirectory(gnuradio) add_subdirectory(pmt) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/0000775000175000017500000000000012207440367021753 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/CMakeLists.txt0000664000175000017500000000224212207440367024513 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) add_subdirectory(gr) add_subdirectory(gru) if(ENABLE_GR_CTRLPORT) add_subdirectory(ctrlport) endif(ENABLE_GR_CTRLPORT) GR_PYTHON_INSTALL(FILES __init__.py eng_notation.py eng_option.py gr_unittest.py gr_xmlrunner.py DESTINATION ${GR_PYTHON_DIR}/gnuradio COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/0000775000175000017500000000000012207440367022550 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/CMakeLists.txt0000664000175000017500000000211512207440367025307 0ustar jcorganjcorgan# Copyright 2010-2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(FILES __init__.py freqz.py gnuplot_freqz.py hexint.py listmisc.py mathmisc.py msgq_runner.py os_read_exactly.py seq_with_cursor.py socket_stuff.py daemon.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/gru COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/os_read_exactly.py0000664000175000017500000000213312207440367026266 0ustar jcorganjcorgan# # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os def os_read_exactly(file_descriptor, nbytes): """ Replacement for os.read that blocks until it reads exactly nbytes. """ s = '' while nbytes > 0: sbuf = os.read(file_descriptor, nbytes) if not(sbuf): return '' nbytes -= len(sbuf) s = s + sbuf return s gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/mathmisc.py0000664000175000017500000000167012207440367024733 0ustar jcorganjcorgan# # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math def gcd(a,b): while b: a,b = b, a % b return a def lcm(a,b): return a * b / gcd(a, b) def log2(x): return math.log(x)/math.log(2) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/listmisc.py0000664000175000017500000000162012207440367024750 0ustar jcorganjcorgan# # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # def list_reverse(x): """ Return a copy of x that is reverse order. """ r = list(x) r.reverse() return r gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/socket_stuff.py0000664000175000017500000000332412207440367025623 0ustar jcorganjcorgan# # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # random socket related stuff import socket import os import sys def tcp_connect_or_die(sock_addr): """ Args: sock_addr: (host, port) to connect to (tuple) Returns: : socket or exits """ s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) try: s.connect(sock_addr) except socket.error, err: sys.stderr.write('Failed to connect to %s: %s\n' % (sock_addr, os.strerror (err.args[0]),)) sys.exit(1) return s def udp_connect_or_die(sock_addr): """ Args: sock_addr: (host, port) to connect to (tuple) Returns: : socket or exits """ s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(sock_addr) except socket.error, err: sys.stderr.write('Failed to connect to %s: %s\n' % (sock_addr, os.strerror (err.args[0]),)) sys.exit(1) return s gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/gnuplot_freqz.py0000775000175000017500000001005112207440367026021 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # __all__ = ['gnuplot_freqz'] import tempfile import os import math import numpy from gnuradio import gr from gnuradio.gru.freqz import freqz def gnuplot_freqz (hw, Fs=None, logfreq=False): """hw is a tuple of the form (h, w) where h is sequence of complex freq responses, and w is a sequence of corresponding frequency points. Plot the frequency response using gnuplot. If Fs is provide, use it as the sampling frequency, else use 2*pi. Returns a handle to the gnuplot graph. When the handle is reclaimed the graph is torn down.""" data_file = tempfile.NamedTemporaryFile () cmd_file = os.popen ('gnuplot', 'w') h, w = hw ampl = 20 * numpy.log10 (numpy.absolute (h) + 1e-9) phase = map (lambda x: math.atan2 (x.imag, x.real), h) if Fs: w *= (Fs/(2*math.pi)) for freq, a, ph in zip (w, ampl, phase): data_file.write ("%g\t%g\t%g\n" % (freq, a, ph)) data_file.flush () cmd_file.write ("set grid\n") if logfreq: cmd_file.write ("set logscale x\n") else: cmd_file.write ("unset logscale x\n") cmd_file.write ("plot '%s' using 1:2 with lines\n" % (data_file.name,)) cmd_file.flush () return (cmd_file, data_file) def test_plot (): sample_rate = 2.0e6 #taps = firdes.low_pass(1, sample_rate, 200000, 100000, firdes.WIN_HAMMING) taps = (0.0007329441141337156, 0.0007755281985737383, 0.0005323155201040208, -7.679847761841656e-19, -0.0007277769618667662, -0.001415981911122799, -0.0017135187517851591, -0.001282231998629868, 1.61239866282397e-18, 0.0018589380197227001, 0.0035909228026866913, 0.004260237794369459, 0.00310456077568233, -3.0331308923229716e-18, -0.004244099836796522, -0.007970594801008701, -0.009214458055794239, -0.006562007591128349, 4.714311174044374e-18, 0.008654761128127575, 0.01605774275958538, 0.01841980405151844, 0.013079923577606678, -6.2821650235090215e-18, -0.017465557903051376, -0.032989680767059326, -0.03894065320491791, -0.028868533670902252, 7.388111706347014e-18, 0.04517475143074989, 0.09890196472406387, 0.14991308748722076, 0.18646684288978577, 0.19974154233932495, 0.18646684288978577, 0.14991308748722076, 0.09890196472406387, 0.04517475143074989, 7.388111706347014e-18, -0.028868533670902252, -0.03894065320491791, -0.032989680767059326, -0.017465557903051376, -6.2821650235090215e-18, 0.013079923577606678, 0.01841980405151844, 0.01605774275958538, 0.008654761128127575, 4.714311174044374e-18, -0.006562007591128349, -0.009214458055794239, -0.007970594801008701, -0.004244099836796522, -3.0331308923229716e-18, 0.00310456077568233, 0.004260237794369459, 0.0035909228026866913, 0.0018589380197227001, 1.61239866282397e-18, -0.001282231998629868, -0.0017135187517851591, -0.001415981911122799, -0.0007277769618667662, -7.679847761841656e-19, 0.0005323155201040208, 0.0007755281985737383, 0.0007329441141337156) # print len (taps) return gnuplot_freqz (freqz (taps, 1), sample_rate) if __name__ == '__main__': handle = test_plot () raw_input ('Press Enter to continue: ') gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/seq_with_cursor.py0000664000175000017500000000467612207440367026357 0ustar jcorganjcorgan# # Copyright 2003,2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # misc utilities import types import exceptions class seq_with_cursor (object): __slots__ = [ 'items', 'index' ] def __init__ (self, items, initial_index = None, initial_value = None): assert len (items) > 0, "seq_with_cursor: len (items) == 0" self.items = items self.set_index (initial_index) if initial_value is not None: self.set_index_by_value(initial_value) def set_index (self, initial_index): if initial_index is None: self.index = len (self.items) / 2 elif initial_index >= 0 and initial_index < len (self.items): self.index = initial_index else: raise exceptions.ValueError def set_index_by_value(self, v): """ Set index to the smallest value such that items[index] >= v. If there is no such item, set index to the maximum value. """ self.set_index(0) # side effect! cv = self.current() more = True while cv < v and more: cv, more = self.next() # side effect! def next (self): new_index = self.index + 1 if new_index < len (self.items): self.index = new_index return self.items[new_index], True else: return self.items[self.index], False def prev (self): new_index = self.index - 1 if new_index >= 0: self.index = new_index return self.items[new_index], True else: return self.items[self.index], False def current (self): return self.items[self.index] def get_seq (self): return self.items[:] # copy of items gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/daemon.py0000664000175000017500000000620012207440367024363 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os, sys, signal # Turn application into a background daemon process. # # When this function returns: # # 1) The calling process is disconnected from its controlling terminal # and will not exit when the controlling session exits # 2) If a pidfile name is provided, it is created and the new pid is # written into it. # 3) If a logfile name is provided, it is opened and stdout/stderr are # redirected to it. # 4) The process current working directory is changed to '/' to avoid # pinning any filesystem mounts. # 5) The process umask is set to 0111. # # The return value is the new pid. # # To create GNU Radio applications that operate as daemons, add a call to this # function after all initialization but just before calling gr.top_block.run() # or .start(). # # Daemonized GNU Radio applications may be stopped by sending them a # SIGINT, SIGKILL, or SIGTERM, e.g., using 'kill pid' from the command line. # # If your application uses gr.top_block.run(), the flowgraph will be stopped # and the function will return. You should allow your daemon program to exit # at this point. # # If your application uses gr.top_block.start(), you are responsible for hooking # the Python signal handler (see 'signal' module) and calling gr.top_block.stop() # on your top block, and otherwise causing your daemon process to exit. # def daemonize(pidfile=None, logfile=None): # fork() into background try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if pid == 0: # First child of first fork() # Become session leader of new session os.setsid() # fork() into background again try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if pid != 0: os._exit(0) # Second child of second fork() else: # Second child of first fork() os._exit(0) os.umask(0111) # Write pid pid = os.getpid() if pidfile is not None: open(pidfile, 'w').write('%d\n'%pid) # Redirect streams if logfile is not None: lf = open(logfile, 'a+') sys.stdout = lf sys.stderr = lf # Prevent pinning any filesystem mounts os.chdir('/') # Tell caller what pid to send future signals to return pid if __name__ == "__main__": import time daemonize() print "Hello, world, from daemon process." time.sleep(20) print "Goodbye, world, from daemon process." gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/freqz.py0000664000175000017500000002625512207440367024263 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # This code lifted from various parts of www.scipy.org -eb 2005-01-24 # Copyright (c) 2001, 2002 Enthought, Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # a. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # b. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # c. Neither the name of the Enthought nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. # __all__ = ['freqz'] import numpy from numpy import * Num=numpy def atleast_1d(*arys): """ Force a sequence of arrays to each be at least 1D. Description: Force an array to be at least 1D. If an array is 0D, the array is converted to a single row of values. Otherwise, the array is unaltered. Arguments: *arys -- arrays to be converted to 1 or more dimensional array. Returns: input array converted to at least 1D array. """ res = [] for ary in arys: ary = asarray(ary) if len(ary.shape) == 0: result = numpy.array([ary[0]]) else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res def polyval(p,x): """Evaluate the polynomial p at x. If x is a polynomial then composition. Description: If p is of length N, this function returns the value: p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] x can be a sequence and p(x) will be returned for all elements of x. or x can be another polynomial and the composite polynomial p(x) will be returned. """ p = asarray(p) if isinstance(x,poly1d): y = 0 else: x = asarray(x) y = numpy.zeros(x.shape,x.typecode()) for i in range(len(p)): y = x * y + p[i] return y class poly1d: """A one-dimensional polynomial class. p = poly1d([1,2,3]) constructs the polynomial x**2 + 2 x + 3 p(0.5) evaluates the polynomial at the location p.r is a list of roots p.c is the coefficient array [1,2,3] p.order is the polynomial order (after leading zeros in p.c are removed) p[k] is the coefficient on the kth power of x (backwards from sequencing the coefficient array. polynomials can be added, substracted, multplied and divided (returns quotient and remainder). asarray(p) will also give the coefficient array, so polynomials can be used in all functions that accept arrays. """ def __init__(self, c_or_r, r=0): if isinstance(c_or_r,poly1d): for key in c_or_r.__dict__.keys(): self.__dict__[key] = c_or_r.__dict__[key] return if r: c_or_r = poly(c_or_r) c_or_r = atleast_1d(c_or_r) if len(c_or_r.shape) > 1: raise ValueError, "Polynomial must be 1d only." c_or_r = trim_zeros(c_or_r, trim='f') if len(c_or_r) == 0: c_or_r = numpy.array([0]) self.__dict__['coeffs'] = c_or_r self.__dict__['order'] = len(c_or_r) - 1 def __array__(self,t=None): if t: return asarray(self.coeffs,t) else: return asarray(self.coeffs) def __coerce__(self,other): return None def __repr__(self): vals = repr(self.coeffs) vals = vals[6:-1] return "poly1d(%s)" % vals def __len__(self): return self.order def __str__(self): N = self.order thestr = "0" for k in range(len(self.coeffs)): coefstr ='%.4g' % abs(self.coeffs[k]) if coefstr[-4:] == '0000': coefstr = coefstr[:-5] power = (N-k) if power == 0: if coefstr != '0': newstr = '%s' % (coefstr,) else: if k == 0: newstr = '0' else: newstr = '' elif power == 1: if coefstr == '0': newstr = '' elif coefstr == '1': newstr = 'x' else: newstr = '%s x' % (coefstr,) else: if coefstr == '0': newstr = '' elif coefstr == '1': newstr = 'x**%d' % (power,) else: newstr = '%s x**%d' % (coefstr, power) if k > 0: if newstr != '': if self.coeffs[k] < 0: thestr = "%s - %s" % (thestr, newstr) else: thestr = "%s + %s" % (thestr, newstr) elif (k == 0) and (newstr != '') and (self.coeffs[k] < 0): thestr = "-%s" % (newstr,) else: thestr = newstr return _raise_power(thestr) def __call__(self, val): return polyval(self.coeffs, val) def __mul__(self, other): if isscalar(other): return poly1d(self.coeffs * other) else: other = poly1d(other) return poly1d(polymul(self.coeffs, other.coeffs)) def __rmul__(self, other): if isscalar(other): return poly1d(other * self.coeffs) else: other = poly1d(other) return poly1d(polymul(self.coeffs, other.coeffs)) def __add__(self, other): other = poly1d(other) return poly1d(polyadd(self.coeffs, other.coeffs)) def __radd__(self, other): other = poly1d(other) return poly1d(polyadd(self.coeffs, other.coeffs)) def __pow__(self, val): if not isscalar(val) or int(val) != val or val < 0: raise ValueError, "Power to non-negative integers only." res = [1] for k in range(val): res = polymul(self.coeffs, res) return poly1d(res) def __sub__(self, other): other = poly1d(other) return poly1d(polysub(self.coeffs, other.coeffs)) def __rsub__(self, other): other = poly1d(other) return poly1d(polysub(other.coeffs, self.coeffs)) def __div__(self, other): if isscalar(other): return poly1d(self.coeffs/other) else: other = poly1d(other) return map(poly1d,polydiv(self.coeffs, other.coeffs)) def __rdiv__(self, other): if isscalar(other): return poly1d(other/self.coeffs) else: other = poly1d(other) return map(poly1d,polydiv(other.coeffs, self.coeffs)) def __setattr__(self, key, val): raise ValueError, "Attributes cannot be changed this way." def __getattr__(self, key): if key in ['r','roots']: return roots(self.coeffs) elif key in ['c','coef','coefficients']: return self.coeffs elif key in ['o']: return self.order else: return self.__dict__[key] def __getitem__(self, val): ind = self.order - val if val > self.order: return 0 if val < 0: return 0 return self.coeffs[ind] def __setitem__(self, key, val): ind = self.order - key if key < 0: raise ValueError, "Does not support negative powers." if key > self.order: zr = numpy.zeros(key-self.order,self.coeffs.typecode()) self.__dict__['coeffs'] = numpy.concatenate((zr,self.coeffs)) self.__dict__['order'] = key ind = 0 self.__dict__['coeffs'][ind] = val return def integ(self, m=1, k=0): return poly1d(polyint(self.coeffs,m=m,k=k)) def deriv(self, m=1): return poly1d(polyder(self.coeffs,m=m)) def freqz(b, a, worN=None, whole=0, plot=None): """Compute frequency response of a digital filter. Description: Given the numerator (b) and denominator (a) of a digital filter compute its frequency response. jw -jw -jmw jw B(e) b[0] + b[1]e + .... + b[m]e H(e) = ---- = ------------------------------------ jw -jw -jnw A(e) a[0] + a[2]e + .... + a[n]e Inputs: b, a --- the numerator and denominator of a linear filter. worN --- If None, then compute at 512 frequencies around the unit circle. If a single integer, the compute at that many frequencies. Otherwise, compute the response at frequencies given in worN whole -- Normally, frequencies are computed from 0 to pi (upper-half of unit-circle. If whole is non-zero compute frequencies from 0 to 2*pi. Outputs: (h,w) h -- The frequency response. w -- The frequencies at which h was computed. """ b, a = map(atleast_1d, (b,a)) if whole: lastpoint = 2*pi else: lastpoint = pi if worN is None: N = 512 w = Num.arange(0,lastpoint,lastpoint/N) elif isinstance(worN, types.IntType): N = worN w = Num.arange(0,lastpoint,lastpoint/N) else: w = worN w = atleast_1d(w) zm1 = exp(-1j*w) h = polyval(b[::-1], zm1) / polyval(a[::-1], zm1) # if not plot is None: # plot(w, h) return h, w gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/msgq_runner.py0000664000175000017500000000474112207440367025470 0ustar jcorganjcorgan# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Convenience class for dequeuing messages from a gr.msg_queue and invoking a callback. Creates a Python thread that does a blocking read on the supplied gr.msg_queue, then invokes callback each time a msg is received. If the msg type is not 0, then it is treated as a signal to exit its loop. If the callback raises an exception, and the runner was created with 'exit_on_error' equal to True, then the runner will store the exception and exit its loop, otherwise the exception is ignored. To get the exception that the callback raised, if any, call exit_error() on the object. To manually stop the runner, call stop() on the object. To determine if the runner has exited, call exited() on the object. """ from gnuradio import gr import gnuradio.gr.gr_threading as _threading class msgq_runner(_threading.Thread): def __init__(self, msgq, callback, exit_on_error=False): _threading.Thread.__init__(self) self._msgq = msgq self._callback = callback self._exit_on_error = exit_on_error self._done = False self._exited = False self._exit_error = None self.setDaemon(1) self.start() def run(self): while not self._done: msg = self._msgq.delete_head() if msg.type() != 0: self.stop() else: try: self._callback(msg) except Exception, e: if self._exit_on_error: self._exit_error = e self.stop() self._exited = True def stop(self): self._done = True def exited(self): return self._exited def exit_error(self): return self._exit_error gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/__init__.py0000664000175000017500000000044312207440367024662 0ustar jcorganjcorgan# make this a package # Import gru stuff from daemon import * from freqz import * from gnuplot_freqz import * from hexint import * from listmisc import * from mathmisc import * from msgq_runner import * from os_read_exactly import * from seq_with_cursor import * from socket_stuff import * gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gru/hexint.py0000664000175000017500000000250712207440367024425 0ustar jcorganjcorgan# # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # def hexint(mask): """ Convert unsigned masks into signed ints. This allows us to use hex constants like 0xf0f0f0f2 when talking to our hardware and not get screwed by them getting treated as python longs. """ if mask >= 2**31: return int(mask-2**32) return mask def hexshort(mask): """ Convert unsigned masks into signed shorts. This allows us to use hex constants like 0x8000 when talking to our hardware and not get screwed by them getting treated as python longs. """ if mask >= 2**15: return int(mask-2**16) return mask gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/0000775000175000017500000000000012227263356022366 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt0000664000175000017500000000344612207440367025132 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL(FILES __init__.py tag_utils.py gateway.py gr_threading.py gr_threading_23.py gr_threading_24.py hier_block2.py top_block.py pubsub.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/gr COMPONENT "runtime_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gruel/src/python ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/exceptions.py0000664000175000017500000000162612207440367025123 0ustar jcorganjcorgan# # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. class NotDAG (Exception): """Not a directed acyclic graph""" pass class CantHappen (Exception): """Can't happen""" pass gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/pubsub.py0000664000175000017500000001104712207440367024240 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Abstract GNU Radio publisher/subscriber interface This is a proof of concept implementation, will likely change significantly. """ class pubsub(dict): def __init__(self): self._publishers = { } self._subscribers = { } self._proxies = { } def __missing__(self, key, value=None): dict.__setitem__(self, key, value) self._publishers[key] = None self._subscribers[key] = [] self._proxies[key] = None def __setitem__(self, key, val): if not self.has_key(key): self.__missing__(key, val) elif self._proxies[key] is not None: (p, newkey) = self._proxies[key] p[newkey] = val else: dict.__setitem__(self, key, val) for sub in self._subscribers[key]: # Note this means subscribers will get called in the thread # context of the 'set' caller. sub(val) def __getitem__(self, key): if not self.has_key(key): self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] return p[newkey] elif self._publishers[key] is not None: return self._publishers[key]() else: return dict.__getitem__(self, key) def publish(self, key, publisher): if not self.has_key(key): self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.publish(newkey, publisher) else: self._publishers[key] = publisher def subscribe(self, key, subscriber): if not self.has_key(key): self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.subscribe(newkey, subscriber) else: self._subscribers[key].append(subscriber) def unpublish(self, key): if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.unpublish(newkey) else: self._publishers[key] = None def unsubscribe(self, key, subscriber): if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.unsubscribe(newkey, subscriber) else: self._subscribers[key].remove(subscriber) def proxy(self, key, p, newkey=None): if not self.has_key(key): self.__missing__(key) if newkey is None: newkey = key self._proxies[key] = (p, newkey) def unproxy(self, key): self._proxies[key] = None # Test code if __name__ == "__main__": import sys o = pubsub() # Non-existent key gets auto-created with None value print "Auto-created key 'foo' value:", o['foo'] # Add some subscribers # First is a bare function def print_len(x): print "len=%i" % (len(x), ) o.subscribe('foo', print_len) # The second is a class member function class subber(object): def __init__(self, param): self._param = param def printer(self, x): print self._param, `x` s = subber('param') o.subscribe('foo', s.printer) # The third is a lambda function o.subscribe('foo', lambda x: sys.stdout.write('val='+`x`+'\n')) # Update key 'foo', will notify subscribers print "Updating 'foo' with three subscribers:" o['foo'] = 'bar'; # Remove first subscriber o.unsubscribe('foo', print_len) # Update now will only trigger second and third subscriber print "Updating 'foo' after removing a subscriber:" o['foo'] = 'bar2'; # Publish a key as a function, in this case, a lambda function o.publish('baz', lambda : 42) print "Published value of 'baz':", o['baz'] # Unpublish the key o.unpublish('baz') # This will return None, as there is no publisher print "Value of 'baz' with no publisher:", o['baz'] # Set 'baz' key, it gets cached o['baz'] = 'bazzz' # Now will return cached value, since no provider print "Cached value of 'baz' after being set:", o['baz'] gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/qa_feval.py0000775000175000017500000000703012207440367024516 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest class my_add2_dd(gr.feval_dd): def eval(self, x): return x + 2 class my_add2_ll(gr.feval_ll): def eval(self, x): return x + 2 class my_add2_cc(gr.feval_cc): def eval(self, x): return x + (2 - 2j) class my_feval(gr.feval): def __init__(self): gr.feval.__init__(self) self.fired = False def eval(self): self.fired = True class test_feval(gr_unittest.TestCase): def test_dd_1(self): f = my_add2_dd() src_data = (0.0, 1.0, 2.0, 3.0, 4.0) expected_result = (2.0, 3.0, 4.0, 5.0, 6.0) # this is all in python... actual_result = tuple([f.eval(x) for x in src_data]) self.assertEqual(expected_result, actual_result) def test_dd_2(self): f = my_add2_dd() src_data = (0.0, 1.0, 2.0, 3.0, 4.0) expected_result = (2.0, 3.0, 4.0, 5.0, 6.0) # this is python -> C++ -> python and back again... actual_result = tuple([gr.feval_dd_example(f, x) for x in src_data]) self.assertEqual(expected_result, actual_result) def test_ll_1(self): f = my_add2_ll() src_data = (0, 1, 2, 3, 4) expected_result = (2, 3, 4, 5, 6) # this is all in python... actual_result = tuple([f.eval(x) for x in src_data]) self.assertEqual(expected_result, actual_result) def test_ll_2(self): f = my_add2_ll() src_data = (0, 1, 2, 3, 4) expected_result = (2, 3, 4, 5, 6) # this is python -> C++ -> python and back again... actual_result = tuple([gr.feval_ll_example(f, x) for x in src_data]) self.assertEqual(expected_result, actual_result) def test_cc_1(self): f = my_add2_cc() src_data = (0+1j, 2+3j, 4+5j, 6+7j) expected_result = (2-1j, 4+1j, 6+3j, 8+5j) # this is all in python... actual_result = tuple([f.eval(x) for x in src_data]) self.assertEqual(expected_result, actual_result) def test_cc_2(self): f = my_add2_cc() src_data = (0+1j, 2+3j, 4+5j, 6+7j) expected_result = (2-1j, 4+1j, 6+3j, 8+5j) # this is python -> C++ -> python and back again... actual_result = tuple([gr.feval_cc_example(f, x) for x in src_data]) self.assertEqual(expected_result, actual_result) def test_void_1(self): # this is all in python f = my_feval() f.eval() self.assertEqual(True, f.fired) def test_void_2(self): # this is python -> C++ -> python and back again f = my_feval() gr.feval_example(f) self.assertEqual(True, f.fired) if __name__ == '__main__': gr_unittest.run(test_feval, "test_feval.xml") gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/prefs.py0000664000175000017500000000723312207440367024061 0ustar jcorganjcorgan# # Copyright 2006,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import gnuradio_runtime as gsp _prefs_base = gsp.prefs import ConfigParser import os import os.path import sys import glob def _user_prefs_filename(): return os.path.expanduser('~/.gnuradio/config.conf') def _sys_prefs_dirname(): return gsp.prefsdir() def _bool(x): """ Try to coerce obj to a True or False """ if isinstance(x, bool): return x if isinstance(x, (float, int)): return bool(x) raise TypeError, x class _prefs(_prefs_base): """ Derive our 'real class' from the stubbed out base class that has support for SWIG directors. This allows C++ code to magically and transparently invoke the methods in this python class. """ def __init__(self): _prefs_base.__init__(self) self.cp = ConfigParser.RawConfigParser() self.__getattr__ = lambda self, name: getattr(self.cp, name) def _sys_prefs_filenames(self): dir = _sys_prefs_dirname() try: fnames = glob.glob(os.path.join(dir, '*.conf')) except (IOError, OSError): return [] fnames.sort() return fnames def _read_files(self): filenames = self._sys_prefs_filenames() filenames.append(_user_prefs_filename()) #print "filenames: ", filenames self.cp.read(filenames) # ---------------------------------------------------------------- # These methods override the C++ virtual methods of the same name # ---------------------------------------------------------------- def has_section(self, section): return self.cp.has_section(section) def has_option(self, section, option): return self.cp.has_option(section, option) def get_string(self, section, option, default_val): try: return self.cp.get(section, option) except: return default_val def get_bool(self, section, option, default_val): try: return self.cp.getboolean(section, option) except: return default_val def get_long(self, section, option, default_val): try: return self.cp.getint(section, option) except: return default_val def get_double(self, section, option, default_val): try: return self.cp.getfloat(section, option) except: return default_val # ---------------------------------------------------------------- # End override of C++ virtual methods # ---------------------------------------------------------------- _prefs_db = _prefs() # if GR_DONT_LOAD_PREFS is set, don't load them. # (make check uses this to avoid interactions.) if os.getenv("GR_DONT_LOAD_PREFS", None) is None: _prefs_db._read_files() _prefs_base.set_singleton(_prefs_db) # tell C++ what instance to use def prefs(): """ Return the global preference data base """ return _prefs_db gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/gr_threading.py0000664000175000017500000000230412207440367025371 0ustar jcorganjcorgan# # Copyright 2005 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from sys import version_info as _version_info # import patched version of standard threading module if _version_info[0:2] == (2, 3): #print "Importing gr_threading_23" from gr_threading_23 import * elif _version_info[0:2] == (2, 4): #print "Importing gr_threading_24" from gr_threading_24 import * else: # assume the patch was applied... #print "Importing system provided threading" from threading import * gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/tag_utils.py0000664000175000017500000000145012207440367024730 0ustar jcorganjcorganimport pmt import runtime_swig as gr class PythonTag(object): " Python container for tags " def __init__(self): self.offset = None self.key = None self.value = None self.srcid = None def tag_to_python(tag): """ Convert a stream tag to a Python-readable object """ newtag = PythonTag() newtag.offset = tag.offset newtag.key = pmt.to_python(tag.key) newtag.value = pmt.to_python(tag.value) newtag.srcid = pmt.to_python(tag.srcid) return newtag def tag_to_pmt(tag): """ Convert a Python-readable object to a stream tag """ newtag = gr.tag_t() newtag.offset = tag.offset newtag.key = pmt.to_python(tag.key) newtag.value = pmt.from_python(tag.value) newtag.srcid = pmt.from_python(tag.srcid) return newtag gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/gr_threading_23.py0000664000175000017500000005264212207440367025707 0ustar jcorganjcorgan"""Thread module emulating a subset of Java's threading model.""" # This started life as the threading.py module of Python 2.3 # It's been patched to fix a problem with join, where a KeyboardInterrupt # caused a lock to be left in the acquired state. import sys as _sys try: import thread except ImportError: del _sys.modules[__name__] raise from StringIO import StringIO as _StringIO from time import time as _time, sleep as _sleep from traceback import print_exc as _print_exc # Rename some stuff so "from threading import *" is safe __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Timer', 'setprofile', 'settrace'] _start_new_thread = thread.start_new_thread _allocate_lock = thread.allocate_lock _get_ident = thread.get_ident ThreadError = thread.error del thread # Debug support (adapted from ihooks.py). # All the major classes here derive from _Verbose. We force that to # be a new-style class so that all the major classes here are new-style. # This helps debugging (type(instance) is more revealing for instances # of new-style classes). _VERBOSE = False if __debug__: class _Verbose(object): def __init__(self, verbose=None): if verbose is None: verbose = _VERBOSE self.__verbose = verbose def _note(self, format, *args): if self.__verbose: format = format % args format = "%s: %s\n" % ( currentThread().getName(), format) _sys.stderr.write(format) else: # Disable this when using "python -O" class _Verbose(object): def __init__(self, verbose=None): pass def _note(self, *args): pass # Support for profile and trace hooks _profile_hook = None _trace_hook = None def setprofile(func): global _profile_hook _profile_hook = func def settrace(func): global _trace_hook _trace_hook = func # Synchronization classes Lock = _allocate_lock def RLock(*args, **kwargs): return _RLock(*args, **kwargs) class _RLock(_Verbose): def __init__(self, verbose=None): _Verbose.__init__(self, verbose) self.__block = _allocate_lock() self.__owner = None self.__count = 0 def __repr__(self): return "<%s(%s, %d)>" % ( self.__class__.__name__, self.__owner and self.__owner.getName(), self.__count) def acquire(self, blocking=1): me = currentThread() if self.__owner is me: self.__count = self.__count + 1 if __debug__: self._note("%s.acquire(%s): recursive success", self, blocking) return 1 rc = self.__block.acquire(blocking) if rc: self.__owner = me self.__count = 1 if __debug__: self._note("%s.acquire(%s): initial succes", self, blocking) else: if __debug__: self._note("%s.acquire(%s): failure", self, blocking) return rc def release(self): me = currentThread() assert self.__owner is me, "release() of un-acquire()d lock" self.__count = count = self.__count - 1 if not count: self.__owner = None self.__block.release() if __debug__: self._note("%s.release(): final release", self) else: if __debug__: self._note("%s.release(): non-final release", self) # Internal methods used by condition variables def _acquire_restore(self, (count, owner)): self.__block.acquire() self.__count = count self.__owner = owner if __debug__: self._note("%s._acquire_restore()", self) def _release_save(self): if __debug__: self._note("%s._release_save()", self) count = self.__count self.__count = 0 owner = self.__owner self.__owner = None self.__block.release() return (count, owner) def _is_owned(self): return self.__owner is currentThread() def Condition(*args, **kwargs): return _Condition(*args, **kwargs) class _Condition(_Verbose): def __init__(self, lock=None, verbose=None): _Verbose.__init__(self, verbose) if lock is None: lock = RLock() self.__lock = lock # Export the lock's acquire() and release() methods self.acquire = lock.acquire self.release = lock.release # If the lock defines _release_save() and/or _acquire_restore(), # these override the default implementations (which just call # release() and acquire() on the lock). Ditto for _is_owned(). try: self._release_save = lock._release_save except AttributeError: pass try: self._acquire_restore = lock._acquire_restore except AttributeError: pass try: self._is_owned = lock._is_owned except AttributeError: pass self.__waiters = [] def __repr__(self): return "" % (self.__lock, len(self.__waiters)) def _release_save(self): self.__lock.release() # No state to save def _acquire_restore(self, x): self.__lock.acquire() # Ignore saved state def _is_owned(self): # Return True if lock is owned by currentThread. # This method is called only if __lock doesn't have _is_owned(). if self.__lock.acquire(0): self.__lock.release() return False else: return True def wait(self, timeout=None): currentThread() # for side-effect assert self._is_owned(), "wait() of un-acquire()d lock" waiter = _allocate_lock() waiter.acquire() self.__waiters.append(waiter) saved_state = self._release_save() try: # restore state no matter what (e.g., KeyboardInterrupt) if timeout is None: waiter.acquire() if __debug__: self._note("%s.wait(): got it", self) else: # Balancing act: We can't afford a pure busy loop, so we # have to sleep; but if we sleep the whole timeout time, # we'll be unresponsive. The scheme here sleeps very # little at first, longer as time goes on, but never longer # than 20 times per second (or the timeout time remaining). endtime = _time() + timeout delay = 0.0005 # 500 us -> initial delay of 1 ms while True: gotit = waiter.acquire(0) if gotit: break remaining = endtime - _time() if remaining <= 0: break delay = min(delay * 2, remaining, .05) _sleep(delay) if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass else: if __debug__: self._note("%s.wait(%s): got it", self, timeout) finally: self._acquire_restore(saved_state) def notify(self, n=1): currentThread() # for side-effect assert self._is_owned(), "notify() of un-acquire()d lock" __waiters = self.__waiters waiters = __waiters[:n] if not waiters: if __debug__: self._note("%s.notify(): no waiters", self) return self._note("%s.notify(): notifying %d waiter%s", self, n, n!=1 and "s" or "") for waiter in waiters: waiter.release() try: __waiters.remove(waiter) except ValueError: pass def notifyAll(self): self.notify(len(self.__waiters)) def Semaphore(*args, **kwargs): return _Semaphore(*args, **kwargs) class _Semaphore(_Verbose): # After Tim Peters' semaphore class, but not quite the same (no maximum) def __init__(self, value=1, verbose=None): assert value >= 0, "Semaphore initial value must be >= 0" _Verbose.__init__(self, verbose) self.__cond = Condition(Lock()) self.__value = value def acquire(self, blocking=1): rc = False self.__cond.acquire() while self.__value == 0: if not blocking: break if __debug__: self._note("%s.acquire(%s): blocked waiting, value=%s", self, blocking, self.__value) self.__cond.wait() else: self.__value = self.__value - 1 if __debug__: self._note("%s.acquire: success, value=%s", self, self.__value) rc = True self.__cond.release() return rc def release(self): self.__cond.acquire() self.__value = self.__value + 1 if __debug__: self._note("%s.release: success, value=%s", self, self.__value) self.__cond.notify() self.__cond.release() def BoundedSemaphore(*args, **kwargs): return _BoundedSemaphore(*args, **kwargs) class _BoundedSemaphore(_Semaphore): """Semaphore that checks that # releases is <= # acquires""" def __init__(self, value=1, verbose=None): _Semaphore.__init__(self, value, verbose) self._initial_value = value def release(self): if self._Semaphore__value >= self._initial_value: raise ValueError, "Semaphore released too many times" return _Semaphore.release(self) def Event(*args, **kwargs): return _Event(*args, **kwargs) class _Event(_Verbose): # After Tim Peters' event class (without is_posted()) def __init__(self, verbose=None): _Verbose.__init__(self, verbose) self.__cond = Condition(Lock()) self.__flag = False def isSet(self): return self.__flag def set(self): self.__cond.acquire() try: self.__flag = True self.__cond.notifyAll() finally: self.__cond.release() def clear(self): self.__cond.acquire() try: self.__flag = False finally: self.__cond.release() def wait(self, timeout=None): self.__cond.acquire() try: if not self.__flag: self.__cond.wait(timeout) finally: self.__cond.release() # Helper to generate new thread names _counter = 0 def _newname(template="Thread-%d"): global _counter _counter = _counter + 1 return template % _counter # Active thread administration _active_limbo_lock = _allocate_lock() _active = {} _limbo = {} # Main class for threads class Thread(_Verbose): __initialized = False def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, verbose=None): assert group is None, "group argument must be None for now" _Verbose.__init__(self, verbose) self.__target = target self.__name = str(name or _newname()) self.__args = args self.__kwargs = kwargs self.__daemonic = self._set_daemon() self.__started = False self.__stopped = False self.__block = Condition(Lock()) self.__initialized = True def _set_daemon(self): # Overridden in _MainThread and _DummyThread return currentThread().isDaemon() def __repr__(self): assert self.__initialized, "Thread.__init__() was not called" status = "initial" if self.__started: status = "started" if self.__stopped: status = "stopped" if self.__daemonic: status = status + " daemon" return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status) def start(self): assert self.__initialized, "Thread.__init__() not called" assert not self.__started, "thread already started" if __debug__: self._note("%s.start(): starting thread", self) _active_limbo_lock.acquire() _limbo[self] = self _active_limbo_lock.release() _start_new_thread(self.__bootstrap, ()) self.__started = True _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack) def run(self): if self.__target: self.__target(*self.__args, **self.__kwargs) def __bootstrap(self): try: self.__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: self._note("%s.__bootstrap(): thread started", self) if _trace_hook: self._note("%s.__bootstrap(): registering trace hook", self) _sys.settrace(_trace_hook) if _profile_hook: self._note("%s.__bootstrap(): registering profile hook", self) _sys.setprofile(_profile_hook) try: self.run() except SystemExit: if __debug__: self._note("%s.__bootstrap(): raised SystemExit", self) except: if __debug__: self._note("%s.__bootstrap(): unhandled exception", self) s = _StringIO() _print_exc(file=s) _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), s.getvalue())) else: if __debug__: self._note("%s.__bootstrap(): normal return", self) finally: self.__stop() try: self.__delete() except: pass def __stop(self): self.__block.acquire() self.__stopped = True self.__block.notifyAll() self.__block.release() def __delete(self): _active_limbo_lock.acquire() del _active[_get_ident()] _active_limbo_lock.release() def join(self, timeout=None): assert self.__initialized, "Thread.__init__() not called" assert self.__started, "cannot join thread before it is started" assert self is not currentThread(), "cannot join current thread" if __debug__: if not self.__stopped: self._note("%s.join(): waiting until thread stops", self) self.__block.acquire() try: if timeout is None: while not self.__stopped: self.__block.wait() if __debug__: self._note("%s.join(): thread stopped", self) else: deadline = _time() + timeout while not self.__stopped: delay = deadline - _time() if delay <= 0: if __debug__: self._note("%s.join(): timed out", self) break self.__block.wait(delay) else: if __debug__: self._note("%s.join(): thread stopped", self) finally: self.__block.release() def getName(self): assert self.__initialized, "Thread.__init__() not called" return self.__name def setName(self, name): assert self.__initialized, "Thread.__init__() not called" self.__name = str(name) def isAlive(self): assert self.__initialized, "Thread.__init__() not called" return self.__started and not self.__stopped def isDaemon(self): assert self.__initialized, "Thread.__init__() not called" return self.__daemonic def setDaemon(self, daemonic): assert self.__initialized, "Thread.__init__() not called" assert not self.__started, "cannot set daemon status of active thread" self.__daemonic = daemonic # The timer class was contributed by Itamar Shtull-Trauring def Timer(*args, **kwargs): return _Timer(*args, **kwargs) class _Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=[], kwargs={}) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.isSet(): self.function(*self.args, **self.kwargs) self.finished.set() # Special thread class to represent the main thread # This is garbage collected through an exit handler class _MainThread(Thread): def __init__(self): Thread.__init__(self, name="MainThread") self._Thread__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() import atexit atexit.register(self.__exitfunc) def _set_daemon(self): return False def __exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: if __debug__: self._note("%s: waiting for other threads", self) while t: t.join() t = _pickSomeNonDaemonThread() if __debug__: self._note("%s: exiting", self) self._Thread__delete() def _pickSomeNonDaemonThread(): for t in enumerate(): if not t.isDaemon() and t.isAlive(): return t return None # Dummy thread class to represent threads not started here. # These aren't garbage collected when they die, # nor can they be waited for. # Their purpose is to return *something* from currentThread(). # They are marked as daemon threads so we won't wait for them # when we exit (conform previous semantics). class _DummyThread(Thread): def __init__(self): Thread.__init__(self, name=_newname("Dummy-%d")) self._Thread__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() def _set_daemon(self): return True def join(self, timeout=None): assert False, "cannot join a dummy thread" # Global API functions def currentThread(): try: return _active[_get_ident()] except KeyError: ##print "currentThread(): no current thread for", _get_ident() return _DummyThread() def activeCount(): _active_limbo_lock.acquire() count = len(_active) + len(_limbo) _active_limbo_lock.release() return count def enumerate(): _active_limbo_lock.acquire() active = _active.values() + _limbo.values() _active_limbo_lock.release() return active # Create the main thread object _MainThread() # Self-test code def _test(): class BoundedQueue(_Verbose): def __init__(self, limit): _Verbose.__init__(self) self.mon = RLock() self.rc = Condition(self.mon) self.wc = Condition(self.mon) self.limit = limit self.queue = [] def put(self, item): self.mon.acquire() while len(self.queue) >= self.limit: self._note("put(%s): queue full", item) self.wc.wait() self.queue.append(item) self._note("put(%s): appended, length now %d", item, len(self.queue)) self.rc.notify() self.mon.release() def get(self): self.mon.acquire() while not self.queue: self._note("get(): queue empty") self.rc.wait() item = self.queue.pop(0) self._note("get(): got %s, %d left", item, len(self.queue)) self.wc.notify() self.mon.release() return item class ProducerThread(Thread): def __init__(self, queue, quota): Thread.__init__(self, name="Producer") self.queue = queue self.quota = quota def run(self): from random import random counter = 0 while counter < self.quota: counter = counter + 1 self.queue.put("%s.%d" % (self.getName(), counter)) _sleep(random() * 0.00001) class ConsumerThread(Thread): def __init__(self, queue, count): Thread.__init__(self, name="Consumer") self.queue = queue self.count = count def run(self): while self.count > 0: item = self.queue.get() print item self.count = self.count - 1 NP = 3 QL = 4 NI = 5 Q = BoundedQueue(QL) P = [] for i in range(NP): t = ProducerThread(Q, NI) t.setName("Producer-%d" % (i+1)) P.append(t) C = ConsumerThread(Q, NI*NP) for t in P: t.start() _sleep(0.000001) C.start() for t in P: t.join() C.join() if __name__ == '__main__': _test() gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2_message_connections.py0000664000175000017500000001757112227263356031725 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import weakref from gnuradio import blocks, gr, gr_unittest import pmt class block_with_message_output(gr.basic_block): def __init__(self): gr.basic_block.__init__(self, "block_with_message_output", in_sig=None, out_sig=None) self.message_port_register_out(pmt.intern("test")) class block_with_message_input(gr.basic_block): def __init__(self): gr.basic_block.__init__(self, "block_with_message_input", in_sig=None, out_sig=None) self.message_port_register_in(pmt.intern("test")) class hier_block_with_message_output(gr.hier_block2): def __init__(self): gr.hier_block2.__init__(self, "hier_block_with_message_output", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.message_port_register_hier_in("test") self.block = block_with_message_output() self.msg_connect(self.block, "test", weakref.proxy(self), "test") class hier_block_with_message_input(gr.hier_block2): def __init__(self): gr.hier_block2.__init__(self, "hier_block_with_message_output", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.message_port_register_hier_out("test") self.block = block_with_message_input() self.msg_connect(weakref.proxy(self), "test", self.block, "test") class hier_block_with_message_inout(gr.hier_block2): def __init__(self): gr.hier_block2.__init__(self, "hier_block_with_message_inout", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.message_port_register_hier_out("test") self.message_port_register_hier_in("test") self.input = block_with_message_input() self.msg_connect(weakref.proxy(self), "test", self.input, "test") self.output = block_with_message_output() self.msg_connect(self.output, "test", weakref.proxy(self), "test") class test_hier_block2_message_connections(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def run_top_block(self): self.tb.start() self.tb.stop() self.tb.wait() def assert_has_subscription(self, sender, send_port, receiver, receive_port): """assert that the given sender block has a subscription for the given receiver block on the appropriate send and receive ports :param sender: a block sptr to the message sender :param string send_port: the port messages are being sent on :param receiver: a block sptr to the message receiver :param string receive_port: the port messages are being received on """ subs = sender.message_subscribers(pmt.intern(send_port)) self.assertTrue(pmt.list_has(subs, pmt.cons( pmt.intern(receiver.to_basic_block().alias()), pmt.intern(receive_port)))) def assert_has_num_subscriptions(self, block, port, number): """assert that the given block has the given number of subscriptions on the given port :param block: a block sptr :param string port: the port name :param number: the number of subscriptions expected """ subs = block.message_subscribers(pmt.intern(port)) self.assertEqual(pmt.length(subs), number) def test_hier_out_to_normal_in(self): message_debug = blocks.message_debug() hier = hier_block_with_message_output() self.tb.msg_connect(hier, "test", message_debug, "print") self.run_top_block() self.assert_has_num_subscriptions(hier.block, "test", 1) self.assert_has_num_subscriptions(hier, "test", 0) self.assert_has_subscription( hier.block, "test", message_debug, "print") self.tb.msg_disconnect(hier, "test", message_debug, "print") self.assert_has_num_subscriptions(hier.block, "test", 0) def test_normal_out_to_hier_in(self): b = block_with_message_output() hier = hier_block_with_message_input() self.tb.msg_connect(b, "test", hier, "test") self.run_top_block() self.assert_has_num_subscriptions(b, "test", 1) self.assert_has_subscription(b, "test", hier.block, "test") self.tb.msg_disconnect(b, "test", hier, "test") self.assert_has_num_subscriptions(b, "test", 0) def test_hier_out_to_hier_in(self): hier_out = hier_block_with_message_output() hier_in = hier_block_with_message_input() self.tb.msg_connect(hier_out, "test", hier_in, "test") self.run_top_block() self.assert_has_num_subscriptions(hier_out, "test", 0) self.assert_has_num_subscriptions(hier_out.block, "test", 1) self.assert_has_subscription( hier_out.block, "test", hier_in.block, "test") self.tb.msg_disconnect(hier_out, "test", hier_in, "test") self.assert_has_num_subscriptions(hier_out.block, "test", 0) def test_normal_in_to_hier_to_normal_out(self): hier = hier_block_with_message_inout() input = block_with_message_output() output = block_with_message_input() self.tb.msg_connect(input, "test", hier, "test") self.tb.msg_connect(hier, "test", output, "test") self.run_top_block() self.assert_has_num_subscriptions(input, "test", 1) self.assert_has_subscription(input, "test", hier.input, "test") self.assert_has_num_subscriptions(hier, "test", 0) self.assert_has_num_subscriptions(hier.output, "test", 1) self.assert_has_subscription(hier.output, "test", output, "test") self.tb.msg_disconnect(input, "test", hier, "test") self.tb.msg_disconnect(hier, "test", output, "test") self.assert_has_num_subscriptions(input, "test", 0) self.assert_has_num_subscriptions(hier.output, "test", 0) def test_multiple_connections(self): hier = hier_block_with_message_output() x = block_with_message_input() y = block_with_message_input() self.tb.msg_connect(hier, "test", x, "test") self.tb.msg_connect(hier, "test", y, "test") self.run_top_block() self.assert_has_num_subscriptions(hier, "test", 0) self.assert_has_num_subscriptions(hier.block, "test", 2) self.assert_has_subscription(hier.block, "test", x, "test") self.assert_has_subscription(hier.block, "test", y, "test") self.tb.msg_disconnect(hier, "test", y, "test") self.assert_has_num_subscriptions(hier, "test", 0) self.assert_has_num_subscriptions(hier.block, "test", 1) self.assert_has_subscription(hier.block, "test", x, "test") self.run_top_block() self.tb.msg_disconnect(hier, "test", x, "test") self.assert_has_num_subscriptions(hier.block, "test", 0) if __name__ == '__main__': gr_unittest.run(test_hier_block2_message_connections, "test_hier_block2_message_connections.xml") gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/top_block.py0000664000175000017500000001502512207440367024714 0ustar jcorganjcorgan# # Copyright 2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from runtime_swig import top_block_swig, \ top_block_wait_unlocked, top_block_run_unlocked, \ top_block_start_unlocked, top_block_stop_unlocked #import gnuradio.gr.gr_threading as _threading import gr_threading as _threading # # There is no problem that can't be solved with an additional # level of indirection... # # This kludge allows ^C to interrupt top_block.run and top_block.wait # # The problem that we are working around is that Python only services # signals (e.g., KeyboardInterrupt) in its main thread. If the main # thread is blocked in our C++ version of wait, even though Python's # SIGINT handler fires, and even though there may be other python # threads running, no one will know. Thus instead of directly waiting # in the thread that calls wait (which is likely to be the Python main # thread), we create a separate thread that does the blocking wait, # and then use the thread that called wait to do a slow poll of an # event queue. That thread, which is executing "wait" below is # interruptable, and if it sees a KeyboardInterrupt, executes a stop # on the top_block, then goes back to waiting for it to complete. # This ensures that the unlocked wait that was in progress (in the # _top_block_waiter thread) can complete, release its mutex and back # out. If we don't do that, we are never able to clean up, and nasty # things occur like leaving the USRP transmitter sending a carrier. # # See also top_block.wait (below), which uses this class to implement # the interruptable wait. # class _top_block_waiter(_threading.Thread): def __init__(self, tb): _threading.Thread.__init__(self) self.setDaemon(1) self.tb = tb self.event = _threading.Event() self.start() def run(self): top_block_wait_unlocked(self.tb) self.event.set() def wait(self): try: while not self.event.isSet(): self.event.wait(0.100) except KeyboardInterrupt: self.tb.stop() self.wait() # # This hack forces a 'has-a' relationship to look like an 'is-a' one. # # It allows Python classes to subclass this one, while passing through # method calls to the C++ class shared pointer from SWIG. # # It also allows us to intercept method calls if needed. # # This allows the 'run_locked' methods, which are defined in gr_top_block.i, # to release the Python global interpreter lock before calling the actual # method in gr_top_block # class top_block(object): """ Top-level hierarchical block representing a flow-graph. This is a python wrapper around the C++ implementation to allow python subclassing. """ def __init__(self, name="top_block"): self._tb = top_block_swig(name) def __getattr__(self, name): if not hasattr(self, "_tb"): raise RuntimeError("top_block: invalid state--did you forget to call gr.top_block.__init__ in a derived class?") return getattr(self._tb, name) def start(self, max_noutput_items=10000000): top_block_start_unlocked(self._tb, max_noutput_items) def stop(self): top_block_stop_unlocked(self._tb) def run(self, max_noutput_items=10000000): self.start(max_noutput_items) self.wait() def wait(self): _top_block_waiter(self._tb).wait() # FIXME: these are duplicated from hier_block2.py; they should really be implemented # in the original C++ class (gr_hier_block2), then they would all be inherited here def connect(self, *points): '''connect requires one or more arguments that can be coerced to endpoints. If more than two arguments are provided, they are connected together successively. ''' if len (points) < 1: raise ValueError, ("connect requires at least one endpoint; %d provided." % (len (points),)) else: if len(points) == 1: self._tb.primitive_connect(points[0].to_basic_block()) else: for i in range (1, len (points)): self._connect(points[i-1], points[i]) def msg_connect(self, src, srcport, dst, dstport): self.primitive_msg_connect(src.to_basic_block(), srcport, dst.to_basic_block(), dstport); def msg_disconnect(self, src, srcport, dst, dstport): self.primitive_msg_disconnect(src.to_basic_block(), srcport, dst.to_basic_block(), dstport); def _connect(self, src, dst): (src_block, src_port) = self._coerce_endpoint(src) (dst_block, dst_port) = self._coerce_endpoint(dst) self._tb.primitive_connect(src_block.to_basic_block(), src_port, dst_block.to_basic_block(), dst_port) def _coerce_endpoint(self, endp): if hasattr(endp, 'to_basic_block'): return (endp, 0) else: if hasattr(endp, "__getitem__") and len(endp) == 2: return endp # Assume user put (block, port) else: raise ValueError("unable to coerce endpoint") def disconnect(self, *points): '''disconnect requires one or more arguments that can be coerced to endpoints. If more than two arguments are provided, they are disconnected successively. ''' if len (points) < 1: raise ValueError, ("disconnect requires at least one endpoint; %d provided." % (len (points),)) else: if len(points) == 1: self._tb.primitive_disconnect(points[0].to_basic_block()) else: for i in range (1, len (points)): self._disconnect(points[i-1], points[i]) def _disconnect(self, src, dst): (src_block, src_port) = self._coerce_endpoint(src) (dst_block, dst_port) = self._coerce_endpoint(dst) self._tb.primitive_disconnect(src_block.to_basic_block(), src_port, dst_block.to_basic_block(), dst_port) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/gateway.py0000664000175000017500000002163212207440367024402 0ustar jcorganjcorgan# # Copyright 2011-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import runtime_swig as gr from runtime_swig import io_signature, io_signaturev from runtime_swig import block_gw_message_type from runtime_swig import block_gateway import numpy ######################################################################## # Magic to turn pointers into numpy arrays # http://docs.scipy.org/doc/numpy/reference/arrays.interface.html ######################################################################## def pointer_to_ndarray(addr, dtype, nitems): class array_like: __array_interface__ = { 'data' : (int(addr), False), 'typestr' : dtype.base.str, 'descr' : dtype.base.descr, 'shape' : (nitems,) + dtype.shape, 'strides' : None, 'version' : 3 } return numpy.asarray(array_like()).view(dtype.base) ######################################################################## # Handler that does callbacks from C++ ######################################################################## class gateway_handler(gr.feval_ll): #dont put a constructor, it wont work def init(self, callback): self._callback = callback def eval(self, arg): try: self._callback() except Exception as ex: print("handler caught exception: %s"%ex) import traceback; traceback.print_exc() raise ex return 0 ######################################################################## # Handler that does callbacks from C++ ######################################################################## class msg_handler(gr.feval_p): #dont put a constructor, it wont work def init(self, callback): self._callback = callback def eval(self, arg): try: self._callback(arg) except Exception as ex: print("handler caught exception: %s"%ex) import traceback; traceback.print_exc() raise ex return 0 ######################################################################## # The guts that make this into a gr block ######################################################################## class gateway_block(object): def __init__(self, name, in_sig, out_sig, work_type, factor): #ensure that the sigs are iterable dtypes def sig_to_dtype_sig(sig): if sig is None: sig = () return map(numpy.dtype, sig) self.__in_sig = sig_to_dtype_sig(in_sig) self.__out_sig = sig_to_dtype_sig(out_sig) #cache the ranges to iterate when dispatching work self.__in_indexes = range(len(self.__in_sig)) self.__out_indexes = range(len(self.__out_sig)) #convert the signatures into gr.io_signatures def sig_to_gr_io_sigv(sig): if not len(sig): return io_signature(0, 0, 0) return io_signaturev(len(sig), len(sig), [s.itemsize for s in sig]) gr_in_sig = sig_to_gr_io_sigv(self.__in_sig) gr_out_sig = sig_to_gr_io_sigv(self.__out_sig) #create internal gateway block self.__handler = gateway_handler() self.__handler.init(self.__gr_block_handle) self.__gateway = block_gateway( self.__handler, name, gr_in_sig, gr_out_sig, work_type, factor) self.__message = self.__gateway.block_message() #dict to keep references to all message handlers self.__msg_handlers = {} #register block functions prefix = 'block__' for attr in [x for x in dir(self.__gateway) if x.startswith(prefix)]: setattr(self, attr.replace(prefix, ''), getattr(self.__gateway, attr)) self.pop_msg_queue = lambda: gr.block_gw_pop_msg_queue_safe(self.__gateway) def to_basic_block(self): """ Makes this block connectable by hier/top block python """ return self.__gateway.to_basic_block() def __gr_block_handle(self): """ Dispatch tasks according to the action type specified in the message. """ if self.__message.action == gr.block_gw_message_type.ACTION_GENERAL_WORK: self.__message.general_work_args_return_value = self.general_work( input_items=[pointer_to_ndarray( self.__message.general_work_args_input_items[i], self.__in_sig[i], self.__message.general_work_args_ninput_items[i] ) for i in self.__in_indexes], output_items=[pointer_to_ndarray( self.__message.general_work_args_output_items[i], self.__out_sig[i], self.__message.general_work_args_noutput_items ) for i in self.__out_indexes], ) elif self.__message.action == gr.block_gw_message_type.ACTION_WORK: self.__message.work_args_return_value = self.work( input_items=[pointer_to_ndarray( self.__message.work_args_input_items[i], self.__in_sig[i], self.__message.work_args_ninput_items ) for i in self.__in_indexes], output_items=[pointer_to_ndarray( self.__message.work_args_output_items[i], self.__out_sig[i], self.__message.work_args_noutput_items ) for i in self.__out_indexes], ) elif self.__message.action == gr.block_gw_message_type.ACTION_FORECAST: self.forecast( noutput_items=self.__message.forecast_args_noutput_items, ninput_items_required=self.__message.forecast_args_ninput_items_required, ) elif self.__message.action == gr.block_gw_message_type.ACTION_START: self.__message.start_args_return_value = self.start() elif self.__message.action == gr.block_gw_message_type.ACTION_STOP: self.__message.stop_args_return_value = self.stop() def forecast(self, noutput_items, ninput_items_required): """ forecast is only called from a general block this is the default implementation """ for ninput_item in ninput_items_required: ninput_item = noutput_items + self.history() - 1; return def general_work(self, *args, **kwargs): """general work to be overloaded in a derived class""" raise NotImplementedError("general work not implemented") def work(self, *args, **kwargs): """work to be overloaded in a derived class""" raise NotImplementedError("work not implemented") def start(self): return True def stop(self): return True def set_msg_handler(self, which_port, handler_func): handler = msg_handler() handler.init(handler_func) self.__gateway.set_msg_handler_feval(which_port, handler) # Save handler object in class so it's not garbage collected self.__msg_handlers[which_port] = handler ######################################################################## # Wrappers for the user to inherit from ######################################################################## class basic_block(gateway_block): def __init__(self, name, in_sig, out_sig): gateway_block.__init__(self, name=name, in_sig=in_sig, out_sig=out_sig, work_type=gr.GR_BLOCK_GW_WORK_GENERAL, factor=1, #not relevant factor ) class sync_block(gateway_block): def __init__(self, name, in_sig, out_sig): gateway_block.__init__(self, name=name, in_sig=in_sig, out_sig=out_sig, work_type=gr.GR_BLOCK_GW_WORK_SYNC, factor=1, ) class decim_block(gateway_block): def __init__(self, name, in_sig, out_sig, decim): gateway_block.__init__(self, name=name, in_sig=in_sig, out_sig=out_sig, work_type=gr.GR_BLOCK_GW_WORK_DECIM, factor=decim, ) class interp_block(gateway_block): def __init__(self, name, in_sig, out_sig, interp): gateway_block.__init__(self, name=name, in_sig=in_sig, out_sig=out_sig, work_type=gr.GR_BLOCK_GW_WORK_INTERP, factor=interp, ) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/qa_tag_utils.py0000775000175000017500000000275012207440367025420 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest try: import pmt_swig as pmt except ImportError: import pmt class test_tag_utils (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): t = gr.tag_t() t.offset = 10 t.key = pmt.string_to_symbol('key') t.value = pmt.from_long(23) t.srcid = pmt.from_bool(False) pt = gr.tag_to_python(t) self.assertEqual(pt.key, 'key') self.assertEqual(pt.value, 23) self.assertEqual(pt.offset, 10) if __name__ == '__main__': print 'hi' gr_unittest.run(test_tag_utils, "test_tag_utils.xml") gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/hier_block2.py0000664000175000017500000001165212207440367025125 0ustar jcorganjcorgan# # Copyright 2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from runtime_swig import hier_block2_swig import pmt # # This hack forces a 'has-a' relationship to look like an 'is-a' one. # # It allows Python classes to subclass this one, while passing through # method calls to the C++ class shared pointer from SWIG. # # It also allows us to intercept method calls if needed # class hier_block2(object): """ Subclass this to create a python hierarchical block. This is a python wrapper around the C++ hierarchical block implementation. Provides convenience functions and allows proper Python subclassing. """ def __init__(self, name, input_signature, output_signature): """ Create a hierarchical block with a given name and I/O signatures. """ self._hb = hier_block2_swig(name, input_signature, output_signature) def __getattr__(self, name): """ Pass-through member requests to the C++ object. """ if not hasattr(self, "_hb"): raise RuntimeError("hier_block2: invalid state--did you forget to call gr.hier_block2.__init__ in a derived class?") return getattr(self._hb, name) def connect(self, *points): """ Connect two or more block endpoints. An endpoint is either a (block, port) tuple or a block instance. In the latter case, the port number is assumed to be zero. To connect the hierarchical block external inputs or outputs to internal block inputs or outputs, use 'self' in the connect call. If multiple arguments are provided, connect will attempt to wire them in series, interpreting the endpoints as inputs or outputs as appropriate. """ if len (points) < 1: raise ValueError, ("connect requires at least one endpoint; %d provided." % (len (points),)) else: if len(points) == 1: self._hb.primitive_connect(points[0].to_basic_block()) else: for i in range (1, len (points)): self._connect(points[i-1], points[i]) def _connect(self, src, dst): (src_block, src_port) = self._coerce_endpoint(src) (dst_block, dst_port) = self._coerce_endpoint(dst) self._hb.primitive_connect(src_block.to_basic_block(), src_port, dst_block.to_basic_block(), dst_port) def _coerce_endpoint(self, endp): if hasattr(endp, 'to_basic_block'): return (endp, 0) else: if hasattr(endp, "__getitem__") and len(endp) == 2: return endp # Assume user put (block, port) else: raise ValueError("unable to coerce endpoint") def disconnect(self, *points): """ Disconnect two endpoints in the flowgraph. To disconnect the hierarchical block external inputs or outputs to internal block inputs or outputs, use 'self' in the connect call. If more than two arguments are provided, they are disconnected successively. """ if len (points) < 1: raise ValueError, ("disconnect requires at least one endpoint; %d provided." % (len (points),)) else: if len (points) == 1: self._hb.primitive_disconnect(points[0].to_basic_block()) else: for i in range (1, len (points)): self._disconnect(points[i-1], points[i]) def _disconnect(self, src, dst): (src_block, src_port) = self._coerce_endpoint(src) (dst_block, dst_port) = self._coerce_endpoint(dst) self._hb.primitive_disconnect(src_block.to_basic_block(), src_port, dst_block.to_basic_block(), dst_port) def msg_connect(self, src, srcport, dst, dstport): self.primitive_msg_connect(src.to_basic_block(), srcport, dst.to_basic_block(), dstport); def msg_disconnect(self, src, srcport, dst, dstport): self.primitive_msg_disconnect(src.to_basic_block(), srcport, dst.to_basic_block(), dstport); def message_port_register_hier_in(self, portname): self.primitive_message_port_register_hier_in(pmt.intern(portname)); def message_port_register_hier_out(self, portname): self.primitive_message_port_register_hier_out(pmt.intern(portname)); gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/__init__.py0000664000175000017500000000310712207440367024475 0ustar jcorganjcorgan# # Copyright 2003-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # The presence of this file turns this directory into a Python package """ Core contents. """ # This is the main GNU Radio python module. # We pull the swig output and the other modules into the gnuradio.gr namespace # If gnuradio is installed then the swig output will be in this directory. # Otherwise it will reside in ../../../swig. import os try: from runtime_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "..", "swig")) from runtime_swig import * from exceptions import * from top_block import * from hier_block2 import * from tag_utils import * from gateway import basic_block, sync_block, decim_block, interp_block # Force the preference database to be initialized prefs = prefs.singleton gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/gr_threading_24.py0000664000175000017500000006164312207440367025711 0ustar jcorganjcorgan"""Thread module emulating a subset of Java's threading model.""" # This started life as the threading.py module of Python 2.4 # It's been patched to fix a problem with join, where a KeyboardInterrupt # caused a lock to be left in the acquired state. import sys as _sys try: import thread except ImportError: del _sys.modules[__name__] raise from time import time as _time, sleep as _sleep from traceback import format_exc as _format_exc from collections import deque # Rename some stuff so "from threading import *" is safe __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Timer', 'setprofile', 'settrace', 'local'] _start_new_thread = thread.start_new_thread _allocate_lock = thread.allocate_lock _get_ident = thread.get_ident ThreadError = thread.error del thread # Debug support (adapted from ihooks.py). # All the major classes here derive from _Verbose. We force that to # be a new-style class so that all the major classes here are new-style. # This helps debugging (type(instance) is more revealing for instances # of new-style classes). _VERBOSE = False if __debug__: class _Verbose(object): def __init__(self, verbose=None): if verbose is None: verbose = _VERBOSE self.__verbose = verbose def _note(self, format, *args): if self.__verbose: format = format % args format = "%s: %s\n" % ( currentThread().getName(), format) _sys.stderr.write(format) else: # Disable this when using "python -O" class _Verbose(object): def __init__(self, verbose=None): pass def _note(self, *args): pass # Support for profile and trace hooks _profile_hook = None _trace_hook = None def setprofile(func): global _profile_hook _profile_hook = func def settrace(func): global _trace_hook _trace_hook = func # Synchronization classes Lock = _allocate_lock def RLock(*args, **kwargs): return _RLock(*args, **kwargs) class _RLock(_Verbose): def __init__(self, verbose=None): _Verbose.__init__(self, verbose) self.__block = _allocate_lock() self.__owner = None self.__count = 0 def __repr__(self): return "<%s(%s, %d)>" % ( self.__class__.__name__, self.__owner and self.__owner.getName(), self.__count) def acquire(self, blocking=1): me = currentThread() if self.__owner is me: self.__count = self.__count + 1 if __debug__: self._note("%s.acquire(%s): recursive success", self, blocking) return 1 rc = self.__block.acquire(blocking) if rc: self.__owner = me self.__count = 1 if __debug__: self._note("%s.acquire(%s): initial succes", self, blocking) else: if __debug__: self._note("%s.acquire(%s): failure", self, blocking) return rc def release(self): me = currentThread() assert self.__owner is me, "release() of un-acquire()d lock" self.__count = count = self.__count - 1 if not count: self.__owner = None self.__block.release() if __debug__: self._note("%s.release(): final release", self) else: if __debug__: self._note("%s.release(): non-final release", self) # Internal methods used by condition variables def _acquire_restore(self, (count, owner)): self.__block.acquire() self.__count = count self.__owner = owner if __debug__: self._note("%s._acquire_restore()", self) def _release_save(self): if __debug__: self._note("%s._release_save()", self) count = self.__count self.__count = 0 owner = self.__owner self.__owner = None self.__block.release() return (count, owner) def _is_owned(self): return self.__owner is currentThread() def Condition(*args, **kwargs): return _Condition(*args, **kwargs) class _Condition(_Verbose): def __init__(self, lock=None, verbose=None): _Verbose.__init__(self, verbose) if lock is None: lock = RLock() self.__lock = lock # Export the lock's acquire() and release() methods self.acquire = lock.acquire self.release = lock.release # If the lock defines _release_save() and/or _acquire_restore(), # these override the default implementations (which just call # release() and acquire() on the lock). Ditto for _is_owned(). try: self._release_save = lock._release_save except AttributeError: pass try: self._acquire_restore = lock._acquire_restore except AttributeError: pass try: self._is_owned = lock._is_owned except AttributeError: pass self.__waiters = [] def __repr__(self): return "" % (self.__lock, len(self.__waiters)) def _release_save(self): self.__lock.release() # No state to save def _acquire_restore(self, x): self.__lock.acquire() # Ignore saved state def _is_owned(self): # Return True if lock is owned by currentThread. # This method is called only if __lock doesn't have _is_owned(). if self.__lock.acquire(0): self.__lock.release() return False else: return True def wait(self, timeout=None): assert self._is_owned(), "wait() of un-acquire()d lock" waiter = _allocate_lock() waiter.acquire() self.__waiters.append(waiter) saved_state = self._release_save() try: # restore state no matter what (e.g., KeyboardInterrupt) if timeout is None: waiter.acquire() if __debug__: self._note("%s.wait(): got it", self) else: # Balancing act: We can't afford a pure busy loop, so we # have to sleep; but if we sleep the whole timeout time, # we'll be unresponsive. The scheme here sleeps very # little at first, longer as time goes on, but never longer # than 20 times per second (or the timeout time remaining). endtime = _time() + timeout delay = 0.0005 # 500 us -> initial delay of 1 ms while True: gotit = waiter.acquire(0) if gotit: break remaining = endtime - _time() if remaining <= 0: break delay = min(delay * 2, remaining, .05) _sleep(delay) if not gotit: if __debug__: self._note("%s.wait(%s): timed out", self, timeout) try: self.__waiters.remove(waiter) except ValueError: pass else: if __debug__: self._note("%s.wait(%s): got it", self, timeout) finally: self._acquire_restore(saved_state) def notify(self, n=1): assert self._is_owned(), "notify() of un-acquire()d lock" __waiters = self.__waiters waiters = __waiters[:n] if not waiters: if __debug__: self._note("%s.notify(): no waiters", self) return self._note("%s.notify(): notifying %d waiter%s", self, n, n!=1 and "s" or "") for waiter in waiters: waiter.release() try: __waiters.remove(waiter) except ValueError: pass def notifyAll(self): self.notify(len(self.__waiters)) def Semaphore(*args, **kwargs): return _Semaphore(*args, **kwargs) class _Semaphore(_Verbose): # After Tim Peters' semaphore class, but not quite the same (no maximum) def __init__(self, value=1, verbose=None): assert value >= 0, "Semaphore initial value must be >= 0" _Verbose.__init__(self, verbose) self.__cond = Condition(Lock()) self.__value = value def acquire(self, blocking=1): rc = False self.__cond.acquire() while self.__value == 0: if not blocking: break if __debug__: self._note("%s.acquire(%s): blocked waiting, value=%s", self, blocking, self.__value) self.__cond.wait() else: self.__value = self.__value - 1 if __debug__: self._note("%s.acquire: success, value=%s", self, self.__value) rc = True self.__cond.release() return rc def release(self): self.__cond.acquire() self.__value = self.__value + 1 if __debug__: self._note("%s.release: success, value=%s", self, self.__value) self.__cond.notify() self.__cond.release() def BoundedSemaphore(*args, **kwargs): return _BoundedSemaphore(*args, **kwargs) class _BoundedSemaphore(_Semaphore): """Semaphore that checks that # releases is <= # acquires""" def __init__(self, value=1, verbose=None): _Semaphore.__init__(self, value, verbose) self._initial_value = value def release(self): if self._Semaphore__value >= self._initial_value: raise ValueError, "Semaphore released too many times" return _Semaphore.release(self) def Event(*args, **kwargs): return _Event(*args, **kwargs) class _Event(_Verbose): # After Tim Peters' event class (without is_posted()) def __init__(self, verbose=None): _Verbose.__init__(self, verbose) self.__cond = Condition(Lock()) self.__flag = False def isSet(self): return self.__flag def set(self): self.__cond.acquire() try: self.__flag = True self.__cond.notifyAll() finally: self.__cond.release() def clear(self): self.__cond.acquire() try: self.__flag = False finally: self.__cond.release() def wait(self, timeout=None): self.__cond.acquire() try: if not self.__flag: self.__cond.wait(timeout) finally: self.__cond.release() # Helper to generate new thread names _counter = 0 def _newname(template="Thread-%d"): global _counter _counter = _counter + 1 return template % _counter # Active thread administration _active_limbo_lock = _allocate_lock() _active = {} _limbo = {} # Main class for threads class Thread(_Verbose): __initialized = False # Need to store a reference to sys.exc_info for printing # out exceptions when a thread tries to use a global var. during interp. # shutdown and thus raises an exception about trying to perform some # operation on/with a NoneType __exc_info = _sys.exc_info def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, verbose=None): assert group is None, "group argument must be None for now" _Verbose.__init__(self, verbose) self.__target = target self.__name = str(name or _newname()) self.__args = args self.__kwargs = kwargs self.__daemonic = self._set_daemon() self.__started = False self.__stopped = False self.__block = Condition(Lock()) self.__initialized = True # sys.stderr is not stored in the class like # sys.exc_info since it can be changed between instances self.__stderr = _sys.stderr def _set_daemon(self): # Overridden in _MainThread and _DummyThread return currentThread().isDaemon() def __repr__(self): assert self.__initialized, "Thread.__init__() was not called" status = "initial" if self.__started: status = "started" if self.__stopped: status = "stopped" if self.__daemonic: status = status + " daemon" return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status) def start(self): assert self.__initialized, "Thread.__init__() not called" assert not self.__started, "thread already started" if __debug__: self._note("%s.start(): starting thread", self) _active_limbo_lock.acquire() _limbo[self] = self _active_limbo_lock.release() _start_new_thread(self.__bootstrap, ()) self.__started = True _sleep(0.000001) # 1 usec, to let the thread run (Solaris hack) def run(self): if self.__target: self.__target(*self.__args, **self.__kwargs) def __bootstrap(self): try: self.__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self del _limbo[self] _active_limbo_lock.release() if __debug__: self._note("%s.__bootstrap(): thread started", self) if _trace_hook: self._note("%s.__bootstrap(): registering trace hook", self) _sys.settrace(_trace_hook) if _profile_hook: self._note("%s.__bootstrap(): registering profile hook", self) _sys.setprofile(_profile_hook) try: self.run() except SystemExit: if __debug__: self._note("%s.__bootstrap(): raised SystemExit", self) except: if __debug__: self._note("%s.__bootstrap(): unhandled exception", self) # If sys.stderr is no more (most likely from interpreter # shutdown) use self.__stderr. Otherwise still use sys (as in # _sys) in case sys.stderr was redefined since the creation of # self. if _sys: _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.getName(), _format_exc())) else: # Do the best job possible w/o a huge amt. of code to # approximate a traceback (code ideas from # Lib/traceback.py) exc_type, exc_value, exc_tb = self.__exc_info() try: print>>self.__stderr, ( "Exception in thread " + self.getName() + " (most likely raised during interpreter shutdown):") print>>self.__stderr, ( "Traceback (most recent call last):") while exc_tb: print>>self.__stderr, ( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)) exc_tb = exc_tb.tb_next print>>self.__stderr, ("%s: %s" % (exc_type, exc_value)) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: del exc_type, exc_value, exc_tb else: if __debug__: self._note("%s.__bootstrap(): normal return", self) finally: self.__stop() try: self.__delete() except: pass def __stop(self): self.__block.acquire() self.__stopped = True self.__block.notifyAll() self.__block.release() def __delete(self): "Remove current thread from the dict of currently running threads." # Notes about running with dummy_thread: # # Must take care to not raise an exception if dummy_thread is being # used (and thus this module is being used as an instance of # dummy_threading). dummy_thread.get_ident() always returns -1 since # there is only one thread if dummy_thread is being used. Thus # len(_active) is always <= 1 here, and any Thread instance created # overwrites the (if any) thread currently registered in _active. # # An instance of _MainThread is always created by 'threading'. This # gets overwritten the instant an instance of Thread is created; both # threads return -1 from dummy_thread.get_ident() and thus have the # same key in the dict. So when the _MainThread instance created by # 'threading' tries to clean itself up when atexit calls this method # it gets a KeyError if another Thread instance was created. # # This all means that KeyError from trying to delete something from # _active if dummy_threading is being used is a red herring. But # since it isn't if dummy_threading is *not* being used then don't # hide the exception. _active_limbo_lock.acquire() try: try: del _active[_get_ident()] except KeyError: if 'dummy_threading' not in _sys.modules: raise finally: _active_limbo_lock.release() def join(self, timeout=None): assert self.__initialized, "Thread.__init__() not called" assert self.__started, "cannot join thread before it is started" assert self is not currentThread(), "cannot join current thread" if __debug__: if not self.__stopped: self._note("%s.join(): waiting until thread stops", self) self.__block.acquire() try: if timeout is None: while not self.__stopped: self.__block.wait() if __debug__: self._note("%s.join(): thread stopped", self) else: deadline = _time() + timeout while not self.__stopped: delay = deadline - _time() if delay <= 0: if __debug__: self._note("%s.join(): timed out", self) break self.__block.wait(delay) else: if __debug__: self._note("%s.join(): thread stopped", self) finally: self.__block.release() def getName(self): assert self.__initialized, "Thread.__init__() not called" return self.__name def setName(self, name): assert self.__initialized, "Thread.__init__() not called" self.__name = str(name) def isAlive(self): assert self.__initialized, "Thread.__init__() not called" return self.__started and not self.__stopped def isDaemon(self): assert self.__initialized, "Thread.__init__() not called" return self.__daemonic def setDaemon(self, daemonic): assert self.__initialized, "Thread.__init__() not called" assert not self.__started, "cannot set daemon status of active thread" self.__daemonic = daemonic # The timer class was contributed by Itamar Shtull-Trauring def Timer(*args, **kwargs): return _Timer(*args, **kwargs) class _Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=[], kwargs={}) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.isSet(): self.function(*self.args, **self.kwargs) self.finished.set() # Special thread class to represent the main thread # This is garbage collected through an exit handler class _MainThread(Thread): def __init__(self): Thread.__init__(self, name="MainThread") self._Thread__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() import atexit atexit.register(self.__exitfunc) def _set_daemon(self): return False def __exitfunc(self): self._Thread__stop() t = _pickSomeNonDaemonThread() if t: if __debug__: self._note("%s: waiting for other threads", self) while t: t.join() t = _pickSomeNonDaemonThread() if __debug__: self._note("%s: exiting", self) self._Thread__delete() def _pickSomeNonDaemonThread(): for t in enumerate(): if not t.isDaemon() and t.isAlive(): return t return None # Dummy thread class to represent threads not started here. # These aren't garbage collected when they die, # nor can they be waited for. # Their purpose is to return *something* from currentThread(). # They are marked as daemon threads so we won't wait for them # when we exit (conform previous semantics). class _DummyThread(Thread): def __init__(self): Thread.__init__(self, name=_newname("Dummy-%d")) self._Thread__started = True _active_limbo_lock.acquire() _active[_get_ident()] = self _active_limbo_lock.release() def _set_daemon(self): return True def join(self, timeout=None): assert False, "cannot join a dummy thread" # Global API functions def currentThread(): try: return _active[_get_ident()] except KeyError: ##print "currentThread(): no current thread for", _get_ident() return _DummyThread() def activeCount(): _active_limbo_lock.acquire() count = len(_active) + len(_limbo) _active_limbo_lock.release() return count def enumerate(): _active_limbo_lock.acquire() active = _active.values() + _limbo.values() _active_limbo_lock.release() return active # Create the main thread object _MainThread() # get thread-local implementation, either from the thread # module, or from the python fallback try: from thread import _local as local except ImportError: from _threading_local import local # Self-test code def _test(): class BoundedQueue(_Verbose): def __init__(self, limit): _Verbose.__init__(self) self.mon = RLock() self.rc = Condition(self.mon) self.wc = Condition(self.mon) self.limit = limit self.queue = deque() def put(self, item): self.mon.acquire() while len(self.queue) >= self.limit: self._note("put(%s): queue full", item) self.wc.wait() self.queue.append(item) self._note("put(%s): appended, length now %d", item, len(self.queue)) self.rc.notify() self.mon.release() def get(self): self.mon.acquire() while not self.queue: self._note("get(): queue empty") self.rc.wait() item = self.queue.popleft() self._note("get(): got %s, %d left", item, len(self.queue)) self.wc.notify() self.mon.release() return item class ProducerThread(Thread): def __init__(self, queue, quota): Thread.__init__(self, name="Producer") self.queue = queue self.quota = quota def run(self): from random import random counter = 0 while counter < self.quota: counter = counter + 1 self.queue.put("%s.%d" % (self.getName(), counter)) _sleep(random() * 0.00001) class ConsumerThread(Thread): def __init__(self, queue, count): Thread.__init__(self, name="Consumer") self.queue = queue self.count = count def run(self): while self.count > 0: item = self.queue.get() print item self.count = self.count - 1 NP = 3 QL = 4 NI = 5 Q = BoundedQueue(QL) P = [] for i in range(NP): t = ProducerThread(Q, NI) t.setName("Producer-%d" % (i+1)) P.append(t) C = ConsumerThread(Q, NI*NP) for t in P: t.start() _sleep(0.000001) C.start() for t in P: t.join() C.join() if __name__ == '__main__': _test() gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr/qa_kludged_imports.py0000775000175000017500000000225712207440367026623 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2008,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest class test_kludged_imports (gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_gru_import(self): # make sure that this somewhat magic import works from gnuradio import gru if __name__ == '__main__': gr_unittest.run(test_kludged_imports, "test_kludged_imports.xml") gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr_unittest.py0000775000175000017500000001423712207440367024706 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ GNU radio specific extension of unittest. """ import unittest import gr_xmlrunner import sys, os, stat class TestCase(unittest.TestCase): """A subclass of unittest.TestCase that adds additional assertions Adds new methods assertComplexAlmostEqual, assertComplexTuplesAlmostEqual and assertFloatTuplesAlmostEqual """ def assertComplexAlmostEqual (self, first, second, places=7, msg=None): """Fail if the two complex objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) is usually not the same as significant digits (measured from the most signficant digit). """ if round(second.real-first.real, places) != 0: raise self.failureException, \ (msg or '%s != %s within %s places' % (`first`, `second`, `places` )) if round(second.imag-first.imag, places) != 0: raise self.failureException, \ (msg or '%s != %s within %s places' % (`first`, `second`, `places` )) def assertComplexAlmostEqual2 (self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): """ Fail if the two complex objects are unequal as determined by... """ if abs(ref - x) < abs_eps: return if abs(ref) > abs_eps: if abs(ref-x)/abs(ref) > rel_eps: raise self.failureException, \ (msg or '%s != %s rel_error = %s rel_limit = %s' % ( `ref`, `x`, abs(ref-x)/abs(ref), `rel_eps` )) else: raise self.failureException, \ (msg or '%s != %s rel_error = %s rel_limit = %s' % ( `ref`, `x`, abs(ref-x)/abs(ref), `rel_eps` )) def assertComplexTuplesAlmostEqual (self, a, b, places=7, msg=None): self.assertEqual (len(a), len(b)) for i in xrange (len(a)): self.assertComplexAlmostEqual (a[i], b[i], places, msg) def assertComplexTuplesAlmostEqual2 (self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): self.assertEqual (len(ref), len(x)) for i in xrange (len(ref)): try: self.assertComplexAlmostEqual2 (ref[i], x[i], abs_eps, rel_eps, msg) except self.failureException, e: #sys.stderr.write("index = %d " % (i,)) #sys.stderr.write("%s\n" % (e,)) raise def assertFloatTuplesAlmostEqual (self, a, b, places=7, msg=None): self.assertEqual (len(a), len(b)) for i in xrange (len(a)): self.assertAlmostEqual (a[i], b[i], places, msg) def assertFloatTuplesAlmostEqual2 (self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): self.assertEqual (len(ref), len(x)) for i in xrange (len(ref)): try: self.assertComplexAlmostEqual2 (ref[i], x[i], abs_eps, rel_eps, msg) except self.failureException, e: #sys.stderr.write("index = %d " % (i,)) #sys.stderr.write("%s\n" % (e,)) raise TestResult = unittest.TestResult TestSuite = unittest.TestSuite FunctionTestCase = unittest.FunctionTestCase TestLoader = unittest.TestLoader TextTestRunner = unittest.TextTestRunner TestProgram = unittest.TestProgram main = TestProgram def run(PUT, filename=None): ''' Runs the unittest on a TestCase and produces an optional XML report PUT: the program under test and should be a gr_unittest.TestCase filename: an optional filename to save the XML report of the tests this will live in ./.unittests/python ''' # Run this is given a file name if(filename is not None): basepath = "./.unittests" path = basepath + "/python" if not os.path.exists(basepath): os.makedirs(basepath, 0750) xmlrunner = None # only proceed if .unittests is writable st = os.stat(basepath)[stat.ST_MODE] if(st & stat.S_IWUSR > 0): # Test if path exists; if not, build it if not os.path.exists(path): os.makedirs(path, 0750) # Just for safety: make sure we can write here, too st = os.stat(path)[stat.ST_MODE] if(st & stat.S_IWUSR > 0): # Create an XML runner to filename fout = file(path+"/"+filename, "w") xmlrunner = gr_xmlrunner.XMLTestRunner(fout) txtrunner = TextTestRunner(verbosity=1) # Run the test; runner also creates XML output file # FIXME: make xmlrunner output to screen so we don't have to do run and main suite = TestLoader().loadTestsFromTestCase(PUT) # use the xmlrunner if we can write the the directory if(xmlrunner is not None): xmlrunner.run(suite) main() # This will run and fail make check if problem # but does not output to screen. #main(testRunner = xmlrunner) else: # If no filename is given, just run the test main() ############################################################################## # Executing this module from the command line ############################################################################## if __name__ == "__main__": main(module=None) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/gr_xmlrunner.py0000664000175000017500000003052212207440367025051 0ustar jcorganjcorgan""" XML Test Runner for PyUnit """ # Written by Sebastian Rittau and placed in # the Public Domain. With contributions by Paolo Borelli and others. # Added to GNU Radio Oct. 3, 2010 __version__ = "0.1" import os.path import re import sys import time import traceback import unittest from xml.sax.saxutils import escape try: from StringIO import StringIO except ImportError: from io import StringIO class _TestInfo(object): """Information about a particular test. Used by _XMLTestResult. """ def __init__(self, test, time): (self._class, self._method) = test.id().rsplit(".", 1) self._time = time self._error = None self._failure = None @staticmethod def create_success(test, time): """Create a _TestInfo instance for a successful test.""" return _TestInfo(test, time) @staticmethod def create_failure(test, time, failure): """Create a _TestInfo instance for a failed test.""" info = _TestInfo(test, time) info._failure = failure return info @staticmethod def create_error(test, time, error): """Create a _TestInfo instance for an erroneous test.""" info = _TestInfo(test, time) info._error = error return info def print_report(self, stream): """Print information about this test case in XML format to the supplied stream. """ stream.write(' ' % \ { "class": self._class, "method": self._method, "time": self._time, }) if self._failure is not None: self._print_error(stream, 'failure', self._failure) if self._error is not None: self._print_error(stream, 'error', self._error) stream.write('\n') def _print_error(self, stream, tagname, error): """Print information from a failure or error to the supplied stream.""" text = escape(str(error[1])) stream.write('\n') stream.write(' <%s type="%s">%s\n' \ % (tagname, _clsname(error[0]), text)) tb_stream = StringIO() traceback.print_tb(error[2], None, tb_stream) stream.write(escape(tb_stream.getvalue())) stream.write(' \n' % tagname) stream.write(' ') def _clsname(cls): return cls.__module__ + "." + cls.__name__ class _XMLTestResult(unittest.TestResult): """A test result class that stores result as XML. Used by XMLTestRunner. """ def __init__(self, classname): unittest.TestResult.__init__(self) self._test_name = classname self._start_time = None self._tests = [] self._error = None self._failure = None def startTest(self, test): unittest.TestResult.startTest(self, test) self._error = None self._failure = None self._start_time = time.time() def stopTest(self, test): time_taken = time.time() - self._start_time unittest.TestResult.stopTest(self, test) if self._error: info = _TestInfo.create_error(test, time_taken, self._error) elif self._failure: info = _TestInfo.create_failure(test, time_taken, self._failure) else: info = _TestInfo.create_success(test, time_taken) self._tests.append(info) def addError(self, test, err): unittest.TestResult.addError(self, test, err) self._error = err def addFailure(self, test, err): unittest.TestResult.addFailure(self, test, err) self._failure = err def print_report(self, stream, time_taken, out, err): """Prints the XML report to the supplied stream. The time the tests took to perform as well as the captured standard output and standard error streams must be passed in.a """ stream.write('\n' % \ { "n": self._test_name, "t": self.testsRun, "time": time_taken, }) for info in self._tests: info.print_report(stream) stream.write(' \n' % out) stream.write(' \n' % err) stream.write('\n') class XMLTestRunner(object): """A test runner that stores results in XML format compatible with JUnit. XMLTestRunner(stream=None) -> XML test runner The XML file is written to the supplied stream. If stream is None, the results are stored in a file called TEST-..xml in the current working directory (if not overridden with the path property), where and are the module and class name of the test class. """ def __init__(self, stream=None): self._stream = stream self._path = "." def run(self, test): """Run the given test case or test suite.""" class_ = test.__class__ classname = class_.__module__ + "." + class_.__name__ if self._stream == None: filename = "TEST-%s.xml" % classname stream = file(os.path.join(self._path, filename), "w") stream.write('\n') else: stream = self._stream result = _XMLTestResult(classname) start_time = time.time() fss = _fake_std_streams() fss.__enter__() try: test(result) try: out_s = sys.stdout.getvalue() except AttributeError: out_s = "" try: err_s = sys.stderr.getvalue() except AttributeError: err_s = "" finally: fss.__exit__(None, None, None) time_taken = time.time() - start_time result.print_report(stream, time_taken, out_s, err_s) if self._stream is None: stream.close() return result def _set_path(self, path): self._path = path path = property(lambda self: self._path, _set_path, None, """The path where the XML files are stored. This property is ignored when the XML file is written to a file stream.""") class _fake_std_streams(object): def __enter__(self): self._orig_stdout = sys.stdout self._orig_stderr = sys.stderr #sys.stdout = StringIO() #sys.stderr = StringIO() def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout = self._orig_stdout sys.stderr = self._orig_stderr class XMLTestRunnerTest(unittest.TestCase): def setUp(self): self._stream = StringIO() def _try_test_run(self, test_class, expected): """Run the test suite against the supplied test class and compare the XML result against the expected XML string. Fail if the expected string doesn't match the actual string. All time attributes in the expected string should have the value "0.000". All error and failure messages are reduced to "Foobar". """ runner = XMLTestRunner(self._stream) runner.run(unittest.makeSuite(test_class)) got = self._stream.getvalue() # Replace all time="X.YYY" attributes by time="0.000" to enable a # simple string comparison. got = re.sub(r'time="\d+\.\d+"', 'time="0.000"', got) # Likewise, replace all failure and error messages by a simple "Foobar" # string. got = re.sub(r'(?s).*?', r'Foobar', got) got = re.sub(r'(?s).*?', r'Foobar', got) # And finally Python 3 compatibility. got = got.replace('type="builtins.', 'type="exceptions.') self.assertEqual(expected, got) def test_no_tests(self): """Regression test: Check whether a test run without any tests matches a previous run. """ class TestTest(unittest.TestCase): pass self._try_test_run(TestTest, """ """) def test_success(self): """Regression test: Check whether a test run with a successful test matches a previous run. """ class TestTest(unittest.TestCase): def test_foo(self): pass self._try_test_run(TestTest, """ """) def test_failure(self): """Regression test: Check whether a test run with a failing test matches a previous run. """ class TestTest(unittest.TestCase): def test_foo(self): self.assert_(False) self._try_test_run(TestTest, """ Foobar """) def test_error(self): """Regression test: Check whether a test run with a erroneous test matches a previous run. """ class TestTest(unittest.TestCase): def test_foo(self): raise IndexError() self._try_test_run(TestTest, """ Foobar """) def test_stdout_capture(self): """Regression test: Check whether a test run with output to stdout matches a previous run. """ class TestTest(unittest.TestCase): def test_foo(self): sys.stdout.write("Test\n") self._try_test_run(TestTest, """ """) def test_stderr_capture(self): """Regression test: Check whether a test run with output to stderr matches a previous run. """ class TestTest(unittest.TestCase): def test_foo(self): sys.stderr.write("Test\n") self._try_test_run(TestTest, """ """) class NullStream(object): """A file-like object that discards everything written to it.""" def write(self, buffer): pass def test_unittests_changing_stdout(self): """Check whether the XMLTestRunner recovers gracefully from unit tests that change stdout, but don't change it back properly. """ class TestTest(unittest.TestCase): def test_foo(self): sys.stdout = XMLTestRunnerTest.NullStream() runner = XMLTestRunner(self._stream) runner.run(unittest.makeSuite(TestTest)) def test_unittests_changing_stderr(self): """Check whether the XMLTestRunner recovers gracefully from unit tests that change stderr, but don't change it back properly. """ class TestTest(unittest.TestCase): def test_foo(self): sys.stderr = XMLTestRunnerTest.NullStream() runner = XMLTestRunner(self._stream) runner.run(unittest.makeSuite(TestTest)) if __name__ == "__main__": unittest.main() gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/eng_notation.py0000664000175000017500000000430712207440367025015 0ustar jcorganjcorgan# # Copyright 2003 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Display numbers as strings using engineering notation. """ scale_factor = {} scale_factor['E'] = 1e18 scale_factor['P'] = 1e15 scale_factor['T'] = 1e12 scale_factor['G'] = 1e9 scale_factor['M'] = 1e6 scale_factor['k'] = 1e3 scale_factor['m'] = 1e-3 scale_factor['u'] = 1e-6 scale_factor['n'] = 1e-9 scale_factor['p'] = 1e-12 scale_factor['f'] = 1e-15 scale_factor['a'] = 1e-18 def num_to_str (n): '''Convert a number to a string in engineering notation. E.g., 5e-9 -> 5n''' m = abs(n) if m >= 1e9: return "%gG" % (n * 1e-9) elif m >= 1e6: return "%gM" % (n * 1e-6) elif m >= 1e3: return "%gk" % (n * 1e-3) elif m >= 1: return "%g" % (n) elif m >= 1e-3: return "%gm" % (n * 1e3) elif m >= 1e-6: return "%gu" % (n * 1e6) # where's that mu when you need it (unicode?) elif m >= 1e-9: return "%gn" % (n * 1e9) elif m >= 1e-12: return "%gp" % (n * 1e12) elif m >= 1e-15: return "%gf" % (n * 1e15) else: return "%g" % (n) def str_to_num (value): '''Convert a string in engineering notation to a number. E.g., '15m' -> 15e-3''' try: scale = 1.0 suffix = value[-1] if scale_factor.has_key (suffix): return float (value[0:-1]) * scale_factor[suffix] return float (value) except: raise RuntimeError ( "Invalid engineering notation value: %r" % (value,)) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/0000775000175000017500000000000012217337525023626 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/CMakeLists.txt0000664000175000017500000000640312207440367026367 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) EXECUTE_PROCESS( COMMAND ${ICE_SLICE2PY} -I${CMAKE_SOURCE_DIR}/gnuradio-runtime/lib/controlport --output-dir=${CMAKE_BINARY_DIR}/gnuradio-runtime/python ${CMAKE_SOURCE_DIR}/gnuradio-runtime/lib/controlport/gnuradio.ice ) EXECUTE_PROCESS( COMMAND ${ICE_SLICE2PY} -I${CMAKE_SOURCE_DIR}/gnuradio-runtime/lib/controlport --output-dir=${CMAKE_BINARY_DIR}/gnuradio-runtime/python ${CMAKE_SOURCE_DIR}/gnuradio-runtime/lib/controlport/frontend.ice ) EXECUTE_PROCESS( COMMAND ${CMAKE_COMMAND} -E remove ${CMAKE_BINARY_DIR}/gnuradio-runtime/python/gnuradio/__init__.py ) GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_SOURCE_DIR}/__init__.py ${CMAKE_CURRENT_SOURCE_DIR}/IceRadioClient.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/ctrlport/ COMPONENT "runtime_python" ) # We don't want to install these in the root Python directory, but we # aren't given a choice based on the way slice2py generates the # information. GR_PYTHON_INSTALL( FILES ${CMAKE_BINARY_DIR}/gnuradio-runtime/python/gnuradio_ice.py ${CMAKE_BINARY_DIR}/gnuradio-runtime/python/frontend_ice.py DESTINATION ${GR_PYTHON_DIR} COMPONENT "runtime_python" ) GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_BINARY_DIR}/GNURadio/__init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/ctrlport/GNURadio COMPONENT "runtime_python" ) GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_BINARY_DIR}/GNURadio/Booter/__init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/ctrlport/GNURadio/Booter COMPONENT "runtime_python" ) GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_BINARY_DIR}/GNURadio/Frontend/__init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/ctrlport/GNURadio/Frontend COMPONENT "runtime_python" ) install( FILES ${CMAKE_CURRENT_SOURCE_DIR}/icon.png DESTINATION ${GR_PYTHON_DIR}/gnuradio/ctrlport COMPONENT "runtime_python" ) GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_SOURCE_DIR}/GrDataPlotter.py ${CMAKE_CURRENT_SOURCE_DIR}/monitor.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/ctrlport/ COMPONENT "runtime_python" ) GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_SOURCE_DIR}/gr-ctrlport-monitor ${CMAKE_CURRENT_SOURCE_DIR}/gr-perf-monitorx ${CMAKE_CURRENT_SOURCE_DIR}/gr-ctrlport-curses DESTINATION ${GR_RUNTIME_DIR} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitor0000775000175000017500000005251512207440367026611 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, ctrlport from PyQt4 import QtCore,Qt,Qwt5 import PyQt4.QtGui as QtGui import sys, time, re, pprint import itertools import scipy import Ice from gnuradio.ctrlport.IceRadioClient import * from gnuradio.ctrlport.GrDataPlotter import * from gnuradio.ctrlport import GNURadio class MAINWindow(QtGui.QMainWindow): def minimumSizeHint(self): return QtGui.QSize(800,600) def __init__(self, radio, port, interface): super(MAINWindow, self).__init__() self.conns = [] self.plots = [] self.knobprops = [] self.interface = interface self.mdiArea = QtGui.QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QtCore.QSignalMapper(self) self.windowMapper.mapped[QtGui.QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.setWindowTitle("GNU Radio Performance Monitor") self.setUnifiedTitleAndToolBarOnMac(True) self.newCon(radio, port) icon = QtGui.QIcon(ctrlport.__path__[0] + "/icon.png" ) self.setWindowIcon(icon) def newCon(self, radio=None, port=None): child = MForm(radio, port, len(self.conns), self) if(child.radio is not None): child.setWindowTitle(str(child.radio)) horizbar = QtGui.QScrollArea() horizbar.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) horizbar.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) horizbar.setWidget(child) self.mdiArea.addSubWindow(horizbar) self.mdiArea.currentSubWindow().showMaximized() self.conns.append(child) self.plots.append([]) def newUpdater(self, key, radio): updater = UpdaterWindow(key, radio, None) updater.setWindowTitle("Updater: " + key) updater.setModal(False) updater.exec_() def update(self, knobs, uid): #sys.stderr.write("KNOB KEYS: {0}\n".format(knobs.keys())) for plot in self.plots[uid]: data = knobs[plot.name()].value plot.update(data) plot.stop() plot.wait() plot.start() def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window) def createActions(self): self.newConAct = QtGui.QAction("&New Connection", self, shortcut=QtGui.QKeySequence.New, statusTip="Create a new file", triggered=self.newCon) self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=QtGui.qApp.closeAllWindows) self.closeAct = QtGui.QAction("Cl&ose", self, shortcut="Ctrl+F4", statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QtGui.QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) qks = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_T); self.tileAct = QtGui.QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows, shortcut=qks) qks = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_C); self.cascadeAct = QtGui.QAction("&Cascade", self, statusTip="Cascade the windows", shortcut=qks, triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QtGui.QAction("Ne&xt", self, shortcut=QtGui.QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QtGui.QAction("Pre&vious", self, shortcut=QtGui.QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QtGui.QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QtGui.QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QtGui.QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QtGui.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newConAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newConAct) self.fileToolBar = self.addToolBar("Window") self.fileToolBar.addAction(self.tileAct) self.fileToolBar.addAction(self.cascadeAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) def about(self): about_info = \ '''Copyright 2012 Free Software Foundation, Inc.\n This program is part of GNU Radio.\n GNU Radio is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.\n GNU Radio is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n You should have received a copy of the GNU General Public License along with GNU Radio; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301, USA.''' QtGui.QMessageBox.about(None, "gr-ctrlport-monitor", about_info) class ConInfoDialog(QtGui.QDialog): def __init__(self, parent=None): super(ConInfoDialog, self).__init__(parent) self.gridLayout = QtGui.QGridLayout(self) self.host = QtGui.QLineEdit(self); self.port = QtGui.QLineEdit(self); self.host.setText("localhost"); self.port.setText("43243"); self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.host); self.gridLayout.addWidget(self.port); self.gridLayout.addWidget(self.buttonBox); self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def accept(self): self.done(1); def reject(self): self.done(0); class UpdaterWindow(QtGui.QDialog): def __init__(self, key, radio, parent): QtGui.QDialog.__init__(self, parent) self.key = key; self.radio = radio self.resize(300,200) self.layout = QtGui.QVBoxLayout() self.props = radio.properties([key])[key] info = str(self.props) self.infoLabel = QtGui.QLabel(info) self.layout.addWidget(self.infoLabel) self.cancelButton = QtGui.QPushButton("Ok") self.cancelButton.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.reject) self.buttonlayout = QtGui.QHBoxLayout() self.buttonlayout.addWidget(self.cancelButton) self.layout.addLayout(self.buttonlayout) # set layout and go... self.setLayout(self.layout) def _set_slider_value(self, val): self.slider.setValue(self.steps*(val-self.props.min.value)/self.valspan) def _slide(self): val = (self.slider.value()*self.valspan + self.props.min.value)/float(self.steps) self.textInput.setText(str(val)) def _apply(self): if(type(self.sv.value) == str): val = str(self.textInput.text()) elif(type(self.sv.value) == int): val = int(round(float(self.textInput.text()))) elif(type(self.sv.value) == float): val = float(self.textInput.text()) else: sys.stderr.write("set type not supported! ({0})\n".format(type(self.sv.value))) sys.exit(-1) self.sv.value = val km = {} km[self.key] = self.sv self.radio.set(km) self._set_slider_value(self.sv.value) def _set(self): self._apply() self.done(0) def build_edge_graph(sources, sinks, edges): ''' Starting from the sources, walks through all of the edges to find the next connected block. The output is stored in 'allblocks' where each row starts with a source and follows one path down until it terminates in either a sink or as an input to a block that is part of another chain. ''' def find_edge(src, sinks, edges, row, col): #print "\n\nAll blocks: " #printer.pprint(allblocks) #print "\nLooking for: ", src src0 = src.split(":")[0] if(src0 in sinks): if(len(allblocks) <= row): allblocks.append(col*[""]) allblocks[row].append(src) return row+1 for edge in edges: if(re.match(src0, edge)): s = edge.split("->")[0] b = edge.split("->")[1] if(len(allblocks) <= row): allblocks.append(col*[""]) allblocks[row].append(s) #print "Source: {0} Sink: {1}".format(s, b) row = find_edge(b, sinks, edges, row, col+1) return row # Recursively get all edges as a matrix of source->sink n = 0 allblocks = [] for src in sources: n = find_edge(src, sinks, edges, n, 0) # Sort by longest list allblocks = sorted(allblocks, key=len) allblocks.reverse() # Make all rows same length by padding '' in front of sort rows maxrowlen = len(allblocks[0]) for i,a in enumerate(allblocks): rowlen = len(a) allblocks[i] = (maxrowlen-rowlen)*[''] + a # Dedup rows allblocks = sorted(allblocks) allblocks = list(k for k,_ in itertools.groupby(allblocks)) allblocks.reverse() return allblocks class MForm(QtGui.QWidget): def update(self): try: st = time.time() knobs = self.radio.get([b[0] for b in self.block_dict]) ft = time.time() latency = ft-st self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms"%\ (latency*1000)) except Exception, e: sys.stderr.write("ctrlport-monitor: radio.get threw exception ({0}).\n".format(e)) if(type(self.parent) is MAINWindow): # Find window of connection remove = [] for p in self.parent.mdiArea.subWindowList(): if self.parent.conns[self.uid] == p.widget(): remove.append(p) # Find any subplot windows of connection for p in self.parent.mdiArea.subWindowList(): for plot in self.parent.plots[self.uid]: if plot.qwidget() == p.widget(): remove.append(p) # Clean up local references to these self.parent.conns.remove(self.parent.conns[self.uid]) self.parent.plots.remove(self.parent.plots[self.uid]) # Remove subwindows for connection and plots for r in remove: self.parent.mdiArea.removeSubWindow(r) # Clean up self self.close() else: sys.exit(1) return #UPDATE TABLE: self.updateItems(knobs) #UPDATE PLOTS self.parent.update(knobs, self.uid) def updateItems(self, knobs): for b in self.block_dict: if(knobs[b[0]].ice_id.im_class == GNURadio.KnobVecF): b[1].setText("{0:.4f}".format(knobs[b[0]].value[b[2]])) else: b[1].setText("{0:.4f}".format(knobs[b[0]].value)) def __init__(self, radio=None, port=None, uid=0, parent=None): super(MForm, self).__init__() if(radio == None or port == None): askinfo = ConInfoDialog(self); if askinfo.exec_(): host = str(askinfo.host.text()); port = str(askinfo.port.text()); radio = parent.interface.getRadio(host, port) else: self.radio = None return self.uid = uid self.parent = parent self.layout = QtGui.QGridLayout(self) self.layout.setSizeConstraint(QtGui.QLayout.SetFixedSize) self.radio = radio self.knobprops = self.radio.properties([]) self.parent.knobprops.append(self.knobprops) self.resize(775,500) self.timer = QtCore.QTimer() self.constupdatediv = 0 self.tableupdatediv = 0 plotsize=250 # Set up the graph of blocks input_name = lambda x: x+"::avg input % full" output_name = lambda x: x+"::avg output % full" wtime_name = lambda x: x+"::avg work time" nout_name = lambda x: x+"::avg noutput_items" nprod_name = lambda x: x+"::avg nproduced" tmplist = [] knobs = self.radio.get([]) edgelist = None for k in knobs: propname = k.split("::") blockname = propname[0] keyname = propname[1] if(keyname == "edge list"): edgelist = knobs[k].value elif(blockname not in tmplist): # only take gr_blocks (no hier_block2) if(knobs.has_key(input_name(blockname))): tmplist.append(blockname) if not edgelist: sys.stderr.write("Could not find list of edges from flowgraph. " + \ "Make sure the option 'edges_list' is enabled " + \ "in the ControlPort configuration.\n\n") sys.exit(1) edges = edgelist.split("\n")[0:-1] producers = [] consumers = [] for e in edges: _e = e.split("->") producers.append(_e[0]) consumers.append(_e[1]) # Get producers and consumers as sets while ignoring the # ports. prods = set(map(lambda x: x.split(":")[0], producers)) cons = set(map(lambda x: x.split(":")[0], consumers)) # Split out all blocks, sources, and sinks based on how they # appear as consumers and/or producers. blocks = prods.intersection(cons) sources = prods.difference(blocks) sinks = cons.difference(blocks) nblocks = len(prods) + len(cons) allblocks = build_edge_graph(sources, sinks, edges) nrows = len(allblocks) ncols = len(allblocks[0]) col_width = 120 self.block_dict = [] for row, blockrow in enumerate(allblocks): for col, block in enumerate(blockrow): if(block == ''): continue bgroup = QtGui.QGroupBox(block) playout = QtGui.QFormLayout() bgroup.setLayout(playout) self.layout.addWidget(bgroup, row, 2*col) blockname = block.split(":")[0] name = wtime_name(blockname) wtime = knobs[name].value newtime = QtGui.QLineEdit() newtime.setMinimumWidth(col_width) newtime.setText("{0:.4f}".format(wtime)) self.block_dict.append((name, newtime)) name = nout_name(blockname) nout = knobs[name].value newnout = QtGui.QLineEdit() newnout.setText("{0:.4f}".format(nout)) newnout.setMinimumWidth(col_width) self.block_dict.append((name, newnout)) name = nprod_name(blockname) nprod = knobs[name].value newnprod = QtGui.QLineEdit() newnprod.setMinimumWidth(col_width) newnprod.setText("{0:.4f}".format(nprod)) self.block_dict.append((name, newnprod)) playout.addRow("Work time", newtime) playout.addRow("noutput_items", newnout) playout.addRow("nproduced", newnprod) if blockname in blocks or blockname in sources: # Add a buffer between blocks buffgroup = QtGui.QGroupBox("Buffer") bufflayout = QtGui.QFormLayout() buffgroup.setLayout(bufflayout) self.layout.addWidget(buffgroup, row, 2*col+1) i = int(block.split(":")[1]) name = output_name(blockname) obuff = knobs[name].value for i,o in enumerate(obuff): newobuff = QtGui.QLineEdit() newobuff.setMinimumWidth(col_width) newobuff.setText("{0:.4f}".format(o)) self.block_dict.append((name, newobuff, i)) bufflayout.addRow("Out Buffer {0}".format(i), newobuff) if blockname in blocks or blockname in sinks: item = self.layout.itemAtPosition(row, 2*col-1) if(item): buffgroup = item.widget() bufflayout = buffgroup.layout() else: buffgroup = QtGui.QGroupBox("Buffer") bufflayout = QtGui.QFormLayout() buffgroup.setLayout(bufflayout) self.layout.addWidget(buffgroup, row, 2*col-1) i = int(block.split(":")[1]) name = input_name(blockname) ibuff = knobs[name].value[i] newibuff = QtGui.QLineEdit() newibuff.setMinimumWidth(col_width) newibuff.setText("{0:.4f}".format(ibuff)) self.block_dict.append((name, newibuff, i)) bufflayout.addRow("In Buffer {0}".format(i), newibuff) # set up timer self.timer = QtCore.QTimer() self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.update) self.timer.start(1000) def openMenu(self, pos): index = self.table.treeWidget.selectedIndexes() item = self.table.treeWidget.itemFromIndex(index[0]) itemname = str(item.text(0)) self.parent.propertiesMenu(itemname, self.radio, self.uid) class MyClient(IceRadioClient): def __init__(self): IceRadioClient.__init__(self, MAINWindow) sys.exit(MyClient().main(sys.argv)) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py0000664000175000017500000003746312207702530026720 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio import filter from gnuradio.ctrlport import GNURadio import sys, time, struct try: from gnuradio import qtgui from PyQt4 import QtGui, QtCore import sip except ImportError: print "Error: Program requires PyQt4 and gr-qtgui." sys.exit(1) class GrDataPlotParent(gr.top_block, QtGui.QWidget): # Setup signals plotupdated = QtCore.pyqtSignal(QtGui.QWidget) def __init__(self, name, rate, pmin=None, pmax=None): gr.top_block.__init__(self) QtGui.QWidget.__init__(self, None) self._name = name self._npts = 500 self._rate = rate self.knobnames = [name,] self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) self.setAcceptDrops(True) def _setup(self, nconnections): self.stop() self.wait() if(self.layout.count() > 0): # Remove and disconnect. Making sure no references to snk # remain so that the plot gets deleted. self.layout.removeWidget(self.py_window) self.disconnect(self.thr, (self.snk, 0)) self.disconnect(self.src[0], self.thr) for n in xrange(1, self._ncons): self.disconnect(self.src[n], (self.snk,n)) self._ncons = nconnections self._data_len = self._ncons*[0,] self.thr = blocks.throttle(self._datasize, self._rate) self.snk = self.get_qtsink() self.connect(self.thr, (self.snk, 0)) self._last_data = [] self.src = [] for n in xrange(self._ncons): self.set_line_label(n, self.knobnames[n]) self._last_data.append(int(self._npts)*[0,]) self.src.append(self.get_vecsource()) if(n == 0): self.connect(self.src[n], self.thr) else: self.connect(self.src[n], (self.snk,n)) self.py_window = sip.wrapinstance(self.snk.pyqwidget(), QtGui.QWidget) self.layout.addWidget(self.py_window) def __del__(self): pass def close(self): self.snk.close() def qwidget(self): return self.py_window def name(self): return self._name def semilogy(self, en=True): self.snk.enable_semilogy(en) def dragEnterEvent(self, e): e.acceptProposedAction() def dropEvent(self, e): if(e.mimeData().hasFormat("text/plain")): data = str(e.mimeData().text()) #"PlotData:{0}:{1}".format(tag, iscomplex) datalst = data.split(":::") tag = datalst[0] name = datalst[1] cpx = datalst[2] != "0" if(tag == "PlotData" and cpx == self._iscomplex): self.knobnames.append(name) # create a new qwidget plot with the new data stream. self._setup(len(self.knobnames)) # emit that this plot has been updated with a new qwidget. self.plotupdated.emit(self) e.acceptProposedAction() def data_to_complex(self, data): if(self._iscomplex): data_r = data[0::2] data_i = data[1::2] data = [complex(r,i) for r,i in zip(data_r, data_i)] return data def update(self, data): # Ask GUI if there has been a change in nsamps npts = self.get_npts() if(self._npts != npts): # Adjust buffers to accomodate new settings for n in xrange(self._ncons): if(npts < self._npts): if(self._data_len[n] < npts): self._last_data[n] = self._last_data[n][0:npts] else: self._last_data[n] = self._last_data[n][self._data_len[n]-npts:self._data_len[n]] self._data_len[n] = npts else: self._last_data[n] += (npts - self._npts)*[0,] self._npts = npts self.snk.reset() if(self._stripchart): # Update the plot data depending on type for n in xrange(self._ncons): if(type(data[n]) == list): data[n] = self.data_to_complex(data[n]) if(len(data[n]) > self._npts): self.src[n].set_data(data[n]) self._last_data[n] = data[n][-self._npts:] else: newdata = self._last_data[n][-(self._npts-len(data)):] newdata += data[n] self.src[n].set_data(newdata) self._last_data[n] = newdata else: # single value update if(self._iscomplex): data[n] = complex(data[n][0], data[n][1]) if(self._data_len[n] < self._npts): self._last_data[n][self._data_len[n]] = data[n] self._data_len[n] += 1 else: self._last_data[n] = self._last_data[n][1:] self._last_data[n].append(data[n]) self.src[n].set_data(self._last_data[n]) else: for n in xrange(self._ncons): if(type(data[n]) != list): data[n] = [data[n],] data[n] = self.data_to_complex(data[n]) self.src[n].set_data(data[n]) class GrDataPlotterC(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None, stripchart=False): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._stripchart = stripchart self._datasize = gr.sizeof_gr_complex self._iscomplex = True self._setup(1) def stem(self, en=True): self.snk.enable_stem_plot(en) def get_qtsink(self): snk = qtgui.time_sink_c(self._npts, 1.0, self._name, self._ncons) snk.enable_autoscale(True) return snk def get_vecsource(self): return blocks.vector_source_c([]) def get_npts(self): self._npts = self.snk.nsamps() return self._npts def set_line_label(self, n, name): self.snk.set_line_label(2*n+0, "Re{" + self.knobnames[n] + "}") self.snk.set_line_label(2*n+1, "Im{" + self.knobnames[n] + "}") class GrDataPlotterF(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None, stripchart=False): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._stripchart = stripchart self._datasize = gr.sizeof_float self._iscomplex = False self._setup(1) def stem(self, en=True): self.snk.enable_stem_plot(en) def get_qtsink(self): snk = qtgui.time_sink_f(self._npts, 1.0, self._name, self._ncons) snk.enable_autoscale(True) return snk def get_vecsource(self): return blocks.vector_source_f([]) def get_npts(self): self._npts = self.snk.nsamps() return self._npts def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) class GrDataPlotterConst(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None, stripchart=False): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._datasize = gr.sizeof_gr_complex self._stripchart = stripchart self._iscomplex = True self._setup(1) def get_qtsink(self): snk = qtgui.const_sink_c(self._npts, self._name, self._ncons) snk.enable_autoscale(True) return snk def get_vecsource(self): return blocks.vector_source_c([]) def get_npts(self): self._npts = self.snk.nsamps() return self._npts def scatter(self, en=True): if(en): self.snk.set_line_style(0, 0) else: self.snk.set_line_style(0, 1) def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) class GrDataPlotterPsdC(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._datasize = gr.sizeof_gr_complex self._stripchart = True self._iscomplex = True self._npts = 2048 self._wintype = filter.firdes.WIN_BLACKMAN_hARRIS self._fc = 0 self._setup(1) def get_qtsink(self): snk = qtgui.freq_sink_c(self._npts, self._wintype, self._fc, 1.0, self._name, self._ncons) snk.enable_autoscale(True) return snk def get_vecsource(self): return blocks.vector_source_c([]) def get_npts(self): self._npts = self.snk.fft_size() return self._npts def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) class GrDataPlotterPsdF(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._datasize = gr.sizeof_float self._stripchart = True self._iscomplex = False self._npts = 2048 self._wintype = filter.firdes.WIN_BLACKMAN_hARRIS self._fc = 0 self._setup(1) def get_qtsink(self): snk = qtgui.freq_sink_f(self._npts, self._wintype, self._fc, 1.0, self._name, self._ncons) snk.enable_autoscale(True) return snk def get_vecsource(self): return blocks.vector_source_f([]) def get_npts(self): self._npts = self.snk.fft_size() return self._npts def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) class GrTimeRasterF(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._npts = 10 self._rows = 40 self._datasize = gr.sizeof_float self._stripchart = False self._iscomplex = False self._setup(1) def get_qtsink(self): snk = qtgui.time_raster_sink_f(1.0, self._npts, self._rows, [], [], self._name, self._ncons) return snk def get_vecsource(self): return blocks.vector_source_f([]) def get_npts(self): self._npts = self.snk.num_cols() return self._npts def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) class GrTimeRasterB(GrDataPlotParent): def __init__(self, name, rate, pmin=None, pmax=None): GrDataPlotParent.__init__(self, name, rate, pmin, pmax) self._npts = 10 self._rows = 40 self._datasize = gr.sizeof_char self._stripchart = False self._iscomplex = False self._setup(1) def get_qtsink(self): snk = qtgui.time_raster_sink_b(1.0, self._npts, self._rows, [], [], self._name, self._ncons) return snk def get_vecsource(self): return blocks.vector_source_b([]) def get_npts(self): self._npts = self.snk.num_cols() return self._npts def set_line_label(self, n, name): self.snk.set_line_label(n, self.knobnames[n]) class GrDataPlotterValueTable: def __init__(self, uid, parent, x, y, xsize, ysize, headers=['Statistic Key ( Source Block :: Stat Name ) ', 'Curent Value', 'Units', 'Description']): # must encapsulate, cuz Qt's bases are not classes self.uid = uid self.treeWidget = QtGui.QTreeWidget(parent) self.treeWidget.setColumnCount(len(headers)) self.treeWidget.setGeometry(x,y,xsize,ysize) self.treeWidget.setHeaderLabels(headers) self.treeWidget.resizeColumnToContents(0) def updateItems(self, knobs, knobprops): items = [] foundKeys = [] deleteKeys = [] numItems = self.treeWidget.topLevelItemCount() # The input knobs variable is a dict of stats to display in the tree. # Update tree stat values with new values found in knobs. # Track found keys and track keys in tree that are not in input knobs. for i in range(0, numItems): item = self.treeWidget.topLevelItem(i) # itemKey is the text in the first column of a QTreeWidgetItem itemKey = str(item.text(0)) if itemKey in knobs.keys(): # This key was found in the tree, update its values. foundKeys.append(itemKey) v = knobs[itemKey].value units = str(knobprops[itemKey].units) descr = str(knobprops[itemKey].description) if(type(v) == GNURadio.complex): v = v.re + v.im*1j # If it's a byte stream, Python thinks it's a string. # Unpack and convert to floats for plotting. # Ignore the edge list knob if it's being exported elif(type(v) == str and itemKey.find('probe2_b') == 0): v = struct.unpack(len(v)*'b', v) # Convert the final value to a string for displaying v = str(v) if (item.text(1) != v or item.text(2) != units or item.text(3) != descr): item.setText(1, v) item.setText(2, units) item.setText(3, descr) else: # This item is not in the knobs list...track it for removal. deleteKeys.append(itemKey) # Add items to tree that are not currently in the tree. for k in knobs.keys(): if k not in foundKeys: v = knobs[k].value if(type(v) == GNURadio.complex): v = v.re + v.im*1j # If it's a byte stream, Python thinks it's a string. # Unpack and convert to floats for plotting. # Ignore the edge list knob if it's being exported elif(type(v) == str and k.find('probe2_b') == 0): v = struct.unpack(len(v)*'b', v) item = QtGui.QTreeWidgetItem([k, str(v), knobprops[k].units, knobprops[k].description]) self.treeWidget.addTopLevelItem(item) # Remove items currently in tree that are not in the knob list. for itemKey in deleteKeys: qtwiList = self.treeWidget.findItems(itemKey, Qt.Qt.MatchFixedString) if (len(qtwiList) > 1): raise Exception('More than one item with key %s in tree' % itemKey) elif (len(qtwiList) == 1): i = self.treeWidget.indexOfTopLevelItem(qtwiList[0]) self.treeWidget.takeTopLevelItem(i) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py0000664000175000017500000000516512207702530025665 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys, subprocess, re, signal, time, atexit, os from gnuradio import gr class monitor: def __init__(self,tool="gr-ctrlport-monitor"): print "ControlPort Monitor running." self.started = False self.tool = tool atexit.register(self.shutdown) try: # setup export prefs gr.prefs().singleton().set_bool("ControlPort","on",True); if(tool == "gr-perf-monitorx"): gr.prefs().singleton().set_bool("ControlPort","edges_list",True); gr.prefs().singleton().set_bool("PerfCounters","on",True); gr.prefs().singleton().set_bool("PerfCounters","export",True); except: print "no support for gr.prefs setting" def __del__(self): if(self.started): self.stop() def start(self): print "monitor::endpoints() = %s" % (gr.rpcmanager_get().endpoints()) try: cmd = map(lambda a: [self.tool, re.search("\d+\.\d+\.\d+\.\d+",a).group(0), re.search("-p (\d+)",a).group(1)], gr.rpcmanager_get().endpoints())[0] print "running: %s"%(str(cmd)) self.proc = subprocess.Popen(cmd); self.started = True except: self.proc = None print "failed to to start ControlPort Monitor on specified port" def stop(self): if(self.proc): if(self.proc.returncode == None): print "\tcalling stop on shutdown" self.proc.terminate() else: print "\tno proc to shut down, exiting" def shutdown(self): print "ctrlport.monitor received shutdown signal" if(self.started): self.stop() gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx0000775000175000017500000007330012207440367026774 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random,math,operator import networkx as nx; import matplotlib matplotlib.use("Qt4Agg"); import matplotlib.pyplot as plt from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.figure import Figure from gnuradio import gr, ctrlport from PyQt4 import QtCore,Qt,Qwt5 import PyQt4.QtGui as QtGui import sys, time, re, pprint import itertools import Ice from gnuradio.ctrlport.IceRadioClient import * from gnuradio.ctrlport.GrDataPlotter import * from gnuradio.ctrlport import GNURadio class MAINWindow(QtGui.QMainWindow): def minimumSizeHint(self): return QtGui.QSize(800,600) def __init__(self, radio, port, interface): super(MAINWindow, self).__init__() self.conns = [] self.plots = [] self.knobprops = [] self.interface = interface self.mdiArea = QtGui.QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QtCore.QSignalMapper(self) self.windowMapper.mapped[QtGui.QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.setWindowTitle("GNU Radio Performance Monitor") self.setUnifiedTitleAndToolBarOnMac(True) self.newCon(radio, port) icon = QtGui.QIcon(ctrlport.__path__[0] + "/icon.png" ) self.setWindowIcon(icon) def newSubWindow(self, window, title): child = window; child.setWindowTitle(title) self.mdiArea.addSubWindow(child) self.conns.append(child) child.show(); self.mdiArea.currentSubWindow().showMaximized() def newCon(self, radio=None, port=None): child = MForm(radio, port, len(self.conns), self) if(child.radio is not None): child.setWindowTitle(str(child.radio)) # horizbar = QtGui.QScrollArea() # horizbar.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) # horizbar.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) # horizbar.setWidget(child) # self.mdiArea.addSubWindow(horizbar) self.mdiArea.addSubWindow(child) self.mdiArea.currentSubWindow().showMaximized() self.conns.append(child) self.plots.append([]) def update(self, knobs, uid): #sys.stderr.write("KNOB KEYS: {0}\n".format(knobs.keys())) for plot in self.plots[uid]: data = knobs[plot.name()].value plot.update(data) plot.stop() plot.wait() plot.start() def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window) def createActions(self): self.newConAct = QtGui.QAction("&New Connection", self, shortcut=QtGui.QKeySequence.New, statusTip="Create a new file", triggered=self.newCon) self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=QtGui.qApp.closeAllWindows) self.closeAct = QtGui.QAction("Cl&ose", self, shortcut="Ctrl+F4", statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QtGui.QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) qks = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_T); self.tileAct = QtGui.QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows, shortcut=qks) qks = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_C); self.cascadeAct = QtGui.QAction("&Cascade", self, statusTip="Cascade the windows", shortcut=qks, triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QtGui.QAction("Ne&xt", self, shortcut=QtGui.QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QtGui.QAction("Pre&vious", self, shortcut=QtGui.QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QtGui.QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QtGui.QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QtGui.QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QtGui.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newConAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newConAct) self.fileToolBar = self.addToolBar("Window") self.fileToolBar.addAction(self.tileAct) self.fileToolBar.addAction(self.cascadeAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) def about(self): about_info = \ '''Copyright 2012 Free Software Foundation, Inc.\n This program is part of GNU Radio.\n GNU Radio is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.\n GNU Radio is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n You should have received a copy of the GNU General Public License along with GNU Radio; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301, USA.''' QtGui.QMessageBox.about(None, "gr-ctrlport-monitor", about_info) class ConInfoDialog(QtGui.QDialog): def __init__(self, parent=None): super(ConInfoDialog, self).__init__(parent) self.gridLayout = QtGui.QGridLayout(self) self.host = QtGui.QLineEdit(self); self.port = QtGui.QLineEdit(self); self.host.setText("localhost"); self.port.setText("43243"); self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.host); self.gridLayout.addWidget(self.port); self.gridLayout.addWidget(self.buttonBox); self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def accept(self): self.done(1); def reject(self): self.done(0); class DataTable(QtGui.QWidget): def update(self): print "update" def __init__(self, radio, G): QtGui.QWidget.__init__( self) self.layout = QtGui.QVBoxLayout(self); self.hlayout = QtGui.QHBoxLayout(); self.layout.addLayout(self.hlayout); self.G = G; self.radio = radio; self._keymap = None # Create a combobox to set the type of statistic we want. self._statistic = "Instantaneous" self._statistics_table = {"Instantaneous": "", "Average": "avg ", "Variance": "var "} self.stattype = QtGui.QComboBox() self.stattype.addItem("Instantaneous") self.stattype.addItem("Average") self.stattype.addItem("Variance") self.stattype.setMaximumWidth(200) self.hlayout.addWidget(self.stattype); self.stattype.currentIndexChanged.connect(self.stat_changed) # Create a checkbox to toggle sorting of graphs self._sort = False self.checksort = QtGui.QCheckBox("Sort") self.checksort.setCheckState(self._sort) self.hlayout.addWidget(self.checksort); self.checksort.stateChanged.connect(self.checksort_changed) # set up table self.perfTable = Qt.QTableWidget(); self.perfTable.setColumnCount(2) self.perfTable.verticalHeader().hide(); self.perfTable.setHorizontalHeaderLabels( ["Block Name", "Percent Runtime"] ); self.perfTable.horizontalHeader().setStretchLastSection(True); self.perfTable.setSortingEnabled(True) nodes = self.G.nodes(data=True) # set up plot self.f = plt.figure(figsize=(10,8), dpi=90) self.sp = self.f.add_subplot(111); self.sp.autoscale_view(True,True,True); self.sp.set_autoscale_on(True) self.canvas = FigureCanvas(self.f) # set up tabs self.tabber = QtGui.QTabWidget(); self.layout.addWidget(self.tabber); self.tabber.addTab(self.perfTable,"Table View"); self.tabber.addTab(self.canvas, "Graph View"); # set up timer self.timer = QtCore.QTimer() self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.update) self.timer.start(500) for i in range(0,len(nodes)): self.perfTable.setItem( i,0, Qt.QTableWidgetItem(nodes[i][0])) def table_update(self,data): for k in data.keys(): weight = data[k] existing = self.perfTable.findItems(str(k),QtCore.Qt.MatchFixedString) if(len(existing) == 0): i = self.perfTable.rowCount(); self.perfTable.setRowCount( i+1) self.perfTable.setItem( i,0, Qt.QTableWidgetItem(str(k))) self.perfTable.setItem( i,1, Qt.QTableWidgetItem(str(weight))) else: self.perfTable.setItem( self.perfTable.row(existing[0]),1, Qt.QTableWidgetItem(str(weight))) def stat_changed(self, index): self._statistic = str(self.stattype.currentText()) def checksort_changed(self, state): self._sort = state > 0 class DataTableBuffers(DataTable): def __init__(self, radio, G): DataTable.__init__(self,radio,G) self.perfTable.setHorizontalHeaderLabels( ["Block Name", "Percent Buffer Full"] ); def update(self): nodes = self.G.nodes(); # get buffer fullness for all blocks kl = map(lambda x: "%s::%soutput %% full" % \ (x, self._statistics_table[self._statistic]), nodes); buf_knobs = self.radio.get(kl) # strip values out of ctrlport response buffer_fullness = dict(zip( map(lambda x: x.split("::")[0], buf_knobs.keys()), map(lambda x: x.value, buf_knobs.values()))) blockport_fullness = {} for blk in buffer_fullness: for port in range(0,len(buffer_fullness[blk])): blockport_fullness["%s:%d"%(blk,port)] = buffer_fullness[blk][port]; self.table_update(blockport_fullness); if(self._sort): sorted_fullness = sorted(blockport_fullness.iteritems(), key=operator.itemgetter(1)) self._keymap = map(operator.itemgetter(0), sorted_fullness) else: if self._keymap: sorted_fullness = len(self._keymap)*['',] for b in blockport_fullness: sorted_fullness[self._keymap.index(b)] = (b, blockport_fullness[b]) else: sorted_fullness = blockport_fullness.items() self.sp.clear(); plt.figure(self.f.number) plt.subplot(111); self.sp.bar(range(0,len(sorted_fullness)), map(lambda x: x[1], sorted_fullness), alpha=0.5) self.sp.set_ylabel("% Buffers Full"); self.sp.set_xticks( map(lambda x: x+0.5, range(0,len(sorted_fullness)))) self.sp.set_xticklabels( map(lambda x: " " + x, map(lambda x: x[0], sorted_fullness)), rotation="vertical", verticalalignment="bottom" ) self.canvas.draw(); self.canvas.show(); class DataTableRuntimes(DataTable): def __init__(self, radio, G): DataTable.__init__(self,radio,G) #self.perfTable.setRowCount(len( self.G.nodes() )) def update(self): nodes = self.G.nodes(); # get work time for all blocks kl = map(lambda x: "%s::%swork time" % \ (x, self._statistics_table[self._statistic]), nodes); wrk_knobs = self.radio.get(kl) # strip values out of ctrlport response total_work = sum(map(lambda x: x.value, wrk_knobs.values())) work_times = dict(zip( map(lambda x: x.split("::")[0], wrk_knobs.keys()), map(lambda x: x.value/total_work, wrk_knobs.values()))) # update table view self.table_update(work_times) if(self._sort): sorted_work = sorted(work_times.iteritems(), key=operator.itemgetter(1)) self._keymap = map(operator.itemgetter(0), sorted_work) else: if self._keymap: sorted_work = len(self._keymap)*['',] for b in work_times: sorted_work[self._keymap.index(b)] = (b, work_times[b]) else: sorted_work = work_times.items() self.sp.clear(); plt.figure(self.f.number) plt.subplot(111); self.sp.bar(range(0,len(sorted_work)), map(lambda x: x[1], sorted_work), alpha=0.5) self.sp.set_ylabel("% Runtime"); self.sp.set_xticks( map(lambda x: x+0.5, range(0,len(sorted_work)))) self.sp.set_xticklabels( map(lambda x: " " + x[0], sorted_work), rotation="vertical", verticalalignment="bottom" ) self.canvas.draw(); self.canvas.show(); class MForm(QtGui.QWidget): def update(self): try: try: # update current clock type self.prevent_clock_change = True; kl1 = None; if(self.clockKey == None): kl1 = self.radio.getRe([".*perfcounter_clock"]) else: kl1 = self.radio.get([self.clockKey]); self.clockKey = kl1.keys()[0]; self.currClock = kl1[self.clockKey].value; self.clockSelIdx = self.clocks.values().index(self.currClock); self.clockSel.setCurrentIndex(self.clockSelIdx); self.prevent_clock_change = False; except: print "WARNING: Failed to get current clock setting!" nodes_stream = self.G_stream.nodes(); nodes_msg = self.G_msg.nodes(); # get current buffer depths of all output buffers kl = map(lambda x: "%s::%soutput %% full" % \ (x, self._statistics_table[self._statistic]), nodes_stream); st = time.time() buf_knobs = self.radio.get(kl) td1 = time.time() - st; # strip values out of ctrlport response buf_vals = dict(zip( map(lambda x: x.split("::")[0], buf_knobs.keys()), map(lambda x: x.value, buf_knobs.values()))) # get work time for all blocks kl = map(lambda x: "%s::%swork time" % \ (x, self._statistics_table[self._statistic]), nodes_stream); st = time.time() wrk_knobs = self.radio.get(kl) td2 = time.time() - st; # strip values out of ctrlport response total_work = sum(map(lambda x: x.value, wrk_knobs.values())) work_times = dict(zip( map(lambda x: x.split("::")[0], wrk_knobs.keys()), map(lambda x: x.value/total_work, wrk_knobs.values()))) work_times_padded = dict(zip( self.G.nodes(), [0.1]*len(self.G.nodes()))) work_times_padded.update(work_times) for n in nodes_stream: # ne is the list of edges away from this node! ne = self.G.edges([n],True); #for e in ne: # iterate over edges from this block for e in ne: # iterate over edges from this block # get the right output buffer/port weight for each edge sourceport = e[2]["sourceport"]; if(e[2]["type"] == "stream"): newweight = buf_vals[n][sourceport] e[2]["weight"] = newweight; for n in nodes_msg: ne = self.G.edges([n],True); for e in ne: # iterate over edges from this block sourceport = e[2]["sourceport"]; if(e[2]["type"] == "msg"): #newweight = buf_vals[n][sourceport] newweight = 0.01; e[2]["weight"] = newweight; # set updated weights #self.node_weights = map(lambda x: 20+2000*work_times[x], nodes_stream); self.node_weights = map(lambda x: 20+2000*work_times_padded[x], self.G.nodes()); self.edge_weights = map(lambda x: 100.0*x[2]["weight"], self.G.edges(data=True)); # draw graph updates self.updateGraph(); latency = td1 + td2; self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms"%\ (latency*1000)) except Exception, e: sys.stderr.write("ctrlport-monitor: radio.get threw exception ({0}).\n".format(e)) if(type(self.parent) is MAINWindow): # Find window of connection remove = [] for p in self.parent.mdiArea.subWindowList(): if self.parent.conns[self.uid] == p.widget(): remove.append(p) # Remove subwindows for connection and plots for r in remove: self.parent.mdiArea.removeSubWindow(r) # Clean up self self.close() else: sys.exit(1) return def rtt(self): self.parent.newSubWindow( DataTableRuntimes(self.radio, self.G_stream), "Runtime Table" ); def bpt(self): self.parent.newSubWindow( DataTableBuffers(self.radio, self.G_stream), "Buffers Table" ); def stat_changed(self, index): self._statistic = str(self.stattype.currentText()) def update_clock(self, clkidx): if(self.prevent_clock_change): return; idx = self.clockSel.currentIndex(); clk = self.clocks.values()[idx] # print "UPDATE CLOCK!!! %d -> %d"%(idx,clk); k = self.radio.get([self.clockKey]); k[self.clockKey].value = clk; km = {}; km[self.clockKey] = k[self.clockKey]; self.radio.set(km); def __init__(self, radio=None, port=None, uid=0, parent=None): super(MForm, self).__init__() if(radio == None or port == None): askinfo = ConInfoDialog(self); if askinfo.exec_(): host = str(askinfo.host.text()); port = str(askinfo.port.text()); radio = parent.interface.getRadio(host, port) else: self.radio = None return self.uid = uid self.parent = parent self.layoutTop = QtGui.QVBoxLayout(self) self.ctlBox = QtGui.QHBoxLayout(); self.layout = QtGui.QHBoxLayout() self.layoutTop.addLayout(self.ctlBox); self.layoutTop.addLayout(self.layout); self.rttAct = QtGui.QAction("Runtime Table", self, statusTip="Runtime Table", triggered=self.rtt) self.rttBut = Qt.QToolButton() self.rttBut.setDefaultAction(self.rttAct); self.ctlBox.addWidget(self.rttBut); self.bptAct = QtGui.QAction("Buffer Table", self, statusTip="Buffer Table", triggered=self.bpt) self.bptBut = Qt.QToolButton() self.bptBut.setDefaultAction(self.bptAct); self.ctlBox.addWidget(self.bptBut); self.prevent_clock_change = True; self.clockKey = None; self.clocks = {"MONOTONIC":1, "THREAD":3}; self.clockSel = QtGui.QComboBox(self); map(lambda x: self.clockSel.addItem(x), self.clocks.keys()); self.ctlBox.addWidget(self.clockSel); self.clockSel.currentIndexChanged.connect(self.update_clock); self.prevent_clock_change = False; self._statistic = "Instantaneous" self._statistics_table = {"Instantaneous": "", "Average": "avg ", "Variance": "var "} self.stattype = QtGui.QComboBox() self.stattype.addItem("Instantaneous") self.stattype.addItem("Average") self.stattype.addItem("Variance") self.stattype.setMaximumWidth(200) self.ctlBox.addWidget(self.stattype); self.stattype.currentIndexChanged.connect(self.stat_changed) # self.setLayout(self.layout); self.radio = radio self.knobprops = self.radio.properties([]) self.parent.knobprops.append(self.knobprops) self.timer = QtCore.QTimer() self.constupdatediv = 0 self.tableupdatediv = 0 plotsize=250 # Set up the graph of blocks input_name = lambda x: x+"::avg input % full" output_name = lambda x: x+"::avg output % full" wtime_name = lambda x: x+"::avg work time" nout_name = lambda x: x+"::avg noutput_items" nprod_name = lambda x: x+"::avg nproduced" tmplist = [] knobs = self.radio.get([]) edgelist = None msgedgelist = None for k in knobs: propname = k.split("::") blockname = propname[0] keyname = propname[1] if(keyname == "edge list"): edgelist = knobs[k].value elif(keyname == "msg edges list"): msgedgelist = knobs[k].value elif(blockname not in tmplist): # only take gr_blocks (no hier_block2) if(knobs.has_key(input_name(blockname))): tmplist.append(blockname) if not edgelist: sys.stderr.write("Could not find list of edges from flowgraph. " + \ "Make sure the option 'edges_list' is enabled " + \ "in the ControlPort configuration.\n\n") sys.exit(1) edges = edgelist.split("\n")[0:-1] msgedges = msgedgelist.split("\n")[0:-1] edgepairs_stream = []; edgepairs_msg = []; # add stream connections for e in edges: _e = e.split("->") edgepairs_stream.append( (_e[0].split(":")[0], _e[1].split(":")[0], {"type":"stream", "sourceport":int(_e[0].split(":")[1])}) ); # add msg connections for e in msgedges: _e = e.split("->") edgepairs_msg.append( (_e[0].split(":")[0], _e[1].split(":")[0], {"type":"msg", "sourceport":_e[0].split(":")[1]}) ); self.G = nx.MultiDiGraph(); self.G_stream = nx.MultiDiGraph(); self.G_msg = nx.MultiDiGraph(); self.G.add_edges_from(edgepairs_stream); self.G.add_edges_from(edgepairs_msg); self.G_stream.add_edges_from(edgepairs_stream); self.G_msg.add_edges_from(edgepairs_msg); n_edges = self.G.edges(data=True); for e in n_edges: e[2]["weight"] = 5+random.random()*10; self.G.clear(); self.G.add_edges_from(n_edges); self.f = plt.figure(figsize=(10,8), dpi=90) self.sp = self.f.add_subplot(111); self.sp.autoscale_view(True,True,True); self.sp.set_autoscale_on(True) self.canvas = FigureCanvas(self.f) self.layout.addWidget(self.canvas); self.pos = nx.graphviz_layout(self.G); #self.pos = nx.pygraphviz_layout(self.G); #self.pos = nx.spectral_layout(self.G); #self.pos = nx.circular_layout(self.G); #self.pos = nx.shell_layout(self.G); #self.pos = nx.spring_layout(self.G); # generate weights and plot self.update(); # set up timer self.timer = QtCore.QTimer() self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.update) self.timer.start(1000) # Set up mouse callback functions to move blocks around. self._grabbed = False self._current_block = '' self.f.canvas.mpl_connect('button_press_event', self.button_press) self.f.canvas.mpl_connect('motion_notify_event', self.mouse_move) self.f.canvas.mpl_connect('button_release_event', self.button_release) def button_press(self, event): x, y = event.xdata, event.ydata thrsh = 100 if(x is not None and y is not None): nearby = map(lambda z: math.sqrt( math.pow(x-z[0],2) + math.pow(y-z[1],2)), self.pos.values()) i = nearby.index(min(nearby)) if(abs(self.pos.values()[i][0] - x) < thrsh and abs(self.pos.values()[i][1]-y) < thrsh): self._current_block = self.pos.keys()[i] #print "MOVING BLOCK: ", self._current_block #print "CUR POS: ", self.pos.values()[i] self._grabbed = True def mouse_move(self, event): if self._grabbed: x, y = event.xdata, event.ydata if(x is not None and y is not None): #print "NEW POS: ", (x,y) self.pos[self._current_block] = (x,y) self.updateGraph(); def button_release(self, event): self._grabbed = False def openMenu(self, pos): index = self.table.treeWidget.selectedIndexes() item = self.table.treeWidget.itemFromIndex(index[0]) itemname = str(item.text(0)) self.parent.propertiesMenu(itemname, self.radio, self.uid) def updateGraph(self): self.canvas.updateGeometry() self.sp.clear(); plt.figure(self.f.number) plt.subplot(111); nx.draw(self.G, self.pos, edge_color=self.edge_weights, node_color='#A0CBE2', width=map(lambda x: 3+math.log(x), self.edge_weights), node_shape="s", node_size=self.node_weights, #edge_cmap=plt.cm.Blues, edge_cmap=plt.cm.Reds, ax=self.sp, arrows=False ) nx.draw_networkx_labels(self.G, self.pos, font_size=12) self.canvas.draw(); self.canvas.show(); class MyClient(IceRadioClient): def __init__(self): IceRadioClient.__init__(self, MAINWindow) sys.exit(MyClient().main(sys.argv)) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/icon.png0000664000175000017500000000277412207440367025274 0ustar jcorganjcorganPNG  IHDR*1;sRGBbKGD pHYs  tIMEᱬtEXtCommentCreated with GIMPWWIDAThYlTUΝL;mbHY*B66b)1BHbw&(bbP6Y""$Ⱦ[(ۙvޙ;3>۪I)-$ߜmsr|ծ{B7.jQM۠+ubz{4xh꣑</U}݄T+MM9.U?|62Oк۸^ xlphAVA%헫Z\N&wu&ML|'WUu{Uzк_[eveP_=GZS_&/D&=gsC?U-JB?)aX߇T4R~AT<,Uu̘@ZYPyzۺ P4֢_='sM)?/!+5'M#y"7Ip@rZ:[^OWRj֖`[?L/_oh_jqkrԇ01[U\.To:Q-r[@pTWAxV_TUhWZTDjSZFm1]0FQㅣo*p&a6sF2uWϼV_7J@̜"\˸|["H `4'ՑX{r[6BQQ:PSRŅ;l.$5QFHsUh0AE1 n4$ ͉:c׈`f4GJ4tRmHH gn~MV'jԋ+5-Фm  zӤq"7Ք@C՗1jwϘ'W*4g$9+kH<ۖrõj0uH} 84|K+l a6 sQ],nk *8m W_3s>Nk x!kavZ3G<#xd坣eg֣@ǼR-Olw(bhٹxf 1hkiFy,Ù5Fjd KI ]; ( i+=ʇI}˧Je&=$/CۅcmmkTYجm,Y1q7+O|ڀN&s#e=8fm@FY#;ؿPuyBͲW|Yqo7Px-IENDB`gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/IceRadioClient.py0000664000175000017500000000671712207440367027027 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import Ice, Glacier2 from PyQt4 import QtGui, QtCore import sys, time, Ice from gnuradio import gr from gnuradio.ctrlport import GNURadio class IceRadioClient(Ice.Application): def __init__(self, parentClass): self.parentClass = parentClass def getRadio(self, host, port): radiostr = "gnuradio -t:tcp -h " + host + " -p " + port + " -t 3000" base = self.communicator().stringToProxy(radiostr).ice_twoway() radio = GNURadio.ControlPortPrx.checkedCast(base) if not radio: sys.stderr.write("{0} : invalid proxy.\n".format(args[0])) return None return radio def run(self,args): if len(args) < 2: print "useage: [glacierinstance glacierhost glacierport] host port" return if len(args) == 8: self.useglacier = True guser = args[1] gpass = args[2] ginst = args[3] ghost = args[4] gport = args[5] host = args[6] port = args[7] else: self.useglacier = False host = args[1] port = args[2] if(port == "-p"): port = args[3] if self.useglacier: gstring = ginst + "/router -t:tcp -h " + ghost + " -p " + gport print "GLACIER: {0}".format(gstring) setrouter = Glacier2.RouterPrx.checkedCast(self.communicator().stringToProxy(gstring)) self.communicator().setDefaultRouter(setrouter) defaultRouter = self.communicator().getDefaultRouter() #defaultRouter = self.communicator().stringToProxy(gstring) if not defaultRouter: print self.appName() + ": no default router set" return 1 else: print str(defaultRouter) router = Glacier2.RouterPrx.checkedCast(defaultRouter) if not router: print self.appName() + ": configured router is not a Glacier2 router" return 1 while True: print "This demo accepts any user-id / password combination." if not guser == '' and not gpass == '': id = guser pw = gpass else: id = raw_input("user id: ") pw = raw_input("password: ") try: router.createSession(id, pw) break except Glacier2.PermissionDeniedException, ex: print "permission denied:\n" + ex.reason radio = self.getRadio(host, port) if(radio is None): return 1 app = QtGui.QApplication(sys.argv) ex = self.parentClass(radio, port, self) ex.show(); app.exec_() gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/gr-ctrlport-monitor0000775000175000017500000006540412217337525027531 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, ctrlport from PyQt4 import QtCore,Qt import PyQt4.QtGui as QtGui import os, sys, time, struct import Ice from gnuradio.ctrlport.IceRadioClient import * from gnuradio.ctrlport.GrDataPlotter import * from gnuradio.ctrlport import GNURadio class RateDialog(QtGui.QDialog): def __init__(self, delay, parent=None): super(RateDialog, self).__init__(parent) self.gridLayout = QtGui.QGridLayout(self) self.setWindowTitle("Update Delay (ms)"); self.delay = QtGui.QLineEdit(self); self.delay.setText(str(delay)); self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.delay); self.gridLayout.addWidget(self.buttonBox); self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def accept(self): self.done(1); def reject(self): self.done(0); class MAINWindow(QtGui.QMainWindow): def minimumSizeHint(self): return Qtgui.QSize(800,600) def __init__(self, radio, port, interface): super(MAINWindow, self).__init__() self.updateRate = 1000; self.conns = [] self.plots = [] self.knobprops = [] self.interface = interface self.mdiArea = QtGui.QMdiArea() self.mdiArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.mdiArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setCentralWidget(self.mdiArea) self.mdiArea.subWindowActivated.connect(self.updateMenus) self.windowMapper = QtCore.QSignalMapper(self) self.windowMapper.mapped[QtGui.QWidget].connect(self.setActiveSubWindow) self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() self.updateMenus() self.setWindowTitle("GNU Radio Control Port Monitor") self.setUnifiedTitleAndToolBarOnMac(True) self.newCon(radio, port) icon = QtGui.QIcon(ctrlport.__path__[0] + "/icon.png" ) self.setWindowIcon(icon) # Locally turn off ControlPort export from GR. This prevents # our GR-based plotters from launching their own ControlPort # instance (and possibly causing a port collision if one has # been specified). os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' def setUpdateRate(self,nur): self.updateRate = int(nur); for c in self.conns: c.updateRate = self.updateRate; c.timer.setInterval(self.updateRate); def newCon(self, radio=None, port=None): child = MForm(radio, port, len(self.conns), self.updateRate, self) if(child.radio is not None): child.setWindowTitle(str(child.radio)) self.mdiArea.addSubWindow(child) child.showMaximized() self.conns.append(child) self.plots.append([]) def propertiesMenu(self, key, radio, uid): r = str(radio).split(" ") title = "{0}:{1}".format(r[3], r[5]) props = radio.properties([key]) pmin,pmax = get_minmax(props[key]) # Use display option mask of item to set up available plot # types and default options. disp = self.knobprops[uid][key].display cplx = disp & gr.DISPOPTCPLX | disp & gr.DISPXY strip = disp & gr.DISPOPTSTRIP stem = disp & gr.DISPOPTSTEM log = disp & gr.DISPOPTLOG scatter = disp & gr.DISPOPTSCATTER def newUpdaterProxy(): self.newUpdater(key, radio) def newPlotterFProxy(): self.newPlotF(key, uid, title, pmin, pmax, log, strip, stem) def newPlotterCProxy(): self.newPlotC(key, uid, title, pmin, pmax, log, strip, stem) def newPlotterConstProxy(): self.newPlotConst(key, uid, title, pmin, pmax, scatter, strip) def newPlotterPsdFProxy(): self.newPlotPsdF(key, uid, title) def newPlotterPsdCProxy(): self.newPlotPsdC(key, uid, title) def newPlotterRasterFProxy(): self.newPlotRasterF(key, uid, title, pmin, pmax) def newPlotterRasterBProxy(): self.newPlotRasterB(key, uid, title, pmin, pmax) menu = QtGui.QMenu(self) menu.setTitle("Item Actions") menu.setTearOffEnabled(False) # object properties menu.addAction("Properties", newUpdaterProxy) # displays available if(cplx == 0): menu.addAction("Plot Time", newPlotterFProxy) menu.addAction("Plot PSD", newPlotterPsdFProxy) menu.addAction("Plot Raster (real)", newPlotterRasterFProxy) #menu.addAction("Plot Raster (bits)", newPlotterRasterBProxy) else: menu.addAction("Plot Time", newPlotterCProxy) menu.addAction("Plot PSD", newPlotterPsdCProxy) menu.addAction("Plot Constellation", newPlotterConstProxy) menu.popup(QtGui.QCursor.pos()) def newUpdater(self, key, radio): updater = UpdaterWindow(key, radio, None) updater.setWindowTitle("Updater: " + key) updater.setModal(False) updater.exec_() def newSub(self, e): tag = str(e.text(0)) tree = e.treeWidget().parent() uid = tree.uid knobprop = self.knobprops[uid][tag] r = str(tree.radio).split(" ") title = "{0}:{1}".format(r[3], r[5]) pmin,pmax = get_minmax(knobprop) disp = knobprop.display if(disp & gr.DISPTIME): strip = disp & gr.DISPOPTSTRIP stem = disp & gr.DISPOPTSTEM log = disp & gr.DISPOPTLOG if(disp & gr.DISPOPTCPLX == 0): self.newPlotF(tag, uid, title, pmin, pmax, log, strip, stem) else: self.newPlotC(tag, uid, title, pmin, pmax, log, strip, stem) elif(disp & gr.DISPXY): scatter = disp & gr.DISPOPTSCATTER self.newPlotConst(tag, uid, title, pmin, pmax, scatter) elif(disp & gr.DISPPSD): if(disp & gr.DISPOPTCPLX == 0): self.newPlotPsdF(tag, uid, title) else: self.newPlotPsdC(tag, uid, title) def startDrag(self, e): drag = QtGui.QDrag(self) mime_data = QtCore.QMimeData() tag = str(e.text(0)) tree = e.treeWidget().parent() knobprop = self.knobprops[tree.uid][tag] disp = knobprop.display iscomplex = (disp & gr.DISPOPTCPLX) or (disp & gr.DISPXY) if(disp != gr.DISPNULL): data = "PlotData:::{0}:::{1}".format(tag, iscomplex) else: data = "OtherData:::{0}:::{1}".format(tag, iscomplex) mime_data.setText(data) drag.setMimeData(mime_data) drop = drag.start() def createPlot(self, plot, uid, title): plot.start() self.plots[uid].append(plot) self.mdiArea.addSubWindow(plot) plot.setWindowTitle("{0}: {1}".format(title, plot.name())) self.connect(plot.qwidget(), QtCore.SIGNAL('destroyed(QObject*)'), self.destroyPlot) # when the plot is updated via drag-and-drop, we need to be # notified of the new qwidget that's created so we can # properly destroy it. plot.plotupdated.connect(self.plotUpdated) plot.show() def plotUpdated(self, q): # the plot has been updated with a new qwidget; make sure this # gets dies to the destroyPlot function. for i, plots in enumerate(self.plots): for p in plots: if(p == q): #plots.remove(p) #plots.append(q) self.connect(q.qwidget(), QtCore.SIGNAL('destroyed(QObject*)'), self.destroyPlot) break def destroyPlot(self, obj): for plots in self.plots: for p in plots: if p.qwidget() == obj: plots.remove(p) break def newPlotConst(self, tag, uid, title="", pmin=None, pmax=None, scatter=False, stripchart=False): plot = GrDataPlotterConst(tag, 32e6, pmin, pmax, stripchart) plot.scatter(scatter) self.createPlot(plot, uid, title) def newPlotF(self, tag, uid, title="", pmin=None, pmax=None, logy=False, stripchart=False, stem=False): plot = GrDataPlotterF(tag, 32e6, pmin, pmax, stripchart) plot.semilogy(logy) plot.stem(stem) self.createPlot(plot, uid, title) def newPlotC(self, tag, uid, title="", pmin=None, pmax=None, logy=False, stripchart=False, stem=False): plot = GrDataPlotterC(tag, 32e6, pmin, pmax, stripchart) plot.semilogy(logy) plot.stem(stem) self.createPlot(plot, uid, title) def newPlotPsdF(self, tag, uid, title="", pmin=None, pmax=None): plot = GrDataPlotterPsdF(tag, 32e6, pmin, pmax) self.createPlot(plot, uid, title) def newPlotPsdC(self, tag, uid, title="", pmin=None, pmax=None): plot = GrDataPlotterPsdC(tag, 32e6, pmin, pmax) self.createPlot(plot, uid, title) def newPlotRasterF(self, tag, uid, title="", pmin=None, pmax=None): plot = GrTimeRasterF(tag, 32e6, pmin, pmax) self.createPlot(plot, uid, title) def newPlotRasterB(self, tag, uid, title="", pmin=None, pmax=None): plot = GrTimeRasterB(tag, 32e6, pmin, pmax) self.createPlot(plot, uid, title) def update(self, knobs, uid): #sys.stderr.write("KNOB KEYS: {0}\n".format(knobs.keys())) for plot in self.plots[uid]: data = [] for n in plot.knobnames: d = knobs[n].value if(type(d) == GNURadio.complex): d = [d.re, d.im] # If it's a byte stream, Python thinks it's a string. # Unpack and convert to floats for plotting. if(type(d) == str and n.find('probe2_b') == 0): d = struct.unpack(len(d)*'b', d) d = [float(di) for di in d] data.append(d) plot.update(data) plot.stop() plot.wait() plot.start() def setActiveSubWindow(self, window): if window: self.mdiArea.setActiveSubWindow(window) def createActions(self): self.newConAct = QtGui.QAction("&New Connection", self, shortcut=QtGui.QKeySequence.New, statusTip="Create a new file", triggered=self.newCon) self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=QtGui.qApp.closeAllWindows) self.closeAct = QtGui.QAction("Cl&ose", self, shortcut="Ctrl+F4", statusTip="Close the active window", triggered=self.mdiArea.closeActiveSubWindow) self.closeAllAct = QtGui.QAction("Close &All", self, statusTip="Close all the windows", triggered=self.mdiArea.closeAllSubWindows) self.urAct = QtGui.QAction("Update Rate", self, shortcut="F5", statusTip="Change Update Rate", triggered=self.updateRateShow) qks = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_T); self.tileAct = QtGui.QAction("&Tile", self, statusTip="Tile the windows", triggered=self.mdiArea.tileSubWindows, shortcut=qks) qks = QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_C); self.cascadeAct = QtGui.QAction("&Cascade", self, statusTip="Cascade the windows", shortcut=qks, triggered=self.mdiArea.cascadeSubWindows) self.nextAct = QtGui.QAction("Ne&xt", self, shortcut=QtGui.QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.mdiArea.activateNextSubWindow) self.previousAct = QtGui.QAction("Pre&vious", self, shortcut=QtGui.QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.mdiArea.activatePreviousSubWindow) self.separatorAct = QtGui.QAction(self) self.separatorAct.setSeparator(True) self.aboutAct = QtGui.QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.aboutQtAct = QtGui.QAction("About &Qt", self, statusTip="Show the Qt library's About box", triggered=QtGui.qApp.aboutQt) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.newConAct) self.fileMenu.addAction(self.urAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.windowMenu = self.menuBar().addMenu("&Window") self.updateWindowMenu() self.windowMenu.aboutToShow.connect(self.updateWindowMenu) self.menuBar().addSeparator() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) def updateRateShow(self): askrate = RateDialog(self.updateRate, self); if askrate.exec_(): ur = float(str(askrate.delay.text())); self.setUpdateRate(ur); return; else: return; def createToolBars(self): self.fileToolBar = self.addToolBar("File") self.fileToolBar.addAction(self.newConAct) self.fileToolBar.addAction(self.urAct) self.fileToolBar = self.addToolBar("Window") self.fileToolBar.addAction(self.tileAct) self.fileToolBar.addAction(self.cascadeAct) def createStatusBar(self): self.statusBar().showMessage("Ready") def activeMdiChild(self): activeSubWindow = self.mdiArea.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() return None def updateMenus(self): hasMdiChild = (self.activeMdiChild() is not None) self.closeAct.setEnabled(hasMdiChild) self.closeAllAct.setEnabled(hasMdiChild) self.tileAct.setEnabled(hasMdiChild) self.cascadeAct.setEnabled(hasMdiChild) self.nextAct.setEnabled(hasMdiChild) self.previousAct.setEnabled(hasMdiChild) self.separatorAct.setVisible(hasMdiChild) def updateWindowMenu(self): self.windowMenu.clear() self.windowMenu.addAction(self.closeAct) self.windowMenu.addAction(self.closeAllAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.tileAct) self.windowMenu.addAction(self.cascadeAct) self.windowMenu.addSeparator() self.windowMenu.addAction(self.nextAct) self.windowMenu.addAction(self.previousAct) self.windowMenu.addAction(self.separatorAct) def about(self): about_info = \ '''Copyright 2012 Free Software Foundation, Inc.\n This program is part of GNU Radio.\n GNU Radio is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.\n GNU Radio is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n You should have received a copy of the GNU General Public License along with GNU Radio; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Boston, MA 02110-1301, USA.''' QtGui.QMessageBox.about(None, "gr-ctrlport-monitor", about_info) class ConInfoDialog(QtGui.QDialog): def __init__(self, parent=None): super(ConInfoDialog, self).__init__(parent) self.gridLayout = QtGui.QGridLayout(self) self.host = QtGui.QLineEdit(self); self.port = QtGui.QLineEdit(self); self.host.setText("localhost"); self.port.setText("43243"); self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.host); self.gridLayout.addWidget(self.port); self.gridLayout.addWidget(self.buttonBox); self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def accept(self): self.done(1); def reject(self): self.done(0); class UpdaterWindow(QtGui.QDialog): def __init__(self, key, radio, parent): QtGui.QDialog.__init__(self, parent) self.key = key; self.radio = radio self.resize(300,200) self.layout = QtGui.QVBoxLayout() self.props = radio.properties([key])[key] info = str(self.props) self.infoLabel = QtGui.QLabel(info) self.layout.addWidget(self.infoLabel) # Test here to make sure that a 'set' function exists try: a = radio.set(radio.get([key])) has_set = True except Ice.UnknownException: has_set = False if(has_set is False): self.cancelButton = QtGui.QPushButton("Ok") self.cancelButton.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.reject) self.buttonlayout = QtGui.QHBoxLayout() self.buttonlayout.addWidget(self.cancelButton) self.layout.addLayout(self.buttonlayout) else: # we have a set function self.textInput = QtGui.QLineEdit() self.layout.addWidget(self.textInput) self.applyButton = QtGui.QPushButton("Apply") self.setButton = QtGui.QPushButton("OK") self.cancelButton = QtGui.QPushButton("Cancel") rv = radio.get([key]) val = rv[key].value if(type(val) == GNURadio.complex): val = val.re + val.im*1j self.textInput.setText(str(val)) self.sv = rv[key] self.applyButton.connect(self.applyButton, QtCore.SIGNAL('clicked()'), self._apply) self.setButton.connect(self.setButton, QtCore.SIGNAL('clicked()'), self._set) self.cancelButton.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.reject) self.is_num = ((type(self.sv.value)==float) or (type(self.sv.value)==int)) if(self.is_num): self.sliderlayout = QtGui.QHBoxLayout() self.slider = QtGui.QSlider(QtCore.Qt.Horizontal) self.sliderlayout.addWidget(QtGui.QLabel(str(self.props.min.value))) self.sliderlayout.addWidget(self.slider) self.sliderlayout.addWidget(QtGui.QLabel(str(self.props.max.value))) self.steps = 10000 self.valspan = self.props.max.value - self.props.min.value self.slider.setRange(0, 10000) self._set_slider_value(self.sv.value) self.connect(self.slider, QtCore.SIGNAL("sliderReleased()"), self._slide) self.layout.addLayout(self.sliderlayout) else: self._set_slider_value = None self.buttonlayout = QtGui.QHBoxLayout() self.buttonlayout.addWidget(self.applyButton) self.buttonlayout.addWidget(self.setButton) self.buttonlayout.addWidget(self.cancelButton) self.layout.addLayout(self.buttonlayout) # set layout and go... self.setLayout(self.layout) def _set_slider_value(self, val): self.slider.setValue(self.steps*(val-self.props.min.value)/self.valspan) def _slide(self): val = (self.slider.value()*self.valspan + self.props.min.value)/float(self.steps) self.textInput.setText(str(val)) def _apply(self): if(type(self.sv.value) == str): val = str(self.textInput.text()) elif(type(self.sv.value) == int): val = int(round(float(self.textInput.text()))) elif(type(self.sv.value) == float): val = float(self.textInput.text()) elif(type(self.sv.value) == GNURadio.complex): t = str(self.textInput.text()) t = complex(t.strip("(").strip(")").replace(" ", "")) val = GNURadio.complex() val.re = t.real val.im = t.imag else: sys.stderr.write("set type not supported! ({0})\n".format(type(self.sv.value))) return self.sv.value = val km = {} km[self.key] = self.sv self.radio.set(km) if self._set_slider_value: self._set_slider_value(self.sv.value) def _set(self): self._apply() self.done(0) class MForm(QtGui.QWidget): def update(self): try: st = time.time(); knobs = self.radio.get([]); ft = time.time(); latency = ft-st; self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms"%(latency*1000)) except Exception, e: sys.stderr.write("ctrlport-monitor: radio.get threw exception ({0}).\n".format(e)) if(type(self.parent) is MAINWindow): # Find window of connection remove = [] for p in self.parent.mdiArea.subWindowList(): if self.parent.conns[self.uid] == p.widget(): remove.append(p) # Find any subplot windows of connection for p in self.parent.mdiArea.subWindowList(): for plot in self.parent.plots[self.uid]: if plot.qwidget() == p.widget(): remove.append(p) # Clean up local references to these self.parent.conns.remove(self.parent.conns[self.uid]) self.parent.plots.remove(self.parent.plots[self.uid]) # Remove subwindows for connection and plots for r in remove: self.parent.mdiArea.removeSubWindow(r) # Clean up self self.close() else: sys.exit(1) return tableitems = knobs.keys() #UPDATE TABLE: try: self.table.updateItems(knobs, self.knobprops) except: self.knobprops = self.radio.properties([]) #UPDATE PLOTS self.parent.update(knobs, self.uid) def __init__(self, radio=None, port=None, uid=0, updateRate=2000, parent=None): super(MForm, self).__init__() if(radio == None or port == None): askinfo = ConInfoDialog(self); if askinfo.exec_(): host = str(askinfo.host.text()); port = str(askinfo.port.text()); radio = parent.interface.getRadio(host, port) else: self.radio = None return self.uid = uid self.parent = parent self.horizontalLayout = QtGui.QVBoxLayout(self) self.gridLayout = QtGui.QGridLayout() self.radio = radio self.knobprops = self.radio.properties([]) self.parent.knobprops.append(self.knobprops) self.resize(775,500) self.timer = QtCore.QTimer() self.constupdatediv = 0 self.tableupdatediv = 0 plotsize=250 # make table self.table = GrDataPlotterValueTable(uid, self, 0, 0, 400, 200) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) self.table.treeWidget.setSizePolicy(sizePolicy) self.table.treeWidget.setEditTriggers(QtGui.QAbstractItemView.EditKeyPressed) self.table.treeWidget.setSortingEnabled(True) self.table.treeWidget.setDragEnabled(True) # add things to layouts self.horizontalLayout.addWidget(self.table.treeWidget) # set up timer self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.update) self.updateRate = updateRate; self.timer.start(self.updateRate) # set up context menu .. self.table.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.table.treeWidget.customContextMenuRequested.connect(self.openMenu) # Set up double-click to launch default plotter self.connect(self.table.treeWidget, QtCore.SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.parent.newSub); # Allow drag/drop event from table item to plotter self.connect(self.table.treeWidget, QtCore.SIGNAL('itemPressed(QTreeWidgetItem*, int)'), self.parent.startDrag) def openMenu(self, pos): index = self.table.treeWidget.selectedIndexes() item = self.table.treeWidget.itemFromIndex(index[0]) itemname = str(item.text(0)) self.parent.propertiesMenu(itemname, self.radio, self.uid) def get_minmax(p): pmin = p.min.value pmax = p.max.value # Find min/max or real or imag for GNURadio::complex if(type(pmin) == GNURadio.complex): pmin = min(pmin.re, pmin.im) if(type(pmax) == GNURadio.complex): pmax = max(pmax.re, pmax.im) # If it's a byte stream, Python thinks it's a string. if(type(pmin) == str): pmin = struct.unpack('b', pmin)[0] if(type(pmax) == str): pmax = struct.unpack('b', pmax)[0] if pmin == []: pmin = None else: pmin = 1.1*float(pmin) if pmax == []: pmax = None else: pmax = 1.1*float(pmax) return pmin, pmax class MyClient(IceRadioClient): def __init__(self): IceRadioClient.__init__(self, MAINWindow) sys.exit(MyClient().main(sys.argv)) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/__init__.py0000664000175000017500000000200312207440367025730 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # The presence of this file turns this directory into a Python package import Ice, IcePy # import swig generated symbols into the ctrlport namespace #from ctrlport_swig import * from monitor import * # import any pure python here #import GNURadio gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/ctrlport/gr-ctrlport-curses0000775000175000017500000002042612207440367027337 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import threading import curses import os, sys, time from optparse import OptionParser import Ice from gnuradio.ctrlport import GNURadio ENTER = chr(10) UP_ARROW = chr(65) DOWN_ARROW = chr(66) class modem_monitor(threading.Thread): def __init__(self, cb_live, cb_exit, interface): threading.Thread.__init__(self) self.cb_live = cb_live self.cb_exit = cb_exit self.running = True def __del__(self): rx.close() def run(self): while self.running: time.sleep(0.5) def shutdown(self): self.running = False self.rx.close() def cb(self,contents): (op, sep, payload) = contents.partition(":") if(op == "live"): print "live" self.cb_live(payload) elif(op == "exit"): self.cb_exit(payload) else: print "unknown op arrived! garbage on multicast adx?" class modem_window(threading.Thread): def __init__(self, locator): threading.Thread.__init__(self) self.locator = locator # curses init self.win = curses.newwin(30,100,4,4) # Ice/GRCP init self.comm = Ice.initialize() proxy = self.comm.stringToProxy(locator) self.radio = GNURadio.ControlPortPrx.checkedCast(proxy) self.updateKnobs() # GUI init self.running = True self.ssel = 0 self.start() #self.updateGUI() # input loop while(self.running): self.getInput() # wait for update thread exit self.join() def updateKnobs(self): self.knobs = self.radio.get([]) def getInput(self): a = self.win.getch() if(a <= 256): a = chr(a) if(a == 'q'): self.running = False elif(a == UP_ARROW): self.ssel = max(self.ssel-1, 0) self.updateGUI() elif(a == DOWN_ARROW): self.ssel = max(min(self.ssel+1, len(self.knobs.keys())-1),0) self.updateGUI() self.updateGUI() def updateGUI(self): self.win.clear() self.win.border(0) self.win.addstr(1, 2, "Modem Statistics :: %s"%(self.locator)) self.win.addstr(2, 2, "---------------------------------------------------") maxnb = 0 maxk = 0 for k in self.knobs.keys(): (nb,k) = k.split("::", 2) maxnb = max(maxnb,len(nb)) maxk = max(maxk,len(k)) offset = 3 keys = self.knobs.keys() keys.sort() for k in keys: (nb,sk) = k.split("::", 2) v = self.knobs[k].value sv = str(v) if(len(sv) > 20): sv = sv[0:20] props = 0 if(self.ssel == offset-3): props = props | curses.A_REVERSE self.win.addstr(offset, 2, "%s %s %s" % \ (nb.rjust(maxnb," "), sk.ljust(maxk," "), sv),props) offset = offset + 1 self.win.refresh() def run(self): while(self.running): self.updateKnobs() self.updateGUI() time.sleep(1) class monitor_gui: def __init__(self, interfaces, options): locator = None # Extract options into a locator if(options.host and options.port): locator = "{0} -t:{1} -h {2} -p {3}".format( options.app, options.protocol, options.host, options.port) # Set up GUI self.locators = {} self.mode = 0 # modem index screen (modal keyboard input) self.lsel = 0 # selected locator self.scr = curses.initscr() self.updateGUI() # Kick off initial monitors self.monitors = [] for i in interfaces: self.monitors.append( modem_monitor(self.addModem, self.delModem, i) ) self.monitors[-1].start() if not ((locator == None) or (locator == "")): self.addModem(locator) # wait for user input while(True): self.getInput() def addModem(self, locator): if(not self.locators.has_key(locator)): self.locators[locator] = {} self.locators[locator]["update_time"] = time.time() self.locators[locator]["status"] = "live" self.updateGUI(); def delModem(self, locator): #if(self.locators.has_key(locator)): if(not self.locators.has_key(locator)): self.locators[locator] = {} self.locators[locator]["update_time"] = time.time() self.locators[locator]["status"] = "exit" self.updateGUI() def updateGUI(self): if(self.mode == 0): #redraw locators self.scr.clear() self.scr.border(0) self.scr.addstr(1, 2, " GRCP-Curses Modem Monitor :: (A)dd (R)efresh, (Q)uit, ...") for i in range(len(self.locators.keys())): locator = self.locators.keys()[i] lhash = self.locators[locator] #self.scr.addstr(3+i, 5, locator + str(lhash)) props = 0 if(self.lsel == i): props = props | curses.A_REVERSE self.scr.addstr(3+i, 5, locator + str(lhash), props) self.scr.refresh() def connectGUI(self): self.scr.clear() self.scr.addstr(1, 1, "Connect to radio:") locator = self.scr.getstr(200) self.addModem(locator) self.updateGUI() def getInput(self): a = self.scr.getch() self.scr.addstr(20, 2, "got key (%d) " % (int(a))) if(a <= 256): a = chr(a) if(a =='r'): self.updateGUI() elif(a == 'q'): self.shutdown() elif(a == 'a'): self.connectGUI() elif(a == UP_ARROW): self.lsel = max(self.lsel-1, 0) self.updateGUI() elif(a == DOWN_ARROW): self.lsel = max(min(self.lsel+1, len(self.locators.keys())-1),0) self.updateGUI() elif(a == ENTER): try: locator = self.locators.keys()[self.lsel] self.mode = 1 mwin = modem_window(locator) self.mode = 0 # pop up a new modem display ... self.updateGUI() except: pass def shutdown(self): curses.endwin() os._exit(0) if __name__ == "__main__": parser = OptionParser() parser.add_option("-H", "--host", type="string", help="Hostname of ControlPort server.") parser.add_option("-p", "--port", type="int", help="Port number of host's ControlPort endpoint.") parser.add_option("-i", "--interfaces", type="string", action="append", default=["lo"], help="Interfaces to use. [default=%default]") parser.add_option("-P", "--protocol", type="string", default="tcp", help="Type of protocol to use (usually tcp). [default=%default]") parser.add_option("-a", "--app", type="string", default="gnuradio", help="Name of application [default=%default]") (options, args) = parser.parse_args() if((options.host == None) ^ (options.port == None)): print "Please set both a hostname and a port number.\n" parser.print_help() sys.exit(1) mg = monitor_gui(options.interfaces, options) gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/eng_option.py0000664000175000017500000000405212207440367024467 0ustar jcorganjcorgan# # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # '''Add support for engineering notation to optparse.OptionParser''' from copy import copy from optparse import Option, OptionValueError import eng_notation def check_eng_float (option, opt, value): try: return eng_notation.str_to_num(value) except: raise OptionValueError ( "option %s: invalid engineering notation value: %r" % (opt, value)) def check_intx (option, opt, value): try: return int (value, 0) except: raise OptionValueError ( "option %s: invalid integer value: %r" % (opt, value)) def check_subdev (option, opt, value): """ Value has the form: (A|B)(:0|1)? Returns: a 2-tuple (0|1, 0|1) """ d = { 'A' : (0, 0), 'A:0' : (0, 0), 'A:1' : (0, 1), 'A:2' : (0, 2), 'B' : (1, 0), 'B:0' : (1, 0), 'B:1' : (1, 1), 'B:2' : (1, 2) } try: return d[value.upper()] except: raise OptionValueError( "option %s: invalid subdev: '%r', must be one of %s" % (opt, value, ', '.join(sorted(d.keys())))) class eng_option (Option): TYPES = Option.TYPES + ("eng_float", "intx", "subdev") TYPE_CHECKER = copy (Option.TYPE_CHECKER) TYPE_CHECKER["eng_float"] = check_eng_float TYPE_CHECKER["intx"] = check_intx TYPE_CHECKER["subdev"] = check_subdev gnuradio-3.7.2.1/gnuradio-runtime/python/gnuradio/__init__.py0000664000175000017500000000633512207440367024073 0ustar jcorganjcorgan""" GNU Radio is a free & open-source software development toolkit that provides signal processing blocks to implement software radios. It can be used with readily-available low-cost external RF hardware to create software-defined radios, or without hardware in a simulation-like environment. It is widely used in hobbyist, academic and commercial environments to support both wireless communications research and real-world radio systems. GNU Radio applications are primarily written using the Python programming language, while the supplied performance-critical signal-processing path is implemented in C++ using processor floating-point extensions, where available. Thus, the developer is able to implement real-time, high-throughput radio systems in a simple-to-use, rapid-application-development environment. While not primarily a simulation tool, GNU Radio does support development of signal processing algorithms using pre-recorded or generated data, avoiding the need for actual RF hardware. GNU Radio is licensed under the GNU General Public License (GPL) version 3. All of the code is copyright of the Free Software Foundation. """ # This file makes gnuradio a package # The docstring will be associated with the top level of the package. import os # Check if the gnuradio package is installed or whether we're attempting to import it from # the build directory. path_ending = os.path.join('gnuradio-runtime', 'python', 'gnuradio', '__init__.py') path = os.path.abspath(__file__) if path.endswith('.pyc'): path = path[:-1] if path.endswith(path_ending): # We importing it from build directory. build_path = os.path.join(path[:-len(path_ending)]) # Place these directories on __path__ so that their contents are # part of the gnuradio package. __path__.append(os.path.join(build_path, 'gr-utils', 'src', 'python')) __path__.append(os.path.join(build_path, 'gr-blocks', 'python')) __path__.append(os.path.join(build_path, 'gr-digital', 'python')) __path__.append(os.path.join(build_path, 'gr-filter', 'python')) __path__.append(os.path.join(build_path, 'gr-fft', 'python')) __path__.append(os.path.join(build_path, 'gr-analog', 'python')) __path__.append(os.path.join(build_path, 'gr-trellis', 'python')) __path__.append(os.path.join(build_path, 'gr-wavelet', 'python')) __path__.append(os.path.join(build_path, 'gr-audio', 'python')) __path__.append(os.path.join(build_path, 'gr-qtgui', 'python')) __path__.append(os.path.join(build_path, 'gr-wxgui', 'python')) __path__.append(os.path.join(build_path, 'gr-atsc', 'python')) __path__.append(os.path.join(build_path, 'gr-noaa', 'python')) __path__.append(os.path.join(build_path, 'gr-pager', 'python')) __path__.append(os.path.join(build_path, 'gr-video-sdl', 'python')) __path__.append(os.path.join(build_path, 'gr-vocoder', 'python')) __path__.append(os.path.join(build_path, 'gr-fcd', 'python')) __path__.append(os.path.join(build_path, 'gr-comedi', 'python')) __path__.append(os.path.join(build_path, 'gr-channels', 'python')) __path__.append(os.path.join(build_path, 'gr-fec', 'python')) __path__.append(os.path.join(build_path, 'gr-utils', 'python')) __path__.append(os.path.join(build_path, 'gr-uhd', 'python')) gnuradio-3.7.2.1/gnuradio-runtime/python/build_utils.py0000664000175000017500000001610512207440367023037 0ustar jcorganjcorgan# # Copyright 2004,2009,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """Misc utilities used at build time """ import re, os, os.path from build_utils_codes import * # set srcdir to the directory that contains Makefile.am try: srcdir = os.environ['srcdir'] except KeyError, e: srcdir = "." srcdir = srcdir + '/' # set do_makefile to either true or false dependeing on the environment try: if os.environ['do_makefile'] == '0': do_makefile = False else: do_makefile = True except KeyError, e: do_makefile = False # set do_sources to either true or false dependeing on the environment try: if os.environ['do_sources'] == '0': do_sources = False else: do_sources = True except KeyError, e: do_sources = True name_dict = {} def log_output_name (name): (base, ext) = os.path.splitext (name) ext = ext[1:] # drop the leading '.' entry = name_dict.setdefault (ext, []) entry.append (name) def open_and_log_name (name, dir): global do_sources if do_sources: f = open (name, dir) else: f = None log_output_name (name) return f def expand_template (d, template_filename, extra = ""): '''Given a dictionary D and a TEMPLATE_FILENAME, expand template into output file ''' global do_sources output_extension = extract_extension (template_filename) template = open_src (template_filename, 'r') output_name = d['NAME'] + extra + '.' + output_extension log_output_name (output_name) if do_sources: output = open (output_name, 'w') do_substitution (d, template, output) output.close () template.close () def output_glue (dirname): output_makefile_fragment () output_ifile_include (dirname) def output_makefile_fragment (): global do_makefile if not do_makefile: return # overwrite the source, which must be writable; this should have been # checked for beforehand in the top-level Makefile.gen.gen . f = open (os.path.join (os.environ.get('gendir', os.environ.get('srcdir', '.')), 'Makefile.gen'), 'w') f.write ('#\n# This file is machine generated. All edits will be overwritten\n#\n') output_subfrag (f, 'h') output_subfrag (f, 'i') output_subfrag (f, 'cc') f.close () def output_ifile_include (dirname): global do_sources if do_sources: f = open ('%s_generated.i' % (dirname,), 'w') f.write ('//\n// This file is machine generated. All edits will be overwritten\n//\n') files = name_dict.setdefault ('i', []) files.sort () f.write ('%{\n') for file in files: f.write ('#include <%s>\n' % (file[0:-1] + 'h',)) f.write ('%}\n\n') for file in files: f.write ('%%include <%s>\n' % (file,)) def output_subfrag (f, ext): files = name_dict.setdefault (ext, []) files.sort () f.write ("GENERATED_%s =" % (ext.upper ())) for file in files: f.write (" \\\n\t%s" % (file,)) f.write ("\n\n") def extract_extension (template_name): # template name is something like: GrFIRfilterXXX.h.t # we return everything between the penultimate . and .t mo = re.search (r'\.([a-z]+)\.t$', template_name) if not mo: raise ValueError, "Incorrectly formed template_name '%s'" % (template_name,) return mo.group (1) def open_src (name, mode): global srcdir return open (os.path.join (srcdir, name), mode) def do_substitution (d, in_file, out_file): def repl (match_obj): key = match_obj.group (1) # print key return d[key] inp = in_file.read () out = re.sub (r"@([a-zA-Z0-9_]+)@", repl, inp) out_file.write (out) copyright = '''/* -*- c++ -*- */ /* * Copyright 2003,2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ ''' def is_complex (code3): if i_code (code3) == 'c' or o_code (code3) == 'c': return '1' else: return '0' def standard_dict (name, code3, package='gr'): d = {} d['NAME'] = name d['NAME_IMPL'] = name+'_impl' d['GUARD_NAME'] = 'INCLUDED_%s_%s_H' % (package.upper(), name.upper()) d['GUARD_NAME_IMPL'] = 'INCLUDED_%s_%s_IMPL_H' % (package.upper(), name.upper()) d['BASE_NAME'] = re.sub ('^' + package + '_', '', name) d['SPTR_NAME'] = '%s_sptr' % name d['WARNING'] = 'WARNING: this file is machine generated. Edits will be overwritten' d['COPYRIGHT'] = copyright d['TYPE'] = i_type (code3) d['I_TYPE'] = i_type (code3) d['O_TYPE'] = o_type (code3) d['TAP_TYPE'] = tap_type (code3) d['IS_COMPLEX'] = is_complex (code3) return d def standard_dict2 (name, code3, package): d = {} d['NAME'] = name d['BASE_NAME'] = name d['GUARD_NAME'] = 'INCLUDED_%s_%s_H' % (package.upper(), name.upper()) d['WARNING'] = 'WARNING: this file is machine generated. Edits will be overwritten' d['COPYRIGHT'] = copyright d['TYPE'] = i_type (code3) d['I_TYPE'] = i_type (code3) d['O_TYPE'] = o_type (code3) d['TAP_TYPE'] = tap_type (code3) d['IS_COMPLEX'] = is_complex (code3) return d def standard_impl_dict2 (name, code3, package): d = {} d['NAME'] = name d['IMPL_NAME'] = name d['BASE_NAME'] = name.rstrip("impl").rstrip("_") d['GUARD_NAME'] = 'INCLUDED_%s_%s_H' % (package.upper(), name.upper()) d['WARNING'] = 'WARNING: this file is machine generated. Edits will be overwritten' d['COPYRIGHT'] = copyright d['FIR_TYPE'] = "fir_filter_" + code3 d['CFIR_TYPE'] = "fir_filter_" + code3[0:2] + 'c' d['TYPE'] = i_type (code3) d['I_TYPE'] = i_type (code3) d['O_TYPE'] = o_type (code3) d['TAP_TYPE'] = tap_type (code3) d['IS_COMPLEX'] = is_complex (code3) return d gnuradio-3.7.2.1/gnuradio-runtime/python/build_utils_codes.py0000664000175000017500000000255712207440367024222 0ustar jcorganjcorgan# # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # def i_code (code3): return code3[0] def o_code (code3): if len (code3) >= 2: return code3[1] else: return code3[0] def tap_code (code3): if len (code3) >= 3: return code3[2] else: return code3[0] def i_type (code3): return char_to_type[i_code (code3)] def o_type (code3): return char_to_type[o_code (code3)] def tap_type (code3): return char_to_type[tap_code (code3)] char_to_type = {} char_to_type['s'] = 'short' char_to_type['i'] = 'int' char_to_type['f'] = 'float' char_to_type['c'] = 'gr_complex' char_to_type['b'] = 'unsigned char' gnuradio-3.7.2.1/gnuradio-runtime/lib/0000775000175000017500000000000012241734056017367 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_mmap_shm_open.h0000664000175000017500000000373512207440367024433 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_VMCIRCBUF_MMAP_SHM_OPEN_H #define GR_VMCIRCBUF_MMAP_SHM_OPEN_H #include #include "vmcircbuf.h" namespace gr { /*! * \brief concrete class to implement circular buffers with mmap and shm_open * \ingroup internal */ class GR_RUNTIME_API vmcircbuf_mmap_shm_open : public gr::vmcircbuf { public: vmcircbuf_mmap_shm_open(int size); virtual ~vmcircbuf_mmap_shm_open(); }; /*! * \brief concrete factory for circular buffers built using mmap and shm_open */ class GR_RUNTIME_API vmcircbuf_mmap_shm_open_factory : public gr::vmcircbuf_factory { private: static gr::vmcircbuf_factory *s_the_factory; public: static gr::vmcircbuf_factory *singleton(); virtual const char *name() const { return "gr::vmcircbuf_mmap_shm_open_factory"; } /*! * \brief return granularity of mapping, typically equal to page size */ virtual int granularity(); /*! * \brief return a gr::vmcircbuf, or 0 if unable. * * Call this to create a doubly mapped circular buffer. */ virtual gr::vmcircbuf *make(int size); }; } /* namespace gr */ #endif /* GR_VMCIRCBUF_MMAP_SHM_OPEN_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/realtime.cc0000664000175000017500000000204112207440367021476 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include namespace gr { rt_status_t enable_realtime_scheduling() { return gr::impl::enable_realtime_scheduling(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf.cc0000664000175000017500000002023712207440367021663 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include "vmcircbuf.h" #include "vmcircbuf_prefs.h" #include "local_sighandler.h" // all the factories we know about #include "vmcircbuf_createfilemapping.h" #include "vmcircbuf_sysv_shm.h" #include "vmcircbuf_mmap_shm_open.h" #include "vmcircbuf_mmap_tmpfile.h" gr::thread::mutex s_vm_mutex; namespace gr { static const char *FACTORY_PREF_KEY = "vmcircbuf_default_factory"; vmcircbuf::~vmcircbuf() { } vmcircbuf_factory::~vmcircbuf_factory() { } // ---------------------------------------------------------------- static vmcircbuf_factory *s_default_factory = 0; vmcircbuf_factory * vmcircbuf_sysconfig::get_default_factory() { if(s_default_factory) return s_default_factory; bool verbose = false; std::vector all = all_factories (); const char *name = gr::vmcircbuf_prefs::get(FACTORY_PREF_KEY); if(name) { for(unsigned int i = 0; i < all.size (); i++) { if(strncmp(name, all[i]->name(), strlen(all[i]->name())) == 0) { s_default_factory = all[i]; if(verbose) fprintf(stderr, "gr::vmcircbuf_sysconfig: using %s\n", s_default_factory->name()); return s_default_factory; } } } // either we don't have a default, or the default named is not in our // list of factories. Find the first factory that works. if(verbose) fprintf(stderr, "gr::vmcircbuf_sysconfig: finding a working factory...\n"); for(unsigned int i = 0; i < all.size (); i++) { if(test_factory(all[i], verbose)) { set_default_factory(all[i]); return s_default_factory; } } // We're screwed! fprintf(stderr, "gr::vmcircbuf_sysconfig: unable to find a working factory!\n"); throw std::runtime_error("gr::vmcircbuf_sysconfig"); } std::vector vmcircbuf_sysconfig::all_factories() { std::vector result; result.push_back(gr::vmcircbuf_createfilemapping_factory::singleton()); #ifdef TRY_SHM_VMCIRCBUF result.push_back(gr::vmcircbuf_sysv_shm_factory::singleton()); result.push_back(gr::vmcircbuf_mmap_shm_open_factory::singleton()); #endif result.push_back (gr::vmcircbuf_mmap_tmpfile_factory::singleton()); return result; } void vmcircbuf_sysconfig::set_default_factory(vmcircbuf_factory *f) { gr::vmcircbuf_prefs::set(FACTORY_PREF_KEY, f->name()); s_default_factory = f; } // ------------------------------------------------------------------------ // test code for vmcircbuf factories // ------------------------------------------------------------------------ static void init_buffer(vmcircbuf *c, int counter, int size) { unsigned int *p = (unsigned int*)c->pointer_to_first_copy(); for(unsigned int i = 0; i < size / sizeof(int); i++) p[i] = counter + i; } static bool check_mapping(vmcircbuf *c, int counter, int size, const char *msg, bool verbose) { bool ok = true; if(verbose) fprintf(stderr, "... %s", msg); unsigned int *p1 = (unsigned int *)c->pointer_to_first_copy(); unsigned int *p2 = (unsigned int *)c->pointer_to_second_copy(); // fprintf(stderr, "p1 = %p, p2 = %p\n", p1, p2); for(unsigned int i = 0; i < size / sizeof (int); i++) { if(p1[i] != counter + i) { ok = false; if(verbose) fprintf(stderr, " p1[%d] == %u, expected %u\n", i, p1[i], counter + i); break; } if(p2[i] != counter + i) { if(verbose) fprintf(stderr, " p2[%d] == %u, expected %u\n", i, p2[i], counter + i); ok = false; break; } } if(ok && verbose) { fprintf(stderr, " OK\n"); } return ok; } static const char * memsize(int size) { static std::string buf; if(size >= (1 << 20)) { buf = str(boost::format("%dMB") % (size / (1 << 20))); } else if(size >= (1 << 10)){ buf = str(boost::format("%dKB") % (size / (1 << 10))); } else { buf = str(boost::format("%d") % size); } return buf.c_str(); } static bool test_a_bunch(vmcircbuf_factory *factory, int n, int size, int *start_ptr, bool verbose) { bool ok = true; std::vector counter(n); std::vector c(n); int cum_size = 0; for(int i = 0; i < n; i++) { counter[i] = *start_ptr; *start_ptr += size; if((c[i] = factory->make (size)) == 0) { if(verbose) fprintf(stderr, "Failed to allocate gr::vmcircbuf number %d of size %d (cum = %s)\n", i + 1, size, memsize(cum_size)); return false; } init_buffer(c[i], counter[i], size); cum_size += size; } for(int i = 0; i < n; i++) { std::string msg = str(boost::format("test_a_bunch_%dx%s[%d]") % n % memsize(size) % i); ok &= check_mapping(c[i], counter[i], size, msg.c_str(), verbose); } for(int i = 0; i < n; i++) { delete c[i]; c[i] = 0; } return ok; } static bool standard_tests(vmcircbuf_factory *f, int verbose) { if(verbose >= 1) fprintf(stderr, "Testing %s...\n", f->name()); bool v = verbose >= 2; int granularity = f->granularity(); int start = 0; bool ok = true; ok &= test_a_bunch(f, 1, 1 * granularity, &start, v); // 1 x 4KB = 4KB if(ok) { ok &= test_a_bunch(f, 64, 4 * granularity, &start, v); // 64 x 16KB = 1MB ok &= test_a_bunch(f, 4, 4 * (1L << 20), &start, v); // 4 x 4MB = 16MB // ok &= test_a_bunch(f, 256, 256 * (1L << 10), &start, v); // 256 x 256KB = 64MB } if(verbose >= 1) fprintf(stderr, "....... %s: %s", f->name(), ok ? "OK\n" : "Doesn't work\n"); return ok; } bool vmcircbuf_sysconfig::test_factory(vmcircbuf_factory *f, int verbose) { // Install local signal handlers for SIGSEGV and SIGBUS. // If something goes wrong, these signals may be invoked. #ifdef SIGSEGV gr::local_sighandler sigsegv (SIGSEGV, gr::local_sighandler::throw_signal); #endif #ifdef SIGBUS gr::local_sighandler sigbus (SIGBUS, gr::local_sighandler::throw_signal); #endif #ifdef SIGSYS gr::local_sighandler sigsys (SIGSYS, gr::local_sighandler::throw_signal); #endif try { return standard_tests (f, verbose); } catch(gr::signal &sig) { if(verbose) { fprintf(stderr, "....... %s: %s", f->name(), "Doesn't work\n"); fprintf(stderr, "gr::vmcircbuf_factory::test_factory (%s): caught %s\n", f->name(), sig.name().c_str()); return false; } } catch (...) { if(verbose) { fprintf(stderr, "....... %s: %s", f->name(), "Doesn't work\n"); fprintf(stderr, "gr::vmcircbuf_factory::test_factory (%s): some kind of uncaught exception\n", f->name()); } return false; } return false; // never gets here. shut compiler up. } bool vmcircbuf_sysconfig::test_all_factories(int verbose) { bool ok = false; std::vector all = all_factories(); for(unsigned int i = 0; i < all.size (); i++) ok |= test_factory(all[i], verbose); return ok; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/misc.h0000664000175000017500000000247012207440367020477 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MISC_H #define INCLUDED_GR_MISC_H #include #include namespace gr { GR_RUNTIME_API unsigned int rounduppow2(unsigned int n); // FIXME should be template GR_RUNTIME_API void zero_vector(std::vector &v); GR_RUNTIME_API void zero_vector(std::vector &v); GR_RUNTIME_API void zero_vector(std::vector &v); GR_RUNTIME_API void zero_vector(std::vector &v); } /* namespace gr */ #endif /* INCLUDED_GR_MISC_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/misc.cc0000664000175000017500000000306212207440367020633 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "misc.h" namespace gr { unsigned int rounduppow2(unsigned int n) { int i; for(i=0;((n-1)>>i) != 0;i++) ; return 1< &v) { for(unsigned int i=0; i < v.size(); i++) v[i] = 0; } void zero_vector(std::vector &v) { for(unsigned int i=0; i < v.size(); i++) v[i] = 0; } void zero_vector(std::vector &v) { for(unsigned int i=0; i < v.size(); i++) v[i] = 0; } void zero_vector(std::vector &v) { for(unsigned int i=0; i < v.size(); i++) v[i] = 0; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/0000775000175000017500000000000012224021502020151 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/CMakeLists.txt0000664000175000017500000001202112207440367022724 0ustar jcorganjcorgan# Copyright 2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # This file included, use CMake directory variables ######################################################################## include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}) include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}) ######################################################################## # Generate serial tags header file ######################################################################## get_filename_component(PMT_SERIAL_TAGS_H ${CMAKE_CURRENT_BINARY_DIR}/../../include/pmt/pmt_serial_tags.h ABSOLUTE ) add_custom_command( OUTPUT ${PMT_SERIAL_TAGS_H} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/gen-serial-tags.py DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/pmt-serial-tags.scm COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/gen-serial-tags.py ${CMAKE_CURRENT_SOURCE_DIR}/pmt-serial-tags.scm ${PMT_SERIAL_TAGS_H} ) install( FILES ${PMT_SERIAL_TAGS_H} DESTINATION ${GR_INCLUDE_DIR}/pmt COMPONENT "runtime_devel" ) include(AddFileDependencies) ADD_FILE_DEPENDENCIES( ${CMAKE_CURRENT_SOURCE_DIR}/pmt_serialize.cc ${PMT_SERIAL_TAGS_H} ) ######################################################################## # Generate other pmt stuff ######################################################################## add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/pmt_unv_int.h ${CMAKE_CURRENT_BINARY_DIR}/qa_pmt_unv.h ${CMAKE_CURRENT_BINARY_DIR}/pmt_unv.cc ${CMAKE_CURRENT_BINARY_DIR}/qa_pmt_unv.cc DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/generate_unv.py ${CMAKE_CURRENT_SOURCE_DIR}/unv_template.h.t ${CMAKE_CURRENT_SOURCE_DIR}/unv_template.cc.t ${CMAKE_CURRENT_SOURCE_DIR}/unv_qa_template.cc.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} -c \"import os,sys\;srcdir='${CMAKE_CURRENT_SOURCE_DIR}'\;sys.path.append(srcdir)\;os.environ['srcdir']=srcdir\;from generate_unv import main\;main()\" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} ) set(pmt_sources ${CMAKE_CURRENT_BINARY_DIR}/pmt_unv.cc ${CMAKE_CURRENT_SOURCE_DIR}/pmt.cc ${CMAKE_CURRENT_SOURCE_DIR}/pmt_io.cc ${CMAKE_CURRENT_SOURCE_DIR}/pmt_pool.cc ${CMAKE_CURRENT_SOURCE_DIR}/pmt_serialize.cc ) list(APPEND gnuradio_pmt_libs ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_custom_target(pmt_generated DEPENDS ${PMT_SERIAL_TAGS_H} ${CMAKE_CURRENT_BINARY_DIR}/pmt_unv_int.h) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-pmt.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-pmt.rc @ONLY) list(APPEND gr_pmt_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-pmt.rc ) endif(MSVC) add_library(gnuradio-pmt SHARED ${pmt_sources}) target_link_libraries(gnuradio-pmt ${gnuradio_pmt_libs}) GR_LIBRARY_FOO(gnuradio-pmt RUNTIME_COMPONENT "runtime_runtime" DEVEL_COMPONENT "runtime_devel") add_dependencies(gnuradio-pmt pmt_generated ) ######################################################################## # Setup tests ######################################################################## if(ENABLE_TESTING) include(GrTest) ######################################################################## # Append gnuradio-runtime test sources ######################################################################## list(APPEND test_gnuradio_pmt_sources qa_pmt.cc qa_pmt_prims.cc ${CMAKE_CURRENT_BINARY_DIR}/qa_pmt_unv.cc ) include_directories(${CPPUNIT_INCLUDE_DIRS}) link_directories(${CPPUNIT_LIBRARY_DIRS}) add_library(test-gnuradio-pmt SHARED ${test_gnuradio_pmt_sources}) target_link_libraries(test-gnuradio-pmt gnuradio-runtime gnuradio-pmt ${CPPUNIT_LIBRARIES} ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES}) ######################################################################## # Build the test executable # Set the test environment so the build libs will be found under MSVC. ######################################################################## list(APPEND GR_TEST_TARGET_DEPS test-gnuradio-pmt) add_executable(gr_pmt_test test_pmt.cc) target_link_libraries(gr_pmt_test test-gnuradio-pmt) GR_ADD_TEST(gr-pmt-test gr_pmt_test) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/pmt_io.cc0000664000175000017500000000671112207440367021773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include "pmt_int.h" #include #include namespace pmt { static void write_list_tail(pmt_t obj, std::ostream &port) { write(car(obj), port); // write the car obj = cdr(obj); // step to cdr if (is_null(obj)) // () port << ")"; else if (is_pair(obj)){ // normal list port << " "; write_list_tail(obj, port); } else { // dotted pair port << " . "; write(obj, port); port << ")"; } } void write(pmt_t obj, std::ostream &port) { if (is_bool(obj)){ if (is_true(obj)) port << "#t"; else port << "#f"; } else if (is_symbol(obj)){ port << symbol_to_string(obj); } else if (is_number(obj)){ if (is_integer(obj)) port << to_long(obj); else if (is_uint64(obj)) port << to_uint64(obj); else if (is_real(obj)) port << to_double(obj); else if (is_complex(obj)){ std::complex c = to_complex(obj); port << c.real() << '+' << c.imag() << 'i'; } else goto error; } else if (is_null(obj)){ port << "()"; } else if (is_pair(obj)){ port << "("; write_list_tail(obj, port); } else if (is_tuple(obj)){ port << "{"; size_t len = length(obj); if (len > 0){ port << tuple_ref(obj, 0); for (size_t i = 1; i < len; i++) port << " " << tuple_ref(obj, i); } port << "}"; } else if (is_vector(obj)){ port << "#("; size_t len = length(obj); if (len > 0){ port << vector_ref(obj, 0); for (size_t i = 1; i < len; i++) port << " " << vector_ref(obj, i); } port << ")"; } else if (is_dict(obj)){ // FIXME // port << "#"; port << "#"; } else if (is_uniform_vector(obj)){ // FIXME // port << "#"; port << "#"; } else { error: // FIXME // port << "#<" << obj << ">"; port << "#"; } } std::ostream& operator<<(std::ostream &os, pmt_t obj) { write(obj, os); return os; } std::string write_string(pmt_t obj) { std::ostringstream s; s << obj; return s.str(); } pmt_t read(std::istream &port) { throw notimplemented("notimplemented: pmt::read", PMT_NIL); } void serialize(pmt_t obj, std::ostream &sink) { throw notimplemented("notimplemented: pmt::serialize", obj); } /*! * \brief Create obj from portable byte-serial representation */ pmt_t deserialize(std::istream &source) { throw notimplemented("notimplemented: pmt::deserialize", PMT_NIL); } } /* namespace pmt */ void pmt::print(pmt_t v) { std::cout << write_string(v) << std::endl; } gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/pmt.cc0000664000175000017500000006731512207440367021313 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include "pmt_int.h" #include #include #include #include namespace pmt { static const int CACHE_LINE_SIZE = 64; // good guess # if (PMT_LOCAL_ALLOCATOR) static pmt_pool global_pmt_pool(sizeof(pmt_pair), CACHE_LINE_SIZE); void * pmt_base::operator new(size_t size) { void *p = global_pmt_pool.malloc(); // fprintf(stderr, "pmt_base::new p = %p\n", p); assert((reinterpret_cast(p) & (CACHE_LINE_SIZE - 1)) == 0); return p; } void pmt_base::operator delete(void *p, size_t size) { global_pmt_pool.free(p); } #endif void intrusive_ptr_add_ref(pmt_base* p) { ++(p->count_); } void intrusive_ptr_release(pmt_base* p) { if (--(p->count_) == 0 ) delete p; } pmt_base::~pmt_base() { // nop -- out of line virtual destructor } //////////////////////////////////////////////////////////////////////////// // Exceptions //////////////////////////////////////////////////////////////////////////// exception::exception(const std::string &msg, pmt_t obj) : logic_error(msg + ": " + write_string(obj)) { } wrong_type::wrong_type(const std::string &msg, pmt_t obj) : exception(msg + ": wrong_type ", obj) { } out_of_range::out_of_range(const std::string &msg, pmt_t obj) : exception(msg + ": out of range ", obj) { } notimplemented::notimplemented(const std::string &msg, pmt_t obj) : exception(msg + ": notimplemented ", obj) { } //////////////////////////////////////////////////////////////////////////// // Dynamic Casts //////////////////////////////////////////////////////////////////////////// static pmt_symbol * _symbol(pmt_t x) { return dynamic_cast(x.get()); } static pmt_integer * _integer(pmt_t x) { return dynamic_cast(x.get()); } static pmt_uint64 * _uint64(pmt_t x) { return dynamic_cast(x.get()); } static pmt_real * _real(pmt_t x) { return dynamic_cast(x.get()); } static pmt_complex * _complex(pmt_t x) { return dynamic_cast(x.get()); } static pmt_pair * _pair(pmt_t x) { return dynamic_cast(x.get()); } static pmt_vector * _vector(pmt_t x) { return dynamic_cast(x.get()); } static pmt_tuple * _tuple(pmt_t x) { return dynamic_cast(x.get()); } static pmt_uniform_vector * _uniform_vector(pmt_t x) { return dynamic_cast(x.get()); } static pmt_any * _any(pmt_t x) { return dynamic_cast(x.get()); } //////////////////////////////////////////////////////////////////////////// // Globals //////////////////////////////////////////////////////////////////////////// const pmt_t PMT_T = pmt_t(new pmt_bool()); // singleton const pmt_t PMT_F = pmt_t(new pmt_bool()); // singleton const pmt_t PMT_NIL = pmt_t(new pmt_null()); // singleton const pmt_t PMT_EOF = cons(PMT_NIL, PMT_NIL); // singleton //////////////////////////////////////////////////////////////////////////// // Booleans //////////////////////////////////////////////////////////////////////////// pmt_bool::pmt_bool(){} bool is_true(pmt_t obj) { return obj != PMT_F; } bool is_false(pmt_t obj) { return obj == PMT_F; } bool is_bool(pmt_t obj) { return obj->is_bool(); } pmt_t from_bool(bool val) { return val ? PMT_T : PMT_F; } bool to_bool(pmt_t val) { if (val == PMT_T) return true; if (val == PMT_F) return false; throw wrong_type("pmt_to_bool", val); } //////////////////////////////////////////////////////////////////////////// // Symbols //////////////////////////////////////////////////////////////////////////// static const unsigned int SYMBOL_HASH_TABLE_SIZE = 701; static std::vector s_symbol_hash_table(SYMBOL_HASH_TABLE_SIZE); pmt_symbol::pmt_symbol(const std::string &name) : d_name(name){} static unsigned int hash_string(const std::string &s) { unsigned int h = 0; unsigned int g = 0; for (std::string::const_iterator p = s.begin(); p != s.end(); ++p){ h = (h << 4) + (*p & 0xff); g = h & 0xf0000000; if (g){ h = h ^ (g >> 24); h = h ^ g; } } return h; } bool is_symbol(const pmt_t& obj) { return obj->is_symbol(); } pmt_t string_to_symbol(const std::string &name) { unsigned hash = hash_string(name) % SYMBOL_HASH_TABLE_SIZE; // Does a symbol with this name already exist? for (pmt_t sym = s_symbol_hash_table[hash]; sym; sym = _symbol(sym)->next()){ if (name == _symbol(sym)->name()) return sym; // Yes. Return it } // Nope. Make a new one. pmt_t sym = pmt_t(new pmt_symbol(name)); _symbol(sym)->set_next(s_symbol_hash_table[hash]); s_symbol_hash_table[hash] = sym; return sym; } // alias... pmt_t intern(const std::string &name) { return string_to_symbol(name); } const std::string symbol_to_string(const pmt_t& sym) { if (!sym->is_symbol()) throw wrong_type("pmt_symbol_to_string", sym); return _symbol(sym)->name(); } //////////////////////////////////////////////////////////////////////////// // Number //////////////////////////////////////////////////////////////////////////// bool is_number(pmt_t x) { return x->is_number(); } //////////////////////////////////////////////////////////////////////////// // Integer //////////////////////////////////////////////////////////////////////////// pmt_integer::pmt_integer(long value) : d_value(value) {} bool is_integer(pmt_t x) { return x->is_integer(); } pmt_t from_long(long x) { return pmt_t(new pmt_integer(x)); } long to_long(pmt_t x) { pmt_integer* i = dynamic_cast(x.get()); if ( i ) return i->value(); throw wrong_type("pmt_to_long", x); } //////////////////////////////////////////////////////////////////////////// // Uint64 //////////////////////////////////////////////////////////////////////////// pmt_uint64::pmt_uint64(uint64_t value) : d_value(value) {} bool is_uint64(pmt_t x) { return x->is_uint64(); } pmt_t from_uint64(uint64_t x) { return pmt_t(new pmt_uint64(x)); } uint64_t to_uint64(pmt_t x) { if(x->is_uint64()) return _uint64(x)->value(); if(x->is_integer()) { long tmp = _integer(x)->value(); if(tmp >= 0) return (uint64_t) tmp; } throw wrong_type("pmt_to_uint64", x); } //////////////////////////////////////////////////////////////////////////// // Real //////////////////////////////////////////////////////////////////////////// pmt_real::pmt_real(double value) : d_value(value) {} bool is_real(pmt_t x) { return x->is_real(); } pmt_t from_double(double x) { return pmt_t(new pmt_real(x)); } double to_double(pmt_t x) { if (x->is_real()) return _real(x)->value(); if (x->is_integer()) return _integer(x)->value(); throw wrong_type("pmt_to_double", x); } //////////////////////////////////////////////////////////////////////////// // Complex //////////////////////////////////////////////////////////////////////////// pmt_complex::pmt_complex(std::complex value) : d_value(value) {} bool is_complex(pmt_t x) { return x->is_complex(); } pmt_t make_rectangular(double re, double im) { return from_complex(re, im); } pmt_t from_complex(double re, double im) { return pmt_from_complex(re, im); } pmt_t pmt_from_complex(double re, double im) { return pmt_t(new pmt_complex(std::complex(re, im))); } pmt_t from_complex(const std::complex &z) { return pmt_t(new pmt_complex(z)); } std::complex to_complex(pmt_t x) { if (x->is_complex()) return _complex(x)->value(); if (x->is_real()) return _real(x)->value(); if (x->is_integer()) return _integer(x)->value(); throw wrong_type("pmt_to_complex", x); } //////////////////////////////////////////////////////////////////////////// // Pairs //////////////////////////////////////////////////////////////////////////// pmt_null::pmt_null() {} pmt_pair::pmt_pair(const pmt_t& car, const pmt_t& cdr) : d_car(car), d_cdr(cdr) {} bool is_null(const pmt_t& x) { return x == PMT_NIL; } bool is_pair(const pmt_t& obj) { return obj->is_pair(); } pmt_t cons(const pmt_t& x, const pmt_t& y) { return pmt_t(new pmt_pair(x, y)); } pmt_t car(const pmt_t& pair) { pmt_pair* p = dynamic_cast(pair.get()); if ( p ) return p->car(); throw wrong_type("pmt_car", pair); } pmt_t cdr(const pmt_t& pair) { pmt_pair* p = dynamic_cast(pair.get()); if ( p ) return p->cdr(); throw wrong_type("pmt_cdr", pair); } void set_car(pmt_t pair, pmt_t obj) { if (pair->is_pair()) _pair(pair)->set_car(obj); else throw wrong_type("pmt_set_car", pair); } void set_cdr(pmt_t pair, pmt_t obj) { if (pair->is_pair()) _pair(pair)->set_cdr(obj); else throw wrong_type("pmt_set_cdr", pair); } //////////////////////////////////////////////////////////////////////////// // Vectors //////////////////////////////////////////////////////////////////////////// pmt_vector::pmt_vector(size_t len, pmt_t fill) : d_v(len) { for (size_t i = 0; i < len; i++) d_v[i] = fill; } pmt_t pmt_vector::ref(size_t k) const { if (k >= length()) throw out_of_range("pmt_vector_ref", from_long(k)); return d_v[k]; } void pmt_vector::set(size_t k, pmt_t obj) { if (k >= length()) throw out_of_range("pmt_vector_set", from_long(k)); d_v[k] = obj; } void pmt_vector::fill(pmt_t obj) { for (size_t i = 0; i < length(); i++) d_v[i] = obj; } bool is_vector(pmt_t obj) { return obj->is_vector(); } pmt_t make_vector(size_t k, pmt_t fill) { return pmt_t(new pmt_vector(k, fill)); } pmt_t vector_ref(pmt_t vector, size_t k) { if (!vector->is_vector()) throw wrong_type("pmt_vector_ref", vector); return _vector(vector)->ref(k); } void vector_set(pmt_t vector, size_t k, pmt_t obj) { if (!vector->is_vector()) throw wrong_type("pmt_vector_set", vector); _vector(vector)->set(k, obj); } void vector_fill(pmt_t vector, pmt_t obj) { if (!vector->is_vector()) throw wrong_type("pmt_vector_set", vector); _vector(vector)->fill(obj); } //////////////////////////////////////////////////////////////////////////// // Tuples //////////////////////////////////////////////////////////////////////////// pmt_tuple::pmt_tuple(size_t len) : d_v(len) { } pmt_t pmt_tuple::ref(size_t k) const { if (k >= length()) throw out_of_range("pmt_tuple_ref", from_long(k)); return d_v[k]; } bool is_tuple(pmt_t obj) { return obj->is_tuple(); } pmt_t tuple_ref(const pmt_t &tuple, size_t k) { if (!tuple->is_tuple()) throw wrong_type("pmt_tuple_ref", tuple); return _tuple(tuple)->ref(k); } // for (i=0; i < 10; i++) // make_constructor() pmt_t make_tuple() { return pmt_t(new pmt_tuple(0)); } pmt_t make_tuple(const pmt_t &e0) { pmt_tuple *t = new pmt_tuple(1); t->_set(0, e0); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1) { pmt_tuple *t = new pmt_tuple(2); t->_set(0, e0); t->_set(1, e1); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2) { pmt_tuple *t = new pmt_tuple(3); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3) { pmt_tuple *t = new pmt_tuple(4); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4) { pmt_tuple *t = new pmt_tuple(5); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); t->_set(4, e4); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5) { pmt_tuple *t = new pmt_tuple(6); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); t->_set(4, e4); t->_set(5, e5); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6) { pmt_tuple *t = new pmt_tuple(7); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); t->_set(4, e4); t->_set(5, e5); t->_set(6, e6); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7) { pmt_tuple *t = new pmt_tuple(8); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); t->_set(4, e4); t->_set(5, e5); t->_set(6, e6); t->_set(7, e7); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8) { pmt_tuple *t = new pmt_tuple(9); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); t->_set(4, e4); t->_set(5, e5); t->_set(6, e6); t->_set(7, e7); t->_set(8, e8); return pmt_t(t); } pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8, const pmt_t &e9) { pmt_tuple *t = new pmt_tuple(10); t->_set(0, e0); t->_set(1, e1); t->_set(2, e2); t->_set(3, e3); t->_set(4, e4); t->_set(5, e5); t->_set(6, e6); t->_set(7, e7); t->_set(8, e8); t->_set(9, e9); return pmt_t(t); } pmt_t to_tuple(const pmt_t &x) { if (x->is_tuple()) // already one return x; size_t len = length(x); pmt_tuple *t = new pmt_tuple(len); pmt_t r = pmt_t(t); if (x->is_vector()){ for (size_t i = 0; i < len; i++) t->_set(i, _vector(x)->ref(i)); return r; } if (x->is_pair()){ pmt_t y = x; for (size_t i = 0; i < len; i++){ t->_set(i, car(y)); y = cdr(y); } return r; } throw wrong_type("pmt_to_tuple", x); } //////////////////////////////////////////////////////////////////////////// // Uniform Numeric Vectors //////////////////////////////////////////////////////////////////////////// bool is_uniform_vector(pmt_t x) { return x->is_uniform_vector(); } const void * uniform_vector_elements(pmt_t vector, size_t &len) { if (!vector->is_uniform_vector()) throw wrong_type("pmt_uniform_vector_elements", vector); return _uniform_vector(vector)->uniform_elements(len); } void * uniform_vector_writable_elements(pmt_t vector, size_t &len) { if (!vector->is_uniform_vector()) throw wrong_type("pmt_uniform_vector_writable_elements", vector); return _uniform_vector(vector)->uniform_writable_elements(len); } //////////////////////////////////////////////////////////////////////////// // Dictionaries //////////////////////////////////////////////////////////////////////////// /* * This is an a-list implementation. * * When we need better performance for large dictionaries, consider implementing * persistent Red-Black trees as described in "Purely Functional Data Structures", * Chris Okasaki, 1998, section 3.3. */ bool is_dict(const pmt_t &obj) { return is_null(obj) || is_pair(obj); } pmt_t make_dict() { return PMT_NIL; } pmt_t dict_add(const pmt_t &dict, const pmt_t &key, const pmt_t &value) { if (is_null(dict)) return acons(key, value, PMT_NIL); if (dict_has_key(dict, key)) return acons(key, value, dict_delete(dict, key)); return acons(key, value, dict); } pmt_t dict_delete(const pmt_t &dict, const pmt_t &key) { if (is_null(dict)) return dict; if (eqv(caar(dict), key)) return cdr(dict); return cons(car(dict), dict_delete(cdr(dict), key)); } pmt_t dict_ref(const pmt_t &dict, const pmt_t &key, const pmt_t ¬_found) { pmt_t p = assv(key, dict); // look for (key . value) pair if (is_pair(p)) return cdr(p); else return not_found; } bool dict_has_key(const pmt_t &dict, const pmt_t &key) { return is_pair(assv(key, dict)); } pmt_t dict_items(pmt_t dict) { if (!is_dict(dict)) throw wrong_type("pmt_dict_values", dict); return dict; // equivalent to dict in the a-list case } pmt_t dict_keys(pmt_t dict) { if (!is_dict(dict)) throw wrong_type("pmt_dict_keys", dict); return map(car, dict); } pmt_t dict_values(pmt_t dict) { if (!is_dict(dict)) throw wrong_type("pmt_dict_keys", dict); return map(cdr, dict); } //////////////////////////////////////////////////////////////////////////// // Any //////////////////////////////////////////////////////////////////////////// pmt_any::pmt_any(const boost::any &any) : d_any(any) {} bool is_any(pmt_t obj) { return obj->is_any(); } pmt_t make_any(const boost::any &any) { return pmt_t(new pmt_any(any)); } boost::any any_ref(pmt_t obj) { if (!obj->is_any()) throw wrong_type("pmt_any_ref", obj); return _any(obj)->ref(); } void any_set(pmt_t obj, const boost::any &any) { if (!obj->is_any()) throw wrong_type("pmt_any_set", obj); _any(obj)->set(any); } //////////////////////////////////////////////////////////////////////////// // msg_accepter -- built from "any" //////////////////////////////////////////////////////////////////////////// bool is_msg_accepter(const pmt_t &obj) { if (!is_any(obj)) return false; boost::any r = any_ref(obj); return boost::any_cast(&r) != 0; } //! make a msg_accepter pmt_t make_msg_accepter(gr::messages::msg_accepter_sptr ma) { return make_any(ma); } //! Return underlying msg_accepter gr::messages::msg_accepter_sptr msg_accepter_ref(const pmt_t &obj) { try { return boost::any_cast(any_ref(obj)); } catch (boost::bad_any_cast &e){ throw wrong_type("pmt_msg_accepter_ref", obj); } } //////////////////////////////////////////////////////////////////////////// // Binary Large Object -- currently a u8vector //////////////////////////////////////////////////////////////////////////// bool is_blob(pmt_t x) { // return is_u8vector(x); return is_uniform_vector(x); } pmt_t make_blob(const void *buf, size_t len_in_bytes) { return init_u8vector(len_in_bytes, (const uint8_t *) buf); } const void * blob_data(pmt_t blob) { size_t len; return uniform_vector_elements(blob, len); } size_t blob_length(pmt_t blob) { size_t len; uniform_vector_elements(blob, len); return len; } //////////////////////////////////////////////////////////////////////////// // General Functions //////////////////////////////////////////////////////////////////////////// bool eq(const pmt_t& x, const pmt_t& y) { return x == y; } bool eqv(const pmt_t& x, const pmt_t& y) { if (x == y) return true; if (x->is_integer() && y->is_integer()) return _integer(x)->value() == _integer(y)->value(); if (x->is_uint64() && y->is_uint64()) return _uint64(x)->value() == _uint64(y)->value(); if (x->is_real() && y->is_real()) return _real(x)->value() == _real(y)->value(); if (x->is_complex() && y->is_complex()) return _complex(x)->value() == _complex(y)->value(); return false; } bool eqv_raw(pmt_base *x, pmt_base *y) { if (x == y) return true; if (x->is_integer() && y->is_integer()) return _integer(x)->value() == _integer(y)->value(); if (x->is_uint64() && y->is_uint64()) return _uint64(x)->value() == _uint64(y)->value(); if (x->is_real() && y->is_real()) return _real(x)->value() == _real(y)->value(); if (x->is_complex() && y->is_complex()) return _complex(x)->value() == _complex(y)->value(); return false; } bool equal(const pmt_t& x, const pmt_t& y) { if (eqv(x, y)) return true; if (x->is_pair() && y->is_pair()) return equal(car(x), car(y)) && equal(cdr(x), cdr(y)); if (x->is_vector() && y->is_vector()){ pmt_vector *xv = _vector(x); pmt_vector *yv = _vector(y); if (xv->length() != yv->length()) return false; for (unsigned i = 0; i < xv->length(); i++) if (!equal(xv->_ref(i), yv->_ref(i))) return false; return true; } if (x->is_tuple() && y->is_tuple()){ pmt_tuple *xv = _tuple(x); pmt_tuple *yv = _tuple(y); if (xv->length() != yv->length()) return false; for (unsigned i = 0; i < xv->length(); i++) if (!equal(xv->_ref(i), yv->_ref(i))) return false; return true; } if (x->is_uniform_vector() && y->is_uniform_vector()){ pmt_uniform_vector *xv = _uniform_vector(x); pmt_uniform_vector *yv = _uniform_vector(y); if (xv->length() != yv->length()) return false; size_t len_x, len_y; if (memcmp(xv->uniform_elements(len_x), yv->uniform_elements(len_y), len_x) == 0) return true; return true; } // FIXME add other cases here... return false; } size_t length(const pmt_t& x) { if (x->is_vector()) return _vector(x)->length(); if (x->is_uniform_vector()) return _uniform_vector(x)->length(); if (x->is_tuple()) return _tuple(x)->length(); if (x->is_null()) return 0; if (x->is_pair()) { size_t length=1; pmt_t it = cdr(x); while (is_pair(it)){ length++; it = cdr(it); } if (is_null(it)) return length; // not a proper list throw wrong_type("pmt_length", x); } // FIXME dictionary length (number of entries) throw wrong_type("pmt_length", x); } pmt_t assq(pmt_t obj, pmt_t alist) { while (is_pair(alist)){ pmt_t p = car(alist); if (!is_pair(p)) // malformed alist return PMT_F; if (eq(obj, car(p))) return p; alist = cdr(alist); } return PMT_F; } /* * This avoids a bunch of shared_pointer reference count manipulation. */ pmt_t assv_raw(pmt_base *obj, pmt_base *alist) { while (alist->is_pair()){ pmt_base *p = ((pmt_pair *)alist)->d_car.get(); if (!p->is_pair()) // malformed alist return PMT_F; if (eqv_raw(obj, ((pmt_pair *)p)->d_car.get())) return ((pmt_pair *)alist)->d_car; alist = (((pmt_pair *)alist)->d_cdr).get(); } return PMT_F; } #if 1 pmt_t assv(pmt_t obj, pmt_t alist) { return assv_raw(obj.get(), alist.get()); } #else pmt_t assv(pmt_t obj, pmt_t alist) { while (is_pair(alist)){ pmt_t p = car(alist); if (!is_pair(p)) // malformed alist return PMT_F; if (eqv(obj, car(p))) return p; alist = cdr(alist); } return PMT_F; } #endif pmt_t assoc(pmt_t obj, pmt_t alist) { while (is_pair(alist)){ pmt_t p = car(alist); if (!is_pair(p)) // malformed alist return PMT_F; if (equal(obj, car(p))) return p; alist = cdr(alist); } return PMT_F; } pmt_t map(pmt_t proc(const pmt_t&), pmt_t list) { pmt_t r = PMT_NIL; while(is_pair(list)){ r = cons(proc(car(list)), r); list = cdr(list); } return reverse_x(r); } pmt_t reverse(pmt_t listx) { pmt_t list = listx; pmt_t r = PMT_NIL; while(is_pair(list)){ r = cons(car(list), r); list = cdr(list); } if (is_null(list)) return r; else throw wrong_type("pmt_reverse", listx); } pmt_t reverse_x(pmt_t list) { // FIXME do it destructively return reverse(list); } pmt_t nth(size_t n, pmt_t list) { pmt_t t = nthcdr(n, list); if (is_pair(t)) return car(t); else return PMT_NIL; } pmt_t nthcdr(size_t n, pmt_t list) { if (!(is_pair(list) || is_null(list))) throw wrong_type("pmt_nthcdr", list); while (n > 0){ if (is_pair(list)){ list = cdr(list); n--; continue; } if (is_null(list)) return PMT_NIL; else throw wrong_type("pmt_nthcdr: not a LIST", list); } return list; } pmt_t memq(pmt_t obj, pmt_t list) { while (is_pair(list)){ if (eq(obj, car(list))) return list; list = cdr(list); } return PMT_F; } pmt_t memv(pmt_t obj, pmt_t list) { while (is_pair(list)){ if (eqv(obj, car(list))) return list; list = cdr(list); } return PMT_F; } pmt_t member(pmt_t obj, pmt_t list) { while (is_pair(list)){ if (equal(obj, car(list))) return list; list = cdr(list); } return PMT_F; } bool subsetp(pmt_t list1, pmt_t list2) { while (is_pair(list1)){ pmt_t p = car(list1); if (is_false(memv(p, list2))) return false; list1 = cdr(list1); } return true; } pmt_t list1(const pmt_t& x1) { return cons(x1, PMT_NIL); } pmt_t list2(const pmt_t& x1, const pmt_t& x2) { return cons(x1, cons(x2, PMT_NIL)); } pmt_t list3(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3) { return cons(x1, cons(x2, cons(x3, PMT_NIL))); } pmt_t list4(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4) { return cons(x1, cons(x2, cons(x3, cons(x4, PMT_NIL)))); } pmt_t list5(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4, const pmt_t& x5) { return cons(x1, cons(x2, cons(x3, cons(x4, cons(x5, PMT_NIL))))); } pmt_t list6(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4, const pmt_t& x5, const pmt_t& x6) { return cons(x1, cons(x2, cons(x3, cons(x4, cons(x5, cons(x6, PMT_NIL)))))); } pmt_t list_add(pmt_t list, const pmt_t& item) { return reverse(cons(item, reverse(list))); } pmt_t list_rm(pmt_t list, const pmt_t& item) { if(is_pair(list)){ pmt_t left = car(list); pmt_t right = cdr(list); if(!equal(left, item)){ return cons(left, list_rm(right, item)); } else { return list_rm(right, item); } } else { return list; } } bool list_has(pmt_t list, const pmt_t& item) { if(is_pair(list)){ pmt_t left = car(list); pmt_t right = cdr(list); if(equal(left,item)) return true; return list_has(right, item); } else { if(is_null(list)) return false; throw std::runtime_error("list contains invalid format!"); } } pmt_t caar(pmt_t pair) { return (car(car(pair))); } pmt_t cadr(pmt_t pair) { return car(cdr(pair)); } pmt_t cdar(pmt_t pair) { return cdr(car(pair)); } pmt_t cddr(pmt_t pair) { return cdr(cdr(pair)); } pmt_t caddr(pmt_t pair) { return car(cdr(cdr(pair))); } pmt_t cadddr(pmt_t pair) { return car(cdr(cdr(cdr(pair)))); } bool is_eof_object(pmt_t obj) { return eq(obj, PMT_EOF); } void dump_sizeof() { printf("sizeof(pmt_t) = %3zd\n", sizeof(pmt_t)); printf("sizeof(pmt_base) = %3zd\n", sizeof(pmt_base)); printf("sizeof(pmt_bool) = %3zd\n", sizeof(pmt_bool)); printf("sizeof(pmt_symbol) = %3zd\n", sizeof(pmt_symbol)); printf("sizeof(pmt_integer) = %3zd\n", sizeof(pmt_integer)); printf("sizeof(pmt_uint64) = %3zd\n", sizeof(pmt_uint64)); printf("sizeof(pmt_real) = %3zd\n", sizeof(pmt_real)); printf("sizeof(pmt_complex) = %3zd\n", sizeof(pmt_complex)); printf("sizeof(pmt_null) = %3zd\n", sizeof(pmt_null)); printf("sizeof(pmt_pair) = %3zd\n", sizeof(pmt_pair)); printf("sizeof(pmt_vector) = %3zd\n", sizeof(pmt_vector)); printf("sizeof(pmt_uniform_vector) = %3zd\n", sizeof(pmt_uniform_vector)); } } /* namespace pmt */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/gnuradio-pmt.rc.in0000664000175000017500000000331212207440367023530 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-pmt" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-pmt.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-pmt.dll" VALUE "ProductName", "gnuradio-pmt" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/unv_template.cc.t0000664000175000017500000000537712207440367023460 0ustar jcorganjcorgan//////////////////////////////////////////////////////////////////////////// // pmt_@TAG@vector //////////////////////////////////////////////////////////////////////////// namespace pmt { static pmt_@TAG@vector * _@TAG@vector(pmt_t x) { return dynamic_cast(x.get()); } pmt_@TAG@vector::pmt_@TAG@vector(size_t k, @TYPE@ fill) : d_v(k) { for (size_t i = 0; i < k; i++) d_v[i] = fill; } pmt_@TAG@vector::pmt_@TAG@vector(size_t k, const @TYPE@ *data) : d_v(k) { for (size_t i = 0; i < k; i++) d_v[i] = data[i]; } @TYPE@ pmt_@TAG@vector::ref(size_t k) const { if (k >= length()) throw out_of_range("pmt_@TAG@vector_ref", from_long(k)); return d_v[k]; } void pmt_@TAG@vector::set(size_t k, @TYPE@ x) { if (k >= length()) throw out_of_range("pmt_@TAG@vector_set", from_long(k)); d_v[k] = x; } const @TYPE@ * pmt_@TAG@vector::elements(size_t &len) { len = length(); return &d_v[0]; } @TYPE@ * pmt_@TAG@vector::writable_elements(size_t &len) { len = length(); return &d_v[0]; } const void* pmt_@TAG@vector::uniform_elements(size_t &len) { len = length() * sizeof(@TYPE@); return &d_v[0]; } void* pmt_@TAG@vector::uniform_writable_elements(size_t &len) { len = length() * sizeof(@TYPE@); return &d_v[0]; } bool is_@TAG@vector(pmt_t obj) { return obj->is_@TAG@vector(); } pmt_t make_@TAG@vector(size_t k, @TYPE@ fill) { return pmt_t(new pmt_@TAG@vector(k, fill)); } pmt_t init_@TAG@vector(size_t k, const @TYPE@ *data) { return pmt_t(new pmt_@TAG@vector(k, data)); } pmt_t init_@TAG@vector(size_t k, const std::vector< @TYPE@ > &data) { return pmt_t(new pmt_@TAG@vector(k, &data[0])); } @TYPE@ @TAG@vector_ref(pmt_t vector, size_t k) { if (!vector->is_@TAG@vector()) throw wrong_type("pmt_@TAG@vector_ref", vector); return _@TAG@vector(vector)->ref(k); } void @TAG@vector_set(pmt_t vector, size_t k, @TYPE@ obj) { if (!vector->is_@TAG@vector()) throw wrong_type("pmt_@TAG@vector_set", vector); _@TAG@vector(vector)->set(k, obj); } const @TYPE@ * @TAG@vector_elements(pmt_t vector, size_t &len) { if (!vector->is_@TAG@vector()) throw wrong_type("pmt_@TAG@vector_elements", vector); return _@TAG@vector(vector)->elements(len); } const std::vector< @TYPE@ > @TAG@vector_elements(pmt_t vector) { if (!vector->is_@TAG@vector()) throw wrong_type("pmt_@TAG@vector_elements", vector); size_t len; const @TYPE@ *array = _@TAG@vector(vector)->elements(len); const std::vector< @TYPE@ > vec(array, array+len); return vec; } @TYPE@ * @TAG@vector_writable_elements(pmt_t vector, size_t &len) { if (!vector->is_@TAG@vector()) throw wrong_type("pmt_@TAG@vector_writable_elements", vector); return _@TAG@vector(vector)->writable_elements(len); } } /* namespace pmt */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/unv_qa_template.cc.t0000664000175000017500000000212312207440367024123 0ustar jcorganjcorganvoid qa_pmt_unv::test_@TAG@vector() { static const size_t N = 3; pmt::pmt_t v1 = pmt::make_@TAG@vector(N, 0); CPPUNIT_ASSERT_EQUAL(N, pmt::length(v1)); @TYPE@ s0 = @TYPE@(10); @TYPE@ s1 = @TYPE@(20); @TYPE@ s2 = @TYPE@(30); pmt::@TAG@vector_set(v1, 0, s0); pmt::@TAG@vector_set(v1, 1, s1); pmt::@TAG@vector_set(v1, 2, s2); CPPUNIT_ASSERT_EQUAL(s0, pmt::@TAG@vector_ref(v1, 0)); CPPUNIT_ASSERT_EQUAL(s1, pmt::@TAG@vector_ref(v1, 1)); CPPUNIT_ASSERT_EQUAL(s2, pmt::@TAG@vector_ref(v1, 2)); CPPUNIT_ASSERT_THROW(pmt::@TAG@vector_ref(v1, N), pmt::out_of_range); CPPUNIT_ASSERT_THROW(pmt::@TAG@vector_set(v1, N, @TYPE@(0)), pmt::out_of_range); size_t len; const @TYPE@ *rd = pmt::@TAG@vector_elements(v1, len); CPPUNIT_ASSERT_EQUAL(len, N); CPPUNIT_ASSERT_EQUAL(s0, rd[0]); CPPUNIT_ASSERT_EQUAL(s1, rd[1]); CPPUNIT_ASSERT_EQUAL(s2, rd[2]); @TYPE@ *wr = pmt::@TAG@vector_writable_elements(v1, len); CPPUNIT_ASSERT_EQUAL(len, N); wr[0] = @TYPE@(0); CPPUNIT_ASSERT_EQUAL(@TYPE@(0), wr[0]); CPPUNIT_ASSERT_EQUAL(s1, wr[1]); CPPUNIT_ASSERT_EQUAL(s2, wr[2]); } gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/pmt_serialize.cc0000664000175000017500000004760512224021502023343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include "pmt_int.h" #include "pmt/pmt_serial_tags.h" namespace pmt { static pmt_t parse_pair(std::streambuf &sb); // ---------------------------------------------------------------- // output primitives // ---------------------------------------------------------------- static bool serialize_untagged_u8(unsigned int i, std::streambuf &sb) { return sb.sputc((i >> 0) & 0xff) != std::streambuf::traits_type::eof(); } // always writes big-endian static bool serialize_untagged_u16(unsigned int i, std::streambuf &sb) { sb.sputc((i >> 8) & 0xff); return sb.sputc((i >> 0) & 0xff) != std::streambuf::traits_type::eof(); } // always writes big-endian static bool serialize_untagged_u32(unsigned int i, std::streambuf &sb) { sb.sputc((i >> 24) & 0xff); sb.sputc((i >> 16) & 0xff); sb.sputc((i >> 8) & 0xff); return sb.sputc((i >> 0) & 0xff) != std::streambuf::traits_type::eof(); } static bool serialize_untagged_f64(double i, std::streambuf &sb) { typedef union { double id; uint64_t ii; } iu_t; iu_t iu; iu.id = i; sb.sputc((iu.ii >> 56) & 0xff); sb.sputc((iu.ii >> 48) & 0xff); sb.sputc((iu.ii >> 40) & 0xff); sb.sputc((iu.ii >> 32) & 0xff); sb.sputc((iu.ii >> 24) & 0xff); sb.sputc((iu.ii >> 16) & 0xff); sb.sputc((iu.ii >> 8) & 0xff); return sb.sputc((iu.ii >> 0) & 0xff) != std::streambuf::traits_type::eof(); } // always writes big-endian static bool serialize_untagged_u64(uint64_t i, std::streambuf &sb) { sb.sputc((i >> 56) & 0xff); sb.sputc((i >> 48) & 0xff); sb.sputc((i >> 40) & 0xff); sb.sputc((i >> 32) & 0xff); sb.sputc((i >> 24) & 0xff); sb.sputc((i >> 16) & 0xff); sb.sputc((i >> 8) & 0xff); return sb.sputc((i >> 0) & 0xff) != std::streambuf::traits_type::eof(); } // ---------------------------------------------------------------- // input primitives // ---------------------------------------------------------------- // always reads big-endian static bool deserialize_untagged_u8(uint8_t *ip, std::streambuf &sb) { std::streambuf::traits_type::int_type t; int i; t = sb.sbumpc(); i = t & 0xff; *ip = i; return t != std::streambuf::traits_type::eof(); } // always reads big-endian static bool deserialize_untagged_u16(uint16_t *ip, std::streambuf &sb) { std::streambuf::traits_type::int_type t; int i; t = sb.sbumpc(); i = t & 0xff; t = sb.sbumpc(); i = (i << 8) | (t & 0xff); *ip = i; return t != std::streambuf::traits_type::eof(); } // always reads big-endian static bool deserialize_untagged_u32(uint32_t *ip, std::streambuf &sb) { std::streambuf::traits_type::int_type t; int i; t = sb.sbumpc(); i = t & 0xff; t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); *ip = i; return t != std::streambuf::traits_type::eof(); } // always reads big-endian static bool deserialize_untagged_u64(uint64_t *ip, std::streambuf &sb) { std::streambuf::traits_type::int_type t; uint64_t i; t = sb.sbumpc(); i = t & 0xff; t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); t = sb.sbumpc(); i = (i << 8) | (t & 0xff); *ip = i; return t != std::streambuf::traits_type::eof(); } static bool deserialize_untagged_f64(double *ip, std::streambuf &sb) { std::streambuf::traits_type::int_type t; typedef union { double id; uint64_t ii; } iu_t; iu_t iu; t = sb.sbumpc(); iu.ii = t & 0xff; t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); t = sb.sbumpc(); iu.ii = (iu.ii<<8) | (t & 0xff); *ip = iu.id; return t != std::streambuf::traits_type::eof(); } static bool deserialize_tuple(pmt_t *tuple, std::streambuf &sb) { uint32_t nitems; bool ok = deserialize_untagged_u32(&nitems, sb); pmt_t list(PMT_NIL); for(uint32_t i=0; i 4) { if(i < -2147483647 || i > 2147483647) throw notimplemented("pmt::serialize (64-bit integers)", obj); } ok = serialize_untagged_u8(PST_INT32, sb); ok &= serialize_untagged_u32(i, sb); return ok; } } if(is_real(obj)) { float i = to_double(obj); ok = serialize_untagged_u8(PST_DOUBLE, sb); ok &= serialize_untagged_f64(i, sb); return ok; } if(is_complex(obj)) { std::complex i = to_complex(obj); ok = serialize_untagged_u8(PST_COMPLEX, sb); ok &= serialize_untagged_f64(i.real(), sb); ok &= serialize_untagged_f64(i.imag(), sb); return ok; } } if(is_vector(obj)) { size_t vec_len = pmt::length(obj); ok = serialize_untagged_u8(PST_VECTOR, sb); ok &= serialize_untagged_u32(vec_len, sb); for(size_t i=0; i c = c32vector_ref(obj, i); ok &= serialize_untagged_f64(c.real(), sb); ok &= serialize_untagged_f64(c.imag(), sb); } return ok; } if(is_c64vector(obj)) { ok = serialize_untagged_u8(PST_UNIFORM_VECTOR, sb); ok &= serialize_untagged_u8(UVI_C64, sb); ok &= serialize_untagged_u32(vec_len, sb); ok &= serialize_untagged_u8(npad, sb); for(size_t i=0; i c = c64vector_ref(obj, i); ok &= serialize_untagged_f64(c.real(), sb); ok &= serialize_untagged_f64(c.imag(), sb); } return ok; } } if (is_dict(obj)) throw notimplemented("pmt::serialize (dict)", obj); if (is_tuple(obj)){ size_t tuple_len = pmt::length(obj); ok = serialize_untagged_u8(PST_TUPLE, sb); ok &= serialize_untagged_u32(tuple_len, sb); for(size_t i=0; i sizeof(tmpbuf)) throw notimplemented("pmt::deserialize: very long symbol", PMT_F); if (sb.sgetn(tmpbuf, u16) != u16) goto error; return intern(std::string(tmpbuf, u16)); case PST_INT32: if (!deserialize_untagged_u32(&u32, sb)) goto error; return from_long((int32_t) u32); case PST_UINT64: if(!deserialize_untagged_u64(&u64, sb)) goto error; return from_uint64(u64); case PST_PAIR: return parse_pair(sb); case PST_DOUBLE: if(!deserialize_untagged_f64(&f64, sb)) goto error; return from_double( f64 ); case PST_COMPLEX: { double r,i; if(!deserialize_untagged_f64(&r, sb) || !deserialize_untagged_f64(&i, sb)) goto error; return make_rectangular( r,i ); } case PST_TUPLE: { pmt_t tuple; if(!deserialize_tuple(&tuple, sb)){ goto error; } return tuple; } case PST_VECTOR: { uint32_t nitems; if(!deserialize_untagged_u32(&nitems, sb)) goto error; pmt_t vec = make_vector(nitems, PMT_NIL); for(uint32_t i=0; i(f64)); } return vec; } case(UVI_F64): { pmt_t vec = make_f64vector(nitems, 0); for(uint32_t i=0; i(f64); deserialize_untagged_f64(&f64, sb); im = static_cast(f64); c32vector_set(vec, i, std::complex(re, im)); } return vec; } case(UVI_C64): { pmt_t vec = make_c64vector(nitems, 0); for(uint32_t i=0; i(re, im)); } return vec; } default: throw exception("pmt::deserialize: malformed input stream, tag value = ", from_long(tag)); } } case PST_DICT: case PST_COMMENT: throw notimplemented("pmt::deserialize: tag value = ", from_long(tag)); default: throw exception("pmt::deserialize: malformed input stream, tag value = ", from_long(tag)); } error: throw exception("pmt::deserialize: malformed input stream", PMT_F); } /* * provide a simple string accessor to the serialized pmt form */ std::string serialize_str(pmt_t obj){ std::stringbuf sb; serialize(obj, sb); return sb.str(); } /* * provide a simple string accessor to the deserialized pmt form */ pmt_t deserialize_str(std::string s){ std::stringbuf sb(s); return deserialize(sb); } /* * This is a mostly non-recursive implementation that allows us to * deserialize very long lists w/o exhausting the evaluation stack. * * On entry we've already eaten the PST_PAIR tag. */ pmt_t parse_pair(std::streambuf &sb) { uint8_t tag; pmt_t val, expr, lastnptr, nptr; // // Keep appending nodes until we get a non-PAIR cdr. // lastnptr = PMT_NIL; while (1){ expr = deserialize(sb); // read the car nptr = cons(expr, PMT_NIL); // build new cell if (is_null(lastnptr)) val = nptr; else set_cdr(lastnptr, nptr); lastnptr = nptr; if (!deserialize_untagged_u8(&tag, sb)) // get tag of cdr throw exception("pmt::deserialize: malformed input stream", PMT_F); if (tag == PST_PAIR) continue; // keep on looping... if (tag == PST_NULL){ expr = PMT_NIL; break; } // // default: push tag back and use pmt_deserialize to get the cdr // sb.sungetc(); expr = deserialize(sb); break; } // // At this point, expr contains the value of the final cdr in the list. // set_cdr(lastnptr, expr); return val; } } /* namespace pmt */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/pmt_pool.cc0000664000175000017500000000514312207440367022333 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include namespace pmt { static inline size_t ROUNDUP(size_t x, size_t stride) { return ((((x) + (stride) - 1)/(stride)) * (stride)); } pmt_pool::pmt_pool(size_t itemsize, size_t alignment, size_t allocation_size, size_t max_items) : d_itemsize(ROUNDUP(itemsize, alignment)), d_alignment(alignment), d_allocation_size(std::max(allocation_size, 16 * itemsize)), d_max_items(max_items), d_n_items(0), d_freelist(0) { } pmt_pool::~pmt_pool() { for (unsigned int i = 0; i < d_allocations.size(); i++){ delete [] d_allocations[i]; } } void * pmt_pool::malloc() { scoped_lock guard(d_mutex); item *p; if (d_max_items != 0){ while (d_n_items >= d_max_items) d_cond.wait(guard); } if (d_freelist){ // got something? p = d_freelist; d_freelist = p->d_next; d_n_items++; return p; } // allocate a new chunk char *alloc = new char[d_allocation_size + d_alignment - 1]; d_allocations.push_back(alloc); // get the alignment we require char *start = (char *)(((uintptr_t)alloc + d_alignment-1) & -d_alignment); char *end = alloc + d_allocation_size + d_alignment - 1; size_t n = (end - start) / d_itemsize; // link the new items onto the free list. p = (item *) start; for (size_t i = 0; i < n; i++){ p->d_next = d_freelist; d_freelist = p; p = (item *)((char *) p + d_itemsize); } // now return the first one p = d_freelist; d_freelist = p->d_next; d_n_items++; return p; } void pmt_pool::free(void *foo) { if (!foo) return; scoped_lock guard(d_mutex); item *p = (item *) foo; p->d_next = d_freelist; d_freelist = p; d_n_items--; if (d_max_items != 0) d_cond.notify_one(); } } /* namespace pmt */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/pmt_int.h0000664000175000017500000001403012207440367022011 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PMT_INT_H #define INCLUDED_PMT_INT_H #include #include #include /* * EVERYTHING IN THIS FILE IS PRIVATE TO THE IMPLEMENTATION! * * See pmt.h for the public interface */ #define PMT_LOCAL_ALLOCATOR 0 // define to 0 or 1 namespace pmt { class PMT_API pmt_base : boost::noncopyable { mutable boost::detail::atomic_count count_; protected: pmt_base() : count_(0) {}; virtual ~pmt_base(); public: virtual bool is_bool() const { return false; } virtual bool is_symbol() const { return false; } virtual bool is_number() const { return false; } virtual bool is_integer() const { return false; } virtual bool is_uint64() const { return false; } virtual bool is_real() const { return false; } virtual bool is_complex() const { return false; } virtual bool is_null() const { return false; } virtual bool is_pair() const { return false; } virtual bool is_tuple() const { return false; } virtual bool is_vector() const { return false; } virtual bool is_dict() const { return false; } virtual bool is_any() const { return false; } virtual bool is_uniform_vector() const { return false; } virtual bool is_u8vector() const { return false; } virtual bool is_s8vector() const { return false; } virtual bool is_u16vector() const { return false; } virtual bool is_s16vector() const { return false; } virtual bool is_u32vector() const { return false; } virtual bool is_s32vector() const { return false; } virtual bool is_u64vector() const { return false; } virtual bool is_s64vector() const { return false; } virtual bool is_f32vector() const { return false; } virtual bool is_f64vector() const { return false; } virtual bool is_c32vector() const { return false; } virtual bool is_c64vector() const { return false; } friend void intrusive_ptr_add_ref(pmt_base* p); friend void intrusive_ptr_release(pmt_base* p); # if (PMT_LOCAL_ALLOCATOR) void *operator new(size_t); void operator delete(void *, size_t); #endif }; class pmt_bool : public pmt_base { public: pmt_bool(); //~pmt_bool(){} bool is_bool() const { return true; } }; class pmt_symbol : public pmt_base { std::string d_name; pmt_t d_next; public: pmt_symbol(const std::string &name); //~pmt_symbol(){} bool is_symbol() const { return true; } const std::string name() { return d_name; } pmt_t next() { return d_next; } // symbol table link void set_next(pmt_t next) { d_next = next; } }; class pmt_integer : public pmt_base { public: long d_value; pmt_integer(long value); //~pmt_integer(){} bool is_number() const { return true; } bool is_integer() const { return true; } long value() const { return d_value; } }; class pmt_uint64 : public pmt_base { public: uint64_t d_value; pmt_uint64(uint64_t value); //~pmt_uint64(){} bool is_number() const { return true; } bool is_uint64() const { return true; } uint64_t value() const { return d_value; } }; class pmt_real : public pmt_base { public: double d_value; pmt_real(double value); //~pmt_real(){} bool is_number() const { return true; } bool is_real() const { return true; } double value() const { return d_value; } }; class pmt_complex : public pmt_base { public: std::complex d_value; pmt_complex(std::complex value); //~pmt_complex(){} bool is_number() const { return true; } bool is_complex() const { return true; } std::complex value() const { return d_value; } }; class pmt_null : public pmt_base { public: pmt_null(); //~pmt_null(){} bool is_null() const { return true; } }; class pmt_pair : public pmt_base { public: pmt_t d_car; pmt_t d_cdr; pmt_pair(const pmt_t& car, const pmt_t& cdr); //~pmt_pair(){}; bool is_pair() const { return true; } pmt_t car() const { return d_car; } pmt_t cdr() const { return d_cdr; } void set_car(pmt_t car) { d_car = car; } void set_cdr(pmt_t cdr) { d_cdr = cdr; } }; class pmt_vector : public pmt_base { std::vector d_v; public: pmt_vector(size_t len, pmt_t fill); //~pmt_vector(); bool is_vector() const { return true; } pmt_t ref(size_t k) const; void set(size_t k, pmt_t obj); void fill(pmt_t fill); size_t length() const { return d_v.size(); } pmt_t _ref(size_t k) const { return d_v[k]; } }; class pmt_tuple : public pmt_base { std::vector d_v; public: pmt_tuple(size_t len); //~pmt_tuple(); bool is_tuple() const { return true; } pmt_t ref(size_t k) const; size_t length() const { return d_v.size(); } pmt_t _ref(size_t k) const { return d_v[k]; } void _set(size_t k, pmt_t v) { d_v[k] = v; } }; class pmt_any : public pmt_base { boost::any d_any; public: pmt_any(const boost::any &any); //~pmt_any(); bool is_any() const { return true; } const boost::any &ref() const { return d_any; } void set(const boost::any &any) { d_any = any; } }; class pmt_uniform_vector : public pmt_base { public: bool is_uniform_vector() const { return true; } virtual const void *uniform_elements(size_t &len) = 0; virtual void *uniform_writable_elements(size_t &len) = 0; virtual size_t length() const = 0; }; #include "pmt_unv_int.h" } /* namespace pmt */ #endif /* INCLUDED_PMT_INT_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/test_pmt.cc0000664000175000017500000000255312207440367022343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include int main (int argc, char **argv) { CppUnit::TextTestRunner runner; std::ofstream xmlfile(get_unittest_path("gnuradio_runtime_runtime.xml").c_str()); CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); runner.addTest(qa_pmt::suite()); runner.setOutputter(xmlout); bool was_successful = runner.run("", false); return was_successful ? 0 : 1; } gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/qa_pmt_prims.cc0000664000175000017500000004555412207440367023207 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2010 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include void qa_pmt_prims::test_symbols() { CPPUNIT_ASSERT(!pmt::is_symbol(pmt::PMT_T)); CPPUNIT_ASSERT(!pmt::is_symbol(pmt::PMT_F)); CPPUNIT_ASSERT_THROW(pmt::symbol_to_string(pmt::PMT_F), pmt::wrong_type); pmt::pmt_t sym1 = pmt::mp("test"); CPPUNIT_ASSERT(pmt::is_symbol(sym1)); CPPUNIT_ASSERT_EQUAL(std::string("test"), pmt::symbol_to_string(sym1)); CPPUNIT_ASSERT(pmt::is_true(sym1)); CPPUNIT_ASSERT(!pmt::is_false(sym1)); pmt::pmt_t sym2 = pmt::mp("foo"); pmt::pmt_t sym3 = pmt::mp("test"); CPPUNIT_ASSERT_EQUAL(sym1, sym3); CPPUNIT_ASSERT(sym1 != sym2); CPPUNIT_ASSERT(sym1 == sym3); static const int N = 2048; std::vector v1(N); std::vector v2(N); // generate a bunch of symbols for (int i = 0; i < N; i++){ std::string buf = str(boost::format("test-%d") % i); v1[i] = pmt::mp(buf.c_str()); } // confirm that they are all unique for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) CPPUNIT_ASSERT(v1[i] != v1[j]); // generate the same symbols again for (int i = 0; i < N; i++){ std::string buf = str(boost::format("test-%d") % i); v2[i] = pmt::mp(buf.c_str()); } // confirm that we get the same ones back for (int i = 0; i < N; i++) CPPUNIT_ASSERT(v1[i] == v2[i]); } void qa_pmt_prims::test_booleans() { pmt::pmt_t sym = pmt::mp("test"); CPPUNIT_ASSERT(pmt::is_bool(pmt::PMT_T)); CPPUNIT_ASSERT(pmt::is_bool(pmt::PMT_F)); CPPUNIT_ASSERT(!pmt::is_bool(sym)); CPPUNIT_ASSERT_EQUAL(pmt::from_bool(false), pmt::PMT_F); CPPUNIT_ASSERT_EQUAL(pmt::from_bool(true), pmt::PMT_T); CPPUNIT_ASSERT_EQUAL(false, pmt::to_bool(pmt::PMT_F)); CPPUNIT_ASSERT_EQUAL(true, pmt::to_bool(pmt::PMT_T)); CPPUNIT_ASSERT_THROW(pmt::to_bool(sym), pmt::wrong_type); } void qa_pmt_prims::test_integers() { pmt::pmt_t p1 = pmt::from_long(1); pmt::pmt_t m1 = pmt::from_long(-1); CPPUNIT_ASSERT(!pmt::is_integer(pmt::PMT_T)); CPPUNIT_ASSERT(pmt::is_integer(p1)); CPPUNIT_ASSERT(pmt::is_integer(m1)); CPPUNIT_ASSERT_THROW(pmt::to_long(pmt::PMT_T), pmt::wrong_type); CPPUNIT_ASSERT_EQUAL(-1L, pmt::to_long(m1)); CPPUNIT_ASSERT_EQUAL(1L, pmt::to_long(p1)); } void qa_pmt_prims::test_uint64s() { pmt::pmt_t p1 = pmt::from_uint64((uint64_t)1); pmt::pmt_t m1 = pmt::from_uint64((uint64_t)8589934592ULL); CPPUNIT_ASSERT(!pmt::is_uint64(pmt::PMT_T)); CPPUNIT_ASSERT(pmt::is_uint64(p1)); CPPUNIT_ASSERT(pmt::is_uint64(m1)); CPPUNIT_ASSERT_THROW(pmt::to_uint64(pmt::PMT_T), pmt::wrong_type); CPPUNIT_ASSERT_EQUAL((uint64_t)8589934592ULL, (uint64_t)pmt::to_uint64(m1)); CPPUNIT_ASSERT_EQUAL((uint64_t)1ULL, (uint64_t)pmt::to_uint64(p1)); } void qa_pmt_prims::test_reals() { pmt::pmt_t p1 = pmt::from_double(1); pmt::pmt_t m1 = pmt::from_double(-1); CPPUNIT_ASSERT(!pmt::is_real(pmt::PMT_T)); CPPUNIT_ASSERT(pmt::is_real(p1)); CPPUNIT_ASSERT(pmt::is_real(m1)); CPPUNIT_ASSERT_THROW(pmt::to_double(pmt::PMT_T), pmt::wrong_type); CPPUNIT_ASSERT_EQUAL(-1.0, pmt::to_double(m1)); CPPUNIT_ASSERT_EQUAL(1.0, pmt::to_double(p1)); CPPUNIT_ASSERT_EQUAL(1.0, pmt::to_double(pmt::from_long(1))); } void qa_pmt_prims::test_complexes() { pmt::pmt_t p1 = pmt::make_rectangular(2, -3); pmt::pmt_t m1 = pmt::make_rectangular(-3, 2); pmt::pmt_t p2 = pmt::from_complex(2, -3); pmt::pmt_t m2 = pmt::from_complex(-3, 2); pmt::pmt_t p3 = pmt::from_complex(std::complex(2, -3)); pmt::pmt_t m3 = pmt::from_complex(std::complex(-3, 2)); CPPUNIT_ASSERT(!pmt::is_complex(pmt::PMT_T)); CPPUNIT_ASSERT(pmt::is_complex(p1)); CPPUNIT_ASSERT(pmt::is_complex(m1)); CPPUNIT_ASSERT(pmt::is_complex(p2)); CPPUNIT_ASSERT(pmt::is_complex(m2)); CPPUNIT_ASSERT(pmt::is_complex(p3)); CPPUNIT_ASSERT(pmt::is_complex(m3)); CPPUNIT_ASSERT_THROW(pmt::to_complex(pmt::PMT_T), pmt::wrong_type); CPPUNIT_ASSERT_EQUAL(std::complex(2, -3), pmt::to_complex(p1)); CPPUNIT_ASSERT_EQUAL(std::complex(-3, 2), pmt::to_complex(m1)); CPPUNIT_ASSERT_EQUAL(std::complex(2, -3), pmt::to_complex(p2)); CPPUNIT_ASSERT_EQUAL(std::complex(-3, 2), pmt::to_complex(m2)); CPPUNIT_ASSERT_EQUAL(std::complex(2, -3), pmt::to_complex(p3)); CPPUNIT_ASSERT_EQUAL(std::complex(-3, 2), pmt::to_complex(m3)); CPPUNIT_ASSERT_EQUAL(std::complex(1.0, 0), pmt::to_complex(pmt::from_long(1))); CPPUNIT_ASSERT_EQUAL(std::complex(1.0, 0), pmt::to_complex(pmt::from_double(1.0))); } void qa_pmt_prims::test_pairs() { CPPUNIT_ASSERT(pmt::is_null(pmt::PMT_NIL)); CPPUNIT_ASSERT(!pmt::is_pair(pmt::PMT_NIL)); pmt::pmt_t s1 = pmt::mp("s1"); pmt::pmt_t s2 = pmt::mp("s2"); pmt::pmt_t s3 = pmt::mp("s3"); CPPUNIT_ASSERT_EQUAL((size_t)0, pmt::length(pmt::PMT_NIL)); CPPUNIT_ASSERT_THROW(pmt::length(s1), pmt::wrong_type); CPPUNIT_ASSERT_THROW(pmt::length(pmt::from_double(42)), pmt::wrong_type); pmt::pmt_t c1 = pmt::cons(s1, pmt::PMT_NIL); CPPUNIT_ASSERT(pmt::is_pair(c1)); CPPUNIT_ASSERT(!pmt::is_pair(s1)); CPPUNIT_ASSERT_EQUAL(s1, pmt::car(c1)); CPPUNIT_ASSERT_EQUAL(pmt::PMT_NIL, pmt::cdr(c1)); CPPUNIT_ASSERT_EQUAL((size_t) 1, pmt::length(c1)); pmt::pmt_t c3 = pmt::cons(s3, pmt::PMT_NIL); pmt::pmt_t c2 = pmt::cons(s2, c3); pmt::set_cdr(c1, c2); CPPUNIT_ASSERT_EQUAL(c2, pmt::cdr(c1)); pmt::set_car(c1, s3); CPPUNIT_ASSERT_EQUAL(s3, pmt::car(c1)); CPPUNIT_ASSERT_EQUAL((size_t)1, pmt::length(c3)); CPPUNIT_ASSERT_EQUAL((size_t)2, pmt::length(c2)); CPPUNIT_ASSERT_THROW(pmt::cdr(pmt::PMT_NIL), pmt::wrong_type); CPPUNIT_ASSERT_THROW(pmt::car(pmt::PMT_NIL), pmt::wrong_type); CPPUNIT_ASSERT_THROW(pmt::set_car(s1, pmt::PMT_NIL), pmt::wrong_type); CPPUNIT_ASSERT_THROW(pmt::set_cdr(s1, pmt::PMT_NIL), pmt::wrong_type); } void qa_pmt_prims::test_vectors() { static const size_t N = 3; pmt::pmt_t v1 = pmt::make_vector(N, pmt::PMT_NIL); CPPUNIT_ASSERT_EQUAL(N, pmt::length(v1)); pmt::pmt_t s0 = pmt::mp("s0"); pmt::pmt_t s1 = pmt::mp("s1"); pmt::pmt_t s2 = pmt::mp("s2"); pmt::vector_set(v1, 0, s0); pmt::vector_set(v1, 1, s1); pmt::vector_set(v1, 2, s2); CPPUNIT_ASSERT_EQUAL(s0, pmt::vector_ref(v1, 0)); CPPUNIT_ASSERT_EQUAL(s1, pmt::vector_ref(v1, 1)); CPPUNIT_ASSERT_EQUAL(s2, pmt::vector_ref(v1, 2)); CPPUNIT_ASSERT_THROW(pmt::vector_ref(v1, N), pmt::out_of_range); CPPUNIT_ASSERT_THROW(pmt::vector_set(v1, N, pmt::PMT_NIL), pmt::out_of_range); pmt::vector_fill(v1, s0); for (size_t i = 0; i < N; i++) CPPUNIT_ASSERT_EQUAL(s0, pmt::vector_ref(v1, i)); } static void check_tuple(size_t len, const std::vector &s, pmt::pmt_t t) { CPPUNIT_ASSERT_EQUAL(true, pmt::is_tuple(t)); CPPUNIT_ASSERT_EQUAL(len, pmt::length(t)); for (size_t i = 0; i < len; i++) CPPUNIT_ASSERT_EQUAL(s[i], pmt::tuple_ref(t, i)); } void qa_pmt_prims::test_tuples() { pmt::pmt_t v = pmt::make_vector(10, pmt::PMT_NIL); std::vector s(10); for (size_t i = 0; i < 10; i++){ std::ostringstream os; os << "s" << i; s[i] = pmt::mp(os.str()); pmt::vector_set(v, i, s[i]); } pmt::pmt_t t; t = pmt::make_tuple(); check_tuple(0, s, t); t = pmt::make_tuple(s[0]); check_tuple(1, s, t); CPPUNIT_ASSERT(pmt::is_vector(v)); CPPUNIT_ASSERT(!pmt::is_tuple(v)); CPPUNIT_ASSERT(pmt::is_tuple(t)); CPPUNIT_ASSERT(!pmt::is_vector(t)); t = pmt::make_tuple(s[0], s[1]); check_tuple(2, s, t); t = pmt::make_tuple(s[0], s[1], s[2]); check_tuple(3, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3]); check_tuple(4, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4]); check_tuple(5, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4], s[5]); check_tuple(6, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4], s[5], s[6]); check_tuple(7, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]); check_tuple(8, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8]); check_tuple(9, s, t); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9]); check_tuple(10, s, t); t = pmt::make_tuple(s[0], s[1], s[2]); CPPUNIT_ASSERT_THROW(pmt::tuple_ref(t, 3), pmt::out_of_range); CPPUNIT_ASSERT_THROW(pmt::vector_ref(t, 0), pmt::wrong_type); CPPUNIT_ASSERT_THROW(pmt::tuple_ref(v, 0), pmt::wrong_type); t = pmt::make_tuple(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9]); pmt::pmt_t t2 = pmt::to_tuple(v); CPPUNIT_ASSERT_EQUAL(size_t(10), pmt::length(v)); CPPUNIT_ASSERT(pmt::equal(t, t2)); //std::cout << v << std::endl; //std::cout << t2 << std::endl; t = pmt::make_tuple(s[0], s[1], s[2]); pmt::pmt_t list0 = pmt::list3(s[0], s[1], s[2]); CPPUNIT_ASSERT_EQUAL(size_t(3), pmt::length(list0)); t2 = pmt::to_tuple(list0); CPPUNIT_ASSERT_EQUAL(size_t(3), pmt::length(t2)); CPPUNIT_ASSERT(pmt::equal(t, t2)); } void qa_pmt_prims::test_equivalence() { pmt::pmt_t s0 = pmt::mp("s0"); pmt::pmt_t s1 = pmt::mp("s1"); pmt::pmt_t s2 = pmt::mp("s2"); pmt::pmt_t list0 = pmt::cons(s0, pmt::cons(s1, pmt::cons(s2, pmt::PMT_NIL))); pmt::pmt_t list1 = pmt::cons(s0, pmt::cons(s1, pmt::cons(s2, pmt::PMT_NIL))); pmt::pmt_t i0 = pmt::from_long(42); pmt::pmt_t i1 = pmt::from_long(42); pmt::pmt_t r0 = pmt::from_double(42); pmt::pmt_t r1 = pmt::from_double(42); pmt::pmt_t r2 = pmt::from_double(43); CPPUNIT_ASSERT(pmt::eq(s0, s0)); CPPUNIT_ASSERT(!pmt::eq(s0, s1)); CPPUNIT_ASSERT(pmt::eqv(s0, s0)); CPPUNIT_ASSERT(!pmt::eqv(s0, s1)); CPPUNIT_ASSERT(pmt::eqv(i0, i1)); CPPUNIT_ASSERT(pmt::eqv(r0, r1)); CPPUNIT_ASSERT(!pmt::eqv(r0, r2)); CPPUNIT_ASSERT(!pmt::eqv(i0, r0)); CPPUNIT_ASSERT(!pmt::eq(list0, list1)); CPPUNIT_ASSERT(!pmt::eqv(list0, list1)); CPPUNIT_ASSERT(pmt::equal(list0, list1)); pmt::pmt_t v0 = pmt::make_vector(3, s0); pmt::pmt_t v1 = pmt::make_vector(3, s0); pmt::pmt_t v2 = pmt::make_vector(4, s0); CPPUNIT_ASSERT(!pmt::eqv(v0, v1)); CPPUNIT_ASSERT(pmt::equal(v0, v1)); CPPUNIT_ASSERT(!pmt::equal(v0, v2)); pmt::vector_set(v0, 0, list0); pmt::vector_set(v0, 1, list0); pmt::vector_set(v1, 0, list1); pmt::vector_set(v1, 1, list1); CPPUNIT_ASSERT(pmt::equal(v0, v1)); } void qa_pmt_prims::test_misc() { pmt::pmt_t k0 = pmt::mp("k0"); pmt::pmt_t k1 = pmt::mp("k1"); pmt::pmt_t k2 = pmt::mp("k2"); pmt::pmt_t k3 = pmt::mp("k3"); pmt::pmt_t v0 = pmt::mp("v0"); pmt::pmt_t v1 = pmt::mp("v1"); pmt::pmt_t v2 = pmt::mp("v2"); pmt::pmt_t p0 = pmt::cons(k0, v0); pmt::pmt_t p1 = pmt::cons(k1, v1); pmt::pmt_t p2 = pmt::cons(k2, v2); pmt::pmt_t alist = pmt::cons(p0, pmt::cons(p1, pmt::cons(p2, pmt::PMT_NIL))); CPPUNIT_ASSERT(pmt::eq(p1, pmt::assv(k1, alist))); CPPUNIT_ASSERT(pmt::eq(pmt::PMT_F, pmt::assv(k3, alist))); pmt::pmt_t keys = pmt::cons(k0, pmt::cons(k1, pmt::cons(k2, pmt::PMT_NIL))); pmt::pmt_t vals = pmt::cons(v0, pmt::cons(v1, pmt::cons(v2, pmt::PMT_NIL))); CPPUNIT_ASSERT(pmt::equal(keys, pmt::map(pmt::car, alist))); CPPUNIT_ASSERT(pmt::equal(vals, pmt::map(pmt::cdr, alist))); } void qa_pmt_prims::test_dict() { pmt::pmt_t dict = pmt::make_dict(); CPPUNIT_ASSERT(pmt::is_dict(dict)); pmt::pmt_t k0 = pmt::mp("k0"); pmt::pmt_t k1 = pmt::mp("k1"); pmt::pmt_t k2 = pmt::mp("k2"); pmt::pmt_t k3 = pmt::mp("k3"); pmt::pmt_t v0 = pmt::mp("v0"); pmt::pmt_t v1 = pmt::mp("v1"); pmt::pmt_t v2 = pmt::mp("v2"); pmt::pmt_t v3 = pmt::mp("v3"); pmt::pmt_t not_found = pmt::cons(pmt::PMT_NIL, pmt::PMT_NIL); CPPUNIT_ASSERT(!pmt::dict_has_key(dict, k0)); dict = pmt::dict_add(dict, k0, v0); CPPUNIT_ASSERT(pmt::dict_has_key(dict, k0)); CPPUNIT_ASSERT(pmt::eqv(pmt::dict_ref(dict, k0, not_found), v0)); CPPUNIT_ASSERT(pmt::eqv(pmt::dict_ref(dict, k1, not_found), not_found)); dict = pmt::dict_add(dict, k1, v1); dict = pmt::dict_add(dict, k2, v2); CPPUNIT_ASSERT(pmt::eqv(pmt::dict_ref(dict, k1, not_found), v1)); dict = pmt::dict_add(dict, k1, v3); CPPUNIT_ASSERT(pmt::eqv(pmt::dict_ref(dict, k1, not_found), v3)); pmt::pmt_t keys = pmt::list3(k1, k2, k0); pmt::pmt_t vals = pmt::list3(v3, v2, v0); //std::cout << "pmt::dict_keys: " << pmt::dict_keys(dict) << std::endl; //std::cout << "pmt::dict_values: " << pmt::dict_values(dict) << std::endl; CPPUNIT_ASSERT(pmt::equal(keys, pmt::dict_keys(dict))); CPPUNIT_ASSERT(pmt::equal(vals, pmt::dict_values(dict))); } void qa_pmt_prims::test_io() { pmt::pmt_t k0 = pmt::mp("k0"); pmt::pmt_t k1 = pmt::mp("k1"); pmt::pmt_t k2 = pmt::mp("k2"); pmt::pmt_t k3 = pmt::mp("k3"); CPPUNIT_ASSERT_EQUAL(std::string("k0"), pmt::write_string(k0)); } void qa_pmt_prims::test_lists() { pmt::pmt_t s0 = pmt::mp("s0"); pmt::pmt_t s1 = pmt::mp("s1"); pmt::pmt_t s2 = pmt::mp("s2"); pmt::pmt_t s3 = pmt::mp("s3"); pmt::pmt_t l1 = pmt::list4(s0, s1, s2, s3); pmt::pmt_t l2 = pmt::list3(s0, s1, s2); pmt::pmt_t l3 = pmt::list_add(l2, s3); CPPUNIT_ASSERT(pmt::equal(l1, l3)); } // ------------------------------------------------------------------------ // class foo is used in test_any below. // It can't be declared in the scope of test_any because of template // namespace problems. class foo { public: double d_double; int d_int; foo(double d=0, int i=0) : d_double(d), d_int(i) {} }; bool operator==(const foo &a, const foo &b) { return a.d_double == b.d_double && a.d_int == b.d_int; } std::ostream& operator<<(std::ostream &os, const foo obj) { os << ""; return os; } void qa_pmt_prims::test_any() { boost::any a0; boost::any a1; boost::any a2; a0 = std::string("Hello!"); a1 = 42; a2 = foo(3.250, 21); pmt::pmt_t p0 = pmt::make_any(a0); pmt::pmt_t p1 = pmt::make_any(a1); pmt::pmt_t p2 = pmt::make_any(a2); CPPUNIT_ASSERT_EQUAL(std::string("Hello!"), boost::any_cast(pmt::any_ref(p0))); CPPUNIT_ASSERT_EQUAL(42, boost::any_cast(pmt::any_ref(p1))); CPPUNIT_ASSERT_EQUAL(foo(3.250, 21), boost::any_cast(pmt::any_ref(p2))); } // ------------------------------------------------------------------------ class qa_pmt_msg_accepter_nop : public gr::messages::msg_accepter { public: qa_pmt_msg_accepter_nop(){}; ~qa_pmt_msg_accepter_nop(); void post(pmt::pmt_t,pmt::pmt_t){}; }; qa_pmt_msg_accepter_nop::~qa_pmt_msg_accepter_nop(){} void qa_pmt_prims::test_msg_accepter() { pmt::pmt_t sym = pmt::mp("my-symbol"); boost::any a0; a0 = std::string("Hello!"); pmt::pmt_t p0 = pmt::make_any(a0); gr::messages::msg_accepter_sptr ma0 = \ gr::messages::msg_accepter_sptr(new qa_pmt_msg_accepter_nop()); pmt::pmt_t p1 = pmt::make_msg_accepter(ma0); CPPUNIT_ASSERT_EQUAL(ma0.get(), pmt::msg_accepter_ref(p1).get()); CPPUNIT_ASSERT_THROW(pmt::msg_accepter_ref(sym), pmt::wrong_type); CPPUNIT_ASSERT_THROW(pmt::msg_accepter_ref(p0), pmt::wrong_type); // just confirm interfaces on send are OK pmt::pmt_t port(pmt::intern("port")); gr::messages::send(ma0.get(), port, sym); gr::messages::send(ma0, port, sym); gr::messages::send(p1, port, sym); } // ------------------------------------------------------------------------ void qa_pmt_prims::test_serialize() { std::stringbuf sb; // fake channel pmt::pmt_t a = pmt::mp("a"); pmt::pmt_t b = pmt::mp("b"); pmt::pmt_t c = pmt::mp("c"); sb.str(""); // reset channel to empty // write stuff to channel pmt::serialize(pmt::PMT_NIL, sb); pmt::serialize(pmt::mp("foobarvia"), sb); pmt::serialize(pmt::from_long(123456789), sb); pmt::serialize(pmt::from_long(-123456789), sb); pmt::serialize(pmt::cons(pmt::PMT_NIL, pmt::PMT_NIL), sb); pmt::serialize(pmt::cons(a, b), sb); pmt::serialize(pmt::list1(a), sb); pmt::serialize(pmt::list2(a, b), sb); pmt::serialize(pmt::list3(a, b, c), sb); pmt::serialize(pmt::list3(a, pmt::list3(c, b, a), c), sb); pmt::serialize(pmt::PMT_T, sb); pmt::serialize(pmt::PMT_F, sb); // read it back CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::PMT_NIL)); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::mp("foobarvia"))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::from_long(123456789))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::from_long(-123456789))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::cons(pmt::PMT_NIL, pmt::PMT_NIL))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::cons(a, b))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::list1(a))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::list2(a, b))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::list3(a, b, c))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::list3(a, pmt::list3(c, b, a), c))); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::PMT_T)); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::PMT_F)); CPPUNIT_ASSERT(pmt::equal(pmt::deserialize(sb), pmt::PMT_EOF)); // last item // FIXME add tests for real, complex, vector, uniform-vector, dict // FIXME add tests for malformed input too. } void qa_pmt_prims::test_sets() { pmt::pmt_t s1 = pmt::mp("s1"); pmt::pmt_t s2 = pmt::mp("s2"); pmt::pmt_t s3 = pmt::mp("s3"); pmt::pmt_t l1 = pmt::list1(s1); pmt::pmt_t l2 = pmt::list2(s2,s3); pmt::pmt_t l3 = pmt::list3(s1,s2,s3); CPPUNIT_ASSERT(pmt::is_pair(pmt::memq(s1,l1))); CPPUNIT_ASSERT(pmt::is_false(pmt::memq(s3,l1))); CPPUNIT_ASSERT(pmt::subsetp(l1,l3)); CPPUNIT_ASSERT(pmt::subsetp(l2,l3)); CPPUNIT_ASSERT(!pmt::subsetp(l1,l2)); CPPUNIT_ASSERT(!pmt::subsetp(l2,l1)); CPPUNIT_ASSERT(!pmt::subsetp(l3,l2)); } void qa_pmt_prims::test_sugar() { CPPUNIT_ASSERT(pmt::is_symbol(pmt::mp("my-symbol"))); CPPUNIT_ASSERT_EQUAL((long) 10, pmt::to_long(pmt::mp(10))); CPPUNIT_ASSERT_EQUAL((double) 1e6, pmt::to_double(pmt::mp(1e6))); CPPUNIT_ASSERT_EQUAL(std::complex(2, 3), pmt::to_complex(pmt::mp(std::complex(2, 3)))); int buf[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; pmt::pmt_t blob = pmt::mp(buf, sizeof(buf)); const void *data = pmt::blob_data(blob); size_t nbytes = pmt::blob_length(blob); CPPUNIT_ASSERT_EQUAL(sizeof(buf), nbytes); CPPUNIT_ASSERT(memcmp(buf, data, nbytes) == 0); } gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/qa_pmt.h0000664000175000017500000000215512207440367021625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_PMT_H #define INCLUDED_QA_PMT_H #include #include //! collect all the tests for pmt class __GR_ATTR_EXPORT qa_pmt { public: //! return suite of tests for all of pmt static CppUnit::TestSuite *suite (); }; #endif /* INCLUDED_QA_PMT_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/qa_pmt_prims.h0000664000175000017500000000424112207440367023035 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_PMT_PRIMS_H #define INCLUDED_QA_PMT_PRIMS_H #include #include //reason: suppress warnings #include #include class __GR_ATTR_EXPORT qa_pmt_prims : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_pmt_prims); CPPUNIT_TEST(test_symbols); CPPUNIT_TEST(test_booleans); CPPUNIT_TEST(test_integers); CPPUNIT_TEST(test_uint64s); CPPUNIT_TEST(test_reals); CPPUNIT_TEST(test_complexes); CPPUNIT_TEST(test_pairs); CPPUNIT_TEST(test_vectors); CPPUNIT_TEST(test_tuples); CPPUNIT_TEST(test_equivalence); CPPUNIT_TEST(test_misc); CPPUNIT_TEST(test_dict); CPPUNIT_TEST(test_any); CPPUNIT_TEST(test_msg_accepter); CPPUNIT_TEST(test_io); CPPUNIT_TEST(test_lists); CPPUNIT_TEST(test_serialize); CPPUNIT_TEST(test_sets); CPPUNIT_TEST(test_sugar); CPPUNIT_TEST_SUITE_END(); private: void test_symbols(); void test_booleans(); void test_integers(); void test_uint64s(); void test_reals(); void test_complexes(); void test_pairs(); void test_vectors(); void test_tuples(); void test_equivalence(); void test_misc(); void test_dict(); void test_any(); void test_msg_accepter(); void test_io(); void test_lists(); void test_serialize(); void test_sets(); void test_sugar(); }; #endif /* INCLUDED_QA_PMT_PRIMS_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/pmt-serial-tags.scm0000664000175000017500000000462512207440367023714 0ustar jcorganjcorgan;;; -*-scheme-*- ;;; ;;; Copyright 2007 Free Software Foundation, Inc. ;;; ;;; This file is part of GNU Radio ;;; ;;; GNU Radio is free software; you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 3, or (define at your option) ;;; any later version. ;;; ;;; GNU Radio is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License along ;;; with this program; if not, write to the Free Software Foundation, Inc., ;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ;;; ;;; definitions of tag values used for marshalling pmt data (define pst-true #x00) (define pst-false #x01) (define pst-symbol #x02) ; untagged-int16 n; followed by n bytes of symbol name (define pst-int32 #x03) (define pst-double #x04) (define pst-complex #x05) ; complex: real, imag (define pst-null #x06) (define pst-pair #x07) ; followed by two objects (define pst-vector #x08) ; untagged-int32 n; followed by n objects (define pst-dict #x09) ; untagged-int32 n; followed by n key/value tuples (define pst-uniform-vector #x0a) (define pst-uint64 #x0b) (define pst-tuple #x0c) ;; u8, s8, u16, s16, u32, s32, u64, s64, f32, f64, c32, c64 ;; ;; untagged-uint8 tag ;; untagged-uint8 uvi (define uniform vector info, see below) ;; untagged-int32 n-items ;; untagged-uint8 npad ;; npad bytes of zeros to align binary data ;; n-items binary numeric items ;; ;; uvi: ;; +-+-+-+-+-+-+-+-+ ;; |B| subtype | ;; +-+-+-+-+-+-+-+-+ ;; ;; B == 0, numeric data is little-endian. ;; B == 1, numeric data is big-endian. (define uvi-endian-mask #x80) (define uvi-subtype-mask #x7f) (define uvi-little-endian #x00) (define uvi-big-endian #x80) (define uvi-u8 #x00) (define uvi-s8 #x01) (define uvi-u16 #x02) (define uvi-s16 #x03) (define uvi-u32 #x04) (define uvi-s32 #x05) (define uvi-u64 #x06) (define uvi-s64 #x07) (define uvi-f32 #x08) (define uvi-f64 #x09) (define uvi-c32 #x0a) (define uvi-c64 #x0b) (define pst-comment #x3b) ; ascii ';' (define pst-comment-end #x0a) ; ascii '\n' gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/qa_pmt.cc0000664000175000017500000000226012207440367021760 0ustar jcorganjcorgan/* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This class gathers together all the test cases for pmt into * a single test suite. As you create new test cases, add them here. */ #include #include #include CppUnit::TestSuite * qa_pmt::suite() { CppUnit::TestSuite *s = new CppUnit::TestSuite("pmt"); s->addTest(qa_pmt_prims::suite()); s->addTest(qa_pmt_unv::suite()); return s; } gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/unv_template.h.t0000664000175000017500000000134512207440367023311 0ustar jcorganjcorgan //////////////////////////////////////////////////////////////////////////// // pmt_@TAG@vector //////////////////////////////////////////////////////////////////////////// class pmt_@TAG@vector : public pmt_uniform_vector { std::vector< @TYPE@ > d_v; public: pmt_@TAG@vector(size_t k, @TYPE@ fill); pmt_@TAG@vector(size_t k, const @TYPE@ *data); // ~pmt_@TAG@vector(); bool is_@TAG@vector() const { return true; } size_t length() const { return d_v.size(); } @TYPE@ ref(size_t k) const; void set(size_t k, @TYPE@ x); const @TYPE@ *elements(size_t &len); @TYPE@ *writable_elements(size_t &len); const void *uniform_elements(size_t &len); void *uniform_writable_elements(size_t &len); }; gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/gen-serial-tags.py0000664000175000017500000000327412207440367023532 0ustar jcorganjcorgan""" // // Copyright 2011 Free Software Foundation, Inc. // // This file is part of GNU Radio // // GNU Radio is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GNU Radio is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // // THIS FILE IS MACHINE GENERATED FROM %s. DO NOT EDIT BY HAND. // See %s for additional commentary. // #ifndef INCLUDED_PMT_SERIAL_TAGS_H #define INCLUDED_PMT_SERIAL_TAGS_H enum pst_tags { %s }; #endif /* INCLUDED_PMT_SERIAL_TAGS_H */ """ import sys, os, re if __name__ == '__main__': if len(sys.argv) != 3: print "Usage %s "%__file__ exit() input_scm_file, output_hdr_file = sys.argv[1:] enums = list() for line in open(input_scm_file).readlines(): match = re.match('^\s*\(define\s+([\w|-]+)\s+#x([0-9a-fA-F]+)\)', line) if not match: continue name, value = match.groups() name = name.upper().replace('-', '_') enums.append(' %s = 0x%s'%(name, value)) open(output_hdr_file, 'w').write(__doc__%( os.path.basename(__file__), os.path.basename(input_scm_file), ',\n'.join(enums), )) gnuradio-3.7.2.1/gnuradio-runtime/lib/pmt/generate_unv.py0000775000175000017500000001126312207440367023232 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Generate code for uniform numeric vectors """ import re, os, os.path unv_types = ( ('u8', 'uint8_t'), ('s8', 'int8_t'), ('u16', 'uint16_t'), ('s16', 'int16_t'), ('u32', 'uint32_t'), ('s32', 'int32_t'), ('u64', 'uint64_t'), ('s64', 'int64_t'), ('f32', 'float'), ('f64', 'double'), ('c32', 'std::complex'), ('c64', 'std::complex') ) header = """\ /* -*- c++ -*- */ /* * Copyright 2006,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ """ guard_tail = """ #endif """ includes = """ #ifdef HAVE_CONFIG_H #include #endif #include #include #include "pmt_int.h" """ qa_includes = """ #include #include #include #include using namespace pmt; """ # set srcdir to the directory that contains Makefile.am try: srcdir = os.environ['srcdir'] except KeyError, e: srcdir = "." srcdir = srcdir + '/' def open_src (name, mode): global srcdir return open(os.path.join (srcdir, name), mode) def guard_name(filename): return 'INCLUDED_' + re.sub('\.', '_', filename.upper()) def guard_head(filename): guard = guard_name(filename) return """ #ifndef %s #define %s """ % (guard, guard) def do_substitution (d, input, out_file): def repl (match_obj): key = match_obj.group (1) # print key return d[key] out = re.sub (r"@([a-zA-Z0-9_]+)@", repl, input) out_file.write (out) def generate_h(): template = open_src('unv_template.h.t', 'r').read() output_filename = 'pmt_unv_int.h' output = open(output_filename, 'w') output.write(header) output.write(guard_head(output_filename)) for tag, typ in unv_types: d = { 'TAG' : tag, 'TYPE' : typ } do_substitution(d, template, output) output.write(guard_tail) def generate_cc(): template = open_src('unv_template.cc.t', 'r').read() output = open('pmt_unv.cc', 'w') output.write(header) output.write(includes) for tag, typ in unv_types: d = { 'TAG' : tag, 'TYPE' : typ } do_substitution(d, template, output) def generate_qa_h(): output_filename = 'qa_pmt_unv.h' output = open(output_filename, 'w') output.write(header) output.write(guard_head(output_filename)) output.write(''' #include #include class qa_pmt_unv : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_pmt_unv); ''') for tag, typ in unv_types: output.write(' CPPUNIT_TEST(test_%svector);\n' % (tag,)) output.write('''\ CPPUNIT_TEST_SUITE_END(); private: ''') for tag, typ in unv_types: output.write(' void test_%svector();\n' % (tag,)) output.write('};\n') output.write(guard_tail) def generate_qa_cc(): template = open_src('unv_qa_template.cc.t', 'r').read() output = open('qa_pmt_unv.cc', 'w') output.write(header) output.write(qa_includes) for tag, typ in unv_types: d = { 'TAG' : tag, 'TYPE' : typ } do_substitution(d, template, output) def main(): generate_h() generate_cc() generate_qa_h() generate_qa_cc() if __name__ == '__main__': main() gnuradio-3.7.2.1/gnuradio-runtime/lib/CMakeLists.txt0000664000175000017500000001722612236474522022142 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrMiscUtils) GR_CHECK_HDR_N_DEF(sys/resource.h HAVE_SYS_RESOURCE_H) ######################################################################## # Handle the generated constants ######################################################################## execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import time;print time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime())" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE ) message(STATUS "Loading build date ${BUILD_DATE} into constants...") message(STATUS "Loading version ${VERSION} into constants...") #double escape for windows backslash path separators string(REPLACE "\\" "\\\\" prefix ${prefix}) string(REPLACE "\\" "\\\\" SYSCONFDIR ${SYSCONFDIR}) string(REPLACE "\\" "\\\\" GR_PREFSDIR ${GR_PREFSDIR}) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/constants.cc.in ${CMAKE_CURRENT_BINARY_DIR}/constants.cc @ONLY) list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_BINARY_DIR}/constants.cc) ######################################################################## # Include subdirs rather to populate to the sources lists. ######################################################################## #GR_INCLUDE_SUBDIRECTORY(foo) ######################################################################## # Setup the include and linker paths ######################################################################## include_directories(${GNURADIO_RUNTIME_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}/../include/ ${VOLK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) ######################################################################## # Include subdirs rather to populate to the sources lists. ######################################################################## add_subdirectory(pmt) GR_INCLUDE_SUBDIRECTORY(messages) GR_INCLUDE_SUBDIRECTORY(thread) GR_INCLUDE_SUBDIRECTORY(math) ######################################################################## # Setup library ######################################################################## list(APPEND gnuradio_runtime_sources basic_block.cc block.cc block_detail.cc block_executor.cc block_gateway_impl.cc block_registry.cc buffer.cc circular_file.cc complex_vec_test.cc feval.cc flat_flowgraph.cc flowgraph.cc hier_block2.cc hier_block2_detail.cc high_res_timer.cc io_signature.cc local_sighandler.cc logger.cc malloc16.c message.cc misc.cc msg_accepter.cc msg_handler.cc msg_queue.cc pagesize.cc prefs.cc realtime.cc realtime_impl.cc scheduler.cc scheduler_sts.cc scheduler_tpb.cc single_threaded_scheduler.cc sptr_magic.cc sync_block.cc sync_decimator.cc sync_interpolator.cc sys_paths.cc tagged_stream_block.cc test.cc top_block.cc top_block_impl.cc tpb_detail.cc tpb_thread_body.cc vmcircbuf.cc vmcircbuf_createfilemapping.cc vmcircbuf_mmap_shm_open.cc vmcircbuf_mmap_tmpfile.cc vmcircbuf_prefs.cc vmcircbuf_sysv_shm.cc ) # PowerPC workaround for posix_memalign # Might not be needed, but we'll keep it for now. if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc|ppc)") list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_SOURCE_DIR}/posix_memalign.cc ) endif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc|ppc)") list(APPEND gnuradio_runtime_libs volk gnuradio-pmt ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES} ) #Add libraries for winsock2.h on Windows CHECK_INCLUDE_FILE_CXX(windows.h HAVE_WINDOWS_H) IF(HAVE_WINDOWS_H) ADD_DEFINITIONS(-DHAVE_WINDOWS_H -DUSING_WINSOCK -DWIN32_LEAN_AND_MEAN) MESSAGE(STATUS "Adding windows libs to gnuradio runtime libs...") LIST(APPEND gnuradio_runtime_libs WS2_32.lib WSock32.lib) ENDIF(HAVE_WINDOWS_H) #need to link with librt on ubuntu 11.10 for shm_* if(LINUX) list(APPEND gnuradio_runtime_libs rt) endif() GR_INCLUDE_SUBDIRECTORY(controlport) ######################################################################## # Add DLL resource file when using MSVC ######################################################################## if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-runtime.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-runtime.rc @ONLY) list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-runtime.rc ) endif(MSVC) ######################################################################## # Control availability of vmcircbuf methods. # For now, only allows disabling of shm methods, which cause uncatchable # segmentation faults on Cygwin with gcc 4.x (x <= 5) # Usage: # GR_VMCIRCBUF() # # Will set TRY_SHM_VMCIRCBUF to 1 by default except on Windows machines. # Can manually set with -DTRY_SHM_VMCIRCBUF=0|1 ######################################################################## if(WIN32) OPTION(TRY_SHM_VMCIRCBUF "Try SHM VMCIRCBUF" OFF) else(WIN32) OPTION(TRY_SHM_VMCIRCBUF "Try SHM VMCIRCBUF" ON) endif(WIN32) message(STATUS "TRY_SHM_VMCIRCBUF set to ${TRY_SHM_VMCIRCBUF}.") if(TRY_SHM_VMCIRCBUF) add_definitions( -DTRY_SHM_VMCIRCBUF ) endif(TRY_SHM_VMCIRCBUF) add_library(gnuradio-runtime SHARED ${gnuradio_runtime_sources}) target_link_libraries(gnuradio-runtime ${gnuradio_runtime_libs}) GR_LIBRARY_FOO(gnuradio-runtime RUNTIME_COMPONENT "runtime_runtime" DEVEL_COMPONENT "runtime_devel") add_dependencies(gnuradio-runtime pmt_generated runtime_generated_includes ) ######################################################################## # Setup tests ######################################################################## if(ENABLE_TESTING) include(GrTest) ######################################################################## # Append gnuradio-runtime test sources ######################################################################## list(APPEND test_gnuradio_runtime_sources math/qa_fxpt.cc math/qa_fxpt_nco.cc math/qa_fxpt_vco.cc math/qa_math.cc math/qa_sincos.cc math/qa_fast_atan2f.cc qa_buffer.cc qa_io_signature.cc qa_circular_file.cc qa_logger.cc qa_vmcircbuf.cc qa_runtime.cc ) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/math) include_directories(${CPPUNIT_INCLUDE_DIRS}) link_directories(${CPPUNIT_LIBRARY_DIRS}) add_library(test-gnuradio-runtime SHARED ${test_gnuradio_runtime_sources}) target_link_libraries(test-gnuradio-runtime gnuradio-runtime gnuradio-pmt ${CPPUNIT_LIBRARIES} ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES}) ######################################################################## # Build the test executable # Set the test environment so the build libs will be found under MSVC. ######################################################################## list(APPEND GR_TEST_TARGET_DEPS test-gnuradio-runtime) add_executable(gr_runtime_test test_runtime.cc) target_link_libraries(gr_runtime_test test-gnuradio-runtime) GR_ADD_TEST(gr-runtime-test gr_runtime_test) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gnuradio-runtime/lib/test_types.h0000664000175000017500000000273512207440367021753 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TEST_TYPES_H #define INCLUDED_GR_TEST_TYPES_H namespace gr { typedef enum { CONSUME_NOUTPUT_ITEMS=0, CONSUME_NOUTPUT_ITEMS_LIMIT_MAX=1, CONSUME_NOUTPUT_ITEMS_LIMIT_MIN=2, CONSUME_ALL_AVAILABLE=3, CONSUME_ALL_AVAILABLE_LIMIT_MAX=4, /*CONSUME_ALL_AVAILABLE_LIMIT_MIN=5,*/ CONSUME_ZERO=6, CONSUME_ONE=7, CONSUME_MINUS_ONE=8 } consume_type_t; typedef enum { PRODUCE_NOUTPUT_ITEMS=0, PRODUCE_NOUTPUT_ITEMS_LIMIT_MAX=1, /*PRODUCE_NOUTPUT_ITEMS_LIMIT_MIN=2,*/ PRODUCE_ZERO=6, PRODUCE_ONE=7, PRODUCE_MINUS_ONE=8 } produce_type_t; } /* namespace gr */ #endif /* INCLUDED_GR_TEST_TYPES_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_mmap_tmpfile.h0000664000175000017500000000372512207440367024262 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_VMCIRCBUF_MMAP_TMPFILE_H #define GR_VMCIRCBUF_MMAP_TMPFILE_H #include #include "vmcircbuf.h" namespace gr { /*! * \brief concrete class to implement circular buffers with mmap and shm_open * \ingroup internal */ class GR_RUNTIME_API vmcircbuf_mmap_tmpfile : public gr::vmcircbuf { public: vmcircbuf_mmap_tmpfile(int size); virtual ~vmcircbuf_mmap_tmpfile(); }; /*! * \brief concrete factory for circular buffers built using mmap and shm_open */ class GR_RUNTIME_API vmcircbuf_mmap_tmpfile_factory : public gr::vmcircbuf_factory { private: static gr::vmcircbuf_factory *s_the_factory; public: static gr::vmcircbuf_factory *singleton(); virtual const char *name() const { return "gr::vmcircbuf_mmap_tmpfile_factory"; } /*! * \brief return granularity of mapping, typically equal to page size */ virtual int granularity(); /*! * \brief return a gr::vmcircbuf, or 0 if unable. * * Call this to create a doubly mapped circular buffer. */ virtual gr::vmcircbuf *make(int size); }; } /* namespace gr */ #endif /* GR_VMCIRCBUF_MMAP_TMPFILE_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block_executor.h0000664000175000017500000000466012207440367022557 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_BLOCK_EXECUTOR_H #define INCLUDED_GR_RUNTIME_BLOCK_EXECUTOR_H #include #include #include #include namespace gr { /*! * \brief Manage the execution of a single block. * \ingroup internal */ class GR_RUNTIME_API block_executor { protected: block_sptr d_block; // The block we're trying to run std::ofstream *d_log; // These are allocated here so we don't have to on each iteration gr_vector_int d_ninput_items_required; gr_vector_int d_ninput_items; gr_vector_const_void_star d_input_items; std::vector d_input_done; gr_vector_void_star d_output_items; std::vector d_start_nitems_read; //stores where tag counts are before work std::vector d_returned_tags; int d_max_noutput_items; #ifdef GR_PERFORMANCE_COUNTERS bool d_use_pc; #endif /* GR_PERFORMANCE_COUNTERS */ public: block_executor(block_sptr block, int max_noutput_items=100000); ~block_executor(); enum state { READY, // We made progress; everything's cool. READY_NO_OUTPUT, // We consumed some input, but produced no output. BLKD_IN, // no progress; we're blocked waiting for input data. BLKD_OUT, // no progress; we're blocked waiting for output buffer space. DONE, // we're done; don't call me again. }; /* * \brief Run one iteration. */ state run_one_iteration(); }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_BLOCK_EXECUTOR_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/message.cc0000664000175000017500000000414512207440367021327 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { static long s_ncurrently_allocated = 0; message::sptr message::make(long type, double arg1, double arg2, size_t length) { return message::sptr(new message(type, arg1, arg2, length)); } message::sptr message::make_from_string(const std::string s, long type, double arg1, double arg2) { message::sptr m = message::make(type, arg1, arg2, s.size()); memcpy(m->msg(), s.data(), s.size()); return m; } message::message(long type, double arg1, double arg2, size_t length) : d_type(type), d_arg1(arg1), d_arg2(arg2) { if(length == 0) d_buf_start = d_msg_start = d_msg_end = d_buf_end = 0; else { d_buf_start = new unsigned char[length]; d_msg_start = d_buf_start; d_msg_end = d_buf_end = d_buf_start + length; } s_ncurrently_allocated++; } message::~message() { assert (d_next == 0); delete [] d_buf_start; d_msg_start = d_msg_end = d_buf_end = 0; s_ncurrently_allocated--; } std::string message::to_string() const { return std::string((char *)d_msg_start, length()); } long message_ncurrently_allocated() { return s_ncurrently_allocated; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/thread/0000775000175000017500000000000012207440367020637 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/lib/thread/CMakeLists.txt0000664000175000017500000000221112207440367023373 0ustar jcorganjcorgan# Copyright 2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # This file included, use CMake directory variables ######################################################################## list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_SOURCE_DIR}/thread.cc ${CMAKE_CURRENT_SOURCE_DIR}/thread_body_wrapper.cc ${CMAKE_CURRENT_SOURCE_DIR}/thread_group.cc ) gnuradio-3.7.2.1/gnuradio-runtime/lib/thread/thread_body_wrapper.cc0000664000175000017500000000411212207440367025170 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #ifdef HAVE_SIGNAL_H #include #endif #include namespace gr { namespace thread { #if defined(HAVE_PTHREAD_SIGMASK) && defined(HAVE_SIGNAL_H) void mask_signals() { sigset_t new_set; int r; sigemptyset(&new_set); sigaddset(&new_set, SIGHUP); // block these... sigaddset(&new_set, SIGINT); sigaddset(&new_set, SIGPIPE); sigaddset(&new_set, SIGALRM); sigaddset(&new_set, SIGTERM); sigaddset(&new_set, SIGUSR1); sigaddset(&new_set, SIGCHLD); #ifdef SIGPOLL sigaddset(&new_set, SIGPOLL); #endif #ifdef SIGPROF sigaddset(&new_set, SIGPROF); #endif #ifdef SIGSYS sigaddset(&new_set, SIGSYS); #endif #ifdef SIGTRAP sigaddset(&new_set, SIGTRAP); #endif #ifdef SIGURG sigaddset(&new_set, SIGURG); #endif #ifdef SIGVTALRM sigaddset(&new_set, SIGVTALRM); #endif #ifdef SIGXCPU sigaddset(&new_set, SIGXCPU); #endif #ifdef SIGXFSZ sigaddset(&new_set, SIGXFSZ); #endif r = pthread_sigmask(SIG_BLOCK, &new_set, 0); if(r != 0) perror("pthread_sigmask"); } #else void mask_signals() { } #endif } /* namespace thread */ } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/thread/thread.cc0000664000175000017500000001452612207440367022425 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #include namespace gr { namespace thread { gr_thread_t get_current_thread_id() { return GetCurrentThread(); } void thread_bind_to_processor(int n) { std::vector mask(1, n); thread_bind_to_processor(get_current_thread_id(), mask); } void thread_bind_to_processor(const std::vector &mask) { thread_bind_to_processor(get_current_thread_id(), mask); } void thread_bind_to_processor(gr_thread_t thread, int n) { std::vector mask(1, n); thread_bind_to_processor(thread, mask); } void thread_bind_to_processor(gr_thread_t thread, const std::vector &mask) { //DWORD_PTR mask = (1 << n); DWORD_PTR dword_mask = 0; std::vector _mask = mask; std::vector::iterator itr; for(itr = _mask.begin(); itr != _mask.end(); itr++) dword_mask |= (1 << (*itr)); DWORD_PTR ret = SetThreadAffinityMask(thread, dword_mask); if(ret == 0) { std::stringstream s; s << "thread_bind_to_processor failed with error: " << GetLastError() << std::endl; throw std::runtime_error(s.str()); } } void thread_unbind() { thread_unbind(get_current_thread_id()); } void thread_unbind(gr_thread_t thread) { DWORD_PTR dword_mask = sizeof(DWORD_PTR) - 1; DWORD_PTR ret = SetThreadAffinityMask(thread, dword_mask); if(ret == 0) { std::stringstream s; s << "thread_unbind failed with error: " << GetLastError() << std::endl; throw std::runtime_error(s.str()); } } int thread_priority(gr_thread_t thread) { // Not implemented on Windows return -1; } int set_thread_priority(gr_thread_t thread, int priority) { // Not implemented on Windows return -1; } } /* namespace thread */ } /* namespace gr */ #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) namespace gr { namespace thread { gr_thread_t get_current_thread_id() { // Not implemented on OSX } void thread_bind_to_processor(int n) { // Not implemented on OSX } void thread_bind_to_processor(gr_thread_t thread, int n) { // Not implemented on OSX } void thread_bind_to_processor(const std::vector &mask) { // Not implemented on OSX } void thread_bind_to_processor(gr_thread_t thread, const std::vector &mask) { // Not implemented on OSX } void thread_unbind() { // Not implemented on OSX } void thread_unbind(gr_thread_t thread) { // Not implemented on OSX } int thread_priority(gr_thread_t thread) { // Not implemented on OSX return -1; } int set_thread_priority(gr_thread_t thread, int priority) { // Not implemented on OSX return -1; } } /* namespace thread */ } /* namespace gr */ #else #include #include #include namespace gr { namespace thread { gr_thread_t get_current_thread_id() { return pthread_self(); } void thread_bind_to_processor(int n) { std::vector mask(1, n); thread_bind_to_processor(get_current_thread_id(), mask); } void thread_bind_to_processor(const std::vector &mask) { thread_bind_to_processor(get_current_thread_id(), mask); } void thread_bind_to_processor(gr_thread_t thread, int n) { std::vector mask(1, n); thread_bind_to_processor(thread, mask); } void thread_bind_to_processor(gr_thread_t thread, const std::vector &mask) { cpu_set_t set; size_t len = sizeof(cpu_set_t); std::vector _mask = mask; std::vector::iterator itr; CPU_ZERO(&set); for(itr = _mask.begin(); itr != _mask.end(); itr++) CPU_SET(*itr, &set); int ret = pthread_setaffinity_np(thread, len, &set); if(ret != 0) { std::stringstream s; s << "thread_bind_to_processor failed with error: " << ret << std::endl; throw std::runtime_error(s.str()); } } void thread_unbind() { thread_unbind(get_current_thread_id()); } void thread_unbind(gr_thread_t thread) { cpu_set_t set; size_t len = sizeof(cpu_set_t); CPU_ZERO(&set); long ncpus = sysconf(_SC_NPROCESSORS_ONLN); for(long n = 0; n < ncpus; n++) { CPU_SET(n, &set); } int ret = pthread_setaffinity_np(thread, len, &set); if(ret != 0) { std::stringstream s; s << "thread_unbind failed with error: " << ret << std::endl; throw std::runtime_error(s.str()); } } int thread_priority(gr_thread_t thread) { sched_param param; int priority; int policy; int ret; ret = pthread_getschedparam (thread, &policy, ¶m); priority = param.sched_priority; return (ret==0)?priority:ret; } int set_thread_priority(gr_thread_t thread, int priority) { int policy; struct sched_param param; pthread_getschedparam (thread, &policy, ¶m); param.sched_priority = priority; return pthread_setschedparam(thread, policy, ¶m); } } /* namespace thread */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gnuradio-runtime/lib/thread/thread_group.cc0000664000175000017500000000610712207440367023635 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright (C) 2001-2003 William E. Kempf * Copyright (C) 2007 Anthony Williams * Copyright 2008 Free Software Foundation, Inc. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /* * This was extracted from Boost 1.35.0 and fixed. */ #include namespace gr { namespace thread { thread_group::thread_group() { } thread_group::~thread_group() { // We shouldn't have to scoped_lock here, since referencing this // object from another thread while we're deleting it in the // current thread is going to lead to undefined behavior any // way. for(std::list::iterator it = m_threads.begin(); it != m_threads.end(); ++it) { delete (*it); } } boost::thread* thread_group::create_thread(const boost::function0& threadfunc) { // No scoped_lock required here since the only "shared data" that's // modified here occurs inside add_thread which does scoped_lock. std::auto_ptr thrd(new boost::thread(threadfunc)); add_thread(thrd.get()); return thrd.release(); } void thread_group::add_thread(boost::thread* thrd) { boost::lock_guard guard(m_mutex); // For now we'll simply ignore requests to add a thread object // multiple times. Should we consider this an error and either // throw or return an error value? std::list::iterator it = std::find(m_threads.begin(), m_threads.end(), thrd); BOOST_ASSERT(it == m_threads.end()); if(it == m_threads.end()) m_threads.push_back(thrd); } void thread_group::remove_thread(boost::thread* thrd) { boost::lock_guard guard(m_mutex); // For now we'll simply ignore requests to remove a thread // object that's not in the group. Should we consider this an // error and either throw or return an error value? std::list::iterator it = std::find(m_threads.begin(), m_threads.end(), thrd); BOOST_ASSERT(it != m_threads.end()); if(it != m_threads.end()) m_threads.erase(it); } void thread_group::join_all() { boost::shared_lock guard(m_mutex); for(std::list::iterator it = m_threads.begin(); it != m_threads.end(); ++it) { (*it)->join(); } } void thread_group::interrupt_all() { boost::shared_lock guard(m_mutex); for(std::list::iterator it=m_threads.begin(),end=m_threads.end(); it!=end; ++it) { (*it)->interrupt(); } } size_t thread_group::size() const { boost::shared_lock guard(m_mutex); return m_threads.size(); } } /* namespace thread */ } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pagesize.cc0000664000175000017500000000277412207440367021520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pagesize.h" #include #include namespace gr { #if defined(_WIN32) && defined(HAVE_GETPAGESIZE) extern "C" size_t getpagesize(void); #endif int pagesize() { static int s_pagesize = -1; if(s_pagesize == -1) { #if defined(HAVE_GETPAGESIZE) s_pagesize = getpagesize(); #elif defined (HAVE_SYSCONF) s_pagesize = sysconf(_SC_PAGESIZE); if(s_pagesize == -1) { perror("_SC_PAGESIZE"); s_pagesize = 4096; } #else fprintf(stderr, "gr::pagesize: no info; setting pagesize = 4096\n"); s_pagesize = 4096; #endif } return s_pagesize; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_prefs.h0000664000175000017500000000215612207440367022724 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_PREFERENCES_H #define GR_PREFERENCES_H #include namespace gr { class GR_RUNTIME_API vmcircbuf_prefs { public: static const char *get(const char *key); static void set(const char *key, const char *value); }; } /* namespace gr */ #endif /* GR_PREFERENCES_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/sptr_magic.cc0000664000175000017500000000423112207440367022027 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include namespace gnuradio { static gr::thread::mutex s_mutex; typedef std::map sptr_map; static sptr_map s_map; void detail::sptr_magic::create_and_stash_initial_sptr(gr::hier_block2 *p) { gr::basic_block_sptr sptr(p); gr::thread::scoped_lock guard(s_mutex); s_map.insert(sptr_map::value_type(static_cast(p), sptr)); } gr::basic_block_sptr detail::sptr_magic::fetch_initial_sptr(gr::basic_block *p) { /* * If p isn't a subclass of gr::hier_block2, just create the * shared ptr and return it. */ gr::hier_block2 *hb2 = dynamic_cast(p); if(!hb2) { return gr::basic_block_sptr(p); } /* * p is a subclass of gr::hier_block2, thus we've already created the shared pointer * and stashed it away. Fish it out and return it. */ gr::thread::scoped_lock guard(s_mutex); sptr_map::iterator pos = s_map.find(static_cast(p)); if(pos == s_map.end()) throw std::invalid_argument("sptr_magic: invalid pointer!"); gr::basic_block_sptr sptr = pos->second; s_map.erase(pos); return sptr; } }; gnuradio-3.7.2.1/gnuradio-runtime/lib/constants.cc.in0000664000175000017500000000241012207440367022315 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #if HAVE_CONFIG_H #include #endif #include namespace gr { const std::string prefix() { return "@prefix@"; } const std::string sysconfdir() { return "@SYSCONFDIR@"; } const std::string prefsdir() { return "@GR_PREFSDIR@"; } const std::string build_date() { return "@BUILD_DATE@"; } const std::string version() { return "@VERSION@"; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/tpb_thread_body.h0000664000175000017500000000275512207440367022703 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_TPB_THREAD_BODY_H #define INCLUDED_GR_TPB_THREAD_BODY_H #include #include #include #include "block_executor.h" namespace gr { /*! * \brief The body of each thread-per-block thread. * * One of these is instantiated in its own thread for each block. * The constructor turns into the main loop which returns when the * block is done or is interrupted. */ class GR_RUNTIME_API tpb_thread_body { block_executor d_exec; public: tpb_thread_body(block_sptr block, int max_noutput_items=100000); ~tpb_thread_body(); }; } /* namespace gr */ #endif /* INCLUDED_GR_TPB_THREAD_BODY_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/scheduler_sts.h0000664000175000017500000000351112207440367022410 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_SCHEDULER_STS_H #define INCLUDED_GR_SCHEDULER_STS_H #include #include #include "scheduler.h" namespace gr { /*! * \brief Concrete scheduler that uses the single_threaded_scheduler */ class GR_RUNTIME_API scheduler_sts : public scheduler { gr::thread::thread_group d_threads; protected: /*! * \brief Construct a scheduler and begin evaluating the graph. * * The scheduler will continue running until all blocks until they * report that they are done or the stop method is called. */ scheduler_sts(flat_flowgraph_sptr ffg, int max_noutput_items); public: static scheduler_sptr make(flat_flowgraph_sptr ffg, int max_noutput_items); ~scheduler_sts(); /*! * \brief Tell the scheduler to stop executing. */ void stop(); /*! * \brief Block until the graph is done. */ void wait(); }; } /* namespace gr */ #endif /* INCLUDED_GR_SCHEDULER_STS_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block_detail.cc0000664000175000017500000003122012237515111022302 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { static long s_ncurrently_allocated = 0; long block_detail_ncurrently_allocated() { return s_ncurrently_allocated; } block_detail::block_detail(unsigned int ninputs, unsigned int noutputs) : d_produce_or(0), d_ninputs(ninputs), d_noutputs(noutputs), d_input(ninputs), d_output(noutputs), d_done(false), d_ins_noutput_items(0), d_avg_noutput_items(0), d_var_noutput_items(0), d_ins_nproduced(0), d_avg_nproduced(0), d_var_nproduced(0), d_ins_input_buffers_full(ninputs, 0), d_avg_input_buffers_full(ninputs, 0), d_var_input_buffers_full(ninputs, 0), d_ins_output_buffers_full(noutputs, 0), d_avg_output_buffers_full(noutputs, 0), d_var_output_buffers_full(noutputs, 0), d_ins_work_time(0), d_avg_work_time(0), d_var_work_time(0), d_pc_counter(0) { s_ncurrently_allocated++; } block_detail::~block_detail() { // should take care of itself s_ncurrently_allocated--; } void block_detail::set_input(unsigned int which, buffer_reader_sptr reader) { if(which >= d_ninputs) throw std::invalid_argument("block_detail::set_input"); d_input[which] = reader; } void block_detail::set_output(unsigned int which, buffer_sptr buffer) { if(which >= d_noutputs) throw std::invalid_argument("block_detail::set_output"); d_output[which] = buffer; } block_detail_sptr make_block_detail(unsigned int ninputs, unsigned int noutputs) { return block_detail_sptr (new block_detail(ninputs, noutputs)); } void block_detail::set_done(bool done) { d_done = done; for(unsigned int i = 0; i < d_noutputs; i++) d_output[i]->set_done(done); for(unsigned int i = 0; i < d_ninputs; i++) d_input[i]->set_done(done); } void block_detail::consume(int which_input, int how_many_items) { if(how_many_items > 0) { input(which_input)->update_read_pointer(how_many_items); } } void block_detail::consume_each(int how_many_items) { if(how_many_items > 0) { for(int i = 0; i < ninputs (); i++) { d_input[i]->update_read_pointer(how_many_items); } } } void block_detail::produce(int which_output, int how_many_items) { if(how_many_items > 0) { d_output[which_output]->update_write_pointer(how_many_items); d_produce_or |= how_many_items; } } void block_detail::produce_each(int how_many_items) { if(how_many_items > 0) { for(int i = 0; i < noutputs (); i++) { d_output[i]->update_write_pointer (how_many_items); } d_produce_or |= how_many_items; } } uint64_t block_detail::nitems_read(unsigned int which_input) { if(which_input >= d_ninputs) throw std::invalid_argument ("block_detail::n_input_items"); return d_input[which_input]->nitems_read(); } uint64_t block_detail::nitems_written(unsigned int which_output) { if(which_output >= d_noutputs) throw std::invalid_argument ("block_detail::n_output_items"); return d_output[which_output]->nitems_written(); } void block_detail::add_item_tag(unsigned int which_output, const tag_t &tag) { if(!pmt::is_symbol(tag.key)) { throw pmt::wrong_type("block_detail::add_item_tag key", tag.key); } else { // Add tag to gr_buffer's deque tags d_output[which_output]->add_item_tag(tag); } } void block_detail::remove_item_tag(unsigned int which_input, const tag_t &tag, long id) { if(!pmt::is_symbol(tag.key)) { throw pmt::wrong_type("block_detail::add_item_tag key", tag.key); } else { // Add tag to gr_buffer's deque tags d_input[which_input]->buffer()->remove_item_tag(tag, id); } } void block_detail::get_tags_in_range(std::vector &v, unsigned int which_input, uint64_t abs_start, uint64_t abs_end, long id) { // get from gr_buffer_reader's deque of tags d_input[which_input]->get_tags_in_range(v, abs_start, abs_end, id); } void block_detail::get_tags_in_range(std::vector &v, unsigned int which_input, uint64_t abs_start, uint64_t abs_end, const pmt::pmt_t &key, long id) { std::vector found_items; v.resize(0); // get from gr_buffer_reader's deque of tags d_input[which_input]->get_tags_in_range(found_items, abs_start, abs_end, id); // Filter further by key name pmt::pmt_t itemkey; std::vector::iterator itr; for(itr = found_items.begin(); itr != found_items.end(); itr++) { itemkey = (*itr).key; if(pmt::eqv(key, itemkey)) { v.push_back(*itr); } } } void block_detail::set_processor_affinity(const std::vector &mask) { if(threaded) { try { gr::thread::thread_bind_to_processor(thread, mask); } catch (std::runtime_error e) { std::cerr << "set_processor_affinity: invalid mask." << std::endl;; } } } void block_detail::unset_processor_affinity() { if(threaded) { gr::thread::thread_unbind(thread); } } int block_detail::thread_priority(){ if(threaded) { return gr::thread::thread_priority(thread); } return -1; } int block_detail::set_thread_priority(int priority){ if(threaded) { return gr::thread::set_thread_priority(thread,priority); } return -1; } void block_detail::start_perf_counters() { d_start_of_work = gr::high_res_timer_now_perfmon(); } void block_detail::stop_perf_counters(int noutput_items, int nproduced) { d_end_of_work = gr::high_res_timer_now_perfmon(); gr::high_res_timer_type diff = d_end_of_work - d_start_of_work; if(d_pc_counter == 0) { d_ins_work_time = diff; d_avg_work_time = diff; d_var_work_time = 0; d_total_work_time = diff; d_ins_nproduced = nproduced; d_avg_nproduced = nproduced; d_var_nproduced = 0; d_ins_noutput_items = noutput_items; d_avg_noutput_items = noutput_items; d_var_noutput_items = 0; for(size_t i=0; i < d_input.size(); i++) { gr::thread::scoped_lock guard(*d_input[i]->mutex()); float pfull = static_cast(d_input[i]->items_available()) / static_cast(d_input[i]->max_possible_items_available()); d_ins_input_buffers_full[i] = pfull; d_avg_input_buffers_full[i] = pfull; d_var_input_buffers_full[i] = 0; } for(size_t i=0; i < d_output.size(); i++) { gr::thread::scoped_lock guard(*d_output[i]->mutex()); float pfull = 1.0f - static_cast(d_output[i]->space_available()) / static_cast(d_output[i]->bufsize()); d_ins_output_buffers_full[i] = pfull; d_avg_output_buffers_full[i] = pfull; d_var_output_buffers_full[i] = 0; } } else { float d = diff - d_avg_work_time; d_ins_work_time = diff; d_avg_work_time = d_avg_work_time + d/d_pc_counter; d_var_work_time = d_var_work_time + d*d; d_total_work_time += diff; d = nproduced - d_avg_nproduced; d_ins_nproduced = nproduced; d_avg_nproduced = d_avg_nproduced + d/d_pc_counter; d_var_nproduced = d_var_nproduced + d*d; d = noutput_items - d_avg_noutput_items; d_ins_noutput_items = noutput_items; d_avg_noutput_items = d_avg_noutput_items + d/d_pc_counter; d_var_noutput_items = d_var_noutput_items + d*d; for(size_t i=0; i < d_input.size(); i++) { gr::thread::scoped_lock guard(*d_input[i]->mutex()); float pfull = static_cast(d_input[i]->items_available()) / static_cast(d_input[i]->max_possible_items_available()); d = pfull - d_avg_input_buffers_full[i]; d_ins_input_buffers_full[i] = pfull; d_avg_input_buffers_full[i] = d_avg_input_buffers_full[i] + d/d_pc_counter; d_var_input_buffers_full[i] = d_var_input_buffers_full[i] + d*d; } for(size_t i=0; i < d_output.size(); i++) { gr::thread::scoped_lock guard(*d_output[i]->mutex()); float pfull = 1.0f - static_cast(d_output[i]->space_available()) / static_cast(d_output[i]->bufsize()); d = pfull - d_avg_output_buffers_full[i]; d_ins_output_buffers_full[i] = pfull; d_avg_output_buffers_full[i] = d_avg_output_buffers_full[i] + d/d_pc_counter; d_var_output_buffers_full[i] = d_var_output_buffers_full[i] + d*d; } } d_pc_counter++; } void block_detail::reset_perf_counters() { d_pc_counter = 0; } float block_detail::pc_noutput_items() { return d_ins_noutput_items; } float block_detail::pc_nproduced() { return d_ins_nproduced; } float block_detail::pc_input_buffers_full(size_t which) { if(which < d_ins_input_buffers_full.size()) return d_ins_input_buffers_full[which]; else return 0; } std::vector block_detail::pc_input_buffers_full() { return d_ins_input_buffers_full; } float block_detail::pc_output_buffers_full(size_t which) { if(which < d_ins_output_buffers_full.size()) return d_ins_output_buffers_full[which]; else return 0; } std::vector block_detail::pc_output_buffers_full() { return d_ins_output_buffers_full; } float block_detail::pc_work_time() { return d_ins_work_time; } float block_detail::pc_noutput_items_avg() { return d_avg_noutput_items; } float block_detail::pc_nproduced_avg() { return d_avg_nproduced; } float block_detail::pc_input_buffers_full_avg(size_t which) { if(which < d_avg_input_buffers_full.size()) return d_avg_input_buffers_full[which]; else return 0; } std::vector block_detail::pc_input_buffers_full_avg() { return d_avg_input_buffers_full; } float block_detail::pc_output_buffers_full_avg(size_t which) { if(which < d_avg_output_buffers_full.size()) return d_avg_output_buffers_full[which]; else return 0; } std::vector block_detail::pc_output_buffers_full_avg() { return d_avg_output_buffers_full; } float block_detail::pc_work_time_avg() { return d_avg_work_time; } float block_detail::pc_noutput_items_var() { return d_var_noutput_items/(d_pc_counter-1); } float block_detail::pc_nproduced_var() { return d_var_nproduced/(d_pc_counter-1); } float block_detail::pc_input_buffers_full_var(size_t which) { if(which < d_avg_input_buffers_full.size()) return d_var_input_buffers_full[which]/(d_pc_counter-1); else return 0; } std::vector block_detail::pc_input_buffers_full_var() { std::vector var(d_avg_input_buffers_full.size(), 0); for(size_t i = 0; i < d_avg_input_buffers_full.size(); i++) var[i] = d_avg_input_buffers_full[i]/(d_pc_counter-1); return var; } float block_detail::pc_output_buffers_full_var(size_t which) { if(which < d_avg_output_buffers_full.size()) return d_var_output_buffers_full[which]/(d_pc_counter-1); else return 0; } std::vector block_detail::pc_output_buffers_full_var() { std::vector var(d_avg_output_buffers_full.size(), 0); for(size_t i = 0; i < d_avg_output_buffers_full.size(); i++) var[i] = d_avg_output_buffers_full[i]/(d_pc_counter-1); return var; } float block_detail::pc_work_time_var() { return d_var_work_time/(d_pc_counter-1); } float block_detail::pc_work_time_total() { return d_total_work_time; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/flowgraph.cc0000664000175000017500000003404712226271766021706 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include namespace gr { #define FLOWGRAPH_DEBUG 0 edge::~edge() { } flowgraph_sptr make_flowgraph() { return flowgraph_sptr(new flowgraph()); } flowgraph::flowgraph() { } flowgraph::~flowgraph() { } template static std::vector unique_vector(std::vector v) { std::vector result; std::insert_iterator > inserter(result, result.begin()); sort(v.begin(), v.end()); unique_copy(v.begin(), v.end(), inserter); return result; } void flowgraph::connect(const endpoint &src, const endpoint &dst) { check_valid_port(src.block()->output_signature(), src.port()); check_valid_port(dst.block()->input_signature(), dst.port()); check_dst_not_used(dst); check_type_match(src, dst); // All ist klar, Herr Kommisar d_edges.push_back(edge(src,dst)); } void flowgraph::disconnect(const endpoint &src, const endpoint &dst) { for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(src == p->src() && dst == p->dst()) { d_edges.erase(p); return; } } std::stringstream msg; msg << "cannot disconnect edge " << edge(src, dst) << ", not found"; throw std::invalid_argument(msg.str()); } void flowgraph::validate() { d_blocks = calc_used_blocks(); for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) { std::vector used_ports; int ninputs, noutputs; if(FLOWGRAPH_DEBUG) std::cout << "Validating block: " << (*p) << std::endl; used_ports = calc_used_ports(*p, true); // inputs ninputs = used_ports.size(); check_contiguity(*p, used_ports, true); // inputs used_ports = calc_used_ports(*p, false); // outputs noutputs = used_ports.size(); check_contiguity(*p, used_ports, false); // outputs if(!((*p)->check_topology(ninputs, noutputs))) { std::stringstream msg; msg << "check topology failed on " << (*p) << " using ninputs=" << ninputs << ", noutputs=" << noutputs; throw std::runtime_error(msg.str()); } } } void flowgraph::clear() { // Boost shared pointers will deallocate as needed d_blocks.clear(); d_edges.clear(); } void flowgraph::check_valid_port(gr::io_signature::sptr sig, int port) { std::stringstream msg; if(port < 0) { msg << "negative port number " << port << " is invalid"; throw std::invalid_argument(msg.str()); } int max = sig->max_streams(); if(max != io_signature::IO_INFINITE && port >= max) { msg << "port number " << port << " exceeds max of "; if(max == 0) msg << "(none)"; else msg << max-1; throw std::invalid_argument(msg.str()); } } void flowgraph::check_valid_port(const msg_endpoint &e) { if(FLOWGRAPH_DEBUG) std::cout << "check_valid_port( " << e.block() << ", " << e.port() << ")\n"; if(!e.block()->has_msg_port(e.port())) throw std::invalid_argument("invalid msg port in connect() or disconnect()"); } void flowgraph::check_dst_not_used(const endpoint &dst) { // A destination is in use if it is already on the edge list for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->dst() == dst) { std::stringstream msg; msg << "destination already in use by edge " << (*p); throw std::invalid_argument(msg.str()); } } void flowgraph::check_type_match(const endpoint &src, const endpoint &dst) { int src_size = src.block()->output_signature()->sizeof_stream_item(src.port()); int dst_size = dst.block()->input_signature()->sizeof_stream_item(dst.port()); if(src_size != dst_size) { std::stringstream msg; msg << "itemsize mismatch: " << src << " using " << src_size << ", " << dst << " using " << dst_size; throw std::invalid_argument(msg.str()); } } basic_block_vector_t flowgraph::calc_used_blocks() { basic_block_vector_t tmp; // make sure free standing message blocks are included for(msg_edge_viter_t p = d_msg_edges.begin(); p != d_msg_edges.end(); p++) { // all msg blocks need a thread context - otherwise start() will never be called! // even if it is a sender that never does anything tmp.push_back(p->src().block()); tmp.push_back(p->dst().block()); } // Collect all blocks in the edge list for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { tmp.push_back(p->src().block()); tmp.push_back(p->dst().block()); } return unique_vector(tmp); } std::vector flowgraph::calc_used_ports(basic_block_sptr block, bool check_inputs) { std::vector tmp; // Collect all seen ports edge_vector_t edges = calc_connections(block, check_inputs); for(edge_viter_t p = edges.begin(); p != edges.end(); p++) { if(check_inputs == true) tmp.push_back(p->dst().port()); else tmp.push_back(p->src().port()); } return unique_vector(tmp); } edge_vector_t flowgraph::calc_connections(basic_block_sptr block, bool check_inputs) { edge_vector_t result; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(check_inputs) { if(p->dst().block() == block) result.push_back(*p); } else { if(p->src().block() == block) result.push_back(*p); } } return result; // assumes no duplicates } void flowgraph::check_contiguity(basic_block_sptr block, const std::vector &used_ports, bool check_inputs) { std::stringstream msg; gr::io_signature::sptr sig = check_inputs ? block->input_signature() : block->output_signature(); int nports = used_ports.size(); int min_ports = sig->min_streams(); int max_ports = sig->max_streams(); if(nports == 0 && min_ports == 0) return; if(nports < min_ports) { msg << block << ": insufficient connected " << (check_inputs ? "input ports " : "output ports ") << "(" << min_ports << " needed, " << nports << " connected)"; throw std::runtime_error(msg.str()); } if(nports > max_ports && max_ports != io_signature::IO_INFINITE) { msg << block << ": too many connected " << (check_inputs ? "input ports " : "output ports ") << "(" << max_ports << " allowed, " << nports << " connected)"; throw std::runtime_error(msg.str()); } if(used_ports[nports-1]+1 != nports) { for(int i = 0; i < nports; i++) { if(used_ports[i] != i) { msg << block << ": missing connection " << (check_inputs ? "to input port " : "from output port ") << i; throw std::runtime_error(msg.str()); } } } } basic_block_vector_t flowgraph::calc_downstream_blocks(basic_block_sptr block, int port) { basic_block_vector_t tmp; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->src() == endpoint(block, port)) tmp.push_back(p->dst().block()); return unique_vector(tmp); } basic_block_vector_t flowgraph::calc_downstream_blocks(basic_block_sptr block) { basic_block_vector_t tmp; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->src().block() == block) tmp.push_back(p->dst().block()); return unique_vector(tmp); } edge_vector_t flowgraph::calc_upstream_edges(basic_block_sptr block) { edge_vector_t result; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) if(p->dst().block() == block) result.push_back(*p); return result; // Assume no duplicates } bool flowgraph::has_block_p(basic_block_sptr block) { basic_block_viter_t result; result = std::find(d_blocks.begin(), d_blocks.end(), block); return (result != d_blocks.end()); } edge flowgraph::calc_upstream_edge(basic_block_sptr block, int port) { edge result; for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(p->dst() == endpoint(block, port)) { result = (*p); break; } } return result; } std::vector flowgraph::partition() { std::vector result; basic_block_vector_t blocks = calc_used_blocks(); basic_block_vector_t graph; while(blocks.size() > 0) { graph = calc_reachable_blocks(blocks[0], blocks); assert(graph.size()); result.push_back(topological_sort(graph)); for(basic_block_viter_t p = graph.begin(); p != graph.end(); p++) blocks.erase(find(blocks.begin(), blocks.end(), *p)); } return result; } basic_block_vector_t flowgraph::calc_reachable_blocks(basic_block_sptr block, basic_block_vector_t &blocks) { basic_block_vector_t result; // Mark all blocks as unvisited for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) (*p)->set_color(basic_block::WHITE); // Recursively mark all reachable blocks reachable_dfs_visit(block, blocks); // Collect all the blocks that have been visited for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) if((*p)->color() == basic_block::BLACK) result.push_back(*p); return result; } // Recursively mark all reachable blocks from given block and block list void flowgraph::reachable_dfs_visit(basic_block_sptr block, basic_block_vector_t &blocks) { // Mark the current one as visited block->set_color(basic_block::BLACK); // Recurse into adjacent vertices basic_block_vector_t adjacent = calc_adjacent_blocks(block, blocks); for(basic_block_viter_t p = adjacent.begin(); p != adjacent.end(); p++) if((*p)->color() == basic_block::WHITE) reachable_dfs_visit(*p, blocks); } // Return a list of block adjacent to a given block along any edge basic_block_vector_t flowgraph::calc_adjacent_blocks(basic_block_sptr block, basic_block_vector_t &blocks) { basic_block_vector_t tmp; // Find any blocks that are inputs or outputs for(edge_viter_t p = d_edges.begin(); p != d_edges.end(); p++) { if(p->src().block() == block) tmp.push_back(p->dst().block()); if(p->dst().block() == block) tmp.push_back(p->src().block()); } return unique_vector(tmp); } basic_block_vector_t flowgraph::topological_sort(basic_block_vector_t &blocks) { basic_block_vector_t tmp; basic_block_vector_t result; tmp = sort_sources_first(blocks); // Start 'em all white for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) (*p)->set_color(basic_block::WHITE); for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) { if((*p)->color() == basic_block::WHITE) topological_dfs_visit(*p, result); } reverse(result.begin(), result.end()); return result; } basic_block_vector_t flowgraph::sort_sources_first(basic_block_vector_t &blocks) { basic_block_vector_t sources, nonsources, result; for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { if(source_p(*p)) sources.push_back(*p); else nonsources.push_back(*p); } for(basic_block_viter_t p = sources.begin(); p != sources.end(); p++) result.push_back(*p); for(basic_block_viter_t p = nonsources.begin(); p != nonsources.end(); p++) result.push_back(*p); return result; } bool flowgraph::source_p(basic_block_sptr block) { return (calc_upstream_edges(block).size() == 0); } void flowgraph::topological_dfs_visit(basic_block_sptr block, basic_block_vector_t &output) { block->set_color(basic_block::GREY); basic_block_vector_t blocks(calc_downstream_blocks(block)); for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { switch((*p)->color()) { case basic_block::WHITE: topological_dfs_visit(*p, output); break; case basic_block::GREY: throw std::runtime_error("flow graph has loops!"); case basic_block::BLACK: continue; default: throw std::runtime_error("invalid color on block!"); } } block->set_color(basic_block::BLACK); output.push_back(block); } void flowgraph::connect(const msg_endpoint &src, const msg_endpoint &dst) { check_valid_port(src); check_valid_port(dst); for(msg_edge_viter_t p = d_msg_edges.begin(); p != d_msg_edges.end(); p++) { if(p->src() == src && p->dst() == dst){ throw std::runtime_error("connect called on already connected edge!"); } } d_msg_edges.push_back(msg_edge(src,dst)); } void flowgraph::disconnect(const msg_endpoint &src, const msg_endpoint &dst) { check_valid_port(src); check_valid_port(dst); for(msg_edge_viter_t p = d_msg_edges.begin(); p != d_msg_edges.end(); p++) { if(p->src() == src && p->dst() == dst){ d_msg_edges.erase(p); return; } } throw std::runtime_error("disconnect called on non-connected edge!"); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/sys_pri.cc0000664000175000017500000000317712207440367021377 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include namespace gr { /* * These may need per-OS tweaking. * * Under linux virtual_pri -> system_pri * 0 -> 0 * 1 -> 5 * 2 -> 10 * 3 -> 15 * 4 -> 20 // typically used by jack and pulse audio * 5 -> 25 * 6 -> 30 * 7 -> 35 * 8 -> 40 * 9 -> 45 * 10 -> 50 * 11 -> 54 * 12 -> 59 * 13 -> 64 * 14 -> 69 * 15 -> 74 */ rt_sched_param sys_pri::python() { return rt_sched_param(0, RT_SCHED_RR); } rt_sched_param sys_pri::normal() { return rt_sched_param(2, RT_SCHED_RR); } rt_sched_param sys_pri::gcell_event_handler(){ return rt_sched_param(5, RT_SCHED_FIFO); } rt_sched_param sys_pri::usrp2_backend() { return rt_sched_param(6, RT_SCHED_FIFO); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/0000775000175000017500000000000012207702530021746 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/CMakeLists.txt0000664000175000017500000000425212207440367024520 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. if(ENABLE_GR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) # Add definition so we can compile in ControlPort to the blocks. ADD_DEFINITIONS(-DGR_CTRLPORT) ######################################################################## # Run ICE To compile Slice files ######################################################################## EXECUTE_PROCESS( COMMAND "${ICE_SLICE2CPP}" "-I${CMAKE_CURRENT_SOURCE_DIR}" "--output-dir=${CMAKE_CURRENT_BINARY_DIR}/" "${CMAKE_CURRENT_SOURCE_DIR}/gnuradio.ice" ) list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_SOURCE_DIR}/ice_application_base.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcmanager.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcpmtconverters_ice.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcserver_aggregator.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcserver_booter_aggregator.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcserver_booter_ice.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcserver_ice.cc ${CMAKE_CURRENT_SOURCE_DIR}/rpcserver_selector.cc ) # Append generated file in build directory list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio.cpp ) ######################################################################## # Add controlport stuff to gnuradio-runtime ######################################################################## include_directories(${CMAKE_CURRENT_BINARY_DIR}) list(APPEND gnuradio_runtime_libs ${ICE_LIBRARIES} ) endif(ENABLE_GR_CTRLPORT) gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/gnuradio.ice0000664000175000017500000000616512207702530024250 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ [["python:package:gnuradio.ctrlport"]] #ifndef GNURADIO_DEBUG #define GNURADIO_DEBUG module GNURadio { struct complex { float re; float im; }; class Knob {}; class KnobB extends Knob { bool value; }; class KnobC extends Knob { byte value; }; class KnobI extends Knob { int value; }; class KnobT extends Knob { short value; }; class KnobF extends Knob { float value; }; class KnobD extends Knob { double value; }; class KnobL extends Knob { long value; }; class KnobS extends Knob { string value; }; class KnobZ extends Knob { complex value; }; sequence VectorB; sequence VectorC; sequence VectorI; sequence VectorF; sequence VectorD; sequence VectorS; sequence VectorL; sequence VectorT; class KnobVecB extends Knob { VectorB value; }; class KnobVecC extends Knob { VectorC value; }; class KnobVecI extends Knob { VectorI value; }; class KnobVecT extends Knob { VectorT value; }; class KnobVecF extends Knob { VectorF value; }; class KnobVecD extends Knob { VectorD value; }; class KnobVecL extends Knob { VectorL value; }; class KnobVecS extends Knob { VectorS value; }; enum KnobType { KNOBBOOL, KNOBCHAR, KNOBINT, KNOBFLOAT, KNOBDOUBLE, KNOBSTRING, KNOBLONG, KNOBVECBOOL, KNOBVECCHAR, KNOBVECINT, KNOBVECFLOAT, KNOBVECDOUBLE, KNOBVECSTRING, KNOBVECLONG, KNOBSHORT}; const int DISPNULL = 0x0000; const int DISPTIME = 0x0001; const int DISPXY = 0x0002; const int DISPPSD = 0x0004; const int DISPSPEC = 0x0008; const int DISPRAST = 0x0010; const int DISPOPTCPLX = 0x0100; const int DISPOPTLOG = 0x0200; const int DISPOPTSTEM = 0x0400; const int DISPOPTSTRIP = 0x0800; const int DISPOPTSCATTER = 0x1000; struct KnobProp { KnobType type; string units; string description; int display; Knob min; Knob max; Knob defaultvalue; }; sequence KnobIDList; dictionary KnobMap; dictionary KnobPropMap; dictionary WaveformArgMap; interface StreamReceiver { void push(VectorC data); }; interface ControlPort { void set(KnobMap knobs); idempotent KnobMap get(KnobIDList knobs); idempotent KnobMap getRe(KnobIDList knobs); idempotent KnobPropMap properties(KnobIDList knobs); void shutdown(); }; }; #endif gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcserver_ice.cc0000664000175000017500000001317512207440367025126 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #define DEBUG 0 using namespace rpcpmtconverter; rpcserver_ice::rpcserver_ice() {} rpcserver_ice::~rpcserver_ice() {} void rpcserver_ice::registerConfigureCallback(const std::string &id, const configureCallback_t callback) { { ConfigureCallbackMap_t::const_iterator iter(d_setcallbackmap.find(id)); if(iter != d_setcallbackmap.end()) { std::stringstream s; s << "rpcserver_ice:: rpcserver_ice ERROR registering set, already registered: " << id << std::endl; throw std::runtime_error(s.str().c_str()); } } if(DEBUG) std::cout << "rpcserver_ice registering set: " << id << std::endl; d_setcallbackmap.insert(ConfigureCallbackMap_t::value_type(id, callback)); } void rpcserver_ice::unregisterConfigureCallback(const std::string &id) { ConfigureCallbackMap_t::iterator iter(d_setcallbackmap.find(id)); if(iter == d_setcallbackmap.end()) { std::stringstream s; s << "rpcserver_ice:: rpcserver_ice ERROR unregistering set, not registered: " << id << std::endl; throw std::runtime_error(s.str().c_str()); } if(DEBUG) std::cout << "rpcserver_ice unregistering set: " << id << std::endl; d_setcallbackmap.erase(iter); } void rpcserver_ice::registerQueryCallback(const std::string &id, const queryCallback_t callback) { { QueryCallbackMap_t::const_iterator iter(d_getcallbackmap.find(id)); if(iter != d_getcallbackmap.end()) { std::stringstream s; s << "rpcserver_ice:: rpcserver_ice ERROR registering get, already registered: " << id << std::endl; throw std::runtime_error(s.str().c_str()); } } if(DEBUG) std::cout << "rpcserver_ice registering get: " << id << std::endl; d_getcallbackmap.insert(QueryCallbackMap_t::value_type(id, callback)); } void rpcserver_ice::unregisterQueryCallback(const std::string &id) { QueryCallbackMap_t::iterator iter(d_getcallbackmap.find(id)); if(iter == d_getcallbackmap.end()) { std::stringstream s; s << "rpcserver_ice:: rpcserver_ice ERROR unregistering get, registered: " << id << std::endl; throw std::runtime_error(s.str().c_str()); } if(DEBUG) std::cout << "rpcserver_ice unregistering get: " << id << std::endl; d_getcallbackmap.erase(iter); } void rpcserver_ice::set(const GNURadio::KnobMap& knobs, const Ice::Current& c) { std::for_each(knobs.begin(), knobs.end(), set_f (c, d_setcallbackmap, cur_priv)); } GNURadio::KnobMap rpcserver_ice::getRe(const GNURadio::KnobIDList& knobs, const Ice::Current& c) { GNURadio::KnobMap outknobs; if(knobs.size() == 0) { std::for_each(d_getcallbackmap.begin(), d_getcallbackmap.end(), get_all_f (c, d_getcallbackmap, cur_priv, outknobs)); } else { QueryCallbackMap_t::iterator it; for(it = d_getcallbackmap.begin(); it != d_getcallbackmap.end(); it++){ for(size_t j=0; jfirst, re)){ get_f (c, d_getcallbackmap, cur_priv, outknobs)(it->first); break; } } } } return outknobs; } GNURadio::KnobMap rpcserver_ice::get(const GNURadio::KnobIDList& knobs, const Ice::Current& c) { GNURadio::KnobMap outknobs; if(knobs.size() == 0) { std::for_each(d_getcallbackmap.begin(), d_getcallbackmap.end(), get_all_f (c, d_getcallbackmap, cur_priv, outknobs)); } else { std::for_each(knobs.begin(), knobs.end(), get_f (c, d_getcallbackmap, cur_priv, outknobs)); } return outknobs; } GNURadio::KnobPropMap rpcserver_ice::properties(const GNURadio::KnobIDList& knobs, const Ice::Current& c) { GNURadio::KnobPropMap outknobs; if(knobs.size() == 0) { std::for_each(d_getcallbackmap.begin(), d_getcallbackmap.end(), properties_all_f(c, d_getcallbackmap, cur_priv, outknobs)); } else { std::for_each(knobs.begin(), knobs.end(), properties_f(c, d_getcallbackmap, cur_priv, outknobs)); } return outknobs; } void rpcserver_ice::shutdown(const Ice::Current& c) { if(DEBUG) std::cout << "Shutting down..." << std::endl; c.adapter->getCommunicator()->shutdown(); } gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcserver_aggregator.cc0000664000175000017500000000554012207440367026505 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include rpcserver_aggregator::rpcserver_aggregator() : d_type(std::string("aggregator")) {;} rpcserver_aggregator::~rpcserver_aggregator() {;} const std::string& rpcserver_aggregator::type() { return d_type; } const std::vector& rpcserver_aggregator::registeredServers() { return d_registeredServers; } void rpcserver_aggregator::registerConfigureCallback(const std::string &id, const configureCallback_t callback) { std::for_each(d_serverlist.begin(), d_serverlist.end(), registerConfigureCallback_f(id, callback)); } void rpcserver_aggregator::unregisterConfigureCallback(const std::string &id) { std::for_each(d_serverlist.begin(), d_serverlist.end(), unregisterConfigureCallback_f(id)); } void rpcserver_aggregator::registerQueryCallback(const std::string &id, const queryCallback_t callback) { std::for_each(d_serverlist.begin(), d_serverlist.end(), registerQueryCallback_f(id, callback)); } void rpcserver_aggregator::unregisterQueryCallback(const std::string &id) { std::for_each(d_serverlist.begin(), d_serverlist.end(), unregisterQueryCallback_f(id)); } void rpcserver_aggregator::registerServer(rpcmanager_base::rpcserver_booter_base_sptr server) { std::vector::iterator it(std::find(d_registeredServers.begin(), d_registeredServers.end(), server->type())); if(it != d_registeredServers.end()) { d_serverlist.push_back(server); d_registeredServers.push_back(server->type()); } else { std::stringstream s; s << "rpcserver_aggregator::registerServer: server of type " << server->type() << " already registered" << std::endl; throw std::runtime_error(s.str().c_str()); } } gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcmanager.cc0000664000175000017500000000370112207440367024404 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include bool rpcmanager::booter_registered(false); bool rpcmanager::aggregator_registered(false); rpcserver_booter_base* rpcmanager::boot(0); std::auto_ptr rpcmanager::aggregator(0); rpcmanager::rpcmanager() {;} rpcmanager::~rpcmanager() { if(boot) delete boot; } rpcserver_booter_base* rpcmanager::get() { if(aggregator_registered) { return aggregator.get(); } else if(booter_registered) { return boot; } assert(booter_registered || aggregator_registered); return boot; } void rpcmanager::register_booter(rpcserver_booter_base* booter) { if(make_aggregator && !aggregator_registered) { aggregator.reset(new rpcserver_booter_aggregator()); aggregator_registered = true; } if(aggregator_registered) { rpcmanager::rpcserver_booter_base_sptr bootreg(booter); aggregator->agg()->registerServer(bootreg); } else if(!booter_registered) { boot = booter; booter_registered = true; } else { throw std::runtime_error("rpcmanager: Aggregator not in use, and a rpc booter is already registered\n"); } } gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcserver_selector.cc0000664000175000017500000000234012207440367026176 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include bool rpcmanager::make_aggregator(false); #ifdef RPCSERVER_ICE #include rpcmanager::rpcserver_booter_register_helper boot_ice; #endif #ifdef RPCSERVER_ERLANG #error TODO ERLANG #endif #ifdef RPCSERVER_XMLRPC #error TODO XMLRPC #endif gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/ice_application_base.cc0000664000175000017500000000265712207440367026413 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include int ice_application_common::d_reacquire_attributes(0); bool ice_application_common::d_main_called(false); bool ice_application_common::d_have_ice_config(false); boost::shared_ptr ice_application_common::d_thread; std::string ice_application_common::d_endpointStr(""); boost::shared_ptr ice_application_common::Instance() { static boost::shared_ptr instance(new ice_application_common()); return instance; } int ice_application_common::run(int, char**) { communicator()->waitForShutdown(); return EXIT_SUCCESS; } gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/ICE_LICENSE0000664000175000017500000000460012207440367023442 0ustar jcorganjcorganCopyright (c) 2003-2011 ZeroC, Inc. All rights reserved. This copy of Ice is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Ice is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, see http://www.gnu.org/licenses. Linking Ice statically or dynamically with other software (such as a library, module or application) is making a combined work based on Ice. Thus, the terms and conditions of the GNU General Public License version 2 cover this combined work. If such software can only be used together with Ice, then not only the combined work but the software itself is a work derived from Ice and as such shall be licensed under the terms of the GNU General Public License version 2. This includes the situation where Ice is only being used through an abstraction layer. As a special exception to the above, ZeroC grants to the contributors for the following projects the permission to license their Ice-based software under the terms of the GNU Lesser General Public License (LGPL) version 2.1 or of the BSD license: - Orca Robotics (http://orca-robotics.sourceforge.net) - Mumble (http://mumble.sourceforge.net) This exception does not extend to the parts of Ice used by these projects, or to any other derived work: as a whole, any work based on Ice shall be licensed under the terms and conditions of the GNU General Public License version 2. You may also combine Ice with any software not derived from Ice, provided the license of such software is compatible with the GNU General Public License version 2. In addition, as a special exception, ZeroC grants you permission to combine Ice with: - the OpenSSL library, or with a modified version of the OpenSSL library that uses the same license as OpenSSL - any library not derived from Ice and licensed under the terms of the Apache License, version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html) If you modify this copy of Ice, you may extend any of the exceptions provided above to your version of Ice, but you are not obligated to do so. gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/frontend.ice0000664000175000017500000001210212207440367024252 0ustar jcorganjcorgan/* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include [["python:package:gnuradio.ctrlport"]] module GNURadio { module Frontend { // primitive types dictionary StrStrDict; dictionary TunerArgs; struct F32Range { float min; float max; }; // exception types exception NotSupported {}; exception InvalidSetting { string msg; }; exception ReceiverFailure { string msg; }; exception NotExist {}; // Status Types struct TunerStatus { float freq; float rate; int a2dbits; float gain; F32Range gainrange; bool isInverted; StrStrDict info; }; struct StreamInfo { string uri; StrStrDict info; }; struct ReceiverInfo { string uid; string name; StrStrDict info; }; struct ChannelStatus { string uid; string name; bool active; float freq; float bandwidth; bool isComplex; StrStrDict info; }; struct ChannelizerStatus { string uid; string name; StrStrDict info; }; // Interfaces interface Component { void setName(string newName); }; interface AbstractReceiver extends Component { idempotent ReceiverInfo getReceiverInfo(); }; interface Tuner extends Component { TunerStatus configureTuner(TunerArgs args) throws ReceiverFailure, InvalidSetting; idempotent TunerStatus status(); idempotent float setGain(float gain) throws ReceiverFailure, NotSupported, InvalidSetting; idempotent bool setInversion(bool inverted) throws ReceiverFailure, NotSupported, InvalidSetting; idempotent float setCenterFreq(float freq) throws ReceiverFailure, NotSupported, InvalidSetting; idempotent float setBandwidth(float bw) throws ReceiverFailure, NotSupported, InvalidSetting; idempotent void setInfo(string k, string v) throws ReceiverFailure, NotSupported, InvalidSetting; }; interface Channel extends Tuner { void start(); void stop(); void destroyChannel() throws NotSupported; idempotent bool active(); idempotent ChannelStatus channelStat(); idempotent StreamInfo stream(); idempotent bool setComplex(bool complex) throws ReceiverFailure, NotSupported, InvalidSetting; idempotent void setStreamInfo(string k, string v) throws ReceiverFailure, NotSupported, InvalidSetting; }; sequence TunerSeq; sequence ChannelSeq; interface Channelizer extends AbstractReceiver { idempotent ChannelizerStatus status(); idempotent Tuner* getTuner(); idempotent ChannelSeq getChannels(); idempotent ChannelSeq getActiveChannels(); idempotent ChannelSeq getInactiveChannels(); Channel* createChannel(float freq, float bw, StrStrDict args) throws NotSupported; }; sequence ChannelizerSeq; interface Receiver extends AbstractReceiver { idempotent ChannelizerSeq getInputs(); idempotent Channel* getChannelByID(string id) throws NotExist; idempotent Channelizer* getChannelizerByID(string id) throws NotExist; idempotent void setInfo(string k, string v) throws ReceiverFailure, NotSupported, InvalidSetting; }; }; module Booter { dictionary WaveformArgs; exception WaveformRunningError { string waveformClass; float centerFrequencyHz; }; exception SignalSourceError {string msg; }; interface WaveformBooter extends Frontend::Receiver, ControlPort { string launchWaveform(string waveformClass, WaveformArgs args) throws WaveformRunningError, SignalSourceError; WaveformArgMap getDriverEnum(); WaveformArgMap getSourceInfo(); idempotent bool waveformRunning(); idempotent string getWaveformClass(); }; }; }; gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcpmtconverters_ice.cc0000664000175000017500000001221512207702530026516 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include GNURadio::KnobPtr rpcpmtconverter::from_pmt(const pmt::pmt_t& knob, const Ice::Current& c) { if(pmt::is_real(knob)) { return new GNURadio::KnobD(Ice::Double(pmt::to_double(knob))); } else if(pmt::is_symbol(knob)) { std::string stuff = pmt::symbol_to_string(knob); return new GNURadio::KnobS(stuff); } else if(pmt::is_integer(knob)) { return new GNURadio::KnobI(pmt::to_long(knob)); } else if(pmt::is_bool(knob)) { return new GNURadio::KnobB(pmt::to_bool(knob)); } else if(pmt::is_uint64(knob)) { return new GNURadio::KnobL(pmt::to_uint64(knob)); } else if(pmt::is_complex(knob)) { std::complex tmp = pmt::to_complex(knob); GNURadio::complex cpx; cpx.re = tmp.real(); cpx.im = tmp.imag(); return new GNURadio::KnobZ(cpx); } else if(pmt::is_c32vector(knob)) { // c32 sent as interleaved floats size_t size(pmt::length(knob)); const float* start((const float*) pmt::c32vector_elements(knob,size)); return new GNURadio::KnobVecF(std::vector(start,start+size*2)); } else if (pmt::is_s32vector(knob)) { size_t size(pmt::length(knob)); const int* start((const int*) pmt::s32vector_elements(knob,size)); return new GNURadio::KnobVecI(std::vector(start,start+size)); } else if (pmt::is_s16vector(knob)) { size_t size(pmt::length(knob)); const short* start((const short*) pmt::s16vector_elements(knob,size)); return new GNURadio::KnobVecT(std::vector(start,start+size)); } else if(pmt::is_f32vector(knob)) { size_t size(pmt::length(knob)); const float* start((const float*) pmt::f32vector_elements(knob,size)); return new GNURadio::KnobVecF(std::vector(start,start+size)); } else if (pmt::is_u8vector(knob)) { size_t size(pmt::length(knob)); const uint8_t* start((const uint8_t*) pmt::u8vector_elements(knob,size)); return new GNURadio::KnobVecC(std::vector(start,start+size)); } else if (pmt::is_s8vector(knob)) { size_t size(pmt::length(knob)); const int8_t* start((const int8_t*) pmt::s8vector_elements(knob,size)); return new GNURadio::KnobVecC(std::vector(start,start+size)); } else { std::cerr << "Error: Don't know how to handle Knob Type (from): " << std::endl; assert(0);} //TODO: VECTORS!!! return new GNURadio::Knob(); } pmt::pmt_t rpcpmtconverter::to_pmt(const GNURadio::KnobPtr& knob, const Ice::Current& c) { std::string id(knob->ice_id(c).substr(12)); if(id == "KnobD") { GNURadio::KnobDPtr k(GNURadio::KnobDPtr::dynamicCast(knob)); return pmt::mp(k->value); } else if(id == "KnobF") { GNURadio::KnobFPtr k(GNURadio::KnobFPtr::dynamicCast(knob)); return pmt::mp(k->value); } else if(id == "KnobI") { GNURadio::KnobIPtr k(GNURadio::KnobIPtr::dynamicCast(knob)); return pmt::mp(k->value); } else if(id == "KnobT") { GNURadio::KnobTPtr k(GNURadio::KnobTPtr::dynamicCast(knob)); return pmt::mp(k->value); } else if(id == "KnobS") { GNURadio::KnobSPtr k(GNURadio::KnobSPtr::dynamicCast(knob)); return pmt::string_to_symbol(k->value); } else if(id == "KnobB") { GNURadio::KnobBPtr k(GNURadio::KnobBPtr::dynamicCast(knob)); return pmt::mp(k->value); } else if(id == "KnobC") { GNURadio::KnobCPtr k(GNURadio::KnobCPtr::dynamicCast(knob)); return pmt::mp(k->value); } else if(id == "KnobL") { GNURadio::KnobLPtr k(GNURadio::KnobLPtr::dynamicCast(knob)); return pmt::mp((long)k->value); } else if(id == "KnobZ") { GNURadio::KnobZPtr k(GNURadio::KnobZPtr::dynamicCast(knob)); std::complex cpx(k->value.re, k->value.im); return pmt::from_complex(cpx); } else if(id == "KnobVecC") { GNURadio::KnobVecCPtr k(GNURadio::KnobVecCPtr::dynamicCast(knob)); return pmt::init_u8vector(k->value.size(), &k->value[0]); } else if(id == "KnobVecI") { GNURadio::KnobVecIPtr k(GNURadio::KnobVecIPtr::dynamicCast(knob)); return pmt::init_s32vector(k->value.size(), &k->value[0]); } //else if(id == "KnobVecF") { // GNURadio::KnobVecFPtr k(GNURadio::KnobVecFPtr::dynamicCast(knob)); // return pmt::mp(k->value); //TODO: FLOAT!!! //TODO: VECTORS!!! else { std::cerr << "Error: Don't know how to handle Knob Type: " << id << std::endl; assert(0); } return pmt::pmt_t(); } gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcserver_booter_aggregator.cc0000664000175000017500000000307112207440367030054 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include rpcserver_booter_aggregator::rpcserver_booter_aggregator() : d_type(std::string("aggregator")), server(new rpcserver_aggregator()) {;} rpcserver_booter_aggregator::~rpcserver_booter_aggregator() {;} rpcserver_base* rpcserver_booter_aggregator::i() { return &(*server); } const std::string& rpcserver_booter_aggregator::type() { return d_type; } const std::vector rpcserver_booter_aggregator::endpoints() { std::vector ep; ep.push_back(std::string("TODO")); return ep; } const std::vector& rpcserver_booter_aggregator::registeredServers() { return server->registeredServers(); } rpcserver_aggregator* rpcserver_booter_aggregator::agg() { return &(*server); } gnuradio-3.7.2.1/gnuradio-runtime/lib/controlport/rpcserver_booter_ice.cc0000664000175000017500000000336512207440367026500 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include namespace { static const char* const CONTROL_PORT_CLASS("ice"); static const char* const CONTROL_PORT_NAME("ControlPort"); static const char* const ENDPOINT_NAME("gnuradio"); }; rpcserver_booter_ice::rpcserver_booter_ice() : ice_server_template (this, std::string(CONTROL_PORT_NAME), std::string(ENDPOINT_NAME)), d_type(std::string(CONTROL_PORT_CLASS)) {;} rpcserver_booter_ice::~rpcserver_booter_ice() {;} rpcserver_base* rpcserver_booter_ice::i() { return ice_server_template::i(); } const std::vector rpcserver_booter_ice::endpoints() { return ice_server_template::endpoints(); } gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_runtime.h0000664000175000017500000000221112207440367021701 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_RUNTIME_H_ #define _QA_RUNTIME_H_ #include #include //! collect all the tests for the runtime directory class __GR_ATTR_EXPORT qa_runtime { public: //! return suite of tests for all of runtime directory static CppUnit::TestSuite *suite (); }; #endif /* _QA_RUNTIME_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/complex_vec_test.cc0000664000175000017500000000261612207440367023247 0ustar jcorganjcorgan#include #include std::vector > complex_vec_test0() { std::vector > r(5); for (size_t i = 0; i < r.size(); i++) r[i] = std::complex(i, i); return r; } std::vector > complex_vec_test1(const std::vector > &input) { std::vector > r(input.size()); for (size_t i = 0; i < input.size(); i++) r[i] = std::complex(input[i].real()+0.5, input[i].imag()-0.5); return r; } std::complex complex_scalar_test0() { return std::complex(5, 5); } std::complex complex_scalar_test1(std::complex input) { return std::complex(input.real()+0.5, input.imag()-0.5); } std::vector float_vec_test0() { std::vector r(5); for (size_t i = 0; i < r.size(); i++) r[i] = (float) i; return r; } std::vector float_vec_test1(const std::vector &input) { std::vector r(input.size()); for (size_t i = 0; i < input.size(); i++) r[i] = input[i] + 0.5; return r; } std::vector int_vec_test0() { std::vector r(5); for (size_t i = 0; i < r.size(); i++) r[i] = (int) i; return r; } std::vector int_vec_test1(const std::vector &input) { std::vector r(input.size()); for (size_t i = 0; i < input.size(); i++) r[i] = input[i] + 1; return r; } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/0000775000175000017500000000000012236474522020323 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fast_atan2f.h0000664000175000017500000000217612236474522023353 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_FAST_ATAN2F_H_ #define _QA_FAST_ATAN2F_H_ #include #include class qa_fast_atan2f : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fast_atan2f); CPPUNIT_TEST(t1); CPPUNIT_TEST_SUITE_END(); private: void t1(); }; #endif /* _QA_FAST_ATAN2F_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/CMakeLists.txt0000664000175000017500000000224112207440367023060 0ustar jcorganjcorgan# Copyright 2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # This file included, use CMake directory variables ######################################################################## list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_SOURCE_DIR}/fast_atan2f.cc ${CMAKE_CURRENT_SOURCE_DIR}/fxpt.cc ${CMAKE_CURRENT_SOURCE_DIR}/random.cc ${CMAKE_CURRENT_SOURCE_DIR}/sincos.cc ) gnuradio-3.7.2.1/gnuradio-runtime/lib/math/fast_atan2f.cc0000664000175000017500000002015512236474522023025 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include // declaration is in here #include namespace gr { /***************************************************************************/ /* Constant definitions */ /***************************************************************************/ #define TAN_MAP_RES 0.003921569 /* (smallest non-zero value in table) */ #define RAD_PER_DEG 0.017453293 #define TAN_MAP_SIZE 256 /* arctangents from 0 to pi/4 radians */ static float fast_atan_table[257] = { 0.000000e+00, 3.921549e-03, 7.842976e-03, 1.176416e-02, 1.568499e-02, 1.960533e-02, 2.352507e-02, 2.744409e-02, 3.136226e-02, 3.527947e-02, 3.919560e-02, 4.311053e-02, 4.702413e-02, 5.093629e-02, 5.484690e-02, 5.875582e-02, 6.266295e-02, 6.656816e-02, 7.047134e-02, 7.437238e-02, 7.827114e-02, 8.216752e-02, 8.606141e-02, 8.995267e-02, 9.384121e-02, 9.772691e-02, 1.016096e-01, 1.054893e-01, 1.093658e-01, 1.132390e-01, 1.171087e-01, 1.209750e-01, 1.248376e-01, 1.286965e-01, 1.325515e-01, 1.364026e-01, 1.402496e-01, 1.440924e-01, 1.479310e-01, 1.517652e-01, 1.555948e-01, 1.594199e-01, 1.632403e-01, 1.670559e-01, 1.708665e-01, 1.746722e-01, 1.784728e-01, 1.822681e-01, 1.860582e-01, 1.898428e-01, 1.936220e-01, 1.973956e-01, 2.011634e-01, 2.049255e-01, 2.086818e-01, 2.124320e-01, 2.161762e-01, 2.199143e-01, 2.236461e-01, 2.273716e-01, 2.310907e-01, 2.348033e-01, 2.385093e-01, 2.422086e-01, 2.459012e-01, 2.495869e-01, 2.532658e-01, 2.569376e-01, 2.606024e-01, 2.642600e-01, 2.679104e-01, 2.715535e-01, 2.751892e-01, 2.788175e-01, 2.824383e-01, 2.860514e-01, 2.896569e-01, 2.932547e-01, 2.968447e-01, 3.004268e-01, 3.040009e-01, 3.075671e-01, 3.111252e-01, 3.146752e-01, 3.182170e-01, 3.217506e-01, 3.252758e-01, 3.287927e-01, 3.323012e-01, 3.358012e-01, 3.392926e-01, 3.427755e-01, 3.462497e-01, 3.497153e-01, 3.531721e-01, 3.566201e-01, 3.600593e-01, 3.634896e-01, 3.669110e-01, 3.703234e-01, 3.737268e-01, 3.771211e-01, 3.805064e-01, 3.838825e-01, 3.872494e-01, 3.906070e-01, 3.939555e-01, 3.972946e-01, 4.006244e-01, 4.039448e-01, 4.072558e-01, 4.105574e-01, 4.138496e-01, 4.171322e-01, 4.204054e-01, 4.236689e-01, 4.269229e-01, 4.301673e-01, 4.334021e-01, 4.366272e-01, 4.398426e-01, 4.430483e-01, 4.462443e-01, 4.494306e-01, 4.526070e-01, 4.557738e-01, 4.589307e-01, 4.620778e-01, 4.652150e-01, 4.683424e-01, 4.714600e-01, 4.745676e-01, 4.776654e-01, 4.807532e-01, 4.838312e-01, 4.868992e-01, 4.899573e-01, 4.930055e-01, 4.960437e-01, 4.990719e-01, 5.020902e-01, 5.050985e-01, 5.080968e-01, 5.110852e-01, 5.140636e-01, 5.170320e-01, 5.199904e-01, 5.229388e-01, 5.258772e-01, 5.288056e-01, 5.317241e-01, 5.346325e-01, 5.375310e-01, 5.404195e-01, 5.432980e-01, 5.461666e-01, 5.490251e-01, 5.518738e-01, 5.547124e-01, 5.575411e-01, 5.603599e-01, 5.631687e-01, 5.659676e-01, 5.687566e-01, 5.715357e-01, 5.743048e-01, 5.770641e-01, 5.798135e-01, 5.825531e-01, 5.852828e-01, 5.880026e-01, 5.907126e-01, 5.934128e-01, 5.961032e-01, 5.987839e-01, 6.014547e-01, 6.041158e-01, 6.067672e-01, 6.094088e-01, 6.120407e-01, 6.146630e-01, 6.172755e-01, 6.198784e-01, 6.224717e-01, 6.250554e-01, 6.276294e-01, 6.301939e-01, 6.327488e-01, 6.352942e-01, 6.378301e-01, 6.403565e-01, 6.428734e-01, 6.453808e-01, 6.478788e-01, 6.503674e-01, 6.528466e-01, 6.553165e-01, 6.577770e-01, 6.602282e-01, 6.626701e-01, 6.651027e-01, 6.675261e-01, 6.699402e-01, 6.723452e-01, 6.747409e-01, 6.771276e-01, 6.795051e-01, 6.818735e-01, 6.842328e-01, 6.865831e-01, 6.889244e-01, 6.912567e-01, 6.935800e-01, 6.958943e-01, 6.981998e-01, 7.004964e-01, 7.027841e-01, 7.050630e-01, 7.073330e-01, 7.095943e-01, 7.118469e-01, 7.140907e-01, 7.163258e-01, 7.185523e-01, 7.207701e-01, 7.229794e-01, 7.251800e-01, 7.273721e-01, 7.295557e-01, 7.317307e-01, 7.338974e-01, 7.360555e-01, 7.382053e-01, 7.403467e-01, 7.424797e-01, 7.446045e-01, 7.467209e-01, 7.488291e-01, 7.509291e-01, 7.530208e-01, 7.551044e-01, 7.571798e-01, 7.592472e-01, 7.613064e-01, 7.633576e-01, 7.654008e-01, 7.674360e-01, 7.694633e-01, 7.714826e-01, 7.734940e-01, 7.754975e-01, 7.774932e-01, 7.794811e-01, 7.814612e-01, 7.834335e-01, 7.853983e-01, 7.853983e-01 }; /***************************************************************************** Function: Arc tangent Syntax: angle = fast_atan2(y, x); float y y component of input vector float x x component of input vector float angle angle of vector (x, y) in radians Description: This function calculates the angle of the vector (x,y) based on a table lookup and linear interpolation. The table uses a 256 point table covering -45 to +45 degrees and uses symetry to determine the final angle value in the range of -180 to 180 degrees. Note that this function uses the small angle approximation for values close to zero. This routine calculates the arc tangent with an average error of +/- 0.045 degrees. *****************************************************************************/ float fast_atan2f(float y, float x) { float x_abs, y_abs, z; float alpha, angle, base_angle; int index; /* normalize to +/- 45 degree range */ y_abs = fabsf(y); x_abs = fabsf(x); /* don't divide by zero! */ if((y_abs < 1.5E-5) && (x_abs < 1.5E-5)) return 0.0; //z = (y_abs < x_abs ? y_abs / x_abs : x_abs / y_abs); if(y_abs < x_abs) z = y_abs / x_abs; else z = x_abs / y_abs; /* when ratio approaches the table resolution, the angle is */ /* best approximated with the argument itself... */ if(z < TAN_MAP_RES) base_angle = z; else { /* find index and interpolation value */ alpha = z * (float)TAN_MAP_SIZE - .5; index = (int)alpha; alpha -= (float)index; /* determine base angle based on quadrant and */ /* add or subtract table value from base angle based on quadrant */ base_angle = fast_atan_table[index]; base_angle += (fast_atan_table[index + 1] - fast_atan_table[index]) * alpha; } if(x_abs > y_abs) { /* -45 -> 45 or 135 -> 225 */ if(x >= 0.0) { /* -45 -> 45 */ if(y >= 0.0) angle = base_angle; /* 0 -> 45, angle OK */ else angle = -base_angle; /* -45 -> 0, angle = -angle */ } else { /* 135 -> 180 or 180 -> -135 */ angle = 3.14159265358979323846; if(y >= 0.0) angle -= base_angle; /* 135 -> 180, angle = 180 - angle */ else angle = base_angle - angle; /* 180 -> -135, angle = angle - 180 */ } } else { /* 45 -> 135 or -135 -> -45 */ if(y >= 0.0) { /* 45 -> 135 */ angle = 1.57079632679489661923; if(x >= 0.0) angle -= base_angle; /* 45 -> 90, angle = 90 - angle */ else angle += base_angle; /* 90 -> 135, angle = 90 + angle */ } else { /* -135 -> -45 */ angle = -1.57079632679489661923; if(x >= 0.0) angle += base_angle; /* -90 -> -45, angle = -90 + angle */ else angle -= base_angle; /* -135 -> -90, angle = -90 - angle */ } } #ifdef ZERO_TO_TWOPI if (angle < 0) return (angle + TWOPI); else return (angle); #else return (angle); #endif } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_sincos.h0000664000175000017500000000220612207440367022451 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_SINCOS_H_ #define _QA_SINCOS_H_ #include #include class qa_sincos : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_sincos); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST_SUITE_END(); private: void t1(); void t2(); }; #endif /* _QA_SINCOS_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/sine_table.h0000664000175000017500000015405012207440367022604 0ustar jcorganjcorgan // max_error = 2.353084136763606e-06 { 2.925817799165007e-09, 7.219194364267018e-09 }, { 2.925707643778599e-09, 2.526699001579799e-07 }, { 2.925487337153070e-09, 1.191140162167675e-06 }, { 2.925156887582842e-09, 3.284585035595589e-06 }, { 2.924716307509151e-09, 6.994872605695784e-06 }, { 2.924165613519592e-09, 1.278374920658798e-05 }, { 2.923504826347475e-09, 2.111280464718590e-05 }, { 2.922733970871080e-09, 3.244343744537165e-05 }, { 2.921853076112655e-09, 4.723682007436170e-05 }, { 2.920862175237416e-09, 6.595386421935634e-05 }, { 2.919761305552202e-09, 8.905518605213658e-05 }, { 2.918550508504146e-09, 1.170010715193098e-04 }, { 2.917229829679050e-09, 1.502514416517192e-04 }, { 2.915799318799769e-09, 1.892658178912071e-04 }, { 2.914259029724184e-09, 2.345032874456615e-04 }, { 2.912609020443340e-09, 2.864224686607020e-04 }, { 2.910849353079123e-09, 3.454814764261432e-04 }, { 2.908980093882049e-09, 4.121378876027343e-04 }, { 2.907001313228646e-09, 4.868487064877691e-04 }, { 2.904913085618902e-09, 5.700703303049837e-04 }, { 2.902715489673383e-09, 6.622585147355725e-04 }, { 2.900408608130373e-09, 7.638683394782519e-04 }, { 2.897992527842612e-09, 8.753541738578119e-04 }, { 2.895467339774186e-09, 9.971696424604937e-04 }, { 2.892833138996999e-09, 1.129767590823255e-03 }, { 2.890090024687216e-09, 1.273600051161478e-03 }, { 2.887238100121550e-09, 1.429118208142094e-03 }, { 2.884277472673313e-09, 1.596772364709564e-03 }, { 2.881208253808507e-09, 1.777011907950626e-03 }, { 2.878030559081432e-09, 1.970285275029487e-03 }, { 2.874744508130554e-09, 2.177039919152579e-03 }, { 2.871350224673798e-09, 2.397722275614272e-03 }, { 2.867847836504030e-09, 2.632777727878843e-03 }, { 2.864237475484149e-09, 2.882650573737405e-03 }, { 2.860519277542297e-09, 3.147783991507308e-03 }, { 2.856693382666432e-09, 3.428620006328931e-03 }, { 2.852759934899389e-09, 3.725599456482154e-03 }, { 2.848719082333207e-09, 4.039161959812243e-03 }, { 2.844570977103752e-09, 4.369745880190706e-03 }, { 2.840315775384800e-09, 4.717788294077374e-03 }, { 2.835953637382310e-09, 5.083724957128360e-03 }, { 2.831484727328322e-09, 5.467990270896617e-03 }, { 2.826909213474759e-09, 5.871017249604038e-03 }, { 2.822227268087134e-09, 6.293237486988512e-03 }, { 2.817439067438018e-09, 6.735081123237729e-03 }, { 2.812544791800534e-09, 7.196976811989608e-03 }, { 2.807544625441273e-09, 7.679351687456759e-03 }, { 2.802438756613836e-09, 8.182631331563162e-03 }, { 2.797227377551135e-09, 8.707239741274575e-03 }, { 2.791910684458716e-09, 9.253599295902304e-03 }, { 2.786488877507140e-09, 9.822130724578715e-03 }, { 2.780962160824228e-09, 1.041325307382490e-02 }, { 2.775330742487884e-09, 1.102738367513773e-02 }, { 2.769594834517682e-09, 1.166493811278924e-02 }, { 2.763754652867477e-09, 1.232633019159818e-02 }, { 2.757810417416620e-09, 1.301197190494069e-02 }, { 2.751762351962413e-09, 1.372227340270610e-02 }, { 2.745610684210923e-09, 1.445764295952962e-02 }, { 2.739355645769094e-09, 1.521848694296229e-02 }, { 2.732997472135539e-09, 1.600520978188769e-02 }, { 2.726536402691907e-09, 1.681821393496225e-02 }, { 2.719972680693777e-09, 1.765789985920713e-02 }, { 2.713306553261610e-09, 1.852466597868779e-02 }, { 2.706538271371373e-09, 1.941890865333146e-02 }, { 2.699668089844909e-09, 2.034102214787814e-02 }, { 2.692696267340880e-09, 2.129139860085272e-02 }, { 2.685623066344263e-09, 2.227042799383416e-02 }, { 2.678448753157212e-09, 2.327849812064098e-02 }, { 2.671173597888530e-09, 2.431599455681316e-02 }, { 2.663797874443630e-09, 2.538330062913108e-02 }, { 2.656321860514457e-09, 2.648079738524795e-02 }, { 2.648745837568575e-09, 2.760886356354952e-02 }, { 2.641070090839117e-09, 2.876787556300114e-02 }, { 2.633294909313421e-09, 2.995820741329835e-02 }, { 2.625420585722845e-09, 3.118023074495535e-02 }, { 2.617447416531143e-09, 3.243431475972608e-02 }, { 2.609375701923643e-09, 3.372082620101990e-02 }, { 2.601205745795833e-09, 3.504012932452527e-02 }, { 2.592937855741933e-09, 3.639258586895711e-02 }, { 2.584572343043400e-09, 3.777855502693250e-02 }, { 2.576109522656942e-09, 3.919839341605197e-02 }, { 2.567549713203028e-09, 4.065245505002102e-02 }, { 2.558893236953688e-09, 4.214109131001403e-02 }, { 2.550140419820252e-09, 4.366465091617666e-02 }, { 2.541291591341445e-09, 4.522347989919473e-02 }, { 2.532347084670572e-09, 4.681792157215026e-02 }, { 2.523307236563343e-09, 4.844831650239501e-02 }, { 2.514172387364900e-09, 5.011500248369893e-02 }, { 2.504942880997064e-09, 5.181831450849345e-02 }, { 2.495619064945627e-09, 5.355858474024022e-02 }, { 2.486201290246928e-09, 5.533614248606705e-02 }, { 2.476689911475047e-09, 5.715131416942842e-02 }, { 2.467085286727668e-09, 5.900442330315692e-02 }, { 2.457387777613798e-09, 6.089579046229943e-02 }, { 2.447597749239101e-09, 6.282573325755320e-02 }, { 2.437715570192557e-09, 6.479456630859221e-02 }, { 2.427741612532542e-09, 6.680260121764925e-02 }, { 2.417676251773166e-09, 6.885014654319160e-02 }, { 2.407519866869294e-09, 7.093750777401114e-02 }, { 2.397272840203310e-09, 7.306498730310884e-02 }, { 2.386935557569868e-09, 7.523288440214027e-02 }, { 2.376508408161815e-09, 7.744149519577415e-02 }, { 2.365991784555363e-09, 7.969111263635709e-02 }, { 2.355386082695641e-09, 8.198202647865405e-02 }, { 2.344691701881232e-09, 8.431452325495814e-02 }, { 2.333909044749407e-09, 8.668888625021409e-02 }, { 2.323038517261246e-09, 8.910539547731611e-02 }, { 2.312080528685971e-09, 9.156432765274414e-02 }, { 2.301035491585642e-09, 9.406595617227698e-02 }, { 2.289903821799651e-09, 9.661055108691619e-02 }, { 2.278685938428940e-09, 9.919837907903295e-02 }, { 2.267382263820762e-09, 1.018297034385580e-01 }, { 2.255993223551837e-09, 1.045047840397028e-01 }, { 2.244519246413220e-09, 1.072238773174577e-01 }, { 2.232960764393620e-09, 1.099872362446146e-01 }, { 2.221318212663309e-09, 1.127951103088245e-01 }, { 2.209592029557811e-09, 1.156477454898748e-01 }, { 2.197782656561395e-09, 1.185453842371912e-01 }, { 2.185890538290176e-09, 1.214882654476019e-01 }, { 2.173916122475606e-09, 1.244766244431883e-01 }, { 2.161859859947797e-09, 1.275106929493488e-01 }, { 2.149722204618256e-09, 1.305906990731841e-01 }, { 2.137503613462743e-09, 1.337168672820376e-01 }, { 2.125204546504321e-09, 1.368894183821595e-01 }, { 2.112825466795944e-09, 1.401085694976751e-01 }, { 2.100366840402933e-09, 1.433745340497602e-01 }, { 2.087829136385612e-09, 1.466875217359607e-01 }, { 2.075212826781308e-09, 1.500477385098620e-01 }, { 2.062518386587093e-09, 1.534553865607503e-01 }, { 2.049746293741359e-09, 1.569106642937665e-01 }, { 2.036897029106193e-09, 1.604137663100403e-01 }, { 2.023971076449323e-09, 1.639648833871233e-01 }, { 2.010968922425217e-09, 1.675642024598467e-01 }, { 1.997891056557933e-09, 1.712119066008896e-01 }, { 1.984737971221581e-09, 1.749081750021970e-01 }, { 1.971510161622434e-09, 1.786531829561379e-01 }, { 1.958208125780130e-09, 1.824471018371070e-01 }, { 1.944832364508511e-09, 1.862900990834311e-01 }, { 1.931383381397782e-09, 1.901823381790926e-01 }, { 1.917861682794392e-09, 1.941239786363039e-01 }, { 1.904267777782611e-09, 1.981151759777950e-01 }, { 1.890602178165317e-09, 2.021560817195309e-01 }, { 1.876865398444616e-09, 2.062468433536743e-01 }, { 1.863057955802572e-09, 2.103876043317229e-01 }, { 1.849180370081465e-09, 2.145785040479915e-01 }, { 1.835233163764673e-09, 2.188196778231083e-01 }, { 1.821216861956509e-09, 2.231112568880342e-01 }, { 1.807131992362945e-09, 2.274533683680190e-01 }, { 1.792979085271234e-09, 2.318461352671018e-01 }, { 1.778758673530482e-09, 2.362896764525300e-01 }, { 1.764471292530943e-09, 2.407841066397789e-01 }, { 1.750117480184598e-09, 2.453295363773890e-01 }, { 1.735697776904342e-09, 2.499260720324433e-01 }, { 1.721212725583874e-09, 2.545738157760434e-01 }, { 1.706662871577097e-09, 2.592728655691494e-01 }, { 1.692048762677849e-09, 2.640233151485341e-01 }, { 1.677370949099090e-09, 2.688252540131204e-01 }, { 1.662629983452104e-09, 2.736787674105404e-01 }, { 1.647826420726167e-09, 2.785839363237506e-01 }, { 1.632960818266680e-09, 2.835408374583758e-01 }, { 1.618033735755429e-09, 2.885495432295704e-01 }, { 1.603045735188609e-09, 2.936101217498361e-01 }, { 1.587997380855918e-09, 2.987226368167127e-01 }, { 1.572889239319430e-09, 3.038871479007593e-01 }, { 1.557721879392051e-09, 3.091037101339017e-01 }, { 1.542495872116447e-09, 3.143723742978435e-01 }, { 1.527211790743024e-09, 3.196931868130269e-01 }, { 1.511870210708909e-09, 3.250661897274744e-01 }, { 1.496471709615926e-09, 3.304914207062036e-01 }, { 1.481016867208896e-09, 3.359689130207621e-01 }, { 1.465506265353924e-09, 3.414986955389885e-01 }, { 1.449940488016384e-09, 3.470807927151147e-01 }, { 1.434320121238994e-09, 3.527152245800635e-01 }, { 1.418645753119802e-09, 3.584020067320109e-01 }, { 1.402917973789838e-09, 3.641411503272979e-01 }, { 1.387137375391042e-09, 3.699326620714776e-01 }, { 1.371304552054134e-09, 3.757765442106153e-01 }, { 1.355420099875958e-09, 3.816727945230153e-01 }, { 1.339484616897137e-09, 3.876214063110671e-01 }, { 1.323498703079580e-09, 3.936223683933865e-01 }, { 1.307462960283922e-09, 3.996756650972121e-01 }, { 1.291377992246768e-09, 4.057812762511174e-01 }, { 1.275244404558188e-09, 4.119391771778626e-01 }, { 1.259062804638585e-09, 4.181493386877248e-01 }, { 1.242833801715929e-09, 4.244117270719281e-01 }, { 1.226558006803155e-09, 4.307263040962509e-01 }, { 1.210236032674760e-09, 4.370930269951803e-01 }, { 1.193868493843725e-09, 4.435118484661861e-01 }, { 1.177456006538695e-09, 4.499827166641340e-01 }, { 1.160999188680582e-09, 4.565055751961679e-01 }, { 1.144498659859216e-09, 4.630803631168164e-01 }, { 1.127955041310214e-09, 4.697070149232604e-01 }, { 1.111368955891417e-09, 4.763854605510119e-01 }, { 1.094741028059551e-09, 4.831156253697562e-01 }, { 1.078071883846871e-09, 4.898974301794375e-01 }, { 1.061362150836978e-09, 4.967307912069362e-01 }, { 1.044612458142151e-09, 5.036156201023686e-01 }, { 1.027823436378632e-09, 5.105518239364775e-01 }, { 1.010995717643647e-09, 5.175393051975563e-01 }, { 9.941299354913699e-10, 5.245779617890562e-01 }, { 9.772267249089968e-10, 5.316676870274011e-01 }, { 9.602867222926046e-10, 5.388083696401416e-01 }, { 9.433105654240147e-10, 5.459998937639375e-01 }, { 9.262988934458084e-10, 5.532421389435711e-01 }, { 9.092523468378193e-10, 5.605349801305876e-01 }, { 8.921715673928355e-10, 5.678782876825250e-01 }, { 8.750571981926701e-10, 5.752719273622372e-01 }, { 8.579098835836508e-10, 5.827157603377209e-01 }, { 8.407302691522673e-10, 5.902096431821322e-01 }, { 8.235190017016133e-10, 5.977534278737073e-01 }, { 8.062767292259225e-10, 6.053469617967722e-01 }, { 7.890041008871165e-10, 6.129900877421282e-01 }, { 7.717017669898175e-10, 6.206826439083659e-01 }, { 7.543703789572603e-10, 6.284244639030392e-01 }, { 7.370105893063053e-10, 6.362153767444958e-01 }, { 7.196230516231919e-10, 6.440552068636356e-01 }, { 7.022084205389746e-10, 6.519437741060674e-01 }, { 6.847673517046416e-10, 6.598808937346672e-01 }, { 6.673005017664976e-10, 6.678663764322770e-01 }, { 6.498085283416530e-10, 6.759000283046127e-01 }, { 6.322920899929834e-10, 6.839816508836737e-01 }, { 6.147518462045659e-10, 6.921110411311926e-01 }, { 5.971884573565851e-10, 7.002879914425926e-01 }, { 5.796025847007168e-10, 7.085122896509806e-01 }, { 5.619948903351406e-10, 7.167837190315758e-01 }, { 5.443660371796048e-10, 7.251020583063744e-01 }, { 5.267166889504394e-10, 7.334670816491009e-01 }, { 5.090475101356742e-10, 7.418785586903696e-01 }, { 4.913591659698399e-10, 7.503362545232619e-01 }, { 4.736523224091392e-10, 7.588399297089872e-01 }, { 4.559276461062478e-10, 7.673893402829834e-01 }, { 4.381858043851147e-10, 7.759842377612828e-01 }, { 4.204274652161870e-10, 7.846243691469355e-01 }, { 4.026532971908398e-10, 7.933094769370790e-01 }, { 3.848639694963359e-10, 8.020392991300200e-01 }, { 3.670601518910503e-10, 8.108135692324444e-01 }, { 3.492425146784233e-10, 8.196320162675177e-01 }, { 3.314117286825031e-10, 8.284943647824689e-01 }, { 3.135684652223755e-10, 8.374003348569865e-01 }, { 2.957133960867535e-10, 8.463496421118015e-01 }, { 2.778471935089361e-10, 8.553419977173513e-01 }, { 2.599705301412391e-10, 8.643771084029740e-01 }, { 2.420840790301135e-10, 8.734546764660205e-01 }, { 2.241885135902046e-10, 8.825743997817682e-01 }, { 2.062845075795238e-10, 8.917359718130367e-01 }, { 1.883727350736140e-10, 9.009390816205823e-01 }, { 1.704538704408269e-10, 9.101834138731877e-01 }, { 1.525285883160648e-10, 9.194686488588080e-01 }, { 1.345975635762696e-10, 9.287944624950824e-01 }, { 1.166614713141648e-10, 9.381605263410157e-01 }, { 9.872098681369190e-11, 9.475665076080466e-01 }, { 8.077678552380464e-11, 9.570120691722380e-01 }, { 6.282954303364090e-11, 9.664968695860140e-01 }, { 4.487993504668797e-11, 9.760205630906909e-01 }, { 2.692863735553042e-11, 9.855827996289697e-01 }, { 8.976325816439114e-12, 9.951832248577780e-01 }, { -8.976323676304494e-12, 1.004821480161519e+00 }, { -2.692863521550168e-11, 1.014497202665280e+00 }, { -4.487993290681805e-11, 1.024210025248670e+00 }, { -6.282954089398273e-11, 1.033959576559617e+00 }, { -8.077678338451706e-11, 1.043745481028715e+00 }, { -9.872098467477489e-11, 1.053567358883467e+00 }, { -1.166614691757772e-10, 1.063424826163223e+00 }, { -1.345975614383584e-10, 1.073317494734013e+00 }, { -1.525285861788948e-10, 1.083244972303963e+00 }, { -1.704538683042922e-10, 1.093206862438572e+00 }, { -1.883727329379793e-10, 1.103202764576806e+00 }, { -2.062845054446831e-10, 1.113232274046796e+00 }, { -2.241885114563697e-10, 1.123294982082432e+00 }, { -2.420840768973375e-10, 1.133390475839767e+00 }, { -2.599705280096278e-10, 1.143518338413855e+00 }, { -2.778471913784365e-10, 1.153678148855860e+00 }, { -2.957133939575774e-10, 1.163869482190458e+00 }, { -3.135684630945758e-10, 1.174091909433296e+00 }, { -3.314117265561857e-10, 1.184344997608959e+00 }, { -3.492425125535882e-10, 1.194628309769018e+00 }, { -3.670601497678034e-10, 1.204941405010466e+00 }, { -3.848639673748360e-10, 1.215283838494269e+00 }, { -4.026532950710339e-10, 1.225655161464298e+00 }, { -4.204274630982869e-10, 1.236054921266445e+00 }, { -4.381858022691734e-10, 1.246482661367958e+00 }, { -4.559276439922654e-10, 1.256937921377146e+00 }, { -4.736523202972214e-10, 1.267420237063216e+00 }, { -4.913591638600925e-10, 1.277929140376502e+00 }, { -5.090475080282032e-10, 1.288464159468706e+00 }, { -5.267166868452449e-10, 1.299024818713528e+00 }, { -5.443660350768455e-10, 1.309610638727845e+00 }, { -5.619948882348695e-10, 1.320221136392390e+00 }, { -5.796025826029868e-10, 1.330855824873457e+00 }, { -5.971884552615020e-10, 1.341514213644420e+00 }, { -6.147518441122357e-10, 1.352195808507556e+00 }, { -6.322920879034590e-10, 1.362900111616144e+00 }, { -6.498085262549874e-10, 1.373626621496939e+00 }, { -6.673004996827436e-10, 1.384374833072571e+00 }, { -6.847673496239581e-10, 1.395144237684605e+00 }, { -7.022084184613616e-10, 1.405934323116231e+00 }, { -7.196230495488082e-10, 1.416744573616104e+00 }, { -7.370105872352039e-10, 1.427574469921397e+00 }, { -7.543703768894941e-10, 1.438423489281758e+00 }, { -7.717017649255453e-10, 1.449291105483472e+00 }, { -7.890040988262324e-10, 1.460176788873383e+00 }, { -8.062767271686383e-10, 1.471080006383765e+00 }, { -8.235189996479819e-10, 1.482000221556656e+00 }, { -8.407302671024475e-10, 1.492936894569018e+00 }, { -8.579098815375368e-10, 1.503889482257845e+00 }, { -8.750571961505266e-10, 1.514857438145604e+00 }, { -8.921715653546624e-10, 1.525840212465756e+00 }, { -9.092523448036167e-10, 1.536837252188703e+00 }, { -9.262988914157881e-10, 1.547848001047890e+00 }, { -9.433105633981766e-10, 1.558871899565883e+00 }, { -9.602867202711075e-10, 1.569908385081254e+00 }, { -9.772267228916820e-10, 1.580956891774897e+00 }, { -9.941299334786078e-10, 1.592016850697478e+00 }, { -1.010995715635332e-09, 1.603087689796053e+00 }, { -1.027823434374870e-09, 1.614168833942028e+00 }, { -1.044612456143047e-09, 1.625259704958335e+00 }, { -1.061362148842745e-09, 1.636359721647526e+00 }, { -1.078071881857297e-09, 1.647468299819543e+00 }, { -1.094741026074900e-09, 1.658584852320419e+00 }, { -1.111368953911690e-09, 1.669708789060341e+00 }, { -1.127955039335462e-09, 1.680839517042381e+00 }, { -1.144498657889600e-09, 1.691976440391624e+00 }, { -1.160999186716154e-09, 1.703118960383971e+00 }, { -1.177456004579561e-09, 1.714266475475616e+00 }, { -1.193868491889832e-09, 1.725418381332405e+00 }, { -1.210236030726319e-09, 1.736574070859850e+00 }, { -1.226558004860220e-09, 1.747732934232508e+00 }, { -1.242833799778447e-09, 1.758894358924547e+00 }, { -1.259062802706714e-09, 1.770057729740021e+00 }, { -1.275244402631982e-09, 1.781222428842935e+00 }, { -1.291377990326492e-09, 1.792387835788660e+00 }, { -1.307462958369363e-09, 1.803553327553897e+00 }, { -1.323498701170897e-09, 1.814718278568759e+00 }, { -1.339484614994490e-09, 1.825882060747428e+00 }, { -1.355420097979292e-09, 1.837044043519582e+00 }, { -1.371304550163662e-09, 1.848203593862598e+00 }, { -1.387137373506711e-09, 1.859360076332671e+00 }, { -1.402917971911754e-09, 1.870512853097495e+00 }, { -1.418645751248018e-09, 1.881661283967967e+00 }, { -1.434320119373722e-09, 1.892804726431080e+00 }, { -1.449940486157623e-09, 1.903942535681972e+00 }, { -1.465506263501516e-09, 1.915074064656886e+00 }, { -1.481016865363264e-09, 1.926198664066737e+00 }, { -1.496471707776859e-09, 1.937315682428795e+00 }, { -1.511870208876724e-09, 1.948424466101625e+00 }, { -1.527211788917509e-09, 1.959524359317042e+00 }, { -1.542495870297867e-09, 1.970614704215133e+00 }, { -1.557721877580406e-09, 1.981694840876775e+00 }, { -1.572889237514880e-09, 1.992764107358707e+00 }, { -1.587997379058514e-09, 2.003821839726753e+00 }, { -1.603045733398246e-09, 2.014867372090665e+00 }, { -1.618033733972424e-09, 2.025900036638798e+00 }, { -1.632960816490822e-09, 2.036919163671778e+00 }, { -1.647826418957721e-09, 2.047924081638631e+00 }, { -1.662629981691070e-09, 2.058914117170269e+00 }, { -1.677370947345626e-09, 2.069888595116115e+00 }, { -1.692048760931849e-09, 2.080846838577820e+00 }, { -1.706662869838827e-09, 2.091788168946183e+00 }, { -1.721212723853279e-09, 2.102711905935372e+00 }, { -1.735697775181424e-09, 2.113617367619504e+00 }, { -1.750117478469621e-09, 2.124503870468520e+00 }, { -1.764471290823748e-09, 2.135370729383332e+00 }, { -1.778758671831281e-09, 2.146217257733207e+00 }, { -1.792979083579974e-09, 2.157042767390815e+00 }, { -1.807131990679890e-09, 2.167846568770014e+00 }, { -1.821216860281448e-09, 2.178627970860822e+00 }, { -1.835233162097977e-09, 2.189386281268046e+00 }, { -1.849180368423027e-09, 2.200120806246095e+00 }, { -1.863057954152340e-09, 2.210830850737588e+00 }, { -1.876865396802907e-09, 2.221515718409926e+00 }, { -1.890602176531920e-09, 2.232174711691990e+00 }, { -1.904267776157843e-09, 2.242807131812679e+00 }, { -1.917861681178094e-09, 2.253412278837029e+00 }, { -1.931383379790273e-09, 2.263989451705295e+00 }, { -1.944832362909578e-09, 2.274537948269257e+00 }, { -1.958208124189984e-09, 2.285057065331676e+00 }, { -1.971510160041235e-09, 2.295546098682665e+00 }, { -1.984737969649064e-09, 2.306004343138794e+00 }, { -1.997891054994522e-09, 2.316431092581699e+00 }, { -2.010968920870647e-09, 2.326825639994779e+00 }, { -2.023971074903858e-09, 2.337187277503834e+00 }, { -2.036897027569834e-09, 2.347515296413520e+00 }, { -2.049746292214264e-09, 2.357808987247877e+00 }, { -2.062518385069210e-09, 2.368067639787542e+00 }, { -2.075212825272584e-09, 2.378290543109652e+00 }, { -2.087829134886364e-09, 2.388476985626922e+00 }, { -2.100366838912949e-09, 2.398626255125417e+00 }, { -2.112825465315542e-09, 2.408737638805759e+00 }, { -2.125204545033289e-09, 2.418810423320288e+00 }, { -2.137503612001452e-09, 2.428843894814472e+00 }, { -2.149722203166389e-09, 2.438837338964302e+00 }, { -2.161859858505829e-09, 2.448790041018174e+00 }, { -2.173916121043380e-09, 2.458701285834241e+00 }, { -2.185890536867478e-09, 2.468570357921585e+00 }, { -2.197782655148702e-09, 2.478396541480230e+00 }, { -2.209592028154913e-09, 2.488179120439544e+00 }, { -2.221318211270522e-09, 2.497917378500214e+00 }, { -2.232960763010574e-09, 2.507610599172123e+00 }, { -2.244519245040444e-09, 2.517258065817044e+00 }, { -2.255993222189014e-09, 2.526859061686102e+00 }, { -2.267382262468209e-09, 2.536412869962689e+00 }, { -2.278685937086658e-09, 2.545918773800664e+00 }, { -2.289903820467374e-09, 2.555376056366064e+00 }, { -2.301035490263848e-09, 2.564784000877677e+00 }, { -2.312080527374447e-09, 2.574141890646339e+00 }, { -2.323038515960257e-09, 2.583449009117307e+00 }, { -2.333909043458635e-09, 2.592704639909166e+00 }, { -2.344691700601153e-09, 2.601908066856634e+00 }, { -2.355386081425938e-09, 2.611058574048749e+00 }, { -2.365991783296513e-09, 2.620155445872768e+00 }, { -2.376508406913500e-09, 2.629197967052127e+00 }, { -2.386935556332088e-09, 2.638185422689490e+00 }, { -2.397272838976436e-09, 2.647117098307332e+00 }, { -2.407519865653114e-09, 2.655992279887846e+00 }, { -2.417676250567891e-09, 2.664810253915885e+00 }, { -2.427741611338014e-09, 2.673570307418169e+00 }, { -2.437715569009093e-09, 2.682271728006635e+00 }, { -2.447597748066437e-09, 2.690913803917100e+00 }, { -2.457387776452357e-09, 2.699495824053297e+00 }, { -2.467085285577292e-09, 2.708017078025636e+00 }, { -2.476689910335470e-09, 2.716476856194105e+00 }, { -2.486201289118733e-09, 2.724874449709689e+00 }, { -2.495619063828443e-09, 2.733209150554255e+00 }, { -2.504942879891263e-09, 2.741480251583985e+00 }, { -2.514172386270163e-09, 2.749687046568741e+00 }, { -2.523307235480146e-09, 2.757828830235740e+00 }, { -2.532347083598520e-09, 2.765904898308531e+00 }, { -2.541291590280960e-09, 2.773914547551261e+00 }, { -2.550140418771202e-09, 2.781857075807392e+00 }, { -2.558893235915887e-09, 2.789731782043156e+00 }, { -2.567549712176927e-09, 2.797537966388929e+00 }, { -2.576109521642196e-09, 2.805274930179221e+00 }, { -2.584572342040407e-09, 2.812941975996573e+00 }, { -2.592937854750428e-09, 2.820538407710556e+00 }, { -2.601205744816134e-09, 2.828063530521908e+00 }, { -2.609375700955458e-09, 2.835516651001539e+00 }, { -2.617447415574869e-09, 2.842897077134583e+00 }, { -2.625420584778350e-09, 2.850204118359573e+00 }, { -2.633294908380520e-09, 2.857437085611509e+00 }, { -2.641070089918234e-09, 2.864595291363663e+00 }, { -2.648745836659391e-09, 2.871678049666939e+00 }, { -2.656321859617343e-09, 2.878684676194483e+00 }, { -2.663797873558322e-09, 2.885614488280000e+00 }, { -2.671173597015318e-09, 2.892466804962122e+00 }, { -2.678448752295859e-09, 2.899240947023252e+00 }, { -2.685623065495139e-09, 2.905936237033475e+00 }, { -2.692696266503800e-09, 2.912551999389617e+00 }, { -2.699668089019767e-09, 2.919087560358171e+00 }, { -2.706538270558513e-09, 2.925542248116882e+00 }, { -2.713306552460767e-09, 2.931915392794031e+00 }, { -2.719972679905295e-09, 2.938206326512581e+00 }, { -2.726536401915442e-09, 2.944414383428562e+00 }, { -2.732997471371516e-09, 2.950538899775061e+00 }, { -2.739355645017194e-09, 2.956579213900666e+00 }, { -2.745610683471516e-09, 2.962534666313284e+00 }, { -2.751762351235315e-09, 2.968404599718795e+00 }, { -2.757810416701751e-09, 2.974188359063684e+00 }, { -2.763754652165128e-09, 2.979885291576143e+00 }, { -2.769594833827588e-09, 2.985494746805227e+00 }, { -2.775330741810390e-09, 2.991016076664491e+00 }, { -2.780962160159068e-09, 2.996448635469842e+00 }, { -2.786488876854607e-09, 3.001791779983262e+00 }, { -2.791910683818570e-09, 3.007044869450794e+00 }, { -2.797227376923695e-09, 3.012207265645876e+00 }, { -2.802438755998943e-09, 3.017278332907412e+00 }, { -2.807544624838820e-09, 3.022257438182037e+00 }, { -2.812544791210840e-09, 3.027143951064684e+00 }, { -2.817439066860792e-09, 3.031937243837070e+00 }, { -2.822227267522746e-09, 3.036636691510884e+00 }, { -2.826909212922864e-09, 3.041241671864994e+00 }, { -2.831484726789317e-09, 3.045751565488710e+00 }, { -2.835953636855826e-09, 3.050165755818853e+00 }, { -2.840315774871260e-09, 3.054483629182857e+00 }, { -2.844570976602957e-09, 3.058704574835744e+00 }, { -2.848719081844986e-09, 3.062827985002047e+00 }, { -2.852759934424164e-09, 3.066853254915581e+00 }, { -2.856693382203833e-09, 3.070779782857041e+00 }, { -2.860519277092708e-09, 3.074606970196721e+00 }, { -2.864237475047239e-09, 3.078334221430809e+00 }, { -2.867847836080156e-09, 3.081960944223928e+00 }, { -2.871350224262603e-09, 3.085486549445314e+00 }, { -2.874744507732462e-09, 3.088910451211251e+00 }, { -2.878030558696270e-09, 3.092232066921130e+00 }, { -2.881208253436038e-09, 3.095450817298478e+00 }, { -2.884277472313999e-09, 3.098566126429974e+00 }, { -2.887238099774968e-09, 3.101577421802070e+00 }, { -2.890090024353816e-09, 3.104484134342861e+00 }, { -2.892833138676371e-09, 3.107285698457308e+00 }, { -2.895467339466766e-09, 3.109981552069083e+00 }, { -2.897992527547963e-09, 3.112571136655481e+00 }, { -2.900408607848946e-09, 3.115053897289195e+00 }, { -2.902715489404992e-09, 3.117429282673042e+00 }, { -2.904913085363323e-09, 3.119696745180238e+00 }, { -2.907001312986328e-09, 3.121855740892224e+00 }, { -2.908980093652563e-09, 3.123905729634218e+00 }, { -2.910849352862924e-09, 3.125846175016163e+00 }, { -2.912609020239985e-09, 3.127676544466606e+00 }, { -2.914259029534118e-09, 3.129396309273659e+00 }, { -2.915799318622574e-09, 3.131004944618667e+00 }, { -2.917229829515169e-09, 3.132501929616775e+00 }, { -2.918550508353347e-09, 3.133886747350606e+00 }, { -2.919761305414294e-09, 3.135158884909254e+00 }, { -2.920862175112829e-09, 3.136317833424958e+00 }, { -2.921853076000972e-09, 3.137363088107359e+00 }, { -2.922733970772719e-09, 3.138294148283254e+00 }, { -2.923504826262027e-09, 3.139110517429204e+00 }, { -2.924165613447473e-09, 3.139811703211207e+00 }, { -2.924716307449950e-09, 3.140397217517018e+00 }, { -2.925156887536978e-09, 3.140866576495489e+00 }, { -2.925487337120335e-09, 3.141219300588825e+00 }, { -2.925707643758784e-09, 3.141454914570261e+00 }, { -2.925817799158535e-09, 3.141572947579352e+00 }, { -2.925817799171455e-09, 3.141572933154836e+00 }, { -2.925707643798390e-09, 3.141454409272987e+00 }, { -2.925487337185779e-09, 3.141216918378770e+00 }, { -2.925156887628892e-09, 3.140860007424112e+00 }, { -2.924716307568119e-09, 3.140383227898687e+00 }, { -2.924165613591896e-09, 3.139786135867868e+00 }, { -2.923504826432903e-09, 3.139068292003385e+00 }, { -2.922733970969412e-09, 3.138229261619561e+00 }, { -2.921853076224321e-09, 3.137268614707029e+00 }, { -2.920862175361976e-09, 3.136185925964038e+00 }, { -2.919761305690083e-09, 3.134980774833275e+00 }, { -2.918550508654911e-09, 3.133652745531368e+00 }, { -2.917229829843137e-09, 3.132201427085629e+00 }, { -2.915799318976726e-09, 3.130626413363146e+00 }, { -2.914259029914435e-09, 3.128927303107136e+00 }, { -2.912609020646661e-09, 3.127103699965947e+00 }, { -2.910849353295315e-09, 3.125155212527586e+00 }, { -2.908980094111509e-09, 3.123081454351802e+00 }, { -2.907001313470937e-09, 3.120882043999591e+00 }, { -2.904913085874448e-09, 3.118556605068443e+00 }, { -2.902715489941767e-09, 3.116104766219928e+00 }, { -2.900408608411958e-09, 3.113526161214776e+00 }, { -2.897992528137022e-09, 3.110820428940251e+00 }, { -2.895467340081818e-09, 3.107987213444579e+00 }, { -2.892833139317615e-09, 3.105026163964191e+00 }, { -2.890090025020589e-09, 3.101936934956479e+00 }, { -2.887238100468092e-09, 3.098719186130021e+00 }, { -2.884277473032614e-09, 3.095372582472161e+00 }, { -2.881208254180937e-09, 3.091896794282404e+00 }, { -2.878030559466594e-09, 3.088291497198199e+00 }, { -2.874744508528832e-09, 3.084556372228054e+00 }, { -2.871350225084755e-09, 3.080691105776848e+00 }, { -2.867847836928063e-09, 3.076695389678615e+00 }, { -2.864237475921086e-09, 3.072568921221621e+00 }, { -2.860519277991847e-09, 3.068311403179147e+00 }, { -2.856693383129018e-09, 3.063922543837792e+00 }, { -2.852759935374575e-09, 3.059402057023109e+00 }, { -2.848719082821403e-09, 3.054749662130841e+00 }, { -2.844570977604520e-09, 3.049965084150782e+00 }, { -2.840315775898525e-09, 3.045048053697736e+00 }, { -2.835953637908582e-09, 3.039998307034967e+00 }, { -2.831484727867511e-09, 3.034815586104635e+00 }, { -2.826909214026628e-09, 3.029499638550941e+00 }, { -2.822227268651470e-09, 3.024050217748861e+00 }, { -2.817439068015245e-09, 3.018467082830179e+00 }, { -2.812544792390175e-09, 3.012749998707001e+00 }, { -2.807544626043751e-09, 3.006898736100911e+00 }, { -2.802438757228650e-09, 3.000913071564665e+00 }, { -2.797227378178760e-09, 2.994792787510961e+00 }, { -2.791910685098702e-09, 2.988537672233504e+00 }, { -2.786488878159805e-09, 2.982147519935565e+00 }, { -2.780962161489413e-09, 2.975622130750641e+00 }, { -2.775330743165298e-09, 2.968961310769028e+00 }, { -2.769594835207775e-09, 2.962164872061613e+00 }, { -2.763754653569747e-09, 2.955232632701135e+00 }, { -2.757810418131543e-09, 2.948164416789036e+00 }, { -2.751762352689432e-09, 2.940960054474719e+00 }, { -2.745610684950541e-09, 2.933619381982341e+00 }, { -2.739355646520809e-09, 2.926142241629213e+00 }, { -2.732997472899722e-09, 2.918528481852205e+00 }, { -2.726536403468318e-09, 2.910777957226018e+00 }, { -2.719972681482232e-09, 2.902890528487386e+00 }, { -2.713306554062453e-09, 2.894866062556452e+00 }, { -2.706538272184154e-09, 2.886704432555728e+00 }, { -2.699668090670078e-09, 2.878405517834426e+00 }, { -2.692696268177908e-09, 2.869969203985464e+00 }, { -2.685623067193599e-09, 2.861395382869544e+00 }, { -2.678448754018380e-09, 2.852683952631486e+00 }, { -2.671173598761847e-09, 2.843834817723832e+00 }, { -2.663797875328991e-09, 2.834847888922988e+00 }, { -2.656321861411517e-09, 2.825723083350459e+00 }, { -2.648745838477759e-09, 2.816460324492298e+00 }, { -2.641070091759922e-09, 2.807059542215146e+00 }, { -2.633294910246296e-09, 2.797520672788269e+00 }, { -2.625420586667340e-09, 2.787843658897949e+00 }, { -2.617447417487602e-09, 2.778028449668942e+00 }, { -2.609375702891616e-09, 2.768075000678399e+00 }, { -2.601205746775692e-09, 2.757983273976943e+00 }, { -2.592937856733464e-09, 2.747753238101915e+00 }, { -2.584572344046340e-09, 2.737384868096553e+00 }, { -2.576109523671634e-09, 2.726878145526201e+00 }, { -2.567549714229129e-09, 2.716233058492422e+00 }, { -2.558893237991435e-09, 2.705449601651722e+00 }, { -2.550140420869302e-09, 2.694527776227857e+00 }, { -2.541291592402089e-09, 2.683467590030445e+00 }, { -2.532347085742440e-09, 2.672269057466213e+00 }, { -2.523307237646751e-09, 2.660932199557362e+00 }, { -2.514172388459584e-09, 2.649457043952206e+00 }, { -2.504942882102813e-09, 2.637843624941622e+00 }, { -2.495619066062810e-09, 2.626091983472908e+00 }, { -2.486201291375123e-09, 2.614202167160335e+00 }, { -2.476689912614465e-09, 2.602174230302269e+00 }, { -2.467085287878098e-09, 2.590008233889805e+00 }, { -2.457387778775451e-09, 2.577704245623143e+00 }, { -2.447597750411553e-09, 2.565262339920002e+00 }, { -2.437715571376127e-09, 2.552682597931055e+00 }, { -2.427741613727123e-09, 2.539965107548168e+00 }, { -2.417676252978335e-09, 2.527109963417675e+00 }, { -2.407519868085581e-09, 2.514117266951687e+00 }, { -2.397272841430131e-09, 2.500987126335739e+00 }, { -2.386935558807595e-09, 2.487719656543254e+00 }, { -2.376508409410024e-09, 2.474314979341178e+00 }, { -2.365991785814531e-09, 2.460773223303822e+00 }, { -2.355386083965131e-09, 2.447094523817833e+00 }, { -2.344691703161363e-09, 2.433279023095734e+00 }, { -2.333909046040126e-09, 2.419326870180582e+00 }, { -2.323038518562289e-09, 2.405238220956597e+00 }, { -2.312080529997549e-09, 2.391013238157397e+00 }, { -2.301035492907384e-09, 2.376652091371587e+00 }, { -2.289903823131822e-09, 2.362154957053137e+00 }, { -2.278685939771276e-09, 2.347522018525197e+00 }, { -2.267382265173420e-09, 2.332753465990296e+00 }, { -2.255993224914501e-09, 2.317849496533128e+00 }, { -2.244519247786155e-09, 2.302810314130351e+00 }, { -2.232960765776561e-09, 2.287636129652823e+00 }, { -2.221318214056095e-09, 2.272327160873552e+00 }, { -2.209592030960763e-09, 2.256883632472565e+00 }, { -2.197782657974034e-09, 2.241305776039511e+00 }, { -2.185890539712767e-09, 2.225593830081461e+00 }, { -2.173916123907886e-09, 2.209748040023618e+00 }, { -2.161859861389976e-09, 2.193768658216360e+00 }, { -2.149722206070124e-09, 2.177655943935795e+00 }, { -2.137503614923981e-09, 2.161410163388424e+00 }, { -2.125204547975352e-09, 2.145031589714984e+00 }, { -2.112825468276292e-09, 2.128520502989477e+00 }, { -2.100366841892917e-09, 2.111877190225612e+00 }, { -2.087829137884807e-09, 2.095101945374541e+00 }, { -2.075212828290086e-09, 2.078195069329960e+00 }, { -2.062518388104923e-09, 2.061156869925600e+00 }, { -2.049746295268559e-09, 2.043987661939897e+00 }, { -2.036897030642658e-09, 2.026687767092888e+00 }, { -2.023971077994576e-09, 2.009257514048162e+00 }, { -2.010968923979840e-09, 1.991697238413571e+00 }, { -1.997891058121344e-09, 1.974007282737320e+00 }, { -1.984737972794098e-09, 1.956187996511354e+00 }, { -1.971510163203686e-09, 1.938239736166060e+00 }, { -1.958208127370276e-09, 1.920162865072273e+00 }, { -1.944832366107339e-09, 1.901957753535934e+00 }, { -1.931383383005451e-09, 1.883624778799427e+00 }, { -1.917861684410531e-09, 1.865164325035177e+00 }, { -1.904267779407432e-09, 1.846576783346324e+00 }, { -1.890602179798714e-09, 1.827862551760622e+00 }, { -1.876865400086483e-09, 1.809022035228338e+00 }, { -1.863057957452539e-09, 1.790055645617624e+00 }, { -1.849180371740008e-09, 1.770963801711725e+00 }, { -1.835233165431475e-09, 1.751746929201178e+00 }, { -1.821216863631569e-09, 1.732405460681919e+00 }, { -1.807131994045840e-09, 1.712939835648088e+00 }, { -1.792979086962494e-09, 1.693350500488565e+00 }, { -1.778758675229683e-09, 1.673637908477153e+00 }, { -1.764471294238191e-09, 1.653802519770021e+00 }, { -1.750117481899733e-09, 1.633844801396848e+00 }, { -1.735697778626995e-09, 1.613765227254186e+00 }, { -1.721212727314574e-09, 1.593564278099856e+00 }, { -1.706662873315474e-09, 1.573242441540939e+00 }, { -1.692048764423848e-09, 1.552800212030258e+00 }, { -1.677370950852395e-09, 1.532238090855187e+00 }, { -1.662629985213192e-09, 1.511556586131055e+00 }, { -1.647826422494560e-09, 1.490756212788764e+00 }, { -1.632960820042537e-09, 1.469837492568651e+00 }, { -1.618033737538645e-09, 1.448800954008929e+00 }, { -1.603045736978760e-09, 1.427647132435469e+00 }, { -1.587997382653428e-09, 1.406376569953373e+00 }, { -1.572889241124034e-09, 1.384989815432507e+00 }, { -1.557721881203696e-09, 1.363487424499449e+00 }, { -1.542495873934815e-09, 1.341869959524515e+00 }, { -1.527211792568486e-09, 1.320137989611176e+00 }, { -1.511870212541253e-09, 1.298292090581491e+00 }, { -1.496471711454994e-09, 1.276332844965754e+00 }, { -1.481016869054634e-09, 1.254260841988828e+00 }, { -1.465506267206068e-09, 1.232076677556547e+00 }, { -1.449940489875303e-09, 1.209780954243628e+00 }, { -1.434320123104372e-09, 1.187374281276747e+00 }, { -1.418645754991533e-09, 1.164857274523495e+00 }, { -1.402917975667710e-09, 1.142230556475749e+00 }, { -1.387137377275425e-09, 1.119494756236361e+00 }, { -1.371304553944712e-09, 1.096650509501278e+00 }, { -1.355420101772623e-09, 1.073698458546610e+00 }, { -1.339484618799891e-09, 1.050639252211352e+00 }, { -1.323498704988051e-09, 1.027473545880543e+00 }, { -1.307462962198534e-09, 1.004202001471034e+00 }, { -1.291377994167204e-09, 9.808252874104182e-01 }, { -1.275244406484394e-09, 9.573440786237052e-01 }, { -1.259062806570190e-09, 9.337590565128454e-01 }, { -1.242833803653464e-09, 9.100709089414796e-01 }, { -1.226558008746195e-09, 8.862803302125812e-01 }, { -1.210236034623253e-09, 8.623880210538113e-01 }, { -1.193868495797618e-09, 8.383946885959868e-01 }, { -1.177456008497777e-09, 8.143010463544786e-01 }, { -1.160999190645010e-09, 7.901078142102129e-01 }, { -1.144498661828833e-09, 7.658157183877095e-01 }, { -1.127955043284965e-09, 7.414254914366063e-01 }, { -1.111368957870986e-09, 7.169378722095157e-01 }, { -1.094741030044308e-09, 6.923536058430697e-01 }, { -1.078071885836393e-09, 6.676734437331688e-01 }, { -1.061362152831423e-09, 6.428981435165511e-01 }, { -1.044612460141255e-09, 6.180284690466404e-01 }, { -1.027823438382183e-09, 5.930651903718045e-01 }, { -1.010995719652015e-09, 5.680090837138436e-01 }, { -9.941299375042378e-10, 5.428609314418970e-01 }, { -9.772267269262058e-10, 5.176215220520872e-01 }, { -9.602867243141016e-10, 4.922916501421032e-01 }, { -9.433105674499058e-10, 4.668721163885412e-01 }, { -9.262988954758817e-10, 4.413637275202624e-01 }, { -9.092523488719689e-10, 4.157672962958654e-01 }, { -8.921715694311144e-10, 3.900836414778084e-01 }, { -8.750572002347607e-10, 3.643135878065193e-01 }, { -8.579098856296589e-10, 3.384579659762392e-01 }, { -8.407302712022458e-10, 3.125176126069478e-01 }, { -8.235190037551917e-10, 2.864933702193017e-01 }, { -8.062767312831008e-10, 2.603860872080448e-01 }, { -7.890041029479477e-10, 2.341966178147619e-01 }, { -7.717017690542486e-10, 2.079258220999725e-01 }, { -7.543703810250266e-10, 1.815745659161734e-01 }, { -7.370105913774597e-10, 1.551437208801425e-01 }, { -7.196230536974697e-10, 1.286341643433767e-01 }, { -7.022084226165876e-10, 1.020467793657360e-01 }, { -6.847673537853251e-10, 7.538245468350446e-02 }, { -6.673005038502516e-10, 4.864208468284503e-02 }, { -6.498085304282128e-10, 2.182656936863137e-02 }, { -6.322920920826137e-10, -5.063185663820913e-03 }, { -6.147518482969490e-10, -3.202626926150343e-02 }, { -5.971884594516681e-10, -5.906176474160862e-02 }, { -5.796025867984469e-10, -8.616874992366363e-02 }, { -5.619948924353588e-10, -1.133462971605448e-01 }, { -5.443660392823640e-10, -1.405934733692621e-01 }, { -5.267166910556339e-10, -1.679093400638023e-01 }, { -5.090475122431451e-10, -1.952929533862739e-01 }, { -4.913591680795342e-10, -2.227433641394564e-01 }, { -4.736523245210571e-10, -2.502596178194491e-01 }, { -4.559276482202303e-10, -2.778407546490776e-01 }, { -4.381858065011618e-10, -3.054858096104932e-01 }, { -4.204274673340870e-10, -3.331938124792702e-01 }, { -4.026532993105397e-10, -3.609637878577768e-01 }, { -3.848639716178888e-10, -3.887947552098022e-01 }, { -3.670601540142443e-10, -4.166857288948674e-01 }, { -3.492425168032583e-10, -4.446357182029681e-01 }, { -3.314117308088734e-10, -4.726437273896633e-01 }, { -3.135684673501752e-10, -5.007087557112619e-01 }, { -2.957133982159296e-10, -5.288297974607742e-01 }, { -2.778471956393828e-10, -5.570058420037128e-01 }, { -2.599705322729564e-10, -5.852358738143247e-01 }, { -2.420840811628366e-10, -6.135188725122560e-01 }, { -2.241885157240923e-10, -6.418538128986450e-01 }, { -2.062845097142585e-10, -6.702396649949099e-01 }, { -1.883727372093546e-10, -6.986753940779493e-01 }, { -1.704538725773087e-10, -7.271599607197149e-01 }, { -1.525285904532877e-10, -7.556923208240308e-01 }, { -1.345975657140748e-10, -7.842714256651911e-01 }, { -1.166614734526054e-10, -8.128962219265712e-01 }, { -9.872098895260891e-11, -8.415656517393372e-01 }, { -8.077678766314517e-11, -8.702786527215916e-01 }, { -6.282954517324612e-11, -8.990341580176152e-01 }, { -4.487993718655790e-11, -9.278310963373758e-01 }, { -2.692863949561210e-11, -9.566683919968972e-01 }, { -8.976327956520795e-12, -9.855449649582175e-01 }, { 8.976321536169872e-12, -1.014459730869357e+00 }, { 2.692863307547294e-11, -1.043411601105914e+00 }, { 4.487993076694813e-11, -1.072399482811314e+00 }, { 6.282953875437751e-11, -1.101422278938424e+00 }, { 8.077678124517653e-11, -1.130478888291020e+00 }, { 9.872098253591082e-11, -1.159568205565684e+00 }, { 1.166614670373367e-10, -1.188689121393192e+00 }, { 1.345975593005002e-10, -1.217840522381901e+00 }, { 1.525285840416718e-10, -1.247021291159495e+00 }, { 1.704538661678104e-10, -1.276230306415868e+00 }, { 1.883727308022916e-10, -1.305466442946703e+00 }, { 2.062845033098954e-10, -1.334728571696106e+00 }, { 2.241885093225349e-10, -1.364015559800721e+00 }, { 2.420840747645085e-10, -1.393326270633325e+00 }, { 2.599705258779635e-10, -1.422659563847049e+00 }, { 2.778471892479898e-10, -1.452014295419243e+00 }, { 2.957133918284542e-10, -1.481389317696831e+00 }, { 3.135684609667761e-10, -1.510783479440191e+00 }, { 3.314117244297624e-10, -1.540195625869043e+00 }, { 3.492425104288060e-10, -1.569624598707558e+00 }, { 3.670601476445565e-10, -1.599069236228850e+00 }, { 3.848639652533361e-10, -1.628528373302631e+00 }, { 4.026532929512281e-10, -1.658000841439269e+00 }, { 4.204274609803869e-10, -1.687485468837799e+00 }, { 4.381858001531792e-10, -1.716981080430596e+00 }, { 4.559276418782829e-10, -1.746486497931567e+00 }, { 4.736523181853565e-10, -1.776000539882225e+00 }, { 4.913591617503452e-10, -1.805522021699094e+00 }, { 5.090475059206794e-10, -1.835049755721194e+00 }, { 5.267166847401562e-10, -1.864582551257262e+00 }, { 5.443660329740862e-10, -1.894119214633676e+00 }, { 5.619948861345454e-10, -1.923658549242818e+00 }, { 5.796025805053097e-10, -1.953199355591180e+00 }, { 5.971884531664190e-10, -1.982740431347091e+00 }, { 6.147518420199055e-10, -2.012280571390674e+00 }, { 6.322920858139346e-10, -2.041818567861395e+00 }, { 6.498085241682158e-10, -2.071353210208005e+00 }, { 6.673004975990425e-10, -2.100883285238127e+00 }, { 6.847673475432746e-10, -2.130407577166309e+00 }, { 7.022084163838545e-10, -2.159924867664933e+00 }, { 7.196230474743716e-10, -2.189433935913779e+00 }, { 7.370105851640495e-10, -2.218933558650552e+00 }, { 7.543703748217808e-10, -2.248422510220072e+00 }, { 7.717017628611672e-10, -2.277899562625407e+00 }, { 7.890040967654542e-10, -2.307363485579104e+00 }, { 8.062767251113011e-10, -2.336813046552684e+00 }, { 8.235189975944034e-10, -2.366247010829556e+00 }, { 8.407302650525749e-10, -2.395664141553858e+00 }, { 8.579098794915287e-10, -2.425063199784153e+00 }, { 8.750571941082773e-10, -2.454442944543319e+00 }, { 8.921715633164894e-10, -2.483802132872044e+00 }, { 9.092523427695200e-10, -2.513139519878584e+00 }, { 9.262988893857148e-10, -2.542453858792682e+00 }, { 9.433105613723914e-10, -2.571743901017465e+00 }, { 9.602867182493987e-10, -2.601008396180870e+00 }, { 9.772267208744730e-10, -2.630246092190425e+00 }, { 9.941299314658458e-10, -2.659455735283526e+00 }, { 1.010995713627070e-09, -2.688636070081818e+00 }, { 1.027823432371055e-09, -2.717785839644439e+00 }, { 1.044612454143997e-09, -2.746903785521352e+00 }, { 1.061362146848353e-09, -2.775988647805256e+00 }, { 1.078071879867828e-09, -2.805039165187255e+00 }, { 1.094741024090249e-09, -2.834054075009077e+00 }, { 1.111368951931856e-09, -2.863032113318052e+00 }, { 1.127955037360817e-09, -2.891972014920939e+00 }, { 1.144498655920037e-09, -2.920872513436805e+00 }, { 1.160999184751779e-09, -2.949732341353290e+00 }, { 1.177456002620215e-09, -2.978550230079517e+00 }, { 1.193868489936097e-09, -3.007324910002949e+00 }, { 1.210236028777826e-09, -3.036055110540183e+00 }, { 1.226558002917232e-09, -3.064739560196251e+00 }, { 1.242833797841123e-09, -3.093376986616735e+00 }, { 1.259062800774685e-09, -3.121966116643377e+00 }, { 1.275244400705935e-09, -3.150505676371791e+00 }, { 1.291377988406056e-09, -3.178994391202159e+00 }, { 1.307462956454857e-09, -3.207430985899192e+00 }, { 1.323498699262108e-09, -3.235814184645077e+00 }, { 1.339484613091842e-09, -3.264142711097884e+00 }, { 1.355420096082785e-09, -3.292415288443373e+00 }, { 1.371304548273191e-09, -3.320630639454825e+00 }, { 1.387137371622433e-09, -3.348787486547389e+00 }, { 1.402917970033511e-09, -3.376884551834256e+00 }, { 1.418645749376393e-09, -3.404920557184582e+00 }, { 1.434320117508396e-09, -3.432894224276359e+00 }, { 1.449940484298756e-09, -3.460804274656981e+00 }, { 1.465506261649108e-09, -3.488649429796768e+00 }, { 1.481016863517580e-09, -3.516428411149154e+00 }, { 1.496471705937951e-09, -3.544139940202303e+00 }, { 1.511870207044433e-09, -3.571782738540999e+00 }, { 1.527211787092206e-09, -3.599355527901174e+00 }, { 1.542495868479076e-09, -3.626857030226671e+00 }, { 1.557721875768920e-09, -3.654285967729458e+00 }, { 1.572889235710329e-09, -3.681641062941412e+00 }, { 1.587997377261005e-09, -3.708921038776707e+00 }, { 1.603045731607830e-09, -3.736124618586623e+00 }, { 1.618033732189314e-09, -3.763250526218862e+00 }, { 1.632960814715177e-09, -3.790297486071938e+00 }, { 1.647826417189275e-09, -3.817264223155802e+00 }, { 1.662629979930247e-09, -3.844149463148589e+00 }, { 1.677370945591844e-09, -3.870951932452996e+00 }, { 1.692048759186008e-09, -3.897670358257890e+00 }, { 1.706662868100504e-09, -3.924303468590212e+00 }, { 1.721212722122685e-09, -3.950849992378278e+00 }, { 1.735697773458400e-09, -3.977308659506432e+00 }, { 1.750117476754591e-09, -4.003678200876669e+00 }, { 1.764471289116712e-09, -4.029957348461003e+00 }, { 1.778758670132079e-09, -4.056144835364877e+00 }, { 1.792979081888926e-09, -4.082239395882965e+00 }, { 1.807131988996465e-09, -4.108239765556996e+00 }, { 1.821216858606652e-09, -4.134144681236933e+00 }, { 1.835233160431175e-09, -4.159952881133585e+00 }, { 1.849180366764537e-09, -4.185663104882633e+00 }, { 1.863057952502055e-09, -4.211274093599509e+00 }, { 1.876865395161145e-09, -4.236784589940537e+00 }, { 1.890602174898734e-09, -4.262193338157148e+00 }, { 1.904267774533022e-09, -4.287499084158302e+00 }, { 1.917861679562008e-09, -4.312700575567174e+00 }, { 1.931383378182392e-09, -4.337796561778708e+00 }, { 1.944832361310856e-09, -4.362785794021793e+00 }, { 1.958208122599839e-09, -4.387667025411434e+00 }, { 1.971510158459931e-09, -4.412439011013396e+00 }, { 1.984737968076495e-09, -4.437100507898339e+00 }, { 1.997891053431005e-09, -4.461650275204912e+00 }, { 2.010968919316289e-09, -4.486087074191693e+00 }, { 2.023971073358447e-09, -4.510409668301784e+00 }, { 2.036897026033634e-09, -4.534616823217992e+00 }, { 2.049746290686799e-09, -4.558707306921882e+00 }, { 2.062518383551274e-09, -4.582679889754607e+00 }, { 2.075212823764071e-09, -4.606533344469879e+00 }, { 2.087829133387063e-09, -4.630266446298172e+00 }, { 2.100366837422912e-09, -4.653877973001258e+00 }, { 2.112825463835087e-09, -4.677366704934605e+00 }, { 2.125204543562522e-09, -4.700731425099899e+00 }, { 2.137503610540056e-09, -4.723970919208608e+00 }, { 2.149722201714786e-09, -4.747083975738060e+00 }, { 2.161859857063438e-09, -4.770069385989595e+00 }, { 2.173916119610994e-09, -4.792925944149308e+00 }, { 2.185890535445098e-09, -4.815652447340950e+00 }, { 2.197782653735957e-09, -4.838247695689436e+00 }, { 2.209592026751962e-09, -4.860710492376411e+00 }, { 2.221318209877576e-09, -4.883039643700314e+00 }, { 2.232960761627846e-09, -4.905233959130168e+00 }, { 2.244519243667616e-09, -4.927292251368517e+00 }, { 2.255993220826402e-09, -4.949213336406265e+00 }, { 2.267382261115285e-09, -4.970996033581527e+00 }, { 2.278685935744269e-09, -4.992639165639563e+00 }, { 2.289903819135414e-09, -5.014141558784778e+00 }, { 2.301035488942000e-09, -5.035502042744443e+00 }, { 2.312080526062763e-09, -5.056719450823151e+00 }, { 2.323038514659161e-09, -5.077792619963239e+00 }, { 2.333909042168180e-09, -5.098720390796817e+00 }, { 2.344691699320969e-09, -5.119501607709159e+00 }, { 2.355386080156553e-09, -5.140135118892792e+00 }, { 2.365991782037187e-09, -5.160619776404897e+00 }, { 2.376508405665132e-09, -5.180954436227641e+00 }, { 2.386935555094626e-09, -5.201137958319343e+00 }, { 2.397272837749508e-09, -5.221169206676762e+00 }, { 2.407519864436774e-09, -5.241047049389645e+00 }, { 2.417676249362563e-09, -5.260770358700167e+00 }, { 2.427741610143750e-09, -5.280338011053974e+00 }, { 2.437715567825576e-09, -5.299748887163106e+00 }, { 2.447597746894037e-09, -5.319001872058887e+00 }, { 2.457387775290440e-09, -5.338095855149190e+00 }, { 2.467085284426756e-09, -5.357029730277389e+00 }, { 2.476689909196263e-09, -5.375802395772283e+00 }, { 2.486201287990485e-09, -5.394412754510426e+00 }, { 2.495619062711154e-09, -5.412859713968929e+00 }, { 2.504942878785408e-09, -5.431142186284682e+00 }, { 2.514172385175743e-09, -5.449259088303476e+00 }, { 2.523307234396791e-09, -5.467209341642627e+00 }, { 2.532347082526785e-09, -5.484991872743321e+00 }, { 2.541291589219998e-09, -5.502605612925014e+00 }, { 2.550140417722072e-09, -5.520049498445633e+00 }, { 2.558893234878378e-09, -5.537322470548212e+00 }, { 2.567549711150773e-09, -5.554423475524196e+00 }, { 2.576109520627371e-09, -5.571351464763084e+00 }, { 2.584572341037361e-09, -5.588105394812198e+00 }, { 2.592937853759161e-09, -5.604684227423386e+00 }, { 2.601205743836355e-09, -5.621086929615246e+00 }, { 2.609375699987564e-09, -5.637312473723475e+00 }, { 2.617447414618146e-09, -5.653359837454964e+00 }, { 2.625420583833750e-09, -5.669228003945694e+00 }, { 2.633294907447937e-09, -5.684915961806963e+00 }, { 2.641070088997271e-09, -5.700422705186584e+00 }, { 2.648745835750128e-09, -5.715747233817712e+00 }, { 2.656321858720176e-09, -5.730888553077074e+00 }, { 2.663797872673252e-09, -5.745845674030161e+00 }, { 2.671173596142054e-09, -5.760617613492118e+00 }, { 2.678448751434797e-09, -5.775203394076705e+00 }, { 2.685623064645538e-09, -5.789602044248679e+00 }, { 2.692696265666640e-09, -5.803812598380606e+00 }, { 2.699668088194915e-09, -5.817834096797069e+00 }, { 2.706538269745573e-09, -5.831665585834668e+00 }, { 2.713306551659817e-09, -5.845306117889361e+00 }, { 2.719972679116734e-09, -5.858754751472542e+00 }, { 2.726536401139295e-09, -5.872010551255358e+00 }, { 2.732997470607439e-09, -5.885072588127400e+00 }, { 2.739355644265558e-09, -5.897939939244211e+00 }, { 2.745610682731633e-09, -5.910611688078208e+00 }, { 2.751762350508137e-09, -5.923086924473290e+00 }, { 2.757810415987146e-09, -5.935364744687794e+00 }, { 2.763754651462700e-09, -5.947444251452243e+00 }, { 2.769594833137415e-09, -5.959324554015538e+00 }, { 2.775330741132843e-09, -5.971004768198829e+00 }, { 2.780962159494174e-09, -5.982484016437981e+00 }, { 2.786488876202047e-09, -5.993761427840588e+00 }, { 2.791910683178690e-09, -6.004836138231525e+00 }, { 2.797227376295779e-09, -6.015707290202086e+00 }, { 2.802438755383971e-09, -6.026374033162623e+00 }, { 2.807544624236659e-09, -6.036835523383457e+00 }, { 2.812544790621093e-09, -6.047090924050914e+00 }, { 2.817439066283459e-09, -6.057139405311101e+00 }, { 2.822227266958278e-09, -6.066980144322601e+00 }, { 2.826909212371261e-09, -6.076612325295799e+00 }, { 2.831484726250221e-09, -6.086035139548830e+00 }, { 2.835953636329660e-09, -6.095247785550617e+00 }, { 2.840315774357203e-09, -6.104249468967751e+00 }, { 2.844570976102082e-09, -6.113039402715685e+00 }, { 2.848719081357095e-09, -6.121616806996519e+00 }, { 2.852759933948860e-09, -6.129980909353977e+00 }, { 2.856693381741114e-09, -6.138130944714082e+00 }, { 2.860519276643053e-09, -6.146066155436312e+00 }, { 2.864237474610633e-09, -6.153785791350256e+00 }, { 2.867847835656203e-09, -6.161289109809551e+00 }, { 2.871350223851726e-09, -6.168575375732642e+00 }, { 2.874744507333867e-09, -6.175643861647406e+00 }, { 2.878030558310989e-09, -6.182493847739853e+00 }, { 2.881208253063899e-09, -6.189124621889823e+00 }, { 2.884277471954592e-09, -6.195535479723423e+00 }, { 2.887238099428306e-09, -6.201725724651554e+00 }, { 2.890090024020323e-09, -6.207694667918394e+00 }, { 2.892833138356060e-09, -6.213441628635915e+00 }, { 2.895467339159240e-09, -6.218965933835304e+00 }, { 2.897992527253659e-09, -6.224266918505075e+00 }, { 2.900408607567016e-09, -6.229343925633495e+00 }, { 2.902715489136496e-09, -6.234196306254763e+00 }, { 2.904913085108075e-09, -6.238823419482017e+00 }, { 2.907001312743911e-09, -6.243224632557377e+00 }, { 2.908980093422997e-09, -6.247399320887848e+00 }, { 2.910849352646620e-09, -6.251346868091392e+00 }, { 2.912609020036956e-09, -6.255066666028537e+00 }, { 2.914259029343965e-09, -6.258558114851525e+00 }, { 2.915799318445710e-09, -6.261820623039620e+00 }, { 2.917229829350759e-09, -6.264853607438842e+00 }, { 2.918550508202463e-09, -6.267656493305673e+00 }, { 2.919761305276718e-09, -6.270228714337005e+00 }, { 2.920862174988150e-09, -6.272569712717951e+00 }, { 2.921853075889193e-09, -6.274678939154603e+00 }, { 2.922733970674264e-09, -6.276555852917634e+00 }, { 2.923504826176907e-09, -6.278199921870962e+00 }, { 2.924165613375264e-09, -6.279610622518139e+00 }, { 2.924716307391075e-09, -6.280787440034993e+00 }, { 2.925156887490598e-09, -6.281729868306345e+00 }, { 2.925487337087508e-09, -6.282437409966992e+00 }, { 2.925707643739298e-09, -6.282909576428774e+00 }, { 2.925817799151970e-09, -6.283145887925411e+00 }, gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fxpt_nco.h0000664000175000017500000000236512207440367023001 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_FXPT_NCO_H #define INCLUDED_QA_GR_FXPT_NCO_H #include #include class qa_fxpt_nco : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fxpt_nco); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1(); void t2(); void t3(); }; #endif /* INCLUDED_QA_GR_FXPT_NCO_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_math.h0000664000175000017500000000243012207440367022103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_GR_MATH_H_ #define _QA_GR_MATH_H_ #include #include class qa_math : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_math); CPPUNIT_TEST(test_binary_slicer1); CPPUNIT_TEST(test_quad_0deg_slicer1); CPPUNIT_TEST(test_quad_45deg_slicer1); CPPUNIT_TEST_SUITE_END(); private: void test_binary_slicer1(); void test_quad_0deg_slicer1(); void test_quad_45deg_slicer1(); }; #endif /* _QA_GR_MATH_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fxpt_vco.cc0000664000175000017500000000756212207702530023144 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include static const float SIN_COS_TOLERANCE = 1e-5; static const float SIN_COS_K = 0.42; static const float SIN_COS_AMPL = 0.8; static const int SIN_COS_BLOCK_SIZE = 100000; static double max_d(double a, double b) { return fabs(a) > fabs(b) ? a : b; } void qa_fxpt_vco::t0() { gr::vco ref_vco; gr::fxpt_vco new_vco; double max_error = 0, max_phase_error = 0; float input[SIN_COS_BLOCK_SIZE]; for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { input[i] = sin(double(i)); } for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { float ref_cos = ref_vco.cos(); float new_cos = new_vco.cos(); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_cos, new_cos, SIN_COS_TOLERANCE); max_error = max_d(max_error, ref_cos-new_cos); ref_vco.adjust_phase(input[i]); new_vco.adjust_phase(input[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_vco.get_phase(), new_vco.get_phase(), SIN_COS_TOLERANCE); max_phase_error = max_d(max_phase_error, ref_vco.get_phase()-new_vco.get_phase()); } // printf ("Fxpt max error %.9f, max phase error %.9f\n", max_error, max_phase_error); } void qa_fxpt_vco::t1() { gr::vco ref_vco; gr::fxpt_vco new_vco; float ref_block[SIN_COS_BLOCK_SIZE]; float new_block[SIN_COS_BLOCK_SIZE]; float input[SIN_COS_BLOCK_SIZE]; double max_error = 0; for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { input[i] = sin(double(i)); } ref_vco.cos(ref_block, input, SIN_COS_BLOCK_SIZE, SIN_COS_K, SIN_COS_AMPL); new_vco.cos(new_block, input, SIN_COS_BLOCK_SIZE, SIN_COS_K, SIN_COS_AMPL); for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_block[i], new_block[i], SIN_COS_TOLERANCE); max_error = max_d(max_error, ref_block[i]-new_block[i]); } CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_vco.get_phase(), new_vco.get_phase(), SIN_COS_TOLERANCE); // printf ("Fxpt max error %.9f, max phase error %.9f\n", max_error, ref_vco.get_phase()-new_vco.get_phase()); } void qa_fxpt_vco::t2() { gr::vco ref_vco; gr::fxpt_vco new_vco; gr_complex ref_block[SIN_COS_BLOCK_SIZE]; gr_complex new_block[SIN_COS_BLOCK_SIZE]; float input[SIN_COS_BLOCK_SIZE]; double max_error = 0; for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { input[i] = sin(double(i)); } ref_vco.sincos(ref_block, input, SIN_COS_BLOCK_SIZE, SIN_COS_K, SIN_COS_AMPL); new_vco.sincos(new_block, input, SIN_COS_BLOCK_SIZE, SIN_COS_K, SIN_COS_AMPL); for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { CPPUNIT_ASSERT_COMPLEXES_EQUAL(ref_block[i], new_block[i], SIN_COS_TOLERANCE); max_error = max_d(max_error, abs(ref_block[i]-new_block[i])); } CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_vco.get_phase(), new_vco.get_phase(), SIN_COS_TOLERANCE); // printf ("Fxpt max error %.9f, max phase error %.9f\n", max_error, ref_vco.get_phase()-new_vco.get_phase()); } void qa_fxpt_vco::t3() { } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/gen_sine_table.py0000775000175000017500000000430112207440367023632 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math import sys def wrap (x): if x >= 2**31: return x - 2**32 return x def gen_approx_table (f, nentries, min_x, max_x): """return a list of nentries containing tuples of the form: (m, c, abs_error). min_x and max_x specify the domain of the table. """ r = [] incx = float (max_x - min_x) / nentries for i in range (nentries): a = (i * incx) + min_x b = ((i + 1) * incx) + min_x m = (f(b)-f(a))/(b-a) c = (3*a+b)*(f(a)-f(b))/(4*(b-a)) + (f((a+b)/2) + f(a))/2 abs_error = c+m*a-f(a) r.append ((m, c, abs_error)) return r def scaled_sine (x): return math.sin (x * math.pi / 2**31) def gen_sine_table (): nbits = 10 nentries = 2**nbits # min_x = -2**31 # max_x = 2**31-1 min_x = 0 max_x = 2**32-1 t = gen_approx_table (scaled_sine, nentries, min_x, max_x) max_error = 0 for e in t: max_error = max (max_error, abs (e[2])) # sys.stdout.write ('static const int WORDBITS = 32;\n') # sys.stdout.write ('static const int NBITS = %d;\n' % (nbits,)) sys.stdout.write (' // max_error = %22.15e\n' % (max_error,)) # sys.stdout.write ('static const double sine_table[%d][2] = {\n'% (nentries,)) for e in t: sys.stdout.write (' { %22.15e, %22.15e },\n' % (2 * e[0], e[1])) # sys.stdout.write ('};\n') if __name__ == '__main__': gen_sine_table () gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_math.cc0000664000175000017500000000571112207440367022246 0ustar jcorganjcorgan/* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include void qa_math::test_binary_slicer1() { float x[5] = {-1, -0.5, 0, 0.5, 1.0}; unsigned int z[5] = {0, 0, 1, 1, 1}; unsigned int y; //printf("\nBinary\n"); for(unsigned int i = 0; i < 5; i++) { y = gr::binary_slicer(x[i]); //printf("in: %f out: %d desired: %d\n", x[i], y, z[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(y, z[i], 1e-9); } //printf("\nBranchless Binary\n"); for (unsigned int i = 0; i < 5; i++) { y = gr::branchless_binary_slicer(x[i]); //printf("in: %f out: %d desired: %d\n", x[i], y, z[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(y, z[i], 1e-9); } } void qa_math::test_quad_0deg_slicer1() { gr_complex x[4] = {gr_complex(1, 0), gr_complex(0, 1), gr_complex(-1, 0), gr_complex(0, -1)}; unsigned int z[4] = {0, 1, 2, 3}; unsigned int y; //printf("\nQuad0\n"); for (unsigned int i = 0; i < 4; i++) { y = gr::quad_0deg_slicer(x[i]); //printf("in: %.4f+j%.4f out: %d desired: %d\n", x[i].real(), x[i].imag(), y, z[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(y, z[i], 1e-9); } //printf("\nBranchless Quad0\n"); for (unsigned int i = 0; i < 4; i++) { y = gr::branchless_quad_0deg_slicer(x[i]); //printf("in: %.4f+j%.4f out: %d desired: %d\n", x[i].real(), x[i].imag(), y, z[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(y, z[i], 1e-9); } } void qa_math::test_quad_45deg_slicer1() { gr_complex x[4] = {gr_complex(0.707, 0.707), gr_complex(-0.707, 0.707), gr_complex(-0.707, -0.707), gr_complex(0.707, -0.707)}; unsigned int z[4] = {0, 1, 2, 3}; unsigned int y; //printf("\nQuad45\n"); for (unsigned int i = 0; i < 4; i++) { y = gr::quad_45deg_slicer(x[i]); //printf("in: %.4f+j%.4f out: %d desired: %d\n", x[i].real(), x[i].imag(), y, z[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(y, z[i], 1e-9); } //printf("\nBranchless Quad45\n"); for (unsigned int i = 0; i < 4; i++) { y = gr::branchless_quad_45deg_slicer(x[i]); //printf("in: %.4f+j%.4f out: %d desired: %d\n", x[i].real(), x[i].imag(), y, z[i]); CPPUNIT_ASSERT_DOUBLES_EQUAL(y, z[i], 1e-9); } } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fxpt.cc0000664000175000017500000000732212207440367022276 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include static const float SIN_COS_TOLERANCE = 1e-5; void qa_fxpt::t0() { CPPUNIT_ASSERT_DOUBLES_EQUAL(M_PI/2, gr::fxpt::fixed_to_float(0x40000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, gr::fxpt::fixed_to_float(0x00000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(-M_PI, gr::fxpt::fixed_to_float(0x80000000), SIN_COS_TOLERANCE); if(0) { /* * These are disabled because of some precision issues. * * Different compilers seem to have different opinions on whether * the calulations are done single or double (or extended) * precision. Any of the answers are fine for our real purpose, but * sometimes the answer is off by a few bits at the bottom. * Hence, the disabled check. */ CPPUNIT_ASSERT_EQUAL((gr_int32)0x40000000, gr::fxpt::float_to_fixed(M_PI/2)); CPPUNIT_ASSERT_EQUAL((gr_int32)0, gr::fxpt::float_to_fixed(0)); CPPUNIT_ASSERT_EQUAL((gr_int32)0x80000000, gr::fxpt::float_to_fixed(-M_PI)); } } void qa_fxpt::t1() { CPPUNIT_ASSERT_DOUBLES_EQUAL( 0, gr::fxpt::sin(0x00000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL( 0.707106781, gr::fxpt::sin(0x20000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL( 1, gr::fxpt::sin(0x40000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL( 0.707106781, gr::fxpt::sin(0x60000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL( 0, gr::fxpt::sin(0x7fffffff), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL( 0, gr::fxpt::sin(0x80000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL( 0, gr::fxpt::sin(0x80000001), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(-1, gr::fxpt::sin(-0x40000000), SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(-0.707106781, gr::fxpt::sin(-0x20000000), SIN_COS_TOLERANCE); for(float p = -M_PI; p < M_PI; p += 2 * M_PI / 3600) { float expected = sin(p); float actual = gr::fxpt::sin(gr::fxpt::float_to_fixed (p)); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected, actual, SIN_COS_TOLERANCE); } } void qa_fxpt::t2() { for(float p = -M_PI; p < M_PI; p += 2 * M_PI / 3600) { float expected = cos(p); float actual = gr::fxpt::cos(gr::fxpt::float_to_fixed(p)); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected, actual, SIN_COS_TOLERANCE); } } void qa_fxpt::t3() { for(float p = -M_PI; p < M_PI; p += 2 * M_PI / 3600) { float expected_sin = sin(p); float expected_cos = cos(p); float actual_sin; float actual_cos; gr::fxpt::sincos(gr::fxpt::float_to_fixed (p), &actual_sin, &actual_cos); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected_sin, actual_sin, SIN_COS_TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(expected_cos, actual_cos, SIN_COS_TOLERANCE); } } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/fxpt.cc0000664000175000017500000000214712207440367021615 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { const float fxpt::s_sine_table[1 << NBITS][2] = { #include "sine_table.h" }; const float fxpt::PI = 3.14159265358979323846; const float fxpt::TWO_TO_THE_31 = 2147483648.0; } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/vco.h0000664000175000017500000000563312207702530021261 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _GR_VCO_H_ #define _GR_VCO_H_ #include #include #include #include namespace gr { /*! * \brief base class template for Voltage Controlled Oscillator (VCO) * \ingroup misc */ template class vco { public: vco() : d_phase(0) {} virtual ~vco() {} // radians void set_phase(double angle) { d_phase = angle; } void adjust_phase(double delta_phase) { d_phase += delta_phase; if(fabs (d_phase) > M_PI){ while(d_phase > M_PI) d_phase -= 2*M_PI; while(d_phase < -M_PI) d_phase += 2*M_PI; } } double get_phase() const { return d_phase; } // compute sin and cos for current phase angle void sincos(float *sinx, float *cosx) const; void sincos(gr_complex *output, const float *input, int noutput_items, double k, double ampl = 1.0); // compute cos or sin for current phase angle float cos() const { return std::cos(d_phase); } float sin() const { return std::sin(d_phase); } // compute a block at a time void cos(float *output, const float *input, int noutput_items, double k, double ampl = 1.0); protected: double d_phase; }; template void vco::sincos(float *sinx, float *cosx) const { gr::sincosf(d_phase, sinx, cosx); } template void vco::sincos(gr_complex *output, const float *input, int noutput_items, double k, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = gr_complex(cos() * ampl, sin() * ampl); adjust_phase(input[i] * k); } } template void vco::cos(float *output, const float *input, int noutput_items, double k, double ampl) { for(int i = 0; i < noutput_items; i++) { output[i] = cos() * ampl; adjust_phase(input[i] * k); } } } /* namespace gr */ #endif /* _GR_VCO_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/random.cc0000664000175000017500000001060712207440367022114 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * Copyright 1997 Massachusetts Institute of Technology * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of M.I.T. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. M.I.T. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * */ #ifdef HAVE_CONFIG_H #include #endif #include #include namespace gr { #define IA 16807 #define IM 2147483647 #define AM (1.0/IM) #define IQ 127773 #define IR 2836 #define NDIV (1+(IM-1)/NTAB) #define EPS 1.2e-7 #define RNMX (1.0-EPS) random::random(long seed) { reseed(seed); } void random::reseed(long seed) { d_seed = seed; d_iy = 0; for(int i = 0; i < NTAB; i++) d_iv[i] = 0; d_iset = 0; d_gset = 0; } /* * This looks like it returns a uniform random deviate between 0.0 and 1.0 * It looks similar to code from "Numerical Recipes in C". */ float random::ran1() { int j; long k; float temp; if(d_seed <= 0 || !d_iy) { if(-d_seed < 1) d_seed=1; else d_seed = -d_seed; for(j=NTAB+7;j>=0;j--) { k=d_seed/IQ; d_seed=IA*(d_seed-k*IQ)-IR*k; if(d_seed < 0) d_seed += IM; if(j < NTAB) d_iv[j] = d_seed; } d_iy=d_iv[0]; } k=(d_seed)/IQ; d_seed=IA*(d_seed-k*IQ)-IR*k; if(d_seed < 0) d_seed += IM; j=d_iy/NDIV; d_iy=d_iv[j]; d_iv[j] = d_seed; temp=AM * d_iy; if(temp > RNMX) temp = RNMX; return temp; } /* * Returns a normally distributed deviate with zero mean and variance 1. * Also looks like it's from "Numerical Recipes in C". */ float random::gasdev() { float fac,rsq,v1,v2; d_iset = 1 - d_iset; if(d_iset) { do { v1=2.0*ran1()-1.0; v2=2.0*ran1()-1.0; rsq=v1*v1+v2*v2; } while(rsq >= 1.0 || rsq == 0.0); fac= sqrt(-2.0*log(rsq)/rsq); d_gset=v1*fac; return v2*fac; } return d_gset; } /* * Copied from The KC7WW / OH2BNS Channel Simulator * FIXME Need to check how good this is at some point */ float random::laplacian() { float z = ran1(); if(z < 0.5) return log(2.0 * z) / M_SQRT2; else return -log(2.0 * (1.0 - z)) / M_SQRT2; } /* * Copied from The KC7WW / OH2BNS Channel Simulator * FIXME Need to check how good this is at some point */ // 5 => scratchy, 8 => Geiger float random::impulse(float factor = 5) { float z = -M_SQRT2 * log(ran1()); if(fabsf(z) <= factor) return 0.0; else return z; } /* * Complex rayleigh is really gaussian I and gaussian Q * It can also be generated by real rayleigh magnitude and * uniform random angle * Adapted from The KC7WW / OH2BNS Channel Simulator * FIXME Need to check how good this is at some point */ gr_complex random::rayleigh_complex() { return gr_complex(gasdev(),gasdev()); } /* Other option mag = rayleigh(); ang = 2.0 * M_PI * RNG(); *Rx = rxx * cos(z); *Iy = rxx * sin(z); */ float random::rayleigh() { return sqrt(-2.0 * log(ran1())); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_sincos.cc0000664000175000017500000000330412207440367022607 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include void qa_sincos::t1() { static const unsigned int N = 1000; double c_sin, c_cos; double gr_sin, gr_cos; for(unsigned i = 0; i < N; i++) { double x = i/100.0; c_sin = sin(x); c_cos = cos(x); gr::sincos(x, &gr_sin, &gr_cos); CPPUNIT_ASSERT_DOUBLES_EQUAL(c_sin, gr_sin, 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL(c_cos, gr_cos, 0.0001); } } void qa_sincos::t2() { static const unsigned int N = 1000; float c_sin, c_cos; float gr_sin, gr_cos; for(unsigned i = 0; i < N; i++) { float x = i/100.0; c_sin = sinf(x); c_cos = cosf(x); gr::sincosf(x, &gr_sin, &gr_cos); CPPUNIT_ASSERT_DOUBLES_EQUAL(c_sin, gr_sin, 0.0001); CPPUNIT_ASSERT_DOUBLES_EQUAL(c_cos, gr_cos, 0.0001); } } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fxpt_vco.h0000664000175000017500000000237212207440367023007 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_FXPT_VCO_H #define INCLUDED_QA_GR_FXPT_VCO_H #include #include class qa_fxpt_vco : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fxpt_vco); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1(); void t2(); void t3(); }; #endif /* INCLUDED_QA_GR_FXPT_VCO_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fast_atan2f.cc0000664000175000017500000000252612236474522023510 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include void qa_fast_atan2f::t1() { static const unsigned int N = 100; float c_atan2; float gr_atan2f; for(float i = -N/2; i < N/2; i++) { for(float j =-N/2; i < N/2; i++) { float x = i/10.0; float y = j/10.0; c_atan2 = atan2(x, y); gr_atan2f = gr::fast_atan2f(x, y); CPPUNIT_ASSERT_DOUBLES_EQUAL(c_atan2, gr_atan2f, 0.0001); } } } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fxpt_nco.cc0000664000175000017500000000702412207440367023134 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include static const float SIN_COS_TOLERANCE = 1e-5; //static const float SIN_COS_FREQ = 5003; static const float SIN_COS_FREQ = 4096; static const int SIN_COS_BLOCK_SIZE = 100000; static double max_d(double a, double b) { return fabs(a) > fabs(b) ? a : b; } void qa_fxpt_nco::t0() { gr::nco ref_nco; gr::fxpt_nco new_nco; double max_error = 0, max_phase_error = 0; ref_nco.set_freq((float)(2 * M_PI / SIN_COS_FREQ)); new_nco.set_freq((float)(2 * M_PI / SIN_COS_FREQ)); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_nco.get_freq(), new_nco.get_freq(), SIN_COS_TOLERANCE); for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { float ref_sin = ref_nco.sin(); float new_sin = new_nco.sin(); //printf ("i = %6d\n", i); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_sin, new_sin, SIN_COS_TOLERANCE); max_error = max_d(max_error, ref_sin-new_sin); float ref_cos = ref_nco.cos(); float new_cos = new_nco.cos(); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_cos, new_cos, SIN_COS_TOLERANCE); max_error = max_d(max_error, ref_cos-new_cos); ref_nco.step(); new_nco.step(); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_nco.get_phase(), new_nco.get_phase(), SIN_COS_TOLERANCE); max_phase_error = max_d(max_phase_error, ref_nco.get_phase()-new_nco.get_phase()); } // printf ("Fxpt max error %.9f, max phase error %.9f\n", max_error, max_phase_error); } void qa_fxpt_nco::t1() { gr::nco ref_nco; gr::fxpt_nco new_nco; gr_complex ref_block[SIN_COS_BLOCK_SIZE]; gr_complex new_block[SIN_COS_BLOCK_SIZE]; double max_error = 0; ref_nco.set_freq((float)(2 * M_PI / SIN_COS_FREQ)); new_nco.set_freq((float)(2 * M_PI / SIN_COS_FREQ)); CPPUNIT_ASSERT_DOUBLES_EQUAL(ref_nco.get_freq(), new_nco.get_freq(), SIN_COS_TOLERANCE); ref_nco.sincos((gr_complex*)ref_block, SIN_COS_BLOCK_SIZE); new_nco.sincos((gr_complex*)new_block, SIN_COS_BLOCK_SIZE); for(int i = 0; i < SIN_COS_BLOCK_SIZE; i++) { CPPUNIT_ASSERT_DOUBLES_EQUAL (ref_block[i].real(), new_block[i].real(), SIN_COS_TOLERANCE); max_error = max_d (max_error, ref_block[i].real()-new_block[i].real()); CPPUNIT_ASSERT_DOUBLES_EQUAL (ref_block[i].imag(), new_block[i].imag(), SIN_COS_TOLERANCE); max_error = max_d (max_error, ref_block[i].imag()-new_block[i].imag()); } CPPUNIT_ASSERT_DOUBLES_EQUAL (ref_nco.get_phase(), new_nco.get_phase(), SIN_COS_TOLERANCE); // printf ("Fxpt max error %.9f, max phase error %.9f\n", max_error, max_phase_error); } void qa_fxpt_nco::t2() { } void qa_fxpt_nco::t3() { } gnuradio-3.7.2.1/gnuradio-runtime/lib/math/qa_fxpt.h0000664000175000017500000000234212207440367022135 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_FXPT_H #define INCLUDED_QA_GR_FXPT_H #include #include class qa_fxpt : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_fxpt); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1(); void t2(); void t3(); }; #endif /* INCLUDED_QA_GR_FXPT_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/math/sincos.cc0000664000175000017500000000334212207440367022130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef _GNU_SOURCE #define _GNU_SOURCE // ask for GNU extensions if available #endif #include #include namespace gr { #if defined (HAVE_SINCOS) void sincos(double x, double *sinx, double *cosx) { ::sincos(x, sinx, cosx); } #else void sincos(double x, double *sinx, double *cosx) { *sinx = ::sin(x); *cosx = ::cos(x); } #endif // ---------------------------------------------------------------- #if defined (HAVE_SINCOSF) void sincosf(float x, float *sinx, float *cosx) { ::sincosf(x, sinx, cosx); } #elif defined (HAVE_SINF) && defined (HAVE_COSF) void sincosf(float x, float *sinx, float *cosx) { *sinx = ::sinf(x); *cosx = ::cosf(x); } #else void sincosf(float x, float *sinx, float *cosx) { *sinx = ::sin(x); *cosx = ::cos(x); } #endif } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/msg_queue.cc0000664000175000017500000000522512207440367021675 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { msg_queue::sptr msg_queue::make(unsigned int limit) { return msg_queue::sptr(new msg_queue(limit)); } msg_queue::msg_queue(unsigned int limit) : d_not_empty(), d_not_full(), /*d_head(0), d_tail(0),*/ d_count(0), d_limit(limit) { } msg_queue::~msg_queue() { flush (); } void msg_queue::insert_tail(message::sptr msg) { if(msg->d_next) throw std::invalid_argument("gr::msg_queue::insert_tail: msg already in queue"); gr::thread::scoped_lock guard(d_mutex); while(full_p()) d_not_full.wait(guard); if(d_tail == 0) { d_tail = d_head = msg; //msg->d_next = 0; msg->d_next.reset(); } else { d_tail->d_next = msg; d_tail = msg; //msg->d_next = 0; msg->d_next.reset(); } d_count++; d_not_empty.notify_one(); } message::sptr msg_queue::delete_head() { gr::thread::scoped_lock guard(d_mutex); message::sptr m; while((m = d_head) == 0) d_not_empty.wait(guard); d_head = m->d_next; if(d_head == 0){ //d_tail = 0; d_tail.reset(); } d_count--; // m->d_next = 0; m->d_next.reset(); d_not_full.notify_one(); return m; } message::sptr msg_queue::delete_head_nowait() { gr::thread::scoped_lock guard(d_mutex); message::sptr m; if((m = d_head) == 0) { //return 0; return message::sptr(); } d_head = m->d_next; if(d_head == 0) { //d_tail = 0; d_tail.reset(); } d_count--; //m->d_next = 0; m->d_next.reset(); d_not_full.notify_one(); return m; } void msg_queue::flush() { message::sptr m; while((m = delete_head_nowait ()) != 0) ; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/single_threaded_scheduler.h0000664000175000017500000000355712207440367024732 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SINGLE_THREADED_SCHEDULER_H #define INCLUDED_GR_SINGLE_THREADED_SCHEDULER_H #include #include #include namespace gr { class single_threaded_scheduler; typedef boost::shared_ptr single_threaded_scheduler_sptr; /*! * \brief Simple scheduler for stream computations. * \ingroup internal */ class GR_RUNTIME_API single_threaded_scheduler { public: ~single_threaded_scheduler(); void run(); void stop(); private: const std::vector d_blocks; volatile bool d_enabled; std::ofstream *d_log; single_threaded_scheduler(const std::vector &blocks); void main_loop(); friend GR_RUNTIME_API single_threaded_scheduler_sptr make_single_threaded_scheduler(const std::vector &blocks); }; GR_RUNTIME_API single_threaded_scheduler_sptr make_single_threaded_scheduler(const std::vector &blocks); } /* namespace gr */ #endif /* INCLUDED_GR_SINGLE_THREADED_SCHEDULER_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/test_runtime.cc0000664000175000017500000000257512207440367022432 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2010,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include int main (int argc, char **argv) { CppUnit::TextTestRunner runner; std::ofstream xmlfile(get_unittest_path("gnuradio_runtime_runtime.xml").c_str()); CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); runner.addTest(qa_runtime::suite()); runner.setOutputter(xmlout); bool was_successful = runner.run("", false); return was_successful ? 0 : 1; } gnuradio-3.7.2.1/gnuradio-runtime/lib/scheduler.cc0000664000175000017500000000205012207440367021652 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "scheduler.h" namespace gr { scheduler::scheduler(flat_flowgraph_sptr ffg, int max_noutput_items) { } scheduler::~scheduler() { } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_mmap_shm_open.cc0000664000175000017500000001417112207440367024565 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vmcircbuf_mmap_shm_open.h" #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_MMAN_H #include #endif #include #include #include "pagesize.h" #include namespace gr { vmcircbuf_mmap_shm_open::vmcircbuf_mmap_shm_open(int size) : gr::vmcircbuf(size) { #if !defined(HAVE_MMAP) || !defined(HAVE_SHM_OPEN) fprintf(stderr, "gr::vmcircbuf_mmap_shm_open: mmap or shm_open is not available\n"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); #else gr::thread::scoped_lock guard(s_vm_mutex); static int s_seg_counter = 0; if(size <= 0 || (size % gr::pagesize ()) != 0) { fprintf(stderr, "gr::vmcircbuf_mmap_shm_open: invalid size = %d\n", size); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } int shm_fd = -1; char seg_name[1024]; static bool portable_format = true; // open a new named shared memory segment while(1) { if(portable_format) { // This is the POSIX recommended "portable format". // Of course the "portable format" doesn't work on some systems... snprintf(seg_name, sizeof(seg_name), "/gnuradio-%d-%d", getpid(), s_seg_counter); } else { // Where the "portable format" doesn't work, we try building // a full filesystem pathname pointing into a suitable temporary directory. snprintf(seg_name, sizeof(seg_name), "%s/gnuradio-%d-%d", gr::tmp_path(), getpid(), s_seg_counter); } shm_fd = shm_open(seg_name, O_RDWR | O_CREAT | O_EXCL, 0600); if(shm_fd == -1 && errno == EACCES && portable_format) { portable_format = false; continue; // try again using "non-portable format" } s_seg_counter++; if(shm_fd == -1) { if(errno == EEXIST) // Named segment already exists (shouldn't happen). Try again continue; char msg[1024]; snprintf(msg, sizeof(msg), "gr::vmcircbuf_mmap_shm_open: shm_open [%s]", seg_name); perror(msg); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } break; } // We've got a new shared memory segment fd open. // Now set it's length to 2x what we really want and mmap it in. if(ftruncate(shm_fd, (off_t)2 * size) == -1) { close(shm_fd); // cleanup perror("gr::vmcircbuf_mmap_shm_open: ftruncate (1)"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } void *first_copy = mmap(0, 2 * size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, (off_t) 0); if(first_copy == MAP_FAILED) { close(shm_fd); // cleanup perror("gr::vmcircbuf_mmap_shm_open: mmap (1)"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } // unmap the 2nd half if(munmap ((char *) first_copy + size, size) == -1) { close(shm_fd); // cleanup perror("gr::vmcircbuf_mmap_shm_open: munmap (1)"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } // map the first half into the now available hole where the // second half used to be. void *second_copy = mmap((char*)first_copy + size, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, (off_t)0); if(second_copy == MAP_FAILED) { close(shm_fd); // cleanup perror("gr::vmcircbuf_mmap_shm_open: mmap (2)"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } #if 0 // OS/X doesn't allow you to resize the segment // cut the shared memory segment down to size if(ftruncate(shm_fd, (off_t)size) == -1) { close(shm_fd); // cleanup perror("gr::vmcircbuf_mmap_shm_open: ftruncate (2)"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } #endif close(shm_fd); // fd no longer needed. The mapping is retained. if(shm_unlink(seg_name) == -1) { // unlink the seg_name. perror("gr::vmcircbuf_mmap_shm_open: shm_unlink"); throw std::runtime_error("gr::vmcircbuf_mmap_shm_open"); } // Now remember the important stuff d_base = (char*)first_copy; d_size = size; #endif } vmcircbuf_mmap_shm_open::~vmcircbuf_mmap_shm_open() { #if defined(HAVE_MMAP) gr::thread::scoped_lock guard(s_vm_mutex); if(munmap (d_base, 2 * d_size) == -1) { perror("gr::vmcircbuf_mmap_shm_open: munmap (2)"); } #endif } // ---------------------------------------------------------------- // The factory interface // ---------------------------------------------------------------- gr::vmcircbuf_factory *vmcircbuf_mmap_shm_open_factory::s_the_factory = 0; gr::vmcircbuf_factory * vmcircbuf_mmap_shm_open_factory::singleton() { if(s_the_factory) return s_the_factory; s_the_factory = new gr::vmcircbuf_mmap_shm_open_factory(); return s_the_factory; } int vmcircbuf_mmap_shm_open_factory::granularity() { return gr::pagesize(); } gr::vmcircbuf * vmcircbuf_mmap_shm_open_factory::make(int size) { try { return new vmcircbuf_mmap_shm_open(size); } catch (...) { return 0; } } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_prefs.cc0000664000175000017500000000537212207440367023065 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2010,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vmcircbuf_prefs.h" #include "vmcircbuf.h" #include #include #include #include #include #include #include #include #include #include namespace fs = boost::filesystem; namespace gr { /* * The simplest thing that could possibly work: * the key is the filename; the value is the file contents. */ static const char * pathname(const char *key) { static fs::path path; path = fs::path(gr::appdata_path()) / ".gnuradio" / "prefs" / key; return path.string().c_str(); } static void ensure_dir_path() { fs::path path = fs::path(gr::appdata_path()) / ".gnuradio"; if(!fs::is_directory(path)) fs::create_directory(path); path = path / "prefs"; if(!fs::is_directory(path)) fs::create_directory(path); } const char * vmcircbuf_prefs::get(const char *key) { static char buf[1024]; gr::thread::scoped_lock guard(s_vm_mutex); FILE *fp = fopen(pathname (key), "r"); if(fp == 0) { perror(pathname (key)); return 0; } memset(buf, 0, sizeof (buf)); size_t ret = fread(buf, 1, sizeof(buf) - 1, fp); if(ret == 0) { if(ferror(fp) != 0) { perror(pathname (key)); fclose(fp); return 0; } } fclose(fp); return buf; } void vmcircbuf_prefs::set(const char *key, const char *value) { gr::thread::scoped_lock guard(s_vm_mutex); ensure_dir_path(); FILE *fp = fopen(pathname(key), "w"); if(fp == 0) { perror(pathname (key)); return; } size_t ret = fwrite(value, 1, strlen(value), fp); if(ret == 0) { if(ferror(fp) != 0) { perror(pathname (key)); fclose(fp); return; } } fclose(fp); }; } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_sysv_shm.cc0000664000175000017500000001426712207440367023624 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vmcircbuf_sysv_shm.h" #include #include #include #include #include #ifdef HAVE_SYS_IPC_H #include #endif #ifdef HAVE_SYS_SHM_H #include #endif #include #include #include "pagesize.h" #define MAX_SYSV_SHM_ATTEMPTS 3 namespace gr { vmcircbuf_sysv_shm::vmcircbuf_sysv_shm(int size) : gr::vmcircbuf(size) { #if !defined(HAVE_SYS_SHM_H) fprintf(stderr, "gr::vmcircbuf_sysv_shm: sysv shared memory is not available\n"); throw std::runtime_error("gr::vmcircbuf_sysv_shm"); #else gr::thread::scoped_lock guard(s_vm_mutex); int pagesize = gr::pagesize(); if(size <= 0 || (size % pagesize) != 0) { fprintf(stderr, "gr::vmcircbuf_sysv_shm: invalid size = %d\n", size); throw std::runtime_error("gr::vmcircbuf_sysv_shm"); } // Attempt to allocate buffers (handle bad_alloc errors) int attempts_remain(MAX_SYSV_SHM_ATTEMPTS); while(attempts_remain-- > 0){ int shmid_guard = -1; int shmid1 = -1; int shmid2 = -1; // We use this as a guard page. We'll map it read-only on both ends of the buffer. // Ideally we'd map it no access, but I don't think that's possible with SysV if((shmid_guard = shmget(IPC_PRIVATE, pagesize, IPC_CREAT | 0400)) == -1) { perror("gr::vmcircbuf_sysv_shm: shmget (0)"); continue; } if((shmid2 = shmget(IPC_PRIVATE, 2 * size + 2 * pagesize, IPC_CREAT | 0700)) == -1) { perror("gr::vmcircbuf_sysv_shm: shmget(1)"); shmctl(shmid_guard, IPC_RMID, 0); continue; } if((shmid1 = shmget(IPC_PRIVATE, size, IPC_CREAT | 0700)) == -1) { perror("gr::vmcircbuf_sysv_shm: shmget (2)"); shmctl(shmid_guard, IPC_RMID, 0); shmctl(shmid2, IPC_RMID, 0); continue; } void *first_copy = shmat (shmid2, 0, 0); if(first_copy == (void *) -1) { perror("gr::vmcircbuf_sysv_shm: shmat(1)"); shmctl(shmid_guard, IPC_RMID, 0); shmctl(shmid2, IPC_RMID, 0); shmctl(shmid1, IPC_RMID, 0); continue; } shmctl(shmid2, IPC_RMID, 0); // There may be a race between our detach and attach. // // If the system allocates all shared memory segments at the same // virtual addresses in all processes and if the system allocates // some other segment to first_copy or first_copoy + size between // our detach and attach, the attaches below could fail [I've never // seen it fail for this reason]. shmdt(first_copy); // first read-only guard page if(shmat(shmid_guard, first_copy, SHM_RDONLY) == (void *) -1) { perror("gr::vmcircbuf_sysv_shm: shmat(2)"); shmctl(shmid_guard, IPC_RMID, 0); shmctl(shmid1, IPC_RMID, 0); continue; } // first copy if(shmat (shmid1, (char*)first_copy + pagesize, 0) == (void *) -1) { perror("gr::vmcircbuf_sysv_shm: shmat (3)"); shmctl(shmid_guard, IPC_RMID, 0); shmctl(shmid1, IPC_RMID, 0); shmdt(first_copy); continue; } // second copy if(shmat (shmid1, (char*)first_copy + pagesize + size, 0) == (void *) -1) { perror("gr::vmcircbuf_sysv_shm: shmat (4)"); shmctl(shmid_guard, IPC_RMID, 0); shmctl(shmid1, IPC_RMID, 0); shmdt((char *)first_copy + pagesize); continue; } // second read-only guard page if(shmat(shmid_guard, (char*)first_copy + pagesize + 2 * size, SHM_RDONLY) == (void *) -1) { perror("gr::vmcircbuf_sysv_shm: shmat(5)"); shmctl(shmid_guard, IPC_RMID, 0); shmctl(shmid1, IPC_RMID, 0); shmdt(first_copy); shmdt((char *)first_copy + pagesize); shmdt((char *)first_copy + pagesize + size); continue; } shmctl(shmid1, IPC_RMID, 0); shmctl(shmid_guard, IPC_RMID, 0); // Now remember the important stuff d_base = (char*)first_copy + pagesize; d_size = size; break; } if(attempts_remain<0){ throw std::runtime_error("gr_vmcircbuf_sysv_shm"); } #endif } vmcircbuf_sysv_shm::~vmcircbuf_sysv_shm() { #if defined(HAVE_SYS_SHM_H) gr::thread::scoped_lock guard(s_vm_mutex); if(shmdt(d_base - gr::pagesize()) == -1 || shmdt(d_base) == -1 || shmdt(d_base + d_size) == -1 || shmdt(d_base + 2 * d_size) == -1){ perror("gr::vmcircbuf_sysv_shm: shmdt(2)"); } #endif } // ---------------------------------------------------------------- // The factory interface // ---------------------------------------------------------------- gr::vmcircbuf_factory *vmcircbuf_sysv_shm_factory::s_the_factory = 0; gr::vmcircbuf_factory * vmcircbuf_sysv_shm_factory::singleton() { if(s_the_factory) return s_the_factory; s_the_factory = new gr::vmcircbuf_sysv_shm_factory(); return s_the_factory; } int vmcircbuf_sysv_shm_factory::granularity() { return gr::pagesize(); } gr::vmcircbuf * vmcircbuf_sysv_shm_factory::make(int size) { try { return new vmcircbuf_sysv_shm(size); } catch (...) { return 0; } } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_mmap_tmpfile.cc0000664000175000017500000001343612207440367024420 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vmcircbuf_mmap_tmpfile.h" #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_MMAN_H #include #endif #include #include #include #include #include "pagesize.h" #include namespace gr { vmcircbuf_mmap_tmpfile::vmcircbuf_mmap_tmpfile (int size) : gr::vmcircbuf (size) { #if !defined(HAVE_MMAP) fprintf(stderr, "gr::vmcircbuf_mmap_tmpfile: mmap or mkstemp is not available\n"); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); #else gr::thread::scoped_lock guard(s_vm_mutex); if(size <= 0 || (size % gr::pagesize ()) != 0) { fprintf(stderr, "gr::vmcircbuf_mmap_tmpfile: invalid size = %d\n", size); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } int seg_fd = -1; char seg_name[1024]; static int s_seg_counter = 0; // open a temporary file that we'll map in a bit later while(1) { snprintf(seg_name, sizeof(seg_name), "%s/gnuradio-%d-%d-XXXXXX", gr::tmp_path(), getpid(), s_seg_counter); s_seg_counter++; seg_fd = open(seg_name, O_RDWR | O_CREAT | O_EXCL, 0600); if(seg_fd == -1) { if(errno == EEXIST) // File already exists (shouldn't happen). Try again continue; char msg[1024]; snprintf(msg, sizeof (msg), "gr::vmcircbuf_mmap_tmpfile: open [%s]", seg_name); perror(msg); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } break; } if(unlink (seg_name) == -1) { perror("gr::vmcircbuf_mmap_tmpfile: unlink"); throw std::runtime_error ("gr::vmcircbuf_mmap_tmpfile"); } // We've got a valid file descriptor to a tmp file. // Now set it's length to 2x what we really want and mmap it in. if(ftruncate (seg_fd, (off_t) 2 * size) == -1) { close(seg_fd); // cleanup perror("gr::vmcircbuf_mmap_tmpfile: ftruncate (1)"); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } void *first_copy = mmap(0, 2 * size, PROT_READ | PROT_WRITE, MAP_SHARED, seg_fd, (off_t)0); if(first_copy == MAP_FAILED) { close(seg_fd); // cleanup perror("gr::vmcircbuf_mmap_tmpfile: mmap (1)"); throw std::runtime_error ("gr::vmcircbuf_mmap_tmpfile"); } // unmap the 2nd half if(munmap ((char *) first_copy + size, size) == -1) { close(seg_fd); // cleanup perror("gr::vmcircbuf_mmap_tmpfile: munmap (1)"); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } // map the first half into the now available hole where the // second half used to be. void *second_copy = mmap((char*)first_copy + size, size, PROT_READ | PROT_WRITE, MAP_SHARED, seg_fd, (off_t)0); if(second_copy == MAP_FAILED) { munmap(first_copy, size); // cleanup close(seg_fd); perror("gr::vmcircbuf_mmap_tmpfile: mmap(2)"); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } // check for contiguity if((char*)second_copy != (char*)first_copy + size) { munmap(first_copy, size); // cleanup munmap(second_copy, size); close(seg_fd); perror("gr::vmcircbuf_mmap_tmpfile: non-contiguous second copy"); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } // cut the tmp file down to size if(ftruncate (seg_fd, (off_t) size) == -1) { munmap(first_copy, size); // cleanup munmap(second_copy, size); close(seg_fd); perror("gr::vmcircbuf_mmap_tmpfile: ftruncate (2)"); throw std::runtime_error("gr::vmcircbuf_mmap_tmpfile"); } close(seg_fd); // fd no longer needed. The mapping is retained. // Now remember the important stuff d_base = (char*)first_copy; d_size = size; #endif } vmcircbuf_mmap_tmpfile::~vmcircbuf_mmap_tmpfile() { #if defined(HAVE_MMAP) gr::thread::scoped_lock guard(s_vm_mutex); if(munmap(d_base, 2 * d_size) == -1) { perror("gr::vmcircbuf_mmap_tmpfile: munmap(2)"); } #endif } // ---------------------------------------------------------------- // The factory interface // ---------------------------------------------------------------- gr::vmcircbuf_factory *vmcircbuf_mmap_tmpfile_factory::s_the_factory = 0; gr::vmcircbuf_factory * vmcircbuf_mmap_tmpfile_factory::singleton() { if(s_the_factory) return s_the_factory; s_the_factory = new gr::vmcircbuf_mmap_tmpfile_factory(); return s_the_factory; } int vmcircbuf_mmap_tmpfile_factory::granularity() { return gr::pagesize(); } gr::vmcircbuf * vmcircbuf_mmap_tmpfile_factory::make(int size) { try { return new vmcircbuf_mmap_tmpfile(size); } catch (...) { return 0; } } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/circular_file.h0000664000175000017500000000365312207440367022353 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_CIRCULAR_FILE_H #define GR_CIRCULAR_FILE_H #include namespace gr { /* * writes input data into a circular buffer on disk. * * the file contains a fixed header: * 0x0000: int32 magic (0xEB021026) * 0x0004: int32 size in bytes of header (constant 4096) * 0x0008: int32 size in bytes of circular buffer (not including header) * 0x000C: int32 file offset to beginning of circular buffer * 0x0010: int32 byte offset from beginning of circular buffer to * current start of data */ class GR_RUNTIME_API circular_file { private: int d_fd; int *d_header; unsigned char *d_buffer; int d_mapped_size; int d_bytes_read; public: circular_file(const char *filename, bool writable = false, int size = 0); ~circular_file(); bool write(void *data, int nbytes); // returns # of bytes actually read or 0 if end of buffer, or -1 on error. int read(void *data, int nbytes); // reset read pointer to beginning of buffer. void reset_read_pointer(); }; } /* namespace gr */ #endif /* GR_CIRCULAR_FILE_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf.h0000664000175000017500000000672512207440367021533 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_VMCIRCBUF_H #define GR_VMCIRCBUF_H #include #include #include extern gr::thread::mutex s_vm_mutex; namespace gr { /*! * \brief abstract class to implement doubly mapped virtual memory circular buffers * \ingroup internal */ class GR_RUNTIME_API vmcircbuf { protected: int d_size; char *d_base; // CREATORS vmcircbuf(int size) : d_size(size), d_base(0) {}; public: virtual ~vmcircbuf(); // ACCESSORS void *pointer_to_first_copy() const{ return d_base; } void *pointer_to_second_copy() const{ return d_base + d_size; } }; /*! * \brief abstract factory for creating circular buffers */ class GR_RUNTIME_API vmcircbuf_factory { protected: vmcircbuf_factory() {}; virtual ~vmcircbuf_factory(); public: /*! * \brief return name of this factory */ virtual const char *name() const = 0; /*! * \brief return granularity of mapping, typically equal to page size */ virtual int granularity() = 0; /*! * \brief return a gr::vmcircbuf, or 0 if unable. * * Call this to create a doubly mapped circular buffer. */ virtual vmcircbuf *make(int size) = 0; }; /* * \brief pulls together all implementations of gr::vmcircbuf */ class GR_RUNTIME_API vmcircbuf_sysconfig { public: /* * \brief return the single instance of the default factory. * * returns the default factory to use if it's already defined, * else find the first working factory and use it. */ static vmcircbuf_factory *get_default_factory(); static int granularity() { return get_default_factory()->granularity(); } static vmcircbuf *make(int size) { return get_default_factory()->make(size); } // N.B. not all factories are guaranteed to work. // It's too hard to check everything at config time, so we check at runtime static std::vector all_factories(); // make this factory the default static void set_default_factory(vmcircbuf_factory *f); /*! * \brief Does this factory really work? * * verbose = 0: silent * verbose = 1: names of factories tested and results * verbose = 2: all intermediate results */ static bool test_factory(vmcircbuf_factory *f, int verbose); /*! * \brief Test all factories, return true if at least one of them works * verbose = 0: silent * verbose = 1: names of factories tested and results * verbose = 2: all intermediate results */ static bool test_all_factories(int verbose); }; } /* namespace gr */ #endif /* GR_VMCIRCBUF_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_circular_file.h0000664000175000017500000000221612207440367023026 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef QA_GR_CIRCULAR_FILE_H #define QA_GR_CIRCULAR_FILE_H #include #include class qa_circular_file : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_circular_file); CPPUNIT_TEST(t1); CPPUNIT_TEST_SUITE_END(); private: void t1(); }; #endif /* QA_GR_CIRCULAR_FILE_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/circular_file.cc0000664000175000017500000001230012207440367022476 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "circular_file.h" #include #ifdef HAVE_SYS_MMAN_H #include #endif #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_IO_H #include #endif namespace gr { static const int HEADER_SIZE = 4096; static const int HEADER_MAGIC = 0xEB021026; static const int HD_MAGIC = 0; static const int HD_HEADER_SIZE = 1; // integer offsets into header static const int HD_BUFFER_SIZE = 2; static const int HD_BUFFER_BASE = 3; static const int HD_BUFFER_CURRENT = 4; circular_file::circular_file(const char *filename, bool writable, int size) : d_fd(-1), d_header(0), d_buffer(0), d_mapped_size(0), d_bytes_read(0) { int mm_prot; if(writable) { #ifdef HAVE_MMAP mm_prot = PROT_READ | PROT_WRITE; #endif d_fd = open(filename, O_CREAT | O_RDWR | O_TRUNC, 0664); if(d_fd < 0) { perror(filename); exit(1); } #ifdef HAVE_MMAP /* FIXME */ if(ftruncate(d_fd, size + HEADER_SIZE) != 0) { perror(filename); exit(1); } #endif } else { #ifdef HAVE_MMAP mm_prot = PROT_READ; #endif d_fd = open (filename, O_RDONLY); if(d_fd < 0) { perror(filename); exit(1); } } struct stat statbuf; if(fstat (d_fd, &statbuf) < 0) { perror(filename); exit(1); } if(statbuf.st_size < HEADER_SIZE) { fprintf(stderr, "%s: file too small to be circular buffer\n", filename); exit(1); } d_mapped_size = statbuf.st_size; #ifdef HAVE_MMAP void *p = mmap (0, d_mapped_size, mm_prot, MAP_SHARED, d_fd, 0); if(p == MAP_FAILED) { perror("gr::circular_file: mmap failed"); exit(1); } d_header = (int*)p; #else perror("gr::circular_file: mmap unsupported by this system"); exit(1); #endif if(writable) { // init header if(size < 0) { fprintf(stderr, "gr::circular_buffer: size must be > 0 when writable\n"); exit(1); } d_header[HD_MAGIC] = HEADER_MAGIC; d_header[HD_HEADER_SIZE] = HEADER_SIZE; d_header[HD_BUFFER_SIZE] = size; d_header[HD_BUFFER_BASE] = HEADER_SIZE; // right after header d_header[HD_BUFFER_CURRENT] = 0; } // sanity check (the asserts are a bit unforgiving...) assert(d_header[HD_MAGIC] == HEADER_MAGIC); assert(d_header[HD_HEADER_SIZE] == HEADER_SIZE); assert(d_header[HD_BUFFER_SIZE] > 0); assert(d_header[HD_BUFFER_BASE] >= d_header[HD_HEADER_SIZE]); assert(d_header[HD_BUFFER_BASE] + d_header[HD_BUFFER_SIZE] <= d_mapped_size); assert(d_header[HD_BUFFER_CURRENT] >= 0 && d_header[HD_BUFFER_CURRENT] < d_header[HD_BUFFER_SIZE]); d_bytes_read = 0; d_buffer = (unsigned char*)d_header + d_header[HD_BUFFER_BASE]; } circular_file::~circular_file() { #ifdef HAVE_MMAP if(munmap ((char *) d_header, d_mapped_size) < 0) { perror("gr::circular_file: munmap"); exit(1); } #endif close(d_fd); } bool circular_file::write(void *vdata, int nbytes) { unsigned char *data = (unsigned char*)vdata; int buffer_size = d_header[HD_BUFFER_SIZE]; int buffer_current = d_header[HD_BUFFER_CURRENT]; while(nbytes > 0) { int n = std::min(nbytes, buffer_size - buffer_current); memcpy(d_buffer + buffer_current, data, n); buffer_current += n; if(buffer_current >= buffer_size) buffer_current = 0; data += n; nbytes -= n; } d_header[HD_BUFFER_CURRENT] = buffer_current; return true; } int circular_file::read(void *vdata, int nbytes) { unsigned char *data = (unsigned char *) vdata; int buffer_current = d_header[HD_BUFFER_CURRENT]; int buffer_size = d_header[HD_BUFFER_SIZE]; int total = 0; nbytes = std::min(nbytes, buffer_size - d_bytes_read); while(nbytes > 0) { int offset = (buffer_current + d_bytes_read) % buffer_size; int n = std::min (nbytes, buffer_size - offset); memcpy(data, d_buffer + offset, n); data += n; d_bytes_read += n; total += n; nbytes -= n; } return total; } void circular_file::reset_read_pointer() { d_bytes_read = 0; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/hier_block2_detail.cc0000664000175000017500000005625412227263356023423 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "hier_block2_detail.h" #include #include #include #include #include namespace gr { #define HIER_BLOCK2_DETAIL_DEBUG 0 hier_block2_detail::hier_block2_detail(hier_block2 *owner) : d_owner(owner), d_parent_detail(0), d_fg(make_flowgraph()) { int min_inputs = owner->input_signature()->min_streams(); int max_inputs = owner->input_signature()->max_streams(); int min_outputs = owner->output_signature()->min_streams(); int max_outputs = owner->output_signature()->max_streams(); if(max_inputs == io_signature::IO_INFINITE || max_outputs == io_signature::IO_INFINITE || (min_inputs != max_inputs) ||(min_outputs != max_outputs) ) { std::stringstream msg; msg << "Hierarchical blocks do not yet support arbitrary or" << " variable numbers of inputs or outputs (" << d_owner->name() << ")"; throw std::runtime_error(msg.str()); } d_inputs = std::vector(max_inputs); d_outputs = endpoint_vector_t(max_outputs); } hier_block2_detail::~hier_block2_detail() { d_owner = 0; // Don't use delete, we didn't allocate } void hier_block2_detail::connect(basic_block_sptr block) { std::stringstream msg; // Check if duplicate if(std::find(d_blocks.begin(), d_blocks.end(), block) != d_blocks.end()) { msg << "Block " << block << " already connected."; throw std::invalid_argument(msg.str()); } // Check if has inputs or outputs if(block->input_signature()->max_streams() != 0 || block->output_signature()->max_streams() != 0) { msg << "Block " << block << " must not have any input or output ports"; throw std::invalid_argument(msg.str()); } hier_block2_sptr hblock(cast_to_hier_block2_sptr(block)); if(hblock && hblock.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connect: block is hierarchical, setting parent to " << this << std::endl; hblock->d_detail->d_parent_detail = this; } d_blocks.push_back(block); } void hier_block2_detail::connect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port) { std::stringstream msg; if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connecting: " << endpoint(src, src_port) << " -> " << endpoint(dst, dst_port) << std::endl; if(src.get() == dst.get()) throw std::invalid_argument("connect: src and destination blocks cannot be the same"); hier_block2_sptr src_block(cast_to_hier_block2_sptr(src)); hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst)); if(src_block && src.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connect: src is hierarchical, setting parent to " << this << std::endl; src_block->d_detail->d_parent_detail = this; } if(dst_block && dst.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connect: dst is hierarchical, setting parent to " << this << std::endl; dst_block->d_detail->d_parent_detail = this; } // Connections to block inputs or outputs int max_port; if(src.get() == d_owner) { max_port = src->input_signature()->max_streams(); if((max_port != -1 && (src_port >= max_port)) || src_port < 0) { msg << "source port " << src_port << " out of range for " << src; throw std::invalid_argument(msg.str()); } return connect_input(src_port, dst_port, dst); } if(dst.get() == d_owner) { max_port = dst->output_signature()->max_streams(); if((max_port != -1 && (dst_port >= max_port)) || dst_port < 0) { msg << "destination port " << dst_port << " out of range for " << dst; throw std::invalid_argument(msg.str()); } return connect_output(dst_port, src_port, src); } // Internal connections d_fg->connect(src, src_port, dst, dst_port); // TODO: connects to NC } void hier_block2_detail::msg_connect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connecting message port..." << std::endl; // register the subscription // this is done later... // src->message_port_sub(srcport, pmt::cons(dst->alias_pmt(), dstport)); // add block uniquely to list to internal blocks if(std::find(d_blocks.begin(), d_blocks.end(), dst) == d_blocks.end()){ d_blocks.push_back(src); d_blocks.push_back(dst); } bool hier_out = (d_owner == src.get()) && src->message_port_is_hier_out(srcport);; bool hier_in = (d_owner == dst.get()) && dst->message_port_is_hier_in(dstport); hier_block2_sptr src_block(cast_to_hier_block2_sptr(src)); hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst)); if(src_block && src.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connect: src is hierarchical, setting parent to " << this << std::endl; src_block->d_detail->d_parent_detail = this; } if(dst_block && dst.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "connect: dst is hierarchical, setting parent to " << this << std::endl; dst_block->d_detail->d_parent_detail = this; } // add edge for this message connection if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << boost::format("connect( (%s, %s, %d), (%s, %s, %d) )\n") % \ src % srcport % hier_out % dst % dstport % hier_in; d_fg->connect(msg_endpoint(src, srcport, hier_out), msg_endpoint(dst, dstport, hier_in)); } void hier_block2_detail::msg_disconnect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "disconnecting message port..." << std::endl; // remove edge for this message connection bool hier_out = (d_owner == src.get()) && src->message_port_is_hier_out(srcport); bool hier_in = (d_owner == dst.get()) && dst->message_port_is_hier_in(dstport); d_fg->disconnect(msg_endpoint(src, srcport, hier_out), msg_endpoint(dst, dstport, hier_in)); hier_block2_sptr src_block(cast_to_hier_block2_sptr(src)); hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst)); if (src_block && src.get() != d_owner) { // if the source is hier, we need to resolve the endpoint before calling unsub msg_edge_vector_t edges = src_block->d_detail->d_fg->msg_edges(); for (msg_edge_viter_t it = edges.begin(); it != edges.end(); ++it) { if ((*it).dst().block() == src) { src = (*it).src().block(); srcport = (*it).src().port(); } } } if (dst_block && dst.get() != d_owner) { // if the destination is hier, we need to resolve the endpoint before calling unsub msg_edge_vector_t edges = dst_block->d_detail->d_fg->msg_edges(); for (msg_edge_viter_t it = edges.begin(); it != edges.end(); ++it) { if ((*it).src().block() == dst) { dst = (*it).dst().block(); dstport = (*it).dst().port(); } } } // unregister the subscription - if already subscribed src->message_port_unsub(srcport, pmt::cons(dst->alias_pmt(), dstport)); } void hier_block2_detail::disconnect(basic_block_sptr block) { // Check on singleton list for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) { if(*p == block) { d_blocks.erase(p); hier_block2_sptr hblock(cast_to_hier_block2_sptr(block)); if(block && block.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "disconnect: block is hierarchical, clearing parent" << std::endl; hblock->d_detail->d_parent_detail = 0; } return; } } // Otherwise find all edges containing block edge_vector_t edges, tmp = d_fg->edges(); edge_vector_t::iterator p; for(p = tmp.begin(); p != tmp.end(); p++) { if((*p).src().block() == block || (*p).dst().block() == block) { edges.push_back(*p); if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "disconnect: block found in edge " << (*p) << std::endl; } } if(edges.size() == 0) { std::stringstream msg; msg << "cannot disconnect block " << block << ", not found"; throw std::invalid_argument(msg.str()); } for(p = edges.begin(); p != edges.end(); p++) { disconnect((*p).src().block(), (*p).src().port(), (*p).dst().block(), (*p).dst().port()); } } void hier_block2_detail::disconnect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "disconnecting: " << endpoint(src, src_port) << " -> " << endpoint(dst, dst_port) << std::endl; if(src.get() == dst.get()) throw std::invalid_argument("disconnect: source and destination blocks cannot be the same"); hier_block2_sptr src_block(cast_to_hier_block2_sptr(src)); hier_block2_sptr dst_block(cast_to_hier_block2_sptr(dst)); if(src_block && src.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "disconnect: src is hierarchical, clearing parent" << std::endl; src_block->d_detail->d_parent_detail = 0; } if(dst_block && dst.get() != d_owner) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "disconnect: dst is hierarchical, clearing parent" << std::endl; dst_block->d_detail->d_parent_detail = 0; } if(src.get() == d_owner) return disconnect_input(src_port, dst_port, dst); if(dst.get() == d_owner) return disconnect_output(dst_port, src_port, src); // Internal connections d_fg->disconnect(src, src_port, dst, dst_port); } void hier_block2_detail::connect_input(int my_port, int port, basic_block_sptr block) { std::stringstream msg; if(my_port < 0 || my_port >= (signed)d_inputs.size()) { msg << "input port " << my_port << " out of range for " << block; throw std::invalid_argument(msg.str()); } endpoint_vector_t &endps = d_inputs[my_port]; endpoint endp(block, port); endpoint_viter_t p = std::find(endps.begin(), endps.end(), endp); if(p != endps.end()) { msg << "external input port " << my_port << " already wired to " << endp; throw std::invalid_argument(msg.str()); } endps.push_back(endp); } void hier_block2_detail::connect_output(int my_port, int port, basic_block_sptr block) { std::stringstream msg; if(my_port < 0 || my_port >= (signed)d_outputs.size()) { msg << "output port " << my_port << " out of range for " << block; throw std::invalid_argument(msg.str()); } if(d_outputs[my_port].block()) { msg << "external output port " << my_port << " already connected from " << d_outputs[my_port]; throw std::invalid_argument(msg.str()); } d_outputs[my_port] = endpoint(block, port); } void hier_block2_detail::disconnect_input(int my_port, int port, basic_block_sptr block) { std::stringstream msg; if(my_port < 0 || my_port >= (signed)d_inputs.size()) { msg << "input port number " << my_port << " out of range for " << block; throw std::invalid_argument(msg.str()); } endpoint_vector_t &endps = d_inputs[my_port]; endpoint endp(block, port); endpoint_viter_t p = std::find(endps.begin(), endps.end(), endp); if(p == endps.end()) { msg << "external input port " << my_port << " not connected to " << endp; throw std::invalid_argument(msg.str()); } endps.erase(p); } void hier_block2_detail::disconnect_output(int my_port, int port, basic_block_sptr block) { std::stringstream msg; if(my_port < 0 || my_port >= (signed)d_outputs.size()) { msg << "output port number " << my_port << " out of range for " << block; throw std::invalid_argument(msg.str()); } if(d_outputs[my_port].block() != block) { msg << "block " << block << " not assigned to output " << my_port << ", can't disconnect"; throw std::invalid_argument(msg.str()); } d_outputs[my_port] = endpoint(); } endpoint_vector_t hier_block2_detail::resolve_port(int port, bool is_input) { std::stringstream msg; if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "Resolving port " << port << " as an " << (is_input ? "input" : "output") << " of " << d_owner->name() << std::endl; endpoint_vector_t result; if(is_input) { if(port < 0 || port >= (signed)d_inputs.size()) { msg << "resolve_port: hierarchical block '" << d_owner->name() << "': input " << port << " is out of range"; throw std::runtime_error(msg.str()); } if(d_inputs[port].empty()) { msg << "resolve_port: hierarchical block '" << d_owner->name() << "': input " << port << " is not connected internally"; throw std::runtime_error(msg.str()); } endpoint_vector_t &endps = d_inputs[port]; endpoint_viter_t p; for(p = endps.begin(); p != endps.end(); p++) { endpoint_vector_t tmp = resolve_endpoint(*p, true); std::copy(tmp.begin(), tmp.end(), back_inserter(result)); } } else { if(port < 0 || port >= (signed)d_outputs.size()) { msg << "resolve_port: hierarchical block '" << d_owner->name() << "': output " << port << " is out of range"; throw std::runtime_error(msg.str()); } if(d_outputs[port] == endpoint()) { msg << "resolve_port: hierarchical block '" << d_owner->name() << "': output " << port << " is not connected internally"; throw std::runtime_error(msg.str()); } result = resolve_endpoint(d_outputs[port], false); } if(result.empty()) { msg << "resolve_port: hierarchical block '" << d_owner->name() << "': unable to resolve " << (is_input ? "input port " : "output port ") << port; throw std::runtime_error(msg.str()); } return result; } void hier_block2_detail::disconnect_all() { d_fg->clear(); d_blocks.clear(); int max_inputs = d_owner->input_signature()->max_streams(); int max_outputs = d_owner->output_signature()->max_streams(); d_inputs = std::vector(max_inputs); d_outputs = endpoint_vector_t(max_outputs); } endpoint_vector_t hier_block2_detail::resolve_endpoint(const endpoint &endp, bool is_input) const { std::stringstream msg; endpoint_vector_t result; // Check if endpoint is a leaf node if(cast_to_block_sptr(endp.block())) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "Block " << endp.block() << " is a leaf node, returning." << std::endl; result.push_back(endp); return result; } // Check if endpoint is a hierarchical block hier_block2_sptr hier_block2(cast_to_hier_block2_sptr(endp.block())); if(hier_block2) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "Resolving endpoint " << endp << " as an " << (is_input ? "input" : "output") << ", recursing" << std::endl; return hier_block2->d_detail->resolve_port(endp.port(), is_input); } msg << "unable to resolve" << (is_input ? " input " : " output ") << "endpoint " << endp; throw std::runtime_error(msg.str()); } void hier_block2_detail::flatten_aux(flat_flowgraph_sptr sfg) const { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << " ** Flattening " << d_owner->name() << std::endl; // Add my edges to the flow graph, resolving references to actual endpoints edge_vector_t edges = d_fg->edges(); msg_edge_vector_t msg_edges = d_fg->msg_edges(); edge_viter_t p; msg_edge_viter_t q,u; // Only run setup_rpc if ControlPort config param is enabled. bool ctrlport_on = prefs::singleton()->get_bool("ControlPort", "on", false); // For every block (gr::block and gr::hier_block2), set up the RPC // interface. for(p = edges.begin(); p != edges.end(); p++) { basic_block_sptr b; b = p->src().block(); if(ctrlport_on) { if(!b->is_rpc_set()) { b->setup_rpc(); b->rpc_set(); } } b = p->dst().block(); if(ctrlport_on) { if(!b->is_rpc_set()) { b->setup_rpc(); b->rpc_set(); } } } if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "Flattening stream connections: " << std::endl; for(p = edges.begin(); p != edges.end(); p++) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "Flattening edge " << (*p) << std::endl; endpoint_vector_t src_endps = resolve_endpoint(p->src(), false); endpoint_vector_t dst_endps = resolve_endpoint(p->dst(), true); endpoint_viter_t s, d; for(s = src_endps.begin(); s != src_endps.end(); s++) { for(d = dst_endps.begin(); d != dst_endps.end(); d++) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << (*s) << "->" << (*d) << std::endl; sfg->connect(*s, *d); } } } // loop through flattening hierarchical connections if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "Flattening msg connections: " << std::endl; std::vector > resolved_endpoints; for(q = msg_edges.begin(); q != msg_edges.end(); q++) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << boost::format(" flattening edge ( %s, %s, %d) -> ( %s, %s, %d)\n") % \ q->src().block() % q->src().port() % q->src().is_hier() % q->dst().block() % \ q->dst().port() % q->dst().is_hier(); bool normal_connection = true; // resolve existing connections to hier ports if(q->dst().is_hier()) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << boost::format(" resolve hier output (%s, %s)") % \ q->dst().block() % q->dst().port() << std::endl; sfg->replace_endpoint( q->dst(), q->src(), true ); resolved_endpoints.push_back(std::pair(q->dst(),true)); normal_connection = false; } if(q->src().is_hier()) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << boost::format(" resolve hier input (%s, %s)") % \ q->src().block() % q->src().port() << std::endl; sfg->replace_endpoint( q->src(), q->dst(), false ); resolved_endpoints.push_back(std::pair(q->src(),false)); normal_connection = false; } // propogate non hier connections through if(normal_connection){ sfg->connect( q->src(), q->dst() ); } } for(std::vector >::iterator it = resolved_endpoints.begin(); it != resolved_endpoints.end(); it++) { sfg->clear_endpoint((*it).first, (*it).second); } /* // connect primitive edges in the new fg for(q = msg_edges.begin(); q != msg_edges.end(); q++) { if((!q->src().is_hier()) && (!q->dst().is_hier())) { sfg->connect(q->src(), q->dst()); } else { std::cout << "not connecting hier connection!" << std::endl; } } */ // Construct unique list of blocks used either in edges, inputs, // outputs, or by themselves. I still hate STL. basic_block_vector_t blocks; // unique list of used blocks basic_block_vector_t tmp = d_fg->calc_used_blocks(); // First add the list of singleton blocks std::vector::const_iterator b; // Because flatten_aux is const for(b = d_blocks.begin(); b != d_blocks.end(); b++) tmp.push_back(*b); // Now add the list of connected input blocks std::stringstream msg; for(unsigned int i = 0; i < d_inputs.size(); i++) { if(d_inputs[i].size() == 0) { msg << "In hierarchical block " << d_owner->name() << ", input " << i << " is not connected internally"; throw std::runtime_error(msg.str()); } for(unsigned int j = 0; j < d_inputs[i].size(); j++) tmp.push_back(d_inputs[i][j].block()); } for(unsigned int i = 0; i < d_outputs.size(); i++) { basic_block_sptr blk = d_outputs[i].block(); if(!blk) { msg << "In hierarchical block " << d_owner->name() << ", output " << i << " is not connected internally"; throw std::runtime_error(msg.str()); } tmp.push_back(blk); } sort(tmp.begin(), tmp.end()); std::insert_iterator inserter(blocks, blocks.begin()); unique_copy(tmp.begin(), tmp.end(), inserter); // Recurse hierarchical children for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { hier_block2_sptr hier_block2(cast_to_hier_block2_sptr(*p)); if(hier_block2 && (hier_block2.get() != d_owner)) { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "flatten_aux: recursing into hierarchical block " << hier_block2 << std::endl; hier_block2->d_detail->flatten_aux(sfg); } } } void hier_block2_detail::lock() { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "lock: entered in " << this << std::endl; if(d_parent_detail) d_parent_detail->lock(); else d_owner->lock(); } void hier_block2_detail::unlock() { if(HIER_BLOCK2_DETAIL_DEBUG) std::cout << "unlock: entered in " << this << std::endl; if(d_parent_detail) d_parent_detail->unlock(); else d_owner->unlock(); } void hier_block2_detail::set_processor_affinity(const std::vector &mask) { basic_block_vector_t tmp = d_fg->calc_used_blocks(); for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) { (*p)->set_processor_affinity(mask); } } void hier_block2_detail::unset_processor_affinity() { basic_block_vector_t tmp = d_fg->calc_used_blocks(); for(basic_block_viter_t p = tmp.begin(); p != tmp.end(); p++) { (*p)->unset_processor_affinity(); } } std::vector hier_block2_detail::processor_affinity() { basic_block_vector_t tmp = d_fg->calc_used_blocks(); return tmp[0]->processor_affinity(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/sync_interpolator.cc0000664000175000017500000000446312207440367023464 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { sync_interpolator::sync_interpolator(const std::string &name, io_signature::sptr input_signature, io_signature::sptr output_signature, unsigned interpolation) : sync_block(name, input_signature, output_signature) { set_interpolation(interpolation); } void sync_interpolator::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = fixed_rate_noutput_to_ninput(noutput_items); } int sync_interpolator::fixed_rate_noutput_to_ninput(int noutput_items) { return noutput_items / interpolation() + history() - 1; } int sync_interpolator::fixed_rate_ninput_to_noutput(int ninput_items) { return std::max(0, ninput_items - (int)history() + 1) * interpolation(); } int sync_interpolator::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int r = work(noutput_items, input_items, output_items); if(r > 0) consume_each(r / interpolation()); return r; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block_registry.cc0000664000175000017500000000733012207440367022724 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include gr::block_registry global_block_registry; namespace gr { block_registry::block_registry() { d_ref_map = pmt::make_dict(); } long block_registry::block_register(basic_block* block) { gr::thread::scoped_lock guard(d_mutex); if(d_map.find(block->name()) == d_map.end()) { d_map[block->name()] = blocksubmap_t(); d_map[block->name()][0] = block; return 0; } else { for(size_t i=0; i<=d_map[block->name()].size(); i++){ if(d_map[block->name()].find(i) == d_map[block->name()].end()){ d_map[block->name()][i] = block; return i; } } } throw std::runtime_error("should not reach this"); } void block_registry::block_unregister(basic_block* block) { gr::thread::scoped_lock guard(d_mutex); d_map[block->name()].erase( d_map[block->name()].find(block->symbolic_id())); d_ref_map = pmt::dict_delete(d_ref_map, pmt::intern(block->symbol_name())); if(block->alias_set()) { d_ref_map = pmt::dict_delete(d_ref_map, pmt::intern(block->alias())); } } std::string block_registry::register_symbolic_name(basic_block* block) { std::stringstream ss; ss << block->name() << block->symbolic_id(); //std::cout << "register_symbolic_name: " << ss.str() << std::endl; register_symbolic_name(block, ss.str()); return ss.str(); } void block_registry::register_symbolic_name(basic_block* block, std::string name) { gr::thread::scoped_lock guard(d_mutex); if(pmt::dict_has_key(d_ref_map, pmt::intern(name))) { throw std::runtime_error("symbol already exists, can not re-use!"); } d_ref_map = pmt::dict_add(d_ref_map, pmt::intern(name), pmt::make_any(block)); } basic_block_sptr block_registry::block_lookup(pmt::pmt_t symbol) { gr::thread::scoped_lock guard(d_mutex); pmt::pmt_t ref = pmt::dict_ref(d_ref_map, symbol, pmt::PMT_NIL); if(pmt::eq(ref, pmt::PMT_NIL)) { throw std::runtime_error("block lookup failed! block not found!"); } basic_block* blk = boost::any_cast(pmt::any_ref(ref)); return blk->shared_from_this(); } void block_registry::register_primitive(std::string blk, block* ref) { gr::thread::scoped_lock guard(d_mutex); primitive_map[blk] = ref; } void block_registry::unregister_primitive(std::string blk) { gr::thread::scoped_lock guard(d_mutex); primitive_map.erase(primitive_map.find(blk)); } void block_registry::notify_blk(std::string blk) { gr::thread::scoped_lock guard(d_mutex); if(primitive_map.find(blk) == primitive_map.end()) { return; } if(primitive_map[blk]->detail().get()) primitive_map[blk]->detail()->d_tpb.notify_msg(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block_gateway_impl.h0000664000175000017500000000505012207440367023375 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_RUNTIME_BLOCK_GATEWAY_IMPL_H #define INCLUDED_RUNTIME_BLOCK_GATEWAY_IMPL_H #include namespace gr { /*********************************************************************** * The gr::block gateway implementation class **********************************************************************/ class block_gateway_impl : public block_gateway { public: block_gateway_impl(feval_ll *handler, const std::string &name, gr::io_signature::sptr in_sig, gr::io_signature::sptr out_sig, const block_gw_work_type work_type, const unsigned factor); /******************************************************************* * Overloads for various scheduler-called functions ******************************************************************/ void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int fixed_rate_noutput_to_ninput(int noutput_items); int fixed_rate_ninput_to_noutput(int ninput_items); bool start(void); bool stop(void); block_gw_message_type& block_message(void); private: feval_ll *_handler; block_gw_message_type _message; const block_gw_work_type _work_type; unsigned _decim, _interp; }; } /* namespace gr */ #endif /* INCLUDED_RUNTIME_BLOCK_GATEWAY_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_io_signature.h0000664000175000017500000000247612207440367022723 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_IO_SIGNATURE_H #define INCLUDED_QA_GR_IO_SIGNATURE_H #include #include #include class qa_io_signature : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_io_signature); CPPUNIT_TEST(t0); CPPUNIT_TEST_EXCEPTION(t1, std::invalid_argument); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1(); void t2(); void t3(); }; #endif /* INCLUDED_QA_GR_IO_SIGNATURE_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_runtime.cc0000664000175000017500000000345212236474522022051 0ustar jcorganjcorgan/* * Copyright 2002,2007,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This class gathers together all the test cases for the gr * directory into a single test suite. As you create new test cases, * add them here. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include #include #include #include #include CppUnit::TestSuite * qa_runtime::suite() { CppUnit::TestSuite *s = new CppUnit::TestSuite("runtime"); s->addTest(qa_buffer::suite()); s->addTest(qa_io_signature::suite()); s->addTest(qa_circular_file::suite()); s->addTest(qa_fxpt::suite()); s->addTest(qa_fxpt_nco::suite()); s->addTest(qa_fxpt_vco::suite()); s->addTest(qa_logger::suite()); s->addTest(qa_math::suite()); s->addTest(qa_vmcircbuf::suite()); s->addTest(qa_sincos::suite()); s->addTest(qa_fast_atan2f::suite()); return s; } gnuradio-3.7.2.1/gnuradio-runtime/lib/posix_memalign.h0000664000175000017500000000216412207440367022557 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _POSIX_MEMALIGN_H_ #define _POSIX_MEMALIGN_H_ #include #ifndef HAVE_POSIX_MEMALIGN #ifdef __cplusplus extern "C" { #endif extern int posix_memalign (void** memptr, size_t alignment, size_t size); #ifdef __cplusplus }; #endif #endif /* ! HAVE_POSIX_MEMALIGN */ #endif /* _POSIX_MEMALIGN_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block_gateway_impl.cc0000664000175000017500000001336512207440367023543 0ustar jcorganjcorgan/* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "block_gateway_impl.h" #include #include #include namespace gr { /*********************************************************************** * Helper routines **********************************************************************/ template void copy_pointers(OutType &out, const InType &in) { out.resize(in.size()); for(size_t i = 0; i < in.size(); i++) { out[i] = (void *)(in[i]); } } block_gateway::sptr block_gateway::make(feval_ll *handler, const std::string &name, gr::io_signature::sptr in_sig, gr::io_signature::sptr out_sig, const block_gw_work_type work_type, const unsigned factor) { return block_gateway::sptr (new block_gateway_impl(handler, name, in_sig, out_sig, work_type, factor)); } block_gateway_impl::block_gateway_impl(feval_ll *handler, const std::string &name, gr::io_signature::sptr in_sig, gr::io_signature::sptr out_sig, const block_gw_work_type work_type, const unsigned factor) : block(name, in_sig, out_sig), _handler(handler), _work_type(work_type) { switch(_work_type) { case GR_BLOCK_GW_WORK_GENERAL: _decim = 1; //not relevant, but set anyway _interp = 1; //not relevant, but set anyway break; case GR_BLOCK_GW_WORK_SYNC: _decim = 1; _interp = 1; this->set_fixed_rate(true); break; case GR_BLOCK_GW_WORK_DECIM: _decim = factor; _interp = 1; break; case GR_BLOCK_GW_WORK_INTERP: _decim = 1; _interp = factor; this->set_output_multiple(_interp); break; } } void block_gateway_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { switch(_work_type) { case GR_BLOCK_GW_WORK_GENERAL: _message.action = block_gw_message_type::ACTION_FORECAST; _message.forecast_args_noutput_items = noutput_items; _message.forecast_args_ninput_items_required = ninput_items_required; _handler->calleval(0); ninput_items_required = _message.forecast_args_ninput_items_required; return; default: unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = fixed_rate_noutput_to_ninput(noutput_items); return; } } int block_gateway_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { switch(_work_type) { case GR_BLOCK_GW_WORK_GENERAL: _message.action = block_gw_message_type::ACTION_GENERAL_WORK; _message.general_work_args_noutput_items = noutput_items; _message.general_work_args_ninput_items = ninput_items; copy_pointers(_message.general_work_args_input_items, input_items); _message.general_work_args_output_items = output_items; _handler->calleval(0); return _message.general_work_args_return_value; default: int r = work (noutput_items, input_items, output_items); if(r > 0) consume_each(r*_decim/_interp); return r; } } int block_gateway_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { _message.action = block_gw_message_type::ACTION_WORK; _message.work_args_ninput_items = fixed_rate_noutput_to_ninput(noutput_items); if(_message.work_args_ninput_items == 0) return -1; _message.work_args_noutput_items = noutput_items; copy_pointers(_message.work_args_input_items, input_items); _message.work_args_output_items = output_items; _handler->calleval(0); return _message.work_args_return_value; } int block_gateway_impl::fixed_rate_noutput_to_ninput(int noutput_items) { return (noutput_items*_decim/_interp) + history() - 1; } int block_gateway_impl::fixed_rate_ninput_to_noutput(int ninput_items) { return std::max(0, ninput_items - (int)history() + 1)*_interp/_decim; } bool block_gateway_impl::start(void) { _message.action = block_gw_message_type::ACTION_START; _handler->calleval(0); return _message.start_args_return_value; } bool block_gateway_impl::stop(void) { _message.action = block_gw_message_type::ACTION_STOP; _handler->calleval(0); return _message.stop_args_return_value; } block_gw_message_type& block_gateway_impl::block_message(void) { return _message; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/pagesize.h0000664000175000017500000000203712207440367021352 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_PAGESIZE_H_ #define GR_PAGESIZE_H_ #include namespace gr { /*! * \brief return the page size in bytes */ GR_RUNTIME_API int pagesize(); } /* namespace gr */ #endif /* GR_PAGESIZE_H_ */ gnuradio-3.7.2.1/gnuradio-runtime/lib/top_block.cc0000664000175000017500000001126612207440367021661 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "top_block_impl.h" #include #include #include #include #include #include namespace gr { top_block_sptr make_top_block(const std::string &name) { return gnuradio::get_initial_sptr (new top_block(name)); } top_block::top_block(const std::string &name) : hier_block2(name, io_signature::make(0,0,0), io_signature::make(0,0,0)) { d_impl = new top_block_impl(this); } top_block::~top_block() { stop(); wait(); delete d_impl; } void top_block::start(int max_noutput_items) { d_impl->start(max_noutput_items); if(prefs::singleton()->get_bool("ControlPort", "on", false)) { setup_rpc(); } } void top_block::stop() { d_impl->stop(); } void top_block::wait() { d_impl->wait(); } void top_block::run(int max_noutput_items) { start(max_noutput_items); wait(); } void top_block::lock() { d_impl->lock(); } void top_block::unlock() { d_impl->unlock(); } std::string top_block::edge_list() { return d_impl->edge_list(); } std::string top_block::msg_edge_list() { return d_impl->msg_edge_list(); } void top_block::dump() { d_impl->dump(); } int top_block::max_noutput_items() { return d_impl->max_noutput_items(); } void top_block::set_max_noutput_items(int nmax) { d_impl->set_max_noutput_items(nmax); } top_block_sptr top_block::to_top_block() { return cast_to_top_block_sptr(shared_from_this()); } void top_block::setup_rpc() { #ifdef GR_CTRLPORT if(is_rpc_set()) return; // Getters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "max noutput_items", &top_block::max_noutput_items, pmt::mp(0), pmt::mp(8192), pmt::mp(8192), "items", "Max number of output items", RPC_PRIVLVL_MIN, DISPNULL))); if(prefs::singleton()->get_bool("ControlPort", "edges_list", false)) { add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "edge list", &top_block::edge_list, pmt::mp(""), pmt::mp(""), pmt::mp(""), "edges", "List of edges in the graph", RPC_PRIVLVL_MIN, DISPNULL))); } if(prefs::singleton()->get_bool("ControlPort", "edges_list", false)) { add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "msg edges list", &top_block::msg_edge_list, pmt::mp(""), pmt::mp(""), pmt::mp(""), "msg_edges", "List of msg edges in the graph", RPC_PRIVLVL_MIN, DISPNULL))); } #ifdef GNURADIO_HRT_USE_CLOCK_GETTIME std::string initial_clock = prefs::singleton()->get_string("PerfCounters", "clock", "thread"); if(initial_clock.compare("thread") == 0){ gr::high_res_timer_source = CLOCK_THREAD_CPUTIME_ID; } else if(initial_clock.compare("monotonic") == 0){ gr::high_res_timer_source = CLOCK_MONOTONIC; } else { throw std::runtime_error("bad argument for PerfCounters.clock!"); } add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_variable_rw( alias(), "perfcounter_clock", (int*)&gr::high_res_timer_source, pmt::mp(0), pmt::mp(2), pmt::mp(2), "clock", "Performance Counters Realtime Clock Type", RPC_PRIVLVL_MIN, DISPNULL))); #endif // Setters add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "max noutput_items", &top_block::set_max_noutput_items, pmt::mp(0), pmt::mp(8192), pmt::mp(8192), "items", "Max number of output items", RPC_PRIVLVL_MIN, DISPNULL))); rpc_set(); #endif /* GR_CTRLPORT */ } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/sync_block.cc0000664000175000017500000000407712207440367022035 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { sync_block::sync_block(const std::string &name, io_signature::sptr input_signature, io_signature::sptr output_signature) : block(name, input_signature, output_signature) { set_fixed_rate(true); } void sync_block::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = fixed_rate_noutput_to_ninput(noutput_items); } int sync_block::fixed_rate_noutput_to_ninput(int noutput_items) { return noutput_items + history() - 1; } int sync_block::fixed_rate_ninput_to_noutput(int ninput_items) { return std::max(0, ninput_items - (int)history() + 1); } int sync_block::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int r = work(noutput_items, input_items, output_items); if(r > 0) consume_each(r); return r; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/io_signature.cc0000664000175000017500000000703412207440367022373 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include namespace gr { gr::io_signature::sptr io_signature::makev(int min_streams, int max_streams, const std::vector &sizeof_stream_items) { return gr::io_signature::sptr (new io_signature(min_streams, max_streams, sizeof_stream_items)); } gr::io_signature::sptr io_signature::make(int min_streams, int max_streams, int sizeof_stream_item) { std::vector sizeof_items(1); sizeof_items[0] = sizeof_stream_item; return io_signature::makev(min_streams, max_streams, sizeof_items); } gr::io_signature::sptr io_signature::make2(int min_streams, int max_streams, int sizeof_stream_item1, int sizeof_stream_item2) { std::vector sizeof_items(2); sizeof_items[0] = sizeof_stream_item1; sizeof_items[1] = sizeof_stream_item2; return io_signature::makev(min_streams, max_streams, sizeof_items); } gr::io_signature::sptr io_signature::make3(int min_streams, int max_streams, int sizeof_stream_item1, int sizeof_stream_item2, int sizeof_stream_item3) { std::vector sizeof_items(3); sizeof_items[0] = sizeof_stream_item1; sizeof_items[1] = sizeof_stream_item2; sizeof_items[2] = sizeof_stream_item3; return io_signature::makev(min_streams, max_streams, sizeof_items); } // ------------------------------------------------------------------------ io_signature::io_signature(int min_streams, int max_streams, const std::vector &sizeof_stream_items) { if(min_streams < 0 || (max_streams != IO_INFINITE && max_streams < min_streams)) throw std::invalid_argument ("gr::io_signature(1)"); if(sizeof_stream_items.size() < 1) throw std::invalid_argument("gr::io_signature(2)"); for(size_t i = 0; i < sizeof_stream_items.size(); i++) { if(max_streams != 0 && sizeof_stream_items[i] < 1) throw std::invalid_argument("gr::io_signature(3)"); } d_min_streams = min_streams; d_max_streams = max_streams; d_sizeof_stream_item = sizeof_stream_items; } io_signature::~io_signature() { } int io_signature::sizeof_stream_item(int _index) const { if(_index < 0) throw std::invalid_argument("gr::io_signature::sizeof_stream_item"); size_t index = _index; return d_sizeof_stream_item[std::min(index, d_sizeof_stream_item.size() - 1)]; } std::vector io_signature::sizeof_stream_items() const { return d_sizeof_stream_item; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/messages/0000775000175000017500000000000012207440367021177 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/lib/messages/msg_accepter_msgq.cc0000664000175000017500000000243312207440367025173 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #if HAVE_CONFIG_H #include #endif #include namespace gr { namespace messages { msg_accepter_msgq::msg_accepter_msgq(msg_queue_sptr msgq) : d_msg_queue(msgq) { } msg_accepter_msgq::~msg_accepter_msgq() { // NOP, required as virtual destructor } void msg_accepter_msgq::post(pmt::pmt_t msg) { d_msg_queue->insert_tail(msg); } } /* namespace messages */ } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/messages/CMakeLists.txt0000664000175000017500000000227012207440367023740 0ustar jcorganjcorgan# Copyright 2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # This file included, use CMake directory variables ######################################################################## list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_SOURCE_DIR}/msg_accepter.cc ${CMAKE_CURRENT_SOURCE_DIR}/msg_accepter_msgq.cc ${CMAKE_CURRENT_SOURCE_DIR}/msg_producer.cc ${CMAKE_CURRENT_SOURCE_DIR}/msg_queue.cc ) gnuradio-3.7.2.1/gnuradio-runtime/lib/messages/msg_producer.cc0000664000175000017500000000211612207440367024177 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { namespace messages { msg_producer::~msg_producer() { // NOP, required as virtual destructor } } /* namespace messages */ } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/messages/msg_queue.cc0000664000175000017500000000441212207440367023501 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { namespace messages { msg_queue_sptr make_msg_queue(unsigned int limit) { return msg_queue_sptr(new msg_queue(limit)); } msg_queue::msg_queue(unsigned int limit) : d_limit(limit) { } msg_queue::~msg_queue() { flush(); } void msg_queue::insert_tail(pmt::pmt_t msg) { gr::thread::scoped_lock guard(d_mutex); while(full_p()) d_not_full.wait(guard); d_msgs.push_back(msg); d_not_empty.notify_one(); } pmt::pmt_t msg_queue::delete_head() { gr::thread::scoped_lock guard(d_mutex); while(empty_p()) d_not_empty.wait(guard); pmt::pmt_t m(d_msgs.front()); d_msgs.pop_front(); if(d_limit > 0) // Unlimited length queues never block on write d_not_full.notify_one(); return m; } pmt::pmt_t msg_queue::delete_head_nowait() { gr::thread::scoped_lock guard(d_mutex); if(empty_p()) return pmt::pmt_t(); pmt::pmt_t m(d_msgs.front()); d_msgs.pop_front(); if(d_limit > 0) // Unlimited length queues never block on write d_not_full.notify_one(); return m; } void msg_queue::flush() { while(delete_head_nowait() != pmt::pmt_t()) ; } } /* namespace messages */ } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/messages/msg_accepter.cc0000664000175000017500000000211612207440367024142 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { namespace messages { msg_accepter::~msg_accepter() { // NOP, required as virtual destructor } } /* namespace messages */ } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/feval.cc0000664000175000017500000000447612207440367021007 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include namespace gr { feval_dd::~feval_dd(){} double feval_dd::eval(double x) { return 0; } double feval_dd::calleval(double x) { return eval(x); } // ---------------------------------------------------------------- feval_cc::~feval_cc(){} gr_complex feval_cc::eval(gr_complex x) { return 0; } gr_complex feval_cc::calleval(gr_complex x) { return eval(x); } // ---------------------------------------------------------------- feval_ll::~feval_ll(){} long feval_ll::eval(long x) { return 0; } long feval_ll::calleval(long x) { return eval(x); } // ---------------------------------------------------------------- feval::~feval(){} void feval::eval(void) { // nop } void feval::calleval(void) { eval(); } // ---------------------------------------------------------------- feval_p::~feval_p(){} void feval_p::eval(pmt::pmt_t x) { // nop } void feval_p::calleval(pmt::pmt_t x) { eval(x); } /* * Trivial examples showing C++ (transparently) calling Python */ double feval_dd_example(feval_dd *f, double x) { return f->calleval(x); } gr_complex feval_cc_example(feval_cc *f, gr_complex x) { return f->calleval(x); } long feval_ll_example(feval_ll *f, long x) { return f->calleval(x); } void feval_example(feval *f) { f->calleval(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block.cc0000664000175000017500000005012112237515111020761 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include namespace gr { block::block(const std::string &name, io_signature::sptr input_signature, io_signature::sptr output_signature) : basic_block(name, input_signature, output_signature), d_output_multiple (1), d_output_multiple_set(false), d_unaligned(0), d_is_unaligned(false), d_relative_rate (1.0), d_history(1), d_attr_delay(0), d_fixed_rate(false), d_max_noutput_items_set(false), d_max_noutput_items(0), d_min_noutput_items(0), d_tag_propagation_policy(TPP_ALL_TO_ALL), d_priority(-1), d_pc_rpc_set(false), d_update_rate(false), d_max_output_buffer(std::max(output_signature->max_streams(),1), -1), d_min_output_buffer(std::max(output_signature->max_streams(),1), -1) { global_block_registry.register_primitive(alias(), this); #ifdef ENABLE_GR_LOG #ifdef HAVE_LOG4CPP prefs *p = prefs::singleton(); std::string config_file = p->get_string("LOG", "log_config", ""); std::string log_level = p->get_string("LOG", "log_level", "off"); std::string log_file = p->get_string("LOG", "log_file", ""); std::string debug_level = p->get_string("LOG", "debug_level", "off"); std::string debug_file = p->get_string("LOG", "debug_file", ""); GR_CONFIG_LOGGER(config_file); GR_LOG_GETLOGGER(LOG, "gr_log." + alias()); GR_LOG_SET_LEVEL(LOG, log_level); if(log_file.size() > 0) { if(log_file == "stdout") { GR_LOG_ADD_CONSOLE_APPENDER(LOG, "cout","gr::log :%p: %c{1} - %m%n"); } else if(log_file == "stderr") { GR_LOG_ADD_CONSOLE_APPENDER(LOG, "cerr","gr::log :%p: %c{1} - %m%n"); } else { GR_LOG_ADD_FILE_APPENDER(LOG, log_file , true,"%r :%p: %c{1} - %m%n"); } } d_logger = LOG; GR_LOG_GETLOGGER(DLOG, "gr_log_debug." + alias()); GR_LOG_SET_LEVEL(DLOG, debug_level); if(debug_file.size() > 0) { if(debug_file == "stdout") { GR_LOG_ADD_CONSOLE_APPENDER(DLOG, "cout","gr::debug :%p: %c{1} - %m%n"); } else if(debug_file == "stderr") { GR_LOG_ADD_CONSOLE_APPENDER(DLOG, "cerr", "gr::debug :%p: %c{1} - %m%n"); } else { GR_LOG_ADD_FILE_APPENDER(DLOG, debug_file, true, "%r :%p: %c{1} - %m%n"); } } d_debug_logger = DLOG; #endif /* HAVE_LOG4CPP */ #else /* ENABLE_GR_LOG */ d_logger = NULL; d_debug_logger = NULL; #endif /* ENABLE_GR_LOG */ } block::~block() { global_block_registry.unregister_primitive(alias()); } unsigned block::history() const { return d_history; } void block::set_history(unsigned history) { d_history = history; } void block::declare_sample_delay(unsigned delay) { d_attr_delay = delay; if(d_detail) { unsigned int nins = static_cast(d_detail->ninputs()); for(unsigned int n = 0; n < nins; n++) { d_detail->input(n)->declare_sample_delay(d_attr_delay); } } } void block::declare_sample_delay(int which, unsigned delay) { d_attr_delay = delay; if(d_detail) { d_detail->input(which)->declare_sample_delay(d_attr_delay); } } unsigned block::sample_delay(int which) const { return d_attr_delay; } // stub implementation: 1:1 void block::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size (); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = noutput_items + history() - 1; } // default implementation bool block::start() { return true; } bool block::stop() { return true; } void block::set_output_multiple(int multiple) { if(multiple < 1) throw std::invalid_argument("block::set_output_multiple"); d_output_multiple_set = true; d_output_multiple = multiple; } void block::set_alignment(int multiple) { if(multiple < 1) throw std::invalid_argument("block::set_alignment_multiple"); d_output_multiple = multiple; } void block::set_unaligned(int na) { // unaligned value must be less than 0 and it doesn't make sense // that it's larger than the alignment value. if((na < 0) || (na > d_output_multiple)) throw std::invalid_argument("block::set_unaligned"); d_unaligned = na; } void block::set_is_unaligned(bool u) { d_is_unaligned = u; } void block::set_relative_rate(double relative_rate) { if(relative_rate < 0.0) throw std::invalid_argument("block::set_relative_rate"); d_relative_rate = relative_rate; } void block::consume(int which_input, int how_many_items) { d_detail->consume(which_input, how_many_items); } void block::consume_each(int how_many_items) { d_detail->consume_each(how_many_items); } void block::produce(int which_output, int how_many_items) { d_detail->produce(which_output, how_many_items); } int block::fixed_rate_ninput_to_noutput(int ninput) { throw std::runtime_error("Unimplemented"); } int block::fixed_rate_noutput_to_ninput(int noutput) { throw std::runtime_error("Unimplemented"); } uint64_t block::nitems_read(unsigned int which_input) { if(d_detail) { return d_detail->nitems_read(which_input); } else { //throw std::runtime_error("No block_detail associated with block yet"); return 0; } } uint64_t block::nitems_written(unsigned int which_output) { if(d_detail) { return d_detail->nitems_written(which_output); } else { //throw std::runtime_error("No block_detail associated with block yet"); return 0; } } void block::add_item_tag(unsigned int which_output, const tag_t &tag) { d_detail->add_item_tag(which_output, tag); } void block::remove_item_tag(unsigned int which_input, const tag_t &tag) { d_detail->remove_item_tag(which_input, tag, unique_id()); } void block::get_tags_in_range(std::vector &v, unsigned int which_output, uint64_t start, uint64_t end) { d_detail->get_tags_in_range(v, which_output, start, end, unique_id()); } void block::get_tags_in_range(std::vector &v, unsigned int which_output, uint64_t start, uint64_t end, const pmt::pmt_t &key) { d_detail->get_tags_in_range(v, which_output, start, end, key, unique_id()); } block::tag_propagation_policy_t block::tag_propagation_policy() { return d_tag_propagation_policy; } void block::set_tag_propagation_policy(tag_propagation_policy_t p) { d_tag_propagation_policy = p; } int block::max_noutput_items() { return d_max_noutput_items; } void block::set_max_noutput_items(int m) { if(m <= 0) throw std::runtime_error("block::set_max_noutput_items: value for max_noutput_items must be greater than 0.\n"); d_max_noutput_items = m; d_max_noutput_items_set = true; } void block::unset_max_noutput_items() { d_max_noutput_items_set = false; } bool block::is_set_max_noutput_items() { return d_max_noutput_items_set; } void block::set_processor_affinity(const std::vector &mask) { d_affinity = mask; if(d_detail) { d_detail->set_processor_affinity(d_affinity); } } void block::unset_processor_affinity() { d_affinity.clear(); if(d_detail) { d_detail->unset_processor_affinity(); } } int block::active_thread_priority() { if(d_detail) { return d_detail->thread_priority(); } return -1; } int block::thread_priority() { return d_priority; } int block::set_thread_priority(int priority) { d_priority = priority; if(d_detail) { return d_detail->set_thread_priority(priority); } return d_priority; } void block::expand_minmax_buffer(int port) { if((size_t)port >= d_max_output_buffer.size()) set_max_output_buffer(port, -1); if((size_t)port >= d_min_output_buffer.size()) set_min_output_buffer(port, -1); } long block::max_output_buffer(size_t i) { if(i >= d_max_output_buffer.size()) throw std::invalid_argument("basic_block::max_output_buffer: port out of range."); return d_max_output_buffer[i]; } void block::set_max_output_buffer(long max_output_buffer) { for(int i = 0; i < output_signature()->max_streams(); i++) { set_max_output_buffer(i, max_output_buffer); } } void block::set_max_output_buffer(int port, long max_output_buffer) { if((size_t)port >= d_max_output_buffer.size()) d_max_output_buffer.push_back(max_output_buffer); else d_max_output_buffer[port] = max_output_buffer; } long block::min_output_buffer(size_t i) { if(i >= d_min_output_buffer.size()) throw std::invalid_argument("basic_block::min_output_buffer: port out of range."); return d_min_output_buffer[i]; } void block::set_min_output_buffer(long min_output_buffer) { std::cout << "set_min_output_buffer on block " << unique_id() << " to " << min_output_buffer << std::endl; for(int i=0; imax_streams(); i++) { set_min_output_buffer(i, min_output_buffer); } } void block::set_min_output_buffer(int port, long min_output_buffer) { if((size_t)port >= d_min_output_buffer.size()) d_min_output_buffer.push_back(min_output_buffer); else d_min_output_buffer[port] = min_output_buffer; } bool block::update_rate() const { return d_update_rate; } void block::enable_update_rate(bool en) { d_update_rate = en; } float block::pc_noutput_items() { if(d_detail) { return d_detail->pc_noutput_items(); } else { return 0; } } float block::pc_noutput_items_avg() { if(d_detail) { return d_detail->pc_noutput_items_avg(); } else { return 0; } } float block::pc_noutput_items_var() { if(d_detail) { return d_detail->pc_noutput_items_var(); } else { return 0; } } float block::pc_nproduced() { if(d_detail) { return d_detail->pc_nproduced(); } else { return 0; } } float block::pc_nproduced_avg() { if(d_detail) { return d_detail->pc_nproduced_avg(); } else { return 0; } } float block::pc_nproduced_var() { if(d_detail) { return d_detail->pc_nproduced_var(); } else { return 0; } } float block::pc_input_buffers_full(int which) { if(d_detail) { return d_detail->pc_input_buffers_full(static_cast(which)); } else { return 0; } } float block::pc_input_buffers_full_avg(int which) { if(d_detail) { return d_detail->pc_input_buffers_full_avg(static_cast(which)); } else { return 0; } } float block::pc_input_buffers_full_var(int which) { if(d_detail) { return d_detail->pc_input_buffers_full_var(static_cast(which)); } else { return 0; } } std::vector block::pc_input_buffers_full() { if(d_detail) { return d_detail->pc_input_buffers_full(); } else { return std::vector(1,0); } } std::vector block::pc_input_buffers_full_avg() { if(d_detail) { return d_detail->pc_input_buffers_full_avg(); } else { return std::vector(1,0); } } std::vector block::pc_input_buffers_full_var() { if(d_detail) { return d_detail->pc_input_buffers_full_var(); } else { return std::vector(1,0); } } float block::pc_output_buffers_full(int which) { if(d_detail) { return d_detail->pc_output_buffers_full(static_cast(which)); } else { return 0; } } float block::pc_output_buffers_full_avg(int which) { if(d_detail) { return d_detail->pc_output_buffers_full_avg(static_cast(which)); } else { return 0; } } float block::pc_output_buffers_full_var(int which) { if(d_detail) { return d_detail->pc_output_buffers_full_var(static_cast(which)); } else { return 0; } } std::vector block::pc_output_buffers_full() { if(d_detail) { return d_detail->pc_output_buffers_full(); } else { return std::vector(1,0); } } std::vector block::pc_output_buffers_full_avg() { if(d_detail) { return d_detail->pc_output_buffers_full_avg(); } else { return std::vector(1,0); } } std::vector block::pc_output_buffers_full_var() { if(d_detail) { return d_detail->pc_output_buffers_full_var(); } else { return std::vector(1,0); } } float block::pc_work_time() { if(d_detail) { return d_detail->pc_work_time(); } else { return 0; } } float block::pc_work_time_avg() { if(d_detail) { return d_detail->pc_work_time_avg(); } else { return 0; } } float block::pc_work_time_var() { if(d_detail) { return d_detail->pc_work_time_var(); } else { return 0; } } float block::pc_work_time_total() { if(d_detail) { return d_detail->pc_work_time_total(); } else { return 0; } } void block::reset_perf_counters() { if(d_detail) { d_detail->reset_perf_counters(); } } void block::setup_pc_rpc() { d_pc_rpc_set = true; #ifdef GR_CTRLPORT d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "noutput_items", &block::pc_noutput_items, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "noutput items", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "avg noutput_items", &block::pc_noutput_items_avg, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "Average noutput items", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "var noutput_items", &block::pc_noutput_items_var, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "Var. noutput items", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "nproduced", &block::pc_nproduced, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "items produced", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "avg nproduced", &block::pc_nproduced_avg, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "Average items produced", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "var nproduced", &block::pc_nproduced_var, pmt::mp(0), pmt::mp(32768), pmt::mp(0), "", "Var. items produced", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "work time", &block::pc_work_time, pmt::mp(0), pmt::mp(1e9), pmt::mp(0), "", "clock cycles in call to work", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "avg work time", &block::pc_work_time_avg, pmt::mp(0), pmt::mp(1e9), pmt::mp(0), "", "Average clock cycles in call to work", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "var work time", &block::pc_work_time_var, pmt::mp(0), pmt::mp(1e9), pmt::mp(0), "", "Var. clock cycles in call to work", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "total work time", &block::pc_work_time_total, pmt::mp(0), pmt::mp(1e9), pmt::mp(0), "", "Total clock cycles in calls to work", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "input \% full", &block::pc_input_buffers_full, pmt::make_c32vector(0,0), pmt::make_c32vector(0,1), pmt::make_c32vector(0,0), "", "how full input buffers are", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "avg input \% full", &block::pc_input_buffers_full_avg, pmt::make_c32vector(0,0), pmt::make_c32vector(0,1), pmt::make_c32vector(0,0), "", "Average of how full input buffers are", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "var input \% full", &block::pc_input_buffers_full_var, pmt::make_c32vector(0,0), pmt::make_c32vector(0,1), pmt::make_c32vector(0,0), "", "Var. of how full input buffers are", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "output \% full", &block::pc_output_buffers_full, pmt::make_c32vector(0,0), pmt::make_c32vector(0,1), pmt::make_c32vector(0,0), "", "how full output buffers are", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "avg output \% full", &block::pc_output_buffers_full_avg, pmt::make_c32vector(0,0), pmt::make_c32vector(0,1), pmt::make_c32vector(0,0), "", "Average of how full output buffers are", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), "var output \% full", &block::pc_output_buffers_full_var, pmt::make_c32vector(0,0), pmt::make_c32vector(0,1), pmt::make_c32vector(0,0), "", "Var. of how full output buffers are", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } std::ostream& operator << (std::ostream& os, const block *m) { os << "name() << " (" << m->unique_id() << ")>"; return os; } int block::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { throw std::runtime_error("block::general_work() not implemented"); return 0; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/sys_paths.cc0000664000175000017500000000320212207440367021711 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include //getenv #include //P_tmpdir (maybe) namespace gr { const char *tmp_path() { const char *path; //first case, try TMP environment variable path = getenv("TMP"); if(path) return path; //second case, try P_tmpdir when its defined #ifdef P_tmpdir if(P_tmpdir) return P_tmpdir; #endif /*P_tmpdir*/ //fall-through case, nothing worked return "/tmp"; } const char *appdata_path() { const char *path; //first case, try HOME environment variable (unix) path = getenv("HOME"); if(path) return path; //second case, try APPDATA environment variable (windows) path = getenv("APPDATA"); if(path) return path; //fall-through case, nothing worked return tmp_path(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/hier_block2_detail.h0000664000175000017500000000561312207702530023244 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_HIER_BLOCK2_DETAIL_H #define INCLUDED_GR_RUNTIME_HIER_BLOCK2_DETAIL_H #include #include #include #include namespace gr { /*! * \ingroup internal */ class GR_RUNTIME_API hier_block2_detail : boost::noncopyable { public: hier_block2_detail(hier_block2 *owner); ~hier_block2_detail(); void connect(basic_block_sptr block); void connect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port); void msg_connect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport); void msg_disconnect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport); void disconnect(basic_block_sptr block); void disconnect(basic_block_sptr, int src_port, basic_block_sptr, int dst_port); void disconnect_all(); void lock(); void unlock(); void flatten_aux(flat_flowgraph_sptr sfg) const; void set_processor_affinity(const std::vector &mask); void unset_processor_affinity(); std::vector processor_affinity(); private: // Private implementation data hier_block2 *d_owner; hier_block2_detail *d_parent_detail; flowgraph_sptr d_fg; std::vector d_inputs; // Multiple internal endpoints per external input endpoint_vector_t d_outputs; // Single internal endpoint per external output basic_block_vector_t d_blocks; void connect_input(int my_port, int port, basic_block_sptr block); void connect_output(int my_port, int port, basic_block_sptr block); void disconnect_input(int my_port, int port, basic_block_sptr block); void disconnect_output(int my_port, int port, basic_block_sptr block); endpoint_vector_t resolve_port(int port, bool is_input); endpoint_vector_t resolve_endpoint(const endpoint &endp, bool is_input) const; }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_HIER_BLOCK2_DETAIL_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/scheduler.h0000664000175000017500000000355612207440367021530 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_SCHEDULER_H #define INCLUDED_GR_SCHEDULER_H #include #include #include #include "flat_flowgraph.h" namespace gr { class scheduler; typedef boost::shared_ptr scheduler_sptr; /*! * \brief Abstract scheduler that takes a flattened flow graph and * runs it. * * Preconditions: details, buffers and buffer readers have been * assigned. */ class GR_RUNTIME_API scheduler : boost::noncopyable { public: /*! * \brief Construct a scheduler and begin evaluating the graph. * * The scheduler will continue running until all blocks until they * report that they are done or the stop method is called. */ scheduler(flat_flowgraph_sptr ffg, int max_noutput_items); virtual ~scheduler(); /*! * \brief Tell the scheduler to stop executing. */ virtual void stop() = 0; /*! * \brief Block until the graph is done. */ virtual void wait() = 0; }; } /* namespace gr */ #endif /* INCLUDED_GR_SCHEDULER_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/tpb_thread_body.cc0000664000175000017500000001306212214652673023035 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "tpb_thread_body.h" #include #include #include #include #include namespace gr { tpb_thread_body::tpb_thread_body(block_sptr block, int max_noutput_items) : d_exec(block, max_noutput_items) { //std::cerr << "tpb_thread_body: " << block << std::endl; block_detail *d = block->detail().get(); block_executor::state s; pmt::pmt_t msg; d->threaded = true; d->thread = gr::thread::get_current_thread_id(); prefs *p = prefs::singleton(); size_t max_nmsgs = static_cast(p->get_long("DEFAULT", "max_messages", 100)); // Set thread affinity if it was set before fg was started. if(block->processor_affinity().size() > 0) { gr::thread::thread_bind_to_processor(d->thread, block->processor_affinity()); } // Set thread priority if it was set before fg was started if(block->thread_priority() > 0) { gr::thread::set_thread_priority(d->thread, block->thread_priority()); } while(1) { boost::this_thread::interruption_point(); // handle any queued up messages BOOST_FOREACH(basic_block::msg_queue_map_t::value_type &i, block->msg_queue) { // Check if we have a message handler attached before getting // any messages. This is mostly a protection for the unknown // startup sequence of the threads. if(block->has_msg_handler(i.first)) { while((msg = block->delete_head_nowait(i.first))) { block->dispatch_msg(i.first,msg); } } else { // If we don't have a handler but are building up messages, // prune the queue from the front to keep memory in check. if(block->nmsgs(i.first) > max_nmsgs) msg = block->delete_head_nowait(i.first); } } d->d_tpb.clear_changed(); // run one iteration if we are a connected stream block if(d->noutputs() >0 || d->ninputs()>0){ s = d_exec.run_one_iteration(); } else { s = block_executor::BLKD_IN; } switch(s){ case block_executor::READY: // Tell neighbors we made progress. d->d_tpb.notify_neighbors(d); break; case block_executor::READY_NO_OUTPUT: // Notify upstream only d->d_tpb.notify_upstream(d); break; case block_executor::DONE: // Game over. d->d_tpb.notify_neighbors(d); return; case block_executor::BLKD_IN: // Wait for input. { gr::thread::scoped_lock guard(d->d_tpb.mutex); while(!d->d_tpb.input_changed) { // wait for input or message while(!d->d_tpb.input_changed && block->empty_handled_p()) d->d_tpb.input_cond.wait(guard); // handle all pending messages BOOST_FOREACH(basic_block::msg_queue_map_t::value_type &i, block->msg_queue) { if(block->has_msg_handler(i.first)) { while((msg = block->delete_head_nowait(i.first))) { guard.unlock(); // release lock while processing msg block->dispatch_msg(i.first, msg); guard.lock(); } } else { // leave msg in queue if no handler is defined // start dropping if we have too many if(block->nmsgs(i.first) > max_nmsgs) msg = block->delete_head_nowait(i.first); } } if (d->done()) { return; } } } break; case block_executor::BLKD_OUT: // Wait for output buffer space. { gr::thread::scoped_lock guard(d->d_tpb.mutex); while(!d->d_tpb.output_changed) { // wait for output room or message while(!d->d_tpb.output_changed && block->empty_handled_p()) d->d_tpb.output_cond.wait(guard); // handle all pending messages BOOST_FOREACH(basic_block::msg_queue_map_t::value_type &i, block->msg_queue) { if(block->has_msg_handler(i.first)) { while((msg = block->delete_head_nowait(i.first))) { guard.unlock(); // release lock while processing msg block->dispatch_msg(i.first, msg); guard.lock(); } } else { // leave msg in queue if no handler is defined // start dropping if we have too many if(block->nmsgs(i.first) > max_nmsgs) msg = block->delete_head_nowait(i.first); } } } } break; default: throw std::runtime_error("possible memory corruption in scheduler"); } } } tpb_thread_body::~tpb_thread_body() { } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_circular_file.cc0000664000175000017500000000364512207440367023173 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "qa_circular_file.h" #include "circular_file.h" #include #include #include #include static const char *test_file = "qa_gr_circular_file.data"; static const int BUFFER_SIZE = 8192; static const int NWRITE = 8192 * 9 / 8; void qa_circular_file::t1() { #ifdef HAVE_MMAP gr::circular_file *cf_writer; gr::circular_file *cf_reader; // write the data... cf_writer = new gr::circular_file(test_file, true, BUFFER_SIZE * sizeof(short)); short sd; for(int i = 0; i < NWRITE; i++) { sd = i; cf_writer->write(&sd, sizeof (sd)); } delete cf_writer; // now read it back... cf_reader = new gr::circular_file(test_file); for(int i = 0; i < BUFFER_SIZE; i++) { int n = cf_reader->read (&sd, sizeof(sd)); CPPUNIT_ASSERT_EQUAL((int) sizeof (sd), n); CPPUNIT_ASSERT_EQUAL(NWRITE - BUFFER_SIZE + i, (int)sd); } int n = cf_reader->read(&sd, sizeof(sd)); CPPUNIT_ASSERT_EQUAL(0, n); delete cf_reader; unlink(test_file); #endif // HAVE_MMAP } gnuradio-3.7.2.1/gnuradio-runtime/lib/complex_vec_test.h0000664000175000017500000000271712207440367023113 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include GR_RUNTIME_API std::vector > complex_vec_test0(); GR_RUNTIME_API std::vector > complex_vec_test1(const std::vector > &input); GR_RUNTIME_API std::complex complex_scalar_test0(); GR_RUNTIME_API std::complex complex_scalar_test1(std::complex input); GR_RUNTIME_API std::vector int_vec_test0(); GR_RUNTIME_API std::vector int_vec_test1(const std::vector &input); GR_RUNTIME_API std::vector float_vec_test0(); GR_RUNTIME_API std::vector float_vec_test1(const std::vector &input); gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_buffer.cc0000664000175000017500000001507512207440367021641 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include static void leak_check(void f()) { long buffer_count = gr::buffer_ncurrently_allocated(); long buffer_reader_count = gr::buffer_reader_ncurrently_allocated(); f(); CPPUNIT_ASSERT_EQUAL(buffer_reader_count, gr::buffer_reader_ncurrently_allocated()); CPPUNIT_ASSERT_EQUAL(buffer_count, gr::buffer_ncurrently_allocated()); } // ---------------------------------------------------------------------------- // test single writer, no readers... // static void t0_body() { int nitems = 4000 / sizeof(int); int counter = 0; gr::buffer_sptr buf(gr::make_buffer(nitems, sizeof(int), gr::block_sptr())); int last_sa; int sa; sa = buf->space_available(); CPPUNIT_ASSERT(sa > 0); last_sa = sa; for(int i = 0; i < 5; i++) { sa = buf->space_available(); CPPUNIT_ASSERT_EQUAL(last_sa, sa); last_sa = sa; int *p = (int*)buf->write_pointer(); CPPUNIT_ASSERT(p != 0); for(int j = 0; j < sa; j++) *p++ = counter++; buf->update_write_pointer(sa); } } // ---------------------------------------------------------------------------- // test single writer, single reader // static void t1_body() { int nitems = 4000 / sizeof(int); int write_counter = 0; int read_counter = 0; gr::buffer_sptr buf(gr::make_buffer(nitems, sizeof(int), gr::block_sptr())); gr::buffer_reader_sptr r1(gr::buffer_add_reader(buf, 0, gr::block_sptr())); int sa; // write 1/3 of buffer sa = buf->space_available(); CPPUNIT_ASSERT(sa > 0); int *p = (int*)buf->write_pointer(); CPPUNIT_ASSERT(p != 0); for(int j = 0; j < sa/3; j++) { *p++ = write_counter++; } buf->update_write_pointer(sa/3); // write the next 1/3 (1/2 of what's left) sa = buf->space_available(); CPPUNIT_ASSERT(sa > 0); p = (int*)buf->write_pointer(); CPPUNIT_ASSERT(p != 0); for(int j = 0; j < sa/2; j++) { *p++ = write_counter++; } buf->update_write_pointer(sa/2); // check that we can read it OK int ia = r1->items_available(); CPPUNIT_ASSERT_EQUAL(write_counter, ia); int *rp = (int*)r1->read_pointer(); CPPUNIT_ASSERT(rp != 0); for(int i = 0; i < ia/2; i++) { CPPUNIT_ASSERT_EQUAL(read_counter, *rp); read_counter++; rp++; } r1->update_read_pointer(ia/2); // read the rest ia = r1->items_available(); rp = (int *) r1->read_pointer(); CPPUNIT_ASSERT(rp != 0); for(int i = 0; i < ia; i++) { CPPUNIT_ASSERT_EQUAL(read_counter, *rp); read_counter++; rp++; } r1->update_read_pointer(ia); } // ---------------------------------------------------------------------------- // single writer, single reader: check wrap-around // static void t2_body() { // 64K is the largest granularity we've seen so far (MS windows file mapping). // This allows a bit of "white box testing" int nitems = (64 * (1L << 10)) / sizeof(int); // 64K worth of ints gr::buffer_sptr buf(gr::make_buffer(nitems, sizeof(int), gr::block_sptr())); gr::buffer_reader_sptr r1(gr::buffer_add_reader(buf, 0, gr::block_sptr())); int read_counter = 0; int write_counter = 0; int n; int *wp = 0; int *rp = 0; // Write 3/4 of buffer n = (int)(buf->space_available() * 0.75); wp = (int*)buf->write_pointer(); for(int i = 0; i < n; i++) *wp++ = write_counter++; buf->update_write_pointer(n); // Now read it all int m = r1->items_available(); CPPUNIT_ASSERT_EQUAL(n, m); rp = (int*)r1->read_pointer(); for(int i = 0; i < m; i++) { CPPUNIT_ASSERT_EQUAL(read_counter, *rp); read_counter++; rp++; } r1->update_read_pointer(m); // Now write as much as we can. // This will wrap around the buffer n = buf->space_available(); CPPUNIT_ASSERT_EQUAL(nitems - 1, n); // white box test wp = (int*)buf->write_pointer(); for(int i = 0; i < n; i++) *wp++ = write_counter++; buf->update_write_pointer(n); // now read it all m = r1->items_available(); CPPUNIT_ASSERT_EQUAL(n, m); rp = (int*)r1->read_pointer(); for(int i = 0; i < m; i++) { CPPUNIT_ASSERT_EQUAL(read_counter, *rp); read_counter++; rp++; } r1->update_read_pointer(m); } // ---------------------------------------------------------------------------- // single writer, N readers, randomized order and lengths // ---------------------------------------------------------------------------- static void t3_body() { int nitems = (64 * (1L << 10)) / sizeof(int); static const int N = 5; gr::buffer_sptr buf(gr::make_buffer(nitems, sizeof(int), gr::block_sptr())); gr::buffer_reader_sptr reader[N]; int read_counter[N]; int write_counter = 0; gr::random random; for(int i = 0; i < N; i++) { read_counter[i] = 0; reader[i] = buffer_add_reader(buf, 0, gr::block_sptr()); } for(int lc = 0; lc < 1000; lc++) { // write some int n = (int)(buf->space_available() * random.ran1()); int *wp = (int*)buf->write_pointer(); for(int i = 0; i < n; i++) *wp++ = write_counter++; buf->update_write_pointer(n); // pick a random reader and read some int r = (int)(N * random.ran1()); CPPUNIT_ASSERT(0 <= r && r < N); int m = reader[r]->items_available(); int *rp = (int*)reader[r]->read_pointer(); for(int i = 0; i < m; i++) { CPPUNIT_ASSERT_EQUAL(read_counter[r], *rp); read_counter[r]++; rp++; } reader[r]->update_read_pointer (m); } } // ---------------------------------------------------------------------------- void qa_buffer::t0() { leak_check(t0_body); } void qa_buffer::t1() { leak_check(t1_body); } void qa_buffer::t2() { leak_check(t2_body); } void qa_buffer::t3() { leak_check(t3_body); } void qa_buffer::t4() { } void qa_buffer::t5() { } gnuradio-3.7.2.1/gnuradio-runtime/lib/tpb_detail.cc0000664000175000017500000000413512207440367022011 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include namespace gr { /* * We assume that no worker threads are ever running when the graph * structure is being manipulated, thus it's safe for us to poke * around in our neighbors w/o holding any locks. */ void tpb_detail::notify_upstream(block_detail *d) { // For each of our inputs, tell the guy upstream that we've // consumed some input, and that he most likely has more output // buffer space available. for(size_t i = 0; i < d->d_input.size(); i++) { // Can you say, "pointer chasing?" d->d_input[i]->buffer()->link()->detail()->d_tpb.set_output_changed(); } } void tpb_detail::notify_downstream(block_detail *d) { // For each of our outputs, tell the guys downstream that they // have new input available. for(size_t i = 0; i < d->d_output.size(); i++) { buffer_sptr buf = d->d_output[i]; for(size_t j = 0, k = buf->nreaders(); j < k; j++) buf->reader(j)->link()->detail()->d_tpb.set_input_changed(); } } void tpb_detail::notify_neighbors(block_detail *d) { notify_downstream(d); notify_upstream(d); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_logger.h0000664000175000017500000000227412207440367021506 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU Example Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Example Public License for more details. * * You should have received a copy of the GNU Example Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_LOG_H #define INCLUDED_QA_GR_LOG_H #include #include //! collect all the tests for the example directory class qa_logger : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(qa_logger); CPPUNIT_TEST(t1); CPPUNIT_TEST_SUITE_END(); private: void t1(); }; #endif /* INCLUDED_QA_GR_LOG_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_createfilemapping.cc0000664000175000017500000001600112207440367025414 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2005,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_MMAN_H #include #endif #include #include #include "pagesize.h" #include "vmcircbuf_createfilemapping.h" #include namespace gr { #ifdef HAVE_CREATEFILEMAPPING // Print Windows error (could/should be global?) static void werror(char *where, DWORD last_error) { char buf[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, last_error, 0, // default language buf, sizeof(buf)/sizeof(TCHAR), // buffer size NULL); fprintf(stderr, "%s: Error %d: %s", where, last_error, buf); return; } #endif vmcircbuf_createfilemapping::vmcircbuf_createfilemapping(int size) : gr::vmcircbuf(size) { #if !defined(HAVE_CREATEFILEMAPPING) fprintf(stderr, "%s: createfilemapping is not available\n", __FUNCTION__); throw std::runtime_error("gr::vmcircbuf_createfilemapping"); #else gr::thread::scoped_lock guard(s_vm_mutex); static int s_seg_counter = 0; if(size <= 0 || (size % gr::pagesize ()) != 0) { fprintf(stderr, "gr::vmcircbuf_createfilemapping: invalid size = %d\n", size); throw std::runtime_error ("gr::vmcircbuf_createfilemapping"); } std::string seg_name = str(boost::format("/gnuradio-%d-%d") % getpid() % s_seg_counter); d_handle = CreateFileMapping(INVALID_HANDLE_VALUE, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // max. object size size, // buffer size seg_name.c_str()); // name of mapping object s_seg_counter++; if(d_handle == NULL || d_handle == INVALID_HANDLE_VALUE) { std::string msg = str(boost::format( "gr::vmcircbuf_mmap_createfilemapping: CreateFileMapping [%s]") % seg_name); werror((char*)msg.c_str(), GetLastError()); throw std::runtime_error("gr::vmcircbuf_mmap_createfilemapping"); } // Allocate virtual memory of the needed size, then free it so we can use it LPVOID first_tmp; first_tmp = VirtualAlloc( NULL, 2*size, MEM_RESERVE, PAGE_NOACCESS ); if(first_tmp == NULL) { werror("gr::vmcircbuf_mmap_createfilemapping: VirtualAlloc", GetLastError()); CloseHandle(d_handle); // cleanup throw std::runtime_error("gr::vmcircbuf_mmap_createfilemapping"); } if(VirtualFree(first_tmp, 0, MEM_RELEASE) == 0) { werror("gr::vmcircbuf_mmap_createfilemapping: VirtualFree", GetLastError()); CloseHandle(d_handle); // cleanup throw std::runtime_error("gr::vmcircbuf_mmap_createfilemapping"); } d_first_copy = MapViewOfFileEx((HANDLE)d_handle, // handle to map object FILE_MAP_WRITE, // read/write permission 0, 0, size, first_tmp); if(d_first_copy != first_tmp) { werror( "gr::vmcircbuf_mmap_createfilemapping: MapViewOfFileEx(1)", GetLastError()); CloseHandle(d_handle); // cleanup throw std::runtime_error ("gr::vmcircbuf_mmap_createfilemapping"); } d_second_copy = MapViewOfFileEx((HANDLE)d_handle, // handle to map object FILE_MAP_WRITE, // read/write permission 0, 0, size, (char*)first_tmp + size);//(LPVOID) ((char *)d_first_copy + size)); if(d_second_copy != (char *)first_tmp + size) { werror( "gr::vmcircbuf_mmap_createfilemapping: MapViewOfFileEx(2)", GetLastError()); UnmapViewOfFile(d_first_copy); CloseHandle(d_handle); // cleanup throw std::runtime_error ("gr::vmcircbuf_mmap_createfilemapping"); } #ifdef DEBUG fprintf(stderr,"gr::vmcircbuf_mmap_createfilemapping: contiguous? mmap %p %p %p %p\n", (char*)d_first_copy, (char*)d_second_copy, size, (char*)d_first_copy + size); #endif // Now remember the important stuff d_base = (char*)d_first_copy; d_size = size; #endif /*HAVE_CREATEFILEMAPPING*/ } vmcircbuf_createfilemapping::~vmcircbuf_createfilemapping() { #ifdef HAVE_CREATEFILEMAPPING gr::thread::scoped_lock guard(s_vm_mutex); if(UnmapViewOfFile(d_first_copy) == 0) { werror("gr::vmcircbuf_createfilemapping: UnmapViewOfFile(d_first_copy)", GetLastError()); } d_base=NULL; if(UnmapViewOfFile(d_second_copy) == 0) { werror("gr::vmcircbuf_createfilemapping: UnmapViewOfFile(d_second_copy)", GetLastError()); } //d_second=NULL; CloseHandle(d_handle); #endif } // ---------------------------------------------------------------- // The factory interface // ---------------------------------------------------------------- gr::vmcircbuf_factory *vmcircbuf_createfilemapping_factory::s_the_factory = 0; gr::vmcircbuf_factory * vmcircbuf_createfilemapping_factory::singleton() { if(s_the_factory) return s_the_factory; s_the_factory = new vmcircbuf_createfilemapping_factory(); return s_the_factory; } int vmcircbuf_createfilemapping_factory::granularity() { #ifdef HAVE_CREATEFILEMAPPING // return 65536;//TODO, check, is this needed or can we just use gr::pagesize() SYSTEM_INFO system_info; GetSystemInfo(&system_info); //fprintf(stderr,"win32 AllocationGranularity %p\n",(int)system_info.dwAllocationGranularity); return (int)system_info.dwAllocationGranularity; #else return gr::pagesize(); #endif } gr::vmcircbuf * vmcircbuf_createfilemapping_factory::make(int size) { try { return new vmcircbuf_createfilemapping(size); } catch(...) { return 0; } } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/high_res_timer.cc0000664000175000017500000000022512207440367022666 0ustar jcorganjcorgan#include #ifdef GNURADIO_HRT_USE_CLOCK_GETTIME clockid_t gr::high_res_timer_source = CLOCK_THREAD_CPUTIME_ID; #endif gnuradio-3.7.2.1/gnuradio-runtime/lib/flat_flowgraph.h0000664000175000017500000000571212207440367022545 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_RUNTIME_FLAT_FLOWGRAPH_H #define INCLUDED_GR_RUNTIME_FLAT_FLOWGRAPH_H #include #include #include namespace gr { // Create a shared pointer to a heap allocated gr::flat_flowgraph // (types defined in gr_runtime_types.h) GR_RUNTIME_API flat_flowgraph_sptr make_flat_flowgraph(); /*! *\brief Class specializing gr_flat_flowgraph that has all nodes * as blocks, with no hierarchy * \ingroup internal */ class GR_RUNTIME_API flat_flowgraph : public flowgraph { public: friend GR_RUNTIME_API flat_flowgraph_sptr make_flat_flowgraph(); // Destruct an arbitrary gr::flat_flowgraph ~flat_flowgraph(); // Wire list of gr::block together in new flat_flowgraph void setup_connections(); // Merge applicable connections from existing flat flowgraph void merge_connections(flat_flowgraph_sptr sfg); // Return a string list of edges std::string edge_list(); // Return a string list of msg edges std::string msg_edge_list(); void dump(); /*! * Make a vector of gr::block from a vector of gr::basic_block */ static block_vector_t make_block_vector(basic_block_vector_t &blocks); void replace_endpoint(const msg_endpoint &e, const msg_endpoint &r, bool is_src); void clear_endpoint(const msg_endpoint &e, bool is_src); /*! * Enables export of perf. counters to ControlPort on all blocks in * the flowgraph. */ void enable_pc_rpc(); private: flat_flowgraph(); block_detail_sptr allocate_block_detail(basic_block_sptr block); buffer_sptr allocate_buffer(basic_block_sptr block, int port); void connect_block_inputs(basic_block_sptr block); /* When reusing a flowgraph's blocks, this call makes sure all of * the buffer's are aligned at the machine's alignment boundary * and tells the blocks that they are aligned. * * Called from both setup_connections and merge_connections for * start and restarts. */ void setup_buffer_alignment(block_sptr block); }; } /* namespace gr */ #endif /* INCLUDED_GR_RUNTIME_FLAT_FLOWGRAPH_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/test.h0000664000175000017500000001762012207440367020526 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TEST_H #define INCLUDED_GR_TEST_H #include #include #include #include "test_types.h" namespace gr { class test; typedef boost::shared_ptr test_sptr; // public constructor GR_RUNTIME_API test_sptr make_test(const std::string &name=std::string("test"), int min_inputs=1, int max_inputs=1, unsigned int sizeof_input_item=1, int min_outputs=1, int max_outputs=1, unsigned int sizeof_output_item=1, unsigned int history=1,unsigned int output_multiple=1,double relative_rate=1.0, bool fixed_rate=true,consume_type_t cons_type=CONSUME_NOUTPUT_ITEMS, produce_type_t prod_type=PRODUCE_NOUTPUT_ITEMS); /*! * \brief Test class for testing runtime system (setting up buffers and such.) * \ingroup misc * * This block does not do any usefull actual data processing. It * just exposes setting all standard block parameters using the * contructor or public methods. * * This block can be usefull when testing the runtime system. * You can force this block to have a large history, decimation * factor and/or large output_multiple. * The runtime system should detect this and create large enough buffers * all through the signal chain. */ class GR_RUNTIME_API test : public block { public: ~test() {} int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); // ---------------------------------------------------------------- // override these to define your behavior // ---------------------------------------------------------------- /*! * \brief Estimate input requirements given output request * * \param noutput_items number of output items to produce * \param ninput_items_required number of input items required on each input stream * * Given a request to product \p noutput_items, estimate the * number of data items required on each input stream. The * estimate doesn't have to be exact, but should be close. */ void forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = (int)((double)noutput_items / relative_rate()) + (int)history(); } /*! * \brief Force check topology to return true or false. * * \param check_topology value to return when check_topology is * called (true or false) default check_topology returns true */ void set_check_topology(bool check_topology) { d_check_topology=check_topology; } /*! * \brief Confirm that ninputs and noutputs is an acceptable combination. * * \param ninputs number of input streams connected * \param noutputs number of output streams connected * * \returns true if this is a valid configuration for this block. * * This function is called by the runtime system whenever the * topology changes. Most classes do not need to override this. * This check is in addition to the constraints specified by the * input and output gr::io_signatures. */ bool check_topology(int ninputs, int noutputs) { return d_check_topology; } // ---------------------------------------------------------------- /* * The following two methods provide special case info to the * scheduler in the event that a block has a fixed input to output * ratio. gr::sync_block, gr::sync_decimator and * gr::sync_interpolator override these. If you're fixed rate, * subclass one of those. */ /*! * \brief Given ninput samples, return number of output samples * that will be produced. N.B. this is only defined if fixed_rate * returns true. Generally speaking, you don't need to override * this. */ int fixed_rate_ninput_to_noutput(int ninput) { return (int)((double)ninput/relative_rate()); } /*! * \brief Given noutput samples, return number of input samples * required to produce noutput. N.B. this is only defined if * fixed_rate returns true. */ int fixed_rate_noutput_to_ninput(int noutput) { return (int)((double)noutput*relative_rate()); } /*! * \brief Set if fixed rate should return true. * N.B. This is normally a private method but we make it available here as public. */ void set_fixed_rate_public(bool fixed_rate) { set_fixed_rate(fixed_rate); } /*! * \brief Set the consume pattern. * * \param cons_type which consume pattern to use */ void set_consume_type(consume_type_t cons_type) { d_consume_type=cons_type; } /*! * \brief Set the consume limit. * * \param limit min or maximum items to consume (depending on * consume_type) */ void set_consume_limit(unsigned int limit) { d_min_consume=limit; d_max_consume=limit; } /*! * \brief Set the produce pattern. * * \param prod_type which produce pattern to use */ void set_produce_type(produce_type_t prod_type) { d_produce_type=prod_type; } /*! * \brief Set the produce limit. * * \param limit min or maximum items to produce (depending on * produce_type) */ void set_produce_limit(unsigned int limit) { d_min_produce=limit; d_max_produce=limit; } // ---------------------------------------------------------------------------- protected: unsigned int d_sizeof_input_item; unsigned int d_sizeof_output_item; bool d_check_topology; char d_temp; consume_type_t d_consume_type; int d_min_consume; int d_max_consume; produce_type_t d_produce_type; int d_min_produce; int d_max_produce; test(const std::string &name,int min_inputs, int max_inputs, unsigned int sizeof_input_item, int min_outputs, int max_outputs, unsigned int sizeof_output_item, unsigned int history, unsigned int output_multiple, double relative_rate, bool fixed_rate, consume_type_t cons_type, produce_type_t prod_type); friend GR_RUNTIME_API test_sptr make_test(const std::string &name, int min_inputs, int max_inputs, unsigned int sizeof_input_item, int min_outputs, int max_outputs, unsigned int sizeof_output_item, unsigned int history, unsigned int output_multiple, double relative_rate, bool fixed_rate, consume_type_t cons_type, produce_type_t prod_type); }; } /* namespace gr */ #endif /* INCLUDED_TEST_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_buffer.h0000664000175000017500000000244712207440367021502 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_BUFFER_H #define INCLUDED_QA_GR_BUFFER_H #include #include class qa_buffer : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_buffer); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST(t4); CPPUNIT_TEST(t5); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1(); void t2(); void t3(); void t4(); void t5(); }; #endif /* INCLUDED_QA_GR_BUFFER_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/gnuradio-runtime.rc.in0000664000175000017500000000333212207440367023615 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-runtime" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-runtime.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-runtime.dll" VALUE "ProductName", "gnuradio-runtime" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_sysv_shm.h0000664000175000017500000000365612207440367023466 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_VMCIRCBUF_SYSV_SHM_H #define GR_VMCIRCBUF_SYSV_SHM_H #include #include "vmcircbuf.h" namespace gr { /*! * \brief concrete class to implement circular buffers with mmap and shm_open * \ingroup internal */ class GR_RUNTIME_API vmcircbuf_sysv_shm : public gr::vmcircbuf { public: vmcircbuf_sysv_shm(int size); virtual ~vmcircbuf_sysv_shm(); }; /*! * \brief concrete factory for circular buffers built using mmap and shm_open */ class GR_RUNTIME_API vmcircbuf_sysv_shm_factory : public gr::vmcircbuf_factory { private: static gr::vmcircbuf_factory *s_the_factory; public: static gr::vmcircbuf_factory *singleton(); virtual const char *name() const { return "gr::vmcircbuf_sysv_shm_factory"; } /*! * \brief return granularity of mapping, typically equal to page size */ virtual int granularity(); /*! * \brief return a gr::vmcircbuf, or 0 if unable. * * Call this to create a doubly mapped circular buffer. */ virtual gr::vmcircbuf *make(int size); }; } /* namespace gr */ #endif /* GR_VMCIRCBUF_SYSV_SHM_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_vmcircbuf.h0000664000175000017500000000220612207440367022202 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef QA_GR_VMCIRCBUF_H #define QA_GR_VMCIRCBUF_H #include #include class qa_vmcircbuf : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_vmcircbuf); CPPUNIT_TEST(test_all); CPPUNIT_TEST_SUITE_END(); private: void test_all(); }; #endif /* QA_GR_VMCIRCBUF_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/local_sighandler.cc0000664000175000017500000000731712207440367023201 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "local_sighandler.h" #include #include #include namespace gr { local_sighandler::local_sighandler(int signum, void (*new_handler)(int)) : d_signum(signum) { #ifdef HAVE_SIGACTION struct sigaction new_action; memset(&new_action, 0, sizeof(new_action)); new_action.sa_handler = new_handler; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; if(sigaction (d_signum, &new_action, &d_old_action) < 0) { perror("sigaction (install new)"); throw std::runtime_error("sigaction"); } #endif } local_sighandler::~local_sighandler() { #ifdef HAVE_SIGACTION if(sigaction (d_signum, &d_old_action, 0) < 0) { perror("sigaction (restore old)"); throw std::runtime_error("sigaction"); } #endif } void local_sighandler::throw_signal(int signum) { throw signal(signum); } /* * Semi-hideous way to may a signal number into a signal name */ #define SIGNAME(x) case x: return #x std::string signal::name() const { char tmp[128]; switch(signum()) { #ifdef SIGHUP SIGNAME(SIGHUP); #endif #ifdef SIGINT SIGNAME(SIGINT); #endif #ifdef SIGQUIT SIGNAME(SIGQUIT); #endif #ifdef SIGILL SIGNAME(SIGILL); #endif #ifdef SIGTRAP SIGNAME(SIGTRAP); #endif #ifdef SIGABRT SIGNAME(SIGABRT); #endif #ifdef SIGBUS SIGNAME(SIGBUS); #endif #ifdef SIGFPE SIGNAME(SIGFPE); #endif #ifdef SIGKILL SIGNAME(SIGKILL); #endif #ifdef SIGUSR1 SIGNAME(SIGUSR1); #endif #ifdef SIGSEGV SIGNAME(SIGSEGV); #endif #ifdef SIGUSR2 SIGNAME(SIGUSR2); #endif #ifdef SIGPIPE SIGNAME(SIGPIPE); #endif #ifdef SIGALRM SIGNAME(SIGALRM); #endif #ifdef SIGTERM SIGNAME(SIGTERM); #endif #ifdef SIGSTKFLT SIGNAME(SIGSTKFLT); #endif #ifdef SIGCHLD SIGNAME(SIGCHLD); #endif #ifdef SIGCONT SIGNAME(SIGCONT); #endif #ifdef SIGSTOP SIGNAME(SIGSTOP); #endif #ifdef SIGTSTP SIGNAME(SIGTSTP); #endif #ifdef SIGTTIN SIGNAME(SIGTTIN); #endif #ifdef SIGTTOU SIGNAME(SIGTTOU); #endif #ifdef SIGURG SIGNAME(SIGURG); #endif #ifdef SIGXCPU SIGNAME(SIGXCPU); #endif #ifdef SIGXFSZ SIGNAME(SIGXFSZ); #endif #ifdef SIGVTALRM SIGNAME(SIGVTALRM); #endif #ifdef SIGPROF SIGNAME(SIGPROF); #endif #ifdef SIGWINCH SIGNAME(SIGWINCH); #endif #ifdef SIGIO SIGNAME(SIGIO); #endif #ifdef SIGPWR SIGNAME(SIGPWR); #endif #ifdef SIGSYS SIGNAME(SIGSYS); #endif default: #if defined (HAVE_SNPRINTF) #if defined (SIGRTMIN) && defined (SIGRTMAX) if(signum() >= SIGRTMIN && signum() <= SIGRTMAX) { snprintf(tmp, sizeof(tmp), "SIGRTMIN + %d", signum()); return tmp; } #endif snprintf(tmp, sizeof(tmp), "SIGNAL %d", signum()); return tmp; #else return "Unknown signal"; #endif } } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/sync_decimator.cc0000664000175000017500000000431712207440367022707 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { sync_decimator::sync_decimator(const std::string &name, io_signature::sptr input_signature, io_signature::sptr output_signature, unsigned decimation) : sync_block(name, input_signature, output_signature) { set_decimation(decimation); } void sync_decimator::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = fixed_rate_noutput_to_ninput(noutput_items); } int sync_decimator::fixed_rate_noutput_to_ninput(int noutput_items) { return noutput_items * decimation() + history() - 1; } int sync_decimator::fixed_rate_ninput_to_noutput(int ninput_items) { return std::max(0, ninput_items - (int)history() + 1) / decimation(); } int sync_decimator::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int r = work(noutput_items, input_items, output_items); if(r > 0) consume_each(r * decimation ()); return r; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/malloc16.c0000664000175000017500000000165412207440367021160 0ustar jcorganjcorgan/* Wrapper functions for malloc/free that force 16-byte alignment * See http://perso.club-internet.fr/matmac/sourcesc.htm * Copyright 2001 Phil Karn, KA9Q * May be used under the terms of the GNU Public License (GPL) */ #include "malloc16.h" #include void *malloc16Align(int size){ void *p; void **p1; if((p = malloc(size+31)) == NULL) return NULL; /* Round up to next 16-byte boundary */ p1 = (void **)(((long)p + 31) & (~15)); /* Stash actual start of block just before ptr we return */ p1[-1] = p; /* Return 16-byte aligned address */ return (void *)p1; } void *calloc16Align(size_t nmemb,size_t size){ int nbytes; void *p; nbytes = nmemb*size; if((p = malloc16Align(nbytes)) == NULL) return NULL; memset(p,0,nbytes); return p; } void free16Align(void *p){ if(p != NULL){ /* Retrieve pointer to actual start of block and free it */ free(((void **)p)[-1]); } } gnuradio-3.7.2.1/gnuradio-runtime/lib/top_block_impl.h0000664000175000017500000000464412207440367022546 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TOP_BLOCK_IMPL_H #define INCLUDED_GR_TOP_BLOCK_IMPL_H #include #include "scheduler.h" #include namespace gr { /*! *\brief Abstract implementation details of top_block * \ingroup internal * * The actual implementation of top_block. Separate class allows * decoupling of changes from dependent classes. */ class GR_RUNTIME_API top_block_impl { public: top_block_impl(top_block *owner); ~top_block_impl(); // Create and start scheduler threads void start(int max_noutput_items=100000000); // Signal scheduler threads to stop void stop(); // Wait for scheduler threads to exit void wait(); // Lock the top block to allow reconfiguration void lock(); // Unlock the top block at end of reconfiguration void unlock(); // Return a string list of edges std::string edge_list(); // Return a string list of msg edges std::string msg_edge_list(); // Dump the flowgraph to stdout void dump(); // Get the number of max noutput_items in the flowgraph int max_noutput_items(); // Set the maximum number of noutput_items in the flowgraph void set_max_noutput_items(int nmax); protected: enum tb_state { IDLE, RUNNING }; top_block *d_owner; flat_flowgraph_sptr d_ffg; scheduler_sptr d_scheduler; gr::thread::mutex d_mutex; // protects d_state and d_lock_count tb_state d_state; int d_lock_count; int d_max_noutput_items; private: void restart(); }; } /* namespace gr */ #endif /* INCLUDED_GR_TOP_BLOCK_IMPL_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/buffer.cc0000664000175000017500000002610512237515111021145 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "vmcircbuf.h" #include #include #include #include #include namespace gr { static long s_buffer_count = 0; // counts for debugging storage mgmt static long s_buffer_reader_count = 0; /* ---------------------------------------------------------------------------- Notes on storage management Pretty much all the fundamental classes are now using the shared_ptr stuff for automatic reference counting. To ensure that no mistakes are made, we make the constructors for classes private, and then provide a free factory function that returns a smart pointer to the desired class. gr::buffer and gr::buffer_reader are no exceptions. However, they both want pointers to each other, and unless we do something, we'll never delete any of them because of the circular structure. They'll always have a reference count of at least one. We could use boost::weak_ptr's from gr::buffer to gr::buffer_reader but that introduces it's own problems. (gr::buffer_reader's destructor needs to call gr::buffer::drop_reader, but has no easy way to get a shared_ptr to itself.) Instead, we solve this problem by having gr::buffer hold a raw pointer to gr::buffer_reader in its d_reader vector. gr::buffer_reader's destructor calls gr::buffer::drop_reader, so we're never left with an dangling pointer. gr::buffer_reader still has a shared_ptr to the buffer ensuring that the buffer doesn't go away under it. However, when the reference count of a gr::buffer_reader goes to zero, we can successfully reclaim it. ---------------------------------------------------------------------------- */ /* * Compute the minimum number of buffer items that work (i.e., * address space wrap-around works). To work is to satisfy this * contraint for integer buffer_size and k: * * type_size * nitems == k * page_size */ static long minimum_buffer_items(long type_size, long page_size) { return page_size / boost::math::gcd (type_size, page_size); } buffer::buffer(int nitems, size_t sizeof_item, block_sptr link) : d_base(0), d_bufsize(0), d_max_reader_delay(0), d_vmcircbuf(0), d_sizeof_item(sizeof_item), d_link(link), d_write_index(0), d_abs_write_offset(0), d_done(false), d_last_min_items_read(0) { if(!allocate_buffer (nitems, sizeof_item)) throw std::bad_alloc (); s_buffer_count++; } buffer_sptr make_buffer(int nitems, size_t sizeof_item, block_sptr link) { return buffer_sptr(new buffer(nitems, sizeof_item, link)); } buffer::~buffer() { delete d_vmcircbuf; assert(d_readers.size() == 0); s_buffer_count--; } /*! * sets d_vmcircbuf, d_base, d_bufsize. * returns true iff successful. */ bool buffer::allocate_buffer(int nitems, size_t sizeof_item) { int orig_nitems = nitems; // Any buffersize we come up with must be a multiple of min_nitems. int granularity = gr::vmcircbuf_sysconfig::granularity(); int min_nitems = minimum_buffer_items(sizeof_item, granularity); // Round-up nitems to a multiple of min_nitems. if(nitems % min_nitems != 0) nitems = ((nitems / min_nitems) + 1) * min_nitems; // If we rounded-up a whole bunch, give the user a heads up. // This only happens if sizeof_item is not a power of two. if(nitems > 2 * orig_nitems && nitems * (int) sizeof_item > granularity){ std::cerr << "gr::buffer::allocate_buffer: warning: tried to allocate\n" << " " << orig_nitems << " items of size " << sizeof_item << ". Due to alignment requirements\n" << " " << nitems << " were allocated. If this isn't OK, consider padding\n" << " your structure to a power-of-two bytes.\n" << " On this platform, our allocation granularity is " << granularity << " bytes.\n"; } d_bufsize = nitems; d_vmcircbuf = gr::vmcircbuf_sysconfig::make(d_bufsize * d_sizeof_item); if(d_vmcircbuf == 0){ std::cerr << "gr::buffer::allocate_buffer: failed to allocate buffer of size " << d_bufsize * d_sizeof_item / 1024 << " KB\n"; return false; } d_base = (char*)d_vmcircbuf->pointer_to_first_copy(); return true; } int buffer::space_available() { if(d_readers.empty()) return d_bufsize - 1; // See comment below else { // Find out the maximum amount of data available to our readers int most_data = d_readers[0]->items_available(); uint64_t min_items_read = d_readers[0]->nitems_read(); for(size_t i = 1; i < d_readers.size (); i++) { most_data = std::max(most_data, d_readers[i]->items_available()); min_items_read = std::min(min_items_read, d_readers[i]->nitems_read()); } if(min_items_read != d_last_min_items_read) { prune_tags(d_last_min_items_read); d_last_min_items_read = min_items_read; } // The -1 ensures that the case d_write_index == d_read_index is // unambiguous. It indicates that there is no data for the reader return d_bufsize - most_data - 1; } } void * buffer::write_pointer() { return &d_base[d_write_index * d_sizeof_item]; } void buffer::update_write_pointer(int nitems) { gr::thread::scoped_lock guard(*mutex()); d_write_index = index_add(d_write_index, nitems); d_abs_write_offset += nitems; } void buffer::set_done(bool done) { gr::thread::scoped_lock guard(*mutex()); d_done = done; } buffer_reader_sptr buffer_add_reader(buffer_sptr buf, int nzero_preload, block_sptr link, int delay) { if(nzero_preload < 0) throw std::invalid_argument("buffer_add_reader: nzero_preload must be >= 0"); buffer_reader_sptr r(new buffer_reader(buf, buf->index_sub(buf->d_write_index, nzero_preload), link)); r->declare_sample_delay(delay); buf->d_readers.push_back(r.get ()); return r; } void buffer::drop_reader(buffer_reader *reader) { std::vector::iterator result = std::find(d_readers.begin(), d_readers.end(), reader); if(result == d_readers.end()) throw std::invalid_argument("buffer::drop_reader"); // we didn't find it... d_readers.erase(result); } void buffer::add_item_tag(const tag_t &tag) { gr::thread::scoped_lock guard(*mutex()); d_item_tags.push_back(tag); } void buffer::remove_item_tag(const tag_t &tag, long id) { gr::thread::scoped_lock guard(*mutex()); for(std::deque::iterator it = d_item_tags.begin(); it != d_item_tags.end(); ++it) { if(*it == tag) { (*it).marked_deleted.push_back(id); } } } void buffer::prune_tags(uint64_t max_time) { /* NOTE: this function _should_ lock the mutex before editing d_item_tags. In practice, this function is only called at runtime by min_available_space in block_executor.cc, which locks the mutex itself. If this function is used elsewhere, remember to lock the buffer's mutex al la the scoped_lock line below. */ //gr::thread::scoped_lock guard(*mutex()); std::deque::iterator itr = d_item_tags.begin(); uint64_t item_time; // Since tags are not guarenteed to be in any particular order, we // need to erase here instead of pop_front. An erase in the middle // invalidates all iterators; so this resets the iterator to find // more. Mostly, we wil be erasing from the front and // therefore lose little time this way. while(itr != d_item_tags.end()) { item_time = (*itr).offset; if(item_time+d_max_reader_delay + bufsize() < max_time) { d_item_tags.erase(itr); itr = d_item_tags.begin(); } else itr++; } } long buffer_ncurrently_allocated() { return s_buffer_count; } // ---------------------------------------------------------------------------- buffer_reader::buffer_reader(buffer_sptr buffer, unsigned int read_index, block_sptr link) : d_buffer(buffer), d_read_index(read_index), d_abs_read_offset(0), d_link(link), d_attr_delay(0) { s_buffer_reader_count++; buffer->d_max_reader_delay = 0; } buffer_reader::~buffer_reader() { d_buffer->drop_reader(this); s_buffer_reader_count--; } void buffer_reader::declare_sample_delay(unsigned delay) { d_attr_delay = delay; d_buffer->d_max_reader_delay = std::max(d_attr_delay, d_buffer->d_max_reader_delay); } unsigned buffer_reader::sample_delay() const { return d_attr_delay; } int buffer_reader::items_available() const { return d_buffer->index_sub(d_buffer->d_write_index, d_read_index); } const void * buffer_reader::read_pointer() { return &d_buffer->d_base[d_read_index * d_buffer->d_sizeof_item]; } void buffer_reader::update_read_pointer(int nitems) { gr::thread::scoped_lock guard(*mutex()); d_read_index = d_buffer->index_add (d_read_index, nitems); d_abs_read_offset += nitems; } void buffer_reader::get_tags_in_range(std::vector &v, uint64_t abs_start, uint64_t abs_end, long id) { gr::thread::scoped_lock guard(*mutex()); v.resize(0); std::deque::iterator itr = d_buffer->get_tags_begin(); uint64_t item_time; while(itr != d_buffer->get_tags_end()) { item_time = (*itr).offset + d_attr_delay; if((item_time >= abs_start) && (item_time < abs_end)) { std::vector::iterator id_itr; id_itr = std::find(itr->marked_deleted.begin(), itr->marked_deleted.end(), id); // If id is not in the vector of marked blocks if(id_itr == itr->marked_deleted.end()) { tag_t t = *itr; t.offset += d_attr_delay; v.push_back(t); v.back().marked_deleted.clear(); } } itr++; } } long buffer_reader_ncurrently_allocated() { return s_buffer_reader_count; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/msg_accepter.cc0000664000175000017500000000307112207440367022334 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include namespace gr { msg_accepter::msg_accepter() { } msg_accepter::~msg_accepter() { // NOP, required as virtual destructor } void msg_accepter::post(pmt::pmt_t which_port, pmt::pmt_t msg) { // Notify derived class, handled case by case block *p = dynamic_cast(this); if(p) { p->_post(which_port, msg); return; } hier_block2 *p2 = dynamic_cast(this); if(p2) { // FIXME do the right thing return; } throw std::runtime_error("unknown derived class"); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/single_threaded_scheduler.cc0000664000175000017500000002667612207440367025077 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "single_threaded_scheduler.h" #include #include #include #include #include #include #include #include #include namespace gr { // must be defined to either 0 or 1 #define ENABLE_LOGGING 0 #if (ENABLE_LOGGING) #define LOG(x) do { x; } while(0) #else #define LOG(x) do {;} while(0) #endif static int which_scheduler = 0; single_threaded_scheduler_sptr make_single_threaded_scheduler(const std::vector &blocks) { return single_threaded_scheduler_sptr (new single_threaded_scheduler(blocks)); } single_threaded_scheduler::single_threaded_scheduler(const std::vector &blocks) : d_blocks(blocks), d_enabled(true), d_log(0) { if(ENABLE_LOGGING) { std::string name = str(boost::format("sst-%d.log") % which_scheduler++); d_log = new std::ofstream(name.c_str()); *d_log << "single_threaded_scheduler: " << d_blocks.size () << " blocks\n"; } } single_threaded_scheduler::~single_threaded_scheduler() { if(ENABLE_LOGGING) delete d_log; } void single_threaded_scheduler::run() { // d_enabled = true; // KLUDGE main_loop (); } void single_threaded_scheduler::stop() { if(0) std::cout << "gr_singled_threaded_scheduler::stop() " << this << std::endl; d_enabled = false; } inline static unsigned int round_up(unsigned int n, unsigned int multiple) { return ((n + multiple - 1) / multiple) * multiple; } inline static unsigned int round_down(unsigned int n, unsigned int multiple) { return (n / multiple) * multiple; } // // Return minimum available write space in all our downstream // buffers or -1 if we're output blocked and the output we're // blocked on is done. // static int min_available_space(block_detail *d, int output_multiple) { int min_space = std::numeric_limits::max(); for(int i = 0; i < d->noutputs (); i++) { int n = round_down (d->output(i)->space_available (), output_multiple); if(n == 0) { // We're blocked on output. if(d->output(i)->done()) { // Downstream is done, therefore we're done. return -1; } return 0; } min_space = std::min (min_space, n); } return min_space; } void single_threaded_scheduler::main_loop() { static const int DEFAULT_CAPACITY = 16; int noutput_items; gr_vector_int ninput_items_required(DEFAULT_CAPACITY); gr_vector_int ninput_items(DEFAULT_CAPACITY); gr_vector_const_void_star input_items(DEFAULT_CAPACITY); gr_vector_void_star output_items(DEFAULT_CAPACITY); unsigned int bi; unsigned int nalive; int max_items_avail; bool made_progress_last_pass; bool making_progress; for(unsigned i = 0; i < d_blocks.size (); i++) d_blocks[i]->detail()->set_done (false); // reset any done flags for(unsigned i = 0; i < d_blocks.size (); i++) // enable any drivers, etc. d_blocks[i]->start(); bi = 0; made_progress_last_pass = true; making_progress = false; // Loop while there are still blocks alive nalive = d_blocks.size (); while(d_enabled && nalive > 0) { if(boost::this_thread::interruption_requested()) break; block *m = d_blocks[bi].get (); block_detail *d = m->detail().get (); LOG(*d_log << std::endl << m); if(d->done ()) goto next_block; if(d->source_p ()) { // Invoke sources as a last resort. As long as the previous // pass made progress, don't call a source. if(made_progress_last_pass) { LOG(*d_log << " Skipping source\n"); goto next_block; } ninput_items_required.resize (0); ninput_items.resize (0); input_items.resize (0); output_items.resize (d->noutputs ()); // determine the minimum available output space noutput_items = min_available_space (d, m->output_multiple ()); LOG(*d_log << " source\n noutput_items = " << noutput_items << std::endl); if(noutput_items == -1) // we're done goto were_done; if(noutput_items == 0) { // we're output blocked LOG(*d_log << " BLKD_OUT\n"); goto next_block; } goto setup_call_to_work; // jump to common code } else if(d->sink_p ()) { ninput_items_required.resize (d->ninputs ()); ninput_items.resize (d->ninputs ()); input_items.resize (d->ninputs ()); output_items.resize (0); LOG(*d_log << " sink\n"); max_items_avail = 0; for(int i = 0; i < d->ninputs (); i++) { ninput_items[i] = d->input(i)->items_available(); //if (ninput_items[i] == 0 && d->input(i)->done()) if(ninput_items[i] < m->output_multiple() && d->input(i)->done()) goto were_done; max_items_avail = std::max (max_items_avail, ninput_items[i]); } // take a swag at how much output we can sink noutput_items = (int) (max_items_avail * m->relative_rate ()); noutput_items = round_down (noutput_items, m->output_multiple ()); LOG(*d_log << " max_items_avail = " << max_items_avail << std::endl); LOG(*d_log << " noutput_items = " << noutput_items << std::endl); if(noutput_items == 0) { // we're blocked on input LOG(*d_log << " BLKD_IN\n"); goto next_block; } goto try_again; // Jump to code shared with regular case. } else { // do the regular thing ninput_items_required.resize(d->ninputs ()); ninput_items.resize(d->ninputs ()); input_items.resize(d->ninputs ()); output_items.resize(d->noutputs ()); max_items_avail = 0; for(int i = 0; i < d->ninputs (); i++) { ninput_items[i] = d->input(i)->items_available (); max_items_avail = std::max(max_items_avail, ninput_items[i]); } // determine the minimum available output space noutput_items = min_available_space(d, m->output_multiple ()); if(ENABLE_LOGGING){ *d_log << " regular "; if(m->relative_rate() >= 1.0) *d_log << "1:" << m->relative_rate() << std::endl; else *d_log << 1.0/m->relative_rate() << ":1\n"; *d_log << " max_items_avail = " << max_items_avail << std::endl; *d_log << " noutput_items = " << noutput_items << std::endl; } if(noutput_items == -1) // we're done goto were_done; if(noutput_items == 0) { // we're output blocked LOG(*d_log << " BLKD_OUT\n"); goto next_block; } #if 0 // Compute best estimate of noutput_items that we can really use. noutput_items = std::min((unsigned)noutput_items, std::max((unsigned)m->output_multiple(), round_up((unsigned)(max_items_avail * m->relative_rate()), m->output_multiple()))); LOG(*d_log << " revised noutput_items = " << noutput_items << std::endl); #endif try_again: if(m->fixed_rate()) { // try to work it forward starting with max_items_avail. // We want to try to consume all the input we've got. int reqd_noutput_items = m->fixed_rate_ninput_to_noutput(max_items_avail); reqd_noutput_items = round_up(reqd_noutput_items, m->output_multiple()); if(reqd_noutput_items > 0 && reqd_noutput_items <= noutput_items) noutput_items = reqd_noutput_items; } // ask the block how much input they need to produce noutput_items m->forecast(noutput_items, ninput_items_required); // See if we've got sufficient input available int i; for(i = 0; i < d->ninputs (); i++) if(ninput_items_required[i] > ninput_items[i]) // not enough break; if(i < d->ninputs()) { // not enough input on input[i] // if we can, try reducing the size of our output request if(noutput_items > m->output_multiple ()){ noutput_items /= 2; noutput_items = round_up (noutput_items, m->output_multiple ()); goto try_again; } // We're blocked on input LOG(*d_log << " BLKD_IN\n"); if(d->input(i)->done()) // If the upstream block is done, we're done goto were_done; // Is it possible to ever fulfill this request? if(ninput_items_required[i] > d->input(i)->max_possible_items_available ()) { // Nope, never going to happen... std::cerr << "\nsched: name() << " (" << m->unique_id() << ")>" << " is requesting more input data\n" << " than we can provide.\n" << " ninput_items_required = " << ninput_items_required[i] << "\n" << " max_possible_items_available = " << d->input(i)->max_possible_items_available() << "\n" << " If this is a filter, consider reducing the number of taps.\n"; goto were_done; } goto next_block; } // We've got enough data on each input to produce noutput_items. // Finish setting up the call to work. for(int i = 0; i < d->ninputs (); i++) input_items[i] = d->input(i)->read_pointer(); setup_call_to_work: for(int i = 0; i < d->noutputs (); i++) output_items[i] = d->output(i)->write_pointer(); // Do the actual work of the block int n = m->general_work(noutput_items, ninput_items, input_items, output_items); LOG(*d_log << " general_work: noutput_items = " << noutput_items << " result = " << n << std::endl); if(n == -1) // block is done goto were_done; d->produce_each(n); // advance write pointers if(n > 0) making_progress = true; goto next_block; } assert(0); were_done: LOG(*d_log << " were_done\n"); d->set_done (true); nalive--; next_block: if(++bi >= d_blocks.size ()) { bi = 0; made_progress_last_pass = making_progress; making_progress = false; } } for(unsigned i = 0; i < d_blocks.size(); i++) // disable any drivers, etc. d_blocks[i]->stop(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_io_signature.cc0000664000175000017500000000345612207440367023060 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include void qa_io_signature::t0() { gr::io_signature::make(1, 1, sizeof(int)); } void qa_io_signature::t1() { gr::io_signature::make(3, 1, sizeof(int)); // throws std::invalid_argument } void qa_io_signature::t2() { gr::io_signature::sptr p = gr::io_signature::make(3, gr::io_signature::IO_INFINITE, sizeof(int)); CPPUNIT_ASSERT_EQUAL(p->min_streams(), 3); CPPUNIT_ASSERT_EQUAL(p->sizeof_stream_item(0), (int)sizeof(int)); } void qa_io_signature::t3() { gr::io_signature::sptr p = gr::io_signature::make3(0, 5, 1, 2, 3); CPPUNIT_ASSERT_EQUAL(p->min_streams(), 0); CPPUNIT_ASSERT_EQUAL(p->max_streams(), 5); CPPUNIT_ASSERT_EQUAL(p->sizeof_stream_item(0), 1); CPPUNIT_ASSERT_EQUAL(p->sizeof_stream_item(1), 2); CPPUNIT_ASSERT_EQUAL(p->sizeof_stream_item(2), 3); CPPUNIT_ASSERT_EQUAL(p->sizeof_stream_item(3), 3); CPPUNIT_ASSERT_EQUAL(p->sizeof_stream_item(4), 3); } gnuradio-3.7.2.1/gnuradio-runtime/lib/basic_block.cc0000664000175000017500000001577112231076123022135 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include namespace gr { static long s_next_id = 0; static long s_ncurrently_allocated = 0; long basic_block_ncurrently_allocated() { return s_ncurrently_allocated; } basic_block::basic_block(const std::string &name, io_signature::sptr input_signature, io_signature::sptr output_signature) : d_name(name), d_input_signature(input_signature), d_output_signature(output_signature), d_unique_id(s_next_id++), d_symbolic_id(global_block_registry.block_register(this)), d_symbol_name(global_block_registry.register_symbolic_name(this)), d_color(WHITE), d_rpc_set(false), d_message_subscribers(pmt::make_dict()) { s_ncurrently_allocated++; } basic_block::~basic_block() { s_ncurrently_allocated--; global_block_registry.block_unregister(this); } basic_block_sptr basic_block::to_basic_block() { return shared_from_this(); } void basic_block::set_block_alias(std::string name) { global_block_registry.register_symbolic_name(this, name); } // ** Message passing interface ** // - register a new input message port void basic_block::message_port_register_in(pmt::pmt_t port_id) { if(!pmt::is_symbol(port_id)) { throw std::runtime_error("message_port_register_in: bad port id"); } msg_queue[port_id] = msg_queue_t(); msg_queue_ready[port_id] = boost::shared_ptr(new boost::condition_variable()); } pmt::pmt_t basic_block::message_ports_in() { pmt::pmt_t port_names = pmt::make_vector(msg_queue.size(), pmt::PMT_NIL); msg_queue_map_itr itr = msg_queue.begin(); for(size_t i = 0; i < msg_queue.size(); i++) { pmt::vector_set(port_names, i, (*itr).first); itr++; } return port_names; } // - register a new output message port void basic_block::message_port_register_out(pmt::pmt_t port_id) { if(!pmt::is_symbol(port_id)) { throw std::runtime_error("message_port_register_out: bad port id"); } if(pmt::dict_has_key(d_message_subscribers, port_id)) { throw std::runtime_error("message_port_register_out: port already in use"); } d_message_subscribers = pmt::dict_add(d_message_subscribers, port_id, pmt::PMT_NIL); } pmt::pmt_t basic_block::message_ports_out() { size_t len = pmt::length(d_message_subscribers); pmt::pmt_t port_names = pmt::make_vector(len, pmt::PMT_NIL); pmt::pmt_t keys = pmt::dict_keys(d_message_subscribers); for(size_t i = 0; i < len; i++) { pmt::vector_set(port_names, i, pmt::nth(i, keys)); } return port_names; } // - publish a message on a message port void basic_block::message_port_pub(pmt::pmt_t port_id, pmt::pmt_t msg) { if(!pmt::dict_has_key(d_message_subscribers, port_id)) { throw std::runtime_error("port does not exist"); } pmt::pmt_t currlist = pmt::dict_ref(d_message_subscribers, port_id, pmt::PMT_NIL); // iterate through subscribers on port while(pmt::is_pair(currlist)) { pmt::pmt_t target = pmt::car(currlist); pmt::pmt_t block = pmt::car(target); pmt::pmt_t port = pmt::cdr(target); currlist = pmt::cdr(currlist); basic_block_sptr blk = global_block_registry.block_lookup(block); //blk->post(msg); blk->post(port, msg); } } // - subscribe to a message port void basic_block::message_port_sub(pmt::pmt_t port_id, pmt::pmt_t target){ if(!pmt::dict_has_key(d_message_subscribers, port_id)){ std::stringstream ss; ss << "Port does not exist: \"" << pmt::write_string(port_id) << "\" on block: " << pmt::write_string(target) << std::endl; throw std::runtime_error(ss.str()); } pmt::pmt_t currlist = pmt::dict_ref(d_message_subscribers,port_id,pmt::PMT_NIL); // ignore re-adds of the same target if(!pmt::list_has(currlist, target)) d_message_subscribers = pmt::dict_add(d_message_subscribers,port_id,pmt::list_add(currlist,target)); } void basic_block::message_port_unsub(pmt::pmt_t port_id, pmt::pmt_t target) { if(!pmt::dict_has_key(d_message_subscribers, port_id)) { std::stringstream ss; ss << "Port does not exist: \"" << pmt::write_string(port_id) << "\" on block: " << pmt::write_string(target) << std::endl; throw std::runtime_error(ss.str()); } // ignore unsubs of unknown targets pmt::pmt_t currlist = pmt::dict_ref(d_message_subscribers,port_id,pmt::PMT_NIL); d_message_subscribers = pmt::dict_add(d_message_subscribers,port_id,pmt::list_rm(currlist,target)); } void basic_block::_post(pmt::pmt_t which_port, pmt::pmt_t msg) { insert_tail(which_port, msg); } void basic_block::insert_tail(pmt::pmt_t which_port, pmt::pmt_t msg) { gr::thread::scoped_lock guard(mutex); if((msg_queue.find(which_port) == msg_queue.end()) || (msg_queue_ready.find(which_port) == msg_queue_ready.end())) { std::cout << "target port = " << pmt::symbol_to_string(which_port) << std::endl; throw std::runtime_error("attempted to insert_tail on invalid queue!"); } msg_queue[which_port].push_back(msg); msg_queue_ready[which_port]->notify_one(); // wake up thread if BLKD_IN or BLKD_OUT global_block_registry.notify_blk(alias()); } pmt::pmt_t basic_block::delete_head_nowait(pmt::pmt_t which_port) { gr::thread::scoped_lock guard(mutex); if(empty_p(which_port)) { return pmt::pmt_t(); } pmt::pmt_t m(msg_queue[which_port].front()); msg_queue[which_port].pop_front(); return m; } pmt::pmt_t basic_block::delete_head_blocking(pmt::pmt_t which_port) { gr::thread::scoped_lock guard(mutex); while(empty_p(which_port)) { msg_queue_ready[which_port]->wait(guard); } pmt::pmt_t m(msg_queue[which_port].front()); msg_queue[which_port].pop_front(); return m; } pmt::pmt_t basic_block::message_subscribers(pmt::pmt_t port) { return pmt::dict_ref(d_message_subscribers,port,pmt::PMT_NIL); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/msg_handler.cc0000664000175000017500000000173512207440367022170 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { msg_handler::~msg_handler() { } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/scheduler_sts.cc0000664000175000017500000000447212207440367022555 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "scheduler_sts.h" #include "single_threaded_scheduler.h" #include namespace gr { class sts_container { block_vector_t d_blocks; public: sts_container(block_vector_t blocks) : d_blocks(blocks) {} void operator()() { make_single_threaded_scheduler(d_blocks)->run(); } }; scheduler_sptr scheduler_sts::make(flat_flowgraph_sptr ffg, int max_noutput_items) { return scheduler_sptr(new scheduler_sts(ffg, max_noutput_items)); } scheduler_sts::scheduler_sts(flat_flowgraph_sptr ffg, int max_noutput_items) : scheduler(ffg, max_noutput_items) { // Split the flattened flow graph into discrete partitions, each // of which is topologically sorted. std::vector graphs = ffg->partition(); // For each partition, create a thread to evaluate it using // an instance of the gr_single_threaded_scheduler for(std::vector::iterator p = graphs.begin(); p != graphs.end(); p++) { block_vector_t blocks = flat_flowgraph::make_block_vector(*p); d_threads.create_thread( gr::thread::thread_body_wrapper(sts_container(blocks), "single-threaded-scheduler")); } } scheduler_sts::~scheduler_sts() { stop(); } void scheduler_sts::stop() { d_threads.interrupt_all(); } void scheduler_sts::wait() { d_threads.join_all(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/scheduler_tpb.h0000664000175000017500000000351412207440367022367 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCLUDED_GR_SCHEDULER_TPB_H #define INCLUDED_GR_SCHEDULER_TPB_H #include #include #include "scheduler.h" namespace gr { /*! * \brief Concrete scheduler that uses a kernel thread-per-block */ class GR_RUNTIME_API scheduler_tpb : public scheduler { gr::thread::thread_group d_threads; protected: /*! * \brief Construct a scheduler and begin evaluating the graph. * * The scheduler will continue running until all blocks until they * report that they are done or the stop method is called. */ scheduler_tpb(flat_flowgraph_sptr ffg, int max_noutput_items); public: static scheduler_sptr make(flat_flowgraph_sptr ffg, int max_noutput_items=100000); ~scheduler_tpb(); /*! * \brief Tell the scheduler to stop executing. */ void stop(); /*! * \brief Block until the graph is done. */ void wait(); }; } /* namespace gr */ #endif /* INCLUDED_GR_SCHEDULER_TPB_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/tagged_stream_block.cc0000664000175000017500000001200712241734056023656 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include namespace gr { tagged_stream_block::tagged_stream_block(const std::string &name, io_signature::sptr input_signature, io_signature::sptr output_signature, const std::string &length_tag_key) : block(name, input_signature, output_signature), d_length_tag_key(pmt::string_to_symbol(length_tag_key)), d_n_input_items_reqd(input_signature->min_streams(), 0), d_length_tag_key_str(length_tag_key) { } // This is evil hackery: We trick the scheduler into creating the right number of input items void tagged_stream_block::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) { if (i < d_n_input_items_reqd.size() && d_n_input_items_reqd[i] != 0) { ninput_items_required[i] = d_n_input_items_reqd[i]; } else { // If there's no item, there's no tag--so there must at least be one! ninput_items_required[i] = std::max(1, (int)std::floor((double) noutput_items / relative_rate() + 0.5)); } } } void tagged_stream_block::parse_length_tags(const std::vector > &tags, gr_vector_int &n_input_items_reqd) { for(unsigned i = 0; i < tags.size(); i++) { for(unsigned k = 0; k < tags[i].size(); k++) { if(tags[i][k].key == d_length_tag_key) { n_input_items_reqd[i] = pmt::to_long(tags[i][k].value); remove_item_tag(i, tags[i][k]); } } } } int tagged_stream_block::calculate_output_stream_length(const gr_vector_int &ninput_items) { int noutput_items = *std::max_element(ninput_items.begin(), ninput_items.end()); return (int)std::floor(relative_rate() * noutput_items + 0.5); } void tagged_stream_block::update_length_tags(int n_produced, int n_ports) { for(int i = 0; i < n_ports; i++) { add_item_tag(i, nitems_written(i), d_length_tag_key, pmt::from_long(n_produced)); } return; } int tagged_stream_block::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { if(d_length_tag_key_str.empty()) { return work(noutput_items, ninput_items, input_items, output_items); } if(d_n_input_items_reqd[0] == 0) { // Otherwise, it's already set from a previous call std::vector > tags(input_items.size(), std::vector()); for(unsigned i = 0; i < input_items.size(); i++) { get_tags_in_range(tags[i], i, nitems_read(i), nitems_read(i)+1); } d_n_input_items_reqd.assign(input_items.size(), -1); parse_length_tags(tags, d_n_input_items_reqd); } for(unsigned i = 0; i < input_items.size(); i++) { if(d_n_input_items_reqd[i] == -1) { GR_LOG_FATAL(d_logger, boost::format("Missing a required length tag on port %1% at item #%2%") % i % nitems_read(i)); throw std::runtime_error("Missing length tag."); } if(d_n_input_items_reqd[i] > ninput_items[i]) { return 0; } } int min_output_size = calculate_output_stream_length(d_n_input_items_reqd); if(noutput_items < min_output_size) { set_min_noutput_items(min_output_size); return 0; } set_min_noutput_items(1); // WORK CALLED HERE // int n_produced = work(noutput_items, d_n_input_items_reqd, input_items, output_items); ////////////////////// if(n_produced == WORK_DONE) { return n_produced; } for(int i = 0; i < (int) d_n_input_items_reqd.size(); i++) { consume(i, d_n_input_items_reqd[i]); } if (n_produced > 0) { update_length_tags(n_produced, output_items.size()); } d_n_input_items_reqd.assign(input_items.size(), 0); return n_produced; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/block_executor.cc0000664000175000017500000004137412237515111022711 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include #include #include #include namespace gr { // must be defined to either 0 or 1 #define ENABLE_LOGGING 0 #if (ENABLE_LOGGING) #define LOG(x) do { x; } while(0) #else #define LOG(x) do {;} while(0) #endif static int which_scheduler = 0; inline static unsigned int round_up(unsigned int n, unsigned int multiple) { return ((n + multiple - 1) / multiple) * multiple; } inline static unsigned int round_down(unsigned int n, unsigned int multiple) { return (n / multiple) * multiple; } // // Return minimum available write space in all our downstream // buffers or -1 if we're output blocked and the output we're // blocked on is done. // static int min_available_space(block_detail *d, int output_multiple, int min_noutput_items) { int min_space = std::numeric_limits::max(); if(min_noutput_items == 0) min_noutput_items = 1; for(int i = 0; i < d->noutputs (); i++) { gr::thread::scoped_lock guard(*d->output(i)->mutex()); int avail_n = round_down(d->output(i)->space_available(), output_multiple); int best_n = round_down(d->output(i)->bufsize()/2, output_multiple); if(best_n < min_noutput_items) throw std::runtime_error("Buffer too small for min_noutput_items"); int n = std::min(avail_n, best_n); if(n < min_noutput_items){ // We're blocked on output. if(d->output(i)->done()){ // Downstream is done, therefore we're done. return -1; } return 0; } min_space = std::min(min_space, n); } return min_space; } static bool propagate_tags(block::tag_propagation_policy_t policy, block_detail *d, const std::vector &start_nitems_read, double rrate, std::vector &rtags, long block_id) { // Move tags downstream // if a sink, we don't need to move downstream if(d->sink_p()) { return true; } switch(policy) { case block::TPP_DONT: return true; break; case block::TPP_ALL_TO_ALL: // every tag on every input propogates to everyone downstream for(int i = 0; i < d->ninputs(); i++) { d->get_tags_in_range(rtags, i, start_nitems_read[i], d->nitems_read(i), block_id); std::vector::iterator t; if(rrate == 1.0) { for(t = rtags.begin(); t != rtags.end(); t++) { for(int o = 0; o < d->noutputs(); o++) d->output(o)->add_item_tag(*t); } } else { for(t = rtags.begin(); t != rtags.end(); t++) { tag_t new_tag = *t; new_tag.offset *= rrate; for(int o = 0; o < d->noutputs(); o++) d->output(o)->add_item_tag(new_tag); } } } break; case block::TPP_ONE_TO_ONE: // tags from input i only go to output i // this requires d->ninputs() == d->noutputs; this is checked when this // type of tag-propagation system is selected in block_detail if(d->ninputs() == d->noutputs()) { for(int i = 0; i < d->ninputs(); i++) { d->get_tags_in_range(rtags, i, start_nitems_read[i], d->nitems_read(i), block_id); std::vector::iterator t; for(t = rtags.begin(); t != rtags.end(); t++) { tag_t new_tag = *t; new_tag.offset *= rrate; d->output(i)->add_item_tag(new_tag); } } } else { std::cerr << "Error: block_executor: propagation_policy 'ONE-TO-ONE' requires ninputs == noutputs" << std::endl; return false; } break; default: return true; } return true; } block_executor::block_executor(block_sptr block, int max_noutput_items) : d_block(block), d_log(0), d_max_noutput_items(max_noutput_items) { if(ENABLE_LOGGING) { std::string name = str(boost::format("sst-%03d.log") % which_scheduler++); d_log = new std::ofstream(name.c_str()); std::unitbuf(*d_log); // make it unbuffered... *d_log << "block_executor: " << d_block << std::endl; } #ifdef GR_PERFORMANCE_COUNTERS prefs *prefs = prefs::singleton(); d_use_pc = prefs->get_bool("PerfCounters", "on", false); #endif /* GR_PERFORMANCE_COUNTERS */ d_block->start(); // enable any drivers, etc. } block_executor::~block_executor() { if(ENABLE_LOGGING) delete d_log; d_block->stop(); // stop any drivers, etc. } block_executor::state block_executor::run_one_iteration() { int noutput_items; int max_items_avail; int max_noutput_items; int new_alignment = 0; int alignment_state = -1; double rrate; block *m = d_block.get(); block_detail *d = m->detail().get(); LOG(*d_log << std::endl << m); max_noutput_items = round_down(d_max_noutput_items, m->output_multiple()); if(d->done()){ assert(0); return DONE; } if(d->source_p ()) { d_ninput_items_required.resize(0); d_ninput_items.resize(0); d_input_items.resize(0); d_input_done.resize(0); d_output_items.resize(d->noutputs()); d_start_nitems_read.resize(0); // determine the minimum available output space noutput_items = min_available_space(d, m->output_multiple (), m->min_noutput_items ()); noutput_items = std::min(noutput_items, max_noutput_items); LOG(*d_log << " source\n noutput_items = " << noutput_items << std::endl); if(noutput_items == -1) // we're done goto were_done; if(noutput_items == 0){ // we're output blocked LOG(*d_log << " BLKD_OUT\n"); return BLKD_OUT; } goto setup_call_to_work; // jump to common code } else if(d->sink_p ()) { d_ninput_items_required.resize(d->ninputs ()); d_ninput_items.resize(d->ninputs ()); d_input_items.resize(d->ninputs ()); d_input_done.resize(d->ninputs()); d_output_items.resize (0); d_start_nitems_read.resize(d->ninputs()); LOG(*d_log << " sink\n"); max_items_avail = 0; for(int i = 0; i < d->ninputs (); i++) { { /* * Acquire the mutex and grab local copies of items_available and done. */ gr::thread::scoped_lock guard(*d->input(i)->mutex()); d_ninput_items[i] = d->input(i)->items_available(); d_input_done[i] = d->input(i)->done(); } LOG(*d_log << " d_ninput_items[" << i << "] = " << d_ninput_items[i] << std::endl); LOG(*d_log << " d_input_done[" << i << "] = " << d_input_done[i] << std::endl); if (d_ninput_items[i] < m->output_multiple() && d_input_done[i]) goto were_done; max_items_avail = std::max (max_items_avail, d_ninput_items[i]); } // take a swag at how much output we can sink noutput_items = (int)(max_items_avail * m->relative_rate ()); noutput_items = round_down(noutput_items, m->output_multiple ()); noutput_items = std::min(noutput_items, max_noutput_items); LOG(*d_log << " max_items_avail = " << max_items_avail << std::endl); LOG(*d_log << " noutput_items = " << noutput_items << std::endl); if(noutput_items == 0) { // we're blocked on input LOG(*d_log << " BLKD_IN\n"); return BLKD_IN; } goto try_again; // Jump to code shared with regular case. } else { // do the regular thing d_ninput_items_required.resize (d->ninputs ()); d_ninput_items.resize (d->ninputs ()); d_input_items.resize (d->ninputs ()); d_input_done.resize(d->ninputs()); d_output_items.resize (d->noutputs ()); d_start_nitems_read.resize(d->ninputs()); max_items_avail = 0; for(int i = 0; i < d->ninputs (); i++) { { /* * Acquire the mutex and grab local copies of items_available and done. */ gr::thread::scoped_lock guard(*d->input(i)->mutex()); d_ninput_items[i] = d->input(i)->items_available (); d_input_done[i] = d->input(i)->done(); } max_items_avail = std::max(max_items_avail, d_ninput_items[i]); } // determine the minimum available output space noutput_items = min_available_space(d, m->output_multiple(), m->min_noutput_items()); if(ENABLE_LOGGING) { *d_log << " regular "; if(m->relative_rate() >= 1.0) *d_log << "1:" << m->relative_rate() << std::endl; else *d_log << 1.0/m->relative_rate() << ":1\n"; *d_log << " max_items_avail = " << max_items_avail << std::endl; *d_log << " noutput_items = " << noutput_items << std::endl; } if(noutput_items == -1) // we're done goto were_done; if(noutput_items == 0) { // we're output blocked LOG(*d_log << " BLKD_OUT\n"); return BLKD_OUT; } try_again: if(m->fixed_rate()) { // try to work it forward starting with max_items_avail. // We want to try to consume all the input we've got. int reqd_noutput_items = m->fixed_rate_ninput_to_noutput(max_items_avail); // only test this if we specifically set the output_multiple if(m->output_multiple_set()) reqd_noutput_items = round_down(reqd_noutput_items, m->output_multiple()); if(reqd_noutput_items > 0 && reqd_noutput_items <= noutput_items) noutput_items = reqd_noutput_items; // if we need this many outputs, overrule the max_noutput_items setting max_noutput_items = std::max(m->output_multiple(), max_noutput_items); } noutput_items = std::min(noutput_items, max_noutput_items); // Check if we're still unaligned; use up items until we're // aligned again. Otherwise, make sure we set the alignment // requirement. if(!m->output_multiple_set()) { if(m->is_unaligned()) { // When unaligned, don't just set noutput_items to the remaining // samples to meet alignment; this causes too much overhead in // requiring a premature call back here. Set the maximum amount // of samples to handle unalignment and get us back aligned. if(noutput_items >= m->unaligned()) { noutput_items = round_up(noutput_items, m->alignment()) \ - (m->alignment() - m->unaligned()); new_alignment = 0; } else { new_alignment = m->unaligned() - noutput_items; } alignment_state = 0; } else if(noutput_items < m->alignment()) { // if we don't have enough for an aligned call, keep track of // misalignment, set unaligned flag, and proceed. new_alignment = m->alignment() - noutput_items; m->set_unaligned(new_alignment); m->set_is_unaligned(true); alignment_state = 1; } else { // enough to round down to the nearest alignment and process. noutput_items = round_down(noutput_items, m->alignment()); m->set_is_unaligned(false); alignment_state = 2; } } // ask the block how much input they need to produce noutput_items m->forecast (noutput_items, d_ninput_items_required); // See if we've got sufficient input available int i; for(i = 0; i < d->ninputs (); i++) if(d_ninput_items_required[i] > d_ninput_items[i]) // not enough break; if(i < d->ninputs()) { // not enough input on input[i] // if we can, try reducing the size of our output request if(noutput_items > m->output_multiple()) { noutput_items /= 2; noutput_items = round_up(noutput_items, m->output_multiple()); goto try_again; } // We're blocked on input LOG(*d_log << " BLKD_IN\n"); if(d_input_done[i]) // If the upstream block is done, we're done goto were_done; // Is it possible to ever fulfill this request? if(d_ninput_items_required[i] > d->input(i)->max_possible_items_available()) { // Nope, never going to happen... std::cerr << "\nsched: name() << " (" << m->unique_id() << ")>" << " is requesting more input data\n" << " than we can provide.\n" << " ninput_items_required = " << d_ninput_items_required[i] << "\n" << " max_possible_items_available = " << d->input(i)->max_possible_items_available() << "\n" << " If this is a filter, consider reducing the number of taps.\n"; goto were_done; } // If we were made unaligned in this round but return here without // processing; reset the unalignment claim before next entry. if(alignment_state == 1) { m->set_unaligned(0); m->set_is_unaligned(false); } return BLKD_IN; } // We've got enough data on each input to produce noutput_items. // Finish setting up the call to work. for(int i = 0; i < d->ninputs (); i++) d_input_items[i] = d->input(i)->read_pointer(); setup_call_to_work: d->d_produce_or = 0; for(int i = 0; i < d->noutputs (); i++) d_output_items[i] = d->output(i)->write_pointer(); // determine where to start looking for new tags for(int i = 0; i < d->ninputs(); i++) d_start_nitems_read[i] = d->nitems_read(i); #ifdef GR_PERFORMANCE_COUNTERS if(d_use_pc) d->start_perf_counters(); #endif /* GR_PERFORMANCE_COUNTERS */ // Do the actual work of the block int n = m->general_work(noutput_items, d_ninput_items, d_input_items, d_output_items); #ifdef GR_PERFORMANCE_COUNTERS if(d_use_pc) d->stop_perf_counters(noutput_items, n); #endif /* GR_PERFORMANCE_COUNTERS */ LOG(*d_log << " general_work: noutput_items = " << noutput_items << " result = " << n << std::endl); // Adjust number of unaligned items left to process if(m->is_unaligned()) { m->set_unaligned(new_alignment); m->set_is_unaligned(m->unaligned() != 0); } // For some blocks that can change their produce/consume ratio // (the relative_rate), we might want to automatically update // based on the amount of items written/read. // In the block constructor, use enable_update_rate(true). if(m->update_rate()) { rrate = ((double)(m->nitems_written(0)+n)) / ((double)m->nitems_read(0)); if(rrate > 0) m->set_relative_rate(rrate); } // Now propagate the tags based on the new relative rate if(!propagate_tags(m->tag_propagation_policy(), d, d_start_nitems_read, m->relative_rate(), d_returned_tags, m->unique_id())) goto were_done; if(n == block::WORK_DONE) goto were_done; if(n != block::WORK_CALLED_PRODUCE) d->produce_each(n); // advance write pointers if(d->d_produce_or > 0) // block produced something return READY; // We didn't produce any output even though we called general_work. // We have (most likely) consumed some input. /* // If this is a source, it's broken. if(d->source_p()) { std::cerr << "block_executor: source " << m << " produced no output. We're marking it DONE.\n"; // FIXME maybe we ought to raise an exception... goto were_done; } */ // Have the caller try again... return READY_NO_OUTPUT; } assert(0); were_done: LOG(*d_log << " were_done\n"); d->set_done (true); return DONE; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/top_block_impl.cc0000664000175000017500000001242312207440367022676 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "top_block_impl.h" #include "flat_flowgraph.h" #include "scheduler_sts.h" #include "scheduler_tpb.h" #include #include #include #include #include #include #include namespace gr { #define GR_TOP_BLOCK_IMPL_DEBUG 0 typedef scheduler_sptr(*scheduler_maker)(flat_flowgraph_sptr ffg, int max_noutput_items); static struct scheduler_table { const char *name; scheduler_maker f; } scheduler_table[] = { { "TPB", scheduler_tpb::make }, // first entry is default { "STS", scheduler_sts::make } }; static scheduler_sptr make_scheduler(flat_flowgraph_sptr ffg, int max_noutput_items) { static scheduler_maker factory = 0; if(factory == 0) { char *v = getenv("GR_SCHEDULER"); if(!v) factory = scheduler_table[0].f; // use default else { for(size_t i = 0; i < sizeof(scheduler_table)/sizeof(scheduler_table[0]); i++) { if(strcmp(v, scheduler_table[i].name) == 0) { factory = scheduler_table[i].f; break; } } if(factory == 0) { std::cerr << "warning: Invalid GR_SCHEDULER environment variable value \"" << v << "\". Using \"" << scheduler_table[0].name << "\"\n"; factory = scheduler_table[0].f; } } } return factory(ffg, max_noutput_items); } top_block_impl::top_block_impl(top_block *owner) : d_owner(owner), d_ffg(), d_state(IDLE), d_lock_count(0) { } top_block_impl::~top_block_impl() { d_owner = 0; } void top_block_impl::start(int max_noutput_items) { gr::thread::scoped_lock l(d_mutex); d_max_noutput_items = max_noutput_items; if(d_state != IDLE) throw std::runtime_error("top_block::start: top block already running or wait() not called after previous stop()"); if(d_lock_count > 0) throw std::runtime_error("top_block::start: can't start with flow graph locked"); // Create new flat flow graph by flattening hierarchy d_ffg = d_owner->flatten(); // Validate new simple flow graph and wire it up d_ffg->validate(); d_ffg->setup_connections(); // Only export perf. counters if ControlPort config param is // enabled and if the PerfCounter option 'export' is turned on. prefs *p = prefs::singleton(); if(p->get_bool("ControlPort", "on", false) && p->get_bool("PerfCounters", "export", false)) d_ffg->enable_pc_rpc(); d_scheduler = make_scheduler(d_ffg, d_max_noutput_items); d_state = RUNNING; } void top_block_impl::stop() { if(d_scheduler) d_scheduler->stop(); } void top_block_impl::wait() { if(d_scheduler) d_scheduler->wait(); d_state = IDLE; } // N.B. lock() and unlock() cannot be called from a flow graph // thread or deadlock will occur when reconfiguration happens void top_block_impl::lock() { gr::thread::scoped_lock lock(d_mutex); d_lock_count++; } void top_block_impl::unlock() { gr::thread::scoped_lock lock(d_mutex); if(d_lock_count <= 0) { d_lock_count = 0; // fix it, then complain throw std::runtime_error("unpaired unlock() call"); } d_lock_count--; if(d_lock_count > 0 || d_state == IDLE) // nothing to do return; restart(); } /* * restart is called with d_mutex held */ void top_block_impl::restart() { stop(); // Stop scheduler and wait for completion wait(); // Create new simple flow graph flat_flowgraph_sptr new_ffg = d_owner->flatten(); new_ffg->validate(); // check consistency, sanity, etc new_ffg->merge_connections(d_ffg); // reuse buffers, etc d_ffg = new_ffg; // Create a new scheduler to execute it d_scheduler = make_scheduler(d_ffg, d_max_noutput_items); d_state = RUNNING; } std::string top_block_impl::edge_list() { if(d_ffg) return d_ffg->edge_list(); else return ""; } std::string top_block_impl::msg_edge_list() { if(d_ffg) return d_ffg->msg_edge_list(); else return ""; } void top_block_impl::dump() { if(d_ffg) d_ffg->dump(); } int top_block_impl::max_noutput_items() { return d_max_noutput_items; } void top_block_impl::set_max_noutput_items(int nmax) { d_max_noutput_items = nmax; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/logger.cc0000664000175000017500000002403512220040621021142 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /******************************************************************************* * Author: Mark Plett * Description: * The gr_log module wraps the log4cpp library for logging in gnuradio. *******************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #ifdef ENABLE_GR_LOG #ifdef HAVE_LOG4CPP namespace gr { bool logger_config::logger_configured(false); /************************ BEGIN LOG4CPP HELPERS ***********************/ /* Logger config class. This is a singleton that controls how * log4cpp is configured If watch_period>0 a thread is started to * watch teh config file for changes. */ // Getters of logger_config logger_config& logger_config::get_instance(void) { static logger_config instance; return instance; } std::string logger_config::get_filename() { logger_config& in=get_instance(); return in.filename; } unsigned int logger_config::get_watch_period() { logger_config& in=get_instance(); return in.watch_period; } // Method to watch config file for changes void logger_config::watch_file(std::string filename, unsigned int watch_period) { std::time_t last_write(boost::filesystem::last_write_time(filename)); std::time_t current_time(0); while(true) { try { current_time = boost::filesystem::last_write_time(filename); if(current_time>last_write) { //std::cout<<"GNURadio Reloading logger configuration:"<0) { instance.watch_thread = new boost::thread(watch_file, instance.filename, instance.watch_period); } } } // Method to stop the watcher thread void logger_config::stop_watch() { logger_config& instance = get_instance(); if(instance.watch_thread) { instance.watch_thread->interrupt(); instance.watch_thread->join(); delete(instance.watch_thread); instance.watch_thread=NULL; } } // Method to reset logger configuration void logger_config::reset_config(void) { logger_config& instance = get_instance(); stop_watch(); std::vector *loggers = log4cpp::Category::getCurrentCategories(); std::vector::iterator logger = loggers->begin(); // We can't destroy categories but we can neuter them by removing all appenders. for(;logger!=loggers->end();logger++) { (*logger)->removeAllAppenders(); } instance.filename = std::string(""); instance.watch_period = 0; logger_configured = false; } /***************** Functions to call log4cpp methods *************************/ logger_ptr logger_get_logger(std::string name) { if(log4cpp::Category::exists(name)) { logger_ptr logger = &log4cpp::Category::getInstance(name); return logger; } else { logger_ptr logger = &log4cpp::Category::getInstance(name); logger->setPriority(log4cpp::Priority::NOTSET); return logger; } } bool logger_load_config(const std::string &config_filename) { if(config_filename.size() != 0) { try { log4cpp::PropertyConfigurator::configure(config_filename); return true; } catch(log4cpp::ConfigureFailure &e) { std::cerr << "Logger config failed :" << e.what() << std::endl; } } return false; } void logger_set_level(logger_ptr logger, const std::string &level) { std::string nocase = level; std::transform(level.begin(), level.end(), nocase.begin(), ::tolower); if(nocase == "off" || nocase == "notset") logger_set_level(logger, log4cpp::Priority::NOTSET); else if(nocase == "all" || nocase == "debug") logger_set_level(logger, log4cpp::Priority::DEBUG); else if(nocase == "info") logger_set_level(logger, log4cpp::Priority::INFO); else if(nocase == "notice") logger_set_level(logger, log4cpp::Priority::NOTICE); else if(nocase == "warn") logger_set_level(logger, log4cpp::Priority::WARN); else if(nocase == "error") logger_set_level(logger, log4cpp::Priority::ERROR); else if(nocase == "crit") logger_set_level(logger, log4cpp::Priority::CRIT); else if(nocase == "alert") logger_set_level(logger, log4cpp::Priority::ALERT); else if(nocase=="fatal") logger_set_level(logger, log4cpp::Priority::FATAL); else if(nocase == "emerg") logger_set_level(logger, log4cpp::Priority::EMERG); else throw std::runtime_error("logger_set_level: Bad level type.\n"); } void logger_set_level(logger_ptr logger, log4cpp::Priority::Value level) { logger->setPriority(level); } void logger_get_level(logger_ptr logger, std::string &level) { log4cpp::Priority::Value levelPtr = logger->getPriority(); if(levelPtr == log4cpp::Priority::NOTSET) level = "noset"; if(levelPtr == log4cpp::Priority::DEBUG) level = "debug"; if(levelPtr == log4cpp::Priority::INFO) level = "info"; if(levelPtr == log4cpp::Priority::NOTICE) level = "notice"; if(levelPtr == log4cpp::Priority::WARN) level = "warn"; if(levelPtr == log4cpp::Priority::ERROR) level = "error"; if(levelPtr == log4cpp::Priority::CRIT) level = "crit"; if(levelPtr == log4cpp::Priority::ALERT) level = "alert"; if(levelPtr == log4cpp::Priority::FATAL) level = "fatal"; if(levelPtr == log4cpp::Priority::EMERG) level = "emerg"; } void logger_get_level(logger_ptr logger,log4cpp::Priority::Value level) { level = logger->getPriority(); } void logger_add_console_appender(logger_ptr logger, std::string target, std::string pattern) { log4cpp::PatternLayout* layout = new log4cpp::PatternLayout(); log4cpp::Appender* app; if(target=="stdout") app = new log4cpp::OstreamAppender("ConsoleAppender::",&std::cout); else app = new log4cpp::OstreamAppender("ConsoleAppender::",&std::cerr); layout->setConversionPattern(pattern); app->setLayout(layout); logger->setAppender(app); } void logger_add_file_appender(logger_ptr logger, std::string filename, bool append, std::string pattern) { log4cpp::PatternLayout* layout = new log4cpp::PatternLayout(); log4cpp::Appender* app = new log4cpp::FileAppender("FileAppender::"+filename, filename); layout->setConversionPattern(pattern); app->setLayout(layout); logger->setAppender(app); } void logger_add_rollingfile_appender(logger_ptr logger, std::string filename, size_t filesize, int bkup_index, bool append, mode_t mode, std::string pattern) { log4cpp::PatternLayout* layout = new log4cpp::PatternLayout(); log4cpp::Appender* app = new log4cpp::RollingFileAppender("RollFileAppender::" + filename, filename, filesize, bkup_index, append, mode); layout->setConversionPattern(pattern); app->setLayout(layout); logger->setAppender(app); } std::vector logger_get_logger_names(void) { std::vector names; std::vector *loggers = log4cpp::Category::getCurrentCategories(); std::vector::iterator logger = loggers->begin(); for(;logger!=loggers->end();logger++) { names.push_back((*logger)->getName()); } return names; } } /* namespace gr */ #endif /* HAVE_LOG4CPP */ /****** Start Methods to provide Python the capabilities of the macros ********/ void gr_logger_config(const std::string config_filename, unsigned int watch_period) { GR_CONFIG_AND_WATCH_LOGGER(config_filename, watch_period); } std::vector gr_logger_get_logger_names(void) { std::vector names; GR_GET_LOGGER_NAMES(names); return names; } void gr_logger_reset_config(void) { GR_RESET_CONFIGURATION(); } // Remaining capability provided by gr::logger class in gnuradio/logger.h #endif /* ENABLE_GR_LOGGER */ gnuradio-3.7.2.1/gnuradio-runtime/lib/posix_memalign.cc0000664000175000017500000000616012207440367022715 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "posix_memalign.h" #ifdef HAVE_MALLOC_H // for Cygwin valloc () prototype #include #endif #ifndef HAVE_POSIX_MEMALIGN /* emulate posix_memalign functionality, to some degree */ #include #include "pagesize.h" int posix_memalign (void **memptr, size_t alignment, size_t size) { /* emulate posix_memalign functionality, to some degree */ /* make sure the return handle is valid; return "bad address" if not valid */ if (memptr == 0) return (EFAULT); *memptr = (void*) 0; /* make sure 'alignment' is a power of 2 * and multiple of sizeof (void*) */ /* make sure 'alignment' is a multiple of sizeof (void*) */ if ((alignment % sizeof (void*)) != 0) return (EINVAL); /* make sure 'alignment' is a power of 2 */ if ((alignment & (alignment - 1)) != 0) return (EINVAL); /* good alignment */ #if (ALIGNED_MALLOC != 0) /* if 'malloc' is known to be aligned, and the desired 'alignment' * matches is <= that provided by 'malloc', then use 'malloc'. This * works on, e.g., Darwin 8 & 9: for which malloc is 16-byte aligned. */ size_t am = (size_t) ALIGNED_MALLOC; if (alignment <= am) { /* make sure ALIGNED_MALLOC is a power of 2, to guarantee that the * alignment is correct (since 'alignment' must be a power of 2). */ if ((am & (am - 1)) != 0) return (EINVAL); /* good malloc alignment */ *memptr = malloc (size); } #endif /* (ALIGNED_MALLOC != 0) */ #ifdef HAVE_VALLOC if (*memptr == (void*) 0) { /* try valloc if it exists */ /* cheap and easy way to make sure alignment is met, so long as it * is <= pagesize () */ if (alignment <= (size_t) gr::pagesize ()) { *memptr = valloc (size); } } #endif /* HAVE_VALLOC */ #if (ALIGNED_MALLOC == 0) && !defined (HAVE_VALLOC) /* no posix_memalign, valloc, and malloc isn't known to be aligned * (enough for the input arguments); no idea what to do. */ #error gnuradio-runtime/lib/posix_memalign.cc: Cannot find a way to alloc aligned memory. #endif /* if the pointer wasn't allocated properly, return that there was * not enough memory to allocate; otherwise, return OK (0). */ if (*memptr == (void*) 0) return (ENOMEM); else return (0); }; #endif /* ! HAVE_POSIX_MEMALIGN */ gnuradio-3.7.2.1/gnuradio-runtime/lib/test.cc0000664000175000017500000001460312207440367020662 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "test.h" #include #include #include #include namespace gr { test_sptr make_test(const std::string &name, int min_inputs, int max_inputs, unsigned int sizeof_input_item, int min_outputs, int max_outputs, unsigned int sizeof_output_item, unsigned int history, unsigned int output_multiple, double relative_rate, bool fixed_rate, consume_type_t cons_type, produce_type_t prod_type) { return gnuradio::get_initial_sptr (new test(name, min_inputs, max_inputs, sizeof_input_item, min_outputs, max_outputs, sizeof_output_item, history, output_multiple, relative_rate, fixed_rate,cons_type, prod_type)); } test::test(const std::string &name, int min_inputs, int max_inputs, unsigned int sizeof_input_item, int min_outputs, int max_outputs, unsigned int sizeof_output_item, unsigned int history, unsigned int output_multiple, double relative_rate, bool fixed_rate, consume_type_t cons_type, produce_type_t prod_type) : block (name, io_signature::make(min_inputs, max_inputs, sizeof_input_item), io_signature::make(min_outputs, max_outputs, sizeof_output_item)), d_sizeof_input_item(sizeof_input_item), d_sizeof_output_item(sizeof_output_item), d_check_topology(true), d_consume_type(cons_type), d_min_consume(0), d_max_consume(0), d_produce_type(prod_type), d_min_produce(0), d_max_produce(0) { set_history(history); set_output_multiple(output_multiple); set_relative_rate(relative_rate); set_fixed_rate(fixed_rate); } int test::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { //touch all inputs and outputs to detect segfaults unsigned ninputs = input_items.size (); unsigned noutputs= output_items.size(); for(unsigned i = 0; i < ninputs; i++) { char * in=(char *)input_items[i]; if(ninput_items[i]< (int)(noutput_items+history())) { std::cerr << "ERROR: ninput_items[" << i << "] < noutput_items+history()" << std::endl; std::cerr << "ninput_items[" << i << "] = " << ninput_items[i] << std::endl; std::cerr << "noutput_items+history() = " << noutput_items+history() << std::endl; std::cerr << "noutput_items = " << noutput_items << std::endl; std::cerr << "history() = " << history() << std::endl; throw std::runtime_error ("test"); } else { for (int j = 0; j < ninput_items[i]; j++) { //Touch every available input_item //We use a class variable to avoid the compiler to optimize this away for(unsigned int k = 0; k < d_sizeof_input_item; k++) d_temp= in[j*d_sizeof_input_item+k]; } switch(d_consume_type){ case CONSUME_NOUTPUT_ITEMS: consume(i,noutput_items); break; case CONSUME_NOUTPUT_ITEMS_LIMIT_MAX: consume(i,std::min(noutput_items,d_max_consume)); break; case CONSUME_NOUTPUT_ITEMS_LIMIT_MIN: consume(i,std::min(std::max(noutput_items,d_min_consume),ninput_items[i])); break; case CONSUME_ALL_AVAILABLE: consume(i,ninput_items[i]); break; case CONSUME_ALL_AVAILABLE_LIMIT_MAX: consume(i,std::min(ninput_items[i],d_max_consume)); break; /* //This could result in segfault, uncomment if you want to test this case CONSUME_ALL_AVAILABLE_LIMIT_MIN: consume(i,std::max(ninput_items[i],d_max_consume)); break;*/ case CONSUME_ZERO: consume(i,0); break; case CONSUME_ONE: consume(i,1); break; case CONSUME_MINUS_ONE: consume(i,-1); break; default: consume(i,noutput_items); } } } for(unsigned i = 0; i < noutputs; i++) { char * out=(char *)output_items[i]; { for(int j=0;j #include #include #include #include #include #include namespace gr { #define FLAT_FLOWGRAPH_DEBUG 0 // 32Kbyte buffer size between blocks #define GR_FIXED_BUFFER_SIZE (32*(1L<<10)) static const unsigned int s_fixed_buffer_size = GR_FIXED_BUFFER_SIZE; flat_flowgraph_sptr make_flat_flowgraph() { return flat_flowgraph_sptr(new flat_flowgraph()); } flat_flowgraph::flat_flowgraph() { } flat_flowgraph::~flat_flowgraph() { } void flat_flowgraph::setup_connections() { basic_block_vector_t blocks = calc_used_blocks(); // Assign block details to blocks for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) cast_to_block_sptr(*p)->set_detail(allocate_block_detail(*p)); // Connect inputs to outputs for each block for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { connect_block_inputs(*p); block_sptr block = cast_to_block_sptr(*p); block->set_unaligned(0); block->set_is_unaligned(false); } // Connect message ports connetions for(msg_edge_viter_t i = d_msg_edges.begin(); i != d_msg_edges.end(); i++) { if(FLAT_FLOWGRAPH_DEBUG) std::cout << boost::format("flat_fg connecting msg primitives: (%s, %s)->(%s, %s)\n") % i->src().block() % i->src().port() % i->dst().block() % i->dst().port(); i->src().block()->message_port_sub(i->src().port(), pmt::cons(i->dst().block()->alias_pmt(), i->dst().port())); } } block_detail_sptr flat_flowgraph::allocate_block_detail(basic_block_sptr block) { int ninputs = calc_used_ports(block, true).size(); int noutputs = calc_used_ports(block, false).size(); block_detail_sptr detail = make_block_detail(ninputs, noutputs); block_sptr grblock = cast_to_block_sptr(block); if(!grblock) throw std::runtime_error("allocate_block_detail found non-gr::block"); if(FLAT_FLOWGRAPH_DEBUG) std::cout << "Creating block detail for " << block << std::endl; for(int i = 0; i < noutputs; i++) { grblock->expand_minmax_buffer(i); buffer_sptr buffer = allocate_buffer(block, i); if(FLAT_FLOWGRAPH_DEBUG) std::cout << "Allocated buffer for output " << block << ":" << i << std::endl; detail->set_output(i, buffer); // Update the block's max_output_buffer based on what was actually allocated. grblock->set_max_output_buffer(i, buffer->bufsize()); } return detail; } buffer_sptr flat_flowgraph::allocate_buffer(basic_block_sptr block, int port) { block_sptr grblock = cast_to_block_sptr(block); if(!grblock) throw std::runtime_error("allocate_buffer found non-gr::block"); int item_size = block->output_signature()->sizeof_stream_item(port); // *2 because we're now only filling them 1/2 way in order to // increase the available parallelism when using the TPB scheduler. // (We're double buffering, where we used to single buffer) int nitems = s_fixed_buffer_size * 2 / item_size; // Make sure there are at least twice the output_multiple no. of items if(nitems < 2*grblock->output_multiple()) // Note: this means output_multiple() nitems = 2*grblock->output_multiple(); // can't be changed by block dynamically // If any downstream blocks are decimators and/or have a large output_multiple, // ensure we have a buffer at least twice their decimation factor*output_multiple basic_block_vector_t blocks = calc_downstream_blocks(block, port); // limit buffer size if indicated if(grblock->max_output_buffer(port) > 0) { //std::cout << "constraining output items to " << block->max_output_buffer(port) << "\n"; nitems = std::min((long)nitems, (long)grblock->max_output_buffer(port)); nitems -= nitems%grblock->output_multiple(); if(nitems < 1) throw std::runtime_error("problems allocating a buffer with the given max output buffer constraint!"); } else if(grblock->min_output_buffer(port) > 0) { nitems = std::max((long)nitems, (long)grblock->min_output_buffer(port)); nitems -= nitems%grblock->output_multiple(); if(nitems < 1) throw std::runtime_error("problems allocating a buffer with the given min output buffer constraint!"); } for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { block_sptr dgrblock = cast_to_block_sptr(*p); if(!dgrblock) throw std::runtime_error("allocate_buffer found non-gr::block"); double decimation = (1.0/dgrblock->relative_rate()); int multiple = dgrblock->output_multiple(); int history = dgrblock->history(); nitems = std::max(nitems, static_cast(2*(decimation*multiple+history))); } // std::cout << "make_buffer(" << nitems << ", " << item_size << ", " << grblock << "\n"; // We're going to let this fail once and retry. If that fails, // throw and exit. buffer_sptr b; try { b = make_buffer(nitems, item_size, grblock); } catch(std::bad_alloc&) { b = make_buffer(nitems, item_size, grblock); } return b; } void flat_flowgraph::connect_block_inputs(basic_block_sptr block) { block_sptr grblock = cast_to_block_sptr(block); if (!grblock) throw std::runtime_error("connect_block_inputs found non-gr::block"); // Get its detail and edges that feed into it block_detail_sptr detail = grblock->detail(); edge_vector_t in_edges = calc_upstream_edges(block); // For each edge that feeds into it for(edge_viter_t e = in_edges.begin(); e != in_edges.end(); e++) { // Set the buffer reader on the destination port to the output // buffer on the source port int dst_port = e->dst().port(); int src_port = e->src().port(); basic_block_sptr src_block = e->src().block(); block_sptr src_grblock = cast_to_block_sptr(src_block); if(!src_grblock) throw std::runtime_error("connect_block_inputs found non-gr::block"); buffer_sptr src_buffer = src_grblock->detail()->output(src_port); if(FLAT_FLOWGRAPH_DEBUG) std::cout << "Setting input " << dst_port << " from edge " << (*e) << std::endl; detail->set_input(dst_port, buffer_add_reader(src_buffer, grblock->history()-1, grblock, grblock->sample_delay(src_port))); } } void flat_flowgraph::merge_connections(flat_flowgraph_sptr old_ffg) { // Allocate block details if needed. Only new blocks that aren't pruned out // by flattening will need one; existing blocks still in the new flowgraph will // already have one. for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) { block_sptr block = cast_to_block_sptr(*p); if(!block->detail()) { if(FLAT_FLOWGRAPH_DEBUG) std::cout << "merge: allocating new detail for block " << (*p) << std::endl; block->set_detail(allocate_block_detail(block)); } else if(FLAT_FLOWGRAPH_DEBUG) std::cout << "merge: reusing original detail for block " << (*p) << std::endl; } // Calculate the old edges that will be going away, and clear the // buffer readers on the RHS. for(edge_viter_t old_edge = old_ffg->d_edges.begin(); old_edge != old_ffg->d_edges.end(); old_edge++) { if(FLAT_FLOWGRAPH_DEBUG) std::cout << "merge: testing old edge " << (*old_edge) << "..."; edge_viter_t new_edge; for(new_edge = d_edges.begin(); new_edge != d_edges.end(); new_edge++) if(new_edge->src() == old_edge->src() && new_edge->dst() == old_edge->dst()) break; if(new_edge == d_edges.end()) { // not found in new edge list if(FLAT_FLOWGRAPH_DEBUG) std::cout << "not in new edge list" << std::endl; // zero the buffer reader on RHS of old edge block_sptr block(cast_to_block_sptr(old_edge->dst().block())); int port = old_edge->dst().port(); block->detail()->set_input(port, buffer_reader_sptr()); } else { if (FLAT_FLOWGRAPH_DEBUG) std::cout << "found in new edge list" << std::endl; } } // Now connect inputs to outputs, reusing old buffer readers if they exist for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) { block_sptr block = cast_to_block_sptr(*p); if(FLAT_FLOWGRAPH_DEBUG) std::cout << "merge: merging " << (*p) << "..."; if(old_ffg->has_block_p(*p)) { // Block exists in old flow graph if(FLAT_FLOWGRAPH_DEBUG) std::cout << "used in old flow graph" << std::endl; block_detail_sptr detail = block->detail(); // Iterate through the inputs and see what needs to be done int ninputs = calc_used_ports(block, true).size(); // Might be different now for(int i = 0; i < ninputs; i++) { if(FLAT_FLOWGRAPH_DEBUG) std::cout << "Checking input " << block << ":" << i << "..."; edge edge = calc_upstream_edge(*p, i); // Fish out old buffer reader and see if it matches correct buffer from edge list block_sptr src_block = cast_to_block_sptr(edge.src().block()); block_detail_sptr src_detail = src_block->detail(); buffer_sptr src_buffer = src_detail->output(edge.src().port()); buffer_reader_sptr old_reader; if(i < detail->ninputs()) // Don't exceed what the original detail has old_reader = detail->input(i); // If there's a match, use it if(old_reader && (src_buffer == old_reader->buffer())) { if(FLAT_FLOWGRAPH_DEBUG) std::cout << "matched, reusing" << std::endl; } else { if(FLAT_FLOWGRAPH_DEBUG) std::cout << "needs a new reader" << std::endl; // Create new buffer reader and assign detail->set_input(i, buffer_add_reader(src_buffer, block->history()-1, block)); } } } else { // Block is new, it just needs buffer readers at this point if(FLAT_FLOWGRAPH_DEBUG) std::cout << "new block" << std::endl; connect_block_inputs(block); // Make sure all buffers are aligned setup_buffer_alignment(block); } // Now deal with the fact that the block details might have // changed numbers of inputs and outputs vs. in the old // flowgraph. } } void flat_flowgraph::setup_buffer_alignment(block_sptr block) { const int alignment = volk_get_alignment(); for(int i = 0; i < block->detail()->ninputs(); i++) { void *r = (void*)block->detail()->input(i)->read_pointer(); unsigned long int ri = (unsigned long int)r % alignment; //std::cerr << "reader: " << r << " alignment: " << ri << std::endl; if(ri != 0) { size_t itemsize = block->detail()->input(i)->get_sizeof_item(); block->detail()->input(i)->update_read_pointer(alignment-ri/itemsize); } block->set_unaligned(0); block->set_is_unaligned(false); } for(int i = 0; i < block->detail()->noutputs(); i++) { void *w = (void*)block->detail()->output(i)->write_pointer(); unsigned long int wi = (unsigned long int)w % alignment; //std::cerr << "writer: " << w << " alignment: " << wi << std::endl; if(wi != 0) { size_t itemsize = block->detail()->output(i)->get_sizeof_item(); block->detail()->output(i)->update_write_pointer(alignment-wi/itemsize); } block->set_unaligned(0); block->set_is_unaligned(false); } } std::string flat_flowgraph::edge_list() { std::stringstream s; for(edge_viter_t e = d_edges.begin(); e != d_edges.end(); e++) s << (*e) << std::endl; return s.str(); } std::string flat_flowgraph::msg_edge_list() { std::stringstream s; for(msg_edge_viter_t e = d_msg_edges.begin(); e != d_msg_edges.end(); e++) s << (*e) << std::endl; return s.str(); } void flat_flowgraph::dump() { for(edge_viter_t e = d_edges.begin(); e != d_edges.end(); e++) std::cout << " edge: " << (*e) << std::endl; for(basic_block_viter_t p = d_blocks.begin(); p != d_blocks.end(); p++) { std::cout << " block: " << (*p) << std::endl; block_detail_sptr detail = cast_to_block_sptr(*p)->detail(); std::cout << " detail @" << detail << ":" << std::endl; int ni = detail->ninputs(); int no = detail->noutputs(); for(int i = 0; i < no; i++) { buffer_sptr buffer = detail->output(i); std::cout << " output " << i << ": " << buffer << std::endl; } for(int i = 0; i < ni; i++) { buffer_reader_sptr reader = detail->input(i); std::cout << " reader " << i << ": " << reader << " reading from buffer=" << reader->buffer() << std::endl; } } } block_vector_t flat_flowgraph::make_block_vector(basic_block_vector_t &blocks) { block_vector_t result; for(basic_block_viter_t p = blocks.begin(); p != blocks.end(); p++) { result.push_back(cast_to_block_sptr(*p)); } return result; } void flat_flowgraph::clear_endpoint(const msg_endpoint &e, bool is_src) { for(size_t i=0; iget_bool("PerfCounters", "on", false)) { basic_block_viter_t p; for(p = d_blocks.begin(); p != d_blocks.end(); p++) { block_sptr block = cast_to_block_sptr(*p); if(!block->is_pc_rpc_set()) block->setup_pc_rpc(); } } #endif /* GR_PERFORMANCE_COUNTERS */ } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/vmcircbuf_createfilemapping.h0000664000175000017500000000430512207440367025262 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_VMCIRCBUF_CREATEFILEMAPPING_H #define GR_VMCIRCBUF_CREATEFILEMAPPING_H #include #include "vmcircbuf.h" #ifdef HAVE_CREATEFILEMAPPING #include #endif namespace gr { /*! * \brief concrete class to implement circular buffers with mmap and shm_open * \ingroup internal */ class GR_RUNTIME_API vmcircbuf_createfilemapping : public gr::vmcircbuf { public: // CREATORS vmcircbuf_createfilemapping(int size); virtual ~vmcircbuf_createfilemapping(); #ifdef HAVE_CREATEFILEMAPPING private: HANDLE d_handle; LPVOID d_first_copy; LPVOID d_second_copy; #endif }; /*! * \brief concrete factory for circular buffers built using mmap and shm_open */ class GR_RUNTIME_API vmcircbuf_createfilemapping_factory : public gr::vmcircbuf_factory { private: static gr::vmcircbuf_factory *s_the_factory; public: static gr::vmcircbuf_factory *singleton(); virtual const char *name() const { return "gr::vmcircbuf_createfilemapping_factory"; } /*! * \brief return granularity of mapping, typically equal to page size */ virtual int granularity(); /*! * \brief return a gr::vmcircbuf, or 0 if unable. * * Call this to create a doubly mapped circular buffer. */ virtual gr::vmcircbuf *make(int size); }; } /* namespace gr */ #endif /* GR_VMCIRCBUF_CREATEFILEMAPPING_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/prefs.cc0000664000175000017500000002471312207440367021025 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include namespace fs = boost::filesystem; namespace gr { /* * Stub implementations */ static prefs s_default_singleton; static prefs *s_singleton = &s_default_singleton; prefs * prefs::singleton() { return s_singleton; } void prefs::set_singleton(prefs *p) { s_singleton = p; } prefs::prefs() { _read_files(); } prefs::~prefs() { // nop } std::vector prefs::_sys_prefs_filenames() { std::vector fnames; fs::path dir = prefsdir(); if(!fs::is_directory(dir)) return fnames; fs::directory_iterator diritr(dir); while(diritr != fs::directory_iterator()) { fs::path p = *diritr++; if(p.extension() != ".swp") fnames.push_back(p.string()); } std::sort(fnames.begin(), fnames.end()); // Find if there is a ~/.gnuradio/config.conf file and add this to // the end of the file list to override any preferences in the // installed path config files. fs::path homedir = fs::path(gr::appdata_path()); homedir = homedir/".gnuradio/config.conf"; if(fs::exists(homedir)) { fnames.push_back(homedir.string()); } return fnames; } void prefs::_read_files() { std::string config; std::vector filenames = _sys_prefs_filenames(); std::vector::iterator sitr; char tmp[1024]; for(sitr = filenames.begin(); sitr != filenames.end(); sitr++) { fs::ifstream fin(*sitr); while(!fin.eof()) { fin.getline(tmp, 1024); std::string t(tmp); // ignore empty lines or lines of just comments if((t.size() > 0) && (t[0] != '#')) { // remove any comments in the line size_t hash = t.find("#"); // Use hash marks at the end of each segment as a delimiter config += t.substr(0, hash) + '#'; } } fin.close(); } // Remove all whitespace. config.erase(std::remove_if(config.begin(), config.end(), ::isspace), config.end()); // Convert the string into a map _convert_to_map(config); } void prefs::_convert_to_map(const std::string &conf) { // Convert the string into an map of maps // Map is structured as {section name: map of options} // And options map is simply: {option name: option value} std::string sub = conf; size_t sec_start = sub.find("["); while(sec_start != std::string::npos) { sub = sub.substr(sec_start); size_t sec_end = sub.find("]"); if(sec_end == std::string::npos) throw std::runtime_error("Config file error: Mismatched section label.\n"); std::string sec = sub.substr(1, sec_end-1); size_t next_sec_start = sub.find("[", sec_end); std::string subsec = sub.substr(sec_end+1, next_sec_start-sec_end-2); std::transform(sec.begin(), sec.end(), sec.begin(), ::tolower); std::map options_map = d_config_map[sec]; size_t next_opt = 0; size_t next_val = 0; next_opt = subsec.find("#"); while(next_opt < subsec.size()-1) { next_val = subsec.find("=", next_opt); std::string option = subsec.substr(next_opt+1, next_val-next_opt-1); next_opt = subsec.find("#", next_val); std::string value = subsec.substr(next_val+1, next_opt-next_val-1); std::transform(option.begin(), option.end(), option.begin(), ::tolower); options_map[option] = value; } d_config_map[sec] = options_map; sec_start = sub.find("[", sec_end); } } std::string prefs::to_string() { config_map_itr sections; config_map_elem_itr options; std::stringstream s; for(sections = d_config_map.begin(); sections != d_config_map.end(); sections++) { s << "[" << sections->first << "]" << std::endl; for(options = sections->second.begin(); options != sections->second.end(); options++) { s << options->first << " = " << options->second << std::endl; } s << std::endl; } return s.str(); } void prefs::save() { std::string conf = to_string(); fs::path homedir = fs::path(gr::appdata_path()); homedir = homedir/".gnuradio/config.conf"; fs::ofstream fout(homedir); fout << conf; fout.close(); } char * prefs::option_to_env(std::string section, std::string option) { std::stringstream envname; std::string secname=section, optname=option; std::transform(section.begin(), section.end(), secname.begin(), ::toupper); std::transform(option.begin(), option.end(), optname.begin(), ::toupper); envname << "GR_CONF_" << secname << "_" << optname; return getenv(envname.str().c_str()); } bool prefs::has_section(const std::string §ion) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); return d_config_map.count(s) > 0; } bool prefs::has_option(const std::string §ion, const std::string &option) { if(option_to_env(section, option)) return true; if(has_section(section)) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); std::string o = option; std::transform(option.begin(), option.end(), o.begin(), ::tolower); config_map_itr sec = d_config_map.find(s); return sec->second.count(o) > 0; } else { return false; } } const std::string prefs::get_string(const std::string §ion, const std::string &option, const std::string &default_val) { char *env = option_to_env(section, option); if(env) return std::string(env); if(has_option(section, option)) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); std::string o = option; std::transform(option.begin(), option.end(), o.begin(), ::tolower); config_map_itr sec = d_config_map.find(s); config_map_elem_itr opt = sec->second.find(o); return opt->second; } else { return default_val; } } void prefs::set_string(const std::string §ion, const std::string &option, const std::string &val) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); std::string o = option; std::transform(option.begin(), option.end(), o.begin(), ::tolower); std::map opt_map = d_config_map[s]; opt_map[o] = val; d_config_map[s] = opt_map; } bool prefs::get_bool(const std::string §ion, const std::string &option, bool default_val) { if(has_option(section, option)) { std::string str = get_string(section, option, ""); if(str == "") { return default_val; } std::transform(str.begin(), str.end(), str.begin(), ::tolower); if((str == "true") || (str == "on") || (str == "1")) return true; else if((str == "false") || (str == "off") || (str == "0")) return false; else return default_val; } else { return default_val; } } void prefs::set_bool(const std::string §ion, const std::string &option, bool val) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); std::string o = option; std::transform(option.begin(), option.end(), o.begin(), ::tolower); std::map opt_map = d_config_map[s]; std::stringstream sstr; sstr << (val == true); opt_map[o] = sstr.str(); d_config_map[s] = opt_map; } long prefs::get_long(const std::string §ion, const std::string &option, long default_val) { if(has_option(section, option)) { std::string str = get_string(section, option, ""); if(str == "") { return default_val; } std::stringstream sstr(str); long n; sstr >> n; return n; } else { return default_val; } } void prefs::set_long(const std::string §ion, const std::string &option, long val) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); std::string o = option; std::transform(option.begin(), option.end(), o.begin(), ::tolower); std::map opt_map = d_config_map[s]; std::stringstream sstr; sstr << val; opt_map[o] = sstr.str(); d_config_map[s] = opt_map; } double prefs::get_double(const std::string §ion, const std::string &option, double default_val) { if(has_option(section, option)) { std::string str = get_string(section, option, ""); if(str == "") { return default_val; } std::stringstream sstr(str); double n; sstr >> n; return n; } else { return default_val; } } void prefs::set_double(const std::string §ion, const std::string &option, double val) { std::string s = section; std::transform(section.begin(), section.end(), s.begin(), ::tolower); std::string o = option; std::transform(option.begin(), option.end(), o.begin(), ::tolower); std::map opt_map = d_config_map[s]; std::stringstream sstr; sstr << val; opt_map[o] = sstr.str(); d_config_map[s] = opt_map; } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/hier_block2.cc0000664000175000017500000001067612207702530022065 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006-2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "hier_block2_detail.h" #include namespace gr { #define GR_HIER_BLOCK2_DEBUG 0 hier_block2_sptr make_hier_block2(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature) { return gnuradio::get_initial_sptr (new hier_block2(name, input_signature, output_signature)); } hier_block2::hier_block2(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature) : basic_block(name, input_signature, output_signature), d_detail(new hier_block2_detail(this)), hier_message_ports_in(pmt::PMT_NIL), hier_message_ports_out(pmt::PMT_NIL) { // This bit of magic ensures that self() works in the constructors of derived classes. gnuradio::detail::sptr_magic::create_and_stash_initial_sptr(this); } hier_block2::~hier_block2() { delete d_detail; } hier_block2::opaque_self hier_block2::self() { return shared_from_this(); } hier_block2_sptr hier_block2::to_hier_block2() { return cast_to_hier_block2_sptr(shared_from_this()); } void hier_block2::connect(basic_block_sptr block) { d_detail->connect(block); } void hier_block2::connect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port) { d_detail->connect(src, src_port, dst, dst_port); } void hier_block2::msg_connect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport) { if(!pmt::is_symbol(srcport)) { throw std::runtime_error("bad port id"); } d_detail->msg_connect(src, srcport, dst, dstport); } void hier_block2::msg_connect(basic_block_sptr src, std::string srcport, basic_block_sptr dst, std::string dstport) { d_detail->msg_connect(src, pmt::mp(srcport), dst, pmt::mp(dstport)); } void hier_block2::msg_disconnect(basic_block_sptr src, pmt::pmt_t srcport, basic_block_sptr dst, pmt::pmt_t dstport) { if(!pmt::is_symbol(srcport)) { throw std::runtime_error("bad port id"); } d_detail->msg_disconnect(src, srcport, dst, dstport); } void hier_block2::msg_disconnect(basic_block_sptr src, std::string srcport, basic_block_sptr dst, std::string dstport) { d_detail->msg_disconnect(src, pmt::mp(srcport), dst, pmt::mp(dstport)); } void hier_block2::disconnect(basic_block_sptr block) { d_detail->disconnect(block); } void hier_block2::disconnect(basic_block_sptr src, int src_port, basic_block_sptr dst, int dst_port) { d_detail->disconnect(src, src_port, dst, dst_port); } void hier_block2::disconnect_all() { d_detail->disconnect_all(); } void hier_block2::lock() { d_detail->lock(); } void hier_block2::unlock() { d_detail->unlock(); } flat_flowgraph_sptr hier_block2::flatten() const { flat_flowgraph_sptr new_ffg = make_flat_flowgraph(); d_detail->flatten_aux(new_ffg); return new_ffg; } void hier_block2::set_processor_affinity(const std::vector &mask) { d_detail->set_processor_affinity(mask); } void hier_block2::unset_processor_affinity() { d_detail->unset_processor_affinity(); } std::vector hier_block2::processor_affinity() { return d_detail->processor_affinity(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/local_sighandler.h0000664000175000017500000000342212207440367023034 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_LOCAL_SIGHANDLER_H #define INCLUDED_GR_LOCAL_SIGHANDLER_H #ifdef HAVE_SIGNAL_H #include #endif #include #include namespace gr { /*! * \brief Get and set signal handler. * * \ingroup internal * Constructor installs new handler, destructor reinstalls * original value. */ class GR_RUNTIME_API local_sighandler { private: int d_signum; #ifdef HAVE_SIGACTION struct sigaction d_old_action; #endif public: local_sighandler(int signum, void (*new_handler)(int)); ~local_sighandler(); /* throw gr_signal (signum) */ static void throw_signal(int signum); }; /*! * \brief Representation of signal. */ class GR_RUNTIME_API signal { private: int d_signum; public: signal(int signum) : d_signum(signum) {} int signum() const { return d_signum; } std::string name() const; }; } /* namespace gr */ #endif /* INCLUDED_GR_LOCAL_SIGHANDLER_H */ gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_vmcircbuf.cc0000664000175000017500000000216712207440367022346 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include "vmcircbuf.h" #include void qa_vmcircbuf::test_all() { int verbose = 1; // summary bool ok = gr::vmcircbuf_sysconfig::test_all_factories(verbose); CPPUNIT_ASSERT_EQUAL(true, ok); } gnuradio-3.7.2.1/gnuradio-runtime/lib/scheduler_tpb.cc0000664000175000017500000000576512224021502022520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "scheduler_tpb.h" #include "tpb_thread_body.h" #include #include namespace gr { class tpb_container { block_sptr d_block; int d_max_noutput_items; public: tpb_container(block_sptr block, int max_noutput_items) : d_block(block), d_max_noutput_items(max_noutput_items) {} void operator()() { tpb_thread_body body(d_block, d_max_noutput_items); } }; scheduler_sptr scheduler_tpb::make(flat_flowgraph_sptr ffg, int max_noutput_items) { return scheduler_sptr(new scheduler_tpb(ffg, max_noutput_items)); } scheduler_tpb::scheduler_tpb(flat_flowgraph_sptr ffg, int max_noutput_items) : scheduler(ffg, max_noutput_items) { int block_max_noutput_items; // Get a topologically sorted vector of all the blocks in use. // Being topologically sorted probably isn't going to matter, but // there's a non-zero chance it might help... basic_block_vector_t used_blocks = ffg->calc_used_blocks(); used_blocks = ffg->topological_sort(used_blocks); block_vector_t blocks = flat_flowgraph::make_block_vector(used_blocks); // Ensure that the done flag is clear on all blocks for(size_t i = 0; i < blocks.size(); i++) { blocks[i]->detail()->set_done(false); } // Fire off a thead for each block for(size_t i = 0; i < blocks.size(); i++) { std::stringstream name; name << "thread-per-block[" << i << "]: " << blocks[i]; // If set, use internal value instead of global value if(blocks[i]->is_set_max_noutput_items()) { block_max_noutput_items = blocks[i]->max_noutput_items(); } else { block_max_noutput_items = max_noutput_items; } d_threads.create_thread( gr::thread::thread_body_wrapper (tpb_container(blocks[i], block_max_noutput_items), name.str())); } } scheduler_tpb::~scheduler_tpb() { stop(); } void scheduler_tpb::stop() { d_threads.interrupt_all(); } void scheduler_tpb::wait() { d_threads.join_all(); } } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/lib/realtime_impl.cc0000664000175000017500000001311612207440367022524 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #ifdef HAVE_SCHED_H #include #endif #include #include #include #include #include #include #if defined(HAVE_PTHREAD_SETSCHEDPARAM) || defined(HAVE_SCHED_SETSCHEDULER) #include namespace gr { namespace impl { /*! * Rescale our virtual priority so that it maps to the middle 1/2 of * the priorities given by min_real_pri and max_real_pri. */ static int rescale_virtual_pri(int virtual_pri, int min_real_pri, int max_real_pri) { float rmin = min_real_pri + (0.25 * (max_real_pri - min_real_pri)); float rmax = min_real_pri + (0.75 * (max_real_pri - min_real_pri)); float m = (rmax - rmin) / (rt_priority_max() - rt_priority_min()); float y = m * (virtual_pri - rt_priority_min()) + rmin; int y_int = static_cast(rint(y)); return std::max(min_real_pri, std::min(max_real_pri, y_int)); } } // namespace impl } // namespace gr #endif #if defined(HAVE_PTHREAD_SETSCHEDPARAM) namespace gr { namespace impl { rt_status_t enable_realtime_scheduling(rt_sched_param p) { int policy = p.policy == RT_SCHED_FIFO ? SCHED_FIFO : SCHED_RR; int min_real_pri = sched_get_priority_min(policy); int max_real_pri = sched_get_priority_max(policy); int pri = rescale_virtual_pri(p.priority, min_real_pri, max_real_pri); // FIXME check hard and soft limits with getrlimit, and limit the value we ask for. // fprintf(stderr, "pthread_setschedparam: policy = %d, pri = %d\n", policy, pri); struct sched_param param; memset (¶m, 0, sizeof (param)); param.sched_priority = pri; int result = pthread_setschedparam (pthread_self(), policy, ¶m); if(result != 0) { if(result == EPERM) // N.B., return value, not errno return RT_NO_PRIVS; else { fprintf(stderr, "pthread_setschedparam: failed to set real time priority: %s\n", strerror(result)); return RT_OTHER_ERROR; } } //printf("SCHED_FIFO enabled with priority = %d\n", pri); return RT_OK; } } // namespace impl } // namespace gr #elif defined(HAVE_SCHED_SETSCHEDULER) namespace gr { namespace impl { rt_status_t enable_realtime_scheduling(rt_sched_param p) { int policy = p.policy == RT_SCHED_FIFO ? SCHED_FIFO : SCHED_RR; int min_real_pri = sched_get_priority_min(policy); int max_real_pri = sched_get_priority_max(policy); int pri = rescale_virtual_pri(p.priority, min_real_pri, max_real_pri); // FIXME check hard and soft limits with getrlimit, and limit the value we ask for. // fprintf(stderr, "sched_setscheduler: policy = %d, pri = %d\n", policy, pri); int pid = 0; // this process struct sched_param param; memset(¶m, 0, sizeof(param)); param.sched_priority = pri; int result = sched_setscheduler(pid, policy, ¶m); if(result != 0){ if(errno == EPERM) return RT_NO_PRIVS; else { perror("sched_setscheduler: failed to set real time priority"); return RT_OTHER_ERROR; } } //printf("SCHED_FIFO enabled with priority = %d\n", pri); return RT_OK; } } // namespace impl } // namespace gr #elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) #include namespace gr { namespace impl { rt_status_t enable_realtime_scheduling(rt_sched_param p) { //set the priority class on the process int pri_class = (true)? REALTIME_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS; if(SetPriorityClass(GetCurrentProcess(), pri_class) == 0) return RT_OTHER_ERROR; //scale the priority value to the constants int priorities[] = { THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL }; const double priority = double(p.priority)/(rt_priority_max() - rt_priority_min()); size_t pri_index = size_t((priority+1.0)*6/2.0); // -1 -> 0, +1 -> 6 pri_index %= sizeof(priorities)/sizeof(*priorities); //range check //set the thread priority on the thread if(SetThreadPriority(GetCurrentThread(), priorities[pri_index]) == 0) return RT_OTHER_ERROR; //printf("SetPriorityClass + SetThreadPriority\n"); return RT_OK; } } // namespace impl } // namespace gr #else namespace gr { namespace impl { rt_status_t enable_realtime_scheduling(rt_sched_param p) { return RT_NOT_IMPLEMENTED; } } // namespace impl } // namespace gr #endif gnuradio-3.7.2.1/gnuradio-runtime/lib/qa_logger.cc0000664000175000017500000000310012207440367021631 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This class gathers together all the test cases for the example * directory into a single test suite. As you create new test cases, * add them here. */ #ifdef HAVE_CONFIG_H #include #endif #include #include void qa_logger::t1() { #ifdef ENABLE_GR_LOG // This doesn't really test anything, more just // making sure nothing's gone horribly wrong. GR_LOG_GETLOGGER(LOG,"main"); GR_ADD_CONSOLE_APPENDER("main","cout","%d{%H:%M:%S} : %m%n"); GR_LOG_NOTICE(LOG,"test from c++ NOTICE"); GR_LOG_DEBUG(LOG,"test from c++ DEBUG"); GR_LOG_INFO(LOG,"test from c++ INFO"); GR_LOG_WARN(LOG,"test from c++ WARN"); GR_LOG_ERROR(LOG,"test from c++ ERROR"); GR_LOG_FATAL(LOG,"test from c++ FATAL"); CPPUNIT_ASSERT(true); #endif } gnuradio-3.7.2.1/gnuradio-runtime/lib/malloc16.h0000664000175000017500000000210112207440367021151 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #ifdef __cplusplus extern "C" { #endif #include GR_RUNTIME_API void *malloc16Align(int size); GR_RUNTIME_API void *calloc16Align(size_t nmemb,size_t size); GR_RUNTIME_API void free16Align(void *p); #ifdef __cplusplus } #endif gnuradio-3.7.2.1/gnuradio-runtime/ctrlport.conf.example0000664000175000017500000000167512207440367023005 0ustar jcorganjcorgan## Use this to create an endpoint used to export ControlPort. ## ## A typical configuation would be to specify using a particular ## interface (determined from the IP address) and port number: ## ## ControlPort.Endpoints=tcp -h 192.168.1.1 -p 9000 ## ## A similar endpoint without the port number stated will pick a ## random, free port: ## ## ControlPort.Endpoints=tcp -h 192.168.1.1 ## ## ICE has some wildcard capabilities, as well. The following tells ## ICE to use all available interfaces: ## ## ControlPort.Endpoints=tcp -h * ## ## Using 'default' for the host will use what 'hostname' resolves to. ## ## For more details: ## http://doc.zeroc.com/display/Ice/Proxy+and+Endpoint+Syntax ## http://www.zeroc.com/doc/Ice-3.2.1/manual/ProxyEndpointRef.51.2.html # ControlPort.Endpoints = tcp -t 300 -h 127.0.0.1 -p 23456 ## Set a default hostname (or IP) if no '-h' is used in the Endpoint ## configuration #Ice.Default.Host = myhost gnuradio-3.7.2.1/gnuradio-runtime/swig/0000775000175000017500000000000012241717647017601 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/swig/CMakeLists.txt0000664000175000017500000000712212207440367022335 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR} ${LOG4CPP_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) set(GR_SWIG_LIBRARIES gnuradio-pmt gnuradio-runtime ${LOG4CPP_LIBRARIES} ) ############################################################### # Build pmt swig ############################################################### set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/pmt_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/pmt ${CMAKE_CURRENT_BINARY_DIR}/../include/pmt) list(APPEND GR_SWIG_TARGET_DEPS pmt_generated) GR_SWIG_MAKE(pmt_swig pmt_swig.i) GR_SWIG_INSTALL( TARGETS pmt_swig DESTINATION ${GR_PYTHON_DIR}/pmt COMPONENT "runtime_python" ) add_custom_target(pmt_swig DEPENDS ${SWIG_MODULE_pmt_swig_REAL_NAME}) ############################################################### # Build gnuradio-runtime swig ############################################################### # Only use if log4cpp is installed # Define ENABLE_GR_LOG for the .i file to ignore it. if(ENABLE_GR_LOG) SET(GR_SWIG_FLAGS "-DENABLE_GR_LOG") endif(ENABLE_GR_LOG) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) list(APPEND GR_SWIG_FLAGS -DGR_CTRLPORT) list(APPEND GR_SWIG_LIBRARIES ${ICE_LIBRARIES}) list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/runtime_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include) set(GR_RUNTIME_SWIG_DOC_FILE ${GR_SWIG_DOC_FILE}) list(APPEND GR_SWIG_TARGET_DEPS pmt_swig) GR_SWIG_MAKE(runtime_swig runtime_swig.i) GR_SWIG_INSTALL( TARGETS runtime_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/gr COMPONENT "runtime_python" ) install( FILES gnuradio_swig_bug_workaround.h runtime_swig.i gnuradio.i basic_block.i block.i block_detail.i block_gateway.i buffer.i complex_vec_test.i constants.i feval.i gnuradio.i gr_ctrlport.i gr_extras.i gr_intrusive_ptr.i gr_logger.i gr_shared_ptr.i gr_swig_block_magic.i gr_types.i hier_block2.i io_signature.i message.i msg_handler.i msg_queue.i pmt_swig.i prefs.i realtime.i single_threaded_scheduler.i sync_block.i sync_decimator.i sync_interpolator.i tagged_stream_block.i tags.i top_block.i ${CMAKE_CURRENT_BINARY_DIR}/runtime_swig_doc.i ${CMAKE_CURRENT_BINARY_DIR}/pmt_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "runtime_swig" ) gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_shared_ptr.i0000664000175000017500000000123412207440367022570 0ustar jcorganjcorgan// // shared_ptr // // An enhanced relative of scoped_ptr with reference counted copy semantics. // The object pointed to is deleted when the last shared_ptr pointing to it // is destroyed or reset. // // // This is highly hacked up version of boost::shared_ptr // We just need enough to get SWIG to "do the right thing" and // generate "Smart Pointer" code. // namespace boost { template class shared_ptr { public: shared_ptr() { } shared_ptr (T * p) { } T * operator-> () // never throws { return px; } private: T * px; // contained pointer int pn; }; // shared_ptr };gnuradio-3.7.2.1/gnuradio-runtime/swig/sync_interpolator.i0000664000175000017500000000212412207440367023522 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::sync_interpolator : public gr::sync_block { protected: sync_interpolator(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature, unsigned interpolation); }; gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_logger.i0000664000175000017500000000636512207440367021726 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /******************************************************************************* * Copyright 2011 Johns Hopkins University Applied Physics Lab * Author: Mark Plett * Description: * SWIG interface generator file for gr_logger module. gr_logger wraps log4cpp logging * for gnuradio. *******************************************************************************/ %feature("autodoc", "1"); // generate python docstrings %include "exception.i" %import "gnuradio.i" // the common stuff %{ #include "gnuradio_swig_bug_workaround.h" // mandatory bug fix #include %} //----------------------------------- %{ // The .h files #include %} %rename(logger) gr::logger; %rename(logger_config) gr_logger_config; %rename(logger_get_names) gr_logger_get_logger_names; %rename(logger_reset_config) gr_logger_reset_config; void gr_logger_config(const std::string config_filename,unsigned int watch_period = 0); std::vector gr_logger_get_logger_names(void); void gr_logger_reset_config(void); namespace gr { // void logger_config(const std::string config_filename, unsigned int watch_period = 0); // std::vector logger_get_logger_names(void); // void logger_reset_config(void); class logger { public: logger(std::string logger_name); void set_level(std::string level){LOG_SET_LEVEL(d_logger,level);} void get_level(std::string &level){LOG_GET_LEVEL(d_logger,level);} void debug(std::string msg){LOG_DEBUG(d_logger,msg);}; void info(std::string msg){LOG_INFO(d_logger,msg);}; void notice(std::string msg){LOG_NOTICE(d_logger,msg);}; void warn(std::string msg){LOG_WARN(d_logger,msg);}; void error(std::string msg){LOG_ERROR(d_logger,msg);}; void crit(std::string msg){LOG_CRIT(d_logger,msg);}; void alert(std::string msg){LOG_ALERT(d_logger,msg);}; void fatal(std::string msg){LOG_FATAL(d_logger,msg);}; void emerg(std::string msg){LOG_EMERG(d_logger,msg);}; void errorIF(bool cond,std::string msg){LOG_ERRORIF(d_logger,cond,msg);}; void log_assert(bool cond,std::string msg){LOG_ASSERT(d_logger,cond,msg);}; void add_console_appender(std::string target,std::string pattern); void add_file_appender(std::string filename,bool append,std::string pattern); void add_rollingfile_appender(std::string filename, size_t filesize, int bkup_index, bool append, mode_t mode, std::string pattern); }; } /* namespace gr */ gnuradio-3.7.2.1/gnuradio-runtime/swig/sync_decimator.i0000664000175000017500000000210212207440367022743 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::sync_decimator : public gr::sync_block { protected: sync_decimator(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature, unsigned decimation); }; gnuradio-3.7.2.1/gnuradio-runtime/swig/runtime_swig.i0000664000175000017500000000515312207440367022465 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define GR_RUNTIME_API #ifndef SWIGIMPORTED %include "runtime_swig_doc.i" %module(directors="1") gnuradio_runtime #endif %feature("autodoc", "1"); // generate python docstrings #define SW_RUNTIME %include "gnuradio.i" // the common stuff %{ #include %} %include %{ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include %} %constant int sizeof_char = sizeof(char); %constant int sizeof_short = sizeof(short); %constant int sizeof_int = sizeof(int); %constant int sizeof_float = sizeof(float); %constant int sizeof_double = sizeof(double); %constant int sizeof_gr_complex = sizeof(gr_complex); %include %include "basic_block.i" %include "block.i" %include "block_detail.i" %include "buffer.i" %include "constants.i" %include "feval.i" %include "hier_block2.i" %include "io_signature.i" %include "message.i" %include "msg_handler.i" %include "msg_queue.i" %include "prefs.i" %include "realtime.i" %include "sync_block.i" %include "sync_decimator.i" %include "sync_interpolator.i" %include "tagged_stream_block.i" %include "tags.i" %include "top_block.i" %include "block_gateway.i" %include "gr_logger.i" %include "gr_swig_block_magic.i" %include "gr_ctrlport.i" gnuradio-3.7.2.1/gnuradio-runtime/swig/complex_vec_test.i0000664000175000017500000000074212207440367023313 0ustar jcorganjcorgan std::vector > complex_vec_test0(); std::vector > complex_vec_test1(const std::vector > &input); std::complex complex_scalar_test0(); std::complex complex_scalar_test1(std::complex input); std::vector int_vec_test0(); std::vector int_vec_test1(const std::vector &input); std::vector float_vec_test0(); std::vector float_vec_test1(const std::vector &input); gnuradio-3.7.2.1/gnuradio-runtime/swig/buffer.i0000664000175000017500000000374712207440367021231 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::buffer; typedef boost::shared_ptr gr::buffer_sptr; %template(buffer_sptr) boost::shared_ptr; %rename(buffer) gr::make_buffer; %ignore gr::buffer; gr::buffer_sptr gr::make_buffer (int nitems, size_t sizeof_item, gr::block_sptr link); class gr::buffer_reader; typedef boost::shared_ptr gr::buffer_reader_sptr; %template(buffer_reader_sptr) boost::shared_ptr; %ignore gr::buffer_reader; %rename(buffer_add_reader) gr::buffer_add_reader; gr::buffer_reader_sptr gr::buffer_add_reader (gr::buffer_sptr buf, int nzero_preload, gr::block_sptr link); namespace gr { class gr::buffer { public: ~buffer(); private: buffer(int nitems, size_t sizeof_item, gr::block_sptr link); }; class gr::buffer_reader { public: ~buffer_reader(); private: friend class buffer; buffer_reader(gr::buffer_sptr buffer, unsigned int read_index, gr::block_sptr link); }; %rename(buffer_ncurrently_allocated) buffer_ncurrently_allocated; long buffer_ncurrently_allocated(); %rename(buffer_reader_ncurrently_allocated) buffer_reader_ncurrently_allocated; long buffer_reader_ncurrently_allocated(); } gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_swig_block_magic.i0000664000175000017500000000405212207440367023721 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %define GR_SWIG_BLOCK_MAGIC(PKG, BASE_NAME) _GR_SWIG_BLOCK_MAGIC_HELPER(PKG, BASE_NAME, PKG ## _ ## BASE_NAME) %enddef %define _GR_SWIG_BLOCK_MAGIC_HELPER_COMMON(PKG, BASE_NAME, FULL_NAME) class FULL_NAME; typedef boost::shared_ptr FULL_NAME ## _sptr; %template(FULL_NAME ## _sptr) boost::shared_ptr; %rename(BASE_NAME) PKG ## _make_ ## BASE_NAME; %ignore FULL_NAME; %enddef #ifdef SWIGPYTHON %define _GR_SWIG_BLOCK_MAGIC_HELPER(PKG, BASE_NAME, FULL_NAME) _GR_SWIG_BLOCK_MAGIC_HELPER_COMMON(PKG, BASE_NAME, FULL_NAME) %pythoncode %{ FULL_NAME ## _sptr.__repr__ = lambda self: "" % (self.name(), self.unique_id ()) %} %enddef #endif %define GR_SWIG_BLOCK_MAGIC2(PKG, BASE_NAME) %template(BASE_NAME ## _sptr) boost::shared_ptr; %pythoncode %{ BASE_NAME ## _sptr.__repr__ = lambda self: "" % (self.name(), self.unique_id()) BASE_NAME = BASE_NAME.make; %} %enddef %define GR_SWIG_BLOCK_MAGIC_FACTORY(PKG, BASE_NAME, FACTORY) %template(FACTORY ## _sptr) boost::shared_ptr; %pythoncode %{ FACTORY ## _sptr.__repr__ = lambda self: "" % (self.name(), self.unique_id()) FACTORY = BASE_NAME ## _make_ ## FACTORY; %} %enddef gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_extras.i0000664000175000017500000000424512207440367021750 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_EXTRAS_I #define GR_EXTRAS_I //////////////////////////////////////////////////////////////////////// // Language independent exception handler //////////////////////////////////////////////////////////////////////// %include exception.i %exception { try { $action } catch(std::exception &e) { SWIG_exception(SWIG_RuntimeError, e.what()); } catch(...) { SWIG_exception(SWIG_RuntimeError, "Unknown exception"); } } //////////////////////////////////////////////////////////////////////// // Wrapper for python calls that may block //////////////////////////////////////////////////////////////////////// /*! * Use GR_PYTHON_BLOCKING_CODE when calling code that blocks. * * The try/catch is to save us from boost::thread::interrupt: * If a thread from the scheduler (or any other boost thread) * is blocking the routine and throws an interrupt exception. */ %{ #define GR_PYTHON_BLOCKING_CODE(code) { \ PyThreadState *_save; \ _save = PyEval_SaveThread(); \ try{code} \ catch(...){PyEval_RestoreThread(_save); throw;} \ PyEval_RestoreThread(_save); \ } %} #endif /*GR_EXTRAS_I*/ gnuradio-3.7.2.1/gnuradio-runtime/swig/top_block.i0000664000175000017500000000454212214652673021731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %template(top_block_sptr) boost::shared_ptr; namespace gr { // Hack to have a Python shim implementation of gr.top_block // that instantiates one of these and passes through calls %rename(top_block_swig) make_top_block; gr::top_block_sptr make_top_block(const std::string name) throw (std::logic_error); class top_block : public gr::hier_block2 { private: top_block(const std::string &name); public: ~top_block(); void start(int max_noutput_items=100000000) throw (std::runtime_error); void stop(); //void wait(); //void run() throw (std::runtime_error); void lock(); void unlock() throw (std::runtime_error); std::string edge_list(); std::string msg_edge_list(); void dump(); int max_noutput_items(); void set_max_noutput_items(int nmax); gr::top_block_sptr to_top_block(); // Needed for Python type coercion }; } #ifdef SWIGPYTHON %inline %{ void top_block_run_unlocked(gr::top_block_sptr r) throw (std::runtime_error) { GR_PYTHON_BLOCKING_CODE ( r->run(); ) } void top_block_start_unlocked(gr::top_block_sptr r, int max_noutput_items) throw (std::runtime_error) { GR_PYTHON_BLOCKING_CODE ( r->start(max_noutput_items); ) } void top_block_wait_unlocked(gr::top_block_sptr r) throw (std::runtime_error) { GR_PYTHON_BLOCKING_CODE ( r->wait(); ) } void top_block_stop_unlocked(gr::top_block_sptr r) throw (std::runtime_error) { GR_PYTHON_BLOCKING_CODE ( r->stop(); ) } %} #endif gnuradio-3.7.2.1/gnuradio-runtime/swig/tags.i0000664000175000017500000000202112207440367020676 0ustar jcorganjcorgan/* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %{ #include %} %import //for pmt support %include //gives support for a vector of tags (get tags in range) %include "std_vector.i" %template(tags_vector_t) std::vector; gnuradio-3.7.2.1/gnuradio-runtime/swig/io_signature.i0000664000175000017500000000456212207440367022444 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005,2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ namespace gr { class GR_RUNTIME_API io_signature { io_signature(int min_streams, int max_streams, const std::vector &sizeof_stream_items); public: typedef boost::shared_ptr sptr; // Avoids a swig warning, otherwise we could just // #include instead of redoing this // #entire class //static const int IO_INFINITE = -1; ~io_signature(); static sptr make(int min_streams, int max_streams, int sizeof_stream_item); static sptr make2(int min_streams, int max_streams, int sizeof_stream_item1, int sizeof_stream_item2); static sptr make3(int min_streams, int max_streams, int sizeof_stream_item1, int sizeof_stream_item2, int sizeof_stream_item3); static sptr makev(int min_streams, int max_streams, const std::vector &sizeof_stream_items); int min_streams() const { return d_min_streams; } int max_streams() const { return d_max_streams; } int sizeof_stream_item(int index) const; std::vector sizeof_stream_items() const; }; } /* namespace gr */ %template(io_signature_sptr) boost::shared_ptr; %pythoncode %{ io_signature_sptr.__repr__ = lambda self: "" % (self.min_streams(), self.max_streams()) io_signaturev = io_signature.makev; io_signature3 = io_signature.make3; io_signature2 = io_signature.make2; io_signature = io_signature.make; %} gnuradio-3.7.2.1/gnuradio-runtime/swig/prefs.i0000664000175000017500000000407512207440367021072 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::prefs { public: static gr::prefs *singleton(); static void set_singleton(gr::prefs *p); virtual ~prefs(); std::string to_string(); void save(); virtual bool has_section(const std::string §ion); virtual bool has_option(const std::string §ion, const std::string &option); virtual const std::string get_string(const std::string §ion, const std::string &option, const std::string &default_val); virtual void set_string(const std::string §ion, const std::string &option, const std::string &val); virtual bool get_bool(const std::string §ion, const std::string &option, bool default_val); virtual void set_bool(const std::string §ion, const std::string &option, bool val); virtual long get_long(const std::string §ion, const std::string &option, long default_val); virtual void set_long(const std::string §ion, const std::string &option, long val); virtual double get_double(const std::string §ion, const std::string &option, double default_val); virtual void set_double(const std::string §ion, const std::string &option, double val); }; gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_ctrlport.i0000664000175000017500000000606612207440367022316 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef GR_CTRLPORT typedef uint32_t DisplayType; // DisplayType Plotting types const uint32_t DISPNULL = 0x0000; const uint32_t DISPTIME = 0x0001; const uint32_t DISPXY = 0x0002; const uint32_t DISPPSD = 0x0004; const uint32_t DISPSPEC = 0x0008; const uint32_t DISPRAST = 0x0010; // DisplayType Options const uint32_t DISPOPTCPLX = 0x0100; const uint32_t DISPOPTLOG = 0x0200; const uint32_t DISPOPTSTEM = 0x0400; const uint32_t DISPOPTSTRIP = 0x0800; const uint32_t DISPOPTSCATTER = 0x1000; enum priv_lvl_t { RPC_PRIVLVL_ALL = 0, RPC_PRIVLVL_MIN = 9, RPC_PRIVLVL_NONE = 10 }; enum KnobType { KNOBBOOL, KNOBCHAR, KNOBINT, KNOBFLOAT, KNOBDOUBLE, KNOBSTRING, KNOBLONG, KNOBVECBOOL, KNOBCOMPLEX, KNOBCOMPLEXD, KNOBVECCHAR, KNOBVECINT, KNOBVECFLOAT, KNOBVECDOUBLE, KNOBVECSTRING, KNOBVECLONG }; %{ #include #include #include %} %include %include %include // Declare this class here but without the nested templated class // inside (replaces include of rpcmanager.h) class GR_RUNTIME_API rpcmanager : public virtual rpcmanager_base { public: rpcmanager(); ~rpcmanager(); static rpcserver_booter_base* get(); static void register_booter(rpcserver_booter_base* booter); }; // Attach a new python callback method to Python function %extend pycallback_object { // Set a Python function object as a callback function // Note : PyObject *pyfunc is remapped with a typempap void activate(PyObject *pyfunc) { self->set_callback(pyfunc); Py_INCREF(pyfunc); } } %template(RPC_get_string) pycallback_object; %template(RPC_get_int) pycallback_object; %template(RPC_get_float) pycallback_object; %template(RPC_get_double) pycallback_object; %template(RPC_get_complex) pycallback_object; %template(RPC_get_complexd) pycallback_object; %template(RPC_get_vector_float) pycallback_object >; %template(RPC_get_vector_gr_complex) pycallback_object >; #endif /* GR_CTRLPORT */ gnuradio-3.7.2.1/gnuradio-runtime/swig/basic_block.i0000664000175000017500000000401212231076123022165 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::basic_block; typedef boost::shared_ptr gr::basic_block_sptr; %template(basic_block_sptr) boost::shared_ptr; %import "pmt_swig.i" // support vectors of these... namespace std { %template(x_vector_basic_block_sptr) vector; }; namespace gr { class gr::basic_block { protected: basic_block(); public: virtual ~basic_block(); std::string name() const; std::string symbol_name() const; gr::io_signature::sptr input_signature() const; gr::io_signature::sptr output_signature() const; long unique_id() const; gr::basic_block_sptr to_basic_block(); bool check_topology(int ninputs, int noutputs); std::string alias(); void set_block_alias(std::string name); void _post(pmt::pmt_t which_port, pmt::pmt_t msg); pmt::pmt_t message_ports_in(); pmt::pmt_t message_ports_out(); pmt::pmt_t message_subscribers(pmt::pmt_t which_port); }; %rename(block_ncurrently_allocated) basic_block_ncurrently_allocated; long basic_block_ncurrently_allocated(); } #ifdef SWIGPYTHON %pythoncode %{ basic_block_sptr.__repr__ = lambda self: "" % (self.name(), self.unique_id ()) %} #endif gnuradio-3.7.2.1/gnuradio-runtime/swig/gnuradio.i0000664000175000017500000000424612241717647021571 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // Disable warning about base class types #pragma SWIG nowarn=401 //////////////////////////////////////////////////////////////////////// // gnuradio.i // SWIG interface definition //////////////////////////////////////////////////////////////////////// %include "std_string.i" %include #ifdef SW_RUNTIME %include #endif //////////////////////////////////////////////////////////////////////// // Headers %{ #include "gnuradio_swig_bug_workaround.h" // mandatory bug fix %} %feature("autodoc","1"); // Required for a bug in SWIG 2.0.4 with GCC 4.6 // see: http://sourceforge.net/p/swig/bugs/1187/ %{ #include %} // local file %include %include //////////////////////////////////////////////////////////////////////// #ifndef SW_RUNTIME // import runtime_swig.i for all but sw_runtime, since it needs to %include %import %import #endif //////////////////////////////////////////////////////////////////////// %{ #include #include #include #include #include #include #include #include #include %} %include gnuradio-3.7.2.1/gnuradio-runtime/swig/tagged_stream_block.i0000664000175000017500000000213712207440367023730 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::tagged_stream_block : public gr::block { protected: tagged_stream_block(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature, const std::string &length_tag_key); }; gnuradio-3.7.2.1/gnuradio-runtime/swig/hier_block2.i0000664000175000017500000000733212207702530022126 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %include class gr::hier_block2; typedef boost::shared_ptr gr::hier_block2_sptr; %template(hier_block2_sptr) boost::shared_ptr; namespace gr { // Hack to have a Python shim implementation of gr.hier_block2 // that instantiates one of these and passes through calls %rename(hier_block2_swig) make_hier_block2; gr::hier_block2_sptr make_hier_block2(const std::string name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature) throw (std::runtime_error); } // Rename connect and disconnect so that we can more easily build a // better interface in scripting land. %rename(primitive_connect) gr::hier_block2::connect; %rename(primitive_disconnect) gr::hier_block2::disconnect; %rename(primitive_msg_connect) gr::hier_block2::msg_connect; %rename(primitive_msg_disconnect) gr::hier_block2::msg_disconnect; %rename(primitive_message_port_register_hier_in) gr::hier_block2::message_port_register_hier_in; %rename(primitive_message_port_register_hier_out) gr::hier_block2::message_port_register_hier_out; namespace gr { class hier_block2 : public gr::basic_block { private: hier_block2(const std::string name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); public: ~hier_block2 (); void connect(gr::basic_block_sptr block) throw (std::invalid_argument); void connect(gr::basic_block_sptr src, int src_port, gr::basic_block_sptr dst, int dst_port) throw (std::invalid_argument); void msg_connect(gr::basic_block_sptr src, pmt::pmt_t srcport, gr::basic_block_sptr dst, pmt::pmt_t dstport) throw (std::runtime_error); void msg_connect(gr::basic_block_sptr src, std::string srcport, gr::basic_block_sptr dst, std::string dstport) throw (std::runtime_error); void msg_disconnect(gr::basic_block_sptr src, pmt::pmt_t srcport, gr::basic_block_sptr dst, pmt::pmt_t dstport) throw (std::runtime_error); void msg_disconnect(gr::basic_block_sptr src, std::string srcport, gr::basic_block_sptr dst, std::string dstport) throw (std::runtime_error); void disconnect(gr::basic_block_sptr block) throw (std::invalid_argument); void disconnect(gr::basic_block_sptr src, int src_port, gr::basic_block_sptr dst, int dst_port) throw (std::invalid_argument); void disconnect_all(); void lock(); void unlock(); void message_port_register_hier_in(pmt::pmt_t port_id); void message_port_register_hier_out(pmt::pmt_t port_id); void set_processor_affinity(const std::vector &mask); void unset_processor_affinity(); std::vector processor_affinity(); gr::hier_block2_sptr to_hier_block2(); // Needed for Python type coercion }; } gnuradio-3.7.2.1/gnuradio-runtime/swig/block.i0000664000175000017500000000702112237515111021030 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %include class gr::block; typedef boost::shared_ptr gr::block_sptr; %template(block_sptr) boost::shared_ptr; // support vectors of these... namespace std { %template(x_vector_block_sptr) vector; }; class gr::block : public gr::basic_block { protected: block (const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); public: virtual ~block (); unsigned history () const; void declare_sample_delay(int which, int delay); void declare_sample_delay(unsigned int delay); unsigned sample_delay(int which) const; int output_multiple () const; double relative_rate () const; bool start(); bool stop(); uint64_t nitems_read(unsigned int which_input); uint64_t nitems_written(unsigned int which_output); // Methods to manage the block's max_noutput_items size. int max_noutput_items(); void set_max_noutput_items(int m); void unset_max_noutput_items(); bool is_set_max_noutput_items(); // Methods to manage block's min/max buffer sizes. long max_output_buffer(int i); void set_max_output_buffer(long max_output_buffer); void set_max_output_buffer(int port, long max_output_buffer); long min_output_buffer(int i); void set_min_output_buffer(long min_output_buffer); void set_min_output_buffer(int port, long min_output_buffer); // Methods to access performance counters float pc_noutput_items(); float pc_noutput_items_avg(); float pc_noutput_items_var(); float pc_nproduced(); float pc_nproduced_avg(); float pc_nproduced_var(); float pc_input_buffers_full(int which); float pc_input_buffers_full_avg(int which); float pc_input_buffers_full_var(int which); std::vector pc_input_buffers_full(); std::vector pc_input_buffers_full_avg(); std::vector pc_input_buffers_full_var(); float pc_output_buffers_full(int which); float pc_output_buffers_full_avg(int which); float pc_output_buffers_full_var(int which); std::vector pc_output_buffers_full(); std::vector pc_output_buffers_full_avg(); std::vector pc_output_buffers_full_var(); float pc_work_time(); float pc_work_time_avg(); float pc_work_time_var(); float pc_work_time_total(); // Methods to manage processor affinity. void set_processor_affinity(const std::vector &mask); void unset_processor_affinity(); std::vector processor_affinity(); // Methods to manage thread priority int active_thread_priority(); int thread_priority(); int set_thread_priority(int priority); // internal use //block_detail_sptr detail () const { return d_detail; } //void set_detail (block_detail_sptr detail) { d_detail = detail; } }; gnuradio-3.7.2.1/gnuradio-runtime/swig/realtime.i0000664000175000017500000000274012207440367021552 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ %rename(enable_realtime_scheduling) gr::enable_realtime_scheduling; // NOTE: This is duplicated from gnuradio-runtime/include/realtime.h, // and must be kept in sync with it. This is the least evil workaround // for allowing 3rd party code builds to work when GNU Radio is // installed from binary packages into the standard system directories. // Otherwise, they can't find #include , since // pkg-config strips -I/usr/include from the --cflags path. namespace gr { typedef enum { RT_OK = 0, RT_NOT_IMPLEMENTED, RT_NO_PRIVS, RT_OTHER_ERROR } rt_status_t; gr::rt_status_t gr::enable_realtime_scheduling(); } gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_types.i0000664000175000017500000000551012241717647021610 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef SWIG_GR_TYPES_I #define SWIG_GR_TYPES_I %include "stdint.i" %{ #include #include #include #include #include // size_t #include #include %} %include %include %include typedef std::complex gr_complex; typedef std::complex gr_complexd; typedef unsigned long long uint64_t; typedef long long int64_t; namespace std { %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector; %template() vector< vector< unsigned char > >; %template() vector< vector< char > >; %template() vector< vector< short > >; %template() vector< vector< int > >; %template() vector< vector< long int> >; %template() vector< vector< float > >; %template() vector< vector< double > >; %template() vector; %template(gr_vsize_t) std::vector; %template(gr_vvvsize_t) std::vector< std::vector< std::vector > >; }; %template(gr_vector_complexf) std::vector< std::complex >; %template(gr_vector_complexd) std::vector< std::complex >; %template(gr_vector_vector_complexf) std::vector< std::vector< std::complex > >; %template(gr_vector_vector_complexd) std::vector< std::vector< std::complex > >; // Fix for Issue #529 #ifdef SIZE_T_32 // On 32-bit systems, whenever we see std::vector, replace it // with vector %apply std::vector { std::vector }; #else // On 64-bit systems, whenever we see std::vector, replace it // with vector %apply std::vector { std::vector }; #endif #endif /* SWIG_GR_TYPES_I */ gnuradio-3.7.2.1/gnuradio-runtime/swig/block_detail.i0000664000175000017500000000336312207440367022366 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::block_detail; typedef boost::shared_ptr gr::block_detail_sptr; %template(block_detail_sptr) boost::shared_ptr; %rename(block_detail) gr::make_block_detail; %ignore gr::block_detail; gr::block_detail_sptr gr:: gr::make_block_detail(unsigned int ninputs, unsigned int noutputs); namespace gr { class gr::block_detail { public: ~block_detail (); int ninputs() const; int noutputs() const; bool sink_p() const; bool source_p() const; void set_input(unsigned int which, gr::buffer_reader_sptr reader); gr::buffer_reader_sptr input(unsigned int which); void set_output(unsigned int which, gr::buffer_sptr buffer); gr::buffer_sptr output(unsigned int which); private: block_detail(unsigned int ninputs, unsigned int noutputs); }; %rename(block_detail_ncurrently_allocated) block_detail_ncurrently_allocated; long block_detail_ncurrently_allocated(); } gnuradio-3.7.2.1/gnuradio-runtime/swig/message.i0000664000175000017500000000366612207440367021404 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ namespace gr { /*! * \brief Message. * * The ideas and method names for adjustable message length were * lifted from the click modular router "Packet" class. */ class message { public: typedef boost::shared_ptr sptr; private: message(long type, double arg1, double arg2, size_t length); unsigned char *buf_data() const; size_t buf_len() const; public: static sptr make(long type = 0, double arg1 = 0, double arg2 = 0, size_t length = 0); static sptr make_from_string(const std::string s, long type = 0, double arg1 = 0, double arg2 = 0); ~message(); long type() const; double arg1() const; double arg2() const; void set_type(long type); void set_arg1(double arg1); void set_arg2(double arg2); size_t length() const; std::string to_string() const; }; %rename(message_ncurrently_allocated) message_ncurrently_allocated; long message_ncurrently_allocated(); } %template(message_sptr) boost::shared_ptr; %pythoncode %{ message_from_string = message.make_from_string message = message.make %} gnuradio-3.7.2.1/gnuradio-runtime/swig/constants.i0000664000175000017500000000053612207440367021765 0ustar jcorganjcorgan/* -*- c++ -*- */ namespace gr { %rename(prefix) prefix; %rename(sysconfdir) sysconfdir; %rename(prefsdir) prefsdir; %rename(build_date) build_date; %rename(version) version; const std::string prefix(); const std::string sysconfdir(); const std::string prefsdir(); const std::string build_date(); const std::string version(); } gnuradio-3.7.2.1/gnuradio-runtime/swig/pmt_swig.i0000664000175000017500000002633212207440367021604 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #pragma SWIG nowarn=401 %include "std_string.i" %include "stdint.i" %{ #include #include #include #include #include #include // size_t #include #include #include #include %} %feature("autodoc","1"); //load generated python docstrings %include "pmt_swig_doc.i" %include %include %include %template(pmt_vector_int8) std::vector; %template(pmt_vector_uint8) std::vector; %template(pmt_vector_int16) std::vector; %template(pmt_vector_uint16) std::vector; %template(pmt_vector_int32) std::vector; %template(pmt_vector_uint32) std::vector; %template(pmt_vector_float) std::vector; %template(pmt_vector_double) std::vector; %template(pmt_vector_cfloat) std::vector< std::complex >; %template(pmt_vector_cdouble) std::vector< std::complex >; //////////////////////////////////////////////////////////////////////// // Language independent exception handler //////////////////////////////////////////////////////////////////////// // Template intrusive_ptr for Swig to avoid dereferencing issues namespace pmt{ class pmt_base; } //%import %import %template(swig_int_ptr) boost::intrusive_ptr; namespace pmt{ typedef boost::intrusive_ptr pmt_t; // Allows Python to directly print a PMT object %pythoncode %{ swig_int_ptr.__repr__ = lambda self: write_string(self) %} extern const pmt_t PMT_T; extern const pmt_t PMT_F; extern const pmt_t PMT_NIL; extern const pmt_t PMT_EOF; bool is_bool(pmt_t obj); bool is_true(pmt_t obj); bool is_false(pmt_t obj); pmt_t from_bool(bool val); bool to_bool(pmt_t val); bool is_symbol(const pmt_t& obj); pmt_t string_to_symbol(const std::string &s); pmt_t intern(const std::string &s); const std::string symbol_to_string(const pmt_t& sym); bool is_number(pmt_t obj); bool is_integer(pmt_t x); pmt_t from_long(long x); long to_long(pmt_t x); bool is_uint64(pmt_t x); pmt_t from_uint64(uint64_t x); uint64_t to_uint64(pmt_t x); bool is_real(pmt_t obj); pmt_t from_double(double x); double to_double(pmt_t x); bool is_complex(pmt_t obj); pmt_t make_rectangular(double re, double im); pmt_t from_complex(const std::complex &z); std::complex to_complex(pmt_t z); bool is_null(const pmt_t& x); bool is_pair(const pmt_t& obj); pmt_t cons(const pmt_t& x, const pmt_t& y); pmt_t car(const pmt_t& pair); pmt_t cdr(const pmt_t& pair); void set_car(pmt_t pair, pmt_t value); void set_cdr(pmt_t pair, pmt_t value); pmt_t caar(pmt_t pair); pmt_t cadr(pmt_t pair); pmt_t cdar(pmt_t pair); pmt_t cddr(pmt_t pair); pmt_t caddr(pmt_t pair); pmt_t cadddr(pmt_t pair); bool is_tuple(pmt_t x); pmt_t make_tuple(); pmt_t make_tuple(const pmt_t &e0); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8); pmt_t make_tuple(const pmt_t &e0, const pmt_t &e1, const pmt_t &e2, const pmt_t &e3, const pmt_t &e4, const pmt_t &e5, const pmt_t &e6, const pmt_t &e7, const pmt_t &e8, const pmt_t &e9); pmt_t to_tuple(const pmt_t &x); pmt_t tuple_ref(const pmt_t &tuple, size_t k); bool is_vector(pmt_t x); pmt_t make_vector(size_t k, pmt_t fill); pmt_t vector_ref(pmt_t vector, size_t k); void vector_set(pmt_t vector, size_t k, pmt_t obj); void vector_fill(pmt_t vector, pmt_t fill); bool is_blob(pmt_t x); pmt_t make_blob(const void *buf, size_t len); const void *blob_data(pmt_t blob); size_t blob_length(pmt_t blob); bool is_uniform_vector(pmt_t x); bool is_u8vector(pmt_t x); bool is_s8vector(pmt_t x); bool is_u16vector(pmt_t x); bool is_s16vector(pmt_t x); bool is_u32vector(pmt_t x); bool is_s32vector(pmt_t x); bool is_u64vector(pmt_t x); bool is_s64vector(pmt_t x); bool is_f32vector(pmt_t x); bool is_f64vector(pmt_t x); bool is_c32vector(pmt_t x); bool is_c64vector(pmt_t x); pmt_t make_u8vector(size_t k, uint8_t fill); pmt_t make_s8vector(size_t k, int8_t fill); pmt_t make_u16vector(size_t k, uint16_t fill); pmt_t make_s16vector(size_t k, int16_t fill); pmt_t make_u32vector(size_t k, uint32_t fill); pmt_t make_s32vector(size_t k, int32_t fill); pmt_t make_u64vector(size_t k, uint64_t fill); pmt_t make_s64vector(size_t k, int64_t fill); pmt_t make_f32vector(size_t k, float fill); pmt_t make_f64vector(size_t k, double fill); pmt_t make_c32vector(size_t k, std::complex fill); pmt_t make_c64vector(size_t k, std::complex fill); pmt_t init_u8vector(size_t k, const std::vector &data); pmt_t init_s8vector(size_t k, const std::vector &data); pmt_t init_u16vector(size_t k, const std::vector &data); pmt_t init_s16vector(size_t k, const std::vector &data); pmt_t init_u32vector(size_t k, const std::vector &data); pmt_t init_s32vector(size_t k, const std::vector &data); pmt_t init_f32vector(size_t k, const std::vector &data); pmt_t init_f64vector(size_t k, const std::vector &data); pmt_t init_c32vector(size_t k, const std::vector > &data); pmt_t init_c64vector(size_t k, const std::vector > &data); uint8_t u8vector_ref(pmt_t v, size_t k); int8_t s8vector_ref(pmt_t v, size_t k); uint16_t u16vector_ref(pmt_t v, size_t k); int16_t s16vector_ref(pmt_t v, size_t k); uint32_t u32vector_ref(pmt_t v, size_t k); int32_t s32vector_ref(pmt_t v, size_t k); uint64_t u64vector_ref(pmt_t v, size_t k); int64_t s64vector_ref(pmt_t v, size_t k); float f32vector_ref(pmt_t v, size_t k); double f64vector_ref(pmt_t v, size_t k); std::complex c32vector_ref(pmt_t v, size_t k); std::complex c64vector_ref(pmt_t v, size_t k); void u8vector_set(pmt_t v, size_t k, uint8_t x); //< v[k] = x void s8vector_set(pmt_t v, size_t k, int8_t x); void u16vector_set(pmt_t v, size_t k, uint16_t x); void s16vector_set(pmt_t v, size_t k, int16_t x); void u32vector_set(pmt_t v, size_t k, uint32_t x); void s32vector_set(pmt_t v, size_t k, int32_t x); void u64vector_set(pmt_t v, size_t k, uint64_t x); void s64vector_set(pmt_t v, size_t k, int64_t x); void f32vector_set(pmt_t v, size_t k, float x); void f64vector_set(pmt_t v, size_t k, double x); void c32vector_set(pmt_t v, size_t k, std::complex x); void c64vector_set(pmt_t v, size_t k, std::complex x); %apply size_t & INOUT { size_t &len }; const void *uniform_vector_elements(pmt_t v, size_t &len); const std::vector u8vector_elements(pmt_t v); const std::vector s8vector_elements(pmt_t v); const std::vector u16vector_elements(pmt_t v); const std::vector s16vector_elements(pmt_t v); const std::vector u32vector_elements(pmt_t v); const std::vector s32vector_elements(pmt_t v); const std::vector f32vector_elements(pmt_t v); const std::vector f64vector_elements(pmt_t v); const std::vector > c32vector_elements(pmt_t v); const std::vector > c64vector_elements(pmt_t v); bool is_dict(const pmt_t &obj); pmt_t make_dict(); pmt_t dict_add(const pmt_t &dict, const pmt_t &key, const pmt_t &value); pmt_t dict_delete(const pmt_t &dict, const pmt_t &key); bool dict_has_key(const pmt_t &dict, const pmt_t &key); pmt_t dict_ref(const pmt_t &dict, const pmt_t &key, const pmt_t ¬_found); pmt_t dict_items(pmt_t dict); pmt_t dict_keys(pmt_t dict); pmt_t dict_values(pmt_t dict); bool is_any(pmt_t obj); pmt_t make_any(const boost::any &any); boost::any any_ref(pmt_t obj); void any_set(pmt_t obj, const boost::any &any); bool is_msg_accepter(const pmt_t &obj); pmt_t make_msg_accepter(boost::shared_ptr ma); boost::shared_ptr msg_accepter_ref(const pmt_t &obj); bool eq(const pmt_t& x, const pmt_t& y); bool eqv(const pmt_t& x, const pmt_t& y); bool equal(const pmt_t& x, const pmt_t& y); size_t length(const pmt_t& v); pmt_t assq(pmt_t obj, pmt_t alist); pmt_t assv(pmt_t obj, pmt_t alist); pmt_t assoc(pmt_t obj, pmt_t alist); pmt_t map(pmt_t proc(const pmt_t&), pmt_t list); pmt_t reverse(pmt_t list); pmt_t reverse_x(pmt_t list); inline static pmt_t acons(pmt_t x, pmt_t y, pmt_t a); pmt_t nth(size_t n, pmt_t list); pmt_t nthcdr(size_t n, pmt_t list); pmt_t memq(pmt_t obj, pmt_t list); pmt_t memv(pmt_t obj, pmt_t list); pmt_t member(pmt_t obj, pmt_t list); bool subsetp(pmt_t list1, pmt_t list2); pmt_t list1(const pmt_t& x1); pmt_t list2(const pmt_t& x1, const pmt_t& x2); pmt_t list3(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3); pmt_t list4(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4); pmt_t list5(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4, const pmt_t& x5); pmt_t list6(const pmt_t& x1, const pmt_t& x2, const pmt_t& x3, const pmt_t& x4, const pmt_t& x5, const pmt_t& x6); pmt_t list_add(pmt_t list, const pmt_t& item); pmt_t list_rm(pmt_t list, const pmt_t& item); bool list_has(pmt_t list, const pmt_t& item); bool is_eof_object(pmt_t obj); pmt_t read(std::istream &port); void write(pmt_t obj, std::ostream &port); std::string write_string(pmt_t obj); //void pmt_print(pmt_t v); bool serialize(pmt_t obj, std::streambuf &sink); pmt_t deserialize(std::streambuf &source); void dump_sizeof(); std::string serialize_str(pmt_t obj); pmt_t deserialize_str(std::string str); } //namespace pmt gnuradio-3.7.2.1/gnuradio-runtime/swig/msg_handler.i0000664000175000017500000000177112207440367022236 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /*! * \brief abstract class of message handlers */ class gr::msg_handler { public: virtual ~msg_handler () = 0; //! handle \p msg virtual void handle(gr::message::sptr msg) = 0; }; gnuradio-3.7.2.1/gnuradio-runtime/swig/msg_queue.i0000664000175000017500000000616612207440367021750 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2009-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ namespace gr { /*! * \brief thread-safe message queue */ class msg_queue : public gr::msg_handler { public: typedef boost::shared_ptr sptr; static sptr make(unsigned int limit=0); msg_queue(unsigned int limit); ~msg_queue(); //! Generic msg_handler method: insert the message. //void handle(gr::message::sptr msg) { insert_tail (msg); } /*! * \brief Insert message at tail of queue. * \param msg message * * Block if queue if full. */ //void insert_tail(gr::message::sptr msg); /*! * \brief Delete message from head of queue and return it. * Block if no message is available. */ //gr::message::sptr delete_head(); /*! * \brief If there's a message in the q, delete it and return it. * If no message is available, return 0. */ gr::message::sptr delete_head_nowait(); //! is the queue empty? bool empty_p() const; //! is the queue full? bool full_p() const; //! return number of messages in queue unsigned int count() const; //! Delete all messages from the queue void flush(); }; } /* * The following kludge-o-rama releases the Python global interpreter * lock around these potentially blocking calls. We don't want * libgnuradio-runtime to be dependent on Python, thus we create these * functions that serve as replacements for the normal C++ delete_head * and insert_tail methods. The %pythoncode smashes these new C++ * functions into the gr.msg_queue wrapper class, so that everything * appears normal. (An evil laugh is heard in the distance...) */ #ifdef SWIGPYTHON %inline %{ gr::message::sptr py_msg_queue__delete_head(gr::msg_queue::sptr q) { gr::message::sptr msg; GR_PYTHON_BLOCKING_CODE( msg = q->delete_head(); ) return msg; } void py_msg_queue__insert_tail(gr::msg_queue::sptr q, gr::message::sptr msg) { GR_PYTHON_BLOCKING_CODE( q->insert_tail(msg); ) } %} // smash in new python delete_head and insert_tail methods... %template(msg_queue_sptr) boost::shared_ptr; %pythoncode %{ msg_queue_sptr.delete_head = py_msg_queue__delete_head msg_queue_sptr.insert_tail = py_msg_queue__insert_tail msg_queue_sptr.handle = py_msg_queue__insert_tail msg_queue = msg_queue.make %} #endif // SWIGPYTHON gnuradio-3.7.2.1/gnuradio-runtime/swig/gr_intrusive_ptr.i0000664000175000017500000001014012207440367023346 0ustar jcorganjcorgan// This file was borrowed from the SWIG project to allow use to // wrap PMTs that use intrusive pointers. This is only necessary // to support backwards compatability with older distributions of // Linux that do not natively support a new enough version of SWIG. // We do this to prevent having to update our dependency on a new // SWIG. Eventually, the need for this should go away. // Allow for different namespaces for shared_ptr / intrusive_ptr - they could be boost or std or std::tr1 // For example for std::tr1, use: // #define SWIG_SHARED_PTR_NAMESPACE std // #define SWIG_SHARED_PTR_SUBNAMESPACE tr1 // #define SWIG_INTRUSIVE_PTR_NAMESPACE boost // #define SWIG_INTRUSIVE_PTR_SUBNAMESPACE #if !defined(SWIG_INTRUSIVE_PTR_NAMESPACE) # define SWIG_INTRUSIVE_PTR_NAMESPACE boost #endif #if defined(SWIG_INTRUSIVE_PTR_SUBNAMESPACE) # define SWIG_INTRUSIVE_PTR_QNAMESPACE SWIG_INTRUSIVE_PTR_NAMESPACE::SWIG_INTRUSIVE_PTR_SUBNAMESPACE #else # define SWIG_INTRUSIVE_PTR_QNAMESPACE SWIG_INTRUSIVE_PTR_NAMESPACE #endif namespace SWIG_INTRUSIVE_PTR_NAMESPACE { #if defined(SWIG_INTRUSIVE_PTR_SUBNAMESPACE) namespace SWIG_INTRUSIVE_PTR_SUBNAMESPACE { #endif template class intrusive_ptr { }; #if defined(SWIG_INTRUSIVE_PTR_SUBNAMESPACE) } #endif } %fragment("SWIG_intrusive_deleter", "header") { template struct SWIG_intrusive_deleter { void operator()(T *p) { if (p) intrusive_ptr_release(p); } }; } %fragment("SWIG_null_deleter", "header") { struct SWIG_null_deleter { void operator() (void const *) const { } }; %#define SWIG_NO_NULL_DELETER_0 , SWIG_null_deleter() %#define SWIG_NO_NULL_DELETER_1 } // Main user macro for defining intrusive_ptr typemaps for both const and non-const pointer types // For plain classes, do not use for derived classes %define SWIG_INTRUSIVE_PTR(PROXYCLASS, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS(PROXYCLASS, , TYPE) SWIG_INTRUSIVE_PTR_TYPEMAPS(PROXYCLASS, const, TYPE) %enddef // Main user macro for defining intrusive_ptr typemaps for both const and non-const pointer types // For derived classes %define SWIG_INTRUSIVE_PTR_DERIVED(PROXYCLASS, BASECLASSTYPE, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS(PROXYCLASS, , TYPE) SWIG_INTRUSIVE_PTR_TYPEMAPS(PROXYCLASS, const, TYPE) %types(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > = SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< BASECLASSTYPE >) %{ *newmemory = SWIG_CAST_NEW_MEMORY; return (void *) new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< BASECLASSTYPE >(*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *)$from); %} %extend TYPE { static SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< BASECLASSTYPE > SWIGSharedPtrUpcast(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast) { return swigSharedPtrUpcast; } } %enddef // Extra user macro for including classes in intrusive_ptr typemaps for both const and non-const pointer types // This caters for classes which cannot be wrapped by intrusive_ptrs but are still part of the class hierarchy // For plain classes, do not use for derived classes %define SWIG_INTRUSIVE_PTR_NO_WRAP(PROXYCLASS, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP(PROXYCLASS, , TYPE) SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP(PROXYCLASS, const, TYPE) %enddef // Extra user macro for including classes in intrusive_ptr typemaps for both const and non-const pointer types // This caters for classes which cannot be wrapped by intrusive_ptrs but are still part of the class hierarchy // For derived classes %define SWIG_INTRUSIVE_PTR_DERIVED_NO_WRAP(PROXYCLASS, BASECLASSTYPE, TYPE...) SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP(PROXYCLASS, , TYPE) SWIG_INTRUSIVE_PTR_TYPEMAPS_NO_WRAP(PROXYCLASS, const, TYPE) %types(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > = SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< BASECLASSTYPE >) %{ *newmemory = SWIG_CAST_NEW_MEMORY; return (void *) new SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< BASECLASSTYPE >(*(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > *)$from); %} %extend TYPE { static SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< BASECLASSTYPE > SWIGSharedPtrUpcast(SWIG_SHARED_PTR_QNAMESPACE::shared_ptr< TYPE > swigSharedPtrUpcast) { return swigSharedPtrUpcast; } } %enddef gnuradio-3.7.2.1/gnuradio-runtime/swig/gnuradio_swig_bug_workaround.h0000664000175000017500000000250112207440367025713 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GNURADIO_SWIG_BUG_WORKAROUND_H #define INCLUDED_GNURADIO_SWIG_BUG_WORKAROUND_H /* * This include files works around a bug in SWIG 1.3.21 and 22 * where it fails to emit these declarations when doing * %import "gnuradio.i" */ class base_error_handler; class basic_block; class block; class file_error_handler; class hier_block2; class msg_handler; class msg_queue; class sync_block; class sync_decimator; class sync_interpolator; class top_block; #endif /* INCLUDED_GNURADIO_SWIG_BUG_WORKAROUND_H */ gnuradio-3.7.2.1/gnuradio-runtime/swig/single_threaded_scheduler.i0000664000175000017500000000332612207440367025130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include class gr::single_threaded_scheduler; typedef boost::shared_ptr gr::single_threaded_scheduler_sptr; %template(single_threaded_scheduler_sptr) boost::shared_ptr; %rename(single_threaded_scheduler) gr::make_single_threaded_scheduler; %ignore gr::single_threaded_scheduler; gr::single_threaded_scheduler_sptr gr::make_single_threaded_scheduler(const std::vector &modules); class gr::single_threaded_scheduler { public: ~single_threaded_scheduler (); // void run (); void stop (); private: single_threaded_scheduler (const std::vector &modules); }; #ifdef SWIGPYTHON %inline %{ void sts_pyrun (gr::single_threaded_scheduler_sptr s) { Py_BEGIN_ALLOW_THREADS; // release global interpreter lock s->run (); Py_END_ALLOW_THREADS; // acquire global interpreter lock } %} #endif gnuradio-3.7.2.1/gnuradio-runtime/swig/feval.i0000664000175000017500000000617412207440367021052 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * N.B., this is a _very_ non-standard SWIG .i file * * It contains a bunch of magic that is required to ensure that when * these classes are used as base classes for python code, * everything works when calling back from C++ into Python. * * The gist of the problem is that our C++ code is usually not holding * the Python Global Interpreter Lock (GIL). Thus if we invoke a * "director" method from C++, we'll end up in Python not holding the * GIL. Disaster (SIGSEGV) will result. To avoid this we insert a * "shim" that grabs and releases the GIL. * * If you don't understand SWIG "directors" or the Python GIL, * don't bother trying to understand what's going on in here. * * [We could eliminate a bunch of this hair by requiring SWIG 1.3.29 * or later and some additional magic declarations, but many systems * aren't shipping that version yet. Thus we kludge...] */ // Directors are only supported in Python, Java and C# #ifdef SWIGPYTHON %import "pmt_swig.i" // Enable SWIG directors for these classes %feature("director") gr::py_feval_dd; %feature("director") gr::py_feval_cc; %feature("director") gr::py_feval_ll; %feature("director") gr::py_feval; %feature("director") gr::py_feval_p; %feature("nodirector") gr::py_feval_dd::calleval; %feature("nodirector") gr::py_feval_cc::calleval; %feature("nodirector") gr::py_feval_ll::calleval; %feature("nodirector") gr::py_feval::calleval; %feature("nodirector") gr::py_feval_p::calleval; //%exception { // try { $action } // catch (Swig::DirectorException &e) { std::cerr << e.getMessage(); SWIG_fail; } //} %ignore gr::feval_dd; %ignore gr::feval_cc; %ignore gr::feval_ll; %ignore gr::feval; %ignore gr::feval_p; %include /* * These are the ones to derive from in Python. They have the magic shim * that ensures that we're holding the Python GIL when we enter Python land... */ namespace gr { %rename(feval_dd) py_feval_dd; %rename(feval_cc) py_feval_cc; %rename(feval_ll) py_feval_ll; %rename(feval) py_feval; %rename(feval_p) py_feval_p; } %include namespace gr { // examples / test cases %rename(feval_dd_example) gr::feval_dd_example; %rename(feval_cc_example) gr::feval_cc_example; %rename(feval_ll_example) gr::feval_ll_example; %rename(feval_example) gr::feval_example; } #endif // SWIGPYTHON gnuradio-3.7.2.1/gnuradio-runtime/swig/block_gateway.i0000664000175000017500000000323612207440367022564 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ //////////////////////////////////////////////////////////////////////// // standard includes //////////////////////////////////////////////////////////////////////// %include %include %import %template(void_start_vector_t) std::vector; //////////////////////////////////////////////////////////////////////// // block headers //////////////////////////////////////////////////////////////////////// %{ #include %} //////////////////////////////////////////////////////////////////////// // block magic //////////////////////////////////////////////////////////////////////// %include %template(block_gateway_sptr) boost::shared_ptr; %pythoncode %{ block_gateway_sptr.__repr__ = lambda self: "" block_gateway = block_gateway.make; %} gnuradio-3.7.2.1/gnuradio-runtime/swig/sync_block.i0000664000175000017500000000200712207440367022072 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ class gr::sync_block : public gr::block { protected: sync_block(const std::string &name, gr::io_signature::sptr input_signature, gr::io_signature::sptr output_signature); }; gnuradio-3.7.2.1/gnuradio-runtime/swig/gen-swig-bug-fix0000775000175000017500000000630212207440367022601 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys import re def write_header (f): f.write ('''/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GNURADIO_SWIG_BUG_WORKAROUND_H #define INCLUDED_GNURADIO_SWIG_BUG_WORKAROUND_H /* * This include files works around a bug in SWIG 1.3.21 and 22 * where it fails to emit these declarations when doing * %import "gnuradio.i" */ ''') def write_trailer (f): f.write (''' #endif /* INCLUDED_GNURADIO_SWIG_BUG_WORKAROUND_H */ ''') def doit (input, output): re_RULES_BEGIN = re.compile ('RULES \(BEGIN\)') re_RULES_END = re.compile ('RULES \(END\)') re_RETURN = re.compile ('^\s*return') re_NOT_ID = re.compile ('[^a-zA-Z0-9_]') words = {} write_header (output) for line in input: if re_RULES_BEGIN.search (line): break for line in input: if re_RULES_END.search (line): break if not re_RETURN.match (line): continue line = re_NOT_ID.sub (' ', line) line = re.sub (' +', ' ', line) for w in line.split (' '): words[w] = 1 for w in ('', 'return', 'void', 'x'): del words[w] wl = words.keys() wl.sort () for w in wl: output.write ('class ' + w + ';\n') write_trailer (output) def main (): if len (sys.argv) != 3: sys.stderr.write ("usage: %s gnuradio_swig_python.cc gnuradio_swig_bug_workaround.h\n" % (sys.argv[0],)) sys.exit (1) input_filename = sys.argv[1] output_filename = sys.argv[2] input = open (input_filename, "r") output = open (output_filename, "w") doit (input, output) if __name__ == '__main__': main () gnuradio-3.7.2.1/gnuradio-runtime/gr_log_default.conf0000664000175000017500000000304112207440367022444 0ustar jcorganjcorgan/* * Copyright 2006,2010,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ log4j.rootCategory=EMERG,A1 log4j.category.gr_log=DEBUG,A2 log4j.category.gr_log_debug=NOTSET,A3 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.target=System.out log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=Root :%p: %c{1} - %m%n log4j.appender.A2=org.apache.log4j.ConsoleAppender log4j.appender.A2.target=System.out log4j.appender.A2.layout=org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern=gr::log :%p: %c{1} - %m%n log4j.appender.A3=org.apache.log4j.ConsoleAppender log4j.appender.A3.target=System.out log4j.appender.A3.layout=org.apache.log4j.PatternLayout log4j.appender.A3.layout.ConversionPattern=gr::debug :%p: %c{1} - %m%n gnuradio-3.7.2.1/gnuradio-runtime/apps/0000775000175000017500000000000012207440367017565 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/apps/CMakeLists.txt0000664000175000017500000000275512207440367022336 0ustar jcorganjcorgan# Copyright 2010-2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories( ${Boost_LIBRARY_DIRS} ) ######################################################################## # Setup executables ######################################################################## add_executable(gnuradio-config-info gnuradio-config-info.cc) target_link_libraries(gnuradio-config-info gnuradio-runtime ${Boost_LIBRARIES}) install( TARGETS gnuradio-config-info DESTINATION ${GR_RUNTIME_DIR} COMPONENT "runtime_runtime" ) gnuradio-3.7.2.1/gnuradio-runtime/apps/gnuradio-config-info.cc0000664000175000017500000000377012207440367024107 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #if HAVE_CONFIG_H #include #endif #include #include #include namespace po = boost::program_options; int main(int argc, char **argv) { po::options_description desc("Program options: gnuradio [options]"); po::variables_map vm; desc.add_options() ("help,h", "print help message") ("prefix", "print gnuradio installation prefix") ("sysconfdir", "print gnuradio system configuration directory") ("prefsdir", "print gnuradio preferences directory") ("builddate", "print gnuradio build date (RFC2822 format)") ("version,v", "print gnuradio version") ; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.size() == 0 || vm.count("help")) { std::cout << desc << std::endl; return 1; } if(vm.count("prefix")) std::cout << gr::prefix() << std::endl; if(vm.count("sysconfdir")) std::cout << gr::sysconfdir() << std::endl; if(vm.count("prefsdir")) std::cout << gr::prefsdir() << std::endl; if(vm.count("builddate")) std::cout << gr::build_date() << std::endl; if(vm.count("version")) std::cout << gr::version() << std::endl; return 0; } gnuradio-3.7.2.1/gnuradio-runtime/ctrlport.conf.in0000664000175000017500000000030012207440367021740 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [ctrlport] ice_directory=@slicedir@ gnuradio-3.7.2.1/gnuradio-runtime/examples/0000775000175000017500000000000012207440367020440 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/examples/CMakeLists.txt0000664000175000017500000000154112207440367023201 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. add_subdirectory(mp-sched) add_subdirectory(network) add_subdirectory(volk_benchmark) gnuradio-3.7.2.1/gnuradio-runtime/examples/network/0000775000175000017500000000000012207440367022131 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/examples/network/CMakeLists.txt0000664000175000017500000000175012207440367024674 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. GR_PYTHON_INSTALL(PROGRAMS audio_sink.py audio_source.py dial_tone_sink.py dial_tone_source.py vector_sink.py vector_source.py DESTINATION ${GR_PKG_DATA_DIR}/examples/network COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gnuradio-runtime/examples/network/vector_sink.py0000775000175000017500000000437412207440367025044 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser class vector_sink(gr.top_block): def __init__(self, host, port, pkt_size, eof): gr.top_block.__init__(self, "vector_sink") udp = blocks.udp_source(gr.sizeof_float, host, port, pkt_size, eof=eof) sink = blocks.file_sink(gr.sizeof_float, "received.dat") self.connect(udp, sink) if __name__ == "__main__": parser = OptionParser(option_class=eng_option) parser.add_option("", "--host", type="string", default="0.0.0.0", help="local host name (domain name or IP address)") parser.add_option("", "--port", type="int", default=65500, help="port value to listen to for connection") parser.add_option("", "--packet-size", type="int", default=1471, help="packet size.") parser.add_option("", "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 # Create an instance of a hierarchical block top_block = vector_sink(options.host, options.port, options.packet_size, not options.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass gnuradio-3.7.2.1/gnuradio-runtime/examples/network/dial_tone_source.py0000775000175000017500000000576712207440367026043 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: from gnuradio import analog except ImportError: sys.stderr.write("This example requires gr-analog.\n") try: from gnuradio import blocks except ImportError: sys.stderr.write("This example requires gr-blocks.\n") class dial_tone_source(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "dial_tone_source") amplitude = 0.3 src0 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 350, amplitude) src1 = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 440, amplitude) add = blocks.add_ff() # Throttle needed here to account for the other side's audio card sampling rate thr = blocks.throttle(gr.sizeof_float, sample_rate) sink = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof) self.connect(src0, (add, 0)) self.connect(src1, (add, 1)) self.connect(add, thr, sink) if __name__ == '__main__': parser = OptionParser(option_class=eng_option) parser.add_option("", "--host", type="string", default="localhost", help="Remote host name (domain name or IP address") parser.add_option("", "--port", type="int", default=65500, help="port number to connect to") parser.add_option("", "--packet-size", type="int", default=1472, help="packet size.") parser.add_option("-r", "--sample-rate", type="int", default=8000, help="audio signal sample rate [default=%default]") parser.add_option("", "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 # Create an instance of a hierarchical block top_block = dial_tone_source(options.host, options.port, options.packet_size, options.sample_rate, not options.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass gnuradio-3.7.2.1/gnuradio-runtime/examples/network/dial_tone_sink.py0000775000175000017500000000465712207440367025504 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser class dial_tone_sink(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "dial_tone_sink") udp = blocks.udp_source(gr.sizeof_float, host, port, pkt_size, eof=eof) sink = audio.sink(sample_rate) self.connect(udp, sink) if __name__ == '__main__': parser = OptionParser(option_class=eng_option) parser.add_option("", "--host", type="string", default="0.0.0.0", help="local host name (domain name or IP address)") parser.add_option("", "--port", type="int", default=65500, help="port value to listen to for connection") parser.add_option("", "--packet-size", type="int", default=1472, help="packet size.") parser.add_option("-r", "--sample-rate", type="int", default=8000, help="audio signal sample rate [default=%default]") parser.add_option("", "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 # Create an instance of a hierarchical block top_block = dial_tone_sink(options.host, options.port, options.packet_size, options.sample_rate, not options.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass gnuradio-3.7.2.1/gnuradio-runtime/examples/network/vector_source.py0000775000175000017500000000436712207440367025402 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser class vector_source(gr.top_block): def __init__(self, host, port, pkt_size, eof): gr.top_block.__init__(self, "vector_source") data = [i*0.01 for i in range(1000)] vec = blocks.vector_source_f(data, True) udp = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof) self.connect(vec, udp) if __name__ == '__main__': parser = OptionParser(option_class=eng_option) parser.add_option("", "--host", type="string", default="localhost", help="Remote host name (domain name or IP address") parser.add_option("", "--port", type="int", default=65500, help="port number to connect to") parser.add_option("", "--packet-size", type="int", default=1471, help="packet size.") parser.add_option("", "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 # Create an instance of a hierarchical block top_block = vector_source(options.host, options.port, options.packet_size, not options.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass gnuradio-3.7.2.1/gnuradio-runtime/examples/network/audio_sink.py0000775000175000017500000000511512207440367024635 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: from gnuradio import audio except ImportError: sys.stderr.write("Failed to import gnuradio.audio. Make sure gr-audio component is installed.\n") sys.exit(1) class audio_sink(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "audio_sink") src = blocks.udp_source(gr.sizeof_float, host, port, pkt_size, eof=eof) dst = audio.sink(sample_rate) self.connect(src, dst) if __name__ == '__main__': parser = OptionParser(option_class=eng_option) parser.add_option("", "--host", type="string", default="0.0.0.0", help="local host name (domain name or IP address)") parser.add_option("", "--port", type="int", default=65500, help="port value to listen to for connection") parser.add_option("", "--packet-size", type="int", default=1472, help="packet size.") parser.add_option("-r", "--sample-rate", type="int", default=32000, help="audio signal sample rate [default=%default]") parser.add_option("", "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 # Create an instance of a hierarchical block top_block = audio_sink(options.host, options.port, options.packet_size, options.sample_rate, not options.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass gnuradio-3.7.2.1/gnuradio-runtime/examples/network/audio_source.py0000775000175000017500000000514012207440367025167 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: from gnuradio import audio except ImportError: sys.stderr.write("Failed to import gnuradio.audio. Make sure gr-audio component is installed.\n") sys.exit(1) class audio_source(gr.top_block): def __init__(self, host, port, pkt_size, sample_rate, eof): gr.top_block.__init__(self, "audio_source") self.audio = audio.source(sample_rate) self.sink = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof) self.connect(self.audio, self.sink) if __name__ == '__main__': parser = OptionParser(option_class=eng_option) parser.add_option("", "--host", type="string", default="localhost", help="Remote host name (domain name or IP address") parser.add_option("", "--port", type="int", default=65500, help="port number to connect to") parser.add_option("", "--packet-size", type="int", default=1472, help="packet size.") parser.add_option("-r", "--sample-rate", type="int", default=32000 , help="audio signal sample rate [default=%default]") parser.add_option("", "--no-eof", action="store_true", default=False, help="don't send EOF on disconnect") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 # Create an instance of a hierarchical block top_block = audio_source(options.host, options.port, options.packet_size, options.sample_rate, not options.no_eof) try: # Run forever top_block.run() except KeyboardInterrupt: # Ctrl-C exits pass gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/0000775000175000017500000000000012207440367022140 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/CMakeLists.txt0000664000175000017500000000213012207440367024674 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS affinity_set.py plot_flops.py run_synthetic.py synthetic.py wfm_rcv_pll_to_wav.py DESTINATION ${GR_PKG_DATA_DIR}/examples/mp-sched COMPONENT "runtime_python" ) install( FILES README DESTINATION ${GR_PKG_DATA_DIR}/examples/mp-sched COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/affinity_set.py0000775000175000017500000000461612207440367025210 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Affinity Set Test ################################################## from gnuradio import eng_notation from gnuradio import gr from gnuradio import blocks from gnuradio import filter from gnuradio.eng_option import eng_option from gnuradio.filter import firdes from optparse import OptionParser import sys class affinity_set(gr.top_block): def __init__(self): gr.top_block.__init__(self, "Affinity Set Test") ################################################## # Variables ################################################## self.samp_rate = samp_rate = 32000 ################################################## # Blocks ################################################## vec_len = 1 self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex*vec_len, samp_rate) self.blocks_null_source_0 = blocks.null_source(gr.sizeof_gr_complex*vec_len) self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_gr_complex*vec_len) self.filter_filt_0 = filter.fir_filter_ccc(1, 40000*[0.2+0.3j,]) self.filter_filt_1 = filter.fir_filter_ccc(1, 40000*[0.2+0.3j,]) self.filter_filt_0.set_processor_affinity([0,]) self.filter_filt_1.set_processor_affinity([0,1]) ################################################## # Connections ################################################## self.connect((self.blocks_null_source_0, 0), (self.blocks_throttle_0, 0)) self.connect((self.blocks_throttle_0, 0), (self.filter_filt_0, 0)) self.connect((self.filter_filt_0, 0), (self.filter_filt_1, 0)) self.connect((self.filter_filt_1, 0), (self.blocks_null_sink_0, 0)) def get_samp_rate(self): return self.samp_rate def set_samp_rate(self, samp_rate): self.samp_rate = samp_rate if __name__ == '__main__': parser = OptionParser(option_class=eng_option, usage="%prog: [options]") (options, args) = parser.parse_args() tb = affinity_set() tb.start() while(1): ret = raw_input('Enter a new Core # or Press Enter to quit: ') if(len(ret) == 0): tb.stop() sys.exit(0) elif(ret.lower() == "none"): tb.filter_filt_0.unset_processor_affinity() else: try: n = int(ret) except ValueError: print "Invalid number" else: tb.filter_filt_0.set_processor_affinity([n,]) gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/run_synthetic.py0000775000175000017500000000762512207440367025425 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Run synthetic.py for npipes in [1,16], nstages in [1,16] """ import re import sys import os import tempfile from optparse import OptionParser def write_shell_script(f, data_filename, description, ncores, gflops, max_pipes_and_stages): """ f is the file to write the script to data_filename is the where the data ends up description describes the machine ncores is the number of cores (used to size the workload) gflops is the estimated GFLOPS per core (used to size the workload) """ f.write("#!/bin/sh\n") f.write("(\n") if description: f.write("echo '#D %s'\n" % (description,)) for npipes in range(1, max_pipes_and_stages + 1): for nstages in range(1, max_pipes_and_stages + 1): # We'd like each run of synthetic to take ~10 seconds desired_time_per_run = 10 est_gflops_avail = min(nstages * npipes, ncores) * gflops nsamples = (est_gflops_avail * desired_time_per_run)/(512.0 * nstages * npipes) nsamples = int(nsamples * 1e9) cmd = "./synthetic.py -m -s %d -p %d -N %d\n" % (nstages, npipes, nsamples) f.write(cmd) f.write('if test $? -ge 128; then exit 128; fi\n') f.write(") 2>&1 | grep --line-buffered -v '^>>>' | tee %s\n" % (data_filename,)) f.flush() def main(): description = """%prog gathers multiprocessor scaling data using the ./synthetic.py benchmark. All combinations of npipes and nstages between 1 and --max-pipes-and-stages are tried. The -n and -f options provides hints used to size the workload. We'd like each run of synthetic to take about 10 seconds. For the full 16x16 case this results in a total runtime of about 43 minutes, assuming that your values for -n and -f are reasonable. For x86 machines, assume 3 FLOPS per processor Hz. E.g., 3 GHz machine -> 9 GFLOPS. plot_flops.py will make pretty graphs from the output data generated by %prog. """ usage = "usage: %prog [options] output.dat" parser = OptionParser(usage=usage, description=description) parser.add_option("-d", "--description", metavar="DESC", help="machine description, e.g., \"Dual quad-core Xeon 3 GHz\"", default=None) parser.add_option("-n", "--ncores", type="int", default=1, help="number of processor cores [default=%default]") parser.add_option("-g", "--gflops", metavar="GFLOPS", type="float", default=3.0, help="estimated GFLOPS per core [default=%default]") parser.add_option("-m", "--max-pipes-and-stages", metavar="MAX", type="int", default=16, help="maximum number of pipes and stages to use [default=%default]") (options, args) = parser.parse_args() if len(args) != 1: parser.print_help() raise SystemExit, 1 output_filename = args[0] shell = os.popen("/bin/sh", "w") write_shell_script(shell, output_filename, options.description, options.ncores, options.gflops, options.max_pipes_and_stages) if __name__ == '__main__': main() gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/README0000664000175000017500000000012312207440367023014 0ustar jcorganjcorganThese are pieces of code used to test and benchmark the multi-processor scheduler. gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py0000775000175000017500000001073212207440367026411 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, eng_notation, optfir from gnuradio import audio from gnuradio import analog from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import sys import math class wfm_rx_block (gr.top_block): def __init__(self): gr.top_block.__init__(self) usage = "usage: %prog [options] input-samples-320kS.dat output.wav" parser=OptionParser(option_class=eng_option, usage=usage) parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") (options, args) = parser.parse_args() if len(args) != 2: parser.print_help() sys.exit(1) input_filename = args[0] output_filename = args[1] self.vol = 0 # build graph self.src = blocks.file_source(gr.sizeof_gr_complex, input_filename, False) adc_rate = 64e6 # 64 MS/s usrp_decim = 200 usrp_rate = adc_rate / usrp_decim # 320 kS/s chanfilt_decim = 1 demod_rate = usrp_rate / chanfilt_decim audio_decimation = 10 audio_rate = demod_rate / audio_decimation # 32 kHz chan_filt_coeffs = optfir.low_pass (1, # gain usrp_rate, # sampling rate 80e3, # passband cutoff 115e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation #print len(chan_filt_coeffs) chan_filt = filter.fir_filter_ccf (chanfilt_decim, chan_filt_coeffs) #self.guts = analog.wfm_rcv (demod_rate, audio_decimation) self.guts = analog.wfm_rcv_pll (demod_rate, audio_decimation) # FIXME rework {add,multiply}_const_* to handle multiple streams self.volume_control_l = blocks.multiply_const_ff(self.vol) self.volume_control_r = blocks.multiply_const_ff(self.vol) # wave file as final sink if 1: sink = blocks.wavfile_sink(output_filename, 2, int(audio_rate), 16) else: sink = audio.sink (int (audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect (self.src, chan_filt, self.guts) self.connect ((self.guts, 0), self.volume_control_l, (sink, 0)) self.connect ((self.guts, 1), self.volume_control_r, (sink, 1)) try: self.guts.stereo_carrier_pll_recovery.squelch_enable(True) except: pass #print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 # set initial values self.set_vol(options.volume) try: self.guts.stereo_carrier_pll_recovery.set_lock_threshold(options.squelch) except: pass #print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control_l.set_k(10**(self.vol/10)) self.volume_control_r.set_k(10**(self.vol/10)) def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': tb = wfm_rx_block() try: tb.run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/synthetic.py0000775000175000017500000001070012207440367024525 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from gnuradio import gr, eng_notation from gnuradio import blocks, filter from gnuradio.eng_option import eng_option from optparse import OptionParser import os class pipeline(gr.hier_block2): def __init__(self, nstages, ntaps=256): """ Create a pipeline of nstages of filter.fir_filter_fff's connected in serial terminating in a blocks.null_sink. """ gr.hier_block2.__init__(self, "pipeline", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(0, 0, 0)) taps = ntaps*[1.0/ntaps] upstream = self for i in range(nstages): op = filter.fir_filter_fff(1, taps) self.connect(upstream, op) upstream = op self.connect(upstream, blocks.null_sink(gr.sizeof_float)) class top(gr.top_block): def __init__(self): gr.top_block.__init__(self) default_nsamples = 10e6 parser=OptionParser(option_class=eng_option) parser.add_option("-p", "--npipelines", type="intx", default=1, metavar="NPIPES", help="the number of pipelines to create (default=%default)") parser.add_option("-s", "--nstages", type="intx", default=1, metavar="NSTAGES", help="the number of stages in each pipeline (default=%default)") parser.add_option("-N", "--nsamples", type="eng_float", default=default_nsamples, help=("the number of samples to run through the graph (default=%s)" % (eng_notation.num_to_str(default_nsamples)))) parser.add_option("-m", "--machine-readable", action="store_true", default=False, help="enable machine readable output") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 self.npipes = options.npipelines self.nstages = options.nstages self.nsamples = options.nsamples self.machine_readable = options.machine_readable ntaps = 256 # Something vaguely like floating point ops self.flop = 2 * ntaps * options.npipelines * options.nstages * options.nsamples src = blocks.null_source(gr.sizeof_float) head = blocks.head(gr.sizeof_float, int(options.nsamples)) self.connect(src, head) for n in range(options.npipelines): self.connect(head, pipeline(options.nstages, ntaps)) def time_it(tb): start = os.times() tb.run() stop = os.times() delta = map((lambda a, b: a-b), stop, start) user, sys, childrens_user, childrens_sys, real = delta total_user = user + childrens_user total_sys = sys + childrens_sys if tb.machine_readable: print "%3d %3d %.3e %7.3f %7.3f %7.3f %7.3f %.6e %.3e" % ( tb.npipes, tb.nstages, tb.nsamples, real, total_user, total_sys, (total_user+total_sys)/real, tb.flop, tb.flop/real) else: print "npipes %7d" % (tb.npipes,) print "nstages %7d" % (tb.nstages,) print "nsamples %s" % (eng_notation.num_to_str(tb.nsamples),) print "real %7.3f" % (real,) print "user %7.3f" % (total_user,) print "sys %7.3f" % (total_sys,) print "(user+sys)/real %7.3f" % ((total_user + total_sys)/real,) print "pseudo_flop %s" % (eng_notation.num_to_str(tb.flop),) print "pseudo_flop/real %s" % (eng_notation.num_to_str(tb.flop/real),) if __name__ == "__main__": try: tb = top() time_it(tb) except KeyboardInterrupt: raise SystemExit, 128 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/plot_flops.py0000775000175000017500000000554612207440367024710 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Reads output from run_synthetic.py and runs gnuplot showing GFLOPS as f(npipes, nstages) """ import re import sys import os import tempfile from optparse import OptionParser def parse_file(input_filename, output): last = None desc = '' for line in open(input_filename, 'r'): s = line.strip() if s.startswith('>>>'): # ignore ">>> using SSE cruft" continue if s.startswith('#D'): # machine description desc = s[2:].strip() continue fields = s.split() npipes, nstages, flops = fields[0], fields[1], fields[8] if last is not None and npipes != last: output.write('\n') last = npipes output.write(' '.join((npipes, nstages, flops))) output.write('\n') output.flush() return desc def handle_file(input_filename): cmd_file = tempfile.NamedTemporaryFile(mode='w+', prefix='pf', suffix='.cmd') cmd_file_name = cmd_file.name data_file = tempfile.NamedTemporaryFile(mode='w+', prefix='pf', suffix='.dat') data_file_name = data_file.name desc = parse_file(input_filename, data_file) if len(desc) > 0: cmd_file.write("set title '%s'\n" % (desc,)) cmd_file.write("set xlabel 'N pipes'\n") cmd_file.write("set ylabel 'N stages'\n") cmd_file.write("set zlabel 'GFLOPS'\n") cmd_file.write("set key off\n") cmd_file.write("set view 60, 312\n") cmd_file.write("set pm3d\n") cmd_file.write("splot '%s' using 1:2:($3*1e-9) with pm3d at b, '%s' using 1:2:($3*1e-9) with pm3d\n" % ( data_file_name, data_file_name)) cmd_file.flush() data_file.flush() os.system("gnuplot " + cmd_file_name + " -") #sys.stdout.write(open(cmd_file_name,'r').read()) #sys.stdout.write(open(data_file_name,'r').read()) def main(): usage = "usage: %prog [options] file.dat" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: parser.print_help() raise SystemExit, 1 handle_file(args[0]) if __name__ == '__main__': main() gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/0000775000175000017500000000000012207440367024003 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/js21-altivec.dat0000664000175000017500000001115712207440367026706 0ustar jcorganjcorgan#D JS21 4-core PPC970M 2.5 GHz (using Altivec) 1 1 9.766e+07 9.820 10.210 0.360 1.076 5.000000e+10 5.092e+09 1 2 9.766e+07 10.620 19.890 0.640 1.933 1.000000e+11 9.416e+09 1 3 9.766e+07 10.310 29.590 0.610 2.929 1.500000e+11 1.455e+10 1 4 9.766e+07 10.440 39.290 0.680 3.829 2.000000e+11 1.916e+10 1 5 7.812e+07 15.730 39.150 0.590 2.526 2.000000e+11 1.271e+10 1 6 6.510e+07 13.100 39.080 0.590 3.028 2.000000e+11 1.527e+10 1 7 5.580e+07 11.550 39.030 0.500 3.423 2.000000e+11 1.732e+10 1 8 4.883e+07 10.410 39.010 0.510 3.796 2.000000e+11 1.921e+10 2 1 9.766e+07 10.080 20.070 0.700 2.061 1.000000e+11 9.921e+09 2 2 9.766e+07 11.360 39.650 0.960 3.575 2.000000e+11 1.761e+10 2 3 6.510e+07 13.120 39.270 0.740 3.050 2.000000e+11 1.524e+10 2 4 4.883e+07 10.410 39.110 0.650 3.819 2.000000e+11 1.921e+10 2 5 3.906e+07 11.030 39.080 0.610 3.598 2.000000e+11 1.813e+10 2 6 3.255e+07 10.640 39.020 0.560 3.720 2.000000e+11 1.880e+10 2 7 2.790e+07 10.510 38.980 0.550 3.761 2.000000e+11 1.903e+10 2 8 2.441e+07 10.440 38.970 0.570 3.787 2.000000e+11 1.916e+10 3 1 9.766e+07 12.130 29.970 0.920 2.547 1.500000e+11 1.237e+10 3 2 6.510e+07 13.100 39.300 0.920 3.070 2.000000e+11 1.527e+10 3 3 4.340e+07 11.400 39.200 0.760 3.505 2.000000e+11 1.754e+10 3 4 3.255e+07 10.730 39.100 0.690 3.708 2.000000e+11 1.864e+10 3 5 2.604e+07 10.470 39.010 0.620 3.785 2.000000e+11 1.910e+10 3 6 2.170e+07 10.380 39.010 0.620 3.818 2.000000e+11 1.927e+10 3 7 1.860e+07 10.280 39.120 0.580 3.862 2.000000e+11 1.946e+10 3 8 1.628e+07 10.230 39.000 0.600 3.871 2.000000e+11 1.955e+10 4 1 9.766e+07 10.700 39.990 1.540 3.881 2.000000e+11 1.869e+10 4 2 4.883e+07 10.530 39.260 0.940 3.818 2.000000e+11 1.899e+10 4 3 3.255e+07 10.840 39.140 0.760 3.681 2.000000e+11 1.845e+10 4 4 2.441e+07 10.530 39.040 0.680 3.772 2.000000e+11 1.899e+10 4 5 1.953e+07 10.380 39.030 0.650 3.823 2.000000e+11 1.927e+10 4 6 1.628e+07 10.310 39.020 0.650 3.848 2.000000e+11 1.940e+10 4 7 1.395e+07 10.160 38.980 0.620 3.898 2.000000e+11 1.969e+10 4 8 1.221e+07 10.150 38.990 0.580 3.899 2.000000e+11 1.970e+10 5 1 7.812e+07 14.750 39.780 1.470 2.797 2.000000e+11 1.356e+10 5 2 3.906e+07 11.350 39.240 0.950 3.541 2.000000e+11 1.762e+10 5 3 2.604e+07 10.720 39.120 0.800 3.724 2.000000e+11 1.866e+10 5 4 1.953e+07 10.440 39.060 0.730 3.811 2.000000e+11 1.916e+10 5 5 1.562e+07 10.410 39.060 0.690 3.818 2.000000e+11 1.921e+10 5 6 1.302e+07 10.260 38.970 0.650 3.862 2.000000e+11 1.949e+10 5 7 1.116e+07 10.270 39.020 0.650 3.863 2.000000e+11 1.947e+10 5 8 9.766e+06 10.130 39.010 0.660 3.916 2.000000e+11 1.974e+10 6 1 6.510e+07 12.850 39.730 1.450 3.205 2.000000e+11 1.556e+10 6 2 3.255e+07 10.700 39.300 0.990 3.765 2.000000e+11 1.869e+10 6 3 2.170e+07 10.770 39.110 0.810 3.707 2.000000e+11 1.857e+10 6 4 1.628e+07 10.570 39.090 0.750 3.769 2.000000e+11 1.892e+10 6 5 1.302e+07 10.310 39.040 0.690 3.854 2.000000e+11 1.940e+10 6 6 1.085e+07 10.260 39.030 0.700 3.872 2.000000e+11 1.949e+10 6 7 9.301e+06 10.170 39.020 0.680 3.904 2.000000e+11 1.967e+10 6 8 8.138e+06 10.150 39.020 0.670 3.910 2.000000e+11 1.970e+10 7 1 5.580e+07 11.440 39.730 1.500 3.604 2.000000e+11 1.748e+10 7 2 2.790e+07 10.950 39.260 0.990 3.676 2.000000e+11 1.826e+10 7 3 1.860e+07 10.620 39.140 0.860 3.766 2.000000e+11 1.883e+10 7 4 1.395e+07 10.420 39.070 0.750 3.821 2.000000e+11 1.919e+10 7 5 1.116e+07 10.290 39.040 0.710 3.863 2.000000e+11 1.944e+10 7 6 9.301e+06 10.200 39.040 0.720 3.898 2.000000e+11 1.961e+10 7 7 7.972e+06 10.210 39.020 0.670 3.887 2.000000e+11 1.959e+10 7 8 6.975e+06 10.160 39.020 0.650 3.905 2.000000e+11 1.969e+10 8 1 4.883e+07 10.870 39.950 1.520 3.815 2.000000e+11 1.840e+10 8 2 2.441e+07 10.690 39.270 1.000 3.767 2.000000e+11 1.871e+10 8 3 1.628e+07 10.540 39.130 0.860 3.794 2.000000e+11 1.898e+10 8 4 1.221e+07 10.410 39.110 0.790 3.833 2.000000e+11 1.921e+10 8 5 9.766e+06 10.230 39.040 0.710 3.886 2.000000e+11 1.955e+10 8 6 8.138e+06 10.260 39.050 0.700 3.874 2.000000e+11 1.949e+10 8 7 6.975e+06 10.220 39.100 0.690 3.893 2.000000e+11 1.957e+10 8 8 6.104e+06 10.170 39.020 0.650 3.901 2.000000e+11 1.967e+10 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/ps3-altivec.dat0000664000175000017500000001114112207440367026625 0ustar jcorganjcorgan#D Playstation 3 (using Altivec) 1 1 3.906e+07 10.500 10.580 0.440 1.050 2.000000e+10 1.905e+09 1 2 1.953e+07 7.010 13.200 0.400 1.940 2.000000e+10 2.853e+09 1 3 1.302e+07 7.540 13.140 0.380 1.793 2.000000e+10 2.653e+09 1 4 9.766e+06 7.200 13.620 0.370 1.943 2.000000e+10 2.778e+09 1 5 7.812e+06 7.170 13.670 0.340 1.954 2.000000e+10 2.789e+09 1 6 6.510e+06 7.010 13.590 0.320 1.984 2.000000e+10 2.853e+09 1 7 5.580e+06 6.990 13.530 0.330 1.983 2.000000e+10 2.861e+09 1 8 4.883e+06 6.980 13.490 0.320 1.979 2.000000e+10 2.865e+09 2 1 1.953e+07 8.110 14.730 0.530 1.882 2.000000e+10 2.466e+09 2 2 9.766e+06 7.090 13.570 0.420 1.973 2.000000e+10 2.821e+09 2 3 6.510e+06 7.040 13.590 0.410 1.989 2.000000e+10 2.841e+09 2 4 4.883e+06 6.990 13.490 0.370 1.983 2.000000e+10 2.861e+09 2 5 3.906e+06 6.970 13.480 0.360 1.986 2.000000e+10 2.869e+09 2 6 3.255e+06 6.990 13.530 0.370 1.989 2.000000e+10 2.861e+09 2 7 2.790e+06 6.890 13.390 0.350 1.994 2.000000e+10 2.903e+09 2 8 2.441e+06 6.880 13.380 0.350 1.996 2.000000e+10 2.907e+09 3 1 1.302e+07 8.220 13.720 0.510 1.731 2.000000e+10 2.433e+09 3 2 6.510e+06 7.050 13.480 0.450 1.976 2.000000e+10 2.837e+09 3 3 4.340e+06 6.990 13.460 0.400 1.983 2.000000e+10 2.861e+09 3 4 3.255e+06 6.990 13.550 0.380 1.993 2.000000e+10 2.861e+09 3 5 2.604e+06 6.920 13.430 0.360 1.993 1.999999e+10 2.890e+09 3 6 2.170e+06 6.940 13.460 0.360 1.991 1.999999e+10 2.882e+09 3 7 1.860e+06 6.920 13.440 0.360 1.994 2.000000e+10 2.890e+09 3 8 1.628e+06 6.890 13.380 0.350 1.993 2.000000e+10 2.903e+09 4 1 9.766e+06 7.620 14.550 0.590 1.987 2.000000e+10 2.625e+09 4 2 4.883e+06 7.010 13.460 0.440 1.983 2.000000e+10 2.853e+09 4 3 3.255e+06 7.040 13.580 0.410 1.987 2.000000e+10 2.841e+09 4 4 2.441e+06 6.960 13.470 0.390 1.991 2.000000e+10 2.874e+09 4 5 1.953e+06 6.920 13.410 0.370 1.991 2.000000e+10 2.890e+09 4 6 1.628e+06 6.950 13.490 0.370 1.994 2.000000e+10 2.878e+09 4 7 1.395e+06 6.890 13.350 0.370 1.991 2.000000e+10 2.903e+09 4 8 1.221e+06 6.940 13.490 0.360 1.996 2.000000e+10 2.882e+09 5 1 7.812e+06 7.680 14.000 0.560 1.896 2.000000e+10 2.604e+09 5 2 3.906e+06 7.070 13.460 0.460 1.969 2.000000e+10 2.829e+09 5 3 2.604e+06 6.990 13.430 0.420 1.981 1.999999e+10 2.861e+09 5 4 1.953e+06 7.010 13.550 0.390 1.989 2.000000e+10 2.853e+09 5 5 1.562e+06 6.920 13.430 0.380 1.996 2.000000e+10 2.890e+09 5 6 1.302e+06 6.920 13.410 0.380 1.993 1.999999e+10 2.890e+09 5 7 1.116e+06 6.920 13.420 0.370 1.993 1.999999e+10 2.890e+09 5 8 9.766e+05 6.910 13.360 0.370 1.987 1.999999e+10 2.894e+09 6 1 6.510e+06 7.350 13.970 0.630 1.986 2.000000e+10 2.721e+09 6 2 3.255e+06 7.040 13.470 0.470 1.980 2.000000e+10 2.841e+09 6 3 2.170e+06 7.050 13.600 0.420 1.989 1.999999e+10 2.837e+09 6 4 1.628e+06 6.970 13.480 0.400 1.991 2.000000e+10 2.869e+09 6 5 1.302e+06 6.990 13.540 0.390 1.993 1.999999e+10 2.861e+09 6 6 1.085e+06 6.970 13.470 0.380 1.987 1.999999e+10 2.869e+09 6 7 9.301e+05 6.890 13.350 0.380 1.993 1.999999e+10 2.903e+09 6 8 8.138e+05 6.920 13.420 0.370 1.993 2.000000e+10 2.890e+09 7 1 5.580e+06 7.530 14.030 0.580 1.940 2.000000e+10 2.656e+09 7 2 2.790e+06 7.000 13.370 0.460 1.976 2.000000e+10 2.857e+09 7 3 1.860e+06 7.000 13.520 0.420 1.991 2.000000e+10 2.857e+09 7 4 1.395e+06 7.060 13.590 0.410 1.983 2.000000e+10 2.833e+09 7 5 1.116e+06 6.950 13.460 0.390 1.993 1.999999e+10 2.878e+09 7 6 9.301e+05 6.950 13.420 0.380 1.986 1.999999e+10 2.878e+09 7 7 7.972e+05 6.880 13.300 0.380 1.988 1.999998e+10 2.907e+09 7 8 6.975e+05 6.920 13.390 0.380 1.990 1.999998e+10 2.890e+09 8 1 4.883e+06 7.440 14.150 0.620 1.985 2.000000e+10 2.688e+09 8 2 2.441e+06 6.990 13.400 0.480 1.986 2.000000e+10 2.861e+09 8 3 1.628e+06 6.990 13.460 0.430 1.987 2.000000e+10 2.861e+09 8 4 1.221e+06 7.020 13.550 0.410 1.989 2.000000e+10 2.849e+09 8 5 9.766e+05 6.920 13.370 0.390 1.988 1.999999e+10 2.890e+09 8 6 8.138e+05 6.950 13.400 0.390 1.984 2.000000e+10 2.878e+09 8 7 6.975e+05 6.930 13.360 0.390 1.984 1.999998e+10 2.886e+09 8 8 6.104e+05 6.920 13.390 0.380 1.990 1.999998e+10 2.890e+09 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/dual-quad-core-3.00-penryn.dat0000664000175000017500000004451212207440367031175 0ustar jcorganjcorgan#D Dual quad-core Xeon 3.0 GHz (Penryn E5472, 1600 MHz FSB, 5400 chipset) 1 1 5.000e+07 2.720 3.020 0.110 1.151 2.560000e+10 9.412e+09 1 2 5.000e+07 2.870 5.630 0.170 2.021 5.120000e+10 1.784e+10 1 3 5.000e+07 2.880 8.380 0.160 2.965 7.680000e+10 2.667e+10 1 4 5.000e+07 2.990 11.080 0.200 3.773 1.024000e+11 3.425e+10 1 5 5.000e+07 2.950 13.950 0.190 4.793 1.280000e+11 4.339e+10 1 6 5.000e+07 3.020 16.620 0.240 5.583 1.536000e+11 5.086e+10 1 7 5.000e+07 2.930 19.250 0.200 6.638 1.792000e+11 6.116e+10 1 8 5.000e+07 3.170 22.240 0.290 7.107 2.048000e+11 6.461e+10 1 9 5.000e+07 5.450 24.410 0.310 4.536 2.304000e+11 4.228e+10 1 10 5.000e+07 5.610 27.400 0.370 4.950 2.560000e+11 4.563e+10 1 11 5.000e+07 5.680 29.960 0.370 5.340 2.816000e+11 4.958e+10 1 12 5.000e+07 5.440 32.490 0.350 6.037 3.072000e+11 5.647e+10 1 13 5.000e+07 5.630 35.270 0.400 6.336 3.328000e+11 5.911e+10 1 14 5.000e+07 6.270 38.500 0.480 6.217 3.584000e+11 5.716e+10 1 15 5.000e+07 6.080 40.880 0.490 6.804 3.840000e+11 6.316e+10 1 16 5.000e+07 7.740 43.390 0.600 5.683 4.096000e+11 5.292e+10 2 1 5.000e+07 2.820 5.700 0.210 2.096 5.120000e+10 1.816e+10 2 2 5.000e+07 2.820 11.130 0.230 4.028 1.024000e+11 3.631e+10 2 3 5.000e+07 2.960 16.570 0.320 5.706 1.536000e+11 5.189e+10 2 4 5.000e+07 3.110 21.920 0.390 7.174 2.048000e+11 6.585e+10 2 5 5.000e+07 5.650 27.550 0.520 4.968 2.560000e+11 4.531e+10 2 6 5.000e+07 5.880 32.890 0.440 5.668 3.072000e+11 5.224e+10 2 7 5.000e+07 6.750 38.210 0.560 5.744 3.584000e+11 5.310e+10 2 8 5.000e+07 6.360 43.480 0.580 6.928 4.096000e+11 6.440e+10 2 9 5.000e+07 8.270 48.750 0.730 5.983 4.608000e+11 5.572e+10 2 10 5.000e+07 8.210 54.400 0.610 6.700 5.120000e+11 6.236e+10 2 11 5.000e+07 8.750 59.760 0.640 6.903 5.632000e+11 6.437e+10 2 12 5.000e+07 9.300 65.050 0.700 7.070 6.144000e+11 6.606e+10 2 13 5.000e+07 9.990 70.750 0.750 7.157 6.656000e+11 6.663e+10 2 14 5.000e+07 10.610 75.950 0.810 7.235 7.168000e+11 6.756e+10 2 15 5.000e+07 11.900 80.400 0.870 6.829 7.680000e+11 6.454e+10 2 16 5.000e+07 11.820 86.790 0.900 7.419 8.192000e+11 6.931e+10 3 1 5.000e+07 2.970 8.300 0.380 2.923 7.680000e+10 2.586e+10 3 2 5.000e+07 2.980 16.660 0.390 5.721 1.536000e+11 5.154e+10 3 3 5.000e+07 5.480 24.690 0.420 4.582 2.304000e+11 4.204e+10 3 4 5.000e+07 5.620 32.820 0.560 5.940 3.072000e+11 5.466e+10 3 5 5.000e+07 6.940 40.800 0.620 5.968 3.840000e+11 5.533e+10 3 6 5.000e+07 7.860 49.010 0.710 6.326 4.608000e+11 5.863e+10 3 7 5.000e+07 8.470 57.130 0.750 6.834 5.376000e+11 6.347e+10 3 8 5.000e+07 9.420 65.310 0.820 7.020 6.144000e+11 6.522e+10 3 9 5.000e+07 10.350 73.640 0.940 7.206 6.912000e+11 6.678e+10 3 10 5.000e+07 11.460 82.230 1.030 7.265 7.680000e+11 6.702e+10 3 11 5.000e+07 12.200 89.590 1.050 7.430 8.448000e+11 6.925e+10 3 12 5.000e+07 13.040 97.520 1.140 7.566 9.216000e+11 7.067e+10 3 13 5.000e+07 14.000 105.560 1.150 7.622 9.984000e+11 7.131e+10 3 14 5.000e+07 14.930 113.630 1.210 7.692 1.075200e+12 7.202e+10 3 15 5.000e+07 15.920 121.610 1.350 7.724 1.152000e+12 7.236e+10 3 16 5.000e+07 16.870 129.770 1.390 7.775 1.228800e+12 7.284e+10 4 1 5.000e+07 2.900 11.100 0.340 3.945 1.024000e+11 3.531e+10 4 2 5.000e+07 4.380 21.980 0.480 5.128 2.048000e+11 4.676e+10 4 3 5.000e+07 5.720 32.800 0.610 5.841 3.072000e+11 5.371e+10 4 4 5.000e+07 6.820 43.880 0.700 6.537 4.096000e+11 6.006e+10 4 5 5.000e+07 8.150 54.420 0.760 6.771 5.120000e+11 6.282e+10 4 6 5.000e+07 9.510 65.180 0.980 6.957 6.144000e+11 6.461e+10 4 7 5.000e+07 10.650 76.080 1.020 7.239 7.168000e+11 6.731e+10 4 8 5.000e+07 11.880 86.720 1.110 7.393 8.192000e+11 6.896e+10 4 9 5.000e+07 13.150 97.920 1.250 7.541 9.216000e+11 7.008e+10 4 10 5.000e+07 14.640 109.260 1.410 7.559 1.024000e+12 6.995e+10 4 11 5.000e+07 15.710 119.170 1.440 7.677 1.126400e+12 7.170e+10 4 12 5.000e+07 16.950 129.960 1.420 7.751 1.228800e+12 7.250e+10 4 13 5.000e+07 18.260 140.520 1.620 7.784 1.331200e+12 7.290e+10 4 14 5.000e+07 19.610 151.290 1.780 7.806 1.433600e+12 7.311e+10 4 15 5.000e+07 21.060 162.760 1.890 7.818 1.536000e+12 7.293e+10 4 16 5.000e+07 22.280 172.870 1.980 7.848 1.638400e+12 7.354e+10 5 1 5.000e+07 3.040 13.810 0.390 4.671 1.280000e+11 4.211e+10 5 2 5.000e+07 5.590 27.510 0.610 5.030 2.560000e+11 4.580e+10 5 3 5.000e+07 6.550 40.970 0.780 6.374 3.840000e+11 5.863e+10 5 4 5.000e+07 8.520 54.470 0.940 6.504 5.120000e+11 6.009e+10 5 5 5.000e+07 9.920 67.950 1.060 6.957 6.400000e+11 6.452e+10 5 6 5.000e+07 11.350 81.490 1.180 7.284 7.680000e+11 6.767e+10 5 7 5.000e+07 12.910 94.960 1.300 7.456 8.960000e+11 6.940e+10 5 8 5.000e+07 14.520 108.510 1.400 7.570 1.024000e+12 7.052e+10 5 9 5.000e+07 16.070 122.120 1.620 7.700 1.152000e+12 7.169e+10 5 10 5.000e+07 17.950 136.140 1.730 7.681 1.280000e+12 7.131e+10 5 11 5.000e+07 19.470 148.330 1.830 7.712 1.408000e+12 7.232e+10 5 12 5.000e+07 20.980 162.100 2.030 7.823 1.536000e+12 7.321e+10 5 13 5.000e+07 22.670 175.470 2.160 7.835 1.664000e+12 7.340e+10 5 14 5.000e+07 24.440 189.630 2.170 7.848 1.792000e+12 7.332e+10 5 15 5.000e+07 26.100 203.010 2.450 7.872 1.920000e+12 7.356e+10 5 16 5.000e+07 27.720 216.000 2.550 7.884 2.048000e+12 7.388e+10 6 1 5.000e+07 2.950 16.560 0.540 5.797 1.536000e+11 5.207e+10 6 2 5.000e+07 5.540 32.900 0.720 6.069 3.072000e+11 5.545e+10 6 3 5.000e+07 8.490 48.860 1.000 5.873 4.608000e+11 5.428e+10 6 4 5.000e+07 10.000 64.670 1.100 6.577 6.144000e+11 6.144e+10 6 5 5.000e+07 11.440 81.430 1.310 7.233 7.680000e+11 6.713e+10 6 6 5.000e+07 13.250 97.690 1.360 7.475 9.216000e+11 6.955e+10 6 7 5.000e+07 15.270 113.730 1.610 7.553 1.075200e+12 7.041e+10 6 8 5.000e+07 17.180 129.780 1.820 7.660 1.228800e+12 7.153e+10 6 9 5.000e+07 19.200 146.020 1.870 7.703 1.382400e+12 7.200e+10 6 10 5.000e+07 21.220 162.290 2.100 7.747 1.536000e+12 7.238e+10 6 11 5.000e+07 23.070 178.420 2.160 7.827 1.689600e+12 7.324e+10 6 12 5.000e+07 25.120 194.590 2.450 7.844 1.843200e+12 7.338e+10 6 13 5.000e+07 27.110 210.640 2.660 7.868 1.996800e+12 7.366e+10 6 14 5.000e+07 29.110 226.820 2.750 7.886 2.150400e+12 7.387e+10 6 15 5.000e+07 31.130 242.800 2.940 7.894 2.304000e+12 7.401e+10 6 16 5.000e+07 33.100 258.790 3.210 7.915 2.457600e+12 7.425e+10 7 1 5.000e+07 2.940 19.140 0.590 6.711 1.792000e+11 6.095e+10 7 2 5.000e+07 5.920 37.910 1.030 6.578 3.584000e+11 6.054e+10 7 3 5.000e+07 8.570 57.010 1.150 6.786 5.376000e+11 6.273e+10 7 4 5.000e+07 10.840 76.060 1.320 7.138 7.168000e+11 6.613e+10 7 5 5.000e+07 13.070 94.920 1.540 7.380 8.960000e+11 6.855e+10 7 6 5.000e+07 15.270 113.790 1.730 7.565 1.075200e+12 7.041e+10 7 7 5.000e+07 17.700 132.560 1.960 7.600 1.254400e+12 7.087e+10 7 8 5.000e+07 19.930 151.500 2.130 7.708 1.433600e+12 7.193e+10 7 9 5.000e+07 22.250 170.570 2.340 7.771 1.612800e+12 7.249e+10 7 10 5.000e+07 24.600 189.280 2.450 7.794 1.792000e+12 7.285e+10 7 11 5.000e+07 26.950 208.030 2.700 7.819 1.971200e+12 7.314e+10 7 12 5.000e+07 29.280 227.070 2.850 7.852 2.150400e+12 7.344e+10 7 13 5.000e+07 31.570 245.750 3.040 7.881 2.329600e+12 7.379e+10 7 14 5.000e+07 33.930 264.960 3.160 7.902 2.508800e+12 7.394e+10 7 15 5.000e+07 36.310 283.960 3.440 7.915 2.688000e+12 7.403e+10 7 16 5.000e+07 38.560 302.120 3.630 7.929 2.867200e+12 7.436e+10 8 1 5.000e+07 3.200 21.880 0.860 7.106 2.048000e+11 6.400e+10 8 2 5.000e+07 5.890 43.450 0.930 7.535 4.096000e+11 6.954e+10 8 3 5.000e+07 9.520 65.180 1.250 6.978 6.144000e+11 6.454e+10 8 4 5.000e+07 12.200 86.780 1.480 7.234 8.192000e+11 6.715e+10 8 5 5.000e+07 14.760 108.420 1.670 7.459 1.024000e+12 6.938e+10 8 6 5.000e+07 17.300 129.850 1.960 7.619 1.228800e+12 7.103e+10 8 7 5.000e+07 20.020 151.430 2.190 7.673 1.433600e+12 7.161e+10 8 8 5.000e+07 22.750 173.550 2.420 7.735 1.638400e+12 7.202e+10 8 9 5.000e+07 25.410 194.560 2.760 7.765 1.843200e+12 7.254e+10 8 10 5.000e+07 28.410 217.250 2.920 7.750 2.048000e+12 7.209e+10 8 11 5.000e+07 30.720 237.990 3.210 7.852 2.252800e+12 7.333e+10 8 12 5.000e+07 33.310 259.340 3.280 7.884 2.457600e+12 7.378e+10 8 13 5.000e+07 36.000 280.760 3.670 7.901 2.662400e+12 7.396e+10 8 14 5.000e+07 38.800 302.570 3.740 7.895 2.867200e+12 7.390e+10 8 15 5.000e+07 41.530 324.520 4.060 7.912 3.072000e+12 7.397e+10 8 16 5.000e+07 44.060 345.420 4.250 7.936 3.276800e+12 7.437e+10 9 1 5.000e+07 5.460 24.660 1.000 4.700 2.304000e+11 4.220e+10 9 2 5.000e+07 8.460 49.010 1.200 5.935 4.608000e+11 5.447e+10 9 3 5.000e+07 10.810 71.410 1.400 6.735 6.912000e+11 6.394e+10 9 4 5.000e+07 13.470 97.570 1.710 7.370 9.216000e+11 6.842e+10 9 5 5.000e+07 16.490 121.780 2.130 7.514 1.152000e+12 6.986e+10 9 6 5.000e+07 19.540 146.070 2.280 7.592 1.382400e+12 7.075e+10 9 7 5.000e+07 22.660 170.830 2.570 7.652 1.612800e+12 7.117e+10 9 8 5.000e+07 25.520 194.720 2.760 7.738 1.843200e+12 7.223e+10 9 9 5.000e+07 28.400 219.020 3.060 7.820 2.073600e+12 7.301e+10 9 10 5.000e+07 31.490 243.030 3.320 7.823 2.304000e+12 7.317e+10 9 11 5.000e+07 34.530 267.230 3.420 7.838 2.534400e+12 7.340e+10 9 12 5.000e+07 37.520 291.720 3.860 7.878 2.764800e+12 7.369e+10 9 13 5.000e+07 40.550 315.780 4.170 7.890 2.995200e+12 7.386e+10 9 14 5.000e+07 43.470 339.930 4.290 7.919 3.225600e+12 7.420e+10 9 15 5.000e+07 46.820 364.970 4.640 7.894 3.456000e+12 7.381e+10 9 16 5.000e+07 49.660 388.630 4.890 7.924 3.686400e+12 7.423e+10 10 1 5.000e+07 5.500 27.290 0.980 5.140 2.560000e+11 4.655e+10 10 2 5.000e+07 8.480 54.830 1.420 6.633 5.120000e+11 6.038e+10 10 3 5.000e+07 11.540 81.580 1.630 7.211 7.680000e+11 6.655e+10 10 4 5.000e+07 14.950 108.480 1.860 7.381 1.024000e+12 6.849e+10 10 5 5.000e+07 18.330 135.300 2.280 7.506 1.280000e+12 6.983e+10 10 6 5.000e+07 21.680 162.380 2.540 7.607 1.536000e+12 7.085e+10 10 7 5.000e+07 24.950 189.360 2.730 7.699 1.792000e+12 7.182e+10 10 8 5.000e+07 28.280 216.090 3.110 7.751 2.048000e+12 7.242e+10 10 9 5.000e+07 31.730 243.290 3.450 7.776 2.304000e+12 7.261e+10 10 10 5.000e+07 35.040 270.380 3.680 7.821 2.560000e+12 7.306e+10 10 11 5.000e+07 38.340 297.080 4.050 7.854 2.816000e+12 7.345e+10 10 12 5.000e+07 41.770 323.840 4.330 7.857 3.072000e+12 7.355e+10 10 13 5.000e+07 45.120 351.380 4.710 7.892 3.328000e+12 7.376e+10 10 14 5.000e+07 48.360 377.870 4.880 7.915 3.584000e+12 7.411e+10 10 15 5.000e+07 51.760 404.740 5.110 7.918 3.840000e+12 7.419e+10 10 16 5.000e+07 55.130 431.760 5.430 7.930 4.096000e+12 7.430e+10 11 1 5.000e+07 5.570 30.080 1.080 5.594 2.816000e+11 5.056e+10 11 2 5.000e+07 9.000 60.230 1.470 6.856 5.632000e+11 6.258e+10 11 3 5.000e+07 12.630 89.890 1.770 7.257 8.448000e+11 6.689e+10 11 4 5.000e+07 16.290 119.110 2.140 7.443 1.126400e+12 6.915e+10 11 5 5.000e+07 19.940 148.730 2.440 7.581 1.408000e+12 7.061e+10 11 6 5.000e+07 23.800 178.620 2.790 7.622 1.689600e+12 7.099e+10 11 7 5.000e+07 27.480 208.510 3.160 7.703 1.971200e+12 7.173e+10 11 8 5.000e+07 31.140 237.820 3.490 7.749 2.252800e+12 7.234e+10 11 9 5.000e+07 34.770 267.390 3.800 7.800 2.534400e+12 7.289e+10 11 10 5.000e+07 38.510 297.250 4.240 7.829 2.816000e+12 7.312e+10 11 11 5.000e+07 42.080 326.570 4.610 7.870 3.097600e+12 7.361e+10 11 12 5.000e+07 45.860 356.540 4.590 7.875 3.379200e+12 7.369e+10 11 13 5.000e+07 49.570 386.250 5.150 7.896 3.660800e+12 7.385e+10 11 14 5.000e+07 53.220 415.630 5.360 7.910 3.942400e+12 7.408e+10 11 15 5.000e+07 57.000 445.200 5.870 7.914 4.224000e+12 7.411e+10 11 16 5.000e+07 60.800 474.810 6.250 7.912 4.505600e+12 7.411e+10 12 1 5.000e+07 5.600 32.770 1.240 6.073 3.072000e+11 5.486e+10 12 2 5.000e+07 10.220 65.660 1.600 6.581 6.144000e+11 6.012e+10 12 3 5.000e+07 13.680 97.900 2.000 7.303 9.216000e+11 6.737e+10 12 4 5.000e+07 17.790 129.710 2.330 7.422 1.228800e+12 6.907e+10 12 5 5.000e+07 21.770 162.420 2.700 7.585 1.536000e+12 7.056e+10 12 6 5.000e+07 25.770 194.770 3.090 7.678 1.843200e+12 7.153e+10 12 7 5.000e+07 29.940 227.290 3.390 7.705 2.150400e+12 7.182e+10 12 8 5.000e+07 34.030 259.370 3.860 7.735 2.457600e+12 7.222e+10 12 9 5.000e+07 38.070 291.890 4.310 7.780 2.764800e+12 7.262e+10 12 10 5.000e+07 42.080 324.370 4.660 7.819 3.072000e+12 7.300e+10 12 11 5.000e+07 45.950 356.370 5.000 7.864 3.379200e+12 7.354e+10 12 12 5.000e+07 49.960 388.790 5.250 7.887 3.686400e+12 7.379e+10 12 13 5.000e+07 54.010 422.050 5.420 7.915 3.993600e+12 7.394e+10 12 14 5.000e+07 58.010 453.330 6.120 7.920 4.300800e+12 7.414e+10 12 15 5.000e+07 62.080 485.830 6.310 7.928 4.608000e+12 7.423e+10 12 16 5.000e+07 66.200 518.060 6.780 7.928 4.915200e+12 7.425e+10 13 1 5.000e+07 5.630 35.420 1.300 6.522 3.328000e+11 5.911e+10 13 2 5.000e+07 10.730 71.050 1.830 6.792 6.656000e+11 6.203e+10 13 3 5.000e+07 14.690 105.710 2.160 7.343 9.984000e+11 6.796e+10 13 4 5.000e+07 19.120 140.630 2.510 7.486 1.331200e+12 6.962e+10 13 5 5.000e+07 23.600 175.730 3.000 7.573 1.664000e+12 7.051e+10 13 6 5.000e+07 27.910 211.000 3.350 7.680 1.996800e+12 7.154e+10 13 7 5.000e+07 32.370 246.320 3.860 7.729 2.329600e+12 7.197e+10 13 8 5.000e+07 36.790 281.150 4.260 7.758 2.662400e+12 7.237e+10 13 9 5.000e+07 41.080 316.080 4.520 7.804 2.995200e+12 7.291e+10 13 10 5.000e+07 45.600 352.020 5.090 7.831 3.328000e+12 7.298e+10 13 11 5.000e+07 49.760 386.130 5.470 7.870 3.660800e+12 7.357e+10 13 12 5.000e+07 54.080 421.160 5.780 7.895 3.993600e+12 7.385e+10 13 13 5.000e+07 58.520 455.980 6.170 7.897 4.326400e+12 7.393e+10 13 14 5.000e+07 63.000 491.340 6.710 7.906 4.659200e+12 7.396e+10 13 15 5.000e+07 67.250 525.920 6.920 7.923 4.992000e+12 7.423e+10 13 16 5.000e+07 72.090 560.640 7.160 7.876 5.324800e+12 7.386e+10 14 1 5.000e+07 5.670 38.290 1.330 6.988 3.584000e+11 6.321e+10 14 2 5.000e+07 10.850 75.880 1.940 7.172 7.168000e+11 6.606e+10 14 3 5.000e+07 15.840 114.160 2.400 7.359 1.075200e+12 6.788e+10 14 4 5.000e+07 20.610 151.540 2.710 7.484 1.433600e+12 6.956e+10 14 5 5.000e+07 25.330 189.160 3.320 7.599 1.792000e+12 7.075e+10 14 6 5.000e+07 30.160 227.510 3.670 7.665 2.150400e+12 7.130e+10 14 7 5.000e+07 34.730 265.020 3.960 7.745 2.508800e+12 7.224e+10 14 8 5.000e+07 39.530 302.550 4.640 7.771 2.867200e+12 7.253e+10 14 9 5.000e+07 44.220 340.330 5.180 7.813 3.225600e+12 7.294e+10 14 10 5.000e+07 48.800 378.180 5.430 7.861 3.584000e+12 7.344e+10 14 11 5.000e+07 53.550 415.790 5.800 7.873 3.942400e+12 7.362e+10 14 12 5.000e+07 58.250 453.340 6.430 7.893 4.300800e+12 7.383e+10 14 13 5.000e+07 63.150 492.200 6.960 7.904 4.659200e+12 7.378e+10 14 14 5.000e+07 67.850 528.470 6.970 7.892 5.017600e+12 7.395e+10 14 15 5.000e+07 72.510 566.950 7.720 7.925 5.376000e+12 7.414e+10 14 16 5.000e+07 77.230 604.250 8.170 7.930 5.734400e+12 7.425e+10 15 1 5.000e+07 5.800 41.070 1.460 7.333 3.840000e+11 6.621e+10 15 2 5.000e+07 11.900 80.380 2.190 6.939 7.680000e+11 6.454e+10 15 3 5.000e+07 16.990 121.790 2.610 7.322 1.152000e+12 6.780e+10 15 4 5.000e+07 22.040 162.330 3.030 7.503 1.536000e+12 6.969e+10 15 5 5.000e+07 27.120 202.750 3.460 7.604 1.920000e+12 7.080e+10 15 6 5.000e+07 32.290 243.420 3.870 7.658 2.304000e+12 7.135e+10 15 7 5.000e+07 37.450 284.300 4.410 7.709 2.688000e+12 7.178e+10 15 8 5.000e+07 42.560 323.740 4.890 7.722 3.072000e+12 7.218e+10 15 9 5.000e+07 47.440 364.880 5.330 7.804 3.456000e+12 7.285e+10 15 10 5.000e+07 52.440 405.400 5.750 7.840 3.840000e+12 7.323e+10 15 11 5.000e+07 57.270 445.500 6.070 7.885 4.224000e+12 7.376e+10 15 12 5.000e+07 62.450 485.920 6.770 7.889 4.608000e+12 7.379e+10 15 13 5.000e+07 67.680 527.540 7.440 7.905 4.992000e+12 7.376e+10 15 14 5.000e+07 72.740 566.990 7.790 7.902 5.376000e+12 7.391e+10 15 15 5.000e+07 77.760 607.620 8.060 7.918 5.760000e+12 7.407e+10 15 16 5.000e+07 82.750 647.630 8.640 7.931 6.144000e+12 7.425e+10 16 1 5.000e+07 6.310 43.540 1.790 7.184 4.096000e+11 6.491e+10 16 2 5.000e+07 12.340 87.310 2.190 7.253 8.192000e+11 6.639e+10 16 3 5.000e+07 17.930 130.440 2.830 7.433 1.228800e+12 6.853e+10 16 4 5.000e+07 23.530 173.540 3.140 7.509 1.638400e+12 6.963e+10 16 5 5.000e+07 28.910 216.290 3.710 7.610 2.048000e+12 7.084e+10 16 6 5.000e+07 34.310 259.400 4.260 7.685 2.457600e+12 7.163e+10 16 7 5.000e+07 39.790 302.740 4.620 7.725 2.867200e+12 7.206e+10 16 8 5.000e+07 44.970 346.250 5.340 7.818 3.276800e+12 7.287e+10 16 9 5.000e+07 50.470 388.870 5.910 7.822 3.686400e+12 7.304e+10 16 10 5.000e+07 55.890 432.480 6.140 7.848 4.096000e+12 7.329e+10 16 11 5.000e+07 61.250 475.380 6.770 7.872 4.505600e+12 7.356e+10 16 12 5.000e+07 66.670 518.940 7.160 7.891 4.915200e+12 7.372e+10 16 13 5.000e+07 72.160 562.230 7.890 7.901 5.324800e+12 7.379e+10 16 14 5.000e+07 77.600 604.950 8.230 7.902 5.734400e+12 7.390e+10 16 15 5.000e+07 82.970 648.420 8.690 7.920 6.144000e+12 7.405e+10 16 16 5.000e+07 88.370 690.730 9.460 7.923 6.553600e+12 7.416e+10 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/js21.dat0000664000175000017500000001114012207440367025251 0ustar jcorganjcorgan#D JS21 4-core PPC970MP 2.5 GHz 1 1 5.273e+07 10.050 10.180 0.290 1.042 2.700000e+10 2.687e+09 1 2 5.273e+07 10.240 20.210 0.260 1.999 5.400000e+10 5.273e+09 1 3 5.273e+07 10.300 30.090 0.340 2.954 8.100000e+10 7.864e+09 1 4 5.273e+07 10.490 40.120 0.490 3.871 1.080000e+11 1.030e+10 1 5 4.219e+07 16.010 39.900 0.380 2.516 1.080000e+11 6.746e+09 1 6 3.516e+07 13.360 39.920 0.370 3.016 1.080000e+11 8.084e+09 1 7 3.013e+07 11.510 39.900 0.330 3.495 1.080000e+11 9.383e+09 1 8 2.637e+07 10.420 39.880 0.320 3.858 1.080000e+11 1.036e+10 2 1 5.273e+07 10.370 20.340 0.470 2.007 5.400000e+10 5.207e+09 2 2 5.273e+07 10.320 40.080 0.550 3.937 1.080000e+11 1.047e+10 2 3 3.516e+07 13.340 39.990 0.470 3.033 1.080000e+11 8.096e+09 2 4 2.637e+07 10.480 39.970 0.400 3.852 1.080000e+11 1.031e+10 2 5 2.109e+07 10.910 39.920 0.390 3.695 1.080000e+11 9.899e+09 2 6 1.758e+07 10.610 39.860 0.360 3.791 1.080000e+11 1.018e+10 2 7 1.507e+07 10.520 39.890 0.360 3.826 1.080000e+11 1.027e+10 2 8 1.318e+07 10.470 39.980 0.350 3.852 1.080000e+11 1.032e+10 3 1 5.273e+07 10.230 30.320 0.600 3.022 8.100000e+10 7.918e+09 3 2 3.516e+07 13.250 40.050 0.560 3.065 1.080000e+11 8.151e+09 3 3 2.344e+07 11.160 40.010 0.470 3.627 1.080000e+11 9.677e+09 3 4 1.758e+07 10.710 39.950 0.420 3.769 1.080000e+11 1.008e+10 3 5 1.406e+07 10.520 39.920 0.400 3.833 1.080000e+11 1.027e+10 3 6 1.172e+07 10.420 39.880 0.380 3.864 1.080000e+11 1.036e+10 3 7 1.004e+07 10.340 39.880 0.370 3.893 1.080000e+11 1.044e+10 3 8 8.789e+06 10.380 39.960 0.380 3.886 1.080000e+11 1.040e+10 4 1 5.273e+07 10.570 40.390 0.890 3.905 1.080000e+11 1.022e+10 4 2 2.637e+07 10.690 40.020 0.560 3.796 1.080000e+11 1.010e+10 4 3 1.758e+07 10.790 39.980 0.480 3.750 1.080000e+11 1.001e+10 4 4 1.318e+07 10.570 39.950 0.430 3.820 1.080000e+11 1.022e+10 4 5 1.055e+07 10.440 39.950 0.420 3.867 1.080000e+11 1.034e+10 4 6 8.789e+06 10.340 39.900 0.420 3.899 1.080000e+11 1.044e+10 4 7 7.533e+06 10.290 39.870 0.410 3.914 1.080000e+11 1.050e+10 4 8 6.592e+06 10.270 39.950 0.390 3.928 1.080000e+11 1.052e+10 5 1 4.219e+07 15.110 40.290 0.830 2.721 1.080000e+11 7.148e+09 5 2 2.109e+07 11.240 40.000 0.580 3.610 1.080000e+11 9.609e+09 5 3 1.406e+07 10.710 39.970 0.490 3.778 1.080000e+11 1.008e+10 5 4 1.055e+07 10.490 39.980 0.460 3.855 1.080000e+11 1.030e+10 5 5 8.438e+06 10.430 39.940 0.440 3.872 1.080000e+11 1.035e+10 5 6 7.031e+06 10.280 39.890 0.420 3.921 1.080000e+11 1.051e+10 5 7 6.027e+06 10.290 39.870 0.400 3.914 1.080000e+11 1.050e+10 5 8 5.273e+06 10.290 39.940 0.400 3.920 1.080000e+11 1.050e+10 6 1 3.516e+07 12.880 40.250 0.850 3.191 1.080000e+11 8.385e+09 6 2 1.758e+07 10.730 39.980 0.580 3.780 1.080000e+11 1.007e+10 6 3 1.172e+07 10.740 39.980 0.490 3.768 1.080000e+11 1.006e+10 6 4 8.789e+06 10.510 39.940 0.460 3.844 1.080000e+11 1.028e+10 6 5 7.031e+06 10.430 39.920 0.450 3.871 1.080000e+11 1.035e+10 6 6 5.859e+06 10.300 39.910 0.430 3.917 1.080000e+11 1.049e+10 6 7 5.022e+06 10.290 39.870 0.420 3.915 1.080000e+11 1.050e+10 6 8 4.395e+06 10.300 39.950 0.420 3.919 1.080000e+11 1.049e+10 7 1 3.013e+07 11.240 40.270 0.860 3.659 1.080000e+11 9.609e+09 7 2 1.507e+07 11.040 40.000 0.590 3.677 1.080000e+11 9.783e+09 7 3 1.004e+07 10.660 39.970 0.520 3.798 1.080000e+11 1.013e+10 7 4 7.533e+06 10.430 39.930 0.470 3.873 1.080000e+11 1.035e+10 7 5 6.027e+06 10.390 39.920 0.470 3.887 1.080000e+11 1.039e+10 7 6 5.022e+06 10.320 39.910 0.430 3.909 1.080000e+11 1.047e+10 7 7 4.305e+06 10.330 39.890 0.420 3.902 1.080000e+11 1.045e+10 7 8 3.767e+06 10.300 39.930 0.420 3.917 1.080000e+11 1.049e+10 8 1 2.637e+07 10.530 40.290 0.910 3.913 1.080000e+11 1.026e+10 8 2 1.318e+07 10.850 40.040 0.610 3.747 1.080000e+11 9.954e+09 8 3 8.789e+06 10.500 39.960 0.540 3.857 1.080000e+11 1.029e+10 8 4 6.592e+06 10.490 39.960 0.500 3.857 1.080000e+11 1.030e+10 8 5 5.273e+06 10.330 39.930 0.480 3.912 1.080000e+11 1.045e+10 8 6 4.395e+06 10.340 39.900 0.450 3.902 1.080000e+11 1.044e+10 8 7 3.767e+06 10.260 39.900 0.430 3.931 1.080000e+11 1.053e+10 8 8 3.296e+06 10.250 39.960 0.430 3.940 1.080000e+11 1.054e+10 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/qs21.dat0000664000175000017500000001113212207440367025261 0ustar jcorganjcorgan#D QS21 dual cell 3.2 GHz 1 1 1.953e+07 8.480 8.730 0.270 1.061 1.000000e+10 1.179e+09 1 2 1.953e+07 8.750 17.210 0.460 2.019 2.000000e+10 2.286e+09 1 3 1.302e+07 12.390 29.530 0.540 2.427 2.000000e+10 1.614e+09 1 4 9.766e+06 10.120 31.500 0.590 3.171 2.000000e+10 1.976e+09 1 5 7.812e+06 10.200 31.350 0.610 3.133 2.000000e+10 1.961e+09 1 6 6.510e+06 9.520 31.690 0.590 3.391 2.000000e+10 2.101e+09 1 7 5.580e+06 9.430 32.610 0.600 3.522 2.000000e+10 2.121e+09 1 8 4.883e+06 9.400 34.160 0.620 3.700 2.000000e+10 2.128e+09 2 1 1.953e+07 8.800 17.750 0.500 2.074 2.000000e+10 2.273e+09 2 2 9.766e+06 8.990 28.900 0.640 3.286 2.000000e+10 2.225e+09 2 3 6.510e+06 9.390 32.450 0.660 3.526 2.000000e+10 2.130e+09 2 4 4.883e+06 9.220 34.450 0.660 3.808 2.000000e+10 2.169e+09 2 5 3.906e+06 9.180 34.730 0.650 3.854 2.000000e+10 2.179e+09 2 6 3.255e+06 9.150 34.960 0.650 3.892 2.000000e+10 2.186e+09 2 7 2.790e+06 9.140 35.290 0.650 3.932 2.000000e+10 2.188e+09 2 8 2.441e+06 9.080 35.240 0.650 3.953 2.000000e+10 2.203e+09 3 1 1.302e+07 11.720 28.890 0.740 2.528 2.000000e+10 1.706e+09 3 2 6.510e+06 9.390 32.700 0.730 3.560 2.000000e+10 2.130e+09 3 3 4.340e+06 9.150 33.930 0.690 3.784 2.000000e+10 2.186e+09 3 4 3.255e+06 9.040 34.650 0.680 3.908 2.000000e+10 2.212e+09 3 5 2.604e+06 9.090 34.990 0.680 3.924 1.999999e+10 2.200e+09 3 6 2.170e+06 9.050 34.870 0.670 3.927 1.999999e+10 2.210e+09 3 7 1.860e+06 9.010 34.850 0.660 3.941 2.000000e+10 2.220e+09 3 8 1.628e+06 8.980 34.860 0.670 3.957 2.000000e+10 2.227e+09 4 1 9.766e+06 9.000 34.680 0.940 3.958 2.000000e+10 2.222e+09 4 2 4.883e+06 9.020 34.180 0.740 3.871 2.000000e+10 2.217e+09 4 3 3.255e+06 9.150 34.640 0.710 3.863 2.000000e+10 2.186e+09 4 4 2.441e+06 9.010 34.780 0.690 3.937 2.000000e+10 2.220e+09 4 5 1.953e+06 8.980 34.680 0.690 3.939 2.000000e+10 2.227e+09 4 6 1.628e+06 9.050 35.120 0.690 3.957 2.000000e+10 2.210e+09 4 7 1.395e+06 9.010 34.900 0.670 3.948 2.000000e+10 2.220e+09 4 8 1.221e+06 8.960 34.900 0.680 3.971 2.000000e+10 2.232e+09 5 1 7.812e+06 10.150 31.760 0.840 3.212 2.000000e+10 1.970e+09 5 2 3.906e+06 9.090 34.040 0.750 3.827 2.000000e+10 2.200e+09 5 3 2.604e+06 9.030 34.650 0.720 3.917 1.999999e+10 2.215e+09 5 4 1.953e+06 8.990 34.610 0.700 3.928 2.000000e+10 2.225e+09 5 5 1.562e+06 9.000 34.920 0.700 3.958 2.000000e+10 2.222e+09 5 6 1.302e+06 9.120 35.370 0.690 3.954 1.999999e+10 2.193e+09 5 7 1.116e+06 8.910 34.680 0.690 3.970 1.999999e+10 2.245e+09 5 8 9.766e+05 8.930 34.790 0.680 3.972 1.999999e+10 2.240e+09 6 1 6.510e+06 9.390 31.810 0.840 3.477 2.000000e+10 2.130e+09 6 2 3.255e+06 9.000 34.320 0.760 3.898 2.000000e+10 2.222e+09 6 3 2.170e+06 8.960 34.310 0.740 3.912 1.999999e+10 2.232e+09 6 4 1.628e+06 8.970 34.640 0.730 3.943 2.000000e+10 2.230e+09 6 5 1.302e+06 9.110 35.360 0.710 3.959 1.999999e+10 2.195e+09 6 6 1.085e+06 8.970 34.750 0.710 3.953 1.999999e+10 2.230e+09 6 7 9.301e+05 8.950 34.710 0.700 3.956 1.999999e+10 2.235e+09 6 8 8.138e+05 8.920 34.570 0.710 3.955 2.000000e+10 2.242e+09 7 1 5.580e+06 9.290 32.840 0.870 3.629 2.000000e+10 2.153e+09 7 2 2.790e+06 9.040 34.400 0.770 3.890 2.000000e+10 2.212e+09 7 3 1.860e+06 8.940 34.380 0.740 3.928 2.000000e+10 2.237e+09 7 4 1.395e+06 8.990 34.820 0.730 3.954 2.000000e+10 2.225e+09 7 5 1.116e+06 8.990 34.820 0.720 3.953 1.999999e+10 2.225e+09 7 6 9.301e+05 8.940 34.720 0.720 3.964 1.999999e+10 2.237e+09 7 7 7.972e+05 8.930 34.700 0.710 3.965 1.999998e+10 2.240e+09 7 8 6.975e+05 8.910 34.510 0.700 3.952 1.999998e+10 2.245e+09 8 1 4.883e+06 9.070 33.770 0.910 3.824 2.000000e+10 2.205e+09 8 2 2.441e+06 9.000 34.340 0.780 3.902 2.000000e+10 2.222e+09 8 3 1.628e+06 8.990 34.510 0.740 3.921 2.000000e+10 2.225e+09 8 4 1.221e+06 8.980 34.650 0.740 3.941 2.000000e+10 2.227e+09 8 5 9.766e+05 8.960 34.700 0.720 3.953 1.999999e+10 2.232e+09 8 6 8.138e+05 8.920 34.680 0.710 3.967 2.000000e+10 2.242e+09 8 7 6.975e+05 8.900 34.580 0.720 3.966 1.999998e+10 2.247e+09 8 8 6.104e+05 8.930 34.590 0.710 3.953 1.999998e+10 2.240e+09 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/dual-quad-core-2.33-clovertown.dat0000664000175000017500000004446212207440367032075 0ustar jcorganjcorgan#D Dual quad-core Xeon 2.33GHz (Clovertown E5345) 1 1 1.367e+08 10.980 12.080 0.360 1.133 7.000000e+10 6.375e+09 1 2 1.367e+08 12.250 24.310 0.400 2.017 1.400000e+11 1.143e+10 1 3 1.367e+08 12.830 36.080 0.580 2.857 2.100000e+11 1.637e+10 1 4 1.367e+08 12.600 46.820 0.770 3.777 2.800000e+11 2.222e+10 1 5 1.367e+08 12.620 58.850 0.720 4.720 3.500000e+11 2.773e+10 1 6 1.367e+08 12.310 69.430 0.860 5.710 4.200000e+11 3.412e+10 1 7 1.367e+08 12.720 80.580 0.950 6.410 4.900000e+11 3.852e+10 1 8 1.367e+08 12.440 91.530 1.010 7.439 5.600000e+11 4.502e+10 1 9 1.367e+08 22.310 102.660 1.080 4.650 6.300000e+11 2.824e+10 1 10 1.367e+08 22.610 113.670 1.160 5.079 7.000000e+11 3.096e+10 1 11 1.367e+08 22.690 124.730 1.030 5.543 7.700000e+11 3.394e+10 1 12 1.367e+08 23.260 136.520 1.030 5.914 8.400000e+11 3.611e+10 1 13 1.367e+08 23.330 147.270 1.130 6.361 9.100000e+11 3.901e+10 1 14 1.367e+08 24.110 158.070 1.010 6.598 9.800000e+11 4.065e+10 1 15 1.367e+08 25.380 168.370 1.080 6.677 1.050000e+12 4.137e+10 1 16 1.367e+08 26.660 179.130 1.250 6.766 1.120000e+12 4.201e+10 2 1 1.367e+08 11.190 23.330 0.420 2.122 1.400000e+11 1.251e+10 2 2 1.367e+08 12.650 46.350 0.940 3.738 2.800000e+11 2.213e+10 2 3 1.367e+08 12.510 69.010 0.980 5.595 4.200000e+11 3.357e+10 2 4 1.367e+08 13.250 89.330 0.890 6.809 5.600000e+11 4.226e+10 2 5 1.367e+08 22.540 113.580 1.150 5.090 7.000000e+11 3.106e+10 2 6 1.367e+08 22.940 135.790 1.260 5.974 8.400000e+11 3.662e+10 2 7 1.367e+08 24.250 158.360 1.520 6.593 9.800000e+11 4.041e+10 2 8 1.367e+08 26.610 179.840 1.490 6.814 1.120000e+12 4.209e+10 2 9 1.215e+08 26.860 179.400 1.540 6.736 1.120000e+12 4.170e+10 2 10 1.094e+08 26.350 178.740 1.430 6.838 1.120000e+12 4.250e+10 2 11 9.943e+07 25.790 177.910 1.350 6.951 1.120000e+12 4.343e+10 2 12 9.115e+07 25.200 176.980 1.460 7.081 1.120000e+12 4.444e+10 2 13 8.413e+07 24.840 177.320 1.260 7.189 1.120000e+12 4.509e+10 2 14 7.812e+07 24.450 176.920 1.130 7.282 1.120000e+12 4.581e+10 2 15 7.292e+07 24.280 177.400 1.140 7.353 1.120000e+12 4.613e+10 2 16 6.836e+07 23.830 176.290 1.100 7.444 1.120000e+12 4.700e+10 3 1 1.367e+08 11.360 34.790 0.930 3.144 2.100000e+11 1.849e+10 3 2 1.367e+08 12.560 68.800 1.400 5.589 4.200000e+11 3.344e+10 3 3 1.367e+08 22.310 103.250 1.310 4.687 6.300000e+11 2.824e+10 3 4 1.367e+08 22.940 136.120 1.500 5.999 8.400000e+11 3.662e+10 3 5 1.367e+08 25.240 168.550 1.790 6.749 1.050000e+12 4.160e+10 3 6 1.215e+08 26.800 178.710 1.610 6.728 1.120000e+12 4.179e+10 3 7 1.042e+08 26.090 178.710 1.490 6.907 1.120000e+12 4.293e+10 3 8 9.115e+07 25.420 178.140 1.360 7.061 1.120000e+12 4.406e+10 3 9 8.102e+07 24.680 177.260 1.410 7.239 1.120000e+12 4.538e+10 3 10 7.292e+07 24.270 176.830 1.390 7.343 1.120000e+12 4.615e+10 3 11 6.629e+07 23.890 177.060 1.240 7.463 1.120000e+12 4.688e+10 3 12 6.076e+07 23.620 176.290 1.300 7.519 1.120000e+12 4.742e+10 3 13 5.609e+07 23.340 176.780 1.230 7.627 1.120000e+12 4.799e+10 3 14 5.208e+07 23.140 176.330 1.300 7.676 1.120000e+12 4.840e+10 3 15 4.861e+07 23.100 176.940 1.080 7.706 1.120000e+12 4.848e+10 3 16 4.557e+07 22.850 176.120 1.060 7.754 1.120000e+12 4.902e+10 4 1 1.367e+08 11.440 45.520 1.080 4.073 2.800000e+11 2.448e+10 4 2 1.367e+08 12.410 90.020 1.440 7.370 5.600000e+11 4.512e+10 4 3 1.367e+08 23.060 135.570 1.600 5.948 8.400000e+11 3.643e+10 4 4 1.367e+08 26.720 179.780 1.880 6.799 1.120000e+12 4.192e+10 4 5 1.094e+08 26.280 178.110 1.890 6.849 1.120000e+12 4.262e+10 4 6 9.115e+07 25.250 177.280 1.700 7.088 1.120000e+12 4.436e+10 4 7 7.812e+07 24.880 177.830 1.570 7.211 1.120000e+12 4.502e+10 4 8 6.836e+07 24.150 177.240 1.350 7.395 1.120000e+12 4.638e+10 4 9 6.076e+07 23.730 176.590 1.370 7.499 1.120000e+12 4.720e+10 4 10 5.469e+07 23.380 176.570 1.310 7.608 1.120000e+12 4.790e+10 4 11 4.972e+07 23.230 176.400 1.290 7.649 1.120000e+12 4.821e+10 4 12 4.557e+07 22.950 176.100 1.250 7.728 1.120000e+12 4.880e+10 4 13 4.207e+07 22.980 176.430 1.260 7.732 1.120000e+12 4.874e+10 4 14 3.906e+07 22.820 176.300 1.350 7.785 1.120000e+12 4.908e+10 4 15 3.646e+07 22.750 176.450 1.220 7.810 1.120000e+12 4.923e+10 4 16 3.418e+07 22.620 176.350 1.080 7.844 1.120000e+12 4.951e+10 5 1 1.367e+08 12.000 56.890 1.600 4.874 3.500000e+11 2.917e+10 5 2 1.367e+08 22.390 112.870 1.920 5.127 7.000000e+11 3.126e+10 5 3 1.367e+08 25.170 167.880 2.110 6.754 1.050000e+12 4.172e+10 5 4 1.094e+08 26.380 178.010 1.900 6.820 1.120000e+12 4.246e+10 5 5 8.750e+07 25.190 177.570 1.660 7.115 1.120000e+12 4.446e+10 5 6 7.292e+07 24.400 176.750 1.650 7.311 1.120000e+12 4.590e+10 5 7 6.250e+07 24.020 177.580 1.570 7.458 1.120000e+12 4.663e+10 5 8 5.469e+07 23.470 176.650 1.350 7.584 1.120000e+12 4.772e+10 5 9 4.861e+07 23.200 176.350 1.280 7.656 1.120000e+12 4.828e+10 5 10 4.375e+07 23.140 176.230 1.410 7.677 1.120000e+12 4.840e+10 5 11 3.977e+07 22.930 176.120 1.320 7.738 1.120000e+12 4.884e+10 5 12 3.646e+07 22.740 176.060 1.330 7.801 1.120000e+12 4.925e+10 5 13 3.365e+07 22.690 176.450 1.210 7.830 1.120000e+12 4.936e+10 5 14 3.125e+07 22.690 176.430 1.230 7.830 1.120000e+12 4.936e+10 5 15 2.917e+07 22.690 176.410 1.260 7.830 1.120000e+12 4.936e+10 5 16 2.734e+07 22.560 176.150 1.110 7.857 1.120000e+12 4.965e+10 6 1 1.367e+08 12.600 68.590 2.230 5.621 4.200000e+11 3.333e+10 6 2 1.367e+08 22.830 135.260 2.100 6.017 8.400000e+11 3.679e+10 6 3 1.215e+08 26.860 178.470 2.140 6.724 1.120000e+12 4.170e+10 6 4 9.115e+07 25.450 177.110 2.060 7.040 1.120000e+12 4.401e+10 6 5 7.292e+07 24.510 176.850 1.910 7.293 1.120000e+12 4.570e+10 6 6 6.076e+07 23.890 176.450 1.760 7.460 1.120000e+12 4.688e+10 6 7 5.208e+07 23.460 175.980 1.540 7.567 1.120000e+12 4.774e+10 6 8 4.557e+07 23.150 176.480 1.370 7.683 1.120000e+12 4.838e+10 6 9 4.051e+07 22.920 176.030 1.400 7.741 1.120000e+12 4.887e+10 6 10 3.646e+07 22.880 176.300 1.350 7.764 1.120000e+12 4.895e+10 6 11 3.314e+07 22.830 175.970 1.360 7.767 1.120000e+12 4.906e+10 6 12 3.038e+07 22.710 176.040 1.190 7.804 1.120000e+12 4.932e+10 6 13 2.804e+07 22.690 176.050 1.340 7.818 1.120000e+12 4.936e+10 6 14 2.604e+07 22.650 176.410 1.140 7.839 1.120000e+12 4.945e+10 6 15 2.431e+07 22.570 175.940 1.250 7.851 1.120000e+12 4.962e+10 6 16 2.279e+07 22.500 175.980 1.170 7.873 1.120000e+12 4.978e+10 7 1 1.367e+08 12.960 79.970 2.850 6.390 4.900000e+11 3.781e+10 7 2 1.367e+08 24.040 156.540 2.500 6.616 9.800000e+11 4.077e+10 7 3 1.042e+08 26.130 178.060 2.210 6.899 1.120000e+12 4.286e+10 7 4 7.812e+07 24.860 176.880 1.810 7.188 1.120000e+12 4.505e+10 7 5 6.250e+07 24.000 176.590 1.790 7.433 1.120000e+12 4.667e+10 7 6 5.208e+07 23.540 176.480 1.670 7.568 1.120000e+12 4.758e+10 7 7 4.464e+07 23.180 176.030 1.510 7.659 1.120000e+12 4.832e+10 7 8 3.906e+07 22.980 176.500 1.340 7.739 1.120000e+12 4.874e+10 7 9 3.472e+07 22.870 175.970 1.280 7.750 1.120000e+12 4.897e+10 7 10 3.125e+07 22.730 176.220 1.300 7.810 1.120000e+12 4.927e+10 7 11 2.841e+07 22.700 176.030 1.300 7.812 1.120000e+12 4.934e+10 7 12 2.604e+07 22.650 176.300 1.210 7.837 1.120000e+12 4.945e+10 7 13 2.404e+07 22.580 176.140 1.170 7.853 1.120000e+12 4.960e+10 7 14 2.232e+07 22.540 176.550 1.130 7.883 1.120000e+12 4.969e+10 7 15 2.083e+07 22.570 175.870 1.260 7.848 1.120000e+12 4.962e+10 7 16 1.953e+07 22.520 175.980 1.310 7.873 1.120000e+12 4.973e+10 8 1 1.367e+08 13.250 91.770 3.010 7.153 5.600000e+11 4.226e+10 8 2 1.367e+08 26.280 178.100 2.980 6.890 1.120000e+12 4.262e+10 8 3 9.115e+07 25.510 177.140 2.270 7.033 1.120000e+12 4.390e+10 8 4 6.836e+07 24.330 176.850 1.870 7.346 1.120000e+12 4.603e+10 8 5 5.469e+07 23.680 176.850 1.690 7.540 1.120000e+12 4.730e+10 8 6 4.557e+07 23.430 176.210 1.700 7.593 1.120000e+12 4.780e+10 8 7 3.906e+07 23.100 176.680 1.440 7.711 1.120000e+12 4.848e+10 8 8 3.418e+07 22.890 176.270 1.430 7.763 1.120000e+12 4.893e+10 8 9 3.038e+07 22.760 175.980 1.320 7.790 1.120000e+12 4.921e+10 8 10 2.734e+07 22.760 176.340 1.290 7.804 1.120000e+12 4.921e+10 8 11 2.486e+07 22.660 176.220 1.170 7.828 1.120000e+12 4.943e+10 8 12 2.279e+07 22.660 176.050 1.280 7.826 1.120000e+12 4.943e+10 8 13 2.103e+07 22.590 176.170 1.350 7.858 1.120000e+12 4.958e+10 8 14 1.953e+07 22.550 176.120 1.320 7.869 1.120000e+12 4.967e+10 8 15 1.823e+07 22.590 176.130 1.270 7.853 1.120000e+12 4.958e+10 8 16 1.709e+07 22.500 176.090 1.230 7.881 1.120000e+12 4.978e+10 9 1 1.367e+08 21.110 101.410 2.640 4.929 6.300000e+11 2.984e+10 9 2 1.215e+08 27.400 178.180 2.720 6.602 1.120000e+12 4.088e+10 9 3 8.102e+07 25.140 177.370 2.230 7.144 1.120000e+12 4.455e+10 9 4 6.076e+07 24.110 176.810 1.910 7.413 1.120000e+12 4.645e+10 9 5 4.861e+07 23.460 176.240 1.600 7.581 1.120000e+12 4.774e+10 9 6 4.051e+07 23.200 176.310 1.620 7.669 1.120000e+12 4.828e+10 9 7 3.472e+07 22.970 176.560 1.540 7.754 1.120000e+12 4.876e+10 9 8 3.038e+07 22.920 176.300 1.440 7.755 1.120000e+12 4.887e+10 9 9 2.701e+07 22.830 176.090 1.370 7.773 1.120000e+12 4.906e+10 9 10 2.431e+07 22.730 175.960 1.430 7.804 1.120000e+12 4.927e+10 9 11 2.210e+07 22.750 176.160 1.260 7.799 1.120000e+12 4.923e+10 9 12 2.025e+07 22.660 176.100 1.380 7.832 1.120000e+12 4.943e+10 9 13 1.870e+07 22.700 176.040 1.400 7.817 1.120000e+12 4.934e+10 9 14 1.736e+07 22.620 175.940 1.410 7.840 1.120000e+12 4.951e+10 9 15 1.620e+07 22.490 175.910 1.340 7.881 1.120000e+12 4.980e+10 9 16 1.519e+07 22.540 175.990 1.330 7.867 1.120000e+12 4.969e+10 10 1 1.367e+08 21.730 113.690 2.870 5.364 7.000000e+11 3.221e+10 10 2 1.094e+08 26.660 177.920 3.180 6.793 1.120000e+12 4.201e+10 10 3 7.292e+07 24.740 176.810 2.090 7.231 1.120000e+12 4.527e+10 10 4 5.469e+07 23.880 176.280 2.020 7.466 1.120000e+12 4.690e+10 10 5 4.375e+07 23.330 176.510 1.610 7.635 1.120000e+12 4.801e+10 10 6 3.646e+07 23.170 176.160 1.680 7.675 1.120000e+12 4.834e+10 10 7 3.125e+07 22.950 176.490 1.470 7.754 1.120000e+12 4.880e+10 10 8 2.734e+07 22.830 176.260 1.360 7.780 1.120000e+12 4.906e+10 10 9 2.431e+07 22.770 175.930 1.410 7.788 1.120000e+12 4.919e+10 10 10 2.188e+07 22.680 175.870 1.440 7.818 1.120000e+12 4.938e+10 10 11 1.989e+07 22.700 176.140 1.310 7.817 1.120000e+12 4.934e+10 10 12 1.823e+07 22.630 176.040 1.430 7.842 1.120000e+12 4.949e+10 10 13 1.683e+07 22.640 176.000 1.320 7.832 1.120000e+12 4.947e+10 10 14 1.562e+07 22.610 176.160 1.230 7.846 1.120000e+12 4.954e+10 10 15 1.458e+07 22.570 176.010 1.290 7.856 1.120000e+12 4.962e+10 10 16 1.367e+07 22.640 176.060 1.270 7.833 1.120000e+12 4.947e+10 11 1 1.367e+08 22.060 124.440 3.050 5.779 7.700000e+11 3.490e+10 11 2 9.943e+07 26.060 178.400 3.000 6.961 1.120000e+12 4.298e+10 11 3 6.629e+07 24.380 176.690 2.200 7.338 1.120000e+12 4.594e+10 11 4 4.972e+07 23.650 176.730 1.830 7.550 1.120000e+12 4.736e+10 11 5 3.977e+07 23.310 176.030 1.780 7.628 1.120000e+12 4.805e+10 11 6 3.314e+07 23.050 176.210 1.680 7.718 1.120000e+12 4.859e+10 11 7 2.841e+07 22.940 176.300 1.540 7.752 1.120000e+12 4.882e+10 11 8 2.486e+07 22.830 175.990 1.530 7.776 1.120000e+12 4.906e+10 11 9 2.210e+07 22.760 176.060 1.440 7.799 1.120000e+12 4.921e+10 11 10 1.989e+07 22.630 176.010 1.430 7.841 1.120000e+12 4.949e+10 11 11 1.808e+07 22.720 176.040 1.390 7.809 1.120000e+12 4.930e+10 11 12 1.657e+07 22.640 175.890 1.400 7.831 1.120000e+12 4.947e+10 11 13 1.530e+07 22.570 176.090 1.260 7.858 1.120000e+12 4.962e+10 11 14 1.420e+07 22.610 176.150 1.450 7.855 1.120000e+12 4.954e+10 11 15 1.326e+07 22.550 175.980 1.310 7.862 1.120000e+12 4.967e+10 11 16 1.243e+07 22.610 175.920 1.400 7.843 1.120000e+12 4.954e+10 12 1 1.367e+08 22.220 136.260 3.390 6.285 8.400000e+11 3.780e+10 12 2 9.115e+07 25.610 178.090 2.800 7.063 1.120000e+12 4.373e+10 12 3 6.076e+07 24.180 176.320 2.230 7.384 1.120000e+12 4.632e+10 12 4 4.557e+07 23.570 176.570 2.010 7.577 1.120000e+12 4.752e+10 12 5 3.646e+07 23.210 176.420 1.710 7.675 1.120000e+12 4.826e+10 12 6 3.038e+07 23.040 175.910 1.640 7.706 1.120000e+12 4.861e+10 12 7 2.604e+07 22.980 176.390 1.510 7.742 1.120000e+12 4.874e+10 12 8 2.279e+07 22.840 176.110 1.640 7.782 1.120000e+12 4.904e+10 12 9 2.025e+07 22.760 175.950 1.500 7.797 1.120000e+12 4.921e+10 12 10 1.823e+07 22.660 175.810 1.600 7.829 1.120000e+12 4.943e+10 12 11 1.657e+07 22.710 175.940 1.410 7.809 1.120000e+12 4.932e+10 12 12 1.519e+07 22.650 175.870 1.400 7.826 1.120000e+12 4.945e+10 12 13 1.402e+07 22.640 176.040 1.260 7.831 1.120000e+12 4.947e+10 12 14 1.302e+07 22.650 176.130 1.450 7.840 1.120000e+12 4.945e+10 12 15 1.215e+07 22.580 175.990 1.370 7.855 1.120000e+12 4.960e+10 12 16 1.139e+07 22.640 175.870 1.440 7.832 1.120000e+12 4.947e+10 13 1 1.367e+08 22.640 147.020 3.570 6.652 9.100000e+11 4.019e+10 13 2 8.413e+07 25.600 177.820 2.870 7.058 1.120000e+12 4.375e+10 13 3 5.609e+07 24.020 176.980 2.270 7.463 1.120000e+12 4.663e+10 13 4 4.207e+07 23.440 176.430 2.030 7.613 1.120000e+12 4.778e+10 13 5 3.365e+07 23.080 176.110 1.790 7.708 1.120000e+12 4.853e+10 13 6 2.804e+07 22.870 176.210 1.600 7.775 1.120000e+12 4.897e+10 13 7 2.404e+07 22.940 176.340 1.580 7.756 1.120000e+12 4.882e+10 13 8 2.103e+07 22.880 176.050 1.520 7.761 1.120000e+12 4.895e+10 13 9 1.870e+07 22.740 176.020 1.400 7.802 1.120000e+12 4.925e+10 13 10 1.683e+07 22.710 175.880 1.440 7.808 1.120000e+12 4.932e+10 13 11 1.530e+07 22.590 176.040 1.350 7.853 1.120000e+12 4.958e+10 13 12 1.402e+07 22.600 175.930 1.380 7.846 1.120000e+12 4.956e+10 13 13 1.294e+07 22.710 176.010 1.340 7.809 1.120000e+12 4.932e+10 13 14 1.202e+07 22.690 176.270 1.350 7.828 1.120000e+12 4.936e+10 13 15 1.122e+07 22.590 175.960 1.290 7.846 1.120000e+12 4.958e+10 13 16 1.052e+07 22.610 175.960 1.370 7.843 1.120000e+12 4.954e+10 14 1 1.367e+08 23.120 157.180 3.810 6.963 9.800000e+11 4.239e+10 14 2 7.812e+07 25.310 177.210 3.020 7.121 1.120000e+12 4.425e+10 14 3 5.208e+07 24.130 177.110 2.340 7.437 1.120000e+12 4.642e+10 14 4 3.906e+07 23.390 176.660 1.800 7.630 1.120000e+12 4.788e+10 14 5 3.125e+07 23.060 176.420 1.750 7.726 1.120000e+12 4.857e+10 14 6 2.604e+07 22.890 176.180 1.530 7.764 1.120000e+12 4.893e+10 14 7 2.232e+07 22.940 176.060 1.550 7.742 1.120000e+12 4.882e+10 14 8 1.953e+07 22.810 176.110 1.500 7.786 1.120000e+12 4.910e+10 14 9 1.736e+07 22.750 176.370 1.370 7.813 1.120000e+12 4.923e+10 14 10 1.562e+07 22.720 176.020 1.450 7.811 1.120000e+12 4.930e+10 14 11 1.420e+07 22.680 176.090 1.310 7.822 1.120000e+12 4.938e+10 14 12 1.302e+07 22.710 175.950 1.510 7.814 1.120000e+12 4.932e+10 14 13 1.202e+07 22.700 176.100 1.500 7.824 1.120000e+12 4.934e+10 14 14 1.116e+07 22.660 176.150 1.460 7.838 1.120000e+12 4.943e+10 14 15 1.042e+07 22.680 176.120 1.370 7.826 1.120000e+12 4.938e+10 14 16 9.766e+06 22.710 176.110 1.430 7.818 1.120000e+12 4.932e+10 15 1 1.367e+08 23.710 168.080 4.140 7.264 1.050000e+12 4.429e+10 15 2 7.292e+07 25.170 176.640 2.930 7.134 1.120000e+12 4.450e+10 15 3 4.861e+07 23.820 176.980 2.110 7.518 1.120000e+12 4.702e+10 15 4 3.646e+07 23.250 176.190 1.970 7.663 1.120000e+12 4.817e+10 15 5 2.917e+07 23.050 176.450 1.690 7.728 1.120000e+12 4.859e+10 15 6 2.431e+07 22.900 175.980 1.680 7.758 1.120000e+12 4.891e+10 15 7 2.083e+07 22.830 176.090 1.640 7.785 1.120000e+12 4.906e+10 15 8 1.823e+07 22.850 176.160 1.530 7.776 1.120000e+12 4.902e+10 15 9 1.620e+07 22.780 176.390 1.360 7.803 1.120000e+12 4.917e+10 15 10 1.458e+07 22.660 176.000 1.440 7.831 1.120000e+12 4.943e+10 15 11 1.326e+07 22.660 176.110 1.430 7.835 1.120000e+12 4.943e+10 15 12 1.215e+07 22.660 176.150 1.380 7.835 1.120000e+12 4.943e+10 15 13 1.122e+07 22.760 175.970 1.580 7.801 1.120000e+12 4.921e+10 15 14 1.042e+07 22.670 176.290 1.270 7.832 1.120000e+12 4.940e+10 15 15 9.722e+06 22.710 176.060 1.550 7.821 1.120000e+12 4.932e+10 15 16 9.115e+06 22.800 176.020 1.490 7.786 1.120000e+12 4.912e+10 16 1 1.367e+08 25.470 179.270 4.730 7.224 1.120000e+12 4.397e+10 16 2 6.836e+07 24.870 176.820 2.960 7.229 1.120000e+12 4.503e+10 16 3 4.557e+07 23.810 176.930 2.250 7.525 1.120000e+12 4.704e+10 16 4 3.418e+07 23.240 176.650 1.950 7.685 1.120000e+12 4.819e+10 16 5 2.734e+07 23.090 175.940 1.940 7.704 1.120000e+12 4.851e+10 16 6 2.279e+07 22.900 176.120 1.680 7.764 1.120000e+12 4.891e+10 16 7 1.953e+07 22.890 176.290 1.440 7.765 1.120000e+12 4.893e+10 16 8 1.709e+07 22.820 176.040 1.610 7.785 1.120000e+12 4.908e+10 16 9 1.519e+07 22.890 175.990 1.470 7.753 1.120000e+12 4.893e+10 16 10 1.367e+07 22.700 175.890 1.470 7.813 1.120000e+12 4.934e+10 16 11 1.243e+07 22.770 175.960 1.520 7.794 1.120000e+12 4.919e+10 16 12 1.139e+07 22.730 176.000 1.430 7.806 1.120000e+12 4.927e+10 16 13 1.052e+07 22.670 175.990 1.540 7.831 1.120000e+12 4.940e+10 16 14 9.766e+06 22.720 176.130 1.440 7.816 1.120000e+12 4.930e+10 16 15 9.115e+06 22.740 176.320 1.360 7.814 1.120000e+12 4.925e+10 16 16 8.545e+06 22.680 176.170 1.320 7.826 1.120000e+12 4.938e+10 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/core2-duo.dat0000664000175000017500000001113512207440367026275 0ustar jcorganjcorgan#D Core2 Duo 2.66 GHz (6700) 1 1 1.406e+08 9.890 10.100 0.230 1.044 7.200000e+10 7.280e+09 1 2 1.406e+08 10.400 19.900 0.290 1.941 1.440000e+11 1.385e+10 1 3 9.375e+07 11.410 19.950 0.200 1.766 1.440000e+11 1.262e+10 1 4 7.031e+07 10.230 19.800 0.230 1.958 1.440000e+11 1.408e+10 1 5 5.625e+07 10.640 19.800 0.180 1.878 1.440000e+11 1.353e+10 1 6 4.688e+07 10.000 19.780 0.130 1.991 1.440000e+11 1.440e+10 1 7 4.018e+07 10.500 19.690 0.180 1.892 1.440000e+11 1.371e+10 1 8 3.516e+07 10.020 19.750 0.170 1.988 1.440000e+11 1.437e+10 2 1 1.406e+08 10.330 20.000 0.460 1.981 1.440000e+11 1.394e+10 2 2 7.031e+07 10.160 19.870 0.270 1.982 1.440000e+11 1.417e+10 2 3 4.688e+07 10.210 19.780 0.230 1.960 1.440000e+11 1.410e+10 2 4 3.516e+07 10.050 19.730 0.210 1.984 1.440000e+11 1.433e+10 2 5 2.812e+07 10.060 19.760 0.170 1.981 1.440000e+11 1.431e+10 2 6 2.344e+07 10.030 19.780 0.180 1.990 1.440000e+11 1.436e+10 2 7 2.009e+07 10.040 19.820 0.180 1.992 1.440000e+11 1.434e+10 2 8 1.758e+07 10.050 19.820 0.180 1.990 1.440000e+11 1.433e+10 3 1 9.375e+07 13.140 19.950 0.450 1.553 1.440000e+11 1.096e+10 3 2 4.688e+07 10.570 19.840 0.290 1.904 1.440000e+11 1.362e+10 3 3 3.125e+07 10.420 19.730 0.280 1.920 1.440000e+11 1.382e+10 3 4 2.344e+07 10.120 19.710 0.240 1.971 1.440000e+11 1.423e+10 3 5 1.875e+07 10.140 19.750 0.190 1.966 1.440000e+11 1.420e+10 3 6 1.562e+07 10.030 19.730 0.190 1.986 1.440000e+11 1.436e+10 3 7 1.339e+07 10.020 19.720 0.200 1.988 1.440000e+11 1.437e+10 3 8 1.172e+07 9.990 19.720 0.170 1.991 1.440000e+11 1.441e+10 4 1 7.031e+07 10.310 19.980 0.460 1.983 1.440000e+11 1.397e+10 4 2 3.516e+07 10.300 19.830 0.320 1.956 1.440000e+11 1.398e+10 4 3 2.344e+07 10.180 19.780 0.230 1.966 1.440000e+11 1.415e+10 4 4 1.758e+07 10.070 19.750 0.220 1.983 1.440000e+11 1.430e+10 4 5 1.406e+07 10.090 19.750 0.190 1.976 1.440000e+11 1.427e+10 4 6 1.172e+07 10.020 19.720 0.190 1.987 1.440000e+11 1.437e+10 4 7 1.004e+07 10.040 19.780 0.190 1.989 1.440000e+11 1.434e+10 4 8 8.789e+06 10.000 19.750 0.160 1.991 1.440000e+11 1.440e+10 5 1 5.625e+07 11.580 19.930 0.500 1.764 1.440000e+11 1.244e+10 5 2 2.812e+07 10.300 19.830 0.320 1.956 1.440000e+11 1.398e+10 5 3 1.875e+07 10.240 19.760 0.240 1.953 1.440000e+11 1.406e+10 5 4 1.406e+07 10.140 19.880 0.230 1.983 1.440000e+11 1.420e+10 5 5 1.125e+07 10.040 19.730 0.200 1.985 1.440000e+11 1.434e+10 5 6 9.375e+06 10.030 19.770 0.200 1.991 1.440000e+11 1.436e+10 5 7 8.036e+06 10.030 19.780 0.170 1.989 1.440000e+11 1.436e+10 5 8 7.031e+06 10.000 19.750 0.180 1.993 1.440000e+11 1.440e+10 6 1 4.688e+07 10.340 19.910 0.560 1.980 1.440000e+11 1.393e+10 6 2 2.344e+07 10.290 19.770 0.330 1.953 1.440000e+11 1.399e+10 6 3 1.562e+07 10.150 19.770 0.270 1.974 1.440000e+11 1.419e+10 6 4 1.172e+07 10.170 19.880 0.240 1.978 1.440000e+11 1.416e+10 6 5 9.375e+06 10.080 19.780 0.240 1.986 1.440000e+11 1.429e+10 6 6 7.812e+06 10.020 19.740 0.220 1.992 1.440000e+11 1.437e+10 6 7 6.696e+06 10.050 19.760 0.200 1.986 1.440000e+11 1.433e+10 6 8 5.859e+06 10.070 19.750 0.210 1.982 1.440000e+11 1.430e+10 7 1 4.018e+07 11.220 19.880 0.530 1.819 1.440000e+11 1.283e+10 7 2 2.009e+07 10.280 19.790 0.340 1.958 1.440000e+11 1.401e+10 7 3 1.339e+07 10.190 19.760 0.250 1.964 1.440000e+11 1.413e+10 7 4 1.004e+07 10.060 19.750 0.240 1.987 1.440000e+11 1.431e+10 7 5 8.036e+06 10.070 19.750 0.240 1.985 1.440000e+11 1.430e+10 7 6 6.696e+06 10.040 19.810 0.220 1.995 1.440000e+11 1.434e+10 7 7 5.740e+06 10.050 19.780 0.210 1.989 1.440000e+11 1.433e+10 7 8 5.022e+06 10.010 19.790 0.190 1.996 1.440000e+11 1.439e+10 8 1 3.516e+07 10.320 19.900 0.470 1.974 1.440000e+11 1.395e+10 8 2 1.758e+07 10.340 19.900 0.320 1.956 1.440000e+11 1.393e+10 8 3 1.172e+07 10.130 19.770 0.290 1.980 1.440000e+11 1.422e+10 8 4 8.789e+06 10.120 19.780 0.230 1.977 1.440000e+11 1.423e+10 8 5 7.031e+06 10.040 19.790 0.200 1.991 1.440000e+11 1.434e+10 8 6 5.859e+06 10.050 19.770 0.220 1.989 1.440000e+11 1.433e+10 8 7 5.022e+06 10.030 19.800 0.200 1.994 1.440000e+11 1.436e+10 8 8 4.395e+06 10.050 19.800 0.210 1.991 1.440000e+11 1.433e+10 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/core-duo.dat0000664000175000017500000001113512207440367026213 0ustar jcorganjcorgan#D Core Duo 1.83 GHz (T2400) 1 1 5.273e+07 10.010 10.160 0.060 1.021 2.700000e+10 2.697e+09 1 2 5.273e+07 10.410 20.180 0.150 1.953 5.400000e+10 5.187e+09 1 3 3.516e+07 10.360 20.030 0.150 1.948 5.400000e+10 5.212e+09 1 4 2.637e+07 10.100 20.030 0.100 1.993 5.400000e+10 5.347e+09 1 5 2.109e+07 10.140 19.980 0.110 1.981 5.400000e+10 5.325e+09 1 6 1.758e+07 10.110 20.030 0.110 1.992 5.400000e+10 5.341e+09 1 7 1.507e+07 10.120 20.030 0.110 1.990 5.400000e+10 5.336e+09 1 8 1.318e+07 10.060 19.980 0.090 1.995 5.400000e+10 5.368e+09 2 1 5.273e+07 10.210 20.130 0.260 1.997 5.400000e+10 5.289e+09 2 2 2.637e+07 10.110 20.030 0.140 1.995 5.400000e+10 5.341e+09 2 3 1.758e+07 10.120 20.010 0.150 1.992 5.400000e+10 5.336e+09 2 4 1.318e+07 10.080 19.990 0.110 1.994 5.400000e+10 5.357e+09 2 5 1.055e+07 10.050 19.990 0.090 1.998 5.400000e+10 5.373e+09 2 6 8.789e+06 10.050 19.980 0.080 1.996 5.400000e+10 5.373e+09 2 7 7.533e+06 10.050 19.970 0.090 1.996 5.400000e+10 5.373e+09 2 8 6.592e+06 10.040 19.970 0.090 1.998 5.399999e+10 5.378e+09 3 1 3.516e+07 10.630 20.130 0.230 1.915 5.400000e+10 5.080e+09 3 2 1.758e+07 10.120 20.020 0.170 1.995 5.400000e+10 5.336e+09 3 3 1.172e+07 10.140 20.050 0.130 1.990 5.400000e+10 5.325e+09 3 4 8.789e+06 10.070 20.010 0.100 1.997 5.400000e+10 5.362e+09 3 5 7.031e+06 10.060 19.980 0.100 1.996 5.400000e+10 5.368e+09 3 6 5.859e+06 10.060 20.000 0.100 1.998 5.400000e+10 5.368e+09 3 7 5.022e+06 10.050 20.010 0.070 1.998 5.400000e+10 5.373e+09 3 8 4.395e+06 10.050 19.990 0.070 1.996 5.400000e+10 5.373e+09 4 1 2.637e+07 10.180 20.080 0.240 1.996 5.400000e+10 5.305e+09 4 2 1.318e+07 10.140 20.000 0.180 1.990 5.400000e+10 5.325e+09 4 3 8.789e+06 10.110 20.020 0.120 1.992 5.400000e+10 5.341e+09 4 4 6.592e+06 10.080 20.020 0.090 1.995 5.399999e+10 5.357e+09 4 5 5.273e+06 10.050 19.990 0.090 1.998 5.399999e+10 5.373e+09 4 6 4.395e+06 10.080 20.010 0.080 1.993 5.400000e+10 5.357e+09 4 7 3.767e+06 10.070 20.000 0.080 1.994 5.400000e+10 5.362e+09 4 8 3.296e+06 10.050 20.000 0.080 1.998 5.399999e+10 5.373e+09 5 1 2.109e+07 11.240 20.080 0.260 1.810 5.400000e+10 4.804e+09 5 2 1.055e+07 10.130 19.990 0.150 1.988 5.400000e+10 5.331e+09 5 3 7.031e+06 10.100 20.020 0.120 1.994 5.400000e+10 5.347e+09 5 4 5.273e+06 10.070 20.000 0.090 1.995 5.399999e+10 5.362e+09 5 5 4.219e+06 10.100 20.040 0.090 1.993 5.400000e+10 5.347e+09 5 6 3.516e+06 10.080 20.000 0.090 1.993 5.400000e+10 5.357e+09 5 7 3.013e+06 10.070 20.000 0.100 1.996 5.399998e+10 5.362e+09 5 8 2.637e+06 10.070 20.000 0.090 1.995 5.399998e+10 5.362e+09 6 1 1.758e+07 10.220 20.100 0.290 1.995 5.400000e+10 5.284e+09 6 2 8.789e+06 10.080 20.010 0.130 1.998 5.400000e+10 5.357e+09 6 3 5.859e+06 10.090 20.030 0.120 1.997 5.400000e+10 5.352e+09 6 4 4.395e+06 10.100 20.030 0.080 1.991 5.400000e+10 5.347e+09 6 5 3.516e+06 10.060 20.020 0.080 1.998 5.400000e+10 5.368e+09 6 6 2.930e+06 10.070 20.030 0.090 1.998 5.399999e+10 5.362e+09 6 7 2.511e+06 10.070 20.030 0.080 1.997 5.399998e+10 5.362e+09 6 8 2.197e+06 10.070 20.010 0.090 1.996 5.399998e+10 5.362e+09 7 1 1.507e+07 10.420 20.030 0.260 1.947 5.400000e+10 5.182e+09 7 2 7.533e+06 10.100 20.010 0.140 1.995 5.400000e+10 5.347e+09 7 3 5.022e+06 10.080 20.020 0.120 1.998 5.400000e+10 5.357e+09 7 4 3.767e+06 10.080 20.010 0.100 1.995 5.400000e+10 5.357e+09 7 5 3.013e+06 10.070 20.030 0.080 1.997 5.399998e+10 5.362e+09 7 6 2.511e+06 10.080 20.010 0.090 1.994 5.399998e+10 5.357e+09 7 7 2.152e+06 10.080 20.060 0.070 1.997 5.399999e+10 5.357e+09 7 8 1.883e+06 10.070 20.040 0.070 1.997 5.399998e+10 5.362e+09 8 1 1.318e+07 10.220 20.080 0.270 1.991 5.400000e+10 5.284e+09 8 2 6.592e+06 10.100 20.010 0.140 1.995 5.399999e+10 5.347e+09 8 3 4.395e+06 10.110 20.020 0.120 1.992 5.400000e+10 5.341e+09 8 4 3.296e+06 10.090 20.040 0.090 1.995 5.399999e+10 5.352e+09 8 5 2.637e+06 10.090 20.040 0.090 1.995 5.399998e+10 5.352e+09 8 6 2.197e+06 10.070 20.040 0.100 2.000 5.399998e+10 5.362e+09 8 7 1.883e+06 10.090 20.050 0.080 1.995 5.399998e+10 5.352e+09 8 8 1.648e+06 10.090 20.040 0.090 1.995 5.399999e+10 5.352e+09 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/qs21-altivec.dat0000664000175000017500000001115212207440367026710 0ustar jcorganjcorgan#D QS21 dual cell 3.2 GHz (using Altivec) 1 1 3.516e+07 9.810 10.240 0.430 1.088 1.800000e+10 1.835e+09 1 2 3.516e+07 11.650 22.840 0.750 2.025 3.600000e+10 3.090e+09 1 3 2.344e+07 9.400 24.860 0.680 2.717 3.600000e+10 3.830e+09 1 4 1.758e+07 7.800 26.820 0.740 3.533 3.600000e+10 4.615e+09 1 5 1.406e+07 8.810 25.970 0.760 3.034 3.600000e+10 4.086e+09 1 6 1.172e+07 8.110 25.710 0.740 3.261 3.600000e+10 4.439e+09 1 7 1.004e+07 7.750 26.020 0.710 3.449 3.600000e+10 4.645e+09 1 8 8.789e+06 7.290 26.600 0.690 3.743 3.600000e+10 4.938e+09 2 1 3.516e+07 10.130 20.690 0.770 2.118 3.600000e+10 3.554e+09 2 2 1.758e+07 7.240 26.820 0.920 3.831 3.600000e+10 4.972e+09 2 3 1.172e+07 8.090 26.670 0.840 3.400 3.600000e+10 4.450e+09 2 4 8.789e+06 7.480 27.010 0.790 3.717 3.600000e+10 4.813e+09 2 5 7.031e+06 7.180 26.530 0.740 3.798 3.600000e+10 5.014e+09 2 6 5.859e+06 7.060 26.590 0.730 3.870 3.600000e+10 5.099e+09 2 7 5.022e+06 7.040 26.610 0.740 3.885 3.600000e+10 5.114e+09 2 8 4.395e+06 7.090 27.020 0.730 3.914 3.600000e+10 5.078e+09 3 1 2.344e+07 9.670 25.850 1.020 2.779 3.600000e+10 3.723e+09 3 2 1.172e+07 7.700 25.940 0.930 3.490 3.600000e+10 4.675e+09 3 3 7.812e+06 7.290 26.760 0.830 3.785 3.600000e+10 4.938e+09 3 4 5.859e+06 7.210 26.900 0.800 3.842 3.600000e+10 4.993e+09 3 5 4.688e+06 7.060 26.690 0.770 3.890 3.600000e+10 5.099e+09 3 6 3.906e+06 7.060 26.830 0.810 3.915 3.600000e+10 5.099e+09 3 7 3.348e+06 6.960 26.680 0.780 3.945 3.600000e+10 5.172e+09 3 8 2.930e+06 6.960 26.600 0.770 3.932 3.599999e+10 5.172e+09 4 1 1.758e+07 7.640 28.700 1.250 3.920 3.600000e+10 4.712e+09 4 2 8.789e+06 7.230 26.640 0.940 3.815 3.600000e+10 4.979e+09 4 3 5.859e+06 7.200 26.800 0.860 3.842 3.600000e+10 5.000e+09 4 4 4.395e+06 7.110 26.900 0.840 3.902 3.600000e+10 5.063e+09 4 5 3.516e+06 7.020 26.680 0.800 3.915 3.600000e+10 5.128e+09 4 6 2.930e+06 6.950 26.700 0.800 3.957 3.599999e+10 5.180e+09 4 7 2.511e+06 6.930 26.590 0.800 3.952 3.599999e+10 5.195e+09 4 8 2.197e+06 6.960 26.570 0.790 3.931 3.599999e+10 5.172e+09 5 1 1.406e+07 8.730 26.540 1.190 3.176 3.600000e+10 4.124e+09 5 2 7.031e+06 7.270 26.450 0.960 3.770 3.600000e+10 4.952e+09 5 3 4.688e+06 7.100 26.630 0.880 3.875 3.600000e+10 5.070e+09 5 4 3.516e+06 7.050 26.700 0.850 3.908 3.600000e+10 5.106e+09 5 5 2.812e+06 6.970 26.610 0.830 3.937 3.600000e+10 5.165e+09 5 6 2.344e+06 6.980 26.710 0.840 3.947 3.600000e+10 5.158e+09 5 7 2.009e+06 6.900 26.470 0.800 3.952 3.599999e+10 5.217e+09 5 8 1.758e+06 6.940 26.580 0.820 3.948 3.599999e+10 5.187e+09 6 1 1.172e+07 8.200 26.510 1.190 3.378 3.600000e+10 4.390e+09 6 2 5.859e+06 7.210 26.590 0.970 3.822 3.600000e+10 4.993e+09 6 3 3.906e+06 7.070 26.580 0.910 3.888 3.600000e+10 5.092e+09 6 4 2.930e+06 7.090 26.750 0.860 3.894 3.599999e+10 5.078e+09 6 5 2.344e+06 7.040 26.830 0.830 3.929 3.600000e+10 5.114e+09 6 6 1.953e+06 6.960 26.600 0.830 3.941 3.600000e+10 5.172e+09 6 7 1.674e+06 6.940 26.500 0.810 3.935 3.600000e+10 5.187e+09 6 8 1.465e+06 6.940 26.540 0.830 3.944 3.599998e+10 5.187e+09 7 1 1.004e+07 7.730 26.940 1.190 3.639 3.600000e+10 4.657e+09 7 2 5.022e+06 7.240 26.600 0.980 3.809 3.600000e+10 4.972e+09 7 3 3.348e+06 7.120 26.680 0.930 3.878 3.600000e+10 5.056e+09 7 4 2.511e+06 7.070 26.840 0.890 3.922 3.599999e+10 5.092e+09 7 5 2.009e+06 6.980 26.570 0.850 3.928 3.599999e+10 5.158e+09 7 6 1.674e+06 6.950 26.530 0.840 3.938 3.600000e+10 5.180e+09 7 7 1.435e+06 6.940 26.570 0.860 3.952 3.599998e+10 5.187e+09 7 8 1.256e+06 6.980 26.590 0.840 3.930 3.599999e+10 5.158e+09 8 1 8.789e+06 7.570 27.360 1.260 3.781 3.600000e+10 4.756e+09 8 2 4.395e+06 7.130 26.460 0.980 3.849 3.600000e+10 5.049e+09 8 3 2.930e+06 7.060 26.680 0.920 3.909 3.599999e+10 5.099e+09 8 4 2.197e+06 7.040 26.670 0.880 3.913 3.599999e+10 5.114e+09 8 5 1.758e+06 6.970 26.600 0.860 3.940 3.599999e+10 5.165e+09 8 6 1.465e+06 6.940 26.490 0.840 3.938 3.599998e+10 5.187e+09 8 7 1.256e+06 6.980 26.630 0.850 3.937 3.599999e+10 5.158e+09 8 8 1.099e+06 7.010 26.820 0.860 3.949 3.599997e+10 5.136e+09 gnuradio-3.7.2.1/gnuradio-runtime/examples/mp-sched/perf-data/ps3.dat0000664000175000017500000001112112207440367025176 0ustar jcorganjcorgan#D Playstation 3 1 1 2.344e+07 9.970 9.960 0.280 1.027 1.200000e+10 1.204e+09 1 2 1.172e+07 12.590 24.430 0.400 1.972 1.200000e+10 9.531e+08 1 3 7.812e+06 12.200 22.790 0.360 1.898 1.200000e+10 9.836e+08 1 4 5.859e+06 12.450 24.440 0.360 1.992 1.200000e+10 9.639e+08 1 5 4.688e+06 12.390 24.100 0.360 1.974 1.200000e+10 9.685e+08 1 6 3.906e+06 12.360 24.200 0.370 1.988 1.200000e+10 9.709e+08 1 7 3.348e+06 12.460 24.390 0.360 1.986 1.200000e+10 9.631e+08 1 8 2.930e+06 12.440 24.400 0.360 1.990 1.200000e+10 9.646e+08 2 1 1.172e+07 12.580 24.660 0.490 1.999 1.200000e+10 9.539e+08 2 2 5.859e+06 12.480 24.290 0.420 1.980 1.200000e+10 9.615e+08 2 3 3.906e+06 12.500 24.500 0.400 1.992 1.200000e+10 9.600e+08 2 4 2.930e+06 12.440 24.400 0.390 1.993 1.200000e+10 9.646e+08 2 5 2.344e+06 12.500 24.510 0.380 1.991 1.200000e+10 9.600e+08 2 6 1.953e+06 12.450 24.480 0.380 1.997 1.200000e+10 9.639e+08 2 7 1.674e+06 12.450 24.430 0.380 1.993 1.200000e+10 9.639e+08 2 8 1.465e+06 12.430 24.450 0.380 1.998 1.199999e+10 9.654e+08 3 1 7.812e+06 12.280 23.600 0.460 1.959 1.200000e+10 9.772e+08 3 2 3.906e+06 12.690 24.760 0.430 1.985 1.200000e+10 9.456e+08 3 3 2.604e+06 12.610 24.700 0.410 1.991 1.200000e+10 9.516e+08 3 4 1.953e+06 12.440 24.410 0.400 1.994 1.200000e+10 9.646e+08 3 5 1.562e+06 12.400 24.370 0.380 1.996 1.200000e+10 9.677e+08 3 6 1.302e+06 12.440 24.450 0.380 1.996 1.200000e+10 9.646e+08 3 7 1.116e+06 12.470 24.470 0.380 1.993 1.200000e+10 9.623e+08 3 8 9.766e+05 12.440 24.440 0.380 1.995 1.199999e+10 9.646e+08 4 1 5.859e+06 12.670 24.710 0.500 1.990 1.200000e+10 9.471e+08 4 2 2.930e+06 12.600 24.600 0.440 1.987 1.200000e+10 9.524e+08 4 3 1.953e+06 12.490 24.480 0.410 1.993 1.200000e+10 9.608e+08 4 4 1.465e+06 12.400 24.340 0.400 1.995 1.199999e+10 9.677e+08 4 5 1.172e+06 12.440 24.410 0.390 1.994 1.200000e+10 9.646e+08 4 6 9.766e+05 12.440 24.440 0.390 1.996 1.199999e+10 9.646e+08 4 7 8.371e+05 12.450 24.420 0.390 1.993 1.199999e+10 9.639e+08 4 8 7.324e+05 12.370 24.310 0.380 1.996 1.199999e+10 9.701e+08 5 1 4.688e+06 12.890 24.790 0.500 1.962 1.200000e+10 9.310e+08 5 2 2.344e+06 12.620 24.680 0.450 1.991 1.200000e+10 9.509e+08 5 3 1.562e+06 12.430 24.360 0.410 1.993 1.200000e+10 9.654e+08 5 4 1.172e+06 12.420 24.390 0.410 1.997 1.200000e+10 9.662e+08 5 5 9.375e+05 12.430 24.380 0.400 1.994 1.200000e+10 9.654e+08 5 6 7.812e+05 12.400 24.340 0.400 1.995 1.200000e+10 9.677e+08 5 7 6.696e+05 12.360 24.290 0.390 1.997 1.199998e+10 9.709e+08 5 8 5.859e+05 12.420 24.370 0.390 1.994 1.199999e+10 9.662e+08 6 1 3.906e+06 12.990 25.320 0.560 1.992 1.200000e+10 9.238e+08 6 2 1.953e+06 12.610 24.550 0.440 1.982 1.200000e+10 9.516e+08 6 3 1.302e+06 12.520 24.310 0.420 1.975 1.200000e+10 9.585e+08 6 4 9.766e+05 12.460 24.310 0.420 1.985 1.199999e+10 9.631e+08 6 5 7.812e+05 12.440 24.240 0.410 1.982 1.200000e+10 9.646e+08 6 6 6.510e+05 12.430 24.170 0.410 1.977 1.199999e+10 9.654e+08 6 7 5.580e+05 12.450 24.230 0.410 1.979 1.199998e+10 9.639e+08 6 8 4.883e+05 12.490 24.190 0.420 1.970 1.199999e+10 9.608e+08 7 1 3.348e+06 13.150 24.280 0.500 1.884 1.200000e+10 9.125e+08 7 2 1.674e+06 12.480 24.170 0.430 1.971 1.200000e+10 9.615e+08 7 3 1.116e+06 12.480 24.430 0.440 1.993 1.200000e+10 9.615e+08 7 4 8.371e+05 12.380 24.270 0.420 1.994 1.199999e+10 9.693e+08 7 5 6.696e+05 12.390 24.290 0.430 1.995 1.199998e+10 9.685e+08 7 6 5.580e+05 12.430 24.300 0.430 1.990 1.199998e+10 9.654e+08 7 7 4.783e+05 12.460 24.360 0.430 1.990 1.199999e+10 9.631e+08 7 8 4.185e+05 12.460 24.340 0.430 1.988 1.199998e+10 9.631e+08 8 1 2.930e+06 12.960 24.600 0.530 1.939 1.200000e+10 9.259e+08 8 2 1.465e+06 12.580 24.240 0.440 1.962 1.199999e+10 9.539e+08 8 3 9.766e+05 12.520 24.060 0.430 1.956 1.199999e+10 9.585e+08 8 4 7.324e+05 12.420 24.200 0.410 1.981 1.199999e+10 9.662e+08 8 5 5.859e+05 12.430 24.310 0.430 1.990 1.199999e+10 9.654e+08 8 6 4.883e+05 12.430 24.130 0.420 1.975 1.199999e+10 9.654e+08 8 7 4.185e+05 12.800 24.220 0.490 1.930 1.199998e+10 9.375e+08 8 8 3.662e+05 12.460 24.340 0.430 1.988 1.199997e+10 9.631e+08 gnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/0000775000175000017500000000000012207440367023425 5ustar jcorganjcorgangnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/CMakeLists.txt0000664000175000017500000000211312207440367026162 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS volk_math.py volk_plot.py volk_test_funcs.py volk_types.py DESTINATION ${GR_PKG_DATA_DIR}/examples/volk_benchmark COMPONENT "runtime_python" ) install( FILES README DESTINATION ${GR_PKG_DATA_DIR}/examples/volk_benchmark COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/volk_types.py0000775000175000017500000001355312207440367026210 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import blocks import argparse from volk_test_funcs import * ###################################################################### def float_to_char(N): op = blocks.float_to_char() tb = helper(N, op, gr.sizeof_float, gr.sizeof_char, 1, 1) return tb ###################################################################### def float_to_int(N): op = blocks.float_to_int() tb = helper(N, op, gr.sizeof_float, gr.sizeof_int, 1, 1) return tb ###################################################################### def float_to_short(N): op = blocks.float_to_short() tb = helper(N, op, gr.sizeof_float, gr.sizeof_short, 1, 1) return tb ###################################################################### def short_to_float(N): op = blocks.short_to_float() tb = helper(N, op, gr.sizeof_short, gr.sizeof_float, 1, 1) return tb ###################################################################### def short_to_char(N): op = blocks.short_to_char() tb = helper(N, op, gr.sizeof_short, gr.sizeof_char, 1, 1) return tb ###################################################################### def char_to_short(N): op = blocks.char_to_short() tb = helper(N, op, gr.sizeof_char, gr.sizeof_short, 1, 1) ###################################################################### def char_to_float(N): op = blocks.char_to_float() tb = helper(N, op, gr.sizeof_char, gr.sizeof_float, 1, 1) ##################################################################### def int_to_float(N): op = blocks.int_to_float() tb = helper(N, op, gr.sizeof_int, gr.sizeof_float, 1, 1) return tb ###################################################################### def complex_to_float(N): op = blocks.complex_to_float() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_float, 1, 2) return tb ###################################################################### def complex_to_real(N): op = blocks.complex_to_real() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_float, 1, 1) return tb ###################################################################### def complex_to_imag(N): op = blocks.complex_to_imag() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_float, 1, 1) return tb ###################################################################### def complex_to_mag(N): op = blocks.complex_to_mag() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_float, 1, 1) return tb ###################################################################### def complex_to_mag_squared(N): op = blocks.complex_to_mag_squared() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_float, 1, 1) return tb ###################################################################### def run_tests(func, N, iters): print("Running Test: {0}".format(func.__name__)) try: tb = func(N) t = timeit(tb, iters) res = format_results(func.__name__, t) return res except AttributeError: print "\tCould not run test. Skipping." return None def main(): avail_tests = [float_to_char, float_to_int, float_to_short, short_to_float, short_to_char, char_to_short, char_to_float, int_to_float, complex_to_float, complex_to_real, complex_to_imag, complex_to_mag, complex_to_mag_squared] desc='Time an operation to compare with other implementations. \ This program runs a simple GNU Radio flowgraph to test a \ particular math function, mostly to compare the \ Volk-optimized implementation versus a regular \ implementation. The results are stored to an SQLite database \ that can then be read by volk_plot.py to plot the differences.' parser = argparse.ArgumentParser(description=desc) parser.add_argument('-L', '--label', type=str, required=True, default=None, help='Label of database table [default: %(default)s]') parser.add_argument('-D', '--database', type=str, default="volk_results.db", help='Database file to store data in [default: %(default)s]') parser.add_argument('-N', '--nitems', type=float, default=1e9, help='Number of items per iterations [default: %(default)s]') parser.add_argument('-I', '--iterations', type=int, default=20, help='Number of iterations [default: %(default)s]') parser.add_argument('--tests', type=int, nargs='*', choices=xrange(len(avail_tests)), help='A list of tests to run; can be a single test or a \ space-separated list.') parser.add_argument('--list', action='store_true', help='List the available tests') parser.add_argument('--all', action='store_true', help='Run all tests') args = parser.parse_args() if(args.list): print "Available Tests to Run:" print "\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)]) sys.exit(0) N = int(args.nitems) iters = args.iterations label = args.label conn = create_connection(args.database) new_table(conn, label) if args.all: tests = xrange(len(avail_tests)) else: tests = args.tests for test in tests: res = run_tests(avail_tests[test], N, iters) if res is not None: replace_results(conn, label, N, iters, res) if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/volk_test_funcs.py0000664000175000017500000001120112207440367027202 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import blocks import math, sys, os, time try: import scipy except ImportError: sys.stderr.write("Unable to import Scipy (www.scipy.org)\n") sys.exit(1) try: import sqlite3 except ImportError: sys.stderr.write("Unable to import sqlite3: requires Python 2.5\n") sys.exit(1) def execute(conn, cmd): ''' Executes the command cmd to the database opened in connection conn. ''' c = conn.cursor() c.execute(cmd) conn.commit() c.close() def create_connection(database): ''' Returns a connection object to the SQLite database. ''' return sqlite3.connect(database) def new_table(conn, tablename): ''' Create a new table for results. All results are in the form: [kernel | nitems | iters | avg. time | variance | max time | min time ] Each table is meant as a different setting (e.g., volk_aligned, volk_unaligned, etc.) ''' cols = "kernel text, nitems int, iters int, avg real, var real, max real, min real" cmd = "create table if not exists {0} ({1})".format( tablename, cols) execute(conn, cmd) def replace_results(conn, tablename, nitems, iters, res): ''' Inserts or replaces the results 'res' dictionary values into the table. This deletes all old entries of the kernel in this table. ''' cmd = "DELETE FROM {0} where kernel='{1}'".format(tablename, res["kernel"]) execute(conn, cmd) insert_results(conn, tablename, nitems, iters, res) def insert_results(conn, tablename, nitems, iters, res): ''' Inserts the results dictionary values into the table. ''' cols = "kernel, nitems, iters, avg, var, max, min" cmd = "INSERT INTO {0} ({1}) VALUES ('{2}', {3}, {4}, {5}, {6}, {7}, {8})".format( tablename, cols, res["kernel"], nitems, iters, res["avg"], res["var"], res["max"], res["min"]) execute(conn, cmd) def list_tables(conn): ''' Returns a list of all tables in the database. ''' cmd = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" c = conn.cursor() c.execute(cmd) t = c.fetchall() c.close() return t def get_results(conn, tablename): ''' Gets all results in tablename. ''' cmd = "SELECT * FROM {0}".format(tablename) c = conn.cursor() c.execute(cmd) fetched = c.fetchall() c.close() res = list() for f in fetched: r = dict() r['kernel'] = f[0] r['nitems'] = f[1] r['iters'] = f[2] r['avg'] = f[3] r['var'] = f[4] r['min'] = f[5] r['max'] = f[6] res.append(r) return res class helper(gr.top_block): ''' Helper function to run the tests. The parameters are: N: number of items to process (int) op: The GR block/hier_block to test isizeof: the sizeof the input type osizeof: the sizeof the output type nsrcs: number of inputs to the op nsnks: number of outputs of the op This function can only handle blocks where all inputs are the same datatype and all outputs are the same data type ''' def __init__(self, N, op, isizeof=gr.sizeof_gr_complex, osizeof=gr.sizeof_gr_complex, nsrcs=1, nsnks=1): gr.top_block.__init__(self, "helper") self.op = op self.srcs = [] self.snks = [] self.head = blocks.head(isizeof, N) for n in xrange(nsrcs): self.srcs.append(blocks.null_source(isizeof)) for n in xrange(nsnks): self.snks.append(blocks.null_sink(osizeof)) self.connect(self.srcs[0], self.head, (self.op,0)) for n in xrange(1, nsrcs): self.connect(self.srcs[n], (self.op,n)) for n in xrange(nsnks): self.connect((self.op,n), self.snks[n]) def timeit(tb, iterations): ''' Given a top block, this function times it for a number of iterations and stores the time in a list that is returned. ''' r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" times = [] for i in xrange(iterations): start_time = time.time() tb.run() end_time = time.time() tb.head.reset() times.append(end_time - start_time) return times def format_results(kernel, times): ''' Convinience function to convert the results of the timeit function into a dictionary. ''' res = dict() res["kernel"] = kernel res["avg"] = scipy.mean(times) res["var"] = scipy.var(times) res["max"] = max(times) res["min"] = min(times) return res gnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/volk_plot.py0000775000175000017500000001374512207440367026025 0ustar jcorganjcorgan#!/usr/bin/env python import sys, math import argparse from volk_test_funcs import * try: import matplotlib import matplotlib.pyplot as plt except ImportError: sys.stderr.write("Could not import Matplotlib (http://matplotlib.sourceforge.net/)\n") sys.exit(1) def main(): desc='Plot Volk performance results from a SQLite database. ' + \ 'Run one of the volk tests first (e.g, volk_math.py)' parser = argparse.ArgumentParser(description=desc) parser.add_argument('-D', '--database', type=str, default='volk_results.db', help='Database file to read data from [default: %(default)s]') parser.add_argument('-E', '--errorbars', action='store_true', default=False, help='Show error bars (1 standard dev.)') parser.add_argument('-P', '--plot', type=str, choices=['mean', 'min', 'max'], default='mean', help='Set the type of plot to produce [default: %(default)s]') parser.add_argument('-%', '--percent', type=str, default=None, metavar="table", help='Show percent difference to the given type [default: %(default)s]') args = parser.parse_args() # Set up global plotting properties matplotlib.rcParams['figure.subplot.bottom'] = 0.2 matplotlib.rcParams['figure.subplot.top'] = 0.95 matplotlib.rcParams['figure.subplot.right'] = 0.98 matplotlib.rcParams['ytick.labelsize'] = 16 matplotlib.rcParams['xtick.labelsize'] = 16 matplotlib.rcParams['legend.fontsize'] = 18 # Get list of tables to compare conn = create_connection(args.database) tables = list_tables(conn) M = len(tables) # Colors to distinguish each table in the bar graph # More than 5 tables will wrap around to the start. colors = ['b', 'r', 'g', 'm', 'k'] # Set up figure for plotting f0 = plt.figure(0, facecolor='w', figsize=(14,10)) s0 = f0.add_subplot(1,1,1) # Create a register of names that exist in all tables tmp_regs = [] for table in tables: # Get results from the next table res = get_results(conn, table[0]) tmp_regs.append(list()) for r in res: try: tmp_regs[-1].index(r['kernel']) except ValueError: tmp_regs[-1].append(r['kernel']) # Get only those names that are common in all tables name_reg = tmp_regs[0] for t in tmp_regs[1:]: name_reg = list(set(name_reg) & set(t)) name_reg.sort() # Pull the data out for each table into a dictionary # we can ref the table by it's name and the data associated # with a given kernel in name_reg by it's name. # This ensures there is no sorting issue with the data in the # dictionary, so the kernels are plotted against each other. table_data = dict() for i,table in enumerate(tables): # Get results from the next table res = get_results(conn, table[0]) data = dict() for r in res: data[r['kernel']] = r table_data[table[0]] = data if args.percent is not None: for i,t in enumerate(table_data): if args.percent == t: norm_data = [] for name in name_reg: if(args.plot == 'max'): norm_data.append(table_data[t][name]['max']) elif(args.plot == 'min'): norm_data.append(table_data[t][name]['min']) elif(args.plot == 'mean'): norm_data.append(table_data[t][name]['avg']) # Plot the results x0 = xrange(len(name_reg)) i = 0 for t in (table_data): ydata = [] stds = [] for name in name_reg: stds.append(math.sqrt(table_data[t][name]['var'])) if(args.plot == 'max'): ydata.append(table_data[t][name]['max']) elif(args.plot == 'min'): ydata.append(table_data[t][name]['min']) elif(args.plot == 'mean'): ydata.append(table_data[t][name]['avg']) if args.percent is not None: ydata = [-100*(y-n)/y for y,n in zip(ydata,norm_data)] if(args.percent != t): # makes x values for this data set placement # width of bars depends on number of comparisons wdth = 0.80/(M-1) x1 = [x + i*wdth for x in x0] i += 1 s0.bar(x1, ydata, width=wdth, color=colors[(i-1)%M], label=t, edgecolor='k', linewidth=2) else: # makes x values for this data set placement # width of bars depends on number of comparisons wdth = 0.80/M x1 = [x + i*wdth for x in x0] i += 1 if(args.errorbars is False): s0.bar(x1, ydata, width=wdth, color=colors[(i-1)%M], label=t, edgecolor='k', linewidth=2) else: s0.bar(x1, ydata, width=wdth, yerr=stds, color=colors[i%M], label=t, edgecolor='k', linewidth=2, error_kw={"ecolor": 'k', "capsize":5, "linewidth":2}) nitems = res[0]['nitems'] if args.percent is None: s0.set_ylabel("Processing time (sec) [{0:G} items]".format(nitems), fontsize=22, fontweight='bold', horizontalalignment='center') else: s0.set_ylabel("% Improvement over {0} [{1:G} items]".format( args.percent, nitems), fontsize=22, fontweight='bold') s0.legend() s0.set_xticks(x0) s0.set_xticklabels(name_reg) for label in s0.xaxis.get_ticklabels(): label.set_rotation(45) label.set_fontsize(16) plt.show() if __name__ == "__main__": main() gnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/README0000664000175000017500000002536712207440367024322 0ustar jcorganjcorganVOLK Benchmarking Scripts The Python programs in this directory are designed to help benchmark and compare Volk enhancements to GNU Radio. There are two kinds of scripts here: collecting data and displaying the data. Data collection is done by running a Volk testing script that will populate a SQLite database file (volk_results.db by default). The plotting utility provided here reads from the database files and plots bar graphs to compare the different installations. These benchmarks can be used to compare previous versions of GNU Radio to using Volk; they can be used to compare different Volk proto-kernels, as well, by editing the volk_config file; or they could be used to compare performance between different machines and/or processors. ====================================================================== Volk Profiling Before doing any kind of Volk benchmarking, it is important to run the volk_profile program. The profiler will build a config file for the best SIMD architecture for your processor. Run volk_profile that is installed into $PREFIX/bin. This program tests all known Volk kernels for each proto-kernel supported by the processor. When finished, it will write to $HOME/.volk/volk_config the best architecture for the VOLK function. This file is read when using a function to know the best version of the function to execute. The volk_config file contains a line for each kernel, where each line looks like: volk_ The architecture will be something like (sse, sse2, sse3, avx, neon, etc.), depending on your processor. ====================================================================== Benchmark Tests There are currently two benchmark scripts defined for collecting data. There is one that runs through the type conversions that have been converted to Volk (volk_types.py) and the other runs through the math operators converted to using Volk (volk_math.py). Script prototypes Both have the same structure for use: ---------------------------------------------------------------------- ./volk_.py [-h] -L LABEL [-D DATABASE] [-N NITEMS] [-I ITERATIONS] [--tests [{0,1,2,3} [{0,1,2,3} ...]]] [--list] [--all] optional arguments: -h, --help show this help message and exit -L LABEL, --label LABEL Label of database table [default: None] -D DATABASE, --database DATABASE Database file to store data in [default: volk_results.db] -N NITEMS, --nitems NITEMS Number of items per iterations [default: 1000000000.0] -I ITERATIONS, --iterations ITERATIONS Number of iterations [default: 20] --tests [{0,1,2,3} [{0,1,2,3} ...]] A list of tests to run; can be a single test or a space-separated list. --list List the available tests --all Run all tests ---------------------------------------------------------------------- To run, you specify the tests to run and a label to store along with the results. To find out what the available tests are, use the '--list' option. To specify a subset of tests, use the '--tests' with space-separated list of tests numbers (e.g., --tests 0 2 4 9). Use the '--all' to run all tests. The label specified is used as an identifier for the benchmarking currently being done. This is required as it is important in organizing the data in the database (each label is its own table). Usually, the label will specify the type of run being done, such as "volk_aligned" or "v3_5_1". In these cases, the "volk_aligned" label says that this is for a benchmarking using the GNU Radio version that uses the aligned scheduler and Volk calls in the work functions. The "v3_5_1" label is if you were benchmarking an installed version 3.5.1 of GNU Radio, which is pre-Volk. These will then be plotted against each other to see the timing differences. The 'database' option will output the results to a new database file. This can be useful for separating the output of different runs or of different benchmarks, such as the types versus the math scripts, say, or to distinguish results from different computers. If rerun using the same database and label, the entries in the table will simply be replaced by the new results. It is often useful to use the 'sqlitebrowser' program to interrogate the database file farther, if you are interested in the structure or the raw data. Other parameters of this script set the number of items to process and number of iterations to use when computing the benchmarking data. These default to 1 billion samples per iteration over 20 iterations. Expect a default run to take a long time. Using the '-N' and '-I' options can be used to change the runtime of the benchmarks but are set high to remove problems of variance between iterations. ====================================================================== Plotting Results The volk_plot.py script reads a given database file and plots the results. The default behavior is to read all of the labels stored in the database and plot them as data sets on a bar graph. This shows the average time taken to process the number of items given. The options for the plotting script are: usage: volk_plot.py [-h] [-D DATABASE] [-E] [-P {mean,min,max}] [-% table] Plot Volk performance results from a SQLite database. Run one of the volk tests first (e.g, volk_math.py) ---------------------------------------------------------------------- optional arguments: -h, --help show this help message and exit -D DATABASE, --database DATABASE Database file to read data from [default: volk_results.db] -E, --errorbars Show error bars (1 standard dev.) -P {mean,min,max}, --plot {mean,min,max} Set the type of plot to produce [default: mean] -% table, --percent table Show percent difference to the given type [default: None] ---------------------------------------------------------------------- This script allows you to specify the database used (-D), but will always read all rows from all tables from it and display them. You can also turn on plotting error bars (1 standard deviation the mean). Be careful, though, as some older versions of Matplotlib might have an issue with this option. The mean time is only one possible statistic that we might be interested in when looking at the data. It represents the average user experience when running a given block. On the other hand, the minimum runtime best represents the actual performance of a block given minimal OS interruptions while running. Right now, the data collected includes the mean, variance, min, and max over the number of iterations given. Using the '-P' option, you can specify the type of data to plot (mean, min, or max). Another useful way of looking at the data is to compare the percent improvement of a benchmark compared to another. This is done using the '-%' option with the provided table (or label) as the baseline. So if we were interested in comparing how much the 'volk_aligned' was over 'v3_5_1', we would specify '-% v3_5_1' to see this. The plot would then only show the percent speedup observed using Volk for each of the blocks. ====================================================================== Benchmarking Walkthrough This will walk through an example of benchmarking the new Volk implementation versus the pre-Volk GNU Radio. It also shows how to look at the SIMD optimized versions versus the generic implementations. Since we introduced Volk in GNU Radio 3.5.2, we will use the following labels for our data: 1.) volk_aligned: v3.5.2 with volk_profile results in .volk/volk_config 2.) v3_5_2: v3.5.2 with the generic (non-SIMD) calls to Volk 3.) v3_5_1: an installation of GNU Radio from version v3.5.1 We assume that we have installed two versions of GNU Radio. v3.5.2 installed into /opt/gr-3_5_2 v3.5.1 installed into /opt/gr-3_5_1 To test cases 1 and 2 above, we have to run GNU Radio from the v3.5.2 installation, so we set the following environmental variables. Note that this is written for Ubuntu 11.10. These commands and directories may have to be changed depending on your OS and versions. export LD_LIBRARY_PATH=/opt/gr-3_5_2/lib export LD_LIBRARY_PATH=/opt/gr-3_5_2/lib/python2.7/dist-packages Now we can run the benchmark tests, so we will focus on the math operators: ./volk_math.py -D volk_results_math.db --all -L volk_aligned When this finishes, the 'volk_results_math.db' will contain our results for this run. We next want to run the generic, non-SIMD, calls. This can be done by changing the Volk kernel settings in $HOME/.volk/volk_config. First, make a backup of this file. Then edit it and change all architecture calls (sse, sse2, etc.) to 'generic.' Now, Volk will only call the generic versions of these functions. So we rerun the benchmark with: ./volk_math.py -D volk_results_math.db --all -L v3_5_2 Notice that the only thing changed here was the label to 'v3_5_2'. Next, we want to collect data for the non-Volk version of GNU Radio. This is important because some internals to GNU Radio were made when adding support for Volk, so it is nice to know what the differences do to our performance. First, we set the environmental variables to point to the v3.5.1 installation: export LD_LIBRARY_PATH=/opt/gr-3_5_1/lib export LD_LIBRARY_PATH=/opt/gr-3_5_1/lib/python2.7/dist-packages And when we run the test, we use the same command line, but the GNU Radio libraries and Python files used come from v3.5.1. We also change the label to indicate the different version to store. ./volk_math.py -D volk_results_math.db --all -L v3_5_1 We now have a database populated with three tables for the three different labels. We can plot them all together by simply running: ./volk_plot.py -D volk_results_math.db This will show the average run times for each of the three configurations for all math functions tested. We might also be interested to see the difference in performance from the v3.5.1 version, so we can run: ./volk_plot.py -D volk_results_math.db -% v3_5_1 That will plot both the 'volk_aligned' and 'v3_5_2' as a percentage improvement over v3_5_1. A positive value indicates that this version runs faster than the v3.5.1 version. ---------------------------------------------------------------------- Another interesting test case could be to compare results on different processors. So if you have different generation Intels, AMD, or whatever, you can simply pass the .db file around and run the Volk benchmark script to populate the database with different results. For this, you would specify a label like '-L i7_2620M' that indicates the processor type to uniquely ID the data. gnuradio-3.7.2.1/gnuradio-runtime/examples/volk_benchmark/volk_math.py0000775000175000017500000001232612207440367025772 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import blocks import argparse from volk_test_funcs import * try: from gnuradio import blocks except ImportError: sys.stderr.write("This example requires gr-blocks.\n") def multiply_const_cc(N): k = 3.3 op = blocks.multiply_const_cc(k) tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_gr_complex, 1, 1) return tb ###################################################################### def multiply_const_ff(N): k = 3.3 op = blocks.multiply_const_ff(k) tb = helper(N, op, gr.sizeof_float, gr.sizeof_float, 1, 1) return tb ###################################################################### def multiply_cc(N): op = blocks.multiply_cc(1) tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_gr_complex, 2, 1) return tb ###################################################################### def multiply_ff(N): op = blocks.multiply_ff() tb = helper(N, op, gr.sizeof_float, gr.sizeof_float, 2, 1) return tb ###################################################################### def add_ff(N): op = blocks.add_ff() tb = helper(N, op, gr.sizeof_float, gr.sizeof_float, 2, 1) return tb ###################################################################### def conjugate_cc(N): op = blocks.conjugate_cc() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_gr_complex, 1, 1) return tb ###################################################################### def multiply_conjugate_cc(N): try: op = blocks.multiply_conjugate_cc() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_gr_complex, 2, 1) return tb except AttributeError: class s(gr.hier_block2): def __init__(self): gr.hier_block2.__init__(self, "s", gr.io_signature(2, 2, gr.sizeof_gr_complex), gr.io_signature(1, 1, gr.sizeof_gr_complex)) conj = blocks.conjugate_cc() mult = blocks.multiply_cc() self.connect((self,0), (mult,0)) self.connect((self,1), conj, (mult,1)) self.connect(mult, self) op = s() tb = helper(N, op, gr.sizeof_gr_complex, gr.sizeof_gr_complex, 2, 1) return tb ###################################################################### def run_tests(func, N, iters): print("Running Test: {0}".format(func.__name__)) try: tb = func(N) t = timeit(tb, iters) res = format_results(func.__name__, t) return res except AttributeError: print "\tCould not run test. Skipping." return None def main(): avail_tests = [multiply_const_cc, multiply_const_ff, multiply_cc, multiply_ff, add_ff, conjugate_cc, multiply_conjugate_cc] desc='Time an operation to compare with other implementations. \ This program runs a simple GNU Radio flowgraph to test a \ particular math function, mostly to compare the \ Volk-optimized implementation versus a regular \ implementation. The results are stored to an SQLite database \ that can then be read by volk_plot.py to plot the differences.' parser = argparse.ArgumentParser(description=desc) parser.add_argument('-L', '--label', type=str, required=True, default=None, help='Label of database table [default: %(default)s]') parser.add_argument('-D', '--database', type=str, default="volk_results.db", help='Database file to store data in [default: %(default)s]') parser.add_argument('-N', '--nitems', type=float, default=1e9, help='Number of items per iterations [default: %(default)s]') parser.add_argument('-I', '--iterations', type=int, default=20, help='Number of iterations [default: %(default)s]') parser.add_argument('--tests', type=int, nargs='*', choices=xrange(len(avail_tests)), help='A list of tests to run; can be a single test or a \ space-separated list.') parser.add_argument('--list', action='store_true', help='List the available tests') parser.add_argument('--all', action='store_true', help='Run all tests') args = parser.parse_args() if(args.list): print "Available Tests to Run:" print "\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)]) sys.exit(0) N = int(args.nitems) iters = args.iterations label = args.label conn = create_connection(args.database) new_table(conn, label) if args.all: tests = xrange(len(avail_tests)) else: tests = args.tests for test in tests: res = run_tests(avail_tests[test], N, iters) if res is not None: replace_results(conn, label, N, iters, res) if __name__ == "__main__": try: main() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gnuradio-runtime/gnuradio-runtime.conf.in0000664000175000017500000000210512207440367023365 0ustar jcorganjcorgan# This file contains system wide configuration data for GNU Radio. # You may override any setting on a per-user basis by editing # ~/.gnuradio/config.conf [DEFAULT] verbose = False # The maximum number of messages a block will store up before pruning # the queue by popping messages from the front. max_messages = 100 [LOG] # Levels can be (case insensitive): # DEBUG, INFO, WARN, TRACE, ERROR, ALERT, CRIT, FATAL, EMERG log_level = debug debug_level = emerg # These file names can either be 'stdout' to output to standard output # or 'stderr' to output to standard error. Any other string will # create a file in which to output the logging information. An empty # string or no value here will ignore this level of configuration # completely. log_file = stdout debug_file = stderr # Used for advanced configuration of the logger #log_config = @CMAKE_INSTALL_PREFIX@/etc/gnuradio/gr_log_default.xml [PerfCounters] on = False export = True clock = thread #clock = monotonic [ControlPort] on = False edges_list = False config = # @CMAKE_INSTALL_PREFIX@/etc/gnuradio/ctrlport.conf gnuradio-3.7.2.1/gr-fft/0000755000175000017500000000000012207440367014514 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/CMakeLists.txt0000664000175000017500000000656212207440367017267 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) find_package(FFTW3f) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-fft" ENABLE_GR_FFT ENABLE_VOLK Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_BLOCKS FFTW3F_FOUND ) GR_SET_GLOBAL(GR_FFT_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/include ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_FFT) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_FFT_DESCRIPTION "GNU Radio FFT Blocks") CPACK_COMPONENT("fft_runtime" GROUP "FFT" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("fft_devel" GROUP "FFT" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("fft_python" GROUP "FFT" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;fft_runtime" ) CPACK_COMPONENT("fft_swig" GROUP "FFT" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;fft_python;fft_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/fft) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/fft) add_subdirectory(grc) endif(ENABLE_PYTHON) #add_subdirectory(examples) add_subdirectory(doc) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-fft.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fft.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fft.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "fft_devel" ) endif(ENABLE_GR_FFT) gnuradio-3.7.2.1/gr-fft/include/0000775000175000017500000000000012207440367016141 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/include/gnuradio/0000775000175000017500000000000012207440367017751 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/0000775000175000017500000000000012245466767020546 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/CMakeLists.txt0000664000175000017500000000241212237515112023261 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h fft.h fft_vcc.h fft_vfc.h goertzel.h goertzel_fc.h window.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/fft COMPONENT "fft_devel" ) if(ENABLE_GR_CTRLPORT) install(FILES ctrlport_probe_psd.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/fft COMPONENT "fft_devel" ) endif(ENABLE_GR_CTRLPORT) gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/goertzel.h0000664000175000017500000000327112207440367022537 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_IMPL_GOERTZEL_H #define INCLUDED_FFT_IMPL_GOERTZEL_H #include #include namespace gr { namespace fft { /*! * \brief Implements Goertzel single-bin DFT calculation * \ingroup misc */ class FFT_API goertzel { public: goertzel(int rate, int len, float freq); void set_params(int rate, int len, float freq); // Process a input array gr_complex batch(float *in); // Process sample by sample void input(const float &in); gr_complex output(); bool ready() const { return d_processed == d_len; } private: float d_d1; float d_d2; float d_wr; float d_wi; int d_len; int d_processed; }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_IMPL_GOERTZEL_H */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/ctrlport_probe_psd.h0000664000175000017500000000413612207440367024613 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE_PSD_H #define INCLUDED_CTRLPORT_PROBE_PSD_H #include #include namespace gr { namespace fft { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block holds * the latest \p len number of complex samples so that every query * by a ControlPort client will get the same length vector. */ class FFT_API ctrlport_probe_psd : virtual public gr::sync_block { public: typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. * \param len Number of samples to transmit. */ static sptr make(const std::string &id, const std::string &desc, int len); virtual std::vector get() = 0; virtual void set_length(int len) = 0; virtual int length() const = 0; }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE_PSD_H */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/window.h0000664000175000017500000002132012245466767022224 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2007,2008,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_WINDOW_H #define INCLUDED_FFT_WINDOW_H #include #include #include #include namespace gr { namespace fft { class FFT_API window { public: enum win_type { WIN_NONE = -1, //!< don't use a window WIN_HAMMING = 0, //!< Hamming window; max attenuation 53 dB WIN_HANN = 1, //!< Hann window; max attenuation 44 dB WIN_BLACKMAN = 2, //!< Blackman window; max attenuation 74 dB WIN_RECTANGULAR = 3, //!< Basic rectangular window WIN_KAISER = 4, //!< Kaiser window; max attenuation a function of beta, google it WIN_BLACKMAN_hARRIS = 5, //!< Blackman-harris window WIN_BLACKMAN_HARRIS = 5, //!< alias to WIN_BLACKMAN_hARRIS for capitalization consistency WIN_BARTLETT = 6, //!< Barlett (triangular) window WIN_FLATTOP = 7, //!< flat top window; useful in FFTs }; /*! * \brief Helper function to build cosine-based windows. 3-coefficient version. */ static std::vector coswindow(int ntaps, float c0, float c1, float c2); /*! * \brief Helper function to build cosine-based windows. 4-coefficient version. */ static std::vector coswindow(int ntaps, float c0, float c1, float c2, float c3); /*! * \brief Helper function to build cosine-based windows. 5-coefficient version. */ static std::vector coswindow(int ntaps, float c0, float c1, float c2, float c3, float c4); /*! * \brief Build a rectangular window. * * Taps are flat across the window. * * \param ntaps Number of coefficients in the window. */ static std::vector rectangular(int ntaps); /*! * \brief Build a Hamming window. * * See: *
       *   A. V. Oppenheim and R. W. Schafer, "Discrete-Time
       *   Signal Processing," Upper Saddle River, N.J.: Prentice
       *   Hall, 2010, pp. 535-538.
       * 
* * \param ntaps Number of coefficients in the window. */ static std::vector hamming(int ntaps); /*! * \brief Build a Hann window (sometimes known as Hanning). * * See: *
       *   A. V. Oppenheim and R. W. Schafer, "Discrete-Time
       *   Signal Processing," Upper Saddle River, N.J.: Prentice
       *   Hall, 2010, pp. 535-538.
       * 
* * \param ntaps Number of coefficients in the window. */ static std::vector hann(int ntaps); /*! * \brief Alias to build a Hann window. * * \param ntaps Number of coefficients in the window. */ static std::vector hanning(int ntaps); /*! * \brief Build an exact Blackman window. * * See: *
       *   A. V. Oppenheim and R. W. Schafer, "Discrete-Time
       *   Signal Processing," Upper Saddle River, N.J.: Prentice
       *   Hall, 2010, pp. 535-538.
       * 
* * \param ntaps Number of coefficients in the window. */ static std::vector blackman(int ntaps); /*! * \brief Build Blackman window, variation 1. */ static std::vector blackman2(int ntaps); /*! * \brief Build Blackman window, variation 2. */ static std::vector blackman3(int ntaps); /*! * \brief Build Blackman window, variation 3. */ static std::vector blackman4(int ntaps); /*! * \brief Build a Blackman-harris window with a given attenuation. * *
       *     f. j. harris, "On the use of windows for harmonic analysis
       *     with the discrete Fourier transforms," Proc. IEEE, Vol. 66,
       *     ppg. 51-83, Jan. 1978.
       * 
* * \param ntaps Number of coefficients in the window. * \param atten Attenuation factor. Must be [61, 67, 74, 92]. * See the above paper for details. */ static std::vector blackman_harris(int ntaps, int atten=92); /*! * Alias to gr::fft::window::blakcman_harris. */ static std::vector blackmanharris(int ntaps, int atten=92); /*! * \brief Build a Nuttal (or Blackman-Nuttal) window. * * See: http://en.wikipedia.org/wiki/Window_function#Blackman.E2.80.93Nuttall_window * * \param ntaps Number of coefficients in the window. */ static std::vector nuttal(int ntaps); /*! * \brief Alias to the Nuttal window. * * \param ntaps Number of coefficients in the window. */ static std::vector blackman_nuttal(int ntaps); /*! * \brief Build a Nuttal continuous first derivative window. * * See: http://en.wikipedia.org/wiki/Window_function#Nuttall_window.2C_continuous_first_derivative * * \param ntaps Number of coefficients in the window. */ static std::vector nuttal_cfd(int ntaps); /*! * \brief Build a Nuttal continuous first derivative window. * * See: http://en.wikipedia.org/wiki/Window_function#Flat_top_window * * \param ntaps Number of coefficients in the window. */ static std::vector flattop(int ntaps); /*! * \brief Build a Kaiser window with a given beta. * * See: *
       *     A. V. Oppenheim and R. W. Schafer, "Discrete-Time
       *     Signal Processing," Upper Saddle River, N.J.: Prentice
       *     Hall, 2010, pp. 541-545.
       * 
* * \param ntaps Number of coefficients in the window. * \param beta Shaping parameter of the window. See the * discussion in Oppenheim and Schafer. */ static std::vector kaiser(int ntaps, double beta); /*! * \brief Build a Barlett (triangular) window. * * See: *
       *   A. V. Oppenheim and R. W. Schafer, "Discrete-Time
       *   Signal Processing," Upper Saddle River, N.J.: Prentice
       *   Hall, 2010, pp. 535-538.
       * 
* * \param ntaps Number of coefficients in the window. */ static std::vector bartlett(int ntaps); static std::vector welch(int ntaps); /*! * \brief Build a Parzen (or de la Valle-Poussin) window. * * See: *
       *   A. D. Poularikas, "Handbook of Formulas and Tables for
       *   Signal Processing," Springer, Oct 28, 1998
       * 
* * \param ntaps Number of coefficients in the window. */ static std::vector parzen(int ntaps); /*! * \brief Build an exponential window with a given decay. * * See: http://en.wikipedia.org/wiki/Window_function#Exponential_or_Poisson_window * * \param ntaps Number of coefficients in the window. * \param d Decay of \p d dB over half the window length. */ static std::vector exponential(int ntaps, double d); /*! * \brief Build a Riemann window. * * See: *
       *   A. D. Poularikas, "Handbook of Formulas and Tables for
       *   Signal Processing," Springer, Oct 28, 1998
       * 
* * \param ntaps Number of coefficients in the window. */ static std::vector riemann(int ntaps); /*! * \brief Build a window using gr::fft::win_type to index the * type of window desired. * * \param type a gr::fft::win_type index for the type of window. * \param ntaps Number of coefficients in the window. * \param beta Used only for building Kaiser windows. */ static std::vector build(win_type type, int ntaps, double beta); }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_WINDOW_H */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/fft.h0000664000175000017500000001270512207440367021465 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _FFT_FFT_H_ #define _FFT_FFT_H_ /* * Wrappers for FFTW single precision 1d dft */ #include #include #include namespace gr { namespace fft { /*! \brief Helper function for allocating complex* buffers */ FFT_API gr_complex* malloc_complex(int size); /*! \brief Helper function for allocating float* buffers */ FFT_API float* malloc_float(int size); /*! \brief Helper function for allocating double* buffers */ FFT_API double* malloc_double(int size); /*! \brief Helper function for freeing fft buffers */ FFT_API void free(void *b); /*! * \brief Export reference to planner mutex for those apps that * want to use FFTW w/o using the fft_impl_fftw* classes. */ class FFT_API planner { public: typedef boost::mutex::scoped_lock scoped_lock; /*! * Return reference to planner mutex */ static boost::mutex &mutex(); }; /*! * \brief FFT: complex in, complex out * \ingroup misc */ class FFT_API fft_complex { int d_fft_size; int d_nthreads; gr_complex *d_inbuf; gr_complex *d_outbuf; void *d_plan; public: fft_complex(int fft_size, bool forward = true, int nthreads=1); virtual ~fft_complex(); /* * These return pointers to buffers owned by fft_impl_fft_complex * into which input and output take place. It's done this way in * order to ensure optimal alignment for SIMD instructions. */ gr_complex *get_inbuf() const { return d_inbuf; } gr_complex *get_outbuf() const { return d_outbuf; } int inbuf_length() const { return d_fft_size; } int outbuf_length() const { return d_fft_size; } /*! * Set the number of threads to use for caclulation. */ void set_nthreads(int n); /*! * Get the number of threads being used by FFTW */ int nthreads() const { return d_nthreads; } /*! * compute FFT. The input comes from inbuf, the output is placed in * outbuf. */ void execute(); }; /*! * \brief FFT: real in, complex out * \ingroup misc */ class FFT_API fft_real_fwd { int d_fft_size; int d_nthreads; float *d_inbuf; gr_complex *d_outbuf; void *d_plan; public: fft_real_fwd (int fft_size, int nthreads=1); virtual ~fft_real_fwd (); /* * These return pointers to buffers owned by fft_impl_fft_real_fwd * into which input and output take place. It's done this way in * order to ensure optimal alignment for SIMD instructions. */ float *get_inbuf() const { return d_inbuf; } gr_complex *get_outbuf() const { return d_outbuf; } int inbuf_length() const { return d_fft_size; } int outbuf_length() const { return d_fft_size / 2 + 1; } /*! * Set the number of threads to use for caclulation. */ void set_nthreads(int n); /*! * Get the number of threads being used by FFTW */ int nthreads() const { return d_nthreads; } /*! * compute FFT. The input comes from inbuf, the output is placed in * outbuf. */ void execute(); }; /*! * \brief FFT: complex in, float out * \ingroup misc */ class FFT_API fft_real_rev { int d_fft_size; int d_nthreads; gr_complex *d_inbuf; float *d_outbuf; void *d_plan; public: fft_real_rev(int fft_size, int nthreads=1); virtual ~fft_real_rev(); /* * These return pointers to buffers owned by fft_impl_fft_real_rev * into which input and output take place. It's done this way in * order to ensure optimal alignment for SIMD instructions. */ gr_complex *get_inbuf() const { return d_inbuf; } float *get_outbuf() const { return d_outbuf; } int inbuf_length() const { return d_fft_size / 2 + 1; } int outbuf_length() const { return d_fft_size; } /*! * Set the number of threads to use for caclulation. */ void set_nthreads(int n); /*! * Get the number of threads being used by FFTW */ int nthreads() const { return d_nthreads; } /*! * compute FFT. The input comes from inbuf, the output is placed in * outbuf. */ void execute(); }; } /* namespace fft */ } /*namespace gr */ #endif /* _FFT_FFT_H_ */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/goertzel_fc.h0000664000175000017500000000306612207440367023211 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_GOERTZEL_FC_H #define INCLUDED_FFT_GOERTZEL_FC_H #include #include namespace gr { namespace fft { /*! * \brief Goertzel single-bin DFT calculation. * \ingroup fourier_analysis_blk */ class FFT_API goertzel_fc : virtual public sync_decimator { public: // gr::fft::goertzel_fc::sptr typedef boost::shared_ptr sptr; static sptr make(int rate, int len, float freq); virtual void set_freq (float freq) = 0; virtual void set_rate (int rate) = 0; virtual float freq() = 0; virtual int rate() = 0; }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_GOERTZEL_FC_H */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/fft_vfc.h0000664000175000017500000000317112207440367022320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_FFT_VFC_H #define INCLUDED_FFT_FFT_VFC_H #include #include namespace gr { namespace fft { /*! * \brief Compute forward or reverse FFT. float vector in / complex vector out. * \ingroup fourier_analysis_blk */ class FFT_API fft_vfc : virtual public sync_block { public: // gr::fft::fft_vfc::sptr typedef boost::shared_ptr sptr; static sptr make(int fft_size, bool forward, const std::vector &window, int nthreads=1); virtual void set_nthreads(int n) = 0; virtual int nthreads() const = 0; virtual bool set_window(const std::vector &window) = 0; }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_FFT_VFC_H */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/fft_vcc.h0000664000175000017500000000325412207440367022317 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_FFT_VCC_H #define INCLUDED_FFT_FFT_VCC_H #include #include namespace gr { namespace fft { /*! * \brief Compute forward or reverse FFT. complex vector in / complex vector out. * \ingroup fourier_analysis_blk */ class FFT_API fft_vcc : virtual public sync_block { public: // gr::fft::fft_vcc::sptr typedef boost::shared_ptr sptr; static sptr make(int fft_size, bool forward, const std::vector &window, bool shift=false, int nthreads=1); virtual void set_nthreads(int n) = 0; virtual int nthreads() const = 0; virtual bool set_window(const std::vector &window) = 0; }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_FFT_VCC_H */ gnuradio-3.7.2.1/gr-fft/include/gnuradio/fft/api.h0000664000175000017500000000201512207440367021450 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_API_H #define INCLUDED_FFT_API_H #include #ifdef gnuradio_fft_EXPORTS # define FFT_API __GR_ATTR_EXPORT #else # define FFT_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_FFT_API_H */ gnuradio-3.7.2.1/gr-fft/grc/0000755000175000017500000000000012207440367015267 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/grc/CMakeLists.txt0000664000175000017500000000172212207440367020033 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install(FILES fft_block_tree.xml fft_fft_vxx.xml fft_goertzel_fc.xml fft_logpwrfft_x.xml fft_ctrlport_probe_psd.xml DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "fft_python" ) gnuradio-3.7.2.1/gr-fft/grc/fft_block_tree.xml0000664000175000017500000000215212207440367020763 0ustar jcorganjcorgan Fourier Analysis fft_vxx goertzel_fc logpwrfft_x gnuradio-3.7.2.1/gr-fft/grc/fft_ctrlport_probe_psd.xml0000664000175000017500000000276712207440367022574 0ustar jcorganjcorgan Ctrlport Probe PSD fft_ctrlport_probe_psd from gnuradio import fft fft.ctrlport_probe_psd($name, $desc, $len) set_length($len) Name name psd string Description desc PSD Plot string Length len 1024 int in complex Place this in a graph to export PSD values to a GRCP port probe. gnuradio-3.7.2.1/gr-fft/grc/fft_logpwrfft_x.xml0000664000175000017500000000337712207440367021225 0ustar jcorganjcorgan Log Power FFT logpwrfft_x from gnuradio.fft import logpwrfft logpwrfft.logpwrfft_$(type.fcn)( sample_rate=$sample_rate, fft_size=$fft_size, ref_scale=$ref_scale, frame_rate=$frame_rate, avg_alpha=$avg_alpha, average=$average, ) set_sample_rate($sample_rate) set_avg_alpha($avg_alpha) set_average($average) Input Type type enum Sample Rate sample_rate samp_rate real FFT Size fft_size 1024 int Reference Scale ref_scale 2 real Frame Rate frame_rate 30 real Average average False bool Average Alpha avg_alpha 1.0 real in $type out float $fft_size gnuradio-3.7.2.1/gr-fft/grc/fft_fft_vxx.xml0000664000175000017500000000332512207440367020341 0ustar jcorganjcorgan FFT fft_vxx from gnuradio import fft from gnuradio.fft import window #if $type() == "complex" fft.fft_vcc($fft_size, $forward, $window, $shift, $nthreads) #else fft.fft_vfc($fft_size, $forward, $window, $nthreads) #end if set_nthreads($nthreads) Input Type type enum FFT Size fft_size 1024 int Forward/Reverse forward enum Window window window.blackmanharris(1024) real_vector Shift shift enum $type.hide_shift Num. Threads nthreads 1 int in $type $fft_size out complex $fft_size gnuradio-3.7.2.1/gr-fft/grc/fft_goertzel_fc.xml0000664000175000017500000000135412207440367021160 0ustar jcorganjcorgan Goertzel goertzel_fc from gnuradio import fft fft.goertzel_fc($rate, $len, $freq) set_freq($freq) set_rate($rate) Rate rate int Length len int Frequency freq real in float out complex gnuradio-3.7.2.1/gr-fft/doc/0000755000175000017500000000000011765410647015267 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/doc/CMakeLists.txt0000644000175000017500000000151511765410647020031 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.fft DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-fft/doc/fft.dox0000644000175000017500000000121011765410647016554 0ustar jcorganjcorgan/*! \page page_fft FFT Signal Processing Blocks \section Introduction This is the gr-fft package. It contains signal processing blocks to perform FFTs and FFT-related functionality. The Python namespace is in gnuradio.fft, which would be normally imported as: \code from gnuradio import fft \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(fft) \endcode \section Dependencies The FFT blocks require the following dependencies. \li fftw3f (>= 3.0) http://www.fftw.org/download.html */ gnuradio-3.7.2.1/gr-fft/doc/README.fft0000644000175000017500000000062311765410647016726 0ustar jcorganjcorganThis is the gr-fft package. It contains signal processing blocks to perform FFTs and FFT-related functionality. The Python namespace is in gnuradio.fft, which would be normally imported as: from gnuradio import fft See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(fft) gnuradio-3.7.2.1/gr-fft/python/0000775000175000017500000000000012207440367016037 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/python/fft/0000775000175000017500000000000012237747146016626 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/python/fft/CMakeLists.txt0000664000175000017500000000317412237515112021355 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py logpwrfft.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/fft COMPONENT "fft_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-fft/python/fft/qa_goertzel.py0000775000175000017500000000400112207440367021502 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from math import pi, cos from gnuradio import gr, gr_unittest, fft, blocks class test_goertzel(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def make_tone_data(self, rate, freq): return [cos(2*pi*x*freq/rate) for x in range(rate)] def transform(self, src_data, rate, freq): src = blocks.vector_source_f(src_data, False) dft = fft.goertzel_fc(rate, rate, freq) dst = blocks.vector_sink_c() self.tb.connect(src, dft, dst) self.tb.run() return dst.data() def test_001(self): # Measure single tone magnitude rate = 8000 freq = 100 bin = freq src_data = self.make_tone_data(rate, freq) expected_result = 0.5 actual_result = abs(self.transform(src_data, rate, bin)[0]) self.assertAlmostEqual(expected_result, actual_result, places=4) def test_002(self): # Measure off frequency magnitude rate = 8000 freq = 100 bin = freq/2 src_data = self.make_tone_data(rate, freq) expected_result = 0.0 actual_result = abs(self.transform(src_data, rate, bin)[0]) self.assertAlmostEqual(expected_result, actual_result, places=4) if __name__ == '__main__': gr_unittest.run(test_goertzel, "test_goertzel.xml") gnuradio-3.7.2.1/gr-fft/python/fft/qa_fft.py0000775000175000017500000002346512207440367020445 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # import sys import random from gnuradio import gr, gr_unittest, fft, blocks primes = (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53, 59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131, 137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223, 227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311) class test_fft(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def assert_fft_ok2(self, expected_result, result_data): expected_result = expected_result[:len(result_data)] self.assertComplexTuplesAlmostEqual2 (expected_result, result_data, abs_eps=1e-9, rel_eps=4e-4) def assert_fft_float_ok2(self, expected_result, result_data, abs_eps=1e-9, rel_eps=4e-4): expected_result = expected_result[:len(result_data)] self.assertFloatTuplesAlmostEqual2 (expected_result, result_data, abs_eps, rel_eps) def test_001(self): tb = gr.top_block() fft_size = 32 src_data = tuple([complex(primes[2*i], primes[2*i+1]) for i in range(fft_size)]) expected_result = ((4377+4516j), (-1706.1268310546875+1638.4256591796875j), (-915.2083740234375+660.69427490234375j), (-660.370361328125+381.59600830078125j), (-499.96044921875+238.41630554199219j), (-462.26748657226562+152.88948059082031j), (-377.98440551757812+77.5928955078125j), (-346.85821533203125+47.152004241943359j), (-295+20j), (-286.33609008789062-22.257017135620117j), (-271.52999877929688-33.081821441650391j), (-224.6358642578125-67.019538879394531j), (-244.24473571777344-91.524826049804688j), (-203.09068298339844-108.54627227783203j), (-198.45195007324219-115.90768432617188j), (-182.97744750976562-128.12318420410156j), (-167-180j), (-130.33688354492188-173.83778381347656j), (-141.19784545898438-190.28807067871094j), (-111.09677124023438-214.48896789550781j), (-70.039543151855469-242.41630554199219j), (-68.960540771484375-228.30015563964844j), (-53.049201965332031-291.47097778320312j), (-28.695289611816406-317.64553833007812j), (57-300j), (45.301143646240234-335.69509887695312j), (91.936195373535156-373.32437133789062j), (172.09465026855469-439.275146484375j), (242.24473571777344-504.47515869140625j), (387.81732177734375-666.6788330078125j), (689.48553466796875-918.2142333984375j), (1646.539306640625-1694.1956787109375j)) src = blocks.vector_source_c(src_data) s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, fft_size) op = fft.fft_vcc(fft_size, True, [], False) v2s = blocks.vector_to_stream(gr.sizeof_gr_complex, fft_size) dst = blocks.vector_sink_c() tb.connect(src, s2v, op, v2s, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data #self.assertComplexTuplesAlmostEqual (expected_result, result_data, 5) self.assert_fft_ok2(expected_result, result_data) def test_002(self): tb = gr.top_block() fft_size = 32 tmp_data = ((4377+4516j), (-1706.1268310546875+1638.4256591796875j), (-915.2083740234375+660.69427490234375j), (-660.370361328125+381.59600830078125j), (-499.96044921875+238.41630554199219j), (-462.26748657226562+152.88948059082031j), (-377.98440551757812+77.5928955078125j), (-346.85821533203125+47.152004241943359j), (-295+20j), (-286.33609008789062-22.257017135620117j), (-271.52999877929688-33.081821441650391j), (-224.6358642578125-67.019538879394531j), (-244.24473571777344-91.524826049804688j), (-203.09068298339844-108.54627227783203j), (-198.45195007324219-115.90768432617188j), (-182.97744750976562-128.12318420410156j), (-167-180j), (-130.33688354492188-173.83778381347656j), (-141.19784545898438-190.28807067871094j), (-111.09677124023438-214.48896789550781j), (-70.039543151855469-242.41630554199219j), (-68.960540771484375-228.30015563964844j), (-53.049201965332031-291.47097778320312j), (-28.695289611816406-317.64553833007812j), (57-300j), (45.301143646240234-335.69509887695312j), (91.936195373535156-373.32437133789062j), (172.09465026855469-439.275146484375j), (242.24473571777344-504.47515869140625j), (387.81732177734375-666.6788330078125j), (689.48553466796875-918.2142333984375j), (1646.539306640625-1694.1956787109375j)) src_data = tuple([x/fft_size for x in tmp_data]) expected_result = tuple([complex(primes[2*i], primes[2*i+1]) for i in range(fft_size)]) src = blocks.vector_source_c(src_data) s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, fft_size) op = fft.fft_vcc(fft_size, False, [], False) v2s = blocks.vector_to_stream(gr.sizeof_gr_complex, fft_size) dst = blocks.vector_sink_c() tb.connect(src, s2v, op, v2s, dst) tb.run() result_data = dst.data() #print 'expected:', expected_result #print 'results: ', result_data #self.assertComplexTuplesAlmostEqual (expected_result, result_data, 5) self.assert_fft_ok2(expected_result, result_data) def test_003(self): # Same test as above, only use 2 threads tb = gr.top_block() fft_size = 32 tmp_data = ((4377+4516j), (-1706.1268310546875+1638.4256591796875j), (-915.2083740234375+660.69427490234375j), (-660.370361328125+381.59600830078125j), (-499.96044921875+238.41630554199219j), (-462.26748657226562+152.88948059082031j), (-377.98440551757812+77.5928955078125j), (-346.85821533203125+47.152004241943359j), (-295+20j), (-286.33609008789062-22.257017135620117j), (-271.52999877929688-33.081821441650391j), (-224.6358642578125-67.019538879394531j), (-244.24473571777344-91.524826049804688j), (-203.09068298339844-108.54627227783203j), (-198.45195007324219-115.90768432617188j), (-182.97744750976562-128.12318420410156j), (-167-180j), (-130.33688354492188-173.83778381347656j), (-141.19784545898438-190.28807067871094j), (-111.09677124023438-214.48896789550781j), (-70.039543151855469-242.41630554199219j), (-68.960540771484375-228.30015563964844j), (-53.049201965332031-291.47097778320312j), (-28.695289611816406-317.64553833007812j), (57-300j), (45.301143646240234-335.69509887695312j), (91.936195373535156-373.32437133789062j), (172.09465026855469-439.275146484375j), (242.24473571777344-504.47515869140625j), (387.81732177734375-666.6788330078125j), (689.48553466796875-918.2142333984375j), (1646.539306640625-1694.1956787109375j)) src_data = tuple([x/fft_size for x in tmp_data]) expected_result = tuple([complex(primes[2*i], primes[2*i+1]) for i in range(fft_size)]) nthreads = 2 src = blocks.vector_source_c(src_data) s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, fft_size) op = fft.fft_vcc(fft_size, False, [], False, nthreads) v2s = blocks.vector_to_stream(gr.sizeof_gr_complex, fft_size) dst = blocks.vector_sink_c() tb.connect(src, s2v, op, v2s, dst) tb.run() result_data = dst.data() self.assert_fft_ok2(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_fft, "test_fft.xml") gnuradio-3.7.2.1/gr-fft/python/fft/logpwrfft.py0000664000175000017500000001272112237747146021215 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import sys, math import fft_swig as fft from fft_swig import window try: from gnuradio import filter except ImportError: sys.stderr.write('fft.logpwrfft required gr-filter.\n') sys.exit(1) class _logpwrfft_base(gr.hier_block2): """ Create a log10(abs(fft)) stream chain, with real or complex input. """ def __init__(self, sample_rate, fft_size, ref_scale, frame_rate, avg_alpha, average, win=None): """ Create an log10(abs(fft)) stream chain. Provide access to the setting the filter and sample rate. Args: sample_rate: Incoming stream sample rate fft_size: Number of FFT bins ref_scale: Sets 0 dB value input amplitude frame_rate: Output frame rate avg_alpha: FFT averaging (over time) constant [0.0-1.0] average: Whether to average [True, False] win: the window taps generation function """ gr.hier_block2.__init__(self, self._name, gr.io_signature(1, 1, self._item_size), # Input signature gr.io_signature(1, 1, gr.sizeof_float*fft_size)) # Output signature self._sd = blocks.stream_to_vector_decimator(item_size=self._item_size, sample_rate=sample_rate, vec_rate=frame_rate, vec_len=fft_size) if win is None: win = window.blackmanharris fft_window = win(fft_size) fft = self._fft_block[0](fft_size, True, fft_window) window_power = sum(map(lambda x: x*x, fft_window)) c2magsq = blocks.complex_to_mag_squared(fft_size) self._avg = filter.single_pole_iir_filter_ff(1.0, fft_size) self._log = blocks.nlog10_ff(10, fft_size, -20*math.log10(fft_size) # Adjust for number of bins -10*math.log10(window_power/fft_size) # Adjust for windowing loss -20*math.log10(ref_scale/2)) # Adjust for reference scale self.connect(self, self._sd, fft, c2magsq, self._avg, self._log, self) self._average = average self._avg_alpha = avg_alpha self.set_avg_alpha(avg_alpha) self.set_average(average) def set_decimation(self, decim): """ Set the decimation on stream decimator. Args: decim: the new decimation """ self._sd.set_decimation(decim) def set_vec_rate(self, vec_rate): """ Set the vector rate on stream decimator. Args: vec_rate: the new vector rate """ self._sd.set_vec_rate(vec_rate) def set_sample_rate(self, sample_rate): """ Set the new sampling rate Args: sample_rate: the new rate """ self._sd.set_sample_rate(sample_rate) def set_average(self, average): """ Set the averaging filter on/off. Args: average: true to set averaging on """ self._average = average if self._average: self._avg.set_taps(self._avg_alpha) else: self._avg.set_taps(1.0) def set_avg_alpha(self, avg_alpha): """ Set the average alpha and set the taps if average was on. Args: avg_alpha: the new iir filter tap """ self._avg_alpha = avg_alpha self.set_average(self._average) def sample_rate(self): """ Return the current sample rate. """ return self._sd.sample_rate() def decimation(self): """ Return the current decimation. """ return self._sd.decimation() def frame_rate(self): """ Return the current frame rate. """ return self._sd.frame_rate() def average(self): """ Return whether or not averaging is being performed. """ return self._average def avg_alpha(self): """ Return averaging filter constant. """ return self._avg_alpha class logpwrfft_f(_logpwrfft_base): """ Create an fft block chain, with real input. """ _name = "logpwrfft_f" _item_size = gr.sizeof_float _fft_block = (fft.fft_vfc, ) class logpwrfft_c(_logpwrfft_base): """ Create an fft block chain, with complex input. """ _name = "logpwrfft_c" _item_size = gr.sizeof_gr_complex _fft_block = (fft.fft_vcc, ) gnuradio-3.7.2.1/gr-fft/python/fft/__init__.py0000664000175000017500000000204112237515112020716 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Fourier-transform blocks and related functions. ''' import os try: from fft_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from fft_swig import * gnuradio-3.7.2.1/gr-fft/lib/0000755000175000017500000000000012245466767015300 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/lib/CMakeLists.txt0000664000175000017500000000474312237515112020026 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${GR_FFT_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${FFTW3F_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) link_directories(${FFTW3F_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND fft_sources fft.cc fft_vcc_fftw.cc fft_vfc_fftw.cc goertzel_fc_impl.cc goertzel.cc window.cc ) if(ENABLE_GR_CTRLPORT) list(APPEND fft_sources ctrlport_probe_psd_impl.cc ) endif(ENABLE_GR_CTRLPORT) list(APPEND fft_libs gnuradio-runtime ${Boost_LIBRARIES} ${FFTW3F_LIBRARIES} ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-fft.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fft.rc @ONLY) list(APPEND fft_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-fft.rc ) endif(MSVC) if(FFTW3F_THREADS_LIBRARIES) list(APPEND fft_libs ${FFTW3F_THREADS_LIBRARIES}) add_definitions("-DFFTW3F_THREADS") endif() add_library(gnuradio-fft SHARED ${fft_sources}) target_link_libraries(gnuradio-fft ${fft_libs}) GR_LIBRARY_FOO(gnuradio-fft RUNTIME_COMPONENT "fft_runtime" DEVEL_COMPONENT "fft_devel") gnuradio-3.7.2.1/gr-fft/lib/fft_vcc_fftw.h0000664000175000017500000000340312207440367020075 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_FFT_VCC_FFTW_IMPL_H #define INCLUDED_FFT_FFT_VCC_FFTW_IMPL_H #include #include namespace gr { namespace fft { class FFT_API fft_vcc_fftw : public fft_vcc { private: fft_complex *d_fft; unsigned int d_fft_size; std::vector d_window; bool d_forward; bool d_shift; public: fft_vcc_fftw(int fft_size, bool forward, const std::vector &window, bool shift, int nthreads=1); ~fft_vcc_fftw(); void set_nthreads(int n); int nthreads() const; bool set_window(const std::vector &window); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_FFT_VCC_FFTW_IMPL_H */ gnuradio-3.7.2.1/gr-fft/lib/ctrlport_probe_psd_impl.cc0000664000175000017500000001261612207440367022530 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe_psd_impl.h" #include namespace gr { namespace fft { ctrlport_probe_psd::sptr ctrlport_probe_psd::make(const std::string &id, const std::string &desc, int len) { return gnuradio::get_initial_sptr (new ctrlport_probe_psd_impl(id, desc, len)); } ctrlport_probe_psd_impl::ctrlport_probe_psd_impl(const std::string &id, const std::string &desc, int len) : gr::sync_block("probe_psd", gr::io_signature::make(1, 1, sizeof(gr_complex)), gr::io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_len(len), d_fft(len, true, 1) { set_length(len); } ctrlport_probe_psd_impl::~ctrlport_probe_psd_impl() { } void ctrlport_probe_psd_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = d_len; } // boost::shared_mutex mutex_buffer; // mutable boost::mutex mutex_notify; // boost::condition_variable condition_buffer_ready; std::vector ctrlport_probe_psd_impl::get() { mutex_buffer.lock(); d_buffer.clear(); mutex_buffer.unlock(); // wait for condition boost::mutex::scoped_lock lock(mutex_notify); condition_buffer_ready.wait(lock); mutex_buffer.lock(); memcpy(d_fft.get_inbuf(), &d_buffer[0], d_len*sizeof(gr_complex)); d_fft.execute(); std::vector buf_copy; buf_copy.resize(d_len); gr_complex* out = d_fft.get_outbuf(); for(size_t i=0; i 8191) { std::cerr << "probe_psd: length " << len << " exceeds maximum buffer size of 8191" << std::endl; len = 8191; } d_len = len; d_buffer.reserve(d_len); } int ctrlport_probe_psd_impl::length() const { return (int)d_len; } int ctrlport_probe_psd_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; // copy samples to get buffer if we need samples mutex_buffer.lock(); if(d_buffer.size() < d_len) { // copy smaller of remaining buffer space and num inputs to work() int num_copy = std::min( (int)(d_len - d_buffer.size()), noutput_items ); // TODO: convert this to a copy operator for speed... for(int i = 0; i < num_copy; i++) { d_buffer.push_back(in[i]); } // notify the waiting get() if we fill up the buffer if(d_buffer.size() == d_len) { condition_buffer_ready.notify_one(); } } mutex_buffer.unlock(); return noutput_items; } void ctrlport_probe_psd_impl::setup_rpc() { #ifdef GR_CTRLPORT int len = static_cast(d_len); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get > >( alias(), d_id.c_str(), &ctrlport_probe_psd::get, pmt::make_c32vector(0,-2), pmt::make_c32vector(0,2), pmt::make_c32vector(0,0), "dB", d_desc.c_str(), RPC_PRIVLVL_MIN, DISPXY | DISPOPTSCATTER))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "length", &ctrlport_probe_psd::length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "get vector length", RPC_PRIVLVL_MIN, DISPNULL))); // d_rpc_vars.push_back( // rpcbasic_sptr(new rpcbasic_register_set( // alias(), "length", &ctrlport_probe_psd::set_length, // pmt::mp(1), pmt::mp(10*len), pmt::mp(len), // "samples", "set vector length", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace fft */ } /* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/fft_vcc_fftw.cc0000664000175000017500000001050712207443274020236 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fft_vcc_fftw.h" #include #include #include namespace gr { namespace fft { fft_vcc::sptr fft_vcc::make(int fft_size, bool forward, const std::vector &window, bool shift, int nthreads) { return gnuradio::get_initial_sptr(new fft_vcc_fftw (fft_size, forward, window, shift, nthreads)); } fft_vcc_fftw::fft_vcc_fftw(int fft_size, bool forward, const std::vector &window, bool shift, int nthreads) : sync_block("fft_vcc_fftw", io_signature::make(1, 1, fft_size * sizeof(gr_complex)), io_signature::make(1, 1, fft_size * sizeof(gr_complex))), d_fft_size(fft_size), d_forward(forward), d_shift(shift) { d_fft = new fft_complex(d_fft_size, forward, nthreads); if(!set_window(window)) throw std::runtime_error("fft_vcc: window not the same length as fft_size\n"); } fft_vcc_fftw::~fft_vcc_fftw() { delete d_fft; } void fft_vcc_fftw::set_nthreads(int n) { d_fft->set_nthreads(n); } int fft_vcc_fftw::nthreads() const { return d_fft->nthreads(); } bool fft_vcc_fftw::set_window(const std::vector &window) { if(window.size()==0 || window.size()==d_fft_size) { d_window=window; return true; } else return false; } int fft_vcc_fftw::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; unsigned int input_data_size = input_signature()->sizeof_stream_item (0); unsigned int output_data_size = output_signature()->sizeof_stream_item (0); int count = 0; while(count++ < noutput_items) { // copy input into optimally aligned buffer if(d_window.size()) { gr_complex *dst = d_fft->get_inbuf(); if(!d_forward && d_shift) { unsigned int offset = (!d_forward && d_shift)?(d_fft_size/2):0; int fft_m_offset = d_fft_size - offset; for(unsigned int i = 0; i < offset; i++) // apply window dst[i+fft_m_offset] = in[i] * d_window[i]; for(unsigned int i = offset; i < d_fft_size; i++) // apply window dst[i-offset] = in[i] * d_window[i]; } else { for(unsigned int i = 0; i < d_fft_size; i++) // apply window dst[i] = in[i] * d_window[i]; } } else { if(!d_forward && d_shift) { // apply an ifft shift on the data gr_complex *dst = d_fft->get_inbuf(); unsigned int len = (unsigned int)(floor(d_fft_size/2.0)); // half length of complex array memcpy(&dst[0], &in[len], sizeof(gr_complex)*(d_fft_size - len)); memcpy(&dst[d_fft_size - len], &in[0], sizeof(gr_complex)*len); } else { memcpy(d_fft->get_inbuf(), in, input_data_size); } } // compute the fft d_fft->execute(); // copy result to our output if(d_forward && d_shift) { // apply a fft shift on the data unsigned int len = (unsigned int)(ceil(d_fft_size/2.0)); memcpy(&out[0], &d_fft->get_outbuf()[len], sizeof(gr_complex)*(d_fft_size - len)); memcpy(&out[d_fft_size - len], &d_fft->get_outbuf()[0], sizeof(gr_complex)*len); } else { memcpy (out, d_fft->get_outbuf (), output_data_size); } in += d_fft_size; out += d_fft_size; } return noutput_items; } } /* namespace fft */ } /* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/fft.cc0000664000175000017500000002254012207440367016355 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2008,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #ifdef _MSC_VER //http://www.fftw.org/install/windows.html#DLLwisdom static void my_fftw_write_char(char c, void *f) { fputc(c, (FILE *) f); } #define fftw_export_wisdom_to_file(f) fftw_export_wisdom(my_fftw_write_char, (void*) (f)) #define fftwf_export_wisdom_to_file(f) fftwf_export_wisdom(my_fftw_write_char, (void*) (f)) #define fftwl_export_wisdom_to_file(f) fftwl_export_wisdom(my_fftw_write_char, (void*) (f)) static int my_fftw_read_char(void *f) { return fgetc((FILE *) f); } #define fftw_import_wisdom_from_file(f) fftw_import_wisdom(my_fftw_read_char, (void*) (f)) #define fftwf_import_wisdom_from_file(f) fftwf_import_wisdom(my_fftw_read_char, (void*) (f)) #define fftwl_import_wisdom_from_file(f) fftwl_import_wisdom(my_fftw_read_char, (void*) (f)) #endif //_MSC_VER #include #include #include #include #include #include #include #include namespace fs = boost::filesystem; namespace gr { namespace fft { gr_complex * malloc_complex(int size) { return (gr_complex*)fftwf_malloc(sizeof(gr_complex)*size); } float * malloc_float(int size) { return (float*)fftwf_malloc(sizeof(float)*size); } double * malloc_double(int size) { return (double*)fftwf_malloc(sizeof(double)*size); } void free(void *b) { fftwf_free(b); } boost::mutex & planner::mutex() { static boost::mutex s_planning_mutex; return s_planning_mutex; } static const char * wisdom_filename() { static fs::path path; path = fs::path(gr::appdata_path()) / ".gr_fftw_wisdom"; return path.string().c_str(); } static void import_wisdom() { const char *filename = wisdom_filename (); FILE *fp = fopen (filename, "r"); if (fp != 0){ int r = fftwf_import_wisdom_from_file (fp); fclose (fp); if (!r){ fprintf (stderr, "gr::fft: can't import wisdom from %s\n", filename); } } } static void config_threading(int nthreads) { static int fftw_threads_inited = 0; #ifdef FFTW3F_THREADS if (fftw_threads_inited == 0) { fftw_threads_inited = 1; fftwf_init_threads(); } fftwf_plan_with_nthreads(nthreads); #endif } static void export_wisdom() { const char *filename = wisdom_filename (); FILE *fp = fopen (filename, "w"); if (fp != 0){ fftwf_export_wisdom_to_file (fp); fclose (fp); } else { fprintf (stderr, "fft_impl_fftw: "); perror (filename); } } // ---------------------------------------------------------------- fft_complex::fft_complex(int fft_size, bool forward, int nthreads) { // Hold global mutex during plan construction and destruction. planner::scoped_lock lock(planner::mutex()); assert (sizeof (fftwf_complex) == sizeof (gr_complex)); if (fft_size <= 0) throw std::out_of_range ("fft_impl_fftw: invalid fft_size"); d_fft_size = fft_size; d_inbuf = (gr_complex *) fftwf_malloc (sizeof (gr_complex) * inbuf_length ()); if (d_inbuf == 0) throw std::runtime_error ("fftwf_malloc"); d_outbuf = (gr_complex *) fftwf_malloc (sizeof (gr_complex) * outbuf_length ()); if (d_outbuf == 0){ fftwf_free (d_inbuf); throw std::runtime_error ("fftwf_malloc"); } d_nthreads = nthreads; config_threading(nthreads); import_wisdom(); // load prior wisdom from disk d_plan = fftwf_plan_dft_1d (fft_size, reinterpret_cast(d_inbuf), reinterpret_cast(d_outbuf), forward ? FFTW_FORWARD : FFTW_BACKWARD, FFTW_MEASURE); if (d_plan == NULL) { fprintf(stderr, "gr::fft: error creating plan\n"); throw std::runtime_error ("fftwf_plan_dft_1d failed"); } export_wisdom(); // store new wisdom to disk } fft_complex::~fft_complex() { // Hold global mutex during plan construction and destruction. planner::scoped_lock lock(planner::mutex()); fftwf_destroy_plan ((fftwf_plan) d_plan); fftwf_free (d_inbuf); fftwf_free (d_outbuf); } void fft_complex::set_nthreads(int n) { if (n <= 0) throw std::out_of_range ("gr::fft: invalid number of threads"); d_nthreads = n; #ifdef FFTW3F_THREADS fftwf_plan_with_nthreads(d_nthreads); #endif } void fft_complex::execute() { fftwf_execute((fftwf_plan) d_plan); } // ---------------------------------------------------------------- fft_real_fwd::fft_real_fwd (int fft_size, int nthreads) { // Hold global mutex during plan construction and destruction. planner::scoped_lock lock(planner::mutex()); assert (sizeof (fftwf_complex) == sizeof (gr_complex)); if (fft_size <= 0) throw std::out_of_range ("gr::fft: invalid fft_size"); d_fft_size = fft_size; d_inbuf = (float *) fftwf_malloc (sizeof (float) * inbuf_length ()); if (d_inbuf == 0) throw std::runtime_error ("fftwf_malloc"); d_outbuf = (gr_complex *) fftwf_malloc (sizeof (gr_complex) * outbuf_length ()); if (d_outbuf == 0){ fftwf_free (d_inbuf); throw std::runtime_error ("fftwf_malloc"); } d_nthreads = nthreads; config_threading(nthreads); import_wisdom(); // load prior wisdom from disk d_plan = fftwf_plan_dft_r2c_1d (fft_size, d_inbuf, reinterpret_cast(d_outbuf), FFTW_MEASURE); if (d_plan == NULL) { fprintf(stderr, "gr::fft::fft_real_fwd: error creating plan\n"); throw std::runtime_error ("fftwf_plan_dft_r2c_1d failed"); } export_wisdom(); // store new wisdom to disk } fft_real_fwd::~fft_real_fwd() { // Hold global mutex during plan construction and destruction. planner::scoped_lock lock(planner::mutex()); fftwf_destroy_plan ((fftwf_plan) d_plan); fftwf_free (d_inbuf); fftwf_free (d_outbuf); } void fft_real_fwd::set_nthreads(int n) { if (n <= 0) throw std::out_of_range ("gr::fft::fft_real_fwd::set_nthreads: invalid number of threads"); d_nthreads = n; #ifdef FFTW3F_THREADS fftwf_plan_with_nthreads(d_nthreads); #endif } void fft_real_fwd::execute() { fftwf_execute ((fftwf_plan) d_plan); } // ---------------------------------------------------------------- fft_real_rev::fft_real_rev(int fft_size, int nthreads) { // Hold global mutex during plan construction and destruction. planner::scoped_lock lock(planner::mutex()); assert (sizeof (fftwf_complex) == sizeof (gr_complex)); if (fft_size <= 0) throw std::out_of_range ("gr::fft::fft_real_rev: invalid fft_size"); d_fft_size = fft_size; d_inbuf = (gr_complex *) fftwf_malloc (sizeof (gr_complex) * inbuf_length ()); if (d_inbuf == 0) throw std::runtime_error ("fftwf_malloc"); d_outbuf = (float *) fftwf_malloc (sizeof (float) * outbuf_length ()); if (d_outbuf == 0){ fftwf_free (d_inbuf); throw std::runtime_error ("fftwf_malloc"); } d_nthreads = nthreads; config_threading(nthreads); import_wisdom(); // load prior wisdom from disk // FIXME If there's ever a chance that the planning functions // will be called in multiple threads, we've got to ensure single // threaded access. They are not thread-safe. d_plan = fftwf_plan_dft_c2r_1d (fft_size, reinterpret_cast(d_inbuf), d_outbuf, FFTW_MEASURE); if (d_plan == NULL) { fprintf(stderr, "gr::fft::fft_real_rev: error creating plan\n"); throw std::runtime_error ("fftwf_plan_dft_c2r_1d failed"); } export_wisdom (); // store new wisdom to disk } fft_real_rev::~fft_real_rev () { // Hold global mutex during plan construction and destruction. planner::scoped_lock lock(planner::mutex()); fftwf_destroy_plan ((fftwf_plan) d_plan); fftwf_free (d_inbuf); fftwf_free (d_outbuf); } void fft_real_rev::set_nthreads(int n) { if (n <= 0) throw std::out_of_range ("gr::fft::fft_real_rev::set_nthreads: invalid number of threads"); d_nthreads = n; #ifdef FFTW3F_THREADS fftwf_plan_with_nthreads(d_nthreads); #endif } void fft_real_rev::execute () { fftwf_execute ((fftwf_plan) d_plan); } } /* namespace fft */ } /* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/goertzel_fc_impl.cc0000664000175000017500000000431312207440367021120 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "goertzel_fc_impl.h" #include namespace gr { namespace fft { goertzel_fc::sptr goertzel_fc::make(int rate, int len, float freq) { return gnuradio::get_initial_sptr(new goertzel_fc_impl(rate, len, freq)); } goertzel_fc_impl::goertzel_fc_impl(int rate, int len, float freq) : sync_decimator("goertzel_fc", io_signature::make (1, 1, sizeof(float)), io_signature::make (1, 1, sizeof(gr_complex)), len), d_goertzel(rate, len, freq) { d_len = len; d_rate = rate; d_freq = freq; } goertzel_fc_impl::~goertzel_fc_impl() { } void goertzel_fc_impl::set_freq(float freq) { d_freq = freq; d_goertzel.set_params(d_rate, d_len, d_freq); } void goertzel_fc_impl::set_rate(int rate) { d_rate = rate; d_goertzel.set_params(d_rate, d_len, d_freq); } int goertzel_fc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *in = (float *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; for(int i = 0; i < noutput_items; i++) { *out++ = d_goertzel.batch(in); in += d_len; } return noutput_items; } } /* namespace fft */ } /* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/fft_vfc_fftw.cc0000664000175000017500000000636212207443310020234 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2008,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "fft_vfc_fftw.h" #include #include #include namespace gr { namespace fft { fft_vfc::sptr fft_vfc::make(int fft_size, bool forward, const std::vector &window, int nthreads) { return gnuradio::get_initial_sptr(new fft_vfc_fftw (fft_size, forward, window, nthreads)); } fft_vfc_fftw::fft_vfc_fftw(int fft_size, bool forward, const std::vector &window, int nthreads) : sync_block("fft_vfc_fftw", io_signature::make(1, 1, fft_size * sizeof(float)), io_signature::make(1, 1, fft_size * sizeof(gr_complex))), d_fft_size(fft_size), d_forward(forward) { d_fft = new fft_complex(d_fft_size, forward, nthreads); if(!set_window(window)) throw std::runtime_error("fft_vfc: window not the same length as fft_size\n"); } fft_vfc_fftw::~fft_vfc_fftw() { delete d_fft; } void fft_vfc_fftw::set_nthreads(int n) { d_fft->set_nthreads(n); } int fft_vfc_fftw::nthreads() const { return d_fft->nthreads(); } bool fft_vfc_fftw::set_window(const std::vector &window) { if(window.size()==0 || window.size()==d_fft_size) { d_window=window; return true; } else return false; } int fft_vfc_fftw::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; gr_complex *out = (gr_complex *)output_items[0]; unsigned int output_data_size = output_signature()->sizeof_stream_item (0); int count = 0; while(count++ < noutput_items) { // copy input into optimally aligned buffer if(d_window.size()) { gr_complex *dst = d_fft->get_inbuf(); for(unsigned int i = 0; i < d_fft_size; i++) // apply window dst[i] = in[i] * d_window[i]; } else { gr_complex *dst = d_fft->get_inbuf(); for(unsigned int i = 0; i < d_fft_size; i++) // float to complex conversion dst[i] = in[i]; } // compute the fft d_fft->execute(); // copy result to output stream memcpy(out, d_fft->get_outbuf(), output_data_size); in += d_fft_size; out += d_fft_size; } return noutput_items; } } /* namespace fft */ } /* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/window.cc0000664000175000017500000002047212245466767017125 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2007,2008,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include namespace gr { namespace fft { #define IzeroEPSILON 1E-21 /* Max error acceptable in Izero */ static double Izero(double x) { double sum, u, halfx, temp; int n; sum = u = n = 1; halfx = x/2.0; do { temp = halfx/(double)n; n += 1; temp *= temp; u *= temp; sum += u; } while (u >= IzeroEPSILON*sum); return(sum); } double midn(int ntaps) { return ntaps/2.0; } double midm1(int ntaps) { return (ntaps - 1.0)/2.0; } double midp1(int ntaps) { return (ntaps + 1.0)/2.0; } double freq(int ntaps) { return 2.0*M_PI/ntaps; } double rate(int ntaps) { return 1.0/(ntaps >> 1); } std::vector window::coswindow(int ntaps, float c0, float c1, float c2) { std::vector taps(ntaps); float M = static_cast(ntaps - 1); for(int n = 0; n < ntaps; n++) taps[n] = c0 - c1*cosf((2.0f*M_PI*n)/M) + c2*cosf((4.0f*M_PI*n)/M); return taps; } std::vector window::coswindow(int ntaps, float c0, float c1, float c2, float c3) { std::vector taps(ntaps); float M = static_cast(ntaps - 1); for(int n = 0; n < ntaps; n++) taps[n] = c0 - c1*cosf((2.0f*M_PI*n)/M) + c2*cosf((4.0f*M_PI*n)/M) \ - c3*cosf((6.0f*M_PI*n)/M); return taps; } std::vector window::coswindow(int ntaps, float c0, float c1, float c2, float c3, float c4) { std::vector taps(ntaps); float M = static_cast(ntaps - 1); for(int n = 0; n < ntaps; n++) taps[n] = c0 - c1*cosf((2.0f*M_PI*n)/M) + c2*cosf((4.0f*M_PI*n)/M) \ - c3*cosf((6.0f*M_PI*n)/M) + c4*cosf((8.0f*M_PI*n)/M); return taps; } std::vector window::rectangular(int ntaps) { std::vector taps(ntaps); for(int n = 0; n < ntaps; n++) taps[n] = 1; return taps; } std::vector window::hamming(int ntaps) { std::vector taps(ntaps); float M = static_cast(ntaps - 1); for(int n = 0; n < ntaps; n++) taps[n] = 0.54 - 0.46 * cos((2 * M_PI * n) / M); return taps; } std::vector window::hann(int ntaps) { std::vector taps(ntaps); float M = static_cast(ntaps - 1); for(int n = 0; n < ntaps; n++) taps[n] = 0.5 - 0.5 * cos((2 * M_PI * n) / M); return taps; } std::vector window::hanning(int ntaps) { return hann(ntaps); } std::vector window::blackman(int ntaps) { return coswindow(ntaps, 0.42, 0.5, 0.08); } std::vector window::blackman2(int ntaps) { return coswindow(ntaps, 0.34401, 0.49755, 0.15844); } std::vector window::blackman3(int ntaps) { return coswindow(ntaps, 0.21747, 0.45325, 0.28256, 0.04672); } std::vector window::blackman4(int ntaps) { return coswindow(ntaps, 0.084037, 0.29145, 0.375696, 0.20762, 0.041194); } std::vector window::blackman_harris(int ntaps, int atten) { switch(atten) { case(61): return coswindow(ntaps, 0.42323, 0.49755, 0.07922); case(67): return coswindow(ntaps, 0.44959, 0.49364, 0.05677); case(74): return coswindow(ntaps, 0.40271, 0.49703, 0.09392, 0.00183); case(92): return coswindow(ntaps, 0.35875, 0.48829, 0.14128, 0.01168); default: throw std::out_of_range("window::blackman_harris: unknown attenuation value (must be 61, 67, 74, or 92)"); } } std::vector window::blackmanharris(int ntaps, int atten) { return blackman_harris(ntaps, atten); } std::vector window::nuttal(int ntaps) { return coswindow(ntaps, 0.3635819, 0.4891775, 0.1365995, 0.0106411); } std::vector window::blackman_nuttal(int ntaps) { return nuttal(ntaps); } std::vector window::nuttal_cfd(int ntaps) { return coswindow(ntaps, 0.355768, 0.487396, 0.144232, 0.012604); } std::vector window::flattop(int ntaps) { double scale = 4.63867; return coswindow(ntaps, 1.0/scale, 1.93/scale, 1.29/scale, 0.388/scale, 0.028/scale); } std::vector window::kaiser(int ntaps, double beta) { if(beta < 0) throw std::out_of_range("window::kaiser: beta must be >= 0"); std::vector taps(ntaps); double IBeta = 1.0/Izero(beta); double inm1 = 1.0/((double)(ntaps-1)); double temp; for(int i = 0; i < ntaps; i++) { temp = 2*i*inm1 - 1; taps[i] = Izero(beta*sqrt(1.0-temp*temp)) * IBeta; } return taps; } std::vector window::bartlett(int ntaps) { std::vector taps(ntaps); float M = static_cast(ntaps - 1); for(int n = 0; n < ntaps/2; n++) taps[n] = 2*n/M; for(int n = ntaps/2; n < ntaps; n++) taps[n] = 2 - 2*n/M; return taps; } std::vector window::welch(int ntaps) { std::vector taps(ntaps); double m1 = midm1(ntaps); double p1 = midp1(ntaps); for(int i = 0; i < midn(ntaps)+1; i++) { taps[i] = 1.0 - pow((i - m1) / p1, 2); taps[ntaps-i-1] = taps[i]; } return taps; } std::vector window::parzen(int ntaps) { std::vector taps(ntaps); double m1 = midm1(ntaps); double m = midn(ntaps); int i; for(i = ntaps/4; i < 3*ntaps/4; i++) { taps[i] = 1.0 - 6.0*pow((i-m1)/m, 2.0) * (1.0 - fabs(i-m1)/m); } for(; i < ntaps; i++) { taps[i] = 2.0 * pow(1.0 - fabs(i-m1)/m, 3.0); taps[ntaps-i-1] = taps[i]; } return taps; } std::vector window::exponential(int ntaps, double d) { if(d < 0) throw std::out_of_range("window::exponential: d must be >= 0"); double m1 = midm1(ntaps); double p = 1.0 / (8.69*ntaps/(2.0*d)); std::vector taps(ntaps); for(int i = 0; i < midn(ntaps)+1; i++) { taps[i] = exp(-fabs(i - m1)*p); taps[ntaps-i-1] = taps[i]; } return taps; } std::vector window::riemann(int ntaps) { double cx; double sr1 = freq(ntaps); double mid = midn(ntaps); std::vector taps(ntaps); for(int i = 0; i < mid; i++) { if(i == midn(ntaps)) { taps[i] = 1.0; taps[ntaps-i-1] = 1.0; } else { cx = sr1*(i - mid); taps[i] = sin(cx)/cx; taps[ntaps-i-1] = sin(cx)/cx; } } return taps; } std::vector window::build(win_type type, int ntaps, double beta) { switch (type) { case WIN_RECTANGULAR: return rectangular(ntaps); case WIN_HAMMING: return hamming(ntaps); case WIN_HANN: return hann(ntaps); case WIN_BLACKMAN: return blackman(ntaps); case WIN_BLACKMAN_hARRIS: return blackman_harris(ntaps); case WIN_KAISER: return kaiser(ntaps, beta); case WIN_BARTLETT: return bartlett(ntaps); case WIN_FLATTOP: return flattop(ntaps); default: throw std::out_of_range("window::build: type out of range"); } } } /* namespace fft */ } /* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/fft_vfc_fftw.h0000664000175000017500000000333412207440367020103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2008,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_FFT_VFC_FFTW_IMPL_H #define INCLUDED_FFT_FFT_VFC_FFTW_IMPL_H #include #include namespace gr { namespace fft { class FFT_API fft_vfc_fftw : public fft_vfc { private: fft_complex *d_fft; unsigned int d_fft_size; std::vector d_window; bool d_forward; public: fft_vfc_fftw(int fft_size, bool forward, const std::vector &window, int nthreads=1); ~fft_vfc_fftw(); void set_nthreads(int n); int nthreads() const; bool set_window(const std::vector &window); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_FFT_VFC_FFTW_IMPL_H */ gnuradio-3.7.2.1/gr-fft/lib/goertzel.cc0000664000175000017500000000357712207440367017442 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include namespace gr { namespace fft { goertzel::goertzel(int rate, int len, float freq) { set_params(rate, len, freq); } void goertzel::set_params(int rate, int len, float freq) { d_d1 = 0.0; d_d2 = 0.0; float w = 2.0*M_PI*freq/rate; d_wr = 2.0*std::cos(w); d_wi = std::sin(w); d_len = len; d_processed = 0; } gr_complex goertzel::batch(float *in) { d_d1 = 0.0; d_d2 = 0.0; for(int i = 0; i < d_len; i++) input(in[i]); return output(); } void goertzel::input(const float &input) { float y = input + d_wr*d_d1 - d_d2; d_d2 = d_d1; d_d1 = y; d_processed++; } gr_complex goertzel::output() { gr_complex out((0.5*d_wr*d_d1-d_d2)/d_len, (d_wi*d_d1)/d_len); d_d1 = 0.0; d_d2 = 0.0; d_processed = 0; return out; } } /* namespace fft */ }/* namespace gr */ gnuradio-3.7.2.1/gr-fft/lib/goertzel_fc_impl.h0000664000175000017500000000321212207440367020757 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2011,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FFT_GOERTZEL_FC_IMPL_H #define INCLUDED_FFT_GOERTZEL_FC_IMPL_H #include #include namespace gr { namespace fft { class FFT_API goertzel_fc_impl : public goertzel_fc { private: goertzel d_goertzel; int d_len; float d_freq; int d_rate; public: goertzel_fc_impl(int rate, int len, float freq); ~goertzel_fc_impl(); void set_freq(float freq); void set_rate(int rate); float freq() { return d_freq; } int rate() { return d_rate; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace fft */ } /* namespace gr */ #endif /* INCLUDED_FFT_GOERTZEL_FC_IMPL_H */ gnuradio-3.7.2.1/gr-fft/lib/gnuradio-fft.rc.in0000664000175000017500000000331212207440367020603 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-fft" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-fft.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-fft.dll" VALUE "ProductName", "gnuradio-fft" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-fft/lib/ctrlport_probe_psd_impl.h0000664000175000017500000000400412207440367022362 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE_PSD_IMPL_H #define INCLUDED_CTRLPORT_PROBE_PSD_IMPL_H #include #include #include #include namespace gr { namespace fft { class ctrlport_probe_psd_impl : public ctrlport_probe_psd { private: std::string d_id; std::string d_desc; size_t d_len; boost::shared_mutex mutex_buffer; mutable boost::mutex mutex_notify; boost::condition_variable condition_buffer_ready; std::vector d_buffer; gr::fft::fft_complex d_fft; public: ctrlport_probe_psd_impl(const std::string &id, const std::string &desc, int len); ~ctrlport_probe_psd_impl(); void setup_rpc(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); std::vector get(); void set_length(int len); int length() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE_PSD_IMPL_H */ gnuradio-3.7.2.1/gr-fft/swig/0000755000175000017500000000000012237515112015457 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-fft/swig/CMakeLists.txt0000664000175000017500000000343112207440367020230 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_FFT_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${FFTW3F_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/fft_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/fft) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-fft) GR_SWIG_MAKE(fft_swig fft_swig.i) GR_SWIG_INSTALL( TARGETS fft_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/fft COMPONENT "fft_python" ) install( FILES fft_swig.i ${CMAKE_CURRENT_BINARY_DIR}/fft_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "fft_swig" ) gnuradio-3.7.2.1/gr-fft/swig/fft_swig.i0000664000175000017500000000275312237515112017452 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define FFT_API %include "gnuradio.i" //load generated python docstrings %include "fft_swig_doc.i" %{ #include "gnuradio/fft/fft_vcc.h" #include "gnuradio/fft/fft_vfc.h" #include "gnuradio/fft/goertzel_fc.h" #include "gnuradio/fft/window.h" %} %include "gnuradio/fft/fft_vcc.h" %include "gnuradio/fft/fft_vfc.h" %include "gnuradio/fft/goertzel_fc.h" %include "gnuradio/fft/window.h" GR_SWIG_BLOCK_MAGIC2(fft, fft_vcc); GR_SWIG_BLOCK_MAGIC2(fft, fft_vfc); GR_SWIG_BLOCK_MAGIC2(fft, goertzel_fc); #ifdef GR_CTRLPORT %{ #include "gnuradio/fft/ctrlport_probe_psd.h" %} %include "gnuradio/fft/ctrlport_probe_psd.h" GR_SWIG_BLOCK_MAGIC2(fft, ctrlport_probe_psd); #endif /* GR_CTRLPORT */ gnuradio-3.7.2.1/gr-fft/gnuradio-fft.pc.in0000664000175000017500000000040212207440367020030 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-fft Description: GNU Radio's FFT signal processing blocks Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-fft Cflags: -I${includedir} gnuradio-3.7.2.1/gr-blocks/0000775000175000017500000000000012207440367015214 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/CMakeLists.txt0000664000175000017500000000701212207440367017754 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-blocks" ENABLE_GR_BLOCKS Boost_FOUND ENABLE_GNURADIO_RUNTIME ) GR_SET_GLOBAL(GR_BLOCKS_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/lib ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/lib ${CMAKE_CURRENT_BINARY_DIR}/include ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_BLOCKS) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_BLOCKS_DESCRIPTION "GNU Radio Basic Blocks") CPACK_COMPONENT("blocks_runtime" GROUP "Blocks" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("blocks_devel" GROUP "Blocks" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("blocks_python" GROUP "Blocks" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;blocks_runtime" ) CPACK_COMPONENT("blocks_swig" GROUP "Blocks" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;blocks_python;blocks_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/blocks) add_subdirectory(lib) #if(ENABLE_TESTING) # add_subdirectory(tests) #endif(ENABLE_TESTING) if(ENABLE_PYTHON) add_subdirectory(python/blocks) add_subdirectory(swig) add_subdirectory(grc) add_subdirectory(doc) add_subdirectory(examples) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-blocks.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-blocks.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-blocks.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "blocks_devel" ) endif(ENABLE_GR_BLOCKS) gnuradio-3.7.2.1/gr-blocks/include/0000775000175000017500000000000012207440367016637 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/include/gnuradio/0000775000175000017500000000000012207440367020447 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/0000775000175000017500000000000012245466767021742 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/short_to_char.h0000664000175000017500000000302712207440367024735 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_SHORT_TO_CHAR_H #define INCLUDED_BLOCKS_SHORT_TO_CHAR_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of shorts to a stream of chars. * \ingroup type_converters_blk */ class BLOCKS_API short_to_char : virtual public sync_block { public: // gr::blocks::short_to_char_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a short to char block. * * \param vlen vector length of data streams. */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_SHORT_TO_CHAR_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/char_to_float.h0000664000175000017500000000410312244272666024705 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_CHAR_TO_FLOAT_H #define INCLUDED_BLOCKS_CHAR_TO_FLOAT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of chars to a stream of float. * \ingroup type_converters_blk * * \details * Converts \p vlen length vectors of input char samples to floats * and applies a scaling factor of \p scale: * * \li output[0][m:m+vlen] = static_cast(input[0][m:m+vlen]) / scale */ class BLOCKS_API char_to_float : virtual public sync_block { public: // gr::blocks::char_to_float_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a chars to float stream converter block. * * \param vlen vector length of data streams. * \param scale a scalar divider to change the output signal scale. */ static sptr make(size_t vlen=1, float scale=1.0); /*! * Get the scalar divider value. */ virtual float scale() const = 0; /*! * Set the scalar divider value. */ virtual void set_scale(float scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_CHAR_TO_FLOAT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/socket_pdu.h0000664000175000017500000000333012207440367024234 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_SOCKET_PDU_H #define INCLUDED_BLOCKS_SOCKET_PDU_H #include #include namespace gr { namespace blocks { /*! * \brief Creates socket interface and translates traffic to PDUs * \ingroup networking_tools_blk */ class BLOCKS_API socket_pdu : virtual public block { public: // gr::blocks::socket_pdu::sptr typedef boost::shared_ptr sptr; /*! * \brief Construct a SOCKET PDU interface * \param type "TCP_SERVER", "TCP_CLIENT", "UDP_SERVER", or "UDP_CLIENT" * \param addr network address to use * \param port network port to use * \param MTU maximum transmission unit */ static sptr make(std::string type, std::string addr, std::string port, int MTU=10000); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_SOCKET_PDU_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_descriptor_sink.h0000664000175000017500000000317112207440367026300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_DESCRIPTOR_SINK_H #define INCLUDED_GR_FILE_DESCRIPTOR_SINK_H #include #include namespace gr { namespace blocks { /*! * \brief Write stream to file descriptor. * \ingroup file_operators_blk */ class BLOCKS_API file_descriptor_sink : virtual public sync_block { public: // gr::blocks::file_descriptor_sink::sptr typedef boost::shared_ptr sptr; /*! * Build a file descriptor sink block. * * \param itemsize item size of the incoming data stream. * \param fd file descriptor (as an integer). */ static sptr make(size_t itemsize, int fd); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_DESCRIPTOR_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/ctrlport_probe2_f.h0000664000175000017500000000436112207702530025521 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_F_H #define INCLUDED_CTRLPORT_PROBE2_F_H #include #include namespace gr { namespace blocks { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block holds * the latest \p len number of complex samples so that every query * by a ControlPort client will get the same length vector. */ class BLOCKS_API ctrlport_probe2_f : virtual public sync_block { public: // gr::blocks::ctrlport_probe2_f::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. * \param len Number of samples to transmit. * \param disp_mask Mask to set default display params. */ static sptr make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); virtual std::vector get() = 0; virtual void set_length(int len) = 0; virtual int length() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_F_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/CMakeLists.txt0000664000175000017500000001410112245466767024477 0ustar jcorganjcorgan# Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict(name, sig, 'blocks') build_utils.expand_template(d, inp) ") macro(expand_h root) #make a list of all the generated files unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the files add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #install rules for the generated h files list(APPEND generated_includes ${expanded_files_h}) endmacro(expand_h) ######################################################################## # Invoke macro to generate various sources ######################################################################## expand_h(add_XX ss ii cc) expand_h(add_const_XX bb ss ii ff cc) expand_h(add_const_vXX bb ss ii ff cc) expand_h(and_XX bb ss ii) expand_h(and_const_XX bb ss ii) expand_h(argmax_XX fs is ss) expand_h(divide_XX ss ii ff cc) expand_h(integrate_XX ss ii ff cc) expand_h(max_XX ff ii ss) expand_h(moving_average_XX ss ii ff cc) expand_h(multiply_XX ss ii) expand_h(multiply_const_XX ss ii) expand_h(multiply_const_vXX ss ii ff cc) expand_h(mute_XX ss ii ff cc) expand_h(not_XX bb ss ii) expand_h(or_XX bb ss ii) expand_h(peak_detector_XX fb ib sb) expand_h(probe_signal_X b s i f c) expand_h(probe_signal_vX b s i f c) expand_h(sample_and_hold_XX bb ss ii ff) expand_h(sub_XX ss ii ff cc) expand_h(xor_XX bb ss ii) expand_h(packed_to_unpacked_XX bb ss ii) expand_h(unpacked_to_packed_XX bb ss ii) expand_h(vector_insert_X b s i f c) expand_h(vector_sink_X b s i f c) expand_h(vector_source_X b s i f c) add_custom_target(blocks_generated_includes DEPENDS ${generated_includes} ) ######################################################################## # Install header files ######################################################################## install(FILES ${generated_includes} api.h control_loop.h count_bits.h file_sink_base.h lfsr_15_1_0.h lfsr_32k.h log2_const.h rotator.h wavfile.h add_ff.h annotator_1to1.h annotator_alltoall.h annotator_raw.h bin_statistics_f.h burst_tagger.h char_to_float.h char_to_short.h check_lfsr_32k_s.h complex_to_interleaved_short.h complex_to_float.h complex_to_imag.h complex_to_real.h complex_to_mag.h complex_to_mag_squared.h complex_to_arg.h conjugate_cc.h copy.h deinterleave.h delay.h endian_swap.h file_descriptor_sink.h file_descriptor_source.h file_sink.h file_source.h file_meta_sink.h file_meta_source.h float_to_char.h float_to_complex.h float_to_int.h float_to_short.h float_to_uchar.h head.h int_to_float.h interleave.h interleaved_short_to_complex.h interleaved_char_to_complex.h keep_m_in_n.h keep_one_in_n.h lfsr_32k_source_s.h message_debug.h message_sink.h message_source.h message_strobe.h message_burst_source.h multiply_cc.h multiply_ff.h multiply_conjugate_cc.h multiply_const_cc.h multiply_const_ff.h nlog10_ff.h nop.h null_sink.h null_source.h pack_k_bits_bb.h patterned_interleaver.h pdu.h pdu_to_tagged_stream.h peak_detector2_fb.h random_pdu.h plateau_detector_fb.h probe_rate.h regenerate_bb.h repack_bits_bb.h repeat.h rms_cf.h rms_ff.h short_to_char.h short_to_float.h skiphead.h socket_pdu.h stream_mux.h stream_to_streams.h stream_to_tagged_stream.h stream_to_vector.h streams_to_stream.h streams_to_vector.h stretch_ff.h tag_debug.h tag_gate.h tagged_file_sink.h tagged_stream_mux.h tagged_stream_to_pdu.h tags_strobe.h threshold_ff.h throttle.h transcendental.h tuntap_pdu.h uchar_to_float.h udp_sink.h udp_source.h unpack_k_bits_bb.h vco_f.h vco_c.h vector_map.h vector_to_stream.h vector_to_streams.h wavfile_sink.h wavfile_source.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/blocks COMPONENT "blocks_devel" ) if(ENABLE_GR_CTRLPORT) install(FILES ctrlport_probe_c.h ctrlport_probe2_c.h ctrlport_probe2_f.h ctrlport_probe2_s.h ctrlport_probe2_i.h ctrlport_probe2_b.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/blocks COMPONENT "blocks_devel" ) endif(ENABLE_GR_CTRLPORT) gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/head.h0000664000175000017500000000311212207440367022773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_HEAD_H #define INCLUDED_GR_HEAD_H #include #include #include // size_t namespace gr { namespace blocks { /*! * \brief copies the first N items to the output then signals done * \ingroup misc_blk * * \details * Useful for building test cases */ class BLOCKS_API head : virtual public sync_block { public: // gr::blocks::head::sptr typedef boost::shared_ptr sptr; static sptr make(size_t sizeof_stream_item, uint64_t nitems); virtual void reset() = 0; virtual void set_length(int nitems) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_HEAD_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/argmax_XX.h.t0000664000175000017500000000355412244272666024252 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief Compares vectors from multiple streams and determines * the index in the vector and stream number where the maximum * value occurred. * \ingroup math_operators_blk * * \details * Data is passed in as a vector of length \p vlen from multiple * input sources. It will look through these streams of \p vlen * data items and output two streams: * * \li Stream 0 will contain the index value in the vector where * the maximum value occurred. * * \li Stream 1 will contain the number of the input stream that * held the maximum value. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/wavfile_sink.h0000664000175000017500000000527312207440367024565 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_WAVFILE_SINK_H #define INCLUDED_GR_WAVFILE_SINK_H #include #include namespace gr { namespace blocks { /*! * \brief Write stream to a Microsoft PCM (.wav) file. * \ingroup audio_blk * * \details * Values must be floats within [-1;1]. * Check gr_make_wavfile_sink() for extra info. */ class BLOCKS_API wavfile_sink : virtual public sync_block { public: // gr::blocks::wavfile_sink::sptr typedef boost::shared_ptr sptr; /* * \param filename The .wav file to be opened * \param n_channels Number of channels (2 = stereo or I/Q output) * \param sample_rate Sample rate [S/s] * \param bits_per_sample 16 or 8 bit, default is 16 */ static sptr make(const char *filename, int n_channels, unsigned int sample_rate, int bits_per_sample = 16); /*! * \brief Opens a new file and writes a WAV header. Thread-safe. */ virtual bool open(const char* filename) = 0; /*! * \brief Closes the currently active file and completes the WAV * header. Thread-safe. */ virtual void close() = 0; /*! * \brief Set the sample rate. This will not affect the WAV file * currently opened. Any following open() calls will use this new * sample rate. */ virtual void set_sample_rate(unsigned int sample_rate) = 0; /*! * \brief Set bits per sample. This will not affect the WAV file * currently opened (see set_sample_rate()). If the value is * neither 8 nor 16, the call is ignored and the current value * is kept. */ virtual void set_bits_per_sample(int bits_per_sample) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_WAVFILE_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/float_to_int.h0000664000175000017500000000350112207440367024555 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FLOAT_TO_INT_H #define INCLUDED_BLOCKS_FLOAT_TO_INT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of floats to a stream of ints. * \ingroup type_converters_blk */ class BLOCKS_API float_to_int : virtual public sync_block { public: // gr::blocks::float_to_int_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a float to int block. * * \param vlen vector length of data streams. * \param scale a scalar multiplier to change the output signal scale. */ static sptr make(size_t vlen=1, float scale=1.0); /*! * Get the scalar multiplier value. */ virtual float scale() const = 0; /*! * Set the scalar multiplier value. */ virtual void set_scale(float scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FLOAT_TO_INT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vector_source_X.h.t0000664000175000017500000000325712207440367025517 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief source of @TYPE@'s that gets its data from a vector * \ingroup misc_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(const std::vector<@TYPE@> &data, bool repeat=false, int vlen=1, const std::vector &tags=std::vector()); virtual void rewind() = 0; virtual void set_data(const std::vector<@TYPE@> &data, const std::vector &tags=std::vector()) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_float.h0000664000175000017500000000346412244272666025450 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_FLOAT_H #define INCLUDED_BLOCKS_COMPLEX_TO_FLOAT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert a stream of gr_complex to 1 or 2 streams of float. * \ingroup type_converters_blk * * \details * If a single output stream is attached, this will output the * real part of the input complex samples. If a second output * stream is connected, output[0] is the real part and output[1] * is the imaginary part. */ class BLOCKS_API complex_to_float : virtual public sync_block { public: // gr::blocks::complex_to_float_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to float block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_FLOAT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tag_gate.h0000664000175000017500000000314212207440367023650 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_TAG_GATE_H #define INCLUDED_BLOCKS_TAG_GATE_H #include #include namespace gr { namespace blocks { /*! * \brief Control tag propagation. * \ingroup blocks * * Use this block to stop tags from propagating. */ class BLOCKS_API tag_gate : virtual public gr::sync_block { public: typedef boost::shared_ptr sptr; virtual void set_propagation(bool propagate_tags) = 0; /*! * \param item_size Item size * \param propagate_tags Set this to true to allow tags to pass through this block. */ static sptr make(size_t item_size, bool propagate_tags=false); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_TAG_GATE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tagged_file_sink.h0000664000175000017500000000447312207440367025363 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAGGED_FILE_SINK_H #define INCLUDED_GR_TAGGED_FILE_SINK_H #include #include namespace gr { namespace blocks { /*! * \brief A file sink that uses tags to save files. * \ingroup file_operators_blk * \ingroup stream_tag_tools_blk * * \details * The sink uses a tag with the key 'burst' to trigger the saving * of the burst data to a new file. If the value of this tag is * True, it will open a new file and start writing all incoming * data to it. If the tag is False, it will close the file (if * already opened). The file names are based on the time when the * burst tag was seen. If there is an 'rx_time' tag (standard with * UHD sources), that is used as the time. If no 'rx_time' tag is * found, the new time is calculated based off the sample rate of * the block. */ class BLOCKS_API tagged_file_sink : virtual public sync_block { public: // gr::blocks::tagged_file_sink::sptr typedef boost::shared_ptr sptr; /*! * \brief Build a tagged_file_sink block. * * \param itemsize The item size of the input data stream. * \param samp_rate The sample rate used to determine the time * difference between bursts */ static sptr make(size_t itemsize, double samp_rate); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TAGGED_FILE_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_imag.h0000664000175000017500000000306612244272666025256 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_IMAG_H #define INCLUDED_BLOCKS_COMPLEX_TO_IMAG_H #include #include namespace gr { namespace blocks { /*! * \brief Produces the imaginary part (as a float0 of a complex stream. * \ingroup type_converters_blk */ class BLOCKS_API complex_to_imag : virtual public sync_block { public: // gr::blocks::complex_to_imag_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to imaginary part block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_IMAG_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/interleaved_char_to_complex.h0000664000175000017500000000313012207702530027613 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_INTERLEAVED_CHAR_TO_COMPLEX_H #define INCLUDED_BLOCKS_INTERLEAVED_CHAR_TO_COMPLEX_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of interleaved chars to a stream of complex * \ingroup type_converters_blk */ class BLOCKS_API interleaved_char_to_complex : virtual public sync_decimator { public: // gr::blocks::interleaved_char_to_complex::sptr typedef boost::shared_ptr sptr; /*! * Build an interleaved char to complex block. */ static sptr make(bool vector_input=false); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_INTERLEAVED_CHAR_TO_COMPLEX_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_mag.h0000664000175000017500000000371212244272666025103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_MAG_H #define INCLUDED_BLOCKS_COMPLEX_TO_MAG_H #include #include namespace gr { namespace blocks { /*! * \brief complex in, magnitude out (float) * \ingroup type_converters_blk * * \details * Calculates the magnitude of the complex samples: * * \li output[0][m] = |input[0][m]| * * Or: * \li output[0][m] = sqrt(Re{input[0][m]}^2 + Im{input[0][m]}^2) * * The input stream can be a vector of length \p vlen, and for * each vector, each item is converted using the above * function. So above, m is from 0 to noutput_items*vlen for each * call to work. */ class BLOCKS_API complex_to_mag : virtual public sync_block { public: // gr::blocks::complex_to_mag_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to magnitude block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_MAG_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/xor_XX.h.t0000664000175000017500000000264112207440367023571 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input_0 ^ input_1 ^ , ... ^ input_N) * \ingroup boolean_operators_blk * * Bitwise boolean xor across all input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/throttle.h0000664000175000017500000000376112207440367023751 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_THROTTLE_H #define INCLUDED_GR_THROTTLE_H #include #include namespace gr { namespace blocks { /*! * \brief throttle flow of samples such that the average rate does * not exceed samples_per_sec. * \ingroup misc_blk * * \details * input: one stream of itemsize; output: one stream of itemsize * * N.B. this should only be used in GUI apps where there is no * other rate limiting block. It is not intended nor effective at * precisely controlling the rate of samples. That should be * controlled by a source or sink tied to sample clock. E.g., a * USRP or audio card. */ class BLOCKS_API throttle : virtual public sync_block { public: typedef boost::shared_ptr sptr; static sptr make(size_t itemsize, double samples_per_sec); //! Sets the sample rate in samples per second. virtual void set_sample_rate(double rate) = 0; //! Get the sample rate in samples per second. virtual double sample_rate() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_THROTTLE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_XX.h.t0000664000175000017500000000264112207440367024640 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004, 2009, 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = prod (input_0, input_1, ...) * \ingroup math_operators_blk * * \details * Multiply across all input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/message_strobe.h0000664000175000017500000000456412207440367025110 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_STROBE_H #define INCLUDED_GR_MESSAGE_STROBE_H #include #include namespace gr { namespace blocks { /*! * \brief Send message at defined interval * \ingroup message_tools_blk * * \details * Takes a PMT message and sends it out every \p period_ms * milliseconds. Useful for testing/debugging the message system. */ class BLOCKS_API message_strobe : virtual public block { public: // gr::blocks::message_strobe::sptr typedef boost::shared_ptr sptr; /*! * Make a message stobe block to send message \p msg every \p * period_ms milliseconds. * * \param msg The message to send as a PMT. * \param period_ms the time period in milliseconds in which to * send \p msg. */ static sptr make(pmt::pmt_t msg, float period_ms); /*! * Reset the message being sent. * \param msg The message to send as a PMT. */ virtual void set_msg(pmt::pmt_t msg) = 0; /*! * Get the value of the message being sent. */ virtual pmt::pmt_t msg() const = 0; /*! * Reset the sending interval. * \param period_ms the time period in milliseconds. */ virtual void set_period(float period_ms) = 0; /*! * Get the time interval of the strobe. */ virtual float period() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_STROBE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vector_to_stream.h0000664000175000017500000000330012207440367025450 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_VECTOR_TO_STREAM_H #define INCLUDED_BLOCKS_VECTOR_TO_STREAM_H #include #include namespace gr { namespace blocks { /*! * \brief convert a stream of gnuradio/blocks of nitems_per_block items into a stream of items * \ingroup stream_operators_blk */ class BLOCKS_API vector_to_stream : virtual public sync_interpolator { public: // gr::blocks::vector_to_stream::sptr typedef boost::shared_ptr sptr; /*! * Make vector-to-stream block * * \param itemsize the item size of the stream * \param nitems_per_block number of items per vector (vector size) */ static sptr make(size_t itemsize, size_t nitems_per_block); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_VECTOR_TO_STREAM_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/null_source.h0000664000175000017500000000302312207440367024425 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_NULL_SOURCE_H #define INCLUDED_GR_NULL_SOURCE_H #include #include namespace gr { namespace blocks { /*! * \brief A source of zeros used mainly for testing. * \ingroup misc_blk */ class BLOCKS_API null_source : virtual public sync_block { public: // gr::blocks::null_source::sptr typedef boost::shared_ptr sptr; /*! * Build a null source block. * * \param sizeof_stream_item size of the stream items in bytes. */ static sptr make(size_t sizeof_stream_item); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_NULL_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_arg.h0000664000175000017500000000301412244272666025103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_ARG_H #define INCLUDED_BLOCKS_COMPLEX_TO_ARG_H #include #include namespace gr { namespace blocks { /*! * \brief complex in, arg (arctan) out (float) * \ingroup type_converters_blk */ class BLOCKS_API complex_to_arg : virtual public sync_block { public: // gr::blocks::complex_to_arg_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to arg block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_ARG_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/ctrlport_probe2_i.h0000664000175000017500000000435712207702530025531 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_I_H #define INCLUDED_CTRLPORT_PROBE2_I_H #include #include namespace gr { namespace blocks { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block holds * the latest \p len number of complex samples so that every query * by a ControlPort client will get the same length vector. */ class BLOCKS_API ctrlport_probe2_i : virtual public sync_block { public: // gr::blocks::ctrlport_probe2_i::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. * \param len Number of samples to transmit. * \param disp_mask Mask to set default display params. */ static sptr make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); virtual std::vector get() = 0; virtual void set_length(int len) = 0; virtual int length() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_I_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vco_c.h0000664000175000017500000000336312207702530023164 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_VCO_C_H #define INCLUDED_GR_VCO_C_H #include #include namespace gr { namespace blocks { /*! * \brief VCO - Voltage controlled oscillator * \ingroup modulators_blk * \ingroup waveform_generators_blk * * \details * input: float stream of control voltages; output: complex oscillator output */ class BLOCKS_API vco_c : virtual public sync_block { public: // gr::blocks::vco_c::sptr typedef boost::shared_ptr sptr; /*! * \brief VCO - Voltage controlled oscillator * * \param sampling_rate sampling rate (Hz) * \param sensitivity units are radians/sec/volt * \param amplitude output amplitude */ static sptr make(double sampling_rate, double sensitivity, double amplitude); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_VCO_C_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/control_loop.h0000664000175000017500000002123112244272666024613 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef GR_BLOCKS_CONTROL_LOOP #define GR_BLOCKS_CONTROL_LOOP #include namespace gr { namespace blocks { /*! * \brief A second-order control loop implementation class. * * \details * This class implements a second order control loop and is * inteded to act as a parent class to blocks which need a control * loop (e.g., gr::digital::costas_loop_cc, * gr::analog::pll_refout_cc, etc.). It takes in a loop bandwidth * as well as a max and min frequency and provides the functions * that control the update of the loop. * * The loop works of alpha and beta gains. These gains are * calculated using the input loop bandwidth and a pre-set damping * factor. The damping factor can be changed using the * #set_damping_factor after the block is * constructed. The alpha and beta values can be set using their * respective #set_alpha or #set_beta functions if very precise * control over these is required. * * The class tracks both phase and frequency of a signal based on * an error signal. The error calculation is unique for each * algorithm and is calculated externally and passed to the * advance_loop function, which uses this to update its phase and * frequency estimates. * * This class also provides the functions #phase_wrap and * #frequency_limit to easily keep the phase and frequency * estimates within our set bounds (phase_wrap keeps it within * +/-2pi). */ class BLOCKS_API control_loop { protected: float d_phase, d_freq; float d_max_freq, d_min_freq; float d_damping, d_loop_bw; float d_alpha, d_beta; public: control_loop(void) {} control_loop(float loop_bw, float max_freq, float min_freq); virtual ~control_loop(); /*! \brief Update the system gains from the loop bandwidth and damping factor. * * \details * This function updates the system gains based on the loop * bandwidth and damping factor of the system. These two * factors can be set separately through their own set * functions. */ void update_gains(); /*! \brief Advance the control loop based on the current gain * settings and the inputted error signal. */ void advance_loop(float error); /*! \brief Keep the phase between -2pi and 2pi. * * \details * This function keeps the phase between -2pi and 2pi. If the * phase is greater than 2pi by d, it wraps around to be -2pi+d; * similarly if it is less than -2pi by d, it wraps around to * 2pi-d. * * This function should be called after advance_loop to keep the * phase in a good operating region. It is set as a separate * method in case another way is desired as this is fairly * heavy-handed. */ void phase_wrap(); /*! \brief Keep the frequency between d_min_freq and d_max_freq. * * \details * This function keeps the frequency between d_min_freq and * d_max_freq. If the frequency is greater than d_max_freq, it * is set to d_max_freq. If the frequency is less than * d_min_freq, it is set to d_min_freq. * * This function should be called after advance_loop to keep the * frequency in the specified region. It is set as a separate * method in case another way is desired as this is fairly * heavy-handed. */ void frequency_limit(); /******************************************************************* * SET FUNCTIONS *******************************************************************/ /*! * \brief Set the loop bandwidth. * * \details * Set the loop filter's bandwidth to \p bw. This should be * between 2*pi/200 and 2*pi/100 (in rads/samp). It must also be * a positive number. * * When a new damping factor is set, the gains, alpha and beta, * of the loop are recalculated by a call to update_gains(). * * \param bw (float) new bandwidth */ virtual void set_loop_bandwidth(float bw); /*! * \brief Set the loop damping factor. * * \details * Set the loop filter's damping factor to \p df. The damping * factor should be sqrt(2)/2.0 for critically damped systems. * Set it to anything else only if you know what you are * doing. It must be a number between 0 and 1. * * When a new damping factor is set, the gains, alpha and beta, * of the loop are recalculated by a call to update_gains(). * * \param df (float) new damping factor */ void set_damping_factor(float df); /*! * \brief Set the loop gain alpha. * * \details * Sets the loop filter's alpha gain parameter. * * This value should really only be set by adjusting the loop * bandwidth and damping factor. * * \param alpha (float) new alpha gain */ void set_alpha(float alpha); /*! * \brief Set the loop gain beta. * * \details * Sets the loop filter's beta gain parameter. * * This value should really only be set by adjusting the loop * bandwidth and damping factor. * * \param beta (float) new beta gain */ void set_beta(float beta); /*! * \brief Set the control loop's frequency. * * \details * Sets the control loop's frequency. While this is normally * updated by the inner loop of the algorithm, it could be * useful to manually initialize, set, or reset this under * certain circumstances. * * \param freq (float) new frequency */ void set_frequency(float freq); /*! * \brief Set the control loop's phase. * * \details * Sets the control loop's phase. While this is normally * updated by the inner loop of the algorithm, it could be * useful to manually initialize, set, or reset this under * certain circumstances. * * \param phase (float) new phase */ void set_phase(float phase); /*! * \brief Set the control loop's maximum frequency. * * \details * Set the maximum frequency the control loop can track. * * \param freq (float) new max frequency */ void set_max_freq(float freq); /*! * \brief Set the control loop's minimum frequency. * * \details * Set the minimum frequency the control loop can track. * * \param freq (float) new min frequency */ void set_min_freq(float freq); /******************************************************************* * GET FUNCTIONS *******************************************************************/ /*! * \brief Returns the loop bandwidth. */ float get_loop_bandwidth() const; /*! * \brief Returns the loop damping factor. */ float get_damping_factor() const; /*! * \brief Returns the loop gain alpha. */ float get_alpha() const; /*! * \brief Returns the loop gain beta. */ float get_beta() const; /*! * \brief Get the control loop's frequency estimate. */ float get_frequency() const; /*! * \brief Get the control loop's phase estimate. */ float get_phase() const; /*! * \brief Get the control loop's maximum frequency. */ float get_max_freq() const; /*! * \brief Get the control loop's minimum frequency. */ float get_min_freq() const; }; } /* namespace blocks */ } /* namespace gr */ #endif /* GR_BLOCKS_CONTROL_LOOP */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_source.h0000664000175000017500000000510712207440367024377 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FILE_SOURCE_H #define INCLUDED_BLOCKS_FILE_SOURCE_H #include #include namespace gr { namespace blocks { /*! * \brief Read stream from file * \ingroup file_operators_blk */ class BLOCKS_API file_source : virtual public sync_block { public: // gr::blocks::file_source::sptr typedef boost::shared_ptr sptr; /*! * \brief Create a file source. * * Opens \p filename as a source of items into a flowgraph. The * data is expected to be in binary format, item after item. The * \p itemsize of the block determines the conversion from bits * to items. * * If \p repeat is turned on, the file will repeat the file after * it's reached the end. * * \param itemsize the size of each item in the file, in bytes * \param filename name of the file to source from * \param repeat repeat file from start */ static sptr make(size_t itemsize, const char *filename, bool repeat = false); /*! * \brief seek file to \p seek_point relative to \p whence * * \param seek_point sample offset in file * \param whence one of SEEK_SET, SEEK_CUR, SEEK_END (man fseek) */ virtual bool seek(long seek_point, int whence) = 0; /*! * \brief Opens a new file. * * \param filename name of the file to source from * \param repeat repeat file from start */ virtual void open(const char *filename, bool repeat) = 0; /*! * \brief Close the file handle. */ virtual void close() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FILE_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/patterned_interleaver.h0000664000175000017500000000311412207440367026462 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_PATTERNED_INTERLEAVER_H #define INCLUDED_BLOCKS_PATTERNED_INTERLEAVER_H #include #include namespace gr { namespace blocks { /*! * \brief Interleave items based on the provided vector \p pattern. * \ingroup stream_operators_blk */ class BLOCKS_API patterned_interleaver : virtual public block { public: typedef boost::shared_ptr sptr; /*! * Make a patterned interleaver block. * * \param itemsize stream itemsize * \param pattern vector that represents the interleaving pattern */ static sptr make(size_t itemsize, std::vector pattern); }; } } #endif /* INCLUDED_BLOCKS_PATTERNED_INTERLEAVER_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/float_to_complex.h0000664000175000017500000000302712207440367025435 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FLOAT_TO_COMPLEX_H #define INCLUDED_BLOCKS_FLOAT_TO_COMPLEX_H #include #include namespace gr { namespace blocks { /*! * \brief one or two floats in, complex out * \ingroup type_converters_blk */ class BLOCKS_API float_to_complex : virtual public sync_block { public: // gr::blocks::float_to_complex_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a float to complex block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FLOAT_TO_COMPLEX_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tag_debug.h0000664000175000017500000000667612237515111024026 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAG_DEBUG_H #define INCLUDED_GR_TAG_DEBUG_H #include #include namespace gr { namespace blocks { /*! * \brief Bit bucket that prints out any tag received. * \ingroup measurement_tools_blk * \ingroup stream_tag_tools_blk * \ingroup debug_tools_blk * * \details * This block collects all tags sent to it on all input ports and * displays them to stdout in a formatted way. The \p name * parameter is used to identify which debug sink generated the * tag, so when connecting a block to this debug sink, an * appropriate name is something that identifies the input block. * * This block otherwise acts as a NULL sink in that items from the * input stream are ignored. It is designed to be able to attach * to any block and watch all tags streaming out of that block for * debugging purposes. * * Specifying a key will allow this block to filter out all other * tags and only display tags that match the given key. This can * help clean up the output and allow you to focus in on a * particular tag of interest. * * The tags from the last call to this work function are stored * and can be retrieved using the function 'current_tags'. */ class BLOCKS_API tag_debug : virtual public sync_block { public: // gr::blocks::tag_debug::sptr typedef boost::shared_ptr sptr; /*! * Build a tag debug block * * \param sizeof_stream_item size of the items in the incoming stream. * \param name name to identify which debug sink generated the info. * \param key_filter Specify a tag's key value to use as a filter. */ static sptr make(size_t sizeof_stream_item, const std::string &name, const std::string &key_filter=""); /*! * \brief Returns a vector of tag_t items as of the last call to * work. */ virtual std::vector current_tags() = 0; /*! * \brief Return the total number of tags in the tag queue. */ virtual int num_tags() = 0; /*! * \brief Set the display of tags to stdout on/off. */ virtual void set_display(bool d) = 0; /*! * \brief Set a new key to filter with. */ virtual void set_key_filter(const std::string &key_filter) = 0; /*! * \brief Get the current filter key. */ virtual std::string key_filter() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TAG_DEBUG_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/packed_to_unpacked_XX.h.t0000664000175000017500000000506212207440367026564 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace blocks { /*! * \brief Convert a stream of packed bytes or shorts to stream of unpacked bytes or shorts. * \ingroup byte_operators_blk * * \details * input: stream of @I_TYPE@; output: stream of @O_TYPE@ * * This is the inverse of gr::blocks::unpacked_to_packed_XX. * * The bits in the bytes or shorts input stream are grouped into * chunks of \p bits_per_chunk bits and each resulting chunk is * written right- justified to the output stream of bytes or * shorts. All b or 16 bits of the each input bytes or short are * processed. The right thing is done if bits_per_chunk is not a * power of two. * * The combination of gr::blocks::packed_to_unpacked_XX_ followed by * gr_chunks_to_symbols_Xf or gr_chunks_to_symbols_Xc handles the * general case of mapping from a stream of bytes or shorts into * arbitrary float or complex symbols. * * \sa gr::blocks::packed_to_unpacked_bb, gr::blocks::unpacked_to_packed_bb, * \sa gr::blocks::packed_to_unpacked_ss, gr::blocks::unpacked_to_packed_ss, * \sa gr::blocks::chunks_to_symbols_bf, gr::blocks::chunks_to_symbols_bc. * \sa gr::blocks::chunks_to_symbols_sf, gr::blocks::chunks_to_symbols_sc. */ class BLOCKS_API @NAME@ : virtual public block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(unsigned int bits_per_chunk, endianness_t endianness); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/or_XX.h.t0000664000175000017500000000264012207440367023400 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input_0 | input_1 | , ... | input_N) * \ingroup boolean_operators_blk * * Bitwise boolean or across all input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/unpack_k_bits_bb.h0000664000175000017500000000311012207440367025347 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UNPACK_K_BITS_BB_H #define INCLUDED_GR_UNPACK_K_BITS_BB_H #include #include namespace gr { namespace blocks { /*! * \brief Converts a byte with k relevent bits to k output bytes with 1 bit in the LSB. * \ingroup byte_operators_blk */ class BLOCKS_API unpack_k_bits_bb : virtual public sync_interpolator { public: // gr::blocks::unpack_k_bits_bb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make an unpack_k_bits block. * \param k number of bits to unpack. */ static sptr make(unsigned k); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_UNPACK_K_BITS_BB_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/probe_rate.h0000664000175000017500000000347612207440367024231 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_PROBE_RATE_H #define INCLUDED_BLOCKS_PROBE_RATE_H #include #include namespace gr { namespace blocks { /*! * \brief throughput measurement * \ingroup measurement_tools_blk */ class BLOCKS_API probe_rate : virtual public sync_block { public: // gr::blocks::probe_rate::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a throughput measurement block * \param itemsize size of each stream item * \param update_rate_ms minimum update time in milliseconds * \param alpha gain for running average filter */ static sptr make(size_t itemsize, double update_rate_ms = 500.0, double alpha = 0.0001); virtual void set_alpha(double alpha) = 0; virtual double rate() = 0; virtual bool start() = 0; virtual bool stop() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_PROBE_RATE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_const_vXX.h.t0000664000175000017500000000337112207440367026235 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input * constant vector (element-wise) * \ingroup math_operators_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * \brief Create an instance of @NAME@ * \param k multiplicative constant vector */ static sptr make(std::vector<@O_TYPE@> k); /*! * \brief Return multiplicative constant vector */ virtual std::vector<@O_TYPE@> k() const = 0; /*! * \brief Set multiplicative constant vector */ virtual void set_k(std::vector<@O_TYPE@> k) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/nop.h0000664000175000017500000000317212207440367022674 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_NOP_H #define INCLUDED_GR_NOP_H #include #include #include // size_t namespace gr { namespace blocks { /*! * \brief Does nothing. Used for testing only. * \ingroup misc_blk */ class BLOCKS_API nop : virtual public block { public: // gr::blocks::nop::sptr typedef boost::shared_ptr sptr; /*! * Build a nop block. * * \param sizeof_stream_item size of the stream items in bytes. */ static sptr make(size_t sizeof_stream_item); virtual int nmsgs_received() const = 0; virtual int ctrlport_test() const = 0; virtual void set_ctrlport_test(int x) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_NOP_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vco_f.h0000664000175000017500000000336612207440367023201 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_VCO_F_H #define INCLUDED_GR_VCO_F_H #include #include namespace gr { namespace blocks { /*! * \brief VCO - Voltage controlled oscillator * \ingroup modulators_blk * \ingroup waveform_generators_blk * * \details * input: float stream of control voltages; output: float oscillator output */ class BLOCKS_API vco_f : virtual public sync_block { public: // gr::blocks::vco_f::sptr typedef boost::shared_ptr sptr; /*! * \brief VCO - Voltage controlled oscillator * * \param sampling_rate sampling rate (Hz) * \param sensitivity units are radians/sec/volt * \param amplitude output amplitude */ static sptr make(double sampling_rate, double sensitivity, double amplitude); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_VCO_F_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/regenerate_bb.h0000664000175000017500000000505612207440367024667 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_REGENERATE_BB_H #define INCLUDED_GR_REGENERATE_BB_H #include #include namespace gr { namespace blocks { /*! * \brief Detect the peak of a signal and repeat every period samples * \ingroup stream_operators_blk * * \details * If a peak is detected, this block outputs a 1 repeated every * period samples until reset by detection of another 1 on the * input or stopped after max_regen regenerations have occurred. * * Note that if max_regen=(-1)/ULONG_MAX then the regeneration * will run forever. */ class BLOCKS_API regenerate_bb : virtual public sync_block { public: // gr::blocks::regenerate_bb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a regenerate block * \param period The number of samples between regenerations * \param max_regen The maximum number of regenerations to * perform; if set to ULONG_MAX, it will regenerate * continuously. */ static sptr make(int period, unsigned int max_regen=500); /*! \brief Reset the maximum regeneration count; this will reset the current regen. */ virtual void set_max_regen(unsigned int regen) = 0; /*! \brief Reset the period of regenerations; this will reset the current regen. */ virtual void set_period(int period) = 0; /*! \brief return the maximum regeneration count. */ virtual unsigned int max_regen() const = 0; /*! \brief return the regeneration period. */ virtual int period() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_REGENERATE_BB_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/keep_m_in_n.h0000664000175000017500000000347212207440367024346 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_KEEP_M_IN_N_H #define INCLUDED_BLOCKS_KEEP_M_IN_N_H #include #include namespace gr { namespace blocks { /*! * \brief decimate a stream, keeping \p m items out of every \p n. * \ingroup stream_operators_blk */ class BLOCKS_API keep_m_in_n : virtual public block { public: // gr::blocks::keep_m_in_n::sptr typedef boost::shared_ptr sptr; /*! * Make a keep m in n block. * * \param itemsize stream itemsize * \param m number of items to take in block of \p n items * \param n block size in items * \param offset initial item offset into the stream */ static sptr make(size_t itemsize, int m, int n, int offset); virtual void set_m(int m) = 0; virtual void set_n(int n) = 0; virtual void set_offset(int offset) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_KEEP_M_IN_N_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/conjugate_cc.h0000664000175000017500000000261012207440367024520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_CONJUGATE_CC_H #define INCLUDED_BLOCKS_CONJUGATE_CC_H #include #include namespace gr { namespace blocks { /*! * \brief output = complex conjugate of input * \ingroup math_operators_blk */ class BLOCKS_API conjugate_cc : virtual public sync_block { public: // gr::blocks::conjugate_cc_ff::sptr typedef boost::shared_ptr sptr; static sptr make(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_CONJUGATE_CC_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/interleave.h0000664000175000017500000000300512207440367024231 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_INTERLEAVE_H #define INCLUDED_BLOCKS_INTERLEAVE_H #include #include namespace gr { namespace blocks { /*! * \brief interleave N inputs into a single output * \ingroup stream_operators_blk */ class BLOCKS_API interleave : virtual public sync_interpolator { public: // gr::blocks::interleave::sptr typedef boost::shared_ptr sptr; /*! * Make a stream interleave block. * * \param itemsize stream itemsize */ static sptr make(size_t itemsize); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_INTERLEAVE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/pdu_to_tagged_stream.h0000664000175000017500000000350512207440367026260 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_PDU_TO_TAGGED_STREAM_H #define INCLUDED_BLOCKS_PDU_TO_TAGGED_STREAM_H #include #include #include namespace gr { namespace blocks { /*! * \brief Turns received PDUs into a tagged stream of items * \ingroup message_tools_blk */ class BLOCKS_API pdu_to_tagged_stream : virtual public sync_block { public: // gr::blocks::pdu_to_tagged_stream::sptr typedef boost::shared_ptr sptr; /*! * \brief Construct a pdu_to_tagged_stream block * \param type PDU type of pdu::vector_type * \param lengthtagname The name of the tag that specifies how long the packet is. * Defaults to 'packet_len'. */ static sptr make(pdu::vector_type type, const std::string& lengthtagname="packet_len"); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_PDU_TO_TAGGED_STREAM_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/udp_source.h0000664000175000017500000000575212207440367024256 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UDP_SOURCE_H #define INCLUDED_GR_UDP_SOURCE_H #include #include namespace gr { namespace blocks { /*! * \brief Read stream from an UDP socket. * \ingroup networking_tools_blk */ class BLOCKS_API udp_source : virtual public sync_block { public: // gr::blocks::udp_source::sptr typedef boost::shared_ptr sptr; /*! * \brief UDP Source Constructor * * \param itemsize The size (in bytes) of the item datatype * \param host The name or IP address of the receiving host; can be * NULL, None, or "0.0.0.0" to allow reading from any * interface on the host * \param port The port number on which to receive data; use 0 to * have the system assign an unused port number * \param payload_size UDP payload size by default set to 1472 = * (1500 MTU - (8 byte UDP header) - (20 byte IP header)) * \param eof Interpret zero-length packet as EOF (default: true) */ static sptr make(size_t itemsize, const std::string &host, int port, int payload_size=1472, bool eof=true); /*! \brief Change the connection to a new destination * * \param host The name or IP address of the receiving host; use * NULL or None to break the connection without closing * \param port Destination port to connect to on receiving host * * Calls disconnect() to terminate any current connection first. */ virtual void connect(const std::string &host, int port) = 0; /*! \brief Cut the connection if we have one set up. */ virtual void disconnect() = 0; /*! \brief return the PAYLOAD_SIZE of the socket */ virtual int payload_size() = 0; /*! \brief return the port number of the socket */ virtual int get_port() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_UDP_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/sample_and_hold_XX.h.t0000664000175000017500000000272612207440367026076 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief sample and hold circuit * \ingroup level_controllers_blk * * \details * Samples the data stream (input stream 0) and holds the value if * the control signal is 1 (intput stream 1). */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/rms_ff.h0000664000175000017500000000300712207440367023351 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_RMS_FF_H #define INCLUDED_BLOCKS_RMS_FF_H #include #include namespace gr { namespace blocks { /*! * \brief RMS average power * \ingroup math_operators_blk */ class BLOCKS_API rms_ff : virtual public sync_block { public: // gr::blocks::rms_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Make an RMS calc. block. * \param alpha gain for running average filter. */ static sptr make(double alpha = 0.0001); virtual void set_alpha(double alpha) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_RMS_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/stream_to_streams.h0000664000175000017500000000340112207440367025626 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAM_TO_STREAMS_H #define INCLUDED_BLOCKS_STREAM_TO_STREAMS_H #include #include namespace gr { namespace blocks { /*! * \brief convert a stream of items into a N streams of items * \ingroup stream_operators_blk * * \details * Converts a stream of N items into N streams of 1 item. * Repeat ad infinitum. */ class BLOCKS_API stream_to_streams : virtual public sync_decimator { public: // gr::blocks::stream_to_streams::sptr typedef boost::shared_ptr sptr; /*! * Make a stream-to-streams block. * * \param itemsize the item size of the stream * \param nstreams number of streams to split input into */ static sptr make(size_t itemsize, size_t nstreams); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_STREAM_TO_STREAMS_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/random_pdu.h0000664000175000017500000000274012207440367024230 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_RANDOM_PDU_H #define INCLUDED_BLOCKS_RANDOM_PDU_H #include #include namespace gr { namespace blocks { /*! * \brief Sends a random PDU at intervals * \ingroup message_tools_blk * \ingroup debug_tools_blk */ class BLOCKS_API random_pdu : virtual public block { public: // gr::blocks::random_pdu::sptr typedef boost::shared_ptr sptr; /*! * \brief Construct a random PDU generator */ static sptr make(int mintime, int maxtime); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_RANDOM_PDU_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tuntap_pdu.h0000664000175000017500000000307612207440367024266 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_TUNTAP_PDU_H #define INCLUDED_BLOCKS_TUNTAP_PDU_H #include #include namespace gr { namespace blocks { /*! * \brief Creates TUNTAP interface and translates traffic to PDUs * \ingroup networking_tools_blk */ class BLOCKS_API tuntap_pdu : virtual public block { public: // gr::blocks::tuntap_pdu::sptr typedef boost::shared_ptr sptr; /*! * \brief Construct a TUNTAP PDU interface * \param dev Device name to create * \param MTU Maximum Transmission Unit size */ static sptr make(std::string dev, int MTU=10000); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_TUNTAP_PDU_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/keep_one_in_n.h0000664000175000017500000000314312207440367024666 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_KEEP_ONE_IN_N_H #define INCLUDED_BLOCKS_KEEP_ONE_IN_N_H #include #include namespace gr { namespace blocks { /*! * \brief decimate a stream, keeping one item out of every \p n. * \ingroup stream_operators_blk */ class BLOCKS_API keep_one_in_n : virtual public block { public: // gr::blocks::keep_one_in_n::sptr typedef boost::shared_ptr sptr; /*! * Make a keep one in n block. * * \param itemsize stream itemsize * \param n block size in items */ static sptr make(size_t itemsize, int n); virtual void set_n(int n) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_KEEP_ONE_IN_N_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/uchar_to_float.h0000664000175000017500000000273412207440367025074 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_UCHAR_TO_FLOAT_H #define INCLUDED_BLOCKS_UCHAR_TO_FLOAT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of unsigned chars to a stream of floats * \ingroup type_converters_blk */ class BLOCKS_API uchar_to_float : virtual public sync_block { public: // gr::blocks::uchar_to_float_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a uchar to float block. */ static sptr make(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_UCHAR_TO_FLOAT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/stream_to_tagged_stream.h0000664000175000017500000000440712237515111026756 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAM_TO_TAGGED_STREAM_H #define INCLUDED_BLOCKS_STREAM_TO_TAGGED_STREAM_H #include #include namespace gr { namespace blocks { /*! * \brief Converts a regular stream into a tagged stream. * \ingroup blocks * * All this block does is add length tags in regular intervals. * It can be used to connect a regular stream to a gr::tagged_stream_block. * * \b Careful: This block is meant to be connected directly to a tagged * stream block. If there are blocks between this block and a tagged * stream block, make sure they either don't change the rate, or modify * the tag value to make sure the length tags actually represent the * packet length. */ class BLOCKS_API stream_to_tagged_stream : virtual public gr::sync_block { public: typedef boost::shared_ptr sptr; /*! * \param itemsize Item size * \param vlen Vector length of the input items. Note that one vector is one item. * \param packet_len Number of items per tagged stream packet. One tag is written every \p packet_len items. * \param len_tag_key Key of the length tag. */ static sptr make( size_t itemsize, int vlen, unsigned packet_len, const std::string &len_tag_key ); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_STREAM_TO_TAGGED_STREAM_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/unpacked_to_packed_XX.h.t0000664000175000017500000000503512207440367026564 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace blocks { /*! * \brief Convert a stream of unpacked bytes or shorts into a stream of packed bytes or shorts. * \ingroup byte_operators_blk * * \details * input: stream of @I_TYPE@; output: stream of @O_TYPE@ * * This is the inverse of gr::blocks::packed_to_unpacked_XX. * * The low \p bits_per_chunk bits are extracted from each input * byte or short. These bits are then packed densely into the * output bytes or shorts, such that all 8 or 16 bits of the * output bytes or shorts are filled with valid input bits. The * right thing is done if bits_per_chunk is not a power of two. * * The combination of gr::blocks::packed_to_unpacked_XX followed by * gr_chunks_to_symbols_Xf or gr_chunks_to_symbols_Xc handles the * general case of mapping from a stream of bytes or shorts into * arbitrary float or complex symbols. * * \sa gr::blocks::packed_to_unpacked_bb, gr::blocks::unpacked_to_packed_bb, * \sa gr::blocks::packed_to_unpacked_ss, gr::blocks::unpacked_to_packed_ss, * \sa gr::blocks::chunks_to_symbols_bf, gr::blocks::chunks_to_symbols_bc. * \sa gr::blocks::chunks_to_symbols_sf, gr::blocks::chunks_to_symbols_sc. */ class BLOCKS_API @NAME@ : virtual public block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(unsigned int bits_per_chunk, endianness_t endianness); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/transcendental.h0000664000175000017500000000343412207440367025106 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TRANSCENDENTAL_H #define INCLUDED_GR_TRANSCENDENTAL_H #include #include #include namespace gr { namespace blocks { /*! * \brief A block that performs various transcendental math operations. * \ingroup math_operators_blk * * \details * Possible function names can be found in the cmath library. IO * may be either complex or real, double or single precision. * * Possible type strings: float, double, complex_float, complex_double * * output[i] = trans_fcn(input[i]) */ class BLOCKS_API transcendental : virtual public sync_block { public: // gr::blocks::transcendental::sptr typedef boost::shared_ptr sptr; static sptr make(const std::string &name, const std::string &type="float"); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TRANSCENDENTAL_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_real.h0000664000175000017500000000305412244272666025261 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_REAL_H #define INCLUDED_BLOCKS_COMPLEX_TO_REAL_H #include #include namespace gr { namespace blocks { /*! * \brief Produces the real part (as a float0 of a complex stream. * \ingroup type_converters_blk */ class BLOCKS_API complex_to_real : virtual public sync_block { public: // gr::blocks::complex_to_real_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to real part block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_REAL_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_const_XX.h.t0000664000175000017500000000323412207440367026045 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input * constant * \ingroup math_operators_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * \brief Create an instance of @NAME@ * \param k multiplicative constant */ static sptr make(@O_TYPE@ k); /*! * \brief Return multiplicative constant */ virtual @O_TYPE@ k() const = 0; /*! * \brief Set multiplicative constant */ virtual void set_k(@O_TYPE@ k) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/plateau_detector_fb.h0000664000175000017500000000465012207440367026075 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_PLATEAU_DETECTOR_FB_H #define INCLUDED_BLOCKS_PLATEAU_DETECTOR_FB_H #include #include namespace gr { namespace blocks { /*! * \brief Detects a plateau and marks the middle. * \ingroup peak_detectors_blk * * \details * Detect a plateau of a-priori known height. Input is a stream of floats, * the output is a stream of bytes. Whenever a plateau is detected, the * middle of that plateau is marked with a '1' on the output stream (all * other samples are left at zero). * * You can use this in a Schmidl & Cox synchronisation algorithm to interpret * the output of the normalized correlator. Just pass the length of the cyclic * prefix (in samples) as the max_len parameter). * * Unlike the peak detectors, you must the now the absolute height of the plateau. * Whenever the amplitude exceeds the given threshold, it starts assuming the * presence of a plateau. * * An implicit hysteresis is provided by the fact that after detecting one plateau, * it waits at least max_len samples before the next plateau can be detected. */ class BLOCKS_API plateau_detector_fb : virtual public block { public: typedef boost::shared_ptr sptr; /*! * \param max_len Maximum length of the plateau * \param threshold Anything above this value is considered a plateau */ static sptr make(int max_len, float threshold=0.9); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_PLATEAU_DETECTOR_FB_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_descriptor_source.h0000664000175000017500000000361312207674672026645 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_DESCRIPTOR_SOURCE_H #define INCLUDED_GR_FILE_DESCRIPTOR_SOURCE_H #include #include namespace gr { namespace blocks { /*! * \brief Read stream from file descriptor. * \ingroup file_operators_blk */ class BLOCKS_API file_descriptor_source : virtual public sync_block { protected: virtual int read_items(char *buf, int nitems) = 0; virtual int handle_residue(char *buf, int nbytes_read) = 0; virtual void flush_residue() = 0; public: // gr::blocks::file_descriptor_source::sptr typedef boost::shared_ptr sptr; /*! * Build a file descriptor source block. * * \param itemsize item size of the incoming data stream. * \param fd file descriptor (as an integer). * \param repeat repeat the data stream continuously. */ static sptr make(size_t itemsize, int fd, bool repeat=false); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_DESCRIPTOR_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/ctrlport_probe2_s.h0000664000175000017500000000436112207702530025536 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_S_H #define INCLUDED_CTRLPORT_PROBE2_S_H #include #include namespace gr { namespace blocks { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block holds * the latest \p len number of complex samples so that every query * by a ControlPort client will get the same length vector. */ class BLOCKS_API ctrlport_probe2_s : virtual public sync_block { public: // gr::blocks::ctrlport_probe2_s::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. * \param len Number of samples to transmit. * \param disp_mask Mask to set default display params. */ static sptr make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); virtual std::vector get() = 0; virtual void set_length(int len) = 0; virtual int length() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_S_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/null_sink.h0000664000175000017500000000314712207440367024100 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_NULL_SINK_H #define INCLUDED_GR_NULL_SINK_H #include #include #include // size_t namespace gr { namespace blocks { /*! * \brief Bit bucket. Use as a termination point when a sink is * required and we don't want to do anything real. * \ingroup misc_blk */ class BLOCKS_API null_sink : virtual public sync_block { public: // gr::blocks::null_sink::sptr typedef boost::shared_ptr sptr; /*! * Build a null sink block. * * \param sizeof_stream_item size of the stream items in bytes. */ static sptr make(size_t sizeof_stream_item); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_NULL_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tagged_stream_mux.h0000664000175000017500000000465012237515111025572 0ustar jcorganjcorgan/* -*- c++ -*- */ /* Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TAGGED_STREAM_MUX_H #define INCLUDED_TAGGED_STREAM_MUX_H #include #include namespace gr { namespace blocks { /*! * \brief Combines tagged streams. * \ingroup stream_operators_blk * * \details * Takes N streams as input. Each stream is tagged with packet lengths. * Packets are output sequentially from each input stream. * * The output signal has a new length tag, which is the sum of all * individual length tags. The old length tags are discarded. * * All other tags are propagated as expected, i.e. they stay associated * with the same input item. * There are cases when this behaviour is undesirable. One special case * is when a tag at the first element (the head item) of one input port * must stay on the head item of the output port. To achieve this, * set \p tag_preserve_head_pos to the port that will receive these special * tags. */ class BLOCKS_API tagged_stream_mux : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /*! * Make a tagged stream mux block. * * \param itemsize Items size (number of bytes per item) * \param lengthtagname Length tag key * \param tag_preserve_head_pos Preserves the head position of tags on this input port */ static sptr make(size_t itemsize, const std::string &lengthtagname, unsigned int tag_preserve_head_pos=0); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_TAGGED_STREAM_MUX_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/char_to_short.h0000664000175000017500000000313012244272666024736 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_CHAR_TO_SHORT_H #define INCLUDED_BLOCKS_CHAR_TO_SHORT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of chars to a stream of short * \ingroup type_converters_blk * * \details * Converts \p vlen length vectors of input char samples to shorts: * * \li output[0][m:m+vlen] = static_cast(input[0][m:m+vlen]) */ class BLOCKS_API char_to_short : virtual public sync_block { public: // gr::blocks::char_to_short_ff::sptr typedef boost::shared_ptr sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_CHAR_TO_SHORT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tagged_stream_to_pdu.h0000664000175000017500000000350112207440367026254 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_TAGGED_STREAM_TO_PDU_H #define INCLUDED_BLOCKS_TAGGED_STREAM_TO_PDU_H #include #include #include namespace gr { namespace blocks { /*! * \brief Turns received stream data and tags into PDUs * \ingroup message_tools_blk */ class BLOCKS_API tagged_stream_to_pdu : virtual public sync_block { public: // gr::blocks::tagged_stream_to_pdu::sptr typedef boost::shared_ptr sptr; /*! * \brief Construct a tagged_stream_to_pdu block * \param type PDU type of pdu::vector_type * \param lengthtagname The name of the tag that specifies how long the packet is. * Defaults to 'packet_len'. */ static sptr make(pdu::vector_type type, const std::string& lengthtagname="packet_len"); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_TAGGED_STREAM_TO_PDU_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_sink.h0000664000175000017500000000345512237515111024040 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_SINK_H #define INCLUDED_GR_FILE_SINK_H #include #include #include namespace gr { namespace blocks { /*! * \brief Write stream to file. * \ingroup file_operators_blk */ class BLOCKS_API file_sink : virtual public sync_block, virtual public file_sink_base { public: // gr::blocks::file_sink::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a file sink. * \param itemsize size of the input data items. * \param filename name of the file to open and write output to. * \param append if true, data is appended to the file instead of * overwriting the initial content. */ static sptr make(size_t itemsize, const char *filename, bool append=false); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/add_XX.h.t0000664000175000017500000000310112244272666023507 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = sum(input[0], input[1], ..., input[M-1]) * \ingroup math_operators_blk * * \details * Add samples across all input streams. For all \f$n\f$ samples * on all \f$M\f$ input streams \f$x_m\f$: * * \f[ * y[n] = \sum_{m=0}^{M-1} x_m[n] * \f] */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/interleaved_short_to_complex.h0000664000175000017500000000314012207440367030045 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_INTERLEAVED_SHORT_TO_COMPLEX_H #define INCLUDED_BLOCKS_INTERLEAVED_SHORT_TO_COMPLEX_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of interleaved shorts to a stream of complex * \ingroup type_converters_blk */ class BLOCKS_API interleaved_short_to_complex : virtual public sync_decimator { public: // gr::blocks::interleaved_short_to_complex::sptr typedef boost::shared_ptr sptr; /*! * Build an interleaved short to complex block. */ static sptr make(bool vector_input=false); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_INTERLEAVED_SHORT_TO_COMPLEX_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/max_XX.h.t0000664000175000017500000000332712207440367023550 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief Compares vectors from multiple streams and determines * the maximum value from each vector over all streams. * \ingroup math_operators_blk * * \details * Data is passed in as a vector of length \p vlen from multiple * input sources. It will look through these streams of \p vlen * data items and output two streams. * Stream 0 will contain the index value in the vector where * the maximum value occurred. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/repack_bits_bb.h0000664000175000017500000000461212207440367025031 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_REPACK_BITS_BB_H #define INCLUDED_BLOCKS_REPACK_BITS_BB_H #include #include namespace gr { namespace blocks { /*! * \brief Pack \p k bits from the input stream onto \p l bits of the output stream. * \ingroup byte_operators_blk * * \details * No bits are lost here; any value for k and l (within [1, 8]) is allowed. * On every fresh input byte, it starts reading on the LSB, and starts copying * to the LSB as well. * * If a packet length tag is given, this block assumes a tagged stream. * In this case, the tag with the packet length is updated accordingly. * Also, the number of input bits is padded with zeros if the number of input * bits is not an integer multiple of \p l, or bits are truncated from the input * if \p align_output is set to true. */ class BLOCKS_API repack_bits_bb : virtual public tagged_stream_block { public: typedef boost::shared_ptr sptr; /*! * \param k Number of relevant bits on the input stream * \param l Number of relevant bits on the output stream * \param len_tag_key If not empty, this is the key for the length tag. * \param align_output If len_tag_key is given, this controls if the input * or the output is aligned. */ static sptr make(int k, int l=8, const std::string &len_tag_key="", bool align_output=false); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_REPACK_BITS_BB_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/moving_average_XX.h.t0000664000175000017500000000452612207440367025756 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output is the moving sum of the last N samples, scaled by the scale factor * \ingroup level_controllers_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * Create a moving average block. * * \param length Number of samples to use in the average. * \param scale scale factor for the result. * \param max_iter limits how long we go without flushing the accumulator * This is necessary to avoid numerical instability for float and complex. */ static sptr make(int length, @O_TYPE@ scale, int max_iter = 4096); /*! * Get the length used in the avaraging calculation. */ virtual int length() const = 0; /*! * Get the scale factor being used. */ virtual @O_TYPE@ scale() const = 0; /*! * Set both the length and the scale factor together. */ virtual void set_length_and_scale(int length, @O_TYPE@ scale) = 0; /*! * Set the length. */ virtual void set_length(int length) = 0; /*! * Set the scale factor. */ virtual void set_scale(@O_TYPE@ scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/threshold_ff.h0000664000175000017500000000427512207440367024554 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_THRESHOLD_FF_H #define INCLUDED_GR_THRESHOLD_FF_H #include #include namespace gr { namespace blocks { /*! * \brief Output a 1 or zero based on a threshold value. * \ingroup level_controllers_blk * * \details * Test the incoming signal against a threshold. If the signal * excedes the \p hi value, it will output a 1 until the signal * falls below the \p lo value. */ class BLOCKS_API threshold_ff : virtual public sync_block { public: // gr::blocks::threshold_ff::sptr typedef boost::shared_ptr sptr; /* \brief Create a threadshold block. * \param lo Threshold input signal needs to drop below to * change state to 0. * \param hi Threshold input signal needs to rise above to * change state to 1. * \param initial_state Initial state of the block (0 or 1). */ static sptr make(float lo, float hi, float initial_state=0); virtual float lo () const = 0; virtual void set_lo (float lo) = 0; virtual float hi () const = 0; virtual void set_hi (float hi) = 0; virtual float last_state () const = 0; virtual void set_last_state (float last_state) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_THRESHOLD_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/lfsr_15_1_0.h0000664000175000017500000000341312207440367024010 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GRI_LFSR_15_1_0_H #define INCLUDED_GRI_LFSR_15_1_0_H #include namespace gr { namespace blocks { /*! * \brief Linear Feedback Shift Register using primitive polynomial x^15 + x + 1 * \ingroup misc * * \details * Generates a maximal length pseudo-random sequence of length * 2^15 - 1 bits. */ class BLOCKS_API lfsr_15_1_0 { private: unsigned long d_sr; // shift register public: lfsr_15_1_0() { reset(); } void reset() { d_sr = 0x7fff; } int next_bit() { d_sr = ((((d_sr >> 1) ^ d_sr) & 0x1) << 14) | (d_sr >> 1); return d_sr & 0x1; } int next_byte () { int v = 0; for(int i = 0; i < 8; i++) { v >>= 1; if(next_bit ()) v |= 0x80; } return v; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GRI_LFSR_15_1_0_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/divide_XX.h.t0000664000175000017500000000265512244272666024240 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input[0] / input[1] / ... / input[M-1] * \ingroup math_operators_blk * * \details * Divide across all input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/ctrlport_probe2_b.h0000664000175000017500000000436712207702530025523 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_B_H #define INCLUDED_CTRLPORT_PROBE2_B_H #include #include namespace gr { namespace blocks { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block holds * the latest \p len number of complex samples so that every query * by a ControlPort client will get the same length vector. */ class BLOCKS_API ctrlport_probe2_b : virtual public sync_block { public: // gr::blocks::ctrlport_probe2_b::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. * \param len Number of samples to transmit. * \param disp_mask Mask to set default display params. */ static sptr make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); virtual std::vector get() = 0; virtual void set_length(int len) = 0; virtual int length() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_B_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/message_source.h0000664000175000017500000000325212207440367025103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_SOURCE_H #define INCLUDED_GR_MESSAGE_SOURCE_H #include #include #include namespace gr { namespace blocks { /*! * \brief Turn received messages into a stream * \ingroup message_tools_blk */ class BLOCKS_API message_source : virtual public sync_block { public: // gr::blocks::message_source::sptr typedef boost::shared_ptr sptr; static sptr make(size_t itemsize, int msgq_limit=0); static sptr make(size_t itemsize, gr::msg_queue::sptr msgq); static sptr make(size_t itemsize, gr::msg_queue::sptr msgq, const std::string& lengthtagname); virtual gr::msg_queue::sptr msgq() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vector_insert_X.h.t0000664000175000017500000000340312207440367025514 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief source of @TYPE@'s that gets its data from a vector * \ingroup stream_operators_blk */ class BLOCKS_API @NAME@ : virtual public block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * Make vector insert block. * * \param data vector of data to insert * \param periodicity number of samples between when to send \p data * \param offset initial item offset of first insert */ static sptr make(const std::vector<@TYPE@> &data, int periodicity, int offset=0); virtual void rewind() = 0; virtual void set_data(const std::vector<@TYPE@> &data) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/rotator.h0000664000175000017500000000367012233506724023574 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _GR_ROTATOR_H_ #define _GR_ROTATOR_H_ #include #include #include namespace gr { namespace blocks { class rotator { private: gr_complex d_phase; gr_complex d_phase_incr; unsigned int d_counter; public: rotator() : d_phase(1), d_phase_incr(1), d_counter(0) { } void set_phase(gr_complex phase) { d_phase = phase / abs(phase); } void set_phase_incr(gr_complex incr) { d_phase_incr = incr / abs(incr); } gr_complex rotate(gr_complex in) { d_counter++; gr_complex z = in * d_phase; // rotate in by phase d_phase *= d_phase_incr; // incr our phase (complex mult == add phases) if((d_counter % 512) == 0) d_phase /= abs(d_phase); // Normalize to ensure multiplication is rotation return z; } void rotateN(gr_complex *out, gr_complex *in, int n) { volk_32fc_s32fc_x2_rotator_32fc(out, in, d_phase_incr, &d_phase, n); } }; } /* namespace blocks */ } /* namespace gr */ #endif /* _GR_ROTATOR_H_ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/stream_mux.h0000664000175000017500000000436412207440367024270 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAM_MUX_H #define INCLUDED_BLOCKS_STREAM_MUX_H #include #include #include namespace gr { namespace blocks { /*! * \brief Stream muxing block to multiplex many streams into * one with a specified format. * \ingroup stream_operators_blk * * \details * Muxes N streams together producing an output stream that * contains N0 items from the first stream, N1 items from the second, * etc. and repeats: * * [N0, N1, N2, ..., Nm, N0, N1, ...] */ class BLOCKS_API stream_mux : virtual public block { public: // gr::blocks::stream_mux::sptr typedef boost::shared_ptr sptr; /*! * \brief Creates a stream muxing block to multiplex many streams into * one with a specified format. * * \param itemsize the item size of the stream * \param lengths a vector (list/tuple) specifying the number of * items from each stream the mux together. * Warning: this requires that at least as many items * per stream are available or the system will wait * indefinitely for the items. * */ static sptr make(size_t itemsize, const std::vector &lengths); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_STREAM_MUX_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/annotator_alltoall.h0000664000175000017500000000414012207440367025765 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ANNOTATOR_ALLTOALL_H #define INCLUDED_GR_ANNOTATOR_ALLTOALL_H #include #include namespace gr { namespace blocks { /*! * \brief All-to-all stream annotator testing block. FOR TESTING PURPOSES ONLY. * \ingroup debug_tools_blk * * \details * This block creates tags to be sent downstream every 10,000 * items it sees. The tags contain the name and ID of the * instantiated block, use "seq" as a key, and have a counter that * increments by 1 for every tag produced that is used as the * tag's value. The tags are propagated using the all-to-all * policy. * * It also stores a copy of all tags it sees flow past it. These * tags can be recalled externally with the data() member. * * This block is only meant for testing and showing how to use the tags. */ class BLOCKS_API annotator_alltoall : virtual public sync_block { public: // gr::blocks::annotator_alltoall::sptr typedef boost::shared_ptr sptr; static sptr make(int when, size_t sizeof_stream_item); virtual std::vector data() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ANNOTATOR_ALLTOALL_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/log2_const.h0000664000175000017500000000347212207440367024154 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * a bit of template hackery... */ #ifndef INCLUDED_BLOCKS_LOG2_CONST_H #define INCLUDED_BLOCKS_LOG2_CONST_H #include #include namespace gr { namespace blocks { template static inline int log2_const() { assert(0); return 0; } template<> inline int log2_const<1>() { return 0; } template<> inline int log2_const<2>() { return 1; } template<> inline int log2_const<4>() { return 2; } template<> inline int log2_const<8>() { return 3; } template<> inline int log2_const<16>() { return 4; } template<> inline int log2_const<32>() { return 5; } template<> inline int log2_const<64>() { return 6; } template<> inline int log2_const<128>() { return 7; } template<> inline int log2_const<256>() { return 8; } template<> inline int log2_const<512>() { return 9; } template<> inline int log2_const<1024>(){ return 10; } } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_LOG2_CONST_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_const_cc.h0000664000175000017500000000353712207440367025637 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef INCLUDED_MULTIPLY_CONST_CC_H #define INCLUDED_MULTIPLY_CONST_CC_H #include #include namespace gr { namespace blocks { /*! * \brief output = input * complex constant * \ingroup math_operators_blk */ class BLOCKS_API multiply_const_cc : virtual public sync_block { public: // gr::blocks::multiply_const_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Create an instance of multiply_const_cc * \param k complex multiplicative constant * \param vlen Vector length of incoming stream */ static sptr make(gr_complex k, size_t vlen=1); /*! * \brief Return complex multiplicative constant */ virtual gr_complex k() const = 0; /*! * \brief Set complex multiplicative constant */ virtual void set_k(gr_complex k) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_MULTIPLY_CONST_CC_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/wavfile.h0000664000175000017500000000664012207440367023540 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // This file stores all the RIFF file type knowledge for the wavfile_* // gnuradio/blocks. #include #include namespace gr { namespace blocks { /*! * \brief Read signal information from a given WAV file. * * \param[in] fp File pointer to an opened, empty file. * \param[out] sample_rate Stores the sample rate [S/s] * \param[out] nchans Number of channels * \param[out] bytes_per_sample Bytes per sample, can either be 1 or 2 (corresponding o * 8 or 16 bit samples, respectively) * \param[out] first_sample_pos Number of the first byte containing a sample. Use this * with fseek() to jump from the end of the file to the * first sample when in repeat mode. * \param[out] samples_per_chan Number of samples per channel * \return True on a successful read, false if the file could not be read or is * not a valid WAV file. */ bool wavheader_parse(FILE *fp, unsigned int &sample_rate, int &nchans, int &bytes_per_sample, int &first_sample_pos, unsigned int &samples_per_chan); /*! * \brief Read one sample from an open WAV file at the current position. * * \details * Takes care of endianness. */ short int wav_read_sample(FILE *fp, int bytes_per_sample); /*! * \brief Write a valid RIFF file header * * Note: Some header values are kept blank because they're usually * not known a-priori (file and chunk lengths). Use * gri_wavheader_complete() to fill these in. */ bool wavheader_write(FILE *fp, unsigned int sample_rate, int nchans, int bytes_per_sample); /*! * \brief Write one sample to an open WAV file at the current position. * * \details * Takes care of endianness. */ void wav_write_sample(FILE *fp, short int sample, int bytes_per_sample); /*! * \brief Complete a WAV header * * \details * Note: The stream position is changed during this function. If * anything needs to be written to the WAV file after calling this * function (which shouldn't happen), you need to fseek() to the * end of the file (or whereever). * * \param[in] fp File pointer to an open WAV file with a blank header * \param[in] byte_count Length of all samples written to the file in bytes. */ bool wavheader_complete(FILE *fp, unsigned int byte_count); } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/skiphead.h0000664000175000017500000000311012207440367023660 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SKIPHEAD_H #define INCLUDED_GR_SKIPHEAD_H #include #include #include // size_t namespace gr { namespace blocks { /*! * \brief skips the first N items, from then on copies items to the output * \ingroup misc_blk * * \details * Useful for building test cases and sources which have metadata * or junk at the start */ class BLOCKS_API skiphead : virtual public block { public: // gr::blocks::skiphead::sptr typedef boost::shared_ptr sptr; static sptr make(size_t itemsize, uint64_t nitems_to_skip); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_SKIPHEAD_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/repeat.h0000664000175000017500000000304312207440367023355 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_REPEAT_H #define INCLUDED_BLOCKS_REPEAT_H #include #include namespace gr { namespace blocks { /*! * \brief repeat each input \p repeat times * \ingroup stream_operators_blk */ class BLOCKS_API repeat : virtual public sync_interpolator { public: // gr::blocks::repeat::sptr typedef boost::shared_ptr sptr; /*! * Make a repeat block. * * \param itemsize stream itemsize * \param repeat number of times to repeat the input */ static sptr make(size_t itemsize, int repeat); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_REPEAT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_meta_source.h0000664000175000017500000000555612244272666025423 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FILE_META_SOURCE_H #define INCLUDED_BLOCKS_FILE_META_SOURCE_H #include #include namespace gr { namespace blocks { /*! * \brief Reads stream from file with meta-data headers. Headers * are parsed into tags. * \ingroup file_operators_blk * * \details * The information in the metadata headers includes: * * \li rx_rate (double): sample rate of data. * \li rx_time (uint64_t, double): time stamp of first sample in segment. * \li size (uint32_t): item size in bytes. * \li type (::gr_file_types as int32_t): data type. * \li cplx (bool): Is data complex? * \li strt (uint64_t): Starting byte of data in this segment. * \li bytes (uint64_t): Size in bytes of data in this segment. * * Any item inside of the extra header dictionary is ready out and * made into a stream tag. */ class BLOCKS_API file_meta_source : virtual public sync_block { public: // gr::blocks::file_meta_source::sptr typedef boost::shared_ptr sptr; /*! * \brief Create a meta-data file source. * * \param filename (string): Name of file to write data to. * \param repeat (bool): Repeats file when EOF is found. * \param detached_header (bool): Set to true if header * info is stored in a separate file (usually named filename.hdr) * \param hdr_filename (string): Name of detached header file if used. * Defaults to 'filename.hdr' if detached_header is true but this * field is an empty string. */ static sptr make(const std::string &filename, bool repeat=false, bool detached_header=false, const std::string &hdr_filename=""); virtual bool open(const std::string &filename, const std::string &hdr_filename="") = 0; virtual void close() = 0; virtual void do_update() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FILE_META_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/lfsr_32k_source_s.h0000664000175000017500000000325512207440367025431 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_LFSR_32K_SOURCE_S_H #define INCLUDED_GR_LFSR_32K_SOURCE_S_H #include #include #include namespace gr { namespace blocks { /*! * \brief LFSR pseudo-random source with period of 2^15 bits (2^11 shorts) * \ingroup misc_blk * * \details * This source is typically used along with gr::blocks::check_lfsr_32k_s to * test the USRP using its digital loopback mode. */ class BLOCKS_API lfsr_32k_source_s : virtual public sync_block { public: // gr::blocks::lfsr_32k_source_s::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a LFSR 32k source block. */ static sptr make(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_LFSR_32K_SOURCE_S_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/stream_to_vector.h0000664000175000017500000000331412207440367025455 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAM_TO_VECTOR_H #define INCLUDED_BLOCKS_STREAM_TO_VECTOR_H #include #include namespace gr { namespace blocks { /*! * \brief convert a stream of items into a stream of gnuradio/blocks containing nitems_per_block * \ingroup stream_operators_blk */ class BLOCKS_API stream_to_vector : virtual public sync_decimator { public: // gr::blocks::stream_to_vector::sptr typedef boost::shared_ptr sptr; /*! * Make a stream-to-vector block. * * \param itemsize the item size of the stream * \param nitems_per_block number of items to but into each vector (vector size) */ static sptr make(size_t itemsize, size_t nitems_per_block); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_STREAM_TO_VECTOR_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_meta_sink.h0000664000175000017500000001013512244272666025054 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FILE_META_SINK_H #define INCLUDED_BLOCKS_FILE_META_SINK_H #include #include namespace gr { namespace blocks { const char METADATA_VERSION = 0; const size_t METADATA_HEADER_SIZE = 149; enum gr_file_types { GR_FILE_BYTE=0, GR_FILE_CHAR=0, GR_FILE_SHORT=1, GR_FILE_INT, GR_FILE_LONG, GR_FILE_LONG_LONG, GR_FILE_FLOAT, GR_FILE_DOUBLE, }; /*! * \brief Write stream to file with meta-data headers. * \ingroup file_operators_blk * * \details * These files represent data as binary information in between * meta-data headers. The headers contain information about the * type of data and properties of the data in the next segment of * samples. The information includes: * * \li rx_rate (double): sample rate of data. * \li rx_time (uint64_t, double): time stamp of first sample in segment. * \li size (uint32_t): item size in bytes. * \li type (::gr_file_types as int32_t): data type. * \li cplx (bool): Is data complex? * \li strt (uint64_t): Starting byte of data in this segment. * \li bytes (uint64_t): Size in bytes of data in this segment. * * Tags can be sent to the file to update the information, which * will create a new header. Headers are found by searching from * the first header (at position 0 in the file) and reading where * the data segment starts plus the data segment size. Following * will either be a new header or EOF. */ class BLOCKS_API file_meta_sink : virtual public sync_block { public: // gr::blocks::file_meta_sink::sptr typedef boost::shared_ptr sptr; /*! * \brief Create a meta-data file sink. * * \param itemsize (size_t): Size of data type. * \param filename (string): Name of file to write data to. * \param samp_rate (double): Sample rate of data. If sample rate will be * set by a tag, such as rx_tag from a UHD source, this is * basically ignored. * \param relative_rate (double): Rate chance from source of sample * rate tag to sink. * \param type (gr_file_types): Data type (int, float, etc.) * \param complex (bool): If data stream is complex * \param max_segment_size (size_t): Length of a single segment * before the header is repeated (in items). * \param extra_dict (string): a serialized PMT dictionary of extra * information. Currently not supported. * \param detached_header (bool): Set to true to store the header * info in a separate file (named filename.hdr) */ static sptr make(size_t itemsize, const std::string &filename, double samp_rate=1, double relative_rate=1, gr_file_types type=GR_FILE_FLOAT, bool complex=true, size_t max_segment_size=1000000, const std::string &extra_dict="", bool detached_header=false); virtual bool open(const std::string &filename) = 0; virtual void close() = 0; virtual void do_update() = 0; virtual void set_unbuffered(bool unbuffered) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FILE_META_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/annotator_1to1.h0000664000175000017500000000411112207440367024743 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ANNOTATOR_1TO1_H #define INCLUDED_GR_ANNOTATOR_1TO1_H #include #include namespace gr { namespace blocks { /*! * \brief 1-to-1 stream annotator testing block. FOR TESTING PURPOSES ONLY. * \ingroup debug_tools_blk * * \details * This block creates tags to be sent downstream every 10,000 * items it sees. The tags contain the name and ID of the * instantiated block, use "seq" as a key, and have a counter that * increments by 1 for every tag produced that is used as the * tag's value. The tags are propagated using the 1-to-1 policy. * * It also stores a copy of all tags it sees flow past it. These * tags can be recalled externally with the data() member. * * Warning: This block is only meant for testing and showing how to use the * tags. */ class BLOCKS_API annotator_1to1 : virtual public sync_block { public: // gr::blocks::annotator_1to1::sptr typedef boost::shared_ptr sptr; static sptr make(int when, size_t sizeof_stream_item); virtual std::vector data() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ANNOTATOR_1TO1_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/add_const_XX.h.t0000664000175000017500000000314012207440367024712 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input + constant * \ingroup math_operators_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * \brief Create an instance of @NAME@ * \param k additive constant */ static sptr make(@O_TYPE@ k); /*! * \brief Return additive constant */ virtual @O_TYPE@ k() const = 0; /*! * \brief Set additive constant */ virtual void set_k(@O_TYPE@ k) = 0; }; } } #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/add_const_vXX.h.t0000664000175000017500000000336112244272666025113 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output[m] = input[m] + constant vector for all M streams. * \ingroup math_operators_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * \brief Create an instance of @NAME@ * \param k additive constant vector */ static sptr make(std::vector<@O_TYPE@> k); /*! * \brief Return additive constant vector */ virtual std::vector<@O_TYPE@> k() const = 0; /*! * \brief Set additive constant vector */ virtual void set_k(std::vector<@O_TYPE@> k) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/nlog10_ff.h0000664000175000017500000000315412207440367023653 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_NLOG10_FF_H #define INCLUDED_BLOCKS_NLOG10_FF_H #include #include namespace gr { namespace blocks { /*! * \brief output = n*log10(input) + k * \ingroup math_operators_blk */ class BLOCKS_API nlog10_ff : virtual public sync_block { public: // gr::blocks::nlog10_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Make an instance of an nlog10_ff block. * \param n Scalar multiplicative constant * \param vlen Input vector length * \param k Scalar additive constant */ static sptr make(float n=1.0, size_t vlen=1, float k=0.0); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_NLOG10_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/add_ff.h0000664000175000017500000000304312207440367023300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_ADD_FF_H #define INCLUDED_BLOCKS_ADD_FF_H #include #include namespace gr { namespace blocks { /*! * \brief output = sum (input_0, input_1, ...) * \ingroup math_operators_blk * * \details * Add across all input streams. */ class BLOCKS_API add_ff : virtual public sync_block { public: // gr::blocks::add_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Add streams of float values * \param vlen Vector length * \ingroup math_blk */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_ADD_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/float_to_short.h0000664000175000017500000000352012207440367025123 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FLOAT_TO_SHORT_H #define INCLUDED_BLOCKS_FLOAT_TO_SHORT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of floats to a stream of shorts * \ingroup type_converters_blk */ class BLOCKS_API float_to_short : virtual public sync_block { public: // gr::blocks::float_to_short_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a float to short block. * * \param vlen vector length of data streams. * \param scale a scalar multiplier to change the output signal scale. */ static sptr make(size_t vlen=1, float scale=1.0); /*! * Get the scalar multiplier value. */ virtual float scale() const = 0; /*! * Set the scalar multiplier value. */ virtual void set_scale(float scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FLOAT_TO_SHORT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/peak_detector2_fb.h0000664000175000017500000000617312207440367025446 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PEAK_DETECTOR2_FB_H #define INCLUDED_GR_PEAK_DETECTOR2_FB_H #include #include namespace gr { namespace blocks { /*! * \brief Detect the peak of a signal * \ingroup peak_detectors_blk * * \details * If a peak is detected, this block outputs a 1, or it outputs * 0's. A separate debug output may be connected, to view the * internal EWMA described below. */ class BLOCKS_API peak_detector2_fb : virtual public sync_block { public: // gr::blocks::peak_detector2_fb::sptr typedef boost::shared_ptr sptr; /*! * Build a peak detector block with float in, byte out. * * \param threshold_factor_rise The threshold factor determins * when a peak is present. An EWMA average of the signal is * calculated and when the value of the signal goes over * threshold_factor_rise*average, we call the peak. * \param look_ahead The look-ahead value is used when the * threshold is found to locate the peak within this range. * \param alpha The gain value of a single-pole moving average filter. */ static sptr make(float threshold_factor_rise=7, int look_ahead=1000, float alpha=0.001); /*! \brief Set the threshold factor value for the rise time * \param thr new threshold factor */ virtual void set_threshold_factor_rise(float thr) = 0; /*! \brief Set the look-ahead factor * \param look new look-ahead factor */ virtual void set_look_ahead(int look) = 0; /*! \brief Set the running average alpha * \param alpha new alpha for running average */ virtual void set_alpha(int alpha) = 0; /*! \brief Get the threshold factor value for the rise time * \return threshold factor */ virtual float threshold_factor_rise() = 0; /*! \brief Get the look-ahead factor value * \return look-ahead factor */ virtual int look_ahead() = 0; /*! \brief Get the alpha value of the running average * \return alpha */ virtual float alpha() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_PEAK_DETECTOR2_FB_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/and_XX.h.t0000664000175000017500000000266312244272666023535 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input[0] & input[1] & ... & input[M-1] * \ingroup boolean_operators_blk * * \details * bitwise boolean AND across all input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vector_to_streams.h0000664000175000017500000000331212207440367025636 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_VECTOR_TO_STREAMS_H #define INCLUDED_BLOCKS_VECTOR_TO_STREAMS_H #include #include namespace gr { namespace blocks { /*! * \brief Convert 1 stream of vectors of length N to N streams of items * \ingroup stream_operators_blk */ class BLOCKS_API vector_to_streams : virtual public sync_block { public: // gr::blocks::vector_to_streams::sptr typedef boost::shared_ptr sptr; /*! * Make vector-to-streams block * * \param itemsize the item size of the stream * \param nstreams number of items per vector (vector size and * number of streams produced) */ static sptr make(size_t itemsize, size_t nstreams); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_VECTOR_TO_STREAMS_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/annotator_raw.h0000664000175000017500000000345712207440367024764 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ANNOTATOR_RAW_H #define INCLUDED_GR_ANNOTATOR_RAW_H #include #include #include namespace gr { namespace blocks { /*! * \brief raw stream annotator testing block. * \ingroup debug_tools_blk * * \details * This block creates arbitrary tags to be sent downstream gnuradio/blocks * to be sent are set manually via accessor methods and are sent * only once. * * This block is intended for testing of tag related gnuradio/blocks */ class BLOCKS_API annotator_raw : virtual public sync_block { public: // gr::blocks::annotator_raw::sptr typedef boost::shared_ptr sptr; static sptr make(size_t sizeof_stream_item); // insert a tag to be added virtual void add_tag(uint64_t offset, pmt::pmt_t key, pmt::pmt_t val) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ANNOTATOR_RAW_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/rms_cf.h0000664000175000017500000000300712207440367023346 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_RMS_CF_H #define INCLUDED_BLOCKS_RMS_CF_H #include #include namespace gr { namespace blocks { /*! * \brief RMS average power * \ingroup math_operators_blk */ class BLOCKS_API rms_cf : virtual public sync_block { public: // gr::blocks::rms_cf::sptr typedef boost::shared_ptr sptr; /*! * \brief Make an RMS calc. block. * \param alpha gain for running average filter. */ static sptr make(double alpha = 0.0001); virtual void set_alpha(double alpha) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_RMS_CF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/burst_tagger.h0000664000175000017500000000463512207440367024575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_BURST_TAGGER_H #define INCLUDED_GR_BURST_TAGGER_H #include #include namespace gr { namespace blocks { /*! * \brief Sets a burst on/off tag based on the value of the trigger input. * \ingroup peak_detectors_blk * \ingroup stream_tag_tools_blk * * \details * This block takes two inputs, a signal stream on the input * stream 0 and a trigger stream of shorts on input stream 1. If * the trigger stream goes above 0, a tag with the key "burst" * will be transmitted as a pmt::PMT_T. When the trigger signal * falls below 0, the "burst" tag will be transmitted as * pmt::PMT_F. * * The signal on stream 0 is retransmitted to output stream 0. */ class BLOCKS_API burst_tagger : virtual public sync_block { public: // gr::blocks::burst_tagger::sptr typedef boost::shared_ptr sptr; /*! * Build a burst tagger gnuradio/blocks. * * \param itemsize itemsize of the signal stream on input 0. */ static sptr make(size_t itemsize); /*! * For the true burst tag, change the key name to \p key and a * new value of \p value. */ virtual void set_true_tag(const std::string &key, bool value) = 0; /*! * For the false burst tag, change the key name to \p key and a * new value of \p value. */ virtual void set_false_tag(const std::string &key, bool value) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_BURST_TAGGER_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/copy.h0000664000175000017500000000306212207440367023050 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_COPY_H #define INCLUDED_GR_COPY_H #include #include namespace gr { namespace blocks { /*! * \brief output[i] = input[i] * \ingroup misc_blk * * \details * When enabled (default), this block copies its input to its * output. When disabled, this block drops its input on the floor. */ class BLOCKS_API copy : virtual public block { public: // gr::blocks::copy::sptr typedef boost::shared_ptr sptr; static sptr make(size_t itemsize); virtual void set_enabled(bool enable) = 0; virtual bool enabled() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_COPY_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/message_debug.h0000664000175000017500000000571712207440367024701 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_DEBUG_H #define INCLUDED_GR_MESSAGE_DEBUG_H #include #include namespace gr { namespace blocks { /*! * \brief Debug block for the message passing system. * \ingroup message_tools_blk * \ingroup measurement_tools_blk * \ingroup debug_tools_blk * * \details * The message debug block is used to capture and print or store * messages as they are received. Any block that generates a * message may connect that message port to one or more of the * three message input ports of this debug block. The message * ports are: * * \li print: prints the message directly to standard out. * \li store: stores the message in an internal vector. May be * access using the get_message function. * \li print_pdu: specifically designed to handle formatted PDUs * (see pdu.h). */ class BLOCKS_API message_debug : virtual public block { public: // gr::blocks::message_debug::sptr typedef boost::shared_ptr sptr; /*! * \brief Build the message debug block. It takes no parameters * and has three message ports: print, store, and * print_pdu. */ static sptr make(); /*! * \brief Reports the number of messages received by this block. */ virtual int num_messages() = 0; /*! * \brief Get a message (as a PMT) from the message vector at index \p i. * * Messages passed to the 'store' port will be stored in a * vector. This function retrieves those messages by index. They * are index in order of when they were received (all messages * are just pushed onto the back of a vector). This is mostly * useful in debugging message passing graphs and in QA code. * * \param i The index in the vector for the message to retrieve. * * \return a message at index \p i as a pmt_t. */ virtual pmt::pmt_t get_message(int i) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_DEBUG_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/pack_k_bits_bb.h0000664000175000017500000000310012207440367025003 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PACK_K_BITS_BB_H #define INCLUDED_GR_PACK_K_BITS_BB_H #include #include namespace gr { namespace blocks { /*! * \brief Converts a stream of bytes with 1 bit in the LSB to a * byte with k relevent bits. * \ingroup byte_operators_blk */ class BLOCKS_API pack_k_bits_bb : virtual public sync_decimator { public: // gr::blocks::pack_k_bits_bb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a pack_k_bits block. * \param k number of bits to be packed. */ static sptr make(unsigned k); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_PACK_K_BITS_BB_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/int_to_float.h0000664000175000017500000000347112207440367024563 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_INT_TO_FLOAT_H #define INCLUDED_BLOCKS_INT_TO_FLOAT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of ints to a stream of floats. * \ingroup type_converters_blk */ class BLOCKS_API int_to_float : virtual public sync_block { public: // gr::blocks::int_to_float_ff::sptr typedef boost::shared_ptr sptr; /*! * Build an int to float block. * * \param vlen vector length of data streams. * \param scale a scalar divider to change the output signal scale. */ static sptr make(size_t vlen=1, float scale=1.0); /*! * Get the scalar divider value. */ virtual float scale() const = 0; /*! * Set the scalar divider value. */ virtual void set_scale(float scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_INT_TO_FLOAT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/float_to_char.h0000664000175000017500000000351412207440367024704 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FLOAT_TO_CHAR_H #define INCLUDED_BLOCKS_FLOAT_TO_CHAR_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of floats to a stream of char * \ingroup type_converters_blk */ class BLOCKS_API float_to_char : virtual public sync_block { public: // gr::blocks::float_to_char_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a float to char block. * * \param vlen vector length of data streams. * \param scale a scalar multiplier to change the output signal scale. */ static sptr make(size_t vlen=1, float scale=1.0); /*! * Get the scalar multiplier value. */ virtual float scale() const = 0; /*! * Set the scalar multiplier value. */ virtual void set_scale(float scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FLOAT_TO_CHAR_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_cc.h0000664000175000017500000000310612207440367024421 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MULTIPLY_CC_H #define INCLUDED_GR_MULTIPLY_CC_H #include #include namespace gr { namespace blocks { /*! * \brief output = prod (input_0, input_1, ...) * \ingroup math_operators_blk * * \details * Multiply across all input streams. */ class BLOCKS_API multiply_cc : virtual public sync_block { public: // gr::blocks::multiply_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Multiply streams of complex values * \param vlen Vector length * \ingroup math_blk */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_MULTIPLY_CC_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_const_ff.h0000664000175000017500000000350412207440367025637 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef INCLUDED_MULTIPLY_CONST_FF_H #define INCLUDED_MULTIPLY_CONST_FF_H #include #include namespace gr { namespace blocks { /*! * \brief output = input * real constant * \ingroup math_operators_blk */ class BLOCKS_API multiply_const_ff : virtual public sync_block { public: // gr::blocks::multiply_const_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Create an instance of multiply_const_ff * \param k real multiplicative constant * \param vlen Vector length of incoming stream */ static sptr make(float k, size_t vlen=1); /*! * \brief Return real multiplicative constant */ virtual float k() const = 0; /*! * \brief Set real multiplicative constant */ virtual void set_k(float k) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_MULTIPLY_CONST_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/endian_swap.h0000664000175000017500000000313412207440367024366 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ENDIAN_SWAP_H #define INCLUDED_GR_ENDIAN_SWAP_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of items into thier byte swapped version * \ingroup stream_operators_blk */ class BLOCKS_API endian_swap : virtual public sync_block { public: // gr::blocks::endian_swap::sptr typedef boost::shared_ptr sptr; /*! * Make an endian swap block. * * \param item_size_bytes number of bytes per item, 1=no-op, * 2=uint16_t, 4=uint32_t, 8=uint64_t */ static sptr make(size_t item_size_bytes=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ENDIAN_SWAP_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/udp_sink.h0000664000175000017500000000563412207440367023721 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UDP_SINK_H #define INCLUDED_GR_UDP_SINK_H #include #include namespace gr { namespace blocks { /*! * \brief Write stream to an UDP socket. * \ingroup networking_tools_blk */ class BLOCKS_API udp_sink : virtual public sync_block { public: // gr::blocks::udp_sink::sptr typedef boost::shared_ptr sptr; /*! * \brief UDP Sink Constructor * * \param itemsize The size (in bytes) of the item datatype * \param host The name or IP address of the receiving host; use * NULL or None for no connection * \param port Destination port to connect to on receiving host * \param payload_size UDP payload size by default set to * 1472 = (1500 MTU - (8 byte UDP header) - (20 byte IP header)) * \param eof Send zero-length packet on disconnect */ static sptr make(size_t itemsize, const std::string &host, int port, int payload_size=1472, bool eof=true); /*! \brief return the PAYLOAD_SIZE of the socket */ virtual int payload_size() = 0; /*! \brief Change the connection to a new destination * * \param host The name or IP address of the receiving host; use * NULL or None to break the connection without closing * \param port Destination port to connect to on receiving host * * Calls disconnect() to terminate any current connection first. */ virtual void connect(const std::string &host, int port) = 0; /*! \brief Send zero-length packet (if eof is requested) then stop sending * * Zero-byte packets can be interpreted as EOF by gr_udp_source. * Note that disconnect occurs automatically when the sink is * destroyed, but not when its top_block stops.*/ virtual void disconnect() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_UDP_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/peak_detector_XX.h.t0000664000175000017500000000761412207440367025577 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief Detect the peak of a signal * \ingroup peak_detectors_blk * * \details * If a peak is detected, this block outputs a 1, * or it outputs 0's. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * Make a peak detector block. * * \param threshold_factor_rise The threshold factor determins * when a peak has started. An average of the signal is * calculated and when the value of the signal goes over * threshold_factor_rise*average, we start looking for a * peak. * \param threshold_factor_fall The threshold factor determins * when a peak has ended. An average of the signal is * calculated and when the value of the signal goes * bellow threshold_factor_fall*average, we stop looking * for a peak. * \param look_ahead The look-ahead value is used when the * threshold is found to look if there another peak * within this step range. If there is a larger value, * we set that as the peak and look ahead again. This is * continued until the highest point is found with This * look-ahead range. * \param alpha The gain value of a moving average filter */ static sptr make(float threshold_factor_rise = 0.25, float threshold_factor_fall = 0.40, int look_ahead = 10, float alpha = 0.001); /*! \brief Set the threshold factor value for the rise time * \param thr new threshold factor */ virtual void set_threshold_factor_rise(float thr) = 0; /*! \brief Set the threshold factor value for the fall time * \param thr new threshold factor */ virtual void set_threshold_factor_fall(float thr) = 0; /*! \brief Set the look-ahead factor * \param look new look-ahead factor */ virtual void set_look_ahead(int look) = 0; /*! \brief Set the running average alpha * \param alpha new alpha for running average */ virtual void set_alpha(int alpha) = 0; /*! \brief Get the threshold factor value for the rise time * \return threshold factor */ virtual float threshold_factor_rise() = 0; /*! \brief Get the threshold factor value for the fall time * \return threshold factor */ virtual float threshold_factor_fall() = 0; /*! \brief Get the look-ahead factor value * \return look-ahead factor */ virtual int look_ahead() = 0; /*! \brief Get the alpha value of the running average * \return alpha */ virtual float alpha() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_ff.h0000664000175000017500000000310412207440367024425 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MULTIPLY_FF_H #define INCLUDED_GR_MULTIPLY_FF_H #include #include namespace gr { namespace blocks { /*! * \brief output = prod (input_0, input_1, ...) * \ingroup math_operators_blk * * \details * Multiply across all input streams. */ class BLOCKS_API multiply_ff : virtual public sync_block { public: // gr::blocks::multiply_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Multiply streams of float values * \param vlen Vector length * \ingroup math_blk */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_MULTIPLY_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/wavfile_source.h0000664000175000017500000000421412207440367025113 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_WAVFILE_SOURCE_H #define INCLUDED_GR_WAVFILE_SOURCE_H #include #include namespace gr { namespace blocks { /*! * \brief Read stream from a Microsoft PCM (.wav) file, output floats * \ingroup audio_blk * * \details * Unless otherwise called, values are within [-1;1]. * Check gr_make_wavfile_source() for extra info. */ class BLOCKS_API wavfile_source : virtual public sync_block { public: // gr::blocks::wavfile_source::sptr typedef boost::shared_ptr sptr; static sptr make(const char *filename, bool repeat = false); /*! * \brief Read the sample rate as specified in the wav file header */ virtual unsigned int sample_rate() const = 0; /*! * \brief Return the number of bits per sample as specified in * the wav file header. Only 8 or 16 bit are supported here. */ virtual int bits_per_sample() const = 0; /*! * \brief Return the number of channels in the wav file as * specified in the wav file header. This is also the max number * of outputs you can have. */ virtual int channels() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_WAVFILE_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/tags_strobe.h0000664000175000017500000000521712207702530024407 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAGS_STROBE_H #define INCLUDED_GR_TAGS_STROBE_H #include #include namespace gr { namespace blocks { /*! * \brief Send tags at defined interval * \ingroup debug_blk * * \details * Sends a tag with key 'strobe' and a user-defined value (as a * PMT) every \p nsamps number of samples. Useful for * testing/debugging the tags system. * * Because tags are sent with a data stream, this is a source * block that acts identical to a null_source block. */ class BLOCKS_API tags_strobe : virtual public sync_block { public: // gr::blocks::tags_strobe::sptr typedef boost::shared_ptr sptr; /*! * Make a tags stobe block to send tags with value \p value * every \p nsamps number of samples. * * \param sizeof_stream_item size of the stream items in bytes. * \param value The value of the tags to send, as a PMT. * \param nsamps the number of samples between each tag. */ static sptr make(size_t sizeof_stream_item, pmt::pmt_t value, uint64_t nsamps); /*! * Reset the value of the tags being sent. * \param value The value of the tags to send as a PMT. */ virtual void set_value(pmt::pmt_t value) = 0; /*! * Get the value of the tags being sent. */ virtual pmt::pmt_t value() const = 0; /*! * Reset the sending interval. * \param nsamps the number of samples between each tag */ virtual void set_nsamps(uint64_t nsamps) = 0; /*! * Get the number of samples between the tag strobe. */ virtual uint64_t nsamps() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TAGS_STROBE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/multiply_conjugate_cc.h0000664000175000017500000000315312207440367026462 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MULTIPLY_CONJUGATE_CC_H #define INCLUDED_GR_MULTIPLY_CONJUGATE_CC_H #include #include namespace gr { namespace blocks { /*! * \brief Multiplies stream 0 by the complex conjugate of stream 1. * \ingroup math_operators_blk */ class BLOCKS_API multiply_conjugate_cc : virtual public sync_block { public: // gr::blocks::multiply_conjugate_cc::sptr typedef boost::shared_ptr sptr; /*! * \brief Multiplies a streams by the conjugate of a second stream * \param vlen Vector length * \ingroup math_blk */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_MULTIPLY_CONJUGATE_CC_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/message_sink.h0000664000175000017500000000314512207440367024550 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_SINK_H #define INCLUDED_GR_MESSAGE_SINK_H #include #include #include namespace gr { namespace blocks { /*! * \brief Gather received items into messages and insert into msgq * \ingroup message_tools_blk */ class BLOCKS_API message_sink : virtual public sync_block { public: // gr::blocks::message_sink::sptr typedef boost::shared_ptr sptr; static sptr make(size_t itemsize, gr::msg_queue::sptr msgq, bool dont_block); static sptr make(size_t itemsize, gr::msg_queue::sptr msgq, bool dont_block, const std::string& lengthtagname); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_SINK_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/message_burst_source.h0000664000175000017500000000317212207440367026323 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_BURST_SOURCE_H #define INCLUDED_GR_MESSAGE_BURST_SOURCE_H #include #include #include namespace gr { namespace blocks { /*! * \brief Turn received messages into a stream and tag them for UHD to send. * \ingroup message_tools_blk */ class BLOCKS_API message_burst_source : virtual public sync_block { public: // gr::blocks::message_source::sptr typedef boost::shared_ptr sptr; static sptr make(size_t itemsize, int msgq_limit); static sptr make(size_t itemsize, gr::msg_queue::sptr msgq); virtual gr::msg_queue::sptr msgq() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_BURST_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/deinterleave.h0000664000175000017500000000301012207440367024536 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_DEINTERLEAVE_H #define INCLUDED_BLOCKS_DEINTERLEAVE_H #include #include namespace gr { namespace blocks { /*! * \brief deinterleave a single input into N outputs * \ingroup stream_operators_blk */ class BLOCKS_API deinterleave : virtual public sync_decimator { public: // gr::blocks::deinterleave::sptr typedef boost::shared_ptr sptr; /*! * Make a deinterleave block. * * \param itemsize stream itemsize */ static sptr make(size_t itemsize); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_DEINTERLEAVE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/probe_signal_vX.h.t0000664000175000017500000000273712207440367025471 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace blocks { /*! * \brief Sink that allows a vector of samples to be grabbed from Python. * \ingroup sink_blk * \ingroup measurement_tools_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t size); virtual std::vector<@TYPE@> level() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/streams_to_vector.h0000664000175000017500000000324012207440367025636 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAMS_TO_VECTOR_H #define INCLUDED_BLOCKS_STREAMS_TO_VECTOR_H #include #include namespace gr { namespace blocks { /*! * \brief convert N streams of items to 1 stream of vector length N * \ingroup stream_operators_blk */ class BLOCKS_API streams_to_vector : virtual public sync_block { public: // gr::blocks::streams_to_vector::sptr typedef boost::shared_ptr sptr; /*! * Make a stream-to-vector block. * * \param itemsize the item size of the stream * \param nstreams number of streams to combine into a vector (vector size) */ static sptr make(size_t itemsize, size_t nstreams); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_STREAMS_TO_VECTOR_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/streams_to_stream.h0000664000175000017500000000340012207440367025625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAMS_TO_STREAM_H #define INCLUDED_BLOCKS_STREAMS_TO_STREAM_H #include #include namespace gr { namespace blocks { /*! * \brief Convert N streams of 1 item into a 1 stream of N items * \ingroup stream_operators_blk * * \details * Convert N streams of 1 item into 1 stream of N items. * Repeat ad infinitum. */ class BLOCKS_API streams_to_stream : virtual public sync_interpolator { public: // gr::blocks::streams_to_stream::sptr typedef boost::shared_ptr sptr; /*! * Make a streams-to-stream block. * * \param itemsize the item size of the stream * \param nstreams number of streams to combine */ static sptr make(size_t itemsize, size_t nstreams); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_STREAMS_TO_STREAM_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_interleaved_short.h0000664000175000017500000000374012244272666030061 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_INTERLEAVED_SHORT_H #define INCLUDED_BLOCKS_COMPLEX_TO_INTERLEAVED_SHORT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of complex to a stream of interleaved shorts. * \ingroup type_converters_blk * * \details * The output stream contains shorts with twice as many output * items as input items. For every complex input item, we produce * two output shorts that contain the real part and imaginary part * converted to shorts: * * \li output[0][n] = static_cast(input[0][m].real()); * \li output[0][n+1] = static_cast(input[0][m].imag()); */ class BLOCKS_API complex_to_interleaved_short : virtual public sync_interpolator { public: // gr::blocks::complex_to_interleaved_short::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to interleaved shorts block. */ static sptr make(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_INTERLEAVED_SHORT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/float_to_uchar.h0000664000175000017500000000274312207440367025074 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FLOAT_TO_UCHAR_H #define INCLUDED_BLOCKS_FLOAT_TO_UCHAR_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of floats to a stream of unsigned chars * \ingroup type_converters_blk */ class BLOCKS_API float_to_uchar : virtual public sync_block { public: // gr::blocks::float_to_uchar_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a float to uchar block. */ static sptr make(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FLOAT_TO_UCHAR_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/mute_XX.h.t0000664000175000017500000000266112207440367023735 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input or zero if muted. * \ingroup level_controllers_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(bool mute=false); virtual bool mute() const = 0; virtual void set_mute(bool mute=false) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/file_sink_base.h0000664000175000017500000000430112237515111025021 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_SINK_BASE_H #define INCLUDED_GR_FILE_SINK_BASE_H #include #include #include namespace gr { namespace blocks { /*! * \brief Common base class for file sinks */ class BLOCKS_API file_sink_base { protected: FILE *d_fp; // current FILE pointer FILE *d_new_fp; // new FILE pointer bool d_updated; // is there a new FILE pointer? bool d_is_binary; boost::mutex d_mutex; bool d_unbuffered; bool d_append; protected: file_sink_base(const char *filename, bool is_binary, bool append); public: file_sink_base() {} ~file_sink_base(); /*! * \brief Open filename and begin output to it. */ bool open(const char *filename); /*! * \brief Close current output file. * * Closes current output file and ignores any output until * open is called to connect to another file. */ void close(); /*! * \brief if we've had an update, do it now. */ void do_update(); /*! * \brief turn on unbuffered writes for slower outputs */ void set_unbuffered(bool unbuffered); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_SINK_BASE_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/probe_signal_X.h.t0000664000175000017500000000262112207440367025273 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief Sink that allows a sample to be grabbed from Python. * \ingroup measurement_tools_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(); virtual @TYPE@ level() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/lfsr_32k.h0000664000175000017500000000410012207440367023515 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GRI_LFSR_32k_H #define INCLUDED_GRI_LFSR_32k_H #include #include namespace gr { namespace blocks { /*! * \brief generate pseudo-random sequence of length 32768 bits. * \ingroup misc * * \details * This is based on gri_lfsr_15_1_0 with an extra 0 added at the * end of the sequence. */ class BLOCKS_API lfsr_32k { private: lfsr_15_1_0 d_lfsr; unsigned int d_count; public: lfsr_32k() { reset (); } void reset() { d_lfsr.reset(); d_count = 0; } int next_bit() { if(d_count == 32767) { d_count = 0; return 0; } d_count++; return d_lfsr.next_bit(); } int next_byte() { int v = 0; for(int i = 0; i < 8; i++) { v >>= 1; if(next_bit ()) v |= 0x80; } return v; } int next_short() { int v = 0; for(int i = 0; i < 16; i++) { v >>= 1; if(next_bit ()) v |= 0x8000; } return v; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GRI_LFSR_32k_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/pdu.h0000664000175000017500000000275312207440367022674 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_PDU_H #define INCLUDED_BLOCKS_PDU_H #include #include #include #define PDU_PORT_ID pmt::mp("pdus") namespace gr { namespace blocks { namespace pdu { enum vector_type { byte_t, float_t, complex_t }; BLOCKS_API size_t itemsize(vector_type type); BLOCKS_API bool type_matches(vector_type type, pmt::pmt_t v); BLOCKS_API pmt::pmt_t make_pdu_vector(vector_type type, const uint8_t* buf, size_t items); BLOCKS_API vector_type type_from_pmt(pmt::pmt_t vector); } /* namespace pdu */ } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_PDU_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vector_sink_X.h.t0000664000175000017500000000274412207440367025163 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief @TYPE@ sink that writes to a vector * \ingroup debug_tools_blk */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(int vlen = 1); virtual void reset() = 0; virtual std::vector<@TYPE@> data() const = 0; virtual std::vector tags() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/stretch_ff.h0000664000175000017500000000347012207440367024230 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_STRETCH_FF_H #define INCLUDED_GR_STRETCH_FF_H #include #include namespace gr { namespace blocks { /*! * \brief adjust y-range of an input vector by mapping to range * (max-of-input, stipulated-min). Primarily for spectral * signature matching by normalizing spectrum dynamic ranges. * \ingroup stream_operators_blk */ class BLOCKS_API stretch_ff : virtual public sync_block { public: // gr::blocks::stretch_ff::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a stretch block. * * \param lo Set low value for range. * \param vlen vector length of input stream. */ static sptr make(float lo, size_t vlen=1); virtual float lo() const = 0; virtual void set_lo(float lo) = 0; virtual size_t vlen() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_STRETCH_FF_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/count_bits.h0000664000175000017500000000273612207440367024256 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _GR_COUNT_BITS_H_ #define _GR_COUNT_BITS_H_ #include namespace gr { namespace blocks { //! return number of set bits in the low 8 bits of x BLOCKS_API unsigned int count_bits8(unsigned int x); //! return number of set bits in the low 16 bits of x BLOCKS_API unsigned int count_bits16(unsigned int x); //! return number of set bits in the low 32 bits of x BLOCKS_API unsigned int count_bits32(unsigned int x); //! return number of set bits in a 64-bit word BLOCKS_API unsigned int count_bits64(unsigned long long int x); } /* namespace blocks */ } /* namespace gr */ #endif /* _GR_COUNT_BITS_H_ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/api.h0000664000175000017500000000203712207440367022650 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_API_H #define INCLUDED_BLOCKS_API_H #include #ifdef gnuradio_blocks_EXPORTS # define BLOCKS_API __GR_ATTR_EXPORT #else # define BLOCKS_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_BLOCKS_API_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/integrate_XX.h.t0000664000175000017500000000256212207440367024745 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief Integrate successive samples and decimate * \ingroup math_operators_blk */ class BLOCKS_API @NAME@ : virtual public sync_decimator { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(int decim); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/sub_XX.h.t0000664000175000017500000000264212207440367023553 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = input_0 - input_1 - ...) * \ingroup math_operators_blk * * \details * Subtract across all input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/and_const_XX.h.t0000664000175000017500000000335112244272666024736 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output[m] = input[m] & value for all M streams. * \ingroup boolean_operators_blk * * \details * Bitwise boolean AND of constant \p k with the data stream. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; /*! * \brief Create an instance of @NAME@ * \param k AND constant */ static sptr make(@O_TYPE@ k); /*! * \brief Return AND constant */ virtual @O_TYPE@ k() const = 0; /*! * \brief Set AND constant */ virtual void set_k(@O_TYPE@ k) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/check_lfsr_32k_s.h0000664000175000017500000000330612207440367025203 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_CHECK_LFSR_32K_S_H #define INCLUDED_GR_CHECK_LFSR_32K_S_H #include #include namespace gr { namespace blocks { /*! * \brief sink that checks if its input stream consists of a lfsr_32k sequence. * \ingroup misc_blk * * \details * This sink is typically used along with * gr::blocks::lfsr_32k_source_s to test the USRP using its * digital loopback mode. */ class BLOCKS_API check_lfsr_32k_s : virtual public sync_block { public: // gr::blocks::check_lfsr_32k_s::sptr typedef boost::shared_ptr sptr; static sptr make(); virtual long ntotal () const = 0; virtual long nright () const = 0; virtual long runlength () const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_CHECK_LFSR_32K_S_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/delay.h0000664000175000017500000000313512207440367023175 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_DELAY_H #define INCLUDED_BLOCKS_DELAY_H #include #include namespace gr { namespace blocks { /*! * \brief delay the input by a certain number of samples * \ingroup misc_blk */ class BLOCKS_API delay : virtual public block { public: // gr::blocks::delay::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a delay block. * \param itemsize size of the data items. * \param delay number of samples to delay stream. */ static sptr make(size_t itemsize, int delay); virtual int dly() const = 0; virtual void set_dly(int d) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_DELAY_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/complex_to_mag_squared.h0000664000175000017500000000401112244272666026620 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_COMPLEX_TO_MAG_SQUARED_H #define INCLUDED_BLOCKS_COMPLEX_TO_MAG_SQUARED_H #include #include namespace gr { namespace blocks { /*! * \brief complex in, magnitude squared out (float) * \ingroup type_converters_blk * * \details * Calculates the magnitude squared of the complex samples: * * \li output[0][m] = |input[0][m]|^2 * * Or: * \li output[0][m] = Re{input[0][m]}^2 + Im{input[0][m]}^2 * * The input stream can be a vector of length \p vlen, and for * each vector, each item is converted using the above * function. So above, m is from 0 to noutput_items*vlen for each * call to work. */ class BLOCKS_API complex_to_mag_squared : virtual public sync_block { public: // gr::blocks::complex_to_mag_squared_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a complex to magnitude squared block. * * \param vlen vector len (default 1) */ static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_COMPLEX_TO_MAG_SQUARED_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/short_to_float.h0000664000175000017500000000350712207440367025130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_SHORT_TO_FLOAT_H #define INCLUDED_BLOCKS_SHORT_TO_FLOAT_H #include #include namespace gr { namespace blocks { /*! * \brief Convert stream of shorts to a stream of floats * \ingroup type_converters_blk */ class BLOCKS_API short_to_float : virtual public sync_block { public: // gr::blocks::short_to_float_ff::sptr typedef boost::shared_ptr sptr; /*! * Build a short to float block. * * \param vlen vector length of data streams. * \param scale a scalar divider to change the output signal scale. */ static sptr make(size_t vlen=1, float scale=1.0); /*! * Get the scalar divider value. */ virtual float scale() const = 0; /*! * Set the scalar divider value. */ virtual void set_scale(float scale) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_SHORT_TO_FLOAT_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/bin_statistics_f.h0000664000175000017500000000501412207440367025424 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_BIN_STATISTICS_F_H #define INCLUDED_GR_BIN_STATISTICS_F_H #include #include #include #include namespace gr { namespace blocks { /*! * \brief control scanning and record frequency domain statistics * \ingroup misc_blk */ class BLOCKS_API bin_statistics_f : virtual public sync_block { protected: std::vector d_max; // per bin maxima virtual size_t vlen() const = 0; virtual double center_freq() const = 0; virtual gr::msg_queue::sptr msgq() const = 0; virtual void reset_stats() = 0; virtual void accrue_stats(const float *input) = 0; virtual void send_stats() = 0; public: // gr::blocks::bin_statistics_f::sptr typedef boost::shared_ptr sptr; /*! * Build a bin statistics block. See qa_bin_statistics.py and * gr-uhd/examples/python/usrp_spectrum_sense.py for examples of * its use, specifically how to use the callback function. * * \param vlen vector length * \param msgq message queue * \param tune a feval_dd callback function * \param tune_delay number of samples for the tune delay * \param dwell_delay number of samples for the dwell delay */ static sptr make(unsigned int vlen, // vector length gr::msg_queue::sptr msgq, feval_dd *tune, // callback size_t tune_delay, // samples size_t dwell_delay); // samples }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_BIN_STATISTICS_F_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/not_XX.h.t0000664000175000017500000000257312207440367023565 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include namespace gr { namespace blocks { /*! * \brief output = ~input * \ingroup boolean_operators_blk * * bitwise boolean not of input streams. */ class BLOCKS_API @NAME@ : virtual public sync_block { public: // gr::blocks::@NAME@::sptr typedef boost::shared_ptr<@NAME@> sptr; static sptr make(size_t vlen=1); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/vector_map.h0000664000175000017500000000467612207440367024251 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_VECTOR_MAP_H #define INCLUDED_GR_VECTOR_MAP_H #include #include #include namespace gr { namespace blocks { /*! * \brief Maps elements from a set of input vectors to a set of output vectors. * \ingroup stream_operators_blk * * \details * If in[i] is the input vector in the i'th stream then the output * vector in the j'th stream is: * * out[j][k] = in[mapping[j][k][0]][mapping[j][k][1]] * * That is mapping is of the form (out_stream1_mapping, * out_stream2_mapping, ...) and out_stream1_mapping is of the * form (element1_mapping, element2_mapping, ...) and * element1_mapping is of the form (in_stream, in_element). */ class BLOCKS_API vector_map : virtual public sync_block { public: // gr::blocks::vector_map::sptr typedef boost::shared_ptr sptr; /*! * Build a vector map block. * * \param item_size (integer) size of vector elements * \param in_vlens (vector of integers) number of elements in each * input vector * \param mapping (vector of vectors of vectors of integers) how to * map elements from input to output vectors */ static sptr make(size_t item_size, std::vector in_vlens, std::vector< std::vector< std::vector > > mapping); virtual void set_mapping(std::vector< std::vector< std::vector > > mapping) = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_VECTOR_MAP_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/ctrlport_probe2_c.h0000664000175000017500000000437312207702530025521 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_C_H #define INCLUDED_CTRLPORT_PROBE2_C_H #include #include namespace gr { namespace blocks { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block holds * the latest \p len number of complex samples so that every query * by a ControlPort client will get the same length vector. */ class BLOCKS_API ctrlport_probe2_c : virtual public sync_block { public: // gr::blocks::ctrlport_probe2_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. * \param len Number of samples to transmit. * \param disp_mask Mask to set default display params. */ static sptr make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); virtual std::vector get() = 0; virtual void set_length(int len) = 0; virtual int length() const = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_C_H */ gnuradio-3.7.2.1/gr-blocks/include/gnuradio/blocks/ctrlport_probe_c.h0000664000175000017500000000407412207440367025444 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE_C_H #define INCLUDED_CTRLPORT_PROBE_C_H #include #include #include #include namespace gr { namespace blocks { /*! * \brief A ControlPort probe to export vectors of signals. * \ingroup measurement_tools_blk * \ingroup controlport_blk * * \details * This block acts as a sink in the flowgraph but also exports * vectors of complex samples over ControlPort. This block simply * sends the current vector held in the work function when the * queried by a ControlPort client. */ class BLOCKS_API ctrlport_probe_c : virtual public sync_block { public: // gr::blocks::ctrlport_probe_c::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a ControlPort probe block. * \param id A string ID to name the probe over ControlPort. * \param desc A string describing the probe. */ static sptr make(const std::string &id, const std::string &desc); virtual std::vector get() = 0; }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_GR_CTRLPORT_PROBE_C_H */ gnuradio-3.7.2.1/gr-blocks/grc/0000775000175000017500000000000012245466767016005 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/grc/blocks_head.xml0000664000175000017500000000237712207440367020760 0ustar jcorganjcorgan Head blocks_head from gnuradio import blocks blocks.head($type.size*$vlen, $num_items) Type type enum Num Items num_items 1024 int Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/CMakeLists.txt0000664000175000017500000000250412207440367020530 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## file(GLOB xml_files "*.xml") # Force out the controlport GRC blocks if we've disabled it. if(NOT ENABLE_GR_CTRLPORT) list(REMOVE_ITEM xml_files ${CMAKE_CURRENT_SOURCE_DIR}/ctrlport_viewer.xml ${CMAKE_CURRENT_SOURCE_DIR}/blocks_ctrlport_performance.xml ${CMAKE_CURRENT_SOURCE_DIR}/ctrlport_probe_c.xml ${CMAKE_CURRENT_SOURCE_DIR}/ctrlport_probe2_c.xml ) endif(NOT ENABLE_GR_CTRLPORT) install(FILES ${xml_files} DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "blocks_python") gnuradio-3.7.2.1/gr-blocks/grc/blocks_stream_to_vector_decimator.xml0000664000175000017500000000312312207440367025453 0ustar jcorganjcorgan Stream to Vec Decim blocks_stream_to_vector_decimator from gnuradio import blocks blocks.stream_to_vector_decimator( item_size=$type.size, sample_rate=$sample_rate, vec_rate=$vec_rate, vec_len=$vlen, ) set_sample_rate($sample_rate) set_vec_rate($vec_rate) IO Type type enum Sample Rate sample_rate samp_rate real Vec Rate vec_rate 30 real Vec Length vlen 1024 int $vlen >= 1 in $type out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_integrate_xx.xml0000664000175000017500000000165612207440367022557 0ustar jcorganjcorgan Integrate blocks_integrate_xx from gnuradio import blocks blocks.integrate_$(type.fcn)($decim) IO Type type enum Decimation decim int in $type out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_block_tree.xml0000664000175000017500000001636412245466767022207 0ustar jcorganjcorgan Audio blocks_wavfile_source blocks_wavfile_sink Boolean Operators blocks_and_xx blocks_and_const_xx blocks_not_xx blocks_or_xx blocks_xor_xx Byte Operators blocks_packed_to_unpacked_xx blocks_unpacked_to_packed_xx blocks_pack_k_bits_bb blocks_unpack_k_bits_bb blocks_repack_bits_bb Control Port blocks_ctrlport_monitor blocks_ctrlport_monitor_performance blocks_ctrlport_probe2_x blocks_ctrlport_probe2_c blocks_ctrlport_probe_c Debug Tools blocks_vector_sink_x blocks_tag_debug blocks_message_debug blocks_random_pdu blocks_message_strobe blocks_tags_strobe File Operators blocks_wavfile_source blocks_wavfile_sink blocks_file_source blocks_file_sink blocks_file_descriptor_source blocks_file_descriptor_sink blocks_file_meta_source blocks_file_meta_sink blocks_tagged_file_sink Level Controllers blocks_mute_xx blocks_sample_and_hold_xx blocks_moving_average_xx blocks_threshold_ff Math Operators blocks_add_xx blocks_add_const_vxx blocks_divide_xx blocks_multiply_xx blocks_multiply_const_vxx blocks_multiply_conjugate_cc blocks_sub_xx blocks_conjugate_cc blocks_integrate_xx blocks_nlog10_ff blocks_rms_xx blocks_transcendental blocks_argmax_xx blocks_max_xx Measurement Tools blocks_message_debug blocks_tag_debug blocks_probe_signal_x blocks_probe_signal_vx blocks_probe_rate blocks_ctrlport_probe2_c blocks_ctrlport_probe_c Message Tools blocks_message_source blocks_message_sink blocks_message_burst_source blocks_message_strobe blocks_message_debug blocks_pdu_to_tagged_stream blocks_tagged_stream_to_pdu blocks_random_pdu Misc blocks_throttle blocks_vector_source_x blocks_head blocks_skiphead blocks_delay blocks_null_source blocks_null_sink blocks_copy blocks_nop blocks_ctrlport_monitor blocks_ctrlport_monitor_performance Modulators blocks_vco_f Networking Tools blocks_tuntap_pdu blocks_socket_pdu blocks_udp_source blocks_udp_sink Peak Detectors blocks_burst_tagger blocks_peak_detector_xb blocks_peak_detector2_fb blocks_plateau_detector_fb Stream Operators blocks_deinterleave blocks_interleave blocks_keep_m_in_n blocks_keep_one_in_n blocks_stream_mux blocks_stream_to_streams blocks_stream_to_vector blocks_streams_to_stream blocks_streams_to_vector blocks_stream_to_vector_decimator blocks_vector_to_stream blocks_vector_to_streams blocks_patterned_interleaver blocks_endian_swap blocks_vector_insert_x blocks_tagged_stream_mux blocks_repeat blocks_regenerate_bb blocks_stretch_ff Stream Tag Tools blocks_tag_debug blocks_tag_gate blocks_tagged_file_sink blocks_tagged_stream_mux blocks_stream_to_tagged_stream Type Converters blocks_char_to_float blocks_char_to_short blocks_complex_to_interleaved_short blocks_complex_to_float blocks_complex_to_imag blocks_complex_to_real blocks_complex_to_mag blocks_complex_to_mag_squared blocks_complex_to_arg blocks_float_to_char blocks_float_to_complex blocks_float_to_int blocks_float_to_short blocks_float_to_uchar blocks_int_to_float blocks_interleaved_short_to_complex blocks_short_to_char blocks_short_to_float blocks_uchar_to_float Waveform Generators blocks_vco_f gnuradio-3.7.2.1/gr-blocks/grc/blocks_probe_rate.xml0000664000175000017500000000251112207440367022167 0ustar jcorganjcorgan Probe Rate blocks_probe_rate from gnuradio import blocks blocks.probe_rate($type.size*$vlen, $mintime, $alpha) Input Type type enum Vec Length vlen 1 int Min Update Time (ms) mintime 500.0 real Update Alpha alpha 0.15 real $vlen >= 1 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_interleaved_short_to_complex.xml0000664000175000017500000000163512207440367026025 0ustar jcorganjcorgan IShort To Complex blocks_interleaved_short_to_complex from gnuradio import blocks blocks.interleaved_short_to_complex($vector_input) Vector Input vector_input False enum in short $vector_input.vlen out complex gnuradio-3.7.2.1/gr-blocks/grc/blocks_short_to_char.xml0000664000175000017500000000110212207440367022676 0ustar jcorganjcorgan Short To Char blocks_short_to_char from gnuradio import blocks blocks.short_to_char($vlen) Vec Length vlen 1 int in short $vlen out byte $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_deinterleave.xml0000664000175000017500000000253412207440367022521 0ustar jcorganjcorgan Deinterleave blocks_deinterleave from gnuradio import blocks blocks.deinterleave($type.size*$vlen) IO Type type enum Num Streams num_streams 2 int Vec Length vlen 1 int $num_streams > 0 $vlen >= 1 in $type $vlen out $type $vlen $num_streams gnuradio-3.7.2.1/gr-blocks/grc/blocks_file_descriptor_sink.xml0000664000175000017500000000231212207440367024245 0ustar jcorganjcorgan File Descriptor Sink blocks_file_descriptor_sink from gnuradio import blocks blocks.file_descriptor_sink($type.size*$vlen, $fd) File Descriptor fd int Input Type type enum Vec Length vlen 1 int $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_multiply_conjugate_cc.xml0000664000175000017500000000137312207440367024435 0ustar jcorganjcorgan Multiply Conjugate blocks_multiply_conjugate_cc from gnuradio import blocks blocks.multiply_conjugate_cc($vlen) Vec Length vlen 1 int $vlen > 0 in0 complex $vlen in1 complex $vlen out complex $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_mag.xml0000664000175000017500000000115312207440367023043 0ustar jcorganjcorgan Complex to Mag blocks_complex_to_mag from gnuradio import blocks blocks.complex_to_mag($vlen) Vec Length vlen 1 int $vlen > 0 in complex $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_message_source.xml0000664000175000017500000000231312207440367023051 0ustar jcorganjcorgan Message Source blocks_message_source from gnuradio import blocks blocks.message_source($type.size*$vlen, $(id)_msgq_in) Output Type type enum Vec Length vlen 1 int $vlen > 0 in msg out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_sample_and_hold_xx.xml0000664000175000017500000000163512207440367023703 0ustar jcorganjcorgan Sample and Hold blocks_sample_and_hold_xx from gnuradio import blocks blocks.sample_and_hold_$(type.fcn)() Type type enum in $type ctrl byte out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_tagged_file_sink.xml0000664000175000017500000000235212207440367023326 0ustar jcorganjcorgan Tagged File Sink blocks_tagged_file_sink from gnuradio import blocks blocks.tagged_file_sink($type.size*$vlen, $samp_rate) Input Type type enum Sample Rate samp_rate samp_rate int Vec Length vlen 1 int $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_ctrlport_probe2_c.xml0000664000175000017500000000426312207702530023470 0ustar jcorganjcorgan Ctrlport Probe blocks_ctrlport_probe2_c from gnuradio import blocks blocks.ctrlport_probe2_c($name, $desc, $len, $disp_mask) set_length($len) Name name samples string Description desc Sample Points string Length len 1024 int Display Mask disp_mask gr.DISPTIME int in complex Place this in a graph to export vectors of samples to a GRCP port probe. * Specify the number of samples to transmit at once and the type of default display to use. gnuradio-3.7.2.1/gr-blocks/grc/blocks_sub_xx.xml0000664000175000017500000000232512207440367021360 0ustar jcorganjcorgan Subtract blocks_sub_xx from gnuradio import blocks blocks.sub_$(type.fcn)($vlen) IO Type type enum Vec Length vlen 1 int Num Inputs num_inputs 2 int $vlen > 0 $num_inputs >= 2 in $type $vlen $num_inputs out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_interleaved_short.xml0000664000175000017500000000074212207440367026023 0ustar jcorganjcorgan Complex To IShort blocks_complex_to_interleaved_short from gnuradio import blocks blocks.complex_to_interleaved_short() in complex out short gnuradio-3.7.2.1/gr-blocks/grc/blocks_moving_average_xx.xml0000664000175000017500000000253212207440367023560 0ustar jcorganjcorgan Moving Average blocks_moving_average_xx from gnuradio import blocks blocks.moving_average_$(type.fcn)($length, $scale, $max_iter) set_length_and_scale($length, $scale) Type type enum Length length 1000 int Scale scale 1 $type.scale Max Iter max_iter 4000 int in $type out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_float_to_short.xml0000664000175000017500000000133112207440367023072 0ustar jcorganjcorgan Float To Short blocks_float_to_short from gnuradio import blocks blocks.float_to_short($vlen, $scale) set_scale($scale) Vec Length vlen 1 int Scale scale 1 real in float $vlen out short $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_vector_insert_x.xml0000664000175000017500000000327212207440367023267 0ustar jcorganjcorgan Vector Insert blocks_vector_insert_x from gnuradio import blocks blocks.vector_insert_$(type.fcn)($vector, $period, $offset) Output Type type enum Vector vector 0, 0, 0 $type.vec_type Periodicity period 100 int Offset offset 0 int in $type out $type Periodicity, the length of the periodicity at which the vector should be inserted at the output. (i.e. one vector for every N output items) Offset sepcifies where in the cycle period we should begin at. gnuradio-3.7.2.1/gr-blocks/grc/blocks_endian_swap.xml0000664000175000017500000000144712207440367022344 0ustar jcorganjcorgan Endian Swap blocks_endian_swap from gnuradio import blocks blocks.endian_swap($type.size) IO Type type enum in $type out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_stretch_ff.xml0000664000175000017500000000123712207440367022200 0ustar jcorganjcorgan Stretch blocks_stretch_ff from gnuradio import blocks blocks.stretch_ff($lo, $vlen) Low lo real Vec. Length vlen 1 int in float $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_udp_sink.xml0000664000175000017500000000305412207440367021664 0ustar jcorganjcorgan UDP Sink blocks_udp_sink from gnuradio import blocks blocks.udp_sink($type.size*$vlen, $ipaddr, $port, $psize, $eof) set_mtu($mtu) Input Type type enum Destination IP Address ipaddr string Destination Port port int Payload Size psize 1472 int Send Null Pkt as EOF eof True bool Vec Length vlen 1 int $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_imag.xml0000664000175000017500000000115612207440367023217 0ustar jcorganjcorgan Complex to Imag blocks_complex_to_imag from gnuradio import blocks blocks.complex_to_imag($vlen) Vec Length vlen 1 int $vlen > 0 in complex $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_ctrlport_probe2_x.xml0000664000175000017500000000537212207702530023517 0ustar jcorganjcorgan Ctrlport Probe blocks_ctrlport_probe2_x from gnuradio import blocks blocks.ctrlport_probe2_$(type.fcn)($name, $desc, $len, $disp_mask) set_length($len) Input Type type enum Name name samples string Description desc Sample Points string Length len 1024 int Display Mask disp_mask gr.DISPTIME int in $type Place this in a graph to export vectors of samples to a GRCP port probe. * Specify the number of samples to transmit at once and the type of default display to use. gnuradio-3.7.2.1/gr-blocks/grc/blocks_copy.xml0000664000175000017500000000270312207440367021022 0ustar jcorganjcorgan Copy blocks_copy from gnuradio import blocks blocks.copy($type.size*$vlen) self.$(id).set_enabled($enabled) set_enabled($enabled) Type type enum Enabled enabled True bool Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_udp_source.xml0000664000175000017500000000311612207440367022217 0ustar jcorganjcorgan UDP Source blocks_udp_source from gnuradio import blocks blocks.udp_source($type.size*$vlen, $ipaddr, $port, $psize, $eof) set_mtu($mtu) Output Type type enum IP Address ipaddr 127.0.0.1 string Port port 1234 int Payload Size psize 1472 int Null Pkt is EOF eof True bool Vec Length vlen 1 int $vlen > 0 out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_add_const_vxx.xml0000664000175000017500000000260712207440367022716 0ustar jcorganjcorgan Add Const blocks_add_const_vxx from gnuradio import blocks blocks.add_const_v$(type.fcn)($const) set_k($const) IO Type type enum Constant const 0 $type.const_type Vec Length vlen 1 int len($const) == $vlen $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_rms_xx.xml0000664000175000017500000000147212207440367021372 0ustar jcorganjcorgan RMS blocks_rms_xx from gnuradio import blocks blocks.rms_$(type.fcn)f($alpha) set_alpha($alpha) Input Type type enum Alpha alpha 0.0001 real in $type out float gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_float.xml0000664000175000017500000000136412207440367023410 0ustar jcorganjcorgan Complex To Float blocks_complex_to_float from gnuradio import blocks blocks.complex_to_float($vlen) Vec Length vlen 1 int $vlen > 0 in complex $vlen re float $vlen im float $vlen 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_add_xx.xml0000664000175000017500000000231312207440367021314 0ustar jcorganjcorgan Add blocks_add_xx from gnuradio import blocks blocks.add_v$(type.fcn)($vlen) IO Type type enum Num Inputs num_inputs 2 int Vec Length vlen 1 int $num_inputs > 1 $vlen > 0 in $type $vlen $num_inputs out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_tag_debug.xml0000664000175000017500000000341112237515111021757 0ustar jcorganjcorgan Tag Debug blocks_tag_debug from gnuradio import blocks blocks.tag_debug($type.size*$vlen, $name, $filter); self.$(id).set_display($display) set_display($display) Input Type type enum Name name string Key Filter filter "" string Num Inputs num_inputs 1 int Vec Length vlen 1 int Display display True bool $num_inputs >= 1 $vlen > 0 in $type $vlen $num_inputs gnuradio-3.7.2.1/gr-blocks/grc/blocks_message_strobe.xml0000664000175000017500000000153512207440367023054 0ustar jcorganjcorgan Message Strobe blocks_message_strobe from gnuradio import blocks import pmt blocks.message_strobe($msg, $period) set_msg($msg) set_period($period) Message PMT msg pmt.intern("TEST") raw Period (ms) period 1000 real set_msg message 1 strobe message 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_float_to_int.xml0000664000175000017500000000131712207440367022531 0ustar jcorganjcorgan Float To Int blocks_float_to_int from gnuradio import blocks blocks.float_to_int($vlen, $scale) set_scale($scale) Vec Length vlen 1 int Scale scale 1 real in float $vlen out int $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_message_burst_source.xml0000664000175000017500000000234312207440367024273 0ustar jcorganjcorgan Message Burst Source blocks_message_burst_source from gnuradio import blocks blocks.message_burst_source($type.size*$vlen, $(id)_msgq_in) Output Type type enum Vec Length vlen 1 int $vlen > 0 in msg out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_interleaved_char_to_complex.xml0000664000175000017500000000163012207702530025567 0ustar jcorganjcorgan IChar To Complex blocks_interleaved_char_to_complex from gnuradio import blocks blocks.interleaved_char_to_complex($vector_input) Vector Input vector_input False enum in byte $vector_input.vlen out complex gnuradio-3.7.2.1/gr-blocks/grc/blocks_vco_c.xml0000664000175000017500000000130512207702530021127 0ustar jcorganjcorgan VCO (complex) blocks_vco_c from gnuradio import blocks blocks.vco_c($samp_rate, $sensitivity, $amplitude) Sample Rate samp_rate real Sensitivity sensitivity real Amplitude amplitude real in float out complex gnuradio-3.7.2.1/gr-blocks/grc/blocks_max_xx.xml0000664000175000017500000000213512207440367021353 0ustar jcorganjcorgan Max blocks_max_xx from gnuradio import blocks blocks.max_$(type.fcn)($vlen) IO Type type enum Num Inputs num_inputs 1 int Vec Length vlen 1 int $num_inputs >= 1 $vlen >= 1 in $type $vlen $num_inputs out $type 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_skiphead.xml0000664000175000017500000000242112207440367021635 0ustar jcorganjcorgan Skip Head blocks_skiphead from gnuradio import blocks blocks.skiphead($type.size*$vlen, $num_items) Type type enum Num Items num_items 1024 int Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_ctrlport_probe_c.xml0000664000175000017500000000257412207440367023420 0ustar jcorganjcorgan Ctrlport Complex Probe blocks_ctrlport_probe_c from gnuradio import blocks blocks.ctrlport_probe_c($name, $desc) Name name constellation string Description desc Constellation Points string in complex Place this in a graph to export complex values to a GRCP port probe. gnuradio-3.7.2.1/gr-blocks/grc/blocks_stream_mux.xml0000664000175000017500000000303612207440367022234 0ustar jcorganjcorgan Stream Mux blocks_stream_mux from gnuradio import blocks blocks.stream_mux($type.size*$vlen, $lengths) Type type enum Lengths lengths 1, 1 int_vector Num Inputs num_inputs 2 int Vec Length vlen 1 int $num_inputs > 0 $num_inputs == len($lengths) $vlen > 0 in $type $vlen $num_inputs out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_packed_to_unpacked_xx.xml0000664000175000017500000000253212207440367024372 0ustar jcorganjcorgan Packed to Unpacked blocks_packed_to_unpacked_xx from gnuradio import blocks blocks.packed_to_unpacked_$(type.fcn)($bits_per_chunk, $endianness) Type type enum Bits per Chunk bits_per_chunk 2 int Endianness endianness int Num Ports num_ports 1 int $num_ports > 0 in $type $num_ports out $type $num_ports gnuradio-3.7.2.1/gr-blocks/grc/blocks_wavfile_sink.xml0000664000175000017500000000164712207440367022537 0ustar jcorganjcorgan Wav File Sink blocks_wavfile_sink from gnuradio import blocks blocks.wavfile_sink($file, $nchan, $samp_rate, $bits_per_sample) open($file) File file file_save N Channels nchan 1 int Sample Rate samp_rate samp_rate int Bits per Sample bits_per_sample 8 int 1 <= $nchan in float $nchan gnuradio-3.7.2.1/gr-blocks/grc/blocks_mute_xx.xml0000664000175000017500000000217112207440367021540 0ustar jcorganjcorgan Mute blocks_mute_xx from gnuradio import blocks blocks.mute_$(type.fcn)(bool($mute)) set_mute(bool($mute)) IO Type type enum Mute mute False raw in $type out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_streams_to_stream.xml0000664000175000017500000000257612207440367023613 0ustar jcorganjcorgan Streams to Stream blocks_streams_to_stream from gnuradio import blocks blocks.streams_to_stream($type.size*$vlen, $num_streams) IO Type type enum Num Streams num_streams 2 int Vec Length vlen 1 int $num_streams > 0 $vlen >= 1 in $type $vlen $num_streams out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_nop.xml0000664000175000017500000000251212207440367020642 0ustar jcorganjcorgan Nop blocks_nop from gnuradio import blocks blocks.nop($type.size*$vlen) Type type enum Num Ports num_ports 1 int Vec Length vlen 1 int $num_ports > 0 $vlen > 0 in $type $vlen $num_ports out $type $vlen $num_ports gnuradio-3.7.2.1/gr-blocks/grc/blocks_vector_to_streams.xml0000664000175000017500000000261312207440367023612 0ustar jcorganjcorgan Vector to Streams blocks_vector_to_streams from gnuradio import blocks blocks.vector_to_streams($type.size*$vlen, $num_streams) IO Type type enum Num Streams num_streams 2 int Vec Length vlen 1 int $num_streams > 0 $vlen >= 1 in $type $vlen*$num_streams out $type $vlen $num_streams gnuradio-3.7.2.1/gr-blocks/grc/blocks_wavfile_source.xml0000664000175000017500000000156012207440367023065 0ustar jcorganjcorgan Wav File Source blocks_wavfile_source from gnuradio import blocks blocks.wavfile_source($file, $repeat) File file file_open Repeat repeat True enum N Channels nchan 1 int 1 <= $nchan out float $nchan gnuradio-3.7.2.1/gr-blocks/grc/blocks_file_meta_sink.xml0000664000175000017500000000522312207440367023021 0ustar jcorganjcorgan File Meta Sink blocks_file_meta_sink from gnuradio import gr, blocks blocks.file_meta_sink($type.size*$vlen, $file, $samp_rate, $rel_rate, $type.dtype, $type.cplx, $max_seg_size, $extra_dict, $detached) self.$(id).set_unbuffered($unbuffered) set_unbuffered($unbuffered) open($file) File file file_save Input Type type enum Sample Rate samp_rate samp_rate real Relative Rate Change rel_rate 1 real Vec Length vlen 1 int Max Seg. Size max_seg_size 1000000 int Extra Dict. extra_dict "" string Detached detached False bool Unbuffered unbuffered False bool $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_pack_k_bits_bb.xml0000664000175000017500000000116612207440367022766 0ustar jcorganjcorgan Pack K Bits blocks_pack_k_bits_bb from gnuradio import blocks blocks.pack_k_bits_bb($k) K k int in byte out byte Pack K unpacked bits (one bit per byte) into a single packed byte containing k bits and 8 - k zeros. gnuradio-3.7.2.1/gr-blocks/grc/blocks_int_to_float.xml0000664000175000017500000000131712207440367022531 0ustar jcorganjcorgan Int To Float blocks_int_to_float from gnuradio import blocks blocks.int_to_float($vlen, $scale) set_scale($scale) Vec Length vlen 1 int Scale scale 1 real in int $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_throttle.xml0000664000175000017500000000260312207440367021714 0ustar jcorganjcorgan Throttle blocks_throttle 1 from gnuradio import blocks blocks.throttle($type.size*$vlen, $samples_per_second) set_sample_rate($samples_per_second) Type type enum Sample Rate samples_per_second samp_rate real Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_interleave.xml0000664000175000017500000000252412207440367022207 0ustar jcorganjcorgan Interleave blocks_interleave from gnuradio import blocks blocks.interleave($type.size*$vlen) IO Type type enum Num Streams num_streams 2 int Vec Length vlen 1 int $num_streams > 0 $vlen >= 1 in $type $vlen $num_streams out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_file_meta_source.xml0000664000175000017500000000346712207440367023365 0ustar jcorganjcorgan File Meta Source blocks_file_meta_source from gnuradio import gr, blocks blocks.file_meta_source($file, $repeat, $detached, $hdr_file) open($file, $repeat) Output Type type enum File file file_open Repeat repeat True enum Detached Header detached False enum Header File hdr_file file_open Vec Length vlen 1 int out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_and_const_xx.xml0000664000175000017500000000166712207440367022547 0ustar jcorganjcorgan And Const blocks_and_const_xx from gnuradio import blocks blocks.and_const_$(type.fcn)($const) set_k($const) IO Type type enum Constant const 0 int in $type out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_keep_one_in_n.xml0000664000175000017500000000247612207440367022647 0ustar jcorganjcorgan Keep 1 in N blocks_keep_one_in_n from gnuradio import blocks blocks.keep_one_in_n($type.size*$vlen, $n) set_n($n) Type type enum N n 1 int Vec Length vlen 1 int $n > 0 $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_probe_signal_x.xml0000664000175000017500000000171612207440367023046 0ustar jcorganjcorgan Probe Signal blocks_probe_signal_x from gnuradio import blocks blocks.probe_signal_$(type.fcn)() Input Type type enum in $type Available functions to probe: level() Use with the function probe block. gnuradio-3.7.2.1/gr-blocks/grc/blocks_conjugate_cc.xml0000664000175000017500000000067012207440367022475 0ustar jcorganjcorgan Complex Conjugate blocks_conjugate_cc from gnuradio import blocks blocks.conjugate_cc() in complex out complex gnuradio-3.7.2.1/gr-blocks/grc/blocks_vco_f.xml0000664000175000017500000000127112207440367021143 0ustar jcorganjcorgan VCO blocks_vco_f from gnuradio import blocks blocks.vco_f($samp_rate, $sensitivity, $amplitude) Sample Rate samp_rate real Sensitivity sensitivity real Amplitude amplitude real in float out float gnuradio-3.7.2.1/gr-blocks/grc/blocks_file_sink.xml0000664000175000017500000000344212237515111022005 0ustar jcorganjcorgan File Sink blocks_file_sink from gnuradio import blocks blocks.file_sink($type.size*$vlen, $file, $append) self.$(id).set_unbuffered($unbuffered) set_unbuffered($unbuffered) open($file) File file file_save Input Type type enum Vec Length vlen 1 int Unbuffered unbuffered False bool Append file append False bool $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_argmax_xx.xml0000664000175000017500000000223512207440367022046 0ustar jcorganjcorgan Argmax blocks_argmax_xx from gnuradio import blocks blocks.argmax_$(type.fcn)($vlen) IO Type type enum Num Inputs num_inputs 2 int Vec Length vlen 1 int $num_inputs >= 1 $vlen >= 1 in $type $vlen $num_inputs max_vec short max_inp short gnuradio-3.7.2.1/gr-blocks/grc/blocks_file_source.xml0000664000175000017500000000273712207440367022356 0ustar jcorganjcorgan File Source blocks_file_source from gnuradio import blocks blocks.file_source($type.size*$vlen, $file, $repeat) open($file, $repeat) File file file_open Output Type type enum Repeat repeat True enum Vec Length vlen 1 int $vlen > 0 out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_multiply_xx.xml0000664000175000017500000000233712207440367022451 0ustar jcorganjcorgan Multiply blocks_multiply_xx from gnuradio import blocks blocks.multiply_v$(type.fcn)($vlen) IO Type type enum Num Inputs num_inputs 2 int Vec Length vlen 1 int $num_inputs > 1 $vlen > 0 in $type $vlen $num_inputs out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_peak_detector2_fb.xml0000664000175000017500000000177512207440367023422 0ustar jcorganjcorgan Peak Detector2 blocks_peak_detector2_fb from gnuradio import blocks blocks.peak_detector2_fb($threshold_factor_rise, $look_ahead, $alpha) set_threshold_factor_rise($threshold_factor_rise) set_look_ahead($look_ahead) set_alpha($alpha) TH Factor Rise threshold_factor_rise 7 real Look Ahead look_ahead 1000 int Alpha alpha 0.001 real in float out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_float_to_complex.xml0000664000175000017500000000136012207440367023404 0ustar jcorganjcorgan Float To Complex blocks_float_to_complex from gnuradio import blocks blocks.float_to_complex($vlen) Vec Length vlen 1 int $vlen > 0 re float $vlen im float $vlen 1 out complex $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_stream_to_tagged_stream.xml0000664000175000017500000000244212237515111024724 0ustar jcorganjcorgan Stream to Tagged Stream blocks_stream_to_tagged_stream from gnuradio import blocks blocks.stream_to_tagged_stream($type.size, $vlen, $packet_len, $len_tag_key) Type type enum Vector Length vlen 1 int Packet Length packet_len int Length Tag Key len_tag_key "packet_len" string in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_and_xx.xml0000664000175000017500000000163512207440367021334 0ustar jcorganjcorgan And blocks_and_xx from gnuradio import blocks blocks.and_$(type.fcn)() IO Type type enum Num Inputs num_inputs 2 int $num_inputs >= 2 in $type $num_inputs out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_repack_bits_bb.xml0000664000175000017500000000172012207440367022777 0ustar jcorganjcorgan Repack Bits blocks_repack_bits_bb from gnuradio import blocks blocks.repack_bits_bb($k, $l, $len_tag_key, $align_output) Bits per input byte k 1 int Bits per output byte l 8 int Length Tag Key len_tag_key "" string Packet Alignment align_output False enum in byte out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_threshold_ff.xml0000664000175000017500000000145112207440367022516 0ustar jcorganjcorgan Threshold blocks_threshold_ff from gnuradio import blocks blocks.threshold_ff($low, $high, $init) set_hi($high) set_lo($low) Low low -100 real High high 100 real Initial State init 0 real in float out float gnuradio-3.7.2.1/gr-blocks/grc/blocks_tags_strobe.xml0000664000175000017500000000307212207702530022355 0ustar jcorganjcorgan Tags Strobe blocks_tags_strobe from gnuradio import blocks import pmt blocks.tags_strobe($type.size*$vlen, $value, $nsamps) set_value($value) set_nsamps($nsamps) Output Type type enum Value (PMT) value pmt.intern("TEST") raw Num. Samples nsamps 1000 int Vec Length vlen 1 int $vlen > 0 out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_message_debug.xml0000664000175000017500000000110512207440367022635 0ustar jcorganjcorgan Message Debug blocks_message_debug from gnuradio import blocks blocks.message_debug() print message 1 store message 1 print_pdu message 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_unpacked_to_packed_xx.xml0000664000175000017500000000253212207440367024372 0ustar jcorganjcorgan Unpacked to Packed blocks_unpacked_to_packed_xx from gnuradio import blocks blocks.unpacked_to_packed_$(type.fcn)($bits_per_chunk, $endianness) Type type enum Bits per Chunk bits_per_chunk 2 int Endianness endianness int Num Ports num_ports 1 int $num_ports > 0 in $type $num_ports out $type $num_ports gnuradio-3.7.2.1/gr-blocks/grc/blocks_xor_xx.xml0000664000175000017500000000163612207440367021403 0ustar jcorganjcorgan Xor blocks_xor_xx from gnuradio import blocks blocks.xor_$(type.fcn)() IO Type type enum Num Inputs num_inputs 2 int $num_inputs >= 2 in $type $num_inputs out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_tagged_stream_to_pdu.xml0000664000175000017500000000225412207440367024231 0ustar jcorganjcorgan Tagged Stream to PDU blocks_tagged_stream_to_pdu from gnuradio import blocks blocks.tagged_stream_to_pdu($type.tv, $tag) Item Type type enum Length tag name tag packet_len string in $type pdus message gnuradio-3.7.2.1/gr-blocks/grc/blocks_regenerate_bb.xml0000664000175000017500000000122612207440367022633 0ustar jcorganjcorgan Regenerate blocks_regenerate_bb from gnuradio import blocks blocks.regenerate_bb($period, $max_regen) Period period int Max Regen Count max_regen 500 int in byte out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_arg.xml0000664000175000017500000000114512207440367023051 0ustar jcorganjcorgan Complex to Arg blocks_complex_to_arg from gnuradio import blocks blocks.complex_to_arg($vlen) Vec Length vlen 1 int $vlen > 0 in complex $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_stream_to_streams.xml0000664000175000017500000000257612207440367023613 0ustar jcorganjcorgan Stream to Streams blocks_stream_to_streams from gnuradio import blocks blocks.stream_to_streams($type.size*$vlen, $num_streams) IO Type type enum Num Streams num_streams 2 int Vec Length vlen 1 int $num_streams > 0 $vlen >= 1 in $type $vlen out $type $vlen $num_streams gnuradio-3.7.2.1/gr-blocks/grc/blocks_probe_signal_vx.xml0000664000175000017500000000216312207440367023231 0ustar jcorganjcorgan Probe Signal Vector blocks_probe_signal_vx from gnuradio import blocks blocks.probe_signal_v$(type.fcn)($vlen) Input Type type enum Vec Length vlen 1 int $vlen > 0 in $type $vlen Available functions to probe: level() Use with the function probe block. gnuradio-3.7.2.1/gr-blocks/grc/blocks_ctrlport_performance.xml0000664000175000017500000000260412207440367024302 0ustar jcorganjcorgan CtrlPort Performance Monitor blocks_ctrlport_monitor_performance from gnuradio.ctrlport.monitor import * not $en or monitor("gr-perf-monitorx") Enabled en enum Place this in a graph to launch a QtPy GR CtrlPort Performance Monitor app. gnuradio-3.7.2.1/gr-blocks/grc/blocks_peak_detector_xb.xml0000664000175000017500000000300612207440367023347 0ustar jcorganjcorgan Peak Detector blocks_peak_detector_xb from gnuradio import blocks blocks.peak_detector_$(type.fcn)b($threshold_factor_rise, $threshold_factor_fall, $look_ahead, $alpha) set_threshold_factor_rise($threshold_factor_rise) set_threshold_factor_fall($threshold_factor_fall) set_look_ahead($look_ahead) set_alpha($alpha) Input Type type enum TH Factor Rise threshold_factor_rise 0.25 real TH Factor Fall threshold_factor_fall 0.40 real Look Ahead look_ahead 10 int Alpha alpha 0.001 real in $type out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_tuntap_pdu.xml0000664000175000017500000000136712207440367022240 0ustar jcorganjcorgan TUNTAP PDU blocks_tuntap_pdu from gnuradio import blocks blocks.tuntap_pdu($ifn, $mtu) Interface Name ifn tun0 string MTU mtu 10000 int pdus message 1 pdus message 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_tagged_stream_mux.xml0000664000175000017500000000275512237515111023547 0ustar jcorganjcorgan Tagged Stream Mux blocks_tagged_stream_mux from gnuradio import blocks blocks.tagged_stream_mux($type.size*$vlen, $lengthtagname, $tag_preserve_head_pos) IO Type type enum Number of inputs ninputs int Length tag names lengthtagname string Vector Length vlen 1 int Tags: Preserve head position on input tag_preserve_head_pos 0 int part in $type $vlen $ninputs out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_short_to_float.xml0000664000175000017500000000133112207440367023072 0ustar jcorganjcorgan Short To Float blocks_short_to_float from gnuradio import blocks blocks.short_to_float($vlen, $scale) set_scale($scale) Vec Length vlen 1 int Scale scale 1 real in short $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_real.xml0000664000175000017500000000120612207440367023221 0ustar jcorganjcorgan Complex To Real blocks_complex_to_real from gnuradio import blocks blocks.complex_to_real($vlen) Vec Length vlen 1 int $vlen > 0 in complex $vlen re float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_nlog10_ff.xml0000664000175000017500000000143712207440367021626 0ustar jcorganjcorgan Log10 blocks_nlog10_ff from gnuradio import blocks blocks.nlog10_ff($n, $vlen, $k) n n 1 real k k 0 real Vec Length vlen 1 int $vlen >= 1 in float $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_unpack_k_bits_bb.xml0000664000175000017500000000077212207440367023333 0ustar jcorganjcorgan Unpack K Bits blocks_unpack_k_bits_bb from gnuradio import blocks blocks.unpack_k_bits_bb($k) K k int in byte out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_tag_gate.xml0000664000175000017500000000265012207440367021624 0ustar jcorganjcorgan Tag Gate blocks_tag_gate from gnuradio import blocks blocks.tag_gate($type.size * $vlen, $propagate_tags) Item Type type enum Vec Length vlen 1 int Propagate_tags propagate_tags False enum $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_null_source.xml0000664000175000017500000000213512207440367022401 0ustar jcorganjcorgan Null Source blocks_null_source from gnuradio import blocks blocks.null_source($type.size*$vlen) Output Type type enum Vec Length vlen 1 int $vlen > 0 out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_vector_to_stream.xml0000664000175000017500000000253512207440367023432 0ustar jcorganjcorgan Vector to Stream blocks_vector_to_stream from gnuradio import blocks blocks.vector_to_stream($type.size*$vlen, $num_items) IO Type type enum Num Items num_items 2 int Vec Length vlen 1 int $num_items > 0 $vlen >= 1 in $type $vlen*$num_items out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_float_to_char.xml0000664000175000017500000000132412207440367022652 0ustar jcorganjcorgan Float To Char blocks_float_to_char from gnuradio import blocks blocks.float_to_char($vlen, $scale) set_scale($scale) Vec Length vlen 1 int Scale scale 1 real in float $vlen out byte $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_complex_to_mag_squared.xml0000664000175000017500000000120512207440367024565 0ustar jcorganjcorgan Complex to Mag^2 blocks_complex_to_mag_squared from gnuradio import blocks blocks.complex_to_mag_squared($vlen) Vec Length vlen 1 int $vlen > 0 in complex $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_message_sink.xml0000664000175000017500000000271212207440367022520 0ustar jcorganjcorgan Message Sink blocks_message_sink from gnuradio import blocks blocks.message_sink($type.size*$vlen, $(id)_msgq_out, $dont_block) Input Type type enum Don't Block dont_block False enum Vec Length vlen 1 int $vlen > 0 in $type $vlen out msg gnuradio-3.7.2.1/gr-blocks/grc/blocks_vector_sink_x.xml0000664000175000017500000000201512207440367022721 0ustar jcorganjcorgan Vector Sink blocks_vector_sink_x from gnuradio import blocks blocks.vector_sink_$(type.fcn)($vlen) Input Type type enum Vec Length vlen 1 int $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_plateau_detector_fb.xml0000664000175000017500000000107212207440367024041 0ustar jcorganjcorgan Plateau Detector blocks_plateau_detector_fb from gnuradio import blocks blocks.plateau_detector_fb($max_len, $threshold) Max. plateau length max_len int Threshold threshold 0.9 real in float out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_not_xx.xml0000664000175000017500000000135712207440367021373 0ustar jcorganjcorgan Not blocks_not_xx from gnuradio import blocks blocks.not_$(type.fcn)() IO Type type enum in $type out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_pdu_to_tagged_stream.xml0000664000175000017500000000203312207440367024224 0ustar jcorganjcorgan PDU to Tagged Stream blocks_pdu_to_tagged_stream from gnuradio import blocks blocks.pdu_to_tagged_stream($type.tv, $tag) Item Type type enum Length tag name tag packet_len string pdus message out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_multiply_const_vxx.xml0000664000175000017500000000263312207440367024044 0ustar jcorganjcorgan Multiply Const blocks_multiply_const_vxx from gnuradio import blocks blocks.multiply_const_v$(type.fcn)($const) set_k($const) IO Type type enum Constant const 0 $type.const_type Vec Length vlen 1 int len($const) == $vlen $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_repeat.xml0000664000175000017500000000235712207440367021335 0ustar jcorganjcorgan Repeat blocks_repeat from gnuradio import blocks blocks.repeat($type.size*$vlen, $interp) Type type enum Interpolation interp int Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_char_to_short.xml0000664000175000017500000000110212207440367022676 0ustar jcorganjcorgan Char To Short blocks_char_to_short from gnuradio import blocks blocks.char_to_short($vlen) Vec Length vlen 1 int in byte $vlen out short $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_vector_source_x.xml0000664000175000017500000000322112207440367023255 0ustar jcorganjcorgan Vector Source blocks_vector_source_x from gnuradio import blocks blocks.vector_source_$(type.fcn)($vector, $repeat, $vlen, $tags) Output Type type enum Vector vector (0, 0, 0) raw Tags tags [] raw Repeat repeat True enum Vec Length vlen 1 int $vlen > 0 out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_ctrlport_viewer.xml0000664000175000017500000000251612207440367023304 0ustar jcorganjcorgan CtrlPort Monitor blocks_ctrlport_monitor from gnuradio.ctrlport.monitor import * not $en or monitor() Enabled en enum Place this in a graph to launch a QtPy GR CtrlPort Monitor app. gnuradio-3.7.2.1/gr-blocks/grc/blocks_file_descriptor_source.xml0000664000175000017500000000270412207440367024606 0ustar jcorganjcorgan File Descriptor Source blocks_file_descriptor_source from gnuradio import blocks blocks.file_descriptor_source($type.size*$vlen, $fd, $repeat) File Descriptor fd int Output Type type enum Repeat repeat True enum Vec Length vlen 1 int $vlen > 0 out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_divide_XX.xml0000664000175000017500000000232712207440367021735 0ustar jcorganjcorgan Divide blocks_divide_xx from gnuradio import blocks blocks.divide_$(type.fcn)($vlen) IO Type type enum Vec Length vlen 1 int Num Inputs num_inputs 2 int $vlen > 0 $num_inputs >= 2 in $type $vlen $num_inputs out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_transcendental.xml0000664000175000017500000000151712207440367023057 0ustar jcorganjcorgan Transcendental blocks_transcendental from gnuradio import blocks blocks.transcendental($name, "$type") Type type enum Function Name name cos string in $type.type out $type.type gnuradio-3.7.2.1/gr-blocks/grc/blocks_float_uchar.xml0000664000175000017500000000067212207440367022342 0ustar jcorganjcorgan Float To UChar blocks_float_to_uchar from gnuradio import blocks blocks.float_to_uchar() in float out byte gnuradio-3.7.2.1/gr-blocks/grc/blocks_stream_to_vector.xml0000664000175000017500000000253512207440367023432 0ustar jcorganjcorgan Stream to Vector blocks_stream_to_vector from gnuradio import blocks blocks.stream_to_vector($type.size*$vlen, $num_items) IO Type type enum Num Items num_items 2 int Vec Length vlen 1 int $num_items > 0 $vlen >= 1 in $type $vlen out $type $vlen*$num_items gnuradio-3.7.2.1/gr-blocks/grc/blocks_delay.xml0000664000175000017500000000274112207440367021150 0ustar jcorganjcorgan Delay blocks_delay from gnuradio import blocks blocks.delay($type.size*$vlen, $delay) set_dly($delay) Type type enum Delay delay 0 int Num Ports num_ports 1 int Vec Length vlen 1 int $num_ports > 0 $vlen > 0 in $type $vlen $num_ports out $type $vlen $num_ports gnuradio-3.7.2.1/gr-blocks/grc/blocks_patterned_interleaver.xml0000664000175000017500000000256112207440367024440 0ustar jcorganjcorgan Patterned Interleaver blocks_patterned_interleaver from gnuradio import blocks blocks.patterned_interleaver($type.size*$vlen, $pattern) IO Type type enum Pattern pattern [0,0,1,2] int_vector Vec Length vlen 1 int $vlen >= 1 in $type $vlen 1+max($pattern) out $type $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_burst_tagger.xml0000664000175000017500000000345312207440367022543 0ustar jcorganjcorgan Burst Tagger blocks_burst_tagger from gnuradio import blocks blocks.burst_tagger($type.size) self.$(id).set_true_tag($true_key,$true_value) self.$(id).set_false_tag($false_key,$false_value) set_true_tag($true_key,$true_value) set_false_tag($false_key,$false_value) Stream Type type enum True KeyID true_key burst string True Value true_value True bool False KeyID false_key burst string False Value false_value False bool in $type 1 trigger short 1 out $type 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_uchar_to_float.xml0000664000175000017500000000067212207440367023044 0ustar jcorganjcorgan UChar To Float blocks_uchar_to_float from gnuradio import blocks blocks.uchar_to_float() in byte out float gnuradio-3.7.2.1/gr-blocks/grc/blocks_random_pdu.xml0000664000175000017500000000136712207440367022205 0ustar jcorganjcorgan Random PDU Generator blocks_random_pdu from gnuradio import blocks import pmt blocks.random_pdu($minsize, $maxsize) Min Bytes minsize 50 int Max Bytes maxsize 2000 int generate message 1 pdus message 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_keep_m_in_n.xml0000664000175000017500000000300412207440367022306 0ustar jcorganjcorgan Keep M in N blocks_keep_m_in_n from gnuradio import blocks blocks.keep_m_in_n($type.size, $m, $n, $offset) set_offset($offset) set_m($m) set_n($n) Type type enum M m 1 int N n 2 int initial offset offset 0 int $n > 0 $m > 0 $m <= $n in $type 1 out $type 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_or_xx.xml0000664000175000017500000000163112207440367021206 0ustar jcorganjcorgan Or blocks_or_xx from gnuradio import blocks blocks.or_$(type.fcn)() IO Type type enum Num Inputs num_inputs 2 int $num_inputs >= 2 in $type $num_inputs out $type gnuradio-3.7.2.1/gr-blocks/grc/blocks_socket_pdu.xml0000664000175000017500000000246212207440367022212 0ustar jcorganjcorgan Socket PDU blocks_socket_pdu from gnuradio import blocks blocks.socket_pdu($type, $host, $port, $mtu) Type type TCP_SERVER enum Host host string Port port 52001 string MTU mtu 10000 int pdus message 1 pdus message 1 gnuradio-3.7.2.1/gr-blocks/grc/blocks_char_to_float.xml0000664000175000017500000000132412207440367022652 0ustar jcorganjcorgan Char To Float blocks_char_to_float from gnuradio import blocks blocks.char_to_float($vlen, $scale) set_scale($scale) Vec Length vlen 1 int Scale scale 1 real in byte $vlen out float $vlen gnuradio-3.7.2.1/gr-blocks/grc/blocks_streams_to_vector.xml0000664000175000017500000000261312207440367023612 0ustar jcorganjcorgan Streams to Vector blocks_streams_to_vector from gnuradio import blocks blocks.streams_to_vector($type.size*$vlen, $num_streams) IO Type type enum Num Streams num_streams 2 int Vec Length vlen 1 int $num_streams > 0 $vlen >= 1 in $type $vlen $num_streams out $type $vlen*$num_streams gnuradio-3.7.2.1/gr-blocks/grc/blocks_null_sink.xml0000664000175000017500000000211712207440367022045 0ustar jcorganjcorgan Null Sink blocks_null_sink from gnuradio import blocks blocks.null_sink($type.size*$vlen) Input Type type enum Vec Length vlen 1 int $vlen > 0 in $type $vlen gnuradio-3.7.2.1/gr-blocks/doc/0000775000175000017500000000000012214652673015764 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/doc/CMakeLists.txt0000664000175000017500000000152412207440367020523 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.blocks DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-blocks/doc/blocks.dox0000664000175000017500000000106712214652673017761 0ustar jcorganjcorgan/*! \page page_blocks Standard GNU Radio Blocks \section Introduction This is the gr-blocks package. It contains many of the generic, standard, or simple blocks used for many aspects of building GNU Radio flowgraphs. To use these blocks, the Python module is gnuradio.blocks, which would be normally imported as: \code from gnuradio import blocks \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(blocks) \endcode */ gnuradio-3.7.2.1/gr-blocks/doc/README.blocks0000664000175000017500000000067112207440367020121 0ustar jcorganjcorganThis is the gr-blocks package. It contains the basic blocks that are widely used in many different types of flowgraphs. To use these blocks, the Python namespace is in gnuradio.blocks, which would be normally imported as: from gnuradio import blocks See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(blocks) gnuradio-3.7.2.1/gr-blocks/python/0000775000175000017500000000000012207440367016535 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/python/blocks/0000775000175000017500000000000012243433176020012 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/python/blocks/qa_block_gateway.py0000664000175000017500000002002612207440367023660 0ustar jcorganjcorgan# # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import numpy import pmt from gnuradio import gr, gr_unittest, blocks class add_2_f32_1_f32(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "add 2 f32", in_sig = [numpy.float32, numpy.float32], out_sig = [numpy.float32], ) def work(self, input_items, output_items): output_items[0][:] = input_items[0] + input_items[1] return len(output_items[0]) class add_2_fc32_1_fc32(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "add 2 fc32", in_sig = [numpy.complex64, numpy.complex64], out_sig = [numpy.complex64], ) def work(self, input_items, output_items): output_items[0][:] = input_items[0] + input_items[1] return len(output_items[0]) class convolve(gr.sync_block): """ A demonstration using block history to properly perform a convolution. """ def __init__(self): gr.sync_block.__init__( self, name = "convolve", in_sig = [numpy.float32], out_sig = [numpy.float32] ) self._taps = [1, 0, 0, 0] self.set_history(len(self._taps)) def work(self, input_items, output_items): output_items[0][:] = numpy.convolve(input_items[0], self._taps, mode='valid') return len(output_items[0]) class decim2x(gr.decim_block): def __init__(self): gr.decim_block.__init__( self, name = "decim2x", in_sig = [numpy.float32], out_sig = [numpy.float32], decim = 2 ) def work(self, input_items, output_items): output_items[0][:] = input_items[0][::2] return len(output_items[0]) class interp2x(gr.interp_block): def __init__(self): gr.interp_block.__init__( self, name = "interp2x", in_sig = [numpy.float32], out_sig = [numpy.float32], interp = 2 ) def work(self, input_items, output_items): output_items[0][1::2] = input_items[0] output_items[0][::2] = input_items[0] return len(output_items[0]) class tag_source(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "tag source", in_sig = None, out_sig = [numpy.float32], ) def work(self, input_items, output_items): num_output_items = len(output_items[0]) #put code here to fill the output items... #make a new tag on the middle element every time work is called count = self.nitems_written(0) + num_output_items/2 key = pmt.string_to_symbol("example_key") value = pmt.string_to_symbol("example_value") self.add_item_tag(0, count, key, value) return num_output_items class tag_sink(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "tag sink", in_sig = [numpy.float32], out_sig = None, ) self.key = None def work(self, input_items, output_items): num_input_items = len(input_items[0]) #put code here to process the input items... #print all the tags received in this work call nread = self.nitems_read(0) tags = self.get_tags_in_range(0, nread, nread+num_input_items) for tag in tags: #print tag.offset #print pmt.symbol_to_string(tag.key) #print pmt.symbol_to_string(tag.value) self.key = pmt.symbol_to_string(tag.key) return num_input_items class fc32_to_f32_2(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "fc32_to_f32_2", in_sig = [numpy.complex64], out_sig = [(numpy.float32, 2)], ) def work(self, input_items, output_items): output_items[0][::,0] = numpy.real(input_items[0]) output_items[0][::,1] = numpy.imag(input_items[0]) return len(output_items[0]) class vector_to_stream(gr.interp_block): def __init__(self, itemsize, nitems_per_block): gr.interp_block.__init__( self, name = "vector_to_stream", in_sig = [(itemsize, nitems_per_block)], out_sig = [itemsize], interp = nitems_per_block ) self.block_size = nitems_per_block def work(self, input_items, output_items): n = 0 for i in xrange(len(input_items[0])): for j in xrange(self.block_size): output_items[0][n] = input_items[0][i][j] n += 1 return len(output_items[0]) class test_block_gateway(gr_unittest.TestCase): def test_add_f32(self): tb = gr.top_block() src0 = blocks.vector_source_f([1, 3, 5, 7, 9], False) src1 = blocks.vector_source_f([0, 2, 4, 6, 8], False) adder = add_2_f32_1_f32() sink = blocks.vector_sink_f() tb.connect((src0, 0), (adder, 0)) tb.connect((src1, 0), (adder, 1)) tb.connect(adder, sink) tb.run() self.assertEqual(sink.data(), (1, 5, 9, 13, 17)) def test_add_fc32(self): tb = gr.top_block() src0 = blocks.vector_source_c([1, 3j, 5, 7j, 9], False) src1 = blocks.vector_source_c([0, 2j, 4, 6j, 8], False) adder = add_2_fc32_1_fc32() sink = blocks.vector_sink_c() tb.connect((src0, 0), (adder, 0)) tb.connect((src1, 0), (adder, 1)) tb.connect(adder, sink) tb.run() self.assertEqual(sink.data(), (1, 5j, 9, 13j, 17)) def test_convolve(self): tb = gr.top_block() src = blocks.vector_source_f([1, 2, 3, 4, 5, 6, 7, 8], False) cv = convolve() sink = blocks.vector_sink_f() tb.connect(src, cv, sink) tb.run() self.assertEqual(sink.data(), (1, 2, 3, 4, 5, 6, 7, 8)) def test_decim2x(self): tb = gr.top_block() src = blocks.vector_source_f([1, 2, 3, 4, 5, 6, 7, 8], False) d2x = decim2x() sink = blocks.vector_sink_f() tb.connect(src, d2x, sink) tb.run() self.assertEqual(sink.data(), (1, 3, 5, 7)) def test_interp2x(self): tb = gr.top_block() src = blocks.vector_source_f([1, 3, 5, 7, 9], False) i2x = interp2x() sink = blocks.vector_sink_f() tb.connect(src, i2x, sink) tb.run() self.assertEqual(sink.data(), (1, 1, 3, 3, 5, 5, 7, 7, 9, 9)) def test_tags(self): src = tag_source() sink = tag_sink() head = blocks.head(gr.sizeof_float, 50000) #should be enough items to get a tag through tb = gr.top_block() tb.connect(src, head, sink) tb.run() self.assertEqual(sink.key, "example_key") def test_fc32_to_f32_2(self): tb = gr.top_block() src = blocks.vector_source_c([1+2j, 3+4j, 5+6j, 7+8j, 9+10j], False) convert = fc32_to_f32_2() v2s = vector_to_stream(numpy.float32, 2) sink = blocks.vector_sink_f() tb.connect(src, convert, v2s, sink) tb.run() self.assertEqual(sink.data(), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) if __name__ == '__main__': gr_unittest.run(test_block_gateway, "test_block_gateway.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_patterned_interleaver.py0000775000175000017500000000335612207440367025445 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_patterned_interleaver (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_000(self): dst_data = [0,0,1,2,0,2,1,0]; src0 = blocks.vector_source_f(200*[0]) src1 = blocks.vector_source_f(200*[1]) src2 = blocks.vector_source_f(200*[2]) itg = blocks.patterned_interleaver(gr.sizeof_float, dst_data) dst = blocks.vector_sink_f() head = blocks.head(gr.sizeof_float, 8); self.tb.connect( src0, (itg,0) ); self.tb.connect( src1, (itg,1) ); self.tb.connect( src2, (itg,2) ); self.tb.connect( itg, head, dst ); self.tb.run() self.assertEqual(list(dst_data), list(dst.data())) if __name__ == '__main__': gr_unittest.run(test_patterned_interleaver, "test_patterned_interleaver.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_throttle.py0000775000175000017500000000226112207440367022716 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_throttle(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_01(self): # Test that we can make the block op = blocks.throttle(gr.sizeof_gr_complex, 1) if __name__ == '__main__': gr_unittest.run(test_throttle, "test_throttle.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/CMakeLists.txt0000664000175000017500000000400712207702530022544 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py parse_file_metadata.py stream_to_vector_decimator.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/blocks COMPONENT "blocks_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") # Force out the controlport QA tests if we've disabled it. if(NOT ENABLE_GR_CTRLPORT) list(REMOVE_ITEM py_qa_test_files ${CMAKE_CURRENT_SOURCE_DIR}/qa_cpp_py_binding.py ${CMAKE_CURRENT_SOURCE_DIR}/qa_cpp_py_binding_set.py ${CMAKE_CURRENT_SOURCE_DIR}/qa_ctrlport_probes.py ) endif(NOT ENABLE_GR_CTRLPORT) foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_tag_debug.py0000775000175000017500000000261412207440367022774 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_tag_debug(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): # Just run some data through and make sure it doesn't puke. src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) src = blocks.vector_source_i(src_data) op = blocks.tag_debug(gr.sizeof_int, "tag QA") self.tb.connect(src, op) self.tb.run() x = op.current_tags() if __name__ == '__main__': gr_unittest.run(test_tag_debug, "test_tag_debug.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_regenerate.py0000775000175000017500000000477312207440367023204 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_regenerate(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_regen1(self): tb = self.tb data = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] expected_result = (0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) src = blocks.vector_source_b(data, False) regen = blocks.regenerate_bb(5, 2) dst = blocks.vector_sink_b() tb.connect(src, regen) tb.connect(regen, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) def test_regen2(self): tb = self.tb data = 200*[0,] data[9] = 1 data[99] = 1 expected_result = 200*[0,] expected_result[9] = 1 expected_result[19] = 1 expected_result[29] = 1 expected_result[39] = 1 expected_result[99] = 1 expected_result[109] = 1 expected_result[119] = 1 expected_result[129] = 1 src = blocks.vector_source_b(data, False) regen = blocks.regenerate_bb(10, 3) dst = blocks.vector_sink_b() tb.connect(src, regen) tb.connect(regen, dst) tb.run () dst_data = dst.data() self.assertEqual(tuple(expected_result), dst_data) if __name__ == '__main__': gr_unittest.run(test_regenerate, "test_regenerate.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_skiphead.py0000775000175000017500000000676012207440367022651 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_skiphead(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() self.src_data = [int(x) for x in range(65536)] def tearDown(self): self.tb = None def test_skip_0(self): skip_cnt = 0 expected_result = tuple(self.src_data[skip_cnt:]) src1 = blocks.vector_source_i(self.src_data) op = blocks.skiphead(gr.sizeof_int, skip_cnt) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_skip_1(self): skip_cnt = 1 expected_result = tuple(self.src_data[skip_cnt:]) src1 = blocks.vector_source_i(self.src_data) op = blocks.skiphead(gr.sizeof_int, skip_cnt) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_skip_1023(self): skip_cnt = 1023 expected_result = tuple(self.src_data[skip_cnt:]) src1 = blocks.vector_source_i(self.src_data) op = blocks.skiphead(gr.sizeof_int, skip_cnt) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_skip_6339(self): skip_cnt = 6339 expected_result = tuple(self.src_data[skip_cnt:]) src1 = blocks.vector_source_i(self.src_data) op = blocks.skiphead(gr.sizeof_int, skip_cnt) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_skip_12678(self): skip_cnt = 12678 expected_result = tuple(self.src_data[skip_cnt:]) src1 = blocks.vector_source_i(self.src_data) op = blocks.skiphead(gr.sizeof_int, skip_cnt) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) def test_skip_all(self): skip_cnt = len(self.src_data) expected_result = tuple(self.src_data[skip_cnt:]) src1 = blocks.vector_source_i(self.src_data) op = blocks.skiphead(gr.sizeof_int, skip_cnt) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_skiphead, "test_skiphead.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_interleave.py0000775000175000017500000000552412207440367023214 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_interleave (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_int_001 (self): lenx = 64 src0 = blocks.vector_source_f (range (0, lenx, 4)) src1 = blocks.vector_source_f (range (1, lenx, 4)) src2 = blocks.vector_source_f (range (2, lenx, 4)) src3 = blocks.vector_source_f (range (3, lenx, 4)) op = blocks.interleave (gr.sizeof_float) dst = blocks.vector_sink_f () self.tb.connect (src0, (op, 0)) self.tb.connect (src1, (op, 1)) self.tb.connect (src2, (op, 2)) self.tb.connect (src3, (op, 3)) self.tb.connect (op, dst) self.tb.run () expected_result = tuple (range (lenx)) result_data = dst.data () self.assertFloatTuplesAlmostEqual (expected_result, result_data) def test_deint_001 (self): lenx = 64 src = blocks.vector_source_f (range (lenx)) op = blocks.deinterleave (gr.sizeof_float) dst0 = blocks.vector_sink_f () dst1 = blocks.vector_sink_f () dst2 = blocks.vector_sink_f () dst3 = blocks.vector_sink_f () self.tb.connect (src, op) self.tb.connect ((op, 0), dst0) self.tb.connect ((op, 1), dst1) self.tb.connect ((op, 2), dst2) self.tb.connect ((op, 3), dst3) self.tb.run () expected_result0 = tuple (range (0, lenx, 4)) expected_result1 = tuple (range (1, lenx, 4)) expected_result2 = tuple (range (2, lenx, 4)) expected_result3 = tuple (range (3, lenx, 4)) self.assertFloatTuplesAlmostEqual (expected_result0, dst0.data ()) self.assertFloatTuplesAlmostEqual (expected_result1, dst1.data ()) self.assertFloatTuplesAlmostEqual (expected_result2, dst2.data ()) self.assertFloatTuplesAlmostEqual (expected_result3, dst3.data ()) if __name__ == '__main__': gr_unittest.run(test_interleave, "test_interleave.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_tag_file_sink.py0000664000175000017500000000464412207440367023653 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import os, struct class test_tag_file_sink(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) trg_data = (-1, -1, 1, 1, -1, -1, 1, 1, -1, -1) src = blocks.vector_source_i(src_data) trg = blocks.vector_source_s(trg_data) op = blocks.burst_tagger(gr.sizeof_int) snk = blocks.tagged_file_sink(gr.sizeof_int, 1) self.tb.connect(src, (op,0)) self.tb.connect(trg, (op,1)) self.tb.connect(op, snk) self.tb.run() # Tagged file sink gets 2 burst tags at index 2 and index 5. # Creates two new files, each with two integers in them from # src_data at these indexes (3,4) and (7,8). file0 = "file{0}_0_2.00000000.dat".format(snk.unique_id()) file1 = "file{0}_1_6.00000000.dat".format(snk.unique_id()) # Open the files and read in the data, then remove the files # to clean up the directory. outfile0 = file(file0, 'rb') outfile1 = file(file1, 'rb') data0 = outfile0.read(8) data1 = outfile1.read(8) outfile0.close() outfile1.close() os.remove(file0) os.remove(file1) # Convert the 8 bytes from the files into a tuple of 2 ints. idata0 = struct.unpack('ii', data0) idata1 = struct.unpack('ii', data1) self.assertEqual(idata0, (3, 4)) self.assertEqual(idata1, (7, 8)) if __name__ == '__main__': gr_unittest.run(test_tag_file_sink, "test_tag_file_sink.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_message.py0000775000175000017500000001130212207440367022471 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import time from gnuradio import gr, gr_unittest, blocks import pmt def all_counts(): return (gr.block_ncurrently_allocated(), gr.block_detail_ncurrently_allocated(), gr.buffer_ncurrently_allocated(), gr.buffer_reader_ncurrently_allocated(), gr.message_ncurrently_allocated()) class test_message(gr_unittest.TestCase): def setUp(self): self.msgq = gr.msg_queue() def tearDown(self): self.msgq = None def leak_check(self, fct): begin = all_counts() fct() # tear down early so we can check for leaks self.tearDown() end = all_counts() self.assertEqual(begin, end) def test_100(self): msg = gr.message(0, 1.5, 2.3) self.assertEquals(0, msg.type()) self.assertAlmostEqual(1.5, msg.arg1()) self.assertAlmostEqual(2.3, msg.arg2()) self.assertEquals(0, msg.length()) def test_101(self): s = 'This is a test' msg = gr.message_from_string(s) self.assertEquals(s, msg.to_string()) def test_200(self): self.leak_check(self.body_200) def body_200(self): self.msgq.insert_tail(gr.message(0)) self.assertEquals(1, self.msgq.count()) self.msgq.insert_tail(gr.message(1)) self.assertEquals(2, self.msgq.count()) msg0 = self.msgq.delete_head() self.assertEquals(0, msg0.type()) msg1 = self.msgq.delete_head() self.assertEquals(1, msg1.type()) self.assertEquals(0, self.msgq.count()) def test_201(self): self.leak_check(self.body_201) def body_201(self): self.msgq.insert_tail(gr.message(0)) self.assertEquals(1, self.msgq.count()) self.msgq.insert_tail(gr.message(1)) self.assertEquals(2, self.msgq.count()) def test_202(self): self.leak_check(self.body_202) def body_202(self): # global msg msg = gr.message(666) def test_300(self): input_data = (0,1,2,3,4,5,6,7,8,9) src = blocks.vector_source_b(input_data) dst = blocks.vector_sink_b() tb = gr.top_block() tb.connect(src, dst) tb.run() self.assertEquals(input_data, dst.data()) def test_301(self): # Use itemsize, limit constructor src = blocks.message_source(gr.sizeof_char) dst = blocks.vector_sink_b() tb = gr.top_block() tb.connect(src, dst) src.msgq().insert_tail(gr.message_from_string('01234')) src.msgq().insert_tail(gr.message_from_string('5')) src.msgq().insert_tail(gr.message_from_string('')) src.msgq().insert_tail(gr.message_from_string('6789')) src.msgq().insert_tail(gr.message(1)) # send EOF tb.run() self.assertEquals(tuple(map(ord, '0123456789')), dst.data()) def test_302(self): # Use itemsize, msgq constructor msgq = gr.msg_queue() src = blocks.message_source(gr.sizeof_char, msgq) dst = blocks.vector_sink_b() tb = gr.top_block() tb.connect(src, dst) src.msgq().insert_tail(gr.message_from_string('01234')) src.msgq().insert_tail(gr.message_from_string('5')) src.msgq().insert_tail(gr.message_from_string('')) src.msgq().insert_tail(gr.message_from_string('6789')) src.msgq().insert_tail(gr.message(1)) # send EOF tb.run() self.assertEquals(tuple(map(ord, '0123456789')), dst.data()) def test_debug_401(self): msg = pmt.intern("TESTING") src = blocks.message_strobe(msg, 500) snk = blocks.message_debug() tb = gr.top_block() tb.msg_connect(src, "strobe", snk, "store") tb.start() time.sleep(1) tb.stop() tb.wait() rec_msg = snk.get_message(0) self.assertTrue(pmt.eqv(rec_msg, msg)) if __name__ == '__main__': gr_unittest.run(test_message, "test_message.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_sample_and_hold.py0000664000175000017500000000334212207440367024160 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import time from gnuradio import gr, gr_unittest, blocks class test_sample_and_hold(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = 10*[0,1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1] ctrl_data = 10*[1,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0] expected_result = 10*(0,0,0,0,4,5,6,7,8,9,9,9,9,9,9,9,9,9) src = blocks.vector_source_f(src_data) ctrl = blocks.vector_source_b(ctrl_data) op = blocks.sample_and_hold_ff() dst = blocks.vector_sink_f() self.tb.connect(src, (op,0)) self.tb.connect(ctrl, (op,1)) self.tb.connect(op, dst) self.tb.run() result = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result, places=6) if __name__ == '__main__': gr_unittest.run(test_sample_and_hold, "test_sample_and_hold.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_vector_insert.py0000775000175000017500000000332012207440367023734 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_vector_insert(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = [float(x) for x in range(16)] expected_result = tuple(src_data) period = 9177; offset = 0; src = blocks.null_source(1) head = blocks.head(1, 10000000); ins = blocks.vector_insert_b([1], period, offset); dst = blocks.vector_sink_b() self.tb.connect(src, head, ins, dst) self.tb.run() result_data = dst.data() for i in range(10000): if(i%period == offset): self.assertEqual(1, result_data[i]) else: self.assertEqual(0, result_data[i]) if __name__ == '__main__': gr_unittest.run(test_vector_insert, "test_vector_insert.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_moving_average.py0000664000175000017500000000476012207440367024045 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math, random def make_random_complex_tuple(L, scale=1): result = [] for x in range(L): result.append(scale*complex(2*random.random()-1, 2*random.random()-1)) return tuple(result) def make_random_float_tuple(L, scale=1): result = [] for x in range(L): result.append(scale*(2*random.random()-1)) return tuple(result) class test_moving_average(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_01(self): tb = self.tb N = 10000 seed = 0 data = make_random_float_tuple(N, 1) expected_result = N*[0,] src = blocks.vector_source_f(data, False) op = blocks.moving_average_ff(100, 0.001) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() dst_data = dst.data() # make sure result is close to zero self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 1) def test_02(self): tb = self.tb N = 10000 seed = 0 data = make_random_complex_tuple(N, 1) expected_result = N*[0,] src = blocks.vector_source_c(data, False) op = blocks.moving_average_cc(100, 0.001) dst = blocks.vector_sink_c() tb.connect(src, op) tb.connect(op, dst) tb.run() dst_data = dst.data() # make sure result is close to zero self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 1) if __name__ == '__main__': gr_unittest.run(test_moving_average, "test_moving_average.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_null_sink_source.py0000664000175000017500000000260112207440367024422 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_null_sink_source(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): # Just running some data through null source/sink src = blocks.null_source(gr.sizeof_float) hed = blocks.head(gr.sizeof_float, 100) dst = blocks.null_sink(gr.sizeof_float) self.tb.connect(src, hed, dst) self.tb.run() if __name__ == '__main__': gr_unittest.run(test_null_sink_source, "test_null_sink_source.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_head.py0000775000175000017500000000273612207440367021761 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_head(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_head(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) expected_result = (1, 2, 3, 4) src1 = blocks.vector_source_i(src_data) op = blocks.head(gr.sizeof_int, 4) dst1 = blocks.vector_sink_i() self.tb.connect(src1, op) self.tb.connect(op, dst1) self.tb.run() dst_data = dst1.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_head, "test_head.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/parse_file_metadata.py0000664000175000017500000001460512207440367024343 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import sys from gnuradio import gr, blocks import pmt ''' sr Sample rate (samples/second) time Time as uint64(secs), double(fractional secs) type Type of data (see gr_file_types enum) cplx is complex? (True or False) strt Start of data (or size of header) in bytes size Size of data in bytes ''' HEADER_LENGTH = blocks.METADATA_HEADER_SIZE ftype_to_string = {blocks.GR_FILE_BYTE: "bytes", blocks.GR_FILE_SHORT: "short", blocks.GR_FILE_INT: "int", blocks.GR_FILE_LONG: "long", blocks.GR_FILE_LONG_LONG: "long long", blocks.GR_FILE_FLOAT: "float", blocks.GR_FILE_DOUBLE: "double" } ftype_to_size = {blocks.GR_FILE_BYTE: gr.sizeof_char, blocks.GR_FILE_SHORT: gr.sizeof_short, blocks.GR_FILE_INT: gr.sizeof_int, blocks.GR_FILE_LONG: gr.sizeof_int, blocks.GR_FILE_LONG_LONG: 2*gr.sizeof_int, blocks.GR_FILE_FLOAT: gr.sizeof_float, blocks.GR_FILE_DOUBLE: gr.sizeof_double} def parse_header(p, VERBOSE=False): dump = pmt.PMT_NIL info = dict() if(pmt.is_dict(p) is False): sys.stderr.write("Header is not a PMT dictionary: invalid or corrupt data file.\n") sys.exit(1) # GET FILE FORMAT VERSION NUMBER if(pmt.dict_has_key(p, pmt.string_to_symbol("version"))): r = pmt.dict_ref(p, pmt.string_to_symbol("version"), dump) version = pmt.to_long(r) if(VERBOSE): print "Version Number: {0}".format(version) else: sys.stderr.write("Could not find key 'version': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SAMPLE RATE if(pmt.dict_has_key(p, pmt.string_to_symbol("rx_rate"))): r = pmt.dict_ref(p, pmt.string_to_symbol("rx_rate"), dump) samp_rate = pmt.to_double(r) info["rx_rate"] = samp_rate if(VERBOSE): print "Sample Rate: {0:.2f} sps".format(samp_rate) else: sys.stderr.write("Could not find key 'sr': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT TIME STAMP if(pmt.dict_has_key(p, pmt.string_to_symbol("rx_time"))): r = pmt.dict_ref(p, pmt.string_to_symbol("rx_time"), dump) secs = pmt.tuple_ref(r, 0) fracs = pmt.tuple_ref(r, 1) secs = float(pmt.to_uint64(secs)) fracs = pmt.to_double(fracs) t = secs + fracs info["rx_time"] = t if(VERBOSE): print "Seconds: {0:.6f}".format(t) else: sys.stderr.write("Could not find key 'time': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT ITEM SIZE if(pmt.dict_has_key(p, pmt.string_to_symbol("size"))): r = pmt.dict_ref(p, pmt.string_to_symbol("size"), dump) dsize = pmt.to_long(r) info["size"] = dsize if(VERBOSE): print "Item size: {0}".format(dsize) else: sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT DATA TYPE if(pmt.dict_has_key(p, pmt.string_to_symbol("type"))): r = pmt.dict_ref(p, pmt.string_to_symbol("type"), dump) dtype = pmt.to_long(r) stype = ftype_to_string[dtype] info["type"] = stype if(VERBOSE): print "Data Type: {0} ({1})".format(stype, dtype) else: sys.stderr.write("Could not find key 'type': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT COMPLEX if(pmt.dict_has_key(p, pmt.string_to_symbol("cplx"))): r = pmt.dict_ref(p, pmt.string_to_symbol("cplx"), dump) cplx = pmt.to_bool(r) info["cplx"] = cplx if(VERBOSE): print "Complex? {0}".format(cplx) else: sys.stderr.write("Could not find key 'cplx': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT WHERE CURRENT SEGMENT STARTS if(pmt.dict_has_key(p, pmt.string_to_symbol("strt"))): r = pmt.dict_ref(p, pmt.string_to_symbol("strt"), dump) seg_start = pmt.to_uint64(r) info["hdr_len"] = seg_start info["extra_len"] = seg_start - HEADER_LENGTH info["has_extra"] = info["extra_len"] > 0 if(VERBOSE): print "Header Length: {0} bytes".format(info["hdr_len"]) print "Extra Length: {0}".format((info["extra_len"])) print "Extra Header? {0}".format(info["has_extra"]) else: sys.stderr.write("Could not find key 'strt': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SIZE OF DATA if(pmt.dict_has_key(p, pmt.string_to_symbol("bytes"))): r = pmt.dict_ref(p, pmt.string_to_symbol("bytes"), dump) nbytes = pmt.to_uint64(r) nitems = nbytes/dsize info["nitems"] = nitems info["nbytes"] = nbytes if(VERBOSE): print "Size of Data: {0} bytes".format(nbytes) print " {0} items".format(nitems) else: sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) return info # IF THERE IS EXTRA DATA, PULL OUT THE DICTIONARY AND PARSE IT def parse_extra_dict(p, info, VERBOSE=False): if(pmt.is_dict(p) is False): sys.stderr.write("Extra header is not a PMT dictionary: invalid or corrupt data file.\n") sys.exit(1) items = pmt.dict_items(p) nitems = pmt.length(items) for i in xrange(nitems): item = pmt.nth(i, items) key = pmt.symbol_to_string(pmt.car(item)) val = pmt.cdr(item) info[key] = val if(VERBOSE): print "{0}: {1}".format(key, val) return info gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_unpack_k_bits.py0000775000175000017500000000343512207440367023671 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import random class test_unpack(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_001(self): src_data = (1,0,1,1,0,1,1,0) expected_results = (1,0,1,1,0,1,1,0) src = blocks.vector_source_b(src_data,False) op = blocks.unpack_k_bits_bb(1) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_002(self): src_data = ( 2, 3, 0, 1) expected_results = (1,0,1,1,0,0,0,1) src = blocks.vector_source_b(src_data,False) op = blocks.unpack_k_bits_bb(2) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) if __name__ == '__main__': gr_unittest.run(test_unpack, "test_unpack.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_stream_to_tagged_stream.py0000775000175000017500000000347712237515112025740 0ustar jcorganjcorgan#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 202013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest from gnuradio import blocks class qa_stream_to_tagged_stream (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): src_data = (1, ) * 50 packet_len = 10L len_tag_key = 'packet_len' src = blocks.vector_source_f(src_data, False, 1) tagger = blocks.stream_to_tagged_stream(gr.sizeof_float, 1, packet_len, len_tag_key) sink = blocks.vector_sink_f() self.tb.connect(src, tagger, sink) self.tb.run () self.assertEqual(sink.data(), src_data) tags = [gr.tag_to_python(x) for x in sink.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) expected_tags = [(long(pos), 'packet_len', packet_len) for pos in range(0, 50, 10) ] self.assertEqual(tags, expected_tags) if __name__ == '__main__': gr_unittest.run(qa_stream_to_tagged_stream, "qa_stream_to_tagged_stream.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_hier_block2.py0000775000175000017500000003657312207702530023242 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr, gr_unittest, blocks import numpy class add_ff(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "add_ff", in_sig = [numpy.float32, numpy.float32], out_sig = [numpy.float32], ) def work(self, input_items, output_items): output_items[0][:] = input_items[0] + input_items[1] return len(output_items[0]) class multiply_const_ff(gr.sync_block): def __init__(self, k): gr.sync_block.__init__( self, name = "multiply_ff", in_sig = [numpy.float32], out_sig = [numpy.float32], ) self.k = k def work(self, input_items, output_items): output_items[0][:] = map(lambda x: self.k*x, input_items[0]) return len(output_items[0]) class test_hier_block2(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_001_make(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) self.assertEqual("test_block", hblock.name()) self.assertEqual(1, hblock.input_signature().max_streams()) self.assertEqual(1, hblock.output_signature().min_streams()) self.assertEqual(1, hblock.output_signature().max_streams()) self.assertEqual(gr.sizeof_int, hblock.output_signature().sizeof_stream_item(0)) def test_002_connect_input(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(hblock, nop1) def test_004_connect_output(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(nop1, hblock) def test_005_connect_output_in_use(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) nop2 = blocks.nop(gr.sizeof_int) hblock.connect(nop1, hblock) self.assertRaises(ValueError, lambda: hblock.connect(nop2, hblock)) def test_006_connect_invalid_src_port_neg(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) self.assertRaises(ValueError, lambda: hblock.connect((hblock, -1), nop1)) def test_005_connect_invalid_src_port_exceeds(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) self.assertRaises(ValueError, lambda: hblock.connect((hblock, 1), nop1)) def test_007_connect_invalid_dst_port_neg(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) nop2 = blocks.nop(gr.sizeof_int) self.assertRaises(ValueError, lambda: hblock.connect(nop1, (nop2, -1))) def test_008_connect_invalid_dst_port_exceeds(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.null_sink(gr.sizeof_int) nop2 = blocks.null_sink(gr.sizeof_int) self.assertRaises(ValueError, lambda: hblock.connect(nop1, (nop2, 1))) def test_009_check_topology(self): hblock = gr.top_block("test_block") hblock.check_topology(0, 0) def test_010_run(self): expected = (1.0, 2.0, 3.0, 4.0) hblock = gr.top_block("test_block") src = blocks.vector_source_f(expected, False) sink1 = blocks.vector_sink_f() sink2 = blocks.vector_sink_f() hblock.connect(src, sink1) hblock.connect(src, sink2) hblock.run() actual1 = sink1.data() actual2 = sink2.data() self.assertEquals(expected, actual1) self.assertEquals(expected, actual2) def test_012_disconnect_input(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(hblock, nop1) hblock.disconnect(hblock, nop1) def test_013_disconnect_input_not_connected(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) nop2 = blocks.nop(gr.sizeof_int) hblock.connect(hblock, nop1) self.assertRaises(ValueError, lambda: hblock.disconnect(hblock, nop2)) def test_014_disconnect_input_neg(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(hblock, nop1) self.assertRaises(ValueError, lambda: hblock.disconnect((hblock, -1), nop1)) def test_015_disconnect_input_exceeds(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(hblock, nop1) self.assertRaises(ValueError, lambda: hblock.disconnect((hblock, 1), nop1)) def test_016_disconnect_output(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(nop1, hblock) hblock.disconnect(nop1, hblock) def test_017_disconnect_output_not_connected(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) nop2 = blocks.nop(gr.sizeof_int) hblock.connect(nop1, hblock) self.assertRaises(ValueError, lambda: hblock.disconnect(nop2, hblock)) def test_018_disconnect_output_neg(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(hblock, nop1) self.assertRaises(ValueError, lambda: hblock.disconnect(nop1, (hblock, -1))) def test_019_disconnect_output_exceeds(self): hblock = gr.hier_block2("test_block", gr.io_signature(1,1,gr.sizeof_int), gr.io_signature(1,1,gr.sizeof_int)) nop1 = blocks.nop(gr.sizeof_int) hblock.connect(nop1, hblock) self.assertRaises(ValueError, lambda: hblock.disconnect(nop1, (hblock, 1))) def test_020_run(self): hblock = gr.top_block("test_block") data = (1.0, 2.0, 3.0, 4.0) src = blocks.vector_source_f(data, False) dst = blocks.vector_sink_f() hblock.connect(src, dst) hblock.run() self.assertEquals(data, dst.data()) def test_021_connect_single(self): hblock = gr.top_block("test_block") blk = gr.hier_block2("block", gr.io_signature(0, 0, 0), gr.io_signature(0, 0, 0)) hblock.connect(blk) def test_022_connect_single_with_ports(self): hblock = gr.top_block("test_block") blk = gr.hier_block2("block", gr.io_signature(1, 1, 1), gr.io_signature(1, 1, 1)) self.assertRaises(ValueError, lambda: hblock.connect(blk)) def test_023_connect_single_twice(self): hblock = gr.top_block("test_block") blk = gr.hier_block2("block", gr.io_signature(0, 0, 0), gr.io_signature(0, 0, 0)) hblock.connect(blk) self.assertRaises(ValueError, lambda: hblock.connect(blk)) def test_024_disconnect_single(self): hblock = gr.top_block("test_block") blk = gr.hier_block2("block", gr.io_signature(0, 0, 0), gr.io_signature(0, 0, 0)) hblock.connect(blk) hblock.disconnect(blk) def test_025_disconnect_single_not_connected(self): hblock = gr.top_block("test_block") blk = gr.hier_block2("block", gr.io_signature(0, 0, 0), gr.io_signature(0, 0, 0)) self.assertRaises(ValueError, lambda: hblock.disconnect(blk)) def test_026_run_single(self): expected_data = (1.0,) tb = gr.top_block("top_block") hb = gr.hier_block2("block", gr.io_signature(0, 0, 0), gr.io_signature(0, 0, 0)) src = blocks.vector_source_f(expected_data) dst = blocks.vector_sink_f() hb.connect(src, dst) tb.connect(hb) tb.run() self.assertEquals(expected_data, dst.data()) def test_027a_internally_unconnected_input(self): tb = gr.top_block() hb = gr.hier_block2("block", gr.io_signature(1, 1, 1), gr.io_signature(1, 1, 1)) hsrc = blocks.vector_source_b([1,]) hb.connect(hsrc, hb) # wire output internally src = blocks.vector_source_b([1, ]) dst = blocks.vector_sink_b() tb.connect(src, hb, dst) # hb's input is not connected internally self.assertRaises(RuntimeError, lambda: tb.run()) def test_027b_internally_unconnected_output(self): tb = gr.top_block() hb = gr.hier_block2("block", gr.io_signature(1, 1, 1), gr.io_signature(1, 1, 1)) hdst = blocks.vector_sink_b() hb.connect(hb, hdst) # wire input internally src = blocks.vector_source_b([1, ]) dst = blocks.vector_sink_b() tb.connect(src, hb, dst) # hb's output is not connected internally self.assertRaises(RuntimeError, lambda: tb.run()) def test_027c_fully_unconnected_output(self): tb = gr.top_block() hb = gr.hier_block2("block", gr.io_signature(1, 1, 1), gr.io_signature(1, 1, 1)) hsrc = blocks.vector_sink_b() hb.connect(hb, hsrc) # wire input internally src = blocks.vector_source_b([1, ]) dst = blocks.vector_sink_b() tb.connect(src, hb) # hb's output is not connected internally or externally self.assertRaises(RuntimeError, lambda: tb.run()) def test_027d_fully_unconnected_input(self): tb = gr.top_block() hb = gr.hier_block2("block", gr.io_signature(1, 1, 1), gr.io_signature(1, 1, 1)) hdst = blocks.vector_source_b([1,]) hb.connect(hdst, hb) # wire output internally dst = blocks.vector_sink_b() tb.connect(hb, dst) # hb's input is not connected internally or externally self.assertRaises(RuntimeError, lambda: tb.run()) def test_028_singleton_reconfigure(self): tb = gr.top_block() hb = gr.hier_block2("block", gr.io_signature(0, 0, 0), gr.io_signature(0, 0, 0)) src = blocks.vector_source_b([1, ]) dst = blocks.vector_sink_b() hb.connect(src, dst) tb.connect(hb) # Singleton connect tb.lock() tb.disconnect_all() tb.connect(src, dst) tb.unlock() def test_029_singleton_disconnect(self): tb = gr.top_block() src = blocks.vector_source_b([1, ]) dst = blocks.vector_sink_b() tb.connect(src, dst) tb.disconnect(src) # Singleton disconnect tb.connect(src, dst) tb.run() self.assertEquals(dst.data(), (1,)) def test_030_nested_input(self): tb = gr.top_block() src = blocks.vector_source_b([1,]) hb1 = gr.hier_block2("hb1", gr.io_signature(1, 1, gr.sizeof_char), gr.io_signature(0, 0, 0)) hb2 = gr.hier_block2("hb2", gr.io_signature(1, 1, gr.sizeof_char), gr.io_signature(0, 0, 0)) dst = blocks.vector_sink_b() tb.connect(src, hb1) hb1.connect(hb1, hb2) hb2.connect(hb2, blocks.copy(gr.sizeof_char), dst) tb.run() self.assertEquals(dst.data(), (1,)) def test_031_multiple_internal_inputs(self): tb = gr.top_block() src = blocks.vector_source_f([1.0,]) hb = gr.hier_block2("hb", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float)) m1 = multiply_const_ff(1.0) m2 = multiply_const_ff(2.0) add = add_ff() hb.connect(hb, m1) # m1 is connected to hb external input #0 hb.connect(hb, m2) # m2 is also connected to hb external input #0 hb.connect(m1, (add, 0)) hb.connect(m2, (add, 1)) hb.connect(add, hb) # add is connected to hb external output #0 dst = blocks.vector_sink_f() tb.connect(src, hb, dst) tb.run() self.assertEquals(dst.data(), (3.0,)) def test_032_nested_multiple_internal_inputs(self): tb = gr.top_block() src = blocks.vector_source_f([1.0,]) hb = gr.hier_block2("hb", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float)) hb2 = gr.hier_block2("hb", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(1, 1, gr.sizeof_float)) m1 = multiply_const_ff(1.0) m2 = multiply_const_ff(2.0) add = add_ff() hb2.connect(hb2, m1) # m1 is connected to hb2 external input #0 hb2.connect(hb2, m2) # m2 is also connected to hb2 external input #0 hb2.connect(m1, (add, 0)) hb2.connect(m2, (add, 1)) hb2.connect(add, hb2) # add is connected to hb2 external output #0 hb.connect(hb, hb2, hb) # hb as hb2 as nested internal block dst = blocks.vector_sink_f() tb.connect(src, hb, dst) tb.run() self.assertEquals(dst.data(), (3.0,)) def test_033a_set_affinity(self): expected = (1.0, 2.0, 3.0, 4.0) hblock = gr.top_block("test_block") src = blocks.vector_source_f(expected, False) snk = blocks.vector_sink_f() hblock.connect(src, snk) hblock.set_processor_affinity([0,]) hblock.run() actual = snk.data() self.assertEquals(expected, actual) def test_033b_unset_affinity(self): expected = (1.0, 2.0, 3.0, 4.0) hblock = gr.top_block("test_block") src = blocks.vector_source_f(expected, False) snk = blocks.vector_sink_f() hblock.connect(src, snk) hblock.set_processor_affinity([0,]) hblock.unset_processor_affinity() hblock.run() actual = snk.data() self.assertEquals(expected, actual) def test_033c_get_affinity(self): expected = (1.0, 2.0, 3.0, 4.0) hblock = gr.top_block("test_block") src = blocks.vector_source_f(expected, False) snk = blocks.vector_sink_f() hblock.connect(src, snk) hblock.set_processor_affinity([0,]) procs = hblock.processor_affinity() self.assertEquals((0,), procs) if __name__ == "__main__": gr_unittest.run(test_hier_block2, "test_hier_block2.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_repack_bits_bb.py0000775000175000017500000001064412207440367024006 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random from gnuradio import gr, gr_unittest, blocks import pmt class qa_repack_bits_bb (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_simple (self): """ Very simple test, 2 bits -> 1 """ src_data = (0b11, 0b01, 0b10) expected_data = (0b1, 0b1, 0b1, 0b0, 0b0, 0b1) k = 2 l = 1 src = blocks.vector_source_b(src_data, False, 1) repack = blocks.repack_bits_bb(k, l) sink = blocks.vector_sink_b() self.tb.connect(src, repack, sink) self.tb.run () self.assertEqual(sink.data(), expected_data) def test_002_three (self): """ 8 -> 3 """ src_data = (0b11111101, 0b11111111, 0b11111111) expected_data = (0b101,) + (0b111,) * 7 k = 8 l = 3 src = blocks.vector_source_b(src_data, False, 1) repack = blocks.repack_bits_bb(k, l) sink = blocks.vector_sink_b() self.tb.connect(src, repack, sink) self.tb.run () self.assertEqual(sink.data(), expected_data) def test_003_lots_of_bytes (self): """ Lots and lots of bytes, multiple packer stages """ src_data = tuple([random.randint(0, 255) for x in range(3*5*7*8 * 10)]) src = blocks.vector_source_b(src_data, False, 1) repack1 = blocks.repack_bits_bb(8, 3) repack2 = blocks.repack_bits_bb(3, 5) repack3 = blocks.repack_bits_bb(5, 7) repack4 = blocks.repack_bits_bb(7, 8) sink = blocks.vector_sink_b() self.tb.connect(src, repack1, repack2, repack3, repack4, sink) self.tb.run () self.assertEqual(sink.data(), src_data) def test_004_three_with_tags (self): """ 8 -> 3 """ src_data = (0b11111101, 0b11111111) expected_data = (0b101,) + (0b111,) * 4 + (0b001,) k = 8 l = 3 tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(src_data)) src = blocks.vector_source_b(src_data, False, 1, (tag,)) repack = blocks.repack_bits_bb(k, l, tag_name) sink = blocks.vector_sink_b() self.tb.connect(src, repack, sink) self.tb.run () self.assertEqual(sink.data(), expected_data) try: out_tag = sink.tags()[0] except: self.assertFail() self.assertEqual(out_tag.offset, 0) self.assertEqual(pmt.symbol_to_string(out_tag.key), tag_name) self.assertEqual(pmt.to_long(out_tag.value), len(expected_data)) def test_005_three_with_tags_trailing (self): """ 3 -> 8, trailing bits """ src_data = (0b101,) + (0b111,) * 4 + (0b001,) expected_data = (0b11111101, 0b11111111) k = 3 l = 8 tag_name = "len" tag = gr.tag_t() tag.offset = 0 tag.key = pmt.string_to_symbol(tag_name) tag.value = pmt.from_long(len(src_data)) src = blocks.vector_source_b(src_data, False, 1, (tag,)) repack = blocks.repack_bits_bb(k, l, tag_name, True) sink = blocks.vector_sink_b() self.tb.connect(src, repack, sink) self.tb.run () self.assertEqual(sink.data(), expected_data) try: out_tag = sink.tags()[0] except: self.assertFail() self.assertEqual(out_tag.offset, 0) self.assertEqual(pmt.symbol_to_string(out_tag.key), tag_name) self.assertEqual(pmt.to_long(out_tag.value), len(expected_data)) if __name__ == '__main__': gr_unittest.run(qa_repack_bits_bb, "qa_repack_bits_bb.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_tag_gate.py0000775000175000017500000000264712207440367022634 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 <+YOU OR YOUR COMPANY+>. # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import pmt class qa_tag_gate (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): tag = gr.tag_t() tag.key = pmt.string_to_symbol('key') tag.value = pmt.from_long(42) tag.offset = 0 src = blocks.vector_source_f(range(20), False, 1, (tag,)) gate = blocks.tag_gate(gr.sizeof_float, False) sink = blocks.vector_sink_f() self.tb.run () self.assertEqual(len(sink.tags()), 0) if __name__ == '__main__': gr_unittest.run(qa_tag_gate, "qa_tag_gate.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_endian_swap.py0000664000175000017500000000354412207440367023343 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import ctypes class test_endian_swap(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = [1,2,3,4] expected_result = [256, 512, 768, 1024]; src = blocks.vector_source_s(src_data) op = blocks.endian_swap(2) dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() result_data = list(dst.data()) self.assertEqual(expected_result, result_data) def test_002(self): src_data = [1,2,3,4] expected_result = [16777216, 33554432, 50331648, 67108864]; src = blocks.vector_source_i(src_data) op = blocks.endian_swap(4) dst = blocks.vector_sink_i() self.tb.connect(src, op, dst) self.tb.run() result_data = list(dst.data()) self.assertEqual(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_endian_swap, "test_endian_swap.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_tags_strobe.py0000664000175000017500000000533512207702530023360 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import pmt import math class test_tags_strobe(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): N = 10000 nsamps = 1000 ntags = N / nsamps - 1 src = blocks.tags_strobe(gr.sizeof_float, pmt.intern("TEST"), nsamps) hed = blocks.head(gr.sizeof_float, N) dst = blocks.vector_sink_f() self.tb.connect(src, hed, dst) self.tb.run() self.assertEqual(ntags, len(dst.tags())) n_expected = nsamps for tag in dst.tags(): self.assertEqual(tag.offset, n_expected) n_expected += nsamps def test_002(self): N = 10000 nsamps = 123 ntags = N / nsamps src = blocks.tags_strobe(gr.sizeof_float, pmt.intern("TEST"), nsamps) hed = blocks.head(gr.sizeof_float, N) dst = blocks.vector_sink_f() self.tb.connect(src, hed, dst) self.tb.run() self.assertEqual(ntags, len(dst.tags())) n_expected = nsamps for tag in dst.tags(): self.assertEqual(tag.offset, n_expected) n_expected += nsamps def test_003(self): N = 100000 nsamps = 10000 ntags = N / nsamps - 1 src = blocks.tags_strobe(gr.sizeof_float, pmt.intern("TEST"), nsamps) hed = blocks.head(gr.sizeof_float, N) dst = blocks.vector_sink_f() self.tb.connect(src, hed, dst) self.tb.run() self.assertEqual(ntags, len(dst.tags())) n_expected = nsamps for tag in dst.tags(): self.assertEqual(tag.offset, n_expected) n_expected += nsamps if __name__ == '__main__': gr_unittest.run(test_tags_strobe, "test_tags_strobe.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_pipe_fittings.py0000775000175000017500000000773412207440367023727 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks def calc_expected_result(src_data, n): assert (len(src_data) % n) == 0 result = [list() for x in range(n)] #print "len(result) =", len(result) for i in xrange(len(src_data)): (result[i % n]).append(src_data[i]) return [tuple(x) for x in result] class test_pipe_fittings(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_001(self): """ Test stream_to_streams. """ n = 8 src_len = n * 8 src_data = range(src_len) expected_results = calc_expected_result(src_data, n) #print "expected results: ", expected_results src = blocks.vector_source_i(src_data) op = blocks.stream_to_streams(gr.sizeof_int, n) self.tb.connect(src, op) dsts = [] for i in range(n): dst = blocks.vector_sink_i() self.tb.connect((op, i), (dst, 0)) dsts.append(dst) self.tb.run() for d in range(n): self.assertEqual(expected_results[d], dsts[d].data()) def test_002(self): # Test streams_to_stream (using stream_to_streams). n = 8 src_len = n * 8 src_data = tuple(range(src_len)) expected_results = src_data src = blocks.vector_source_i(src_data) op1 = blocks.stream_to_streams(gr.sizeof_int, n) op2 = blocks.streams_to_stream(gr.sizeof_int, n) dst = blocks.vector_sink_i() self.tb.connect(src, op1) for i in range(n): self.tb.connect((op1, i), (op2, i)) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_003(self): #Test streams_to_vector (using stream_to_streams & vector_to_stream). n = 8 src_len = n * 8 src_data = tuple(range(src_len)) expected_results = src_data src = blocks.vector_source_i(src_data) op1 = blocks.stream_to_streams(gr.sizeof_int, n) op2 = blocks.streams_to_vector(gr.sizeof_int, n) op3 = blocks.vector_to_stream(gr.sizeof_int, n) dst = blocks.vector_sink_i() self.tb.connect(src, op1) for i in range(n): self.tb.connect((op1, i), (op2, i)) self.tb.connect(op2, op3, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_004(self): #Test vector_to_streams. n = 8 src_len = n * 8 src_data = tuple(range(src_len)) expected_results = src_data src = blocks.vector_source_i(src_data) op1 = blocks.stream_to_vector(gr.sizeof_int, n) op2 = blocks.vector_to_streams(gr.sizeof_int, n) op3 = blocks.streams_to_stream(gr.sizeof_int, n) dst = blocks.vector_sink_i() self.tb.connect(src, op1, op2) for i in range(n): self.tb.connect((op2, i), (op3, i)) self.tb.connect(op3, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) if __name__ == '__main__': gr_unittest.run(test_pipe_fittings, "test_pipe_fittings.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_argmax.py0000664000175000017500000000422212207440367022324 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_arg_max(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): tb = self.tb src1_data = (0,0.2,-0.3,0,12,0) src2_data = (0,0.0,3.0,0,10,0) src3_data = (0,0.0,3.0,0,1,0) src1 = blocks.vector_source_f(src1_data) s2v1 = blocks.stream_to_vector(gr.sizeof_float, len(src1_data)) tb.connect(src1, s2v1) src2 = blocks.vector_source_f(src2_data) s2v2 = blocks.stream_to_vector(gr.sizeof_float, len(src1_data)) tb.connect(src2, s2v2) src3 = blocks.vector_source_f(src3_data) s2v3 = blocks.stream_to_vector(gr.sizeof_float, len(src1_data)) tb.connect(src3, s2v3) dst1 = blocks.vector_sink_s() dst2 = blocks.vector_sink_s() argmax = blocks.argmax_fs(len(src1_data)) tb.connect(s2v1, (argmax, 0)) tb.connect(s2v2, (argmax, 1)) tb.connect(s2v3, (argmax, 2)) tb.connect((argmax,0), dst1) tb.connect((argmax,1), dst2) tb.run() index = dst1.data() source = dst2.data() self.assertEqual(index, (4,)) self.assertEqual(source, (0,)) if __name__ == '__main__': gr_unittest.run(test_arg_max, "test_arg_max.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_mute.py0000775000175000017500000000573512207440367022034 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_mute(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def help_ii(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_i(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_i() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ff(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_f(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_f() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_cc(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_c(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_c() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def test_unmute_ii(self): src_data = (1, 2, 3, 4, 5) expected_result = (1, 2, 3, 4, 5) op = blocks.mute_ii(False) self.help_ii((src_data,), expected_result, op) def test_mute_ii(self): src_data = (1, 2, 3, 4, 5) expected_result = (0, 0, 0, 0, 0) op = blocks.mute_ii(True) self.help_ii((src_data,), expected_result, op) def test_unmute_cc(self): src_data = (1+5j, 2+5j, 3+5j, 4+5j, 5+5j) expected_result = (1+5j, 2+5j, 3+5j, 4+5j, 5+5j) op = blocks.mute_cc(False) self.help_cc((src_data,), expected_result, op) def test_unmute_cc(self): src_data = (1+5j, 2+5j, 3+5j, 4+5j, 5+5j) expected_result =(0+0j, 0+0j, 0+0j, 0+0j, 0+0j) op = blocks.mute_cc(True) self.help_cc((src_data,), expected_result, op) if __name__ == '__main__': gr_unittest.run(test_mute, "test_mute.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_packed_to_unpacked.py0000775000175000017500000002541712207440367024664 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import random class test_packing(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_001(self): src_data = (0x80,) expected_results = (1,0,0,0,0,0,0,0) src = blocks.vector_source_b(src_data, False) op = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_002(self): src_data = (0x80,) expected_results = (0,0,0,0,0,0,0,1) src = blocks.vector_source_b(src_data, False) op = blocks.packed_to_unpacked_bb(1, gr.GR_LSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_003(self): src_data = (0x11,) expected_results = (4, 2) src = blocks.vector_source_b(src_data, False) op = blocks.packed_to_unpacked_bb(3, gr.GR_LSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_004(self): src_data = (0x11,) expected_results = (0, 4) src = blocks.vector_source_b(src_data, False) op = blocks.packed_to_unpacked_bb(3, gr.GR_MSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_005(self): src_data = (1,0,0,0,0,0,1,0,0,1,0,1,1,0,1,0) expected_results = (0x82, 0x5a) src = blocks.vector_source_b(src_data, False) op = blocks.unpacked_to_packed_bb(1, gr.GR_MSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_006(self): src_data = (0,1,0,0,0,0,0,1,0,1,0,1,1,0,1,0) expected_results = (0x82, 0x5a) src = blocks.vector_source_b(src_data, False) op = blocks.unpacked_to_packed_bb(1, gr.GR_LSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_007(self): src_data = (4, 2, 0,0,0) expected_results = (0x11,) src = blocks.vector_source_b(src_data, False) op = blocks.unpacked_to_packed_bb(3, gr.GR_LSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_008(self): src_data = (0, 4, 2,0,0) expected_results = (0x11,) src = blocks.vector_source_b(src_data,False) op = blocks.unpacked_to_packed_bb(3, gr.GR_MSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_009(self): random.seed(0) src_data = [] for i in xrange(202): src_data.append((random.randint(0,255))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_b(tuple(src_data), False) op1 = blocks.packed_to_unpacked_bb(3, gr.GR_MSB_FIRST) op2 = blocks.unpacked_to_packed_bb(3, gr.GR_MSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results[0:201], dst.data()) def test_010(self): random.seed(0) src_data = [] for i in xrange(56): src_data.append((random.randint(0,255))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_b(tuple(src_data), False) op1 = blocks.packed_to_unpacked_bb(7, gr.GR_MSB_FIRST) op2 = blocks.unpacked_to_packed_bb(7, gr.GR_MSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results[0:201], dst.data()) def test_011(self): random.seed(0) src_data = [] for i in xrange(56): src_data.append((random.randint(0,255))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_b(tuple(src_data),False) op1 = blocks.packed_to_unpacked_bb(7, gr.GR_LSB_FIRST) op2 = blocks.unpacked_to_packed_bb(7, gr.GR_LSB_FIRST) dst = blocks.vector_sink_b() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results[0:201], dst.data()) # tests on shorts def test_100a(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**15,2**15-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_s(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ss(1, gr.GR_MSB_FIRST) op2 = blocks.unpacked_to_packed_ss(1, gr.GR_MSB_FIRST) dst = blocks.vector_sink_s() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_100b(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**15,2**15-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_s(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ss(1, gr.GR_LSB_FIRST) op2 = blocks.unpacked_to_packed_ss(1, gr.GR_LSB_FIRST) dst = blocks.vector_sink_s() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_101a(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**15,2**15-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_s(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ss(8, gr.GR_MSB_FIRST) op2 = blocks.unpacked_to_packed_ss(8, gr.GR_MSB_FIRST) dst = blocks.vector_sink_s() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_101b(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**15,2**15-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_s(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ss(8, gr.GR_LSB_FIRST) op2 = blocks.unpacked_to_packed_ss(8, gr.GR_LSB_FIRST) dst = blocks.vector_sink_s() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) # tests on ints def test_200a(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**31,2**31-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_i(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ii(1, gr.GR_MSB_FIRST) op2 = blocks.unpacked_to_packed_ii(1, gr.GR_MSB_FIRST) dst = blocks.vector_sink_i() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_200b(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**31,2**31-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_i(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ii(1, gr.GR_LSB_FIRST) op2 = blocks.unpacked_to_packed_ii(1, gr.GR_LSB_FIRST) dst = blocks.vector_sink_i() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_201a(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**31,2**31-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_i(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ii(8, gr.GR_MSB_FIRST) op2 = blocks.unpacked_to_packed_ii(8, gr.GR_MSB_FIRST) dst = blocks.vector_sink_i() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_201b(self): random.seed(0) src_data = [] for i in xrange(100): src_data.append((random.randint(-2**31,2**31-1))) src_data = tuple(src_data) expected_results = src_data src = blocks.vector_source_i(tuple(src_data), False) op1 = blocks.packed_to_unpacked_ii(8, gr.GR_LSB_FIRST) op2 = blocks.unpacked_to_packed_ii(8, gr.GR_LSB_FIRST) dst = blocks.vector_sink_i() self.tb.connect(src, op1, op2) self.tb.connect(op2, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) if __name__ == '__main__': gr_unittest.run(test_packing, "test_packing.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_vector_sink_source.py0000775000175000017500000000377612207440367024773 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_vector_sink_source(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = [float(x) for x in range(16)] expected_result = tuple(src_data) src = blocks.vector_source_f(src_data) dst = blocks.vector_sink_f() self.tb.connect(src, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_002(self): src_data = [float(x) for x in range(16)] expected_result = tuple(src_data) src = blocks.vector_source_f(src_data, False, 2) dst = blocks.vector_sink_f(2) self.tb.connect(src, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_003(self): src_data = [float(x) for x in range(16)] expected_result = tuple(src_data) self.assertRaises(RuntimeError, lambda : blocks.vector_source_f(src_data, False, 3)) if __name__ == '__main__': gr_unittest.run(test_vector_sink_source, "test_vector_sink_source.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_integrate.py0000775000175000017500000000434512207440367023040 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_integrate (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_000_ss(self): src_data = (1, 2, 3, 4, 5, 6) dst_data = (6, 15) src = blocks.vector_source_s(src_data) itg = blocks.integrate_ss(3) dst = blocks.vector_sink_s() self.tb.connect(src, itg, dst) self.tb.run() self.assertEqual(dst_data, dst.data()) def test_001_ii(self): src_data = (1, 2, 3, 4, 5, 6) dst_data = (6, 15) src = blocks.vector_source_i(src_data) itg = blocks.integrate_ii(3) dst = blocks.vector_sink_i() self.tb.connect(src, itg, dst) self.tb.run() self.assertEqual(dst_data, dst.data()) def test_002_ff(self): src_data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] dst_data = [6.0, 15.0] src = blocks.vector_source_f(src_data) itg = blocks.integrate_ff(3) dst = blocks.vector_sink_f() self.tb.connect(src, itg, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(dst_data, dst.data(), 6) def test_003_cc(self): src_data = [1.0+1.0j, 2.0+2.0j, 3.0+3.0j, 4.0+4.0j, 5.0+5.0j, 6.0+6.0j] dst_data = [6.0+6.0j, 15.0+15.0j] src = blocks.vector_source_c(src_data) itg = blocks.integrate_cc(3) dst = blocks.vector_sink_c() self.tb.connect(src, itg, dst) self.tb.run() self.assertComplexTuplesAlmostEqual(dst_data, dst.data(), 6) if __name__ == '__main__': gr_unittest.run(test_integrate, "test_integrate.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_tagged_stream_mux.py0000775000175000017500000001160512237515112024544 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import pmt import numpy def make_len_tags(tupl, key): tags = [] tag = gr.tag_t() tag.key = pmt.string_to_symbol(key) n_read = 0 for element in tupl: tag.offset = n_read n_read += len(element) tag.value = pmt.to_pmt(len(element)) tags.append(tag) return tags def make_len_tag(offset, key, value): tag = gr.tag_t() tag.offset = offset tag.key = pmt.string_to_symbol(key) tag.value = pmt.to_pmt(value) return tag class qa_tagged_stream_mux (gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_1(self): datas = ( 0, 1, 2, 5, 6, 10, 14, 15, 16, 3, 4, 7, 8, 9, 11, 12, 13, 17 ) expected = tuple(range(18)) tagname = "packet_length" len_tags_0 = ( make_len_tag(0, tagname, 3), make_len_tag(3, tagname, 2), make_len_tag(5, tagname, 1), make_len_tag(6, tagname, 3) ) len_tags_1 = ( make_len_tag(0, tagname, 2), make_len_tag(2, tagname, 3), make_len_tag(5, tagname, 3), make_len_tag(8, tagname, 1) ) test_tag_0 = gr.tag_t() test_tag_0.key = pmt.string_to_symbol('spam') test_tag_0.offset = 4 # On the second '1' test_tag_0.value = pmt.to_pmt(42) test_tag_1 = gr.tag_t() test_tag_1.key = pmt.string_to_symbol('eggs') test_tag_1.offset = 3 # On the first '3' of the 2nd stream test_tag_1.value = pmt.to_pmt(23) src0 = blocks.vector_source_b(datas[0:9], False, 1, len_tags_0 + (test_tag_0,)) src1 = blocks.vector_source_b(datas[9:], False, 1, len_tags_1 + (test_tag_1,)) tagged_stream_mux = blocks.tagged_stream_mux(gr.sizeof_char, tagname) snk = blocks.vector_sink_b() self.tb.connect(src0, (tagged_stream_mux, 0)) self.tb.connect(src1, (tagged_stream_mux, 1)) self.tb.connect(tagged_stream_mux, snk) self.tb.run() self.assertEqual(expected, snk.data()) tags = [gr.tag_to_python(x) for x in snk.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) tags_expected = [ (0, 'packet_length', 5), (5, 'packet_length', 5), (6, 'spam', 42), (8, 'eggs', 23), (10, 'packet_length', 4), (14, 'packet_length', 4) ] self.assertEqual(tags, tags_expected) def test_preserve_tag_head_pos(self): """ Test the 'preserve head position' function. This will add a 'special' tag to item 0 on stream 1. It should be on item 0 of the output stream. """ special_tag = gr.tag_t() special_tag.key = pmt.string_to_symbol('spam') special_tag.offset = 0 special_tag.value = pmt.to_pmt('eggs') len_tag_key = "length" packet_len_1 = 5 packet_len_2 = 3 mux = blocks.tagged_stream_mux(gr.sizeof_float, len_tag_key, 1) sink = blocks.vector_sink_f() self.tb.connect( blocks.vector_source_f(range(packet_len_1)), blocks.stream_to_tagged_stream(gr.sizeof_float, 1, packet_len_1, len_tag_key), (mux, 0) ) self.tb.connect( blocks.vector_source_f(range(packet_len_2), False, 1, (special_tag,)), blocks.stream_to_tagged_stream(gr.sizeof_float, 1, packet_len_2, len_tag_key), (mux, 1) ) self.tb.connect(mux, sink) self.tb.run() self.assertEqual(sink.data(), tuple(range(packet_len_1) + range(packet_len_2))) tags = [gr.tag_to_python(x) for x in sink.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) tags_expected = [ (0, 'length', packet_len_1 + packet_len_2), (0, 'spam', 'eggs'), ] self.assertEqual(tags, tags_expected) if __name__ == '__main__': gr_unittest.run(qa_tagged_stream_mux, "qa_tagged_stream_mux.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_keep_m_in_n.py0000775000175000017500000000342512207440367023317 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from gnuradio import gr, gr_unittest, blocks import sys import random class test_keep_m_in_n(gr_unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_001(self): self.maxDiff = None; tb = gr.top_block() src = blocks.vector_source_b( range(0,100) ) # itemsize, M, N, offset km2 = blocks.keep_m_in_n( 1, 1, 2, 0 ); km3 = blocks.keep_m_in_n( 1, 1, 3, 1 ); km7 = blocks.keep_m_in_n( 1, 1, 7, 2 ); snk2 = blocks.vector_sink_b(); snk3 = blocks.vector_sink_b(); snk7 = blocks.vector_sink_b(); tb.connect(src,km2,snk2); tb.connect(src,km3,snk3); tb.connect(src,km7,snk7); tb.run(); self.assertEqual(range(0,100,2), list(snk2.data())); self.assertEqual(range(1,100,3), list(snk3.data())); self.assertEqual(range(2,100,7), list(snk7.data())); if __name__ == '__main__': gr_unittest.run(test_keep_m_in_n, "test_keep_m_in_n.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_boolean_operators.py0000775000175000017500000001621012207440367024565 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_boolean_operators (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def help_ss (self, src_data, exp_data, op): for s in zip (range (len (src_data)), src_data): src = blocks.vector_source_s (s[1]) self.tb.connect (src, (op, s[0])) dst = blocks.vector_sink_s () self.tb.connect (op, dst) self.tb.run () result_data = dst.data () self.assertEqual (exp_data, result_data) def help_bb (self, src_data, exp_data, op): for s in zip (range (len (src_data)), src_data): src = blocks.vector_source_b (s[1]) self.tb.connect (src, (op, s[0])) dst = blocks.vector_sink_b () self.tb.connect (op, dst) self.tb.run () result_data = dst.data () self.assertEqual (exp_data, result_data) def help_ii (self, src_data, exp_data, op): for s in zip (range (len (src_data)), src_data): src = blocks.vector_source_i (s[1]) self.tb.connect (src, (op, s[0])) dst = blocks.vector_sink_i () self.tb.connect (op, dst) self.tb.run () result_data = dst.data () self.assertEqual (exp_data, result_data) def test_xor_ss (self): src1_data = (1, 2, 3, 0x5004, 0x1150) src2_data = (8, 2, 1 , 0x0508, 0x1105) expected_result = (9, 0, 2, 0x550C, 0x0055) op = blocks.xor_ss () self.help_ss ((src1_data, src2_data), expected_result, op) def test_xor_bb (self): src1_data = (1, 2, 3, 4, 0x50) src2_data = (8, 2, 1 , 8, 0x05) expected_result = (9, 0, 2, 0xC, 0x55) op = blocks.xor_bb () self.help_bb ((src1_data, src2_data), expected_result, op) def test_xor_ii (self): src1_data = (1, 2, 3, 0x5000004, 0x11000050) src2_data = (8, 2, 1 , 0x0500008, 0x11000005) expected_result = (9, 0, 2, 0x550000C, 0x00000055) op = blocks.xor_ii () self.help_ii ((src1_data, src2_data), expected_result, op) def test_and_ss (self): src1_data = (1, 2, 3, 0x5004, 0x1150) src2_data = (8, 2, 1 , 0x0508, 0x1105) expected_result = (0, 2, 1, 0x0000, 0x1100) op = blocks.and_ss () self.help_ss ((src1_data, src2_data), expected_result, op) def test_and_bb (self): src1_data = (1, 2, 2, 3, 0x04, 0x50) src2_data = (8, 2, 2, 1, 0x08, 0x05) src3_data = (8, 2, 1, 1, 0x08, 0x05) expected_result = (0, 2, 0, 1, 0x00, 0x00) op = blocks.and_bb () self.help_bb ((src1_data, src2_data, src3_data), expected_result, op) def test_and_ii (self): src1_data = (1, 2, 3, 0x50005004, 0x11001150) src2_data = (8, 2, 1 , 0x05000508, 0x11001105) expected_result = (0, 2, 1, 0x00000000, 0x11001100) op = blocks.and_ii () self.help_ii ((src1_data, src2_data), expected_result, op) def test_and_const_ss (self): src_data = (1, 2, 3, 0x5004, 0x1150) expected_result = (0, 2, 2, 0x5000, 0x1100) src = blocks.vector_source_s(src_data) op = blocks.and_const_ss (0x55AA) dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(dst.data(), expected_result) def test_and_const_bb (self): src_data = (1, 2, 3, 0x50, 0x11) expected_result = (0, 2, 2, 0x00, 0x00) src = blocks.vector_source_b(src_data) op = blocks.and_const_bb (0xAA) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(dst.data(), expected_result) def test_and_const_ii (self): src_data = (1, 2, 3, 0x5004, 0x1150) expected_result = (0, 2, 2, 0x5000, 0x1100) src = blocks.vector_source_i(src_data) op = blocks.and_const_ii (0x55AA) dst = blocks.vector_sink_i() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(dst.data(), expected_result) def test_or_ss (self): src1_data = (1, 2, 3, 0x5004, 0x1150) src2_data = (8, 2, 1 , 0x0508, 0x1105) expected_result = (9, 2, 3, 0x550C, 0x1155) op = blocks.or_ss () self.help_ss ((src1_data, src2_data), expected_result, op) def test_or_bb (self): src1_data = (1, 2, 2, 3, 0x04, 0x50) src2_data = (8, 2, 2, 1 , 0x08, 0x05) src3_data = (8, 2, 1, 1 , 0x08, 0x05) expected_result = (9, 2, 3, 3, 0x0C, 0x55) op = blocks.or_bb () self.help_bb ((src1_data, src2_data, src3_data), expected_result, op) def test_or_ii (self): src1_data = (1, 2, 3, 0x50005004, 0x11001150) src2_data = (8, 2, 1 , 0x05000508, 0x11001105) expected_result = (9, 2, 3, 0x5500550C, 0x11001155) op = blocks.or_ii () self.help_ii ((src1_data, src2_data), expected_result, op) def test_not_ss (self): src1_data = (1, 2, 3, 0x5004, 0x1150) expected_result = (~1, ~2, ~3, ~0x5004, ~0x1150) op = blocks.not_ss () self.help_ss ((((src1_data),)), expected_result, op) def test_not_bb (self): src1_data = (1, 2, 2, 3, 0x04, 0x50) expected_result = (0xFE, 0xFD, 0xFD, 0xFC, 0xFB, 0xAF) op = blocks.not_bb () self.help_bb (((src1_data), ), expected_result, op) def test_not_ii (self): src1_data = (1, 2, 3, 0x50005004, 0x11001150) expected_result = (~1 , ~2, ~3, ~0x50005004, ~0x11001150) op = blocks.not_ii () self.help_ii (((src1_data),), expected_result, op) if __name__ == '__main__': gr_unittest.run(test_boolean_operators, "test_boolean_operators.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_file_metadata.py0000664000175000017500000001520112207440367023623 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os, math from gnuradio import gr, gr_unittest, blocks import pmt import parse_file_metadata def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: amp*math.cos(2.*math.pi*freq*x) + \ 1j*amp*math.sin(2.*math.pi*freq*x), t) return y class test_file_metadata(gr_unittest.TestCase): def setUp(self): os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): N = 1000 outfile = "test_out.dat" detached = False samp_rate = 200000 key = pmt.intern("samp_rate") val = pmt.from_double(samp_rate) extras = pmt.make_dict() extras = pmt.dict_add(extras, key, val) extras_str = pmt.serialize_str(extras) data = sig_source_c(samp_rate, 1000, 1, N) src = blocks.vector_source_c(data) fsnk = blocks.file_meta_sink(gr.sizeof_gr_complex, outfile, samp_rate, 1, blocks.GR_FILE_FLOAT, True, 1000000, extras_str, detached) fsnk.set_unbuffered(True) self.tb.connect(src, fsnk) self.tb.run() fsnk.close() handle = open(outfile, "rb") header_str = handle.read(parse_file_metadata.HEADER_LENGTH) if(len(header_str) == 0): self.assertFalse() try: header = pmt.deserialize_str(header_str) except RuntimeError: self.assertFalse() info = parse_file_metadata.parse_header(header, False) extra_str = handle.read(info["extra_len"]) self.assertEqual(len(extra_str) > 0, True) handle.close() try: extra = pmt.deserialize_str(extra_str) except RuntimeError: self.assertFalse() extra_info = parse_file_metadata.parse_extra_dict(extra, info, False) self.assertEqual(info['rx_rate'], samp_rate) self.assertEqual(pmt.to_double(extra_info['samp_rate']), samp_rate) # Test file metadata source src.rewind() fsrc = blocks.file_meta_source(outfile, False) vsnk = blocks.vector_sink_c() tsnk = blocks.tag_debug(gr.sizeof_gr_complex, "QA") ssnk = blocks.vector_sink_c() self.tb.disconnect(src, fsnk) self.tb.connect(fsrc, vsnk) self.tb.connect(fsrc, tsnk) self.tb.connect(src, ssnk) self.tb.run() # Test to make sure tags with 'samp_rate' and 'rx_rate' keys # were generated and received correctly. tags = tsnk.current_tags() for t in tags: if(pmt.eq(t.key, pmt.intern("samp_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) elif(pmt.eq(t.key, pmt.intern("rx_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) # Test that the data portion was extracted and received correctly. self.assertComplexTuplesAlmostEqual(vsnk.data(), ssnk.data(), 5) os.remove(outfile) def test_002(self): N = 1000 outfile = "test_out.dat" outfile_hdr = "test_out.dat.hdr" detached = True samp_rate = 200000 key = pmt.intern("samp_rate") val = pmt.from_double(samp_rate) extras = pmt.make_dict() extras = pmt.dict_add(extras, key, val) extras_str = pmt.serialize_str(extras) data = sig_source_c(samp_rate, 1000, 1, N) src = blocks.vector_source_c(data) fsnk = blocks.file_meta_sink(gr.sizeof_gr_complex, outfile, samp_rate, 1, blocks.GR_FILE_FLOAT, True, 1000000, extras_str, detached) fsnk.set_unbuffered(True) self.tb.connect(src, fsnk) self.tb.run() fsnk.close() # Open detached header for reading handle = open(outfile_hdr, "rb") header_str = handle.read(parse_file_metadata.HEADER_LENGTH) if(len(header_str) == 0): self.assertFalse() try: header = pmt.deserialize_str(header_str) except RuntimeError: self.assertFalse() info = parse_file_metadata.parse_header(header, False) extra_str = handle.read(info["extra_len"]) self.assertEqual(len(extra_str) > 0, True) handle.close() try: extra = pmt.deserialize_str(extra_str) except RuntimeError: self.assertFalse() extra_info = parse_file_metadata.parse_extra_dict(extra, info, False) self.assertEqual(info['rx_rate'], samp_rate) self.assertEqual(pmt.to_double(extra_info['samp_rate']), samp_rate) # Test file metadata source src.rewind() fsrc = blocks.file_meta_source(outfile, False, detached, outfile_hdr) vsnk = blocks.vector_sink_c() tsnk = blocks.tag_debug(gr.sizeof_gr_complex, "QA") ssnk = blocks.vector_sink_c() self.tb.disconnect(src, fsnk) self.tb.connect(fsrc, vsnk) self.tb.connect(fsrc, tsnk) self.tb.connect(src, ssnk) self.tb.run() # Test to make sure tags with 'samp_rate' and 'rx_rate' keys # were generated and received correctly. tags = tsnk.current_tags() for t in tags: if(pmt.eq(t.key, pmt.intern("samp_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) elif(pmt.eq(t.key, pmt.intern("rx_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) # Test that the data portion was extracted and received correctly. self.assertComplexTuplesAlmostEqual(vsnk.data(), ssnk.data(), 5) os.remove(outfile) os.remove(outfile_hdr) if __name__ == '__main__': gr_unittest.run(test_file_metadata, "test_file_metadata.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_conjugate.py0000664000175000017500000000317412207440367023031 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_conjugate (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_000 (self): src_data = (-2-2j, -1-1j, -2+2j, -1+1j, 2-2j, 1-1j, 2+2j, 1+1j, 0+0j) exp_data = (-2+2j, -1+1j, -2-2j, -1-1j, 2+2j, 1+1j, 2-2j, 1-1j, 0-0j) src = blocks.vector_source_c(src_data) op = blocks.conjugate_cc () dst = blocks.vector_sink_c () self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data () self.assertEqual (exp_data, result_data) if __name__ == '__main__': gr_unittest.run(test_conjugate, "test_conjugate.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_threshold.py0000664000175000017500000000300112207440367023033 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_threshold(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_01(self): tb = self.tb data = [0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2] expected_result = (0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1) src = blocks.vector_source_f(data, False) op = blocks.threshold_ff(1, 1) dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_threshold, "test_threshold.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_delay.py0000775000175000017500000000367612207440367022162 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_delay(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): delta_t = 0 tb = self.tb src_data = [float(x) for x in range(0, 100)] expected_result = tuple(delta_t*[0.0] + src_data) src = blocks.vector_source_f(src_data) op = blocks.delay(gr.sizeof_float, delta_t) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) def test_010(self): delta_t = 10 tb = self.tb src_data = [float(x) for x in range(0, 100)] expected_result = tuple(delta_t*[0.0] + src_data) src = blocks.vector_source_f(src_data) op = blocks.delay(gr.sizeof_float, delta_t) dst = blocks.vector_sink_f() tb.connect(src, op, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_delay, "test_delay.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_cpp_py_binding_set.py0000775000175000017500000001076612207440367024721 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # # This program tests mixed python and c++ GRCP sets in a single app # import Ice import sys, time, random, numpy from gnuradio import gr, gr_unittest, blocks from gnuradio.ctrlport import GNURadio from gnuradio import ctrlport import os class inc_class: def __init__(self,val): self.val = val; def _get(self): #print "returning get (val = %s)"%(str(self.val)); return self.val; def _set(self,val): #print "updating val to %s"%(str(val)); self.val = val; return; getset1 = inc_class(10); getset2 = inc_class(100.0); getset3 = inc_class("test"); class test_cpp_py_binding_set(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() os.environ['GR_CONF_CONTROLPORT_ON'] = 'True' def tearDown(self): self.tb = None def test_001(self): g1 = gr.RPC_get_int("pyland", "v1", "unit_1_int", "Python Exported Int", 0, 100, 10, gr.DISPNULL) g1.activate(getset1._get) s1 = gr.RPC_get_int("pyland", "v1", "unit_1_int", "Python Exported Int", 0, 100, 10, gr.DISPNULL) s1.activate(getset1._set) time.sleep(0.01) # test int variables getset1._set(21) val = getset1._get() rval = g1.get() self.assertEqual(val, rval) g2 = gr.RPC_get_float("pyland", "v2", "unit_2_float", "Python Exported Float", -100, 1000.0, 100.0, gr.DISPNULL) g2.activate(getset2._get) s2 = gr.RPC_get_float("pyland", "v2", "unit_2_float", "Python Exported Float", -100, 1000.0, 100.0, gr.DISPNULL) s2.activate(getset2._set) time.sleep(0.01) # test float variables getset2._set(123.456) val = getset2._get() rval = g2.get() self.assertAlmostEqual(val, rval, 4) g3 = gr.RPC_get_string("pyland", "v3", "unit_3_string", "Python Exported String", "", "", "", gr.DISPNULL) g3.activate(getset3._get) s3 = gr.RPC_get_string("pyland", "v3", "unit_3_string", "Python Exported String", "", "", "", gr.DISPNULL) s3.activate(getset3._set) time.sleep(0.01) # test string variables getset3._set("third test") val = getset3._get() rval = g3.get() self.assertEqual(val, rval) def test_002(self): data = range(1, 10) self.src = blocks.vector_source_c(data, True) self.p = blocks.nop(gr.sizeof_gr_complex) self.p.set_ctrlport_test(0); probe_info = self.p.alias() self.tb.connect(self.src, self.p) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) self.tb.start() # Make sure we have time for flowgraph to run time.sleep(0.1) # Get all exported knobs key_name_test = probe_info+"::test" ret = radio.get([key_name_test,]) ret[key_name_test].value = 10 radio.set({key_name_test: ret[key_name_test]}) ret = radio.get([]) result_test = ret[key_name_test].value self.assertEqual(result_test, 10) self.tb.stop() self.tb.wait() if __name__ == '__main__': gr_unittest.run(test_cpp_py_binding_set, "test_cpp_py_binding_set.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_udp_source_sink.py0000664000175000017500000000712312241760655024247 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import os from threading import Timer class test_udp_sink_source(gr_unittest.TestCase): def setUp(self): os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' self.tb_snd = gr.top_block() self.tb_rcv = gr.top_block() def tearDown(self): self.tb_rcv = None self.tb_snd = None def test_001(self): # Tests calling disconnect/reconnect. port = 65510 n_data = 16 src_data = [x for x in range(n_data)] expected_result = tuple(src_data) src = blocks.vector_source_s(src_data, False) udp_snd = blocks.udp_sink(gr.sizeof_short, 'localhost', port) self.tb_snd.connect(src, udp_snd) self.tb_snd.run() udp_snd.disconnect() udp_snd.connect('localhost', port+1) src.rewind() self.tb_snd.run() def test_002(self): port = 65520 n_data = 100 src_data = [float(x) for x in range(n_data)] expected_result = tuple(src_data) src = blocks.vector_source_f(src_data, False) udp_snd = blocks.udp_sink(gr.sizeof_float, 'localhost', port) self.tb_snd.connect(src, udp_snd) udp_rcv = blocks.udp_source(gr.sizeof_float, 'localhost', port) dst = blocks.vector_sink_f() self.tb_rcv.connect(udp_rcv, dst) self.tb_rcv.start() self.tb_snd.run() udp_snd.disconnect() self.timeout = False q = Timer(2.0,self.stop_rcv) q.start() self.tb_rcv.wait() q.cancel() result_data = dst.data() self.assertEqual(expected_result, result_data) self.assert_(not self.timeout) def test_003(self): port = 65530 udp_rcv = blocks.udp_source(gr.sizeof_float, '0.0.0.0', 0, eof=False) rcv_port = udp_rcv.get_port() udp_snd = blocks.udp_sink(gr.sizeof_float, '127.0.0.1', port) udp_snd.connect('localhost', rcv_port) n_data = 16 src_data = [float(x) for x in range(n_data)] expected_result = tuple(src_data) src = blocks.vector_source_f(src_data) dst = blocks.vector_sink_f() self.tb_snd.connect(src, udp_snd) self.tb_rcv.connect(udp_rcv, dst) self.tb_rcv.start() self.tb_snd.run() udp_snd.disconnect() self.timeout = False q = Timer(2.0,self.stop_rcv) q.start() self.tb_rcv.wait() q.cancel() result_data = dst.data() self.assertEqual(expected_result, result_data) self.assert_(self.timeout) # source ignores EOF? def stop_rcv(self): self.timeout = True self.tb_rcv.stop() #print "tb_rcv stopped by Timer" if __name__ == '__main__': gr_unittest.run(test_udp_sink_source, "test_udp_sink_source.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_repeat.py0000775000175000017500000000266512207440367022341 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_repeat (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_float(self): src_data = [n*1.0 for n in range(100)]; dst_data = [] for n in range(100): dst_data += [1.0*n, 1.0*n, 1.0*n] src = blocks.vector_source_f(src_data) rpt = blocks.repeat(gr.sizeof_float, 3) dst = blocks.vector_sink_f() self.tb.connect(src, rpt, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(dst_data, dst.data(), 6) if __name__ == '__main__': gr_unittest.run(test_repeat, "test_repeat.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_multiply_conjugate.py0000664000175000017500000000357112207440367024771 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_multiply_conjugate (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_000 (self): src_data0 = (-2-2j, -1-1j, -2+2j, -1+1j, 2-2j, 1-1j, 2+2j, 1+1j, 0+0j) src_data1 = (-3-3j, -4-4j, -3+3j, -4+4j, 3-3j, 4-4j, 3+3j, 4+4j, 0+0j) exp_data = (12+0j, 8+0j, 12+0j, 8+0j, 12+0j, 8+0j, 12+0j, 8+0j, 0+0j) src0 = blocks.vector_source_c(src_data0) src1 = blocks.vector_source_c(src_data1) op = blocks.multiply_conjugate_cc () dst = blocks.vector_sink_c () self.tb.connect(src0, (op,0)) self.tb.connect(src1, (op,1)) self.tb.connect(op, dst) self.tb.run() result_data = dst.data () self.assertEqual (exp_data, result_data) if __name__ == '__main__': gr_unittest.run(test_multiply_conjugate, "test_multiply_conjugate.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_vector_map.py0000664000175000017500000000751012207440367023207 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_vector_map(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_reversing(self): # Chunk data in blocks of N and reverse the block contents. N = 5 src_data = range(0, 20) expected_result = [] for i in range(N-1, len(src_data), N): for j in range(0, N): expected_result.append(1.0*(i-j)) mapping = [list(reversed([(0, i) for i in range(0, N)]))] src = blocks.vector_source_f(src_data, False, N) vmap = blocks.vector_map(gr.sizeof_float, (N, ), mapping) dst = blocks.vector_sink_f(N) self.tb.connect(src, vmap, dst) self.tb.run() result_data = list(dst.data()) self.assertEqual(expected_result, result_data) def test_vector_to_streams(self): # Split an input vector into N streams. N = 5 M = 20 src_data = range(0, M) expected_results = [] for n in range(0, N): expected_results.append(range(n, M, N)) mapping = [[(0, n)] for n in range(0, N)] src = blocks.vector_source_f(src_data, False, N) vmap = blocks.vector_map(gr.sizeof_float, (N, ), mapping) dsts = [blocks.vector_sink_f(1) for n in range(0, N)] self.tb.connect(src, vmap) for n in range(0, N): self.tb.connect((vmap, n), dsts[n]) self.tb.run() for n in range(0, N): result_data = list(dsts[n].data()) self.assertEqual(expected_results[n], result_data) def test_interleaving(self): # Takes 3 streams (a, b and c) # Outputs 2 streams. # First (d) is interleaving of a and b. # Second (e) is interleaving of a and b and c. c is taken in # chunks of 2 which are reversed. A = (1, 2, 3, 4, 5) B = (11, 12, 13, 14, 15) C = (99, 98, 97, 96, 95, 94, 93, 92, 91, 90) expected_D = (1, 11, 2, 12, 3, 13, 4, 14, 5, 15) expected_E = (1, 11, 98, 99, 2, 12, 96, 97, 3, 13, 94, 95, 4, 14, 92, 93, 5, 15, 90, 91) mapping = [[(0, 0), (1, 0)], # mapping to produce D [(0, 0), (1, 0), (2, 1), (2, 0)], # mapping to produce E ] srcA = blocks.vector_source_f(A, False, 1) srcB = blocks.vector_source_f(B, False, 1) srcC = blocks.vector_source_f(C, False, 2) vmap = blocks.vector_map(gr.sizeof_int, (1, 1, 2), mapping) dstD = blocks.vector_sink_f(2) dstE = blocks.vector_sink_f(4) self.tb.connect(srcA, (vmap, 0)) self.tb.connect(srcB, (vmap, 1)) self.tb.connect(srcC, (vmap, 2)) self.tb.connect((vmap, 0), dstD) self.tb.connect((vmap, 1), dstE) self.tb.run() self.assertEqual(expected_D, dstD.data()) self.assertEqual(expected_E, dstE.data()) if __name__ == '__main__': gr_unittest.run(test_vector_map, "test_vector_map.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_file_source_sink.py0000664000175000017500000000523012207440367024370 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import os class test_file_source_sink(gr_unittest.TestCase): def setUp (self): os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): src_data = range(1000) expected_result = range(1000) filename = "tmp.32f" src = blocks.vector_source_f(src_data) snk = blocks.file_sink(gr.sizeof_float, filename) snk.set_unbuffered(True) src2 = blocks.file_source(gr.sizeof_float, filename) snk2 = blocks.vector_sink_f() self.tb.connect(src, snk) self.tb.run() self.tb.disconnect(src, snk) self.tb.connect(src2, snk2) self.tb.run() os.remove(filename) result_data = snk2.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) def test_descriptor_001(self): src_data = range(1000) expected_result = range(1000) filename = "tmp.32f" fhandle0 = open(filename, "wb") fd0 = fhandle0.fileno() src = blocks.vector_source_f(src_data) snk = blocks.file_descriptor_sink(gr.sizeof_float, fd0) self.tb.connect(src, snk) self.tb.run() os.fsync(fd0) fhandle0.close() fhandle1 = open(filename, "rb") fd1 = fhandle1.fileno() src2 = blocks.file_descriptor_source(gr.sizeof_float, fd1, False) snk2 = blocks.vector_sink_f() self.tb.disconnect(src, snk) self.tb.connect(src2, snk2) self.tb.run() os.fsync(fd1) fhandle1.close() os.remove(filename) result_data = snk2.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_file_source_sink, "test_file_source_sink.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_max.py0000775000175000017500000000364212207440367021642 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_max(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = (0,0.2,-0.3,0,12,0) expected_result = (float(max(src_data)),) src = blocks.vector_source_f(src_data) s2v = blocks.stream_to_vector(gr.sizeof_float, len(src_data)) op = blocks.max_ff(len(src_data)) dst = blocks.vector_sink_f() self.tb.connect(src, s2v, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) def test_002(self): src_data=(-100,-99,-98,-97,-96,-1) expected_result = (float(max(src_data)),) src = blocks.vector_source_f(src_data) s2v = blocks.stream_to_vector(gr.sizeof_float, len(src_data)) op = blocks.max_ff(len(src_data)) dst = blocks.vector_sink_f() self.tb.connect(src, s2v, op, dst) self.tb.run() result_data = dst.data() self.assertEqual(expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_max, "test_max.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_stream_mux.py0000775000175000017500000001414112207440367023235 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2005,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import os class test_stream_mux (gr_unittest.TestCase): def setUp (self): os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' self.tb = gr.top_block () def tearDown (self): self.tb = None def help_stream_2ff(self, N, stream_sizes): v0 = blocks.vector_source_f(N*[1,], False) v1 = blocks.vector_source_f(N*[2,], False) mux = blocks.stream_mux(gr.sizeof_float, stream_sizes) dst = blocks.vector_sink_f () self.tb.connect (v0, (mux,0)) self.tb.connect (v1, (mux,1)) self.tb.connect (mux, dst) self.tb.run () return dst.data () def help_stream_ramp_2ff(self, N, stream_sizes): r1 = range(N) r2 = range(N) r2.reverse() v0 = blocks.vector_source_f(r1, False) v1 = blocks.vector_source_f(r2, False) mux = blocks.stream_mux(gr.sizeof_float, stream_sizes) dst = blocks.vector_sink_f () self.tb.connect (v0, (mux,0)) self.tb.connect (v1, (mux,1)) self.tb.connect (mux, dst) self.tb.run () return dst.data () def test_stream_2NN_ff(self): N = 40 stream_sizes = [10, 10] result_data = self.help_stream_2ff(N, stream_sizes) exp_data = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0) self.assertEqual (exp_data, result_data) def test_stream_ramp_2NN_ff(self): N = 40 stream_sizes = [10, 10] result_data = self.help_stream_ramp_2ff(N, stream_sizes) exp_data = ( 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 39.0, 38.0, 37.0, 36.0, 35.0, 34.0, 33.0, 32.0, 31.0, 30.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 29.0, 28.0, 27.0, 26.0, 25.0, 24.0, 23.0, 22.0, 21.0, 20.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 19.0, 18.0, 17.0, 16.0, 15.0, 14.0, 13.0, 12.0, 11.0, 10.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0) self.assertEqual (exp_data, result_data) def test_stream_2NM_ff(self): N = 40 stream_sizes = [7, 9] self.help_stream_2ff(N, stream_sizes) result_data = self.help_stream_2ff(N, stream_sizes) exp_data = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0) self.assertEqual (exp_data, result_data) def test_stream_2MN_ff(self): N = 37 stream_sizes = [7, 9] self.help_stream_2ff(N, stream_sizes) result_data = self.help_stream_2ff(N, stream_sizes) exp_data = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0) self.assertEqual (exp_data, result_data) def test_stream_2N0_ff(self): N = 30 stream_sizes = [7, 0] self.help_stream_2ff(N, stream_sizes) result_data = self.help_stream_2ff(N, stream_sizes) exp_data = (1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) self.assertEqual (exp_data, result_data) def test_stream_20N_ff(self): N = 30 stream_sizes = [0, 9] self.help_stream_2ff(N, stream_sizes) result_data = self.help_stream_2ff(N, stream_sizes) exp_data = (2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0) self.assertEqual (exp_data, result_data) if __name__ == '__main__': gr_unittest.run(test_stream_mux, "test_stream_mux.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_probe_signal.py0000664000175000017500000000366412207440367023522 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_probe_signal(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): value = 12.3 repeats = 100 src_data = [value] * repeats src = blocks.vector_source_f(src_data) dst = blocks.probe_signal_f() self.tb.connect(src, dst) self.tb.run() output = dst.level() self.assertAlmostEqual(value, output, places=6) def test_002(self): vector_length = 10 repeats = 10 value = [0.5+i for i in range(0, vector_length)] src_data = value * repeats src = blocks.vector_source_f(src_data) s2v = blocks.stream_to_vector(gr.sizeof_float, vector_length) dst = blocks.probe_signal_vf(vector_length) self.tb.connect(src, s2v, dst) self.tb.run() output = dst.level() self.assertEqual(len(output), vector_length) self.assertAlmostEqual(value[3], output[3], places=6) if __name__ == '__main__': gr_unittest.run(test_probe_signal, "test_probe_signal.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_add_mult_v.py0000775000175000017500000003023712207440367023173 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_add_mult_v(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def help_ss(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = blocks.vector_source_s(s[1]) srcv = blocks.stream_to_vector(gr.sizeof_short, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = blocks.vector_to_stream(gr.sizeof_short, size) dst = blocks.vector_sink_s() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ii(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = blocks.vector_source_i(s[1]) srcv = blocks.stream_to_vector(gr.sizeof_int, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = blocks.vector_to_stream(gr.sizeof_int, size) dst = blocks.vector_sink_i() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ff(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = blocks.vector_source_f(s[1]) srcv = blocks.stream_to_vector(gr.sizeof_float, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = blocks.vector_to_stream(gr.sizeof_float, size) dst = blocks.vector_sink_f() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_cc(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = blocks.vector_source_c(s[1]) srcv = blocks.stream_to_vector(gr.sizeof_gr_complex, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = blocks.vector_to_stream(gr.sizeof_gr_complex, size) dst = blocks.vector_sink_c() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_ss(self, src_data, exp_data, op): src = blocks.vector_source_s(src_data) srcv = blocks.stream_to_vector(gr.sizeof_short, len(src_data)) rhs = blocks.vector_to_stream(gr.sizeof_short, len(src_data)) dst = blocks.vector_sink_s() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_ii(self, src_data, exp_data, op): src = blocks.vector_source_i(src_data) srcv = blocks.stream_to_vector(gr.sizeof_int, len(src_data)) rhs = blocks.vector_to_stream(gr.sizeof_int, len(src_data)) dst = blocks.vector_sink_i() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_ff(self, src_data, exp_data, op): src = blocks.vector_source_f(src_data) srcv = blocks.stream_to_vector(gr.sizeof_float, len(src_data)) rhs = blocks.vector_to_stream(gr.sizeof_float, len(src_data)) dst = blocks.vector_sink_f() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_cc(self, src_data, exp_data, op): src = blocks.vector_source_c(src_data) srcv = blocks.stream_to_vector(gr.sizeof_gr_complex, len(src_data)) rhs = blocks.vector_to_stream(gr.sizeof_gr_complex, len(src_data)) dst = blocks.vector_sink_c() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) # add_vXX def test_add_vss_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = blocks.add_ss(1) self.help_ss(1, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vss_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (18, 21, 24, 27, 30) op = blocks.add_ss(5) self.help_ss(5, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vii_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = blocks.add_ii(1) self.help_ii(1, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vii_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (18, 21, 24, 27, 30) op = blocks.add_ii(5) self.help_ii(5, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vff_one(self): src1_data = (1.0,) src2_data = (2.0,) src3_data = (3.0,) expected_result = (6.0,) op = blocks.add_ff(1) self.help_ff(1, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vff_five(self): src1_data = (1.0, 2.0, 3.0, 4.0, 5.0) src2_data = (6.0, 7.0, 8.0, 9.0, 10.0) src3_data = (11.0, 12.0, 13.0, 14.0, 15.0) expected_result = (18.0, 21.0, 24.0, 27.0, 30.0) op = blocks.add_ff(5) self.help_ff(5, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vcc_one(self): src1_data = (1.0+2.0j,) src2_data = (3.0+4.0j,) src3_data = (5.0+6.0j,) expected_result = (9.0+12j,) op = blocks.add_cc(1) self.help_cc(1, (src1_data, src2_data, src3_data), expected_result, op) def test_add_vcc_five(self): src1_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) src2_data = (11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j) src3_data = (21.0+22.0j, 23.0+24.0j, 25.0+26.0j, 27.0+28.0j, 29.0+30.0j) expected_result = (33.0+36.0j, 39.0+42.0j, 45.0+48.0j, 51.0+54.0j, 57.0+60.0j) op = blocks.add_cc(5) self.help_cc(5, (src1_data, src2_data, src3_data), expected_result, op) # add_const_vXX def test_add_const_vss_one(self): src_data = (1,) op = blocks.add_const_vss((2,)) exp_data = (3,) self.help_const_ss(src_data, exp_data, op) def test_add_const_vss_five(self): src_data = (1, 2, 3, 4, 5) op = blocks.add_const_vss((6, 7, 8, 9, 10)) exp_data = (7, 9, 11, 13, 15) self.help_const_ss(src_data, exp_data, op) def test_add_const_vii_one(self): src_data = (1,) op = blocks.add_const_vii((2,)) exp_data = (3,) self.help_const_ii(src_data, exp_data, op) def test_add_const_vii_five(self): src_data = (1, 2, 3, 4, 5) op = blocks.add_const_vii((6, 7, 8, 9, 10)) exp_data = (7, 9, 11, 13, 15) self.help_const_ii(src_data, exp_data, op) def test_add_const_vff_one(self): src_data = (1.0,) op = blocks.add_const_vff((2.0,)) exp_data = (3.0,) self.help_const_ff(src_data, exp_data, op) def test_add_const_vff_five(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) op = blocks.add_const_vff((6.0, 7.0, 8.0, 9.0, 10.0)) exp_data = (7.0, 9.0, 11.0, 13.0, 15.0) self.help_const_ff(src_data, exp_data, op) def test_add_const_vcc_one(self): src_data = (1.0+2.0j,) op = blocks.add_const_vcc((2.0+3.0j,)) exp_data = (3.0+5.0j,) self.help_const_cc(src_data, exp_data, op) def test_add_const_vcc_five(self): src_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) op = blocks.add_const_vcc((11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j)) exp_data = (12.0+14.0j, 16.0+18.0j, 20.0+22.0j, 24.0+26.0j, 28.0+30.0j) self.help_const_cc(src_data, exp_data, op) # multiply_vXX def test_multiply_vss_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = blocks.multiply_ss(1) self.help_ss(1, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vss_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (66, 168, 312, 504, 750) op = blocks.multiply_ss(5) self.help_ss(5, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vii_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = blocks.multiply_ii(1) self.help_ii(1, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vii_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (66, 168, 312, 504, 750) op = blocks.multiply_ii(5) self.help_ii(5, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vff_one(self): src1_data = (1.0,) src2_data = (2.0,) src3_data = (3.0,) expected_result = (6.0,) op = blocks.multiply_ff(1) self.help_ff(1, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vff_five(self): src1_data = (1.0, 2.0, 3.0, 4.0, 5.0) src2_data = (6.0, 7.0, 8.0, 9.0, 10.0) src3_data = (11.0, 12.0, 13.0, 14.0, 15.0) expected_result = (66.0, 168.0, 312.0, 504.0, 750.0) op = blocks.multiply_ff(5) self.help_ff(5, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vcc_one(self): src1_data = (1.0+2.0j,) src2_data = (3.0+4.0j,) src3_data = (5.0+6.0j,) expected_result = (-85+20j,) op = blocks.multiply_cc(1) self.help_cc(1, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_vcc_five(self): src1_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) src2_data = (11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j) src3_data = (21.0+22.0j, 23.0+24.0j, 25.0+26.0j, 27.0+28.0j, 29.0+30.0j) expected_result = (-1021.0+428.0j, -2647.0+1754.0j, -4945.0+3704.0j, -8011.0+6374.0j, -11941.0+9860.0j) op = blocks.multiply_cc(5) self.help_cc(5, (src1_data, src2_data, src3_data), expected_result, op) # multiply_const_vXX def test_multiply_const_vss_one(self): src_data = (2,) op = blocks.multiply_const_vss((3,)) exp_data = (6,) self.help_const_ss(src_data, exp_data, op) def test_multiply_const_vss_five(self): src_data = (1, 2, 3, 4, 5) op = blocks.multiply_const_vss((6, 7, 8, 9, 10)) exp_data = (6, 14, 24, 36, 50) self.help_const_ss(src_data, exp_data, op) def test_multiply_const_vii_one(self): src_data = (2,) op = blocks.multiply_const_vii((3,)) exp_data = (6,) self.help_const_ii(src_data, exp_data, op) def test_multiply_const_vii_five(self): src_data = (1, 2, 3, 4, 5) op = blocks.multiply_const_vii((6, 7, 8, 9, 10)) exp_data = (6, 14, 24, 36, 50) self.help_const_ii(src_data, exp_data, op) def test_multiply_const_vff_one(self): src_data = (2.0,) op = blocks.multiply_const_vff((3.0,)) exp_data = (6.0,) self.help_const_ff(src_data, exp_data, op) def test_multiply_const_vff_five(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) op = blocks.multiply_const_vff((6.0, 7.0, 8.0, 9.0, 10.0)) exp_data = (6.0, 14.0, 24.0, 36.0, 50.0) self.help_const_ff(src_data, exp_data, op) def test_multiply_const_vcc_one(self): src_data = (1.0+2.0j,) op = blocks.multiply_const_vcc((2.0+3.0j,)) exp_data = (-4.0+7.0j,) self.help_const_cc(src_data, exp_data, op) def test_multiply_const_vcc_five(self): src_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) op = blocks.multiply_const_vcc((11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j)) exp_data = (-13.0+34.0j, -17.0+94.0j, -21.0+170.0j, -25.0+262.0j, -29.0+370.0j) self.help_const_cc(src_data, exp_data, op) if __name__ == '__main__': gr_unittest.run(test_add_mult_v, "test_add_mult_v.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_transcendental.py0000664000175000017500000000454412207440367024061 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math class test_transcendental(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_01(self): tb = self.tb data = 100*[0,] expected_result = 100*[1,] src = blocks.vector_source_f(data, False) op = blocks.transcendental("cos", "float") dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() dst_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) def test_02(self): tb = self.tb data = 100*[3,] expected_result = 100*[math.log10(3),] src = blocks.vector_source_f(data, False) op = blocks.transcendental("log10", "float") dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() dst_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) def test_03(self): tb = self.tb data = 100*[3,] expected_result = 100*[math.tanh(3),] src = blocks.vector_source_f(data, False) op = blocks.transcendental("tanh", "float") dst = blocks.vector_sink_f() tb.connect(src, op) tb.connect(op, dst) tb.run() dst_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, dst_data, 5) if __name__ == '__main__': gr_unittest.run(test_transcendental, "test_transcendental.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_add_mult_div_sub.py0000775000175000017500000001626112207440367024362 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_add_mult_div_sub(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def help_ii(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_i(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_i() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ss(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_s(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_s() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ff(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_f(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_f() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_cc(self, src_data, exp_data, op): for s in zip(range(len(src_data)), src_data): src = blocks.vector_source_c(s[1]) self.tb.connect(src, (op, s[0])) dst = blocks.vector_sink_c() self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) # add_XX def test_add_ss(self): src1_data = (1, 2, 3, 4, 5) src2_data = (8, -3, 4, 8, 2) expected_result = (9, -1, 7, 12, 7) op = blocks.add_ss() self.help_ss((src1_data, src2_data), expected_result, op) def test_add_ii(self): src1_data = (1, 2, 3, 4, 5) src2_data = (8, -3, 4, 8, 2) expected_result = (9, -1, 7, 12, 7) op = blocks.add_ii() self.help_ii((src1_data, src2_data), expected_result, op) def test_add_ff(self): src1_data = (1.0, 2.0, 3.0, 4.0, 5.0) src2_data = (8.0, -3.0, 4.0, 8.0, 2.0) expected_result = (9.0, -1.0, 7.0, 12.0, 7.0) op = blocks.add_ff() self.help_ff((src1_data, src2_data), expected_result, op) def test_add_cc(self): src1_data = (1+1j, 2+2j, 3+3j, 4+4j, 5+5j) src2_data = (8+8j, -3-3j, 4+4j, 8+8j, 2+2j) expected_result = (9+9j, -1-1j, 7+7j, 12+12j, 7+7j) op = blocks.add_cc() self.help_cc((src1_data, src2_data), expected_result, op) # add_const_XX def test_add_const_ss(self): src_data = (1, 2, 3, 4, 5) expected_result = (6, 7, 8, 9, 10) op = blocks.add_const_ss(5) self.help_ss((src_data,), expected_result, op) def test_add_const_ii(self): src_data = (1, 2, 3, 4, 5) expected_result = (6, 7, 8, 9, 10) op = blocks.add_const_ii(5) self.help_ii((src_data,), expected_result, op) def test_add_const_ff(self): src_data = (1, 2, 3, 4, 5) expected_result = (6, 7, 8, 9, 10) op = blocks.add_const_ff(5) self.help_ff((src_data,), expected_result, op) def test_add_const_cc(self): src_data = (1, 2, 3, 4, 5) expected_result = (1+5j, 2+5j, 3+5j, 4+5j, 5+5j) op = blocks.add_const_cc(5j) self.help_cc((src_data,), expected_result, op) # multiply_XX def test_multiply_ss(self): src1_data = (1, 2, 3, 4, 5) src2_data = (8, -3, 4, 8, 2) expected_result = (8, -6, 12, 32, 10) op = blocks.multiply_ss() self.help_ss((src1_data, src2_data), expected_result, op) def test_multiply_ii(self): src1_data = (1, 2, 3, 4, 5) src2_data = (8, -3, 4, 8, 2) expected_result = (8, -6, 12, 32, 10) op = blocks.multiply_ii() self.help_ii((src1_data, src2_data), expected_result, op) def test_multiply_ff(self): src1_data = (1, 2, 3, 4, 5) src2_data = (8, -3, 4, 8, 2) expected_result = (8, -6, 12, 32, 10) op = blocks.multiply_ff() self.help_ff((src1_data, src2_data), expected_result, op) def test_multiply_cc(self): src1_data = (1+1j, 2+2j, 3+3j, 4+4j, 5+5j) src2_data = (8, -3, 4, 8, 2) expected_result = (8+8j, -6-6j, 12+12j, 32+32j, 10+10j) op = blocks.multiply_cc() self.help_cc((src1_data, src2_data), expected_result, op) # multiply_const_XX def test_multiply_const_ss(self): src_data = (-1, 0, 1, 2, 3) expected_result = (-5, 0, 5, 10, 15) op = blocks.multiply_const_ss(5) self.help_ss((src_data,), expected_result, op) def test_multiply_const_ii(self): src_data = (-1, 0, 1, 2, 3) expected_result = (-5, 0, 5, 10, 15) op = blocks.multiply_const_ii(5) self.help_ii((src_data,), expected_result, op) def test_multiply_const_ff(self): src_data = (-1, 0, 1, 2, 3) expected_result = (-5, 0, 5, 10, 15) op = blocks.multiply_const_ff(5) self.help_ff((src_data,), expected_result, op) def test_multiply_const_cc(self): src_data = (-1-1j, 0+0j, 1+1j, 2+2j, 3+3j) expected_result = (-5-5j, 0+0j, 5+5j, 10+10j, 15+15j) op = blocks.multiply_const_cc(5) self.help_cc((src_data,), expected_result, op) def test_multiply_const_cc2(self): src_data = (-1-1j, 0+0j, 1+1j, 2+2j, 3+3j) expected_result = (-3-7j, 0+0j, 3+7j, 6+14j, 9+21j) op = blocks.multiply_const_cc(5+2j) self.help_cc((src_data,), expected_result, op) def test_sub_ii(self): src1_data = (1, 2, 3, 4, 5) src2_data = (8, -3, 4, 8, 2) expected_result = (-7, 5, -1, -4, 3) op = blocks.sub_ii() self.help_ii((src1_data, src2_data), expected_result, op) def test_div_ff(self): src1_data = ( 5, 9, -15, 1024) src2_data = (10, 3, -5, 64) expected_result = (0.5, 3, 3, 16) op = blocks.divide_ff() self.help_ff((src1_data, src2_data), expected_result, op) if __name__ == '__main__': gr_unittest.run(test_add_mult_div_sub, "test_add_mult_div_sub.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_stretch.py0000775000175000017500000000410112207440367022520 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_stretch(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_stretch_01(self): tb = self.tb data = 10*[1,] data0 = map(lambda x: x/20.0, data) data1 = map(lambda x: x/10.0, data) expected_result0 = 10*[0.05,] expected_result1 = 10*[0.1,] src0 = blocks.vector_source_f(data0, False) src1 = blocks.vector_source_f(data1, False) inter = blocks.streams_to_vector(gr.sizeof_float, 2) op = blocks.stretch_ff(0.1, 2) deinter = blocks.vector_to_streams(gr.sizeof_float, 2) dst0 = blocks.vector_sink_f() dst1 = blocks.vector_sink_f() tb.connect(src0, (inter,0)) tb.connect(src1, (inter,1)) tb.connect(inter, op) tb.connect(op, deinter) tb.connect((deinter,0), dst0) tb.connect((deinter,1), dst1) tb.run() dst0_data = dst0.data() dst1_data = dst1.data() self.assertFloatTuplesAlmostEqual(expected_result0, dst0_data, 4) self.assertFloatTuplesAlmostEqual(expected_result1, dst1_data, 4) if __name__ == '__main__': gr_unittest.run(test_stretch, "test_stretch.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_rms.py0000664000175000017500000000460412207440367021652 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math def sig_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: amp*math.cos(2.*math.pi*freq*x), t) return y def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: amp*math.cos(2.*math.pi*freq*x) + \ 1j*amp*math.sin(2.*math.pi*freq*x), t) return y class test_rms(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_ff(self): amp = 2 src_data = sig_source_f(1, 0.01, amp, 200) N = 750000 expected_data = amp/math.sqrt(2.0) src = blocks.vector_source_f(src_data, True) head = blocks.head(gr.sizeof_float, N) op = blocks.rms_ff(0.0001) dst = blocks.vector_sink_f() self.tb.connect(src, head, op, dst) self.tb.run() dst_data = dst.data() self.assertAlmostEqual(dst_data[-1], expected_data, 4) def test_cf(self): amp = 4 src_data = sig_source_c(1, 0.01, amp, 200) N = 750000 expected_data = amp src = blocks.vector_source_c(src_data, True) head = blocks.head(gr.sizeof_gr_complex, N) op = blocks.rms_cf(0.0001) dst = blocks.vector_sink_f() self.tb.connect(src, head, op, dst) self.tb.run() dst_data = dst.data() self.assertAlmostEqual(dst_data[-1], expected_data, 4) if __name__ == '__main__': gr_unittest.run(test_rms, "test_rms.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_nlog10.py0000775000175000017500000000276712207440367022164 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2010,2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_nlog10(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): src_data = (-10, 0, 10, 100, 1000, 10000, 100000) expected_result = (-180, -180, 10, 20, 30, 40, 50) src = blocks.vector_source_f(src_data) op = blocks.nlog10_ff(10) dst = blocks.vector_sink_f() self.tb.connect (src, op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual (expected_result, result_data) if __name__ == '__main__': gr_unittest.run(test_nlog10, "test_nlog10.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_keep_one_in_n.py0000775000175000017500000000271012207440367023640 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_keep_one_in_n(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) expected_data = (5, 10) src = blocks.vector_source_b(src_data); op = blocks.keep_one_in_n(gr.sizeof_char, 5) dst = blocks.vector_sink_b() print "HERE" self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(dst.data(), expected_data) if __name__ == '__main__': gr_unittest.run(test_keep_one_in_n, "test_integrate.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_pack_k_bits.py0000775000175000017500000000441212207440367023322 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import random from gnuradio import gr, gr_unittest, blocks class test_pack(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = (1,0,1,1,0,1,1,0) expected_results = (1,0,1,1,0,1,1,0) src = blocks.vector_source_b(src_data,False) op = blocks.pack_k_bits_bb(1) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_results, dst.data()) def test_002(self): src_data = (1,0,1,1,0,0,0,1) expected_results = ( 2, 3, 0, 1) src = blocks.vector_source_b(src_data,False) op = blocks.pack_k_bits_bb(2) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() #self.assertEqual(expected_results, dst.data()) self.assertEqual(expected_results, dst.data()) def test_003(self): src_data = expected_results = map(lambda x: random.randint(0,3), range(10)); src = blocks.vector_source_b( src_data ); pack = blocks.pack_k_bits_bb(2); unpack = blocks.unpack_k_bits_bb(2); snk = blocks.vector_sink_b(); self.tb.connect(src,unpack,pack,snk); self.tb.run() self.assertEqual(list(expected_results), list(snk.data())); if __name__ == '__main__': gr_unittest.run(test_pack, "test_pack.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_peak_detector2.py0000664000175000017500000000320512207440367023740 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_peak_detector2(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_regen1(self): tb = self.tb data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] expected_result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) src = blocks.vector_source_f(data, False) regen = blocks.peak_detector2_fb() dst = blocks.vector_sink_b() tb.connect(src, regen) tb.connect(regen, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_peak_detector2, "test_peak_detector2.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_cpp_py_binding.py0000775000175000017500000001206312207440367024036 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # # This program tests mixed python and c++ ctrlport exports in a single app # import Ice import sys, time, random, numpy from gnuradio import gr, gr_unittest, blocks from gnuradio.ctrlport import GNURadio from gnuradio import ctrlport import os def get1(): return "success" def get2(): return "failure" class inc_class: def __init__(self): self.val = 1 def pp(self): self.val = self.val+1 return self.val get3 = inc_class() def get4(): random.seed(0) rv = random.random() return rv def get5(): numpy.random.seed(0) samp_t = numpy.random.randn(24)+1j*numpy.random.randn(24); samp_f = numpy.fft.fft(samp_t); log_pow_f = 20*numpy.log10(numpy.abs(samp_f)) rv = list(log_pow_f) return rv; def get6(): numpy.random.seed(0) samp_t = numpy.random.randn(1024)+1j*numpy.random.randn(1024); rv = list(samp_t) return rv; class test_cpp_py_binding(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() os.environ['GR_CONF_CONTROLPORT_ON'] = 'True' def tearDown(self): self.tb = None def test_001(self): v1 = gr.RPC_get_string("pyland", "v1", "unit_1_string", "Python Exported String", "", "", "", gr.DISPNULL) v1.activate(get1) v2 = gr.RPC_get_string("pyland", "v2", "unit_2_string", "Python Exported String", "", "", "", gr.DISPNULL) v2.activate(get2) v3 = gr.RPC_get_int("pyland", "v3", "unit_3_int", "Python Exported Int", 0, 100, 1, gr.DISPNULL) v3.activate(get3.pp) v4 = gr.RPC_get_double("pyland", "time", "unit_4_time_double", "Python Exported Double", 0, 1000, 1, gr.DISPNULL) v4.activate(get4) v5 = gr.RPC_get_vector_float("pyland", "fvec", "unit_5_float_vector", "Python Exported Float Vector", [], [], [], gr.DISPTIME | gr.DISPOPTCPLX) v5.activate(get5) v6 = gr.RPC_get_vector_gr_complex("pyland", "cvec", "unit_6_gr_complex_vector", "Python Exported Complex Vector", [], [], [], gr.DISPXY | gr.DISPOPTSCATTER) v6.activate(get6) # print some variables locally val = get1() rval = v1.get() self.assertEqual(val, rval) val = get2() rval = v2.get() self.assertEqual(val, rval) val = get3.pp() rval = v3.get() self.assertEqual(val+1, rval) val = get4() rval = v4.get() self.assertEqual(val, rval) val = get5() rval = v5.get() self.assertComplexTuplesAlmostEqual(val, rval, 5) val = get6() rval = v6.get() self.assertComplexTuplesAlmostEqual(val, rval, 5) def test_002(self): data = range(1,9) self.src = blocks.vector_source_c(data) self.p1 = blocks.ctrlport_probe_c("aaa","C++ exported variable") self.p2 = blocks.ctrlport_probe_c("bbb","C++ exported variable") probe_name = self.p2.alias() self.tb.connect(self.src, self.p1) self.tb.connect(self.src, self.p2) self.tb.start() # Probes return complex values as list of floats with re, im # Imaginary parts of this data set are 0. expected_result = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0] # Make sure we have time for flowgraph to run time.sleep(0.1) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) # Get all exported knobs ret = radio.get([probe_name + "::bbb"]) for name in ret.keys(): result = ret[name].value self.assertEqual(result, expected_result) self.tb.stop() if __name__ == '__main__': gr_unittest.run(test_cpp_py_binding, "test_cpp_py_binding.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_message_tags.py0000664000175000017500000000161012207440367023505 0ustar jcorganjcorganimport time from gnuradio import gr, gr_unittest, blocks class test_message_tags (gr_unittest.TestCase): def test_1 (self): data = ('hello', 'you', 'there') tx_msgq = gr.msg_queue() rx_msgq = gr.msg_queue() for d in data: tx_msgq.insert_tail(gr.message_from_string(d)) tx_msgq.insert_tail(gr.message(1)) # send EOF tb = gr.top_block() src = blocks.message_source(gr.sizeof_char, tx_msgq, "packet_length") snk = blocks.message_sink(gr.sizeof_char, rx_msgq, False, "packet_length") tb.connect(src, snk) tb.start() time.sleep(1) tb.stop() for d in data: msg = rx_msgq.delete_head() contents = msg.to_string() self.assertEqual(d, contents) if __name__ == '__main__': gr_unittest.run(test_message_tags, "test_message_tags.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_vco.py0000664000175000017500000000465712207702530021641 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import math def sig_source_f(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: amp*math.cos(2.*math.pi*freq*x), t) return y def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: math.cos(2.*math.pi*freq*x) + \ 1j*math.sin(2.*math.pi*freq*x), t) return y class test_vco(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001(self): src_data = 200*[0,] + 200*[0.5,] + 200*[1,] expected_result = 200*[1,] + \ sig_source_f(1, 0.125, 1, 200) + \ sig_source_f(1, 0.25, 1, 200) src = blocks.vector_source_f(src_data) op = blocks.vco_f(1, math.pi/2.0, 1) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertFloatTuplesAlmostEqual(expected_result, result_data, 5) def test_002(self): src_data = 200*[0,] + 200*[0.5,] + 200*[1,] expected_result = 200*[1,] + \ sig_source_c(1, 0.125, 1, 200) + \ sig_source_c(1, 0.25, 1, 200) src = blocks.vector_source_f(src_data) op = blocks.vco_c(1, math.pi/2.0, 1) dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_vco, "test_vco.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_type_conversions.py0000775000175000017500000002705212207440367024467 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks from math import sqrt, atan2 class test_type_conversions(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_char_to_float_identity(self): src_data = (1, 2, 3, 4, 5) expected_data = (1.0, 2.0, 3.0, 4.0, 5.0) src = blocks.vector_source_b(src_data) op = blocks.char_to_float() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_char_to_float_scale(self): src_data = (1, 2, 3, 4, 5) expected_data = (0.5, 1.0, 1.5, 2.0, 2.5) src = blocks.vector_source_b(src_data) op = blocks.char_to_float(scale=2.0) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_char_to_short(self): src_data = (1, 2, 3, 4, 5) expected_data = (256, 512, 768, 1024, 1280) src = blocks.vector_source_b(src_data) op = blocks.char_to_short() dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_complex_to_interleaved_short(self): src_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) expected_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) src = blocks.vector_source_c(src_data) op = blocks.complex_to_interleaved_short() dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_complex_to_float_1(self): src_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) expected_data = (1.0, 3.0, 5.0, 7.0, 9.0) src = blocks.vector_source_c(src_data) op = blocks.complex_to_float() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_complex_to_float_2(self): src_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) expected_data1 = (1.0, 3.0, 5.0, 7.0, 9.0) expected_data2 = (2.0, 4.0, 6.0, 8.0, 10.0) src = blocks.vector_source_c(src_data) op = blocks.complex_to_float() dst1 = blocks.vector_sink_f() dst2 = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect((op, 0), dst1) self.tb.connect((op, 1), dst2) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data1, dst1.data()) self.assertFloatTuplesAlmostEqual(expected_data2, dst2.data()) def test_complex_to_real(self): src_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) expected_data = (1.0, 3.0, 5.0, 7.0, 9.0) src = blocks.vector_source_c(src_data) op = blocks.complex_to_real() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_complex_to_imag(self): src_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) expected_data = (2.0, 4.0, 6.0, 8.0, 10.0) src = blocks.vector_source_c(src_data) op = blocks.complex_to_imag() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_complex_to_mag(self): src_data = (1+2j, 3-4j, 5+6j, 7-8j, -9+10j) expected_data = (sqrt(5), sqrt(25), sqrt(61), sqrt(113), sqrt(181)) src = blocks.vector_source_c(src_data) op = blocks.complex_to_mag() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data(), 5) def test_complex_to_mag_squared(self): src_data = (1+2j, 3-4j, 5+6j, 7-8j, -9+10j) expected_data = (5.0, 25.0, 61.0, 113.0, 181.0) src = blocks.vector_source_c(src_data) op = blocks.complex_to_mag_squared() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_complex_to_arg(self): src_data = (1+2j, 3-4j, 5+6j, 7-8j, -9+10j) expected_data = (atan2(2, 1), atan2(-4,3), atan2(6, 5), atan2(-8, 7), atan2(10,-9)) src = blocks.vector_source_c(src_data) op = blocks.complex_to_arg() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data(), 2) def test_float_to_char_identity(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) expected_data = (1, 2, 3, 4, 5) src = blocks.vector_source_f(src_data) op = blocks.float_to_char() dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_float_to_char_scale(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) expected_data = (5, 10, 15, 20, 25) src = blocks.vector_source_f(src_data) op = blocks.float_to_char(1, 5) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_float_to_complex_1(self): src_data = (1.0, 3.0, 5.0, 7.0, 9.0) expected_data = (1+0j, 3+0j, 5+0j, 7+0j, 9+0j) src = blocks.vector_source_f(src_data) op = blocks.float_to_complex() dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_float_to_complex_2(self): src1_data = (1.0, 3.0, 5.0, 7.0, 9.0) src2_data = (2.0, 4.0, 6.0, 8.0, 10.0) expected_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) src1 = blocks.vector_source_f(src1_data) src2 = blocks.vector_source_f(src2_data) op = blocks.float_to_complex() dst = blocks.vector_sink_c() self.tb.connect(src1, (op, 0)) self.tb.connect(src2, (op, 1)) self.tb.connect(op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_float_to_int_identity(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) expected_data = (1, 2, 3, 4, 5) src = blocks.vector_source_f(src_data) op = blocks.float_to_int() dst = blocks.vector_sink_i() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_float_to_int_scale(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) expected_data = (5, 10, 15, 20, 25) src = blocks.vector_source_f(src_data) op = blocks.float_to_int(1, 5) dst = blocks.vector_sink_i() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_float_to_short_identity(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) expected_data = (1, 2, 3, 4, 5) src = blocks.vector_source_f(src_data) op = blocks.float_to_short() dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_float_to_short_scale(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) expected_data = (5, 10, 15, 20, 25) src = blocks.vector_source_f(src_data) op = blocks.float_to_short(1, 5) dst = blocks.vector_sink_s() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_float_to_uchar(self): src_data = (1.0, -2.0, 3.0, -4.0, 256.0) expected_data = (1, 0, 3, 0, 255) src = blocks.vector_source_f(src_data) op = blocks.float_to_uchar() dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_int_to_float_identity(self): src_data = (1, 2, 3, 4, 5) expected_data = (1.0, 2.0, 3.0, 4.0, 5.0) src = blocks.vector_source_i(src_data) op = blocks.int_to_float() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_int_to_float_scale(self): src_data = (1, 2, 3, 4, 5) expected_data = (0.2, 0.4, 0.6, 0.8, 1.0) src = blocks.vector_source_i(src_data) op = blocks.int_to_float(1, 5) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertFloatTuplesAlmostEqual(expected_data, dst.data()) def test_interleaved_short_to_complex(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) expected_data = (1+2j, 3+4j, 5+6j, 7+8j, 9+10j) src = blocks.vector_source_s(src_data) op = blocks.interleaved_short_to_complex() dst = blocks.vector_sink_c() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_short_to_char(self): src_data = (256, 512, 768, 1024, 1280) expected_data = (1, 2, 3, 4, 5) src = blocks.vector_source_s(src_data) op = blocks.short_to_char() dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_short_to_float_identity(self): src_data = (1, 2, 3, 4, 5) expected_data = (1.0, 2.0, 3.0, 4.0, 5.0) src = blocks.vector_source_s(src_data) op = blocks.short_to_float() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_short_to_float_scale(self): src_data = (5, 10, 15, 20, 25) expected_data = (1.0, 2.0, 3.0, 4.0, 5.0) src = blocks.vector_source_s(src_data) op = blocks.short_to_float(1, 5) dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) def test_uchar_to_float(self): src_data = (1, 2, 3, 4, 5) expected_data = (1.0, 2.0, 3.0, 4.0, 5.0) src = blocks.vector_source_b(src_data) op = blocks.uchar_to_float() dst = blocks.vector_sink_f() self.tb.connect(src, op, dst) self.tb.run() self.assertEqual(expected_data, dst.data()) if __name__ == '__main__': gr_unittest.run(test_type_conversions, "test_type_conversions.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/stream_to_vector_decimator.py0000664000175000017500000000623512207440367026000 0ustar jcorganjcorgan# # Copyright 2008 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import blocks_swig as blocks from gnuradio import gr class stream_to_vector_decimator(gr.hier_block2): """ Convert the stream to a vector, decimate the vector stream to achieve the vector rate. """ def __init__(self, item_size, sample_rate, vec_rate, vec_len): """ Create the block chain. Args: item_size: the number of bytes per sample sample_rate: the rate of incoming samples vec_rate: the rate of outgoing vectors (same units as sample_rate) vec_len: the length of the outgoing vectors in items """ self._vec_rate = vec_rate self._vec_len = vec_len self._sample_rate = sample_rate gr.hier_block2.__init__(self, "stream_to_vector_decimator", gr.io_signature(1, 1, item_size), # Input signature gr.io_signature(1, 1, item_size*vec_len)) # Output signature s2v = blocks.stream_to_vector(item_size, vec_len) self.one_in_n = blocks.keep_one_in_n(item_size*vec_len, 1) self._update_decimator() self.connect(self, s2v, self.one_in_n, self) def set_sample_rate(self, sample_rate): """ Set the new sampling rate and update the decimator. Args: sample_rate: the new rate """ self._sample_rate = sample_rate self._update_decimator() def set_vec_rate(self, vec_rate): """ Set the new vector rate and update the decimator. Args: vec_rate: the new rate """ self._vec_rate = vec_rate self._update_decimator() def set_decimation(self, decim): """ Set the decimation parameter directly. Args: decim: the new decimation """ self._decim = max(1, int(round(decim))) self.one_in_n.set_n(self._decim) def _update_decimator(self): self.set_decimation(self._sample_rate/self._vec_len/self._vec_rate) def decimation(self): """ Returns the actual decimation. """ return self._decim def sample_rate(self): """ Returns configured sample rate. """ return self._sample_rate def frame_rate(self): """ Returns actual frame rate """ return self._sample_rate/self._vec_len/self._decim gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_affinity.py0000664000175000017500000000271112207440367022657 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_affinity(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): # Just run some data through and make sure it doesn't puke. src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) src = blocks.vector_source_f(src_data) snk = blocks.vector_sink_f() src.set_processor_affinity([0,]) self.tb.connect(src, snk) self.tb.run() a = src.processor_affinity() self.assertEqual((0,), a) if __name__ == '__main__': gr_unittest.run(test_affinity, "test_affinity.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/__init__.py0000664000175000017500000000244712207440367022132 0ustar jcorganjcorgan# # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Processing blocks common to many flowgraphs. ''' import os try: from blocks_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from blocks_swig import * from stream_to_vector_decimator import * #alias old add_vXX and multiply_vXX add_vcc = add_cc add_vff = add_ff add_vii = add_ii add_vss = add_ss multiply_vcc = multiply_cc multiply_vff = multiply_ff multiply_vii = multiply_ii multiply_vss = multiply_ss gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_wavfile.py0000775000175000017500000000425012241734122022477 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import os from os.path import getsize g_in_file = os.path.join(os.getenv("srcdir"), "test_16bit_1chunk.wav") g_extra_header_offset = 36 g_extra_header_len = 18 class test_wavefile(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001_checkwavread(self): wf = blocks.wavfile_source(g_in_file) self.assertEqual(wf.sample_rate(), 8000) def test_002_checkwavcopy(self): infile = g_in_file outfile = "test_out.wav" wf_in = blocks.wavfile_source(infile) wf_out = blocks.wavfile_sink(outfile, wf_in.channels(), wf_in.sample_rate(), wf_in.bits_per_sample()) self.tb.connect(wf_in, wf_out) self.tb.run() wf_out.close() # we're loosing all extra header chunks self.assertEqual(getsize(infile) - g_extra_header_len, getsize(outfile)) in_f = file(infile, 'rb') out_f = file(outfile, 'rb') in_data = in_f.read() out_data = out_f.read() out_f.close() os.remove(outfile) # cut extra header chunks input file self.assertEqual(in_data[:g_extra_header_offset] + \ in_data[g_extra_header_offset + g_extra_header_len:], out_data) if __name__ == '__main__': gr_unittest.run(test_wavefile, "test_wavefile.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_copy.py0000775000175000017500000000353312207440367022026 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_copy(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_copy(self): src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) expected_result = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) src = blocks.vector_source_b(src_data) op = blocks.copy(gr.sizeof_char) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) def test_copy_drop (self): src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) expected_result = () src = blocks.vector_source_b(src_data) op = blocks.copy(gr.sizeof_char) op.set_enabled(False) dst = blocks.vector_sink_b() self.tb.connect(src, op, dst) self.tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_copy, "test_copy.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_pdu.py0000775000175000017500000000672512243433176021652 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import time from gnuradio import gr, gr_unittest, blocks import pmt class test_pdu(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): # Just run some data through and make sure it doesn't puke. src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) src = blocks.pdu_to_tagged_stream(blocks.byte_t) snk3 = blocks.tagged_stream_to_pdu(blocks.byte_t) snk2 = blocks.vector_sink_b() snk = blocks.tag_debug(1, "test") snk.set_display(False) dbg = blocks.message_debug() # Test that the right number of ports exist. pi = snk3.message_ports_in() po = snk3.message_ports_out() self.assertEqual(pmt.length(pi), 0) self.assertEqual(pmt.length(po), 1) self.tb.connect(src, snk) self.tb.connect(src, snk2) self.tb.connect(src, snk3) self.tb.msg_connect(snk3, "pdus", dbg, "store") self.tb.start() # make our reference and message pmts port = pmt.intern("pdus") msg = pmt.cons( pmt.PMT_NIL, pmt.make_u8vector(16, 0xFF)) # post the message src.to_basic_block()._post(port, msg) # eww, what's that smell? while dbg.num_messages() < 1: time.sleep(0.1) self.tb.stop() self.tb.wait() # Get the vector of data from the vector sink result_data = snk2.data() # Get the vector of data from the message sink # Convert the message PMT as a pair into its vector result_msg = dbg.get_message(0) msg_vec = pmt.cdr(result_msg) #pmt.print(msg_vec) # Convert the PMT vector into a Python list msg_data = [] for i in xrange(16): msg_data.append(pmt.u8vector_ref(msg_vec, i)) actual_data = 16*[0xFF,] self.assertEqual(actual_data, list(result_data)) self.assertEqual(actual_data, msg_data) def test_001(self): #Test the overflow buffer in pdu_to_tagged_stream src_data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] src = blocks.pdu_to_tagged_stream(blocks.float_t) snk = blocks.vector_sink_f() self.tb.connect(src, snk) port = pmt.intern("pdus") msg = pmt.cons( pmt.PMT_NIL, pmt.init_f32vector(10, src_data)) src.to_basic_block()._post(port, msg) src.set_max_noutput_items(5) self.tb.start() #ideally, would wait until we get ten samples time.sleep(0.2) self.tb.stop() self.assertEqual(src_data, list(snk.data()) ) if __name__ == '__main__': gr_unittest.run(test_pdu, "test_pdu.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/test_16bit_1chunk.wav0000664000175000017500000000010612241734122023754 0ustar jcorganjcorganRIFF,WAVEfmt @>LISTJUNKdata@3sgnuradio-3.7.2.1/gr-blocks/python/blocks/qa_peak_detector.py0000664000175000017500000000530612207440367023662 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class test_peak_detector(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_01(self): tb = self.tb data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] expected_result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) src = blocks.vector_source_f(data, False) regen = blocks.peak_detector_fb() dst = blocks.vector_sink_b() tb.connect(src, regen) tb.connect(regen, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) def test_02(self): tb = self.tb data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] expected_result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) src = blocks.vector_source_i(data, False) regen = blocks.peak_detector_ib() dst = blocks.vector_sink_b() tb.connect(src, regen) tb.connect(regen, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) def test_03(self): tb = self.tb data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] expected_result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) src = blocks.vector_source_s(data, False) regen = blocks.peak_detector_sb() dst = blocks.vector_sink_b() tb.connect(src, regen) tb.connect(regen, dst) tb.run() dst_data = dst.data() self.assertEqual(expected_result, dst_data) if __name__ == '__main__': gr_unittest.run(test_peak_detector, "test_peak_detector.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_python_message_passing.py0000664000175000017500000001013112207440367025612 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import pmt import numpy import time # Simple block to generate messages class message_generator(gr.sync_block): def __init__(self, msg_list, msg_interval): gr.sync_block.__init__( self, name = "message generator", in_sig = [numpy.float32], out_sig = None ) self.msg_list = msg_list self.msg_interval = msg_interval self.msg_ctr = 0 self.message_port_register_out(pmt.intern('out_port')) def work(self, input_items, output_items): inLen = len(input_items[0]) while self.msg_ctr < len(self.msg_list) and \ (self.msg_ctr * self.msg_interval) < \ (self.nitems_read(0) + inLen): self.message_port_pub(pmt.intern('out_port'), self.msg_list[self.msg_ctr]) self.msg_ctr += 1 return inLen # Simple block to consume messages class message_consumer(gr.sync_block): def __init__(self): gr.sync_block.__init__( self, name = "message consumer", in_sig = None, out_sig = None ) self.msg_list = [] self.message_port_register_in(pmt.intern('in_port')) self.set_msg_handler(pmt.intern('in_port'), self.handle_msg) def handle_msg(self, msg): # Create a new PMT from long value and put in list self.msg_list.append(pmt.from_long(pmt.to_long(msg))) class test_python_message_passing(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000(self): num_msgs = 10 msg_interval = 1000 msg_list = [] for i in range(num_msgs): msg_list.append(pmt.from_long(i)) # Create vector source with dummy data to trigger messages src_data = [] for i in range(num_msgs*msg_interval): src_data.append(float(i)) src = blocks.vector_source_f(src_data, False) msg_gen = message_generator(msg_list, msg_interval) msg_cons = message_consumer() # Connect vector source to message gen self.tb.connect(src, msg_gen) # Connect message generator to message consumer self.tb.msg_connect(msg_gen, 'out_port', msg_cons, 'in_port') # Verify that the messgae port query functions work self.assertEqual(pmt.symbol_to_string(pmt.vector_ref( msg_gen.message_ports_out(), 0)), 'out_port') self.assertEqual(pmt.symbol_to_string(pmt.vector_ref( msg_cons.message_ports_in(), 0)), 'in_port') # Run to verify message passing self.tb.start() # Wait for all messages to be sent while msg_gen.msg_ctr < num_msgs: time.sleep(0.5) self.tb.stop() self.tb.wait() # Verify that the message consumer got all the messages self.assertEqual(num_msgs, len(msg_cons.msg_list)) for i in range(num_msgs): self.assertTrue(pmt.equal(msg_list[i], msg_cons.msg_list[i])) if __name__ == '__main__': gr_unittest.run(test_python_message_passing, 'test_python_message_passing.xml') gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_bin_statistics.py0000775000175000017500000001612412207440367024076 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import random import struct """ Note: There has been an issue with this block in the past, see Issue #199. This test is being enabled only on the 'next' branch for version v3.7 for now. TWR """ class counter(gr.feval_dd): def __init__(self, step_size=1): gr.feval_dd.__init__(self) self.step_size = step_size self.count = 0 def eval(self, input): #print "eval: self.count =", self.count t = self.count self.count = self.count + self.step_size return t class counter3(gr.feval_dd): def __init__(self, f, step_size): gr.feval_dd.__init__(self) self.f = f self.step_size = step_size self.count = 0 def eval(self, input): try: #print "eval: self.count =", self.count t = self.count self.count = self.count + self.step_size self.f(self.count) except Exception, e: print "Exception: ", e return t def foobar3(new_t): #print "foobar3: new_t =", new_t pass class counter4(gr.feval_dd): def __init__(self, obj_instance, step_size): gr.feval_dd.__init__(self) self.obj_instance = obj_instance self.step_size = step_size self.count = 0 def eval(self, input): try: #print "eval: self.count =", self.count t = self.count self.count = self.count + self.step_size self.obj_instance.foobar4(self.count) except Exception, e: print "Exception: ", e return t class parse_msg(object): def __init__(self, msg): self.center_freq = msg.arg1() self.vlen = int(msg.arg2()) assert(msg.length() == self.vlen * gr.sizeof_float) self.data = struct.unpack('%df' % (self.vlen,), msg.to_string()) class test_bin_statistics(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block () def tearDown(self): self.tb = None def test_001(self): vlen = 4 tune = counter(1) tune_delay = 0 dwell_delay = 1 msgq = gr.msg_queue() src_data = tuple([float(x) for x in ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 )]) expected_results = tuple([float(x) for x in ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 )]) src = blocks.vector_source_f(src_data, False) s2v = blocks.stream_to_vector(gr.sizeof_float, vlen) stats = blocks.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay) self.tb.connect(src, s2v, stats) self.tb.run() self.assertEqual(4, msgq.count()) for i in range(4): m = parse_msg(msgq.delete_head()) #print "m =", m.center_freq, m.data self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data) def test_002(self): vlen = 4 tune = counter(1) tune_delay = 1 dwell_delay = 2 msgq = gr.msg_queue() src_data = tuple([float(x) for x in ( 1, 2, 3, 4, 9, 6, 11, 8, 5, 10, 7, 12, 13, 14, 15, 16 )]) expected_results = tuple([float(x) for x in ( 9, 10, 11, 12)]) src = blocks.vector_source_f(src_data, False) s2v = blocks.stream_to_vector(gr.sizeof_float, vlen) stats = blocks.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay) self.tb.connect(src, s2v, stats) self.tb.run() self.assertEqual(1, msgq.count()) for i in range(1): m = parse_msg(msgq.delete_head()) #print "m =", m.center_freq, m.data self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data) def test_003(self): vlen = 4 tune = counter3(foobar3, 1) tune_delay = 1 dwell_delay = 2 msgq = gr.msg_queue() src_data = tuple([float(x) for x in ( 1, 2, 3, 4, 9, 6, 11, 8, 5, 10, 7, 12, 13, 14, 15, 16 )]) expected_results = tuple([float(x) for x in ( 9, 10, 11, 12)]) src = blocks.vector_source_f(src_data, False) s2v = blocks.stream_to_vector(gr.sizeof_float, vlen) stats = blocks.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay) self.tb.connect(src, s2v, stats) self.tb.run() self.assertEqual(1, msgq.count()) for i in range(1): m = parse_msg(msgq.delete_head()) #print "m =", m.center_freq, m.data self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data) def foobar4(self, new_t): #print "foobar4: new_t =", new_t pass def test_004(self): vlen = 4 tune = counter4(self, 1) tune_delay = 1 dwell_delay = 2 msgq = gr.msg_queue() src_data = tuple([float(x) for x in ( 1, 2, 3, 4, 9, 6, 11, 8, 5, 10, 7, 12, 13, 14, 15, 16 )]) expected_results = tuple([float(x) for x in ( 9, 10, 11, 12)]) src = blocks.vector_source_f(src_data, False) s2v = blocks.stream_to_vector(gr.sizeof_float, vlen) stats = blocks.bin_statistics_f(vlen, msgq, tune, tune_delay, dwell_delay) self.tb.connect(src, s2v, stats) self.tb.run() self.assertEqual(1, msgq.count()) for i in range(1): m = parse_msg(msgq.delete_head()) #print "m =", m.center_freq, m.data self.assertEqual(expected_results[vlen*i:vlen*i + vlen], m.data) if __name__ == '__main__': gr_unittest.run(test_bin_statistics, "test_bin_statistics.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_ctrlport_probes.py0000664000175000017500000001631312207702530024265 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import Ice import sys, time, random, numpy from gnuradio import gr, gr_unittest, blocks from gnuradio.ctrlport import GNURadio from gnuradio import ctrlport import os, struct class test_ctrlport_probes(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() os.environ['GR_CONF_CONTROLPORT_ON'] = 'True' def tearDown(self): self.tb = None def test_001(self): data = range(1,9) self.src = blocks.vector_source_c(data, True) self.probe = blocks.ctrlport_probe2_c("samples","Complex", len(data), gr.DISPNULL) probe_name = self.probe.alias() self.tb.connect(self.src, self.probe) self.tb.start() # Probes return complex values as list of floats with re, im # Imaginary parts of this data set are 0. expected_result = [1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0] # Make sure we have time for flowgraph to run time.sleep(0.1) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) # Get all exported knobs ret = radio.get([probe_name + "::samples"]) for name in ret.keys(): # Get data in probe, which might be offset; find the # beginning and unwrap. result = ret[name].value i = result.index(1.0) result = result[i:] + result[0:i] self.assertEqual(expected_result, result) self.tb.stop() def test_002(self): data = range(1,9) self.src = blocks.vector_source_f(data, True) self.probe = blocks.ctrlport_probe2_f("samples","Floats", len(data), gr.DISPNULL) probe_name = self.probe.alias() self.tb.connect(self.src, self.probe) self.tb.start() expected_result = [1, 2, 3, 4, 5, 6, 7, 8,] # Make sure we have time for flowgraph to run time.sleep(0.1) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) # Get all exported knobs ret = radio.get([probe_name + "::samples"]) for name in ret.keys(): # Get data in probe, which might be offset; find the # beginning and unwrap. result = ret[name].value i = result.index(1.0) result = result[i:] + result[0:i] self.assertEqual(expected_result, result) self.tb.stop() def test_003(self): data = range(1,9) self.src = blocks.vector_source_i(data, True) self.probe = blocks.ctrlport_probe2_i("samples","Integers", len(data), gr.DISPNULL) probe_name = self.probe.alias() self.tb.connect(self.src, self.probe) self.tb.start() expected_result = [1, 2, 3, 4, 5, 6, 7, 8,] # Make sure we have time for flowgraph to run time.sleep(0.1) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) # Get all exported knobs ret = radio.get([probe_name + "::samples"]) for name in ret.keys(): # Get data in probe, which might be offset; find the # beginning and unwrap. result = ret[name].value i = result.index(1.0) result = result[i:] + result[0:i] self.assertEqual(expected_result, result) self.tb.stop() def test_004(self): data = range(1,9) self.src = blocks.vector_source_s(data, True) self.probe = blocks.ctrlport_probe2_s("samples","Shorts", len(data), gr.DISPNULL) probe_name = self.probe.alias() self.tb.connect(self.src, self.probe) self.tb.start() expected_result = [1, 2, 3, 4, 5, 6, 7, 8,] # Make sure we have time for flowgraph to run time.sleep(0.1) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) # Get all exported knobs ret = radio.get([probe_name + "::samples"]) for name in ret.keys(): # Get data in probe, which might be offset; find the # beginning and unwrap. result = ret[name].value i = result.index(1.0) result = result[i:] + result[0:i] self.assertEqual(expected_result, result) self.tb.stop() def test_005(self): data = range(1,9) self.src = blocks.vector_source_b(data, True) self.probe = blocks.ctrlport_probe2_b("samples","Bytes", len(data), gr.DISPNULL) probe_name = self.probe.alias() self.tb.connect(self.src, self.probe) self.tb.start() expected_result = [1, 2, 3, 4, 5, 6, 7, 8,] # Make sure we have time for flowgraph to run time.sleep(0.1) # Get available endpoint ep = gr.rpcmanager_get().endpoints()[0] # Initialize a simple Ice client from endpoint ic = Ice.initialize(sys.argv) base = ic.stringToProxy(ep) radio = GNURadio.ControlPortPrx.checkedCast(base) # Get all exported knobs ret = radio.get([probe_name + "::samples"]) for name in ret.keys(): # Get data in probe, which might be offset; find the # beginning and unwrap. result = ret[name].value result = list(struct.unpack(len(result)*'b', result)) i = result.index(1) result = result[i:] + result[0:i] self.assertEqual(expected_result, result) self.tb.stop() if __name__ == '__main__': gr_unittest.run(test_ctrlport_probes, "test_ctrlport_probes.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_burst_tagger.py0000664000175000017500000000374712207440367023550 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks import pmt class test_burst_tagger(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): src_data = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) trg_data = (-1, -1, 1, 1, -1, -1, 1, 1, -1, -1) src = blocks.vector_source_i(src_data) trg = blocks.vector_source_s(trg_data) op = blocks.burst_tagger(gr.sizeof_int) snk = blocks.tag_debug(gr.sizeof_int, "burst tagger QA") self.tb.connect(src, (op,0)) self.tb.connect(trg, (op,1)) self.tb.connect(op, snk) self.tb.run() x = snk.current_tags() self.assertEqual(2, x[0].offset) self.assertEqual(4, x[1].offset) self.assertEqual(6, x[2].offset) self.assertEqual(8, x[3].offset) self.assertEqual(True, pmt.to_bool(x[0].value)) self.assertEqual(False, pmt.to_bool(x[1].value)) self.assertEqual(True, pmt.to_bool(x[2].value)) self.assertEqual(False, pmt.to_bool(x[3].value)) if __name__ == '__main__': gr_unittest.run(test_burst_tagger, "test_burst_tagger.xml") gnuradio-3.7.2.1/gr-blocks/python/blocks/qa_plateau_detector_fb.py0000775000175000017500000000321312207440367025042 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, blocks class qa_plateau_detector_fb (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): # | Spur spike 1 | Plateau | Spur spike 2 test_signal = (0, 1, .2, .4, .6, .8, 1, 1, 1, 1, 1, .8, .6, .4, 1, 0) expected_sig = (0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0) # | Center of Plateau sink = blocks.vector_sink_b() self.tb.connect(blocks.vector_source_f(test_signal), blocks.plateau_detector_fb(5), sink) self.tb.run () self.assertEqual(expected_sig, sink.data()) if __name__ == '__main__': gr_unittest.run(qa_plateau_detector_fb, "qa_plateau_detector_fb.xml") gnuradio-3.7.2.1/gr-blocks/lib/0000775000175000017500000000000012245466767016000 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/lib/tagged_file_sink_impl.cc0000664000175000017500000001543512207440367022600 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "tagged_file_sink_impl.h" #include #include #include #include #include #include #include #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { tagged_file_sink::sptr tagged_file_sink::make(size_t itemsize, double samp_rate) { return gnuradio::get_initial_sptr (new tagged_file_sink_impl(itemsize, samp_rate)); } tagged_file_sink_impl::tagged_file_sink_impl(size_t itemsize, double samp_rate) : sync_block("tagged_file_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize (itemsize), d_n(0), d_sample_rate(samp_rate) { d_state = NOT_IN_BURST; d_last_N = 0; d_timeval = 0; } tagged_file_sink_impl::~tagged_file_sink_impl() { } int tagged_file_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *inbuf = (char*)input_items[0]; uint64_t start_N = nitems_read(0); uint64_t end_N = start_N + (uint64_t)(noutput_items); pmt::pmt_t bkey = pmt::string_to_symbol("burst"); pmt::pmt_t tkey = pmt::string_to_symbol("rx_time"); // use gr_tags::key_time std::vector all_tags; get_tags_in_range(all_tags, 0, start_N, end_N); std::sort(all_tags.begin(), all_tags.end(), tag_t::offset_compare); std::vector::iterator vitr = all_tags.begin(); // Look for a time tag and initialize d_timeval. std::vector time_tags_outer; get_tags_in_range(time_tags_outer, 0, start_N, end_N, tkey); if(time_tags_outer.size() > 0) { const tag_t tag = time_tags_outer[0]; uint64_t offset = tag.offset; pmt::pmt_t time = tag.value; uint64_t tsecs = pmt::to_uint64(pmt::tuple_ref(time, 0)); double tfrac = pmt::to_double(pmt::tuple_ref(time, 1)); double delta = (double)offset / d_sample_rate; d_timeval = (double)tsecs + tfrac + delta; d_last_N = offset; } int idx = 0, idx_stop = 0; while(idx < noutput_items) { if(d_state == NOT_IN_BURST) { while(vitr != all_tags.end()) { if((pmt::eqv((*vitr).key, bkey)) && pmt::is_true((*vitr).value)) { uint64_t N = (*vitr).offset; idx = (int)(N - start_N); //std::cout << std::endl << "Found start of burst: " // << idx << ", " << N << std::endl; // Find time burst occurred by getting latest time tag and extrapolating // to new time based on sample rate of this block. std::vector time_tags; //get_tags_in_range(time_tags, 0, d_last_N, N, gr_tags::key_time); get_tags_in_range(time_tags, 0, d_last_N, N, tkey); if(time_tags.size() > 0) { const tag_t tag = time_tags[time_tags.size()-1]; uint64_t time_nitems = tag.offset; // Get time based on last time tag from USRP pmt::pmt_t time = tag.value; uint64_t tsecs = pmt::to_uint64(pmt::tuple_ref(time, 0)); double tfrac = pmt::to_double(pmt::tuple_ref(time, 1)); // Get new time from last time tag + difference in time to when // burst tag occured based on the sample rate double delta = (double)(N - time_nitems) / d_sample_rate; d_timeval = (double)tsecs + tfrac + delta; //std::cout.setf(std::ios::fixed, std::ios::floatfield); //std::cout.precision(8); //std::cout << "Time found: " << (double)tsecs + tfrac << std::endl; //std::cout << " time: " << d_timeval << std::endl; //std::cout << " time at N = " << time_nitems << " burst N = " << N << std::endl; } else { // if no time tag, use last seen tag and update time based on // sample rate of the block d_timeval += (double)(N - d_last_N) / d_sample_rate; //std::cout << "Time not found" << std::endl; //std::cout << " time: " << d_timeval << std::endl; } d_last_N = N; std::stringstream filename; filename.setf(std::ios::fixed, std::ios::floatfield); filename.precision(8); filename << "file" << unique_id() << "_" << d_n << "_" << d_timeval << ".dat"; d_n++; int fd; if((fd = ::open(filename.str().c_str(), O_WRONLY|O_CREAT|O_TRUNC|OUR_O_LARGEFILE|OUR_O_BINARY, 0664)) < 0){ perror(filename.str().c_str()); return -1; } // FIXME: //if((d_handle = fdopen (fd, d_is_binary ? "wb" : "w")) == NULL) { if((d_handle = fdopen (fd, "wb")) == NULL) { perror(filename.str().c_str()); ::close(fd); // don't leak file descriptor if fdopen fails. } //std::cout << "Created new file: " << filename.str() << std::endl; d_state = IN_BURST; break; } vitr++; } if(d_state == NOT_IN_BURST) return noutput_items; } else { // In burst while(vitr != all_tags.end()) { if((pmt::eqv((*vitr).key, bkey)) && pmt::is_false((*vitr).value)) { uint64_t N = (*vitr).offset; idx_stop = (int)N - start_N; //std::cout << "Found end of burst: " // << idx_stop << ", " << N << std::endl; int count = fwrite (&inbuf[d_itemsize*idx], d_itemsize, idx_stop-idx, d_handle); if(count == 0) { if(ferror(d_handle)) { perror("tagged_file_sink: error writing file"); } } idx = idx_stop; d_state = NOT_IN_BURST; vitr++; fclose(d_handle); break; } else { vitr++; } } if(d_state == IN_BURST) { int count = fwrite (&inbuf[d_itemsize*idx], d_itemsize, noutput_items-idx, d_handle); if (count == 0) { if(ferror(d_handle)) { perror("tagged_file_sink: error writing file"); } } idx = noutput_items; } } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_mag_impl.h0000664000175000017500000000252012207440367022150 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_MAG_IMPL_H #define INCLUDED_COMPLEX_TO_MAG_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_mag_impl : public complex_to_mag { size_t d_vlen; public: complex_to_mag_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_MAG_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/deinterleave_impl.cc0000664000175000017500000000407412207440367021766 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "deinterleave_impl.h" #include namespace gr { namespace blocks { deinterleave::sptr deinterleave::make(size_t itemsize) { return gnuradio::get_initial_sptr(new deinterleave_impl(itemsize)); } deinterleave_impl::deinterleave_impl(size_t itemsize) : sync_decimator("deinterleave", io_signature::make (1, 1, itemsize), io_signature::make (1, io_signature::IO_INFINITE, itemsize), 1), d_itemsize(itemsize) { } bool deinterleave_impl::check_topology(int ninputs, int noutputs) { set_decimation(noutputs); return true; } int deinterleave_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t nchan = output_items.size(); size_t itemsize = d_itemsize; const char *in = (const char *)input_items[0]; char **out = (char **)&output_items[0]; for (int i = 0; i < noutput_items; i++){ for (unsigned int n = 0; n < nchan; n++){ memcpy(out[n], in, itemsize); out[n] += itemsize; in += itemsize; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/stream_to_vector_impl.cc0000664000175000017500000000362312207440367022675 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "stream_to_vector_impl.h" #include namespace gr { namespace blocks { stream_to_vector::sptr stream_to_vector::make(size_t itemsize, size_t nitems_per_block) { return gnuradio::get_initial_sptr(new stream_to_vector_impl(itemsize, nitems_per_block)); } stream_to_vector_impl::stream_to_vector_impl(size_t itemsize, size_t nitems_per_block) : sync_decimator ("stream_to_vector", io_signature::make (1, 1, itemsize), io_signature::make (1, 1, itemsize * nitems_per_block), nitems_per_block) { } int stream_to_vector_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t block_size = output_signature()->sizeof_stream_item (0); const char *in = (const char *) input_items[0]; char *out = (char *) output_items[0]; memcpy (out, in, noutput_items * block_size); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/null_sink_impl.cc0000664000175000017500000000323712207440367021315 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "null_sink_impl.h" #include namespace gr { namespace blocks { null_sink::sptr null_sink::make(size_t sizeof_stream_item) { return gnuradio::get_initial_sptr (new null_sink_impl(sizeof_stream_item)); } null_sink_impl::null_sink_impl(size_t sizeof_stream_item) : sync_block("null_sink", io_signature::make(1, 1, sizeof_stream_item), io_signature::make(0, 0, 0)) { } null_sink_impl::~null_sink_impl() { } int null_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vector_to_streams_impl.h0000664000175000017500000000254012207440367022717 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VECTOR_TO_STREAMS_IMPL_H #define INCLUDED_VECTOR_TO_STREAMS_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API vector_to_streams_impl : public vector_to_streams { public: vector_to_streams_impl(size_t itemsize, size_t nstreams); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_VECTOR_TO_STREAMS_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_conjugate_cc_impl.h0000664000175000017500000000262612207440367023545 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_MULTIPLY_CONJUGATE_CC_IMPL_H #define INCLUDED_BLOCKS_MULTIPLY_CONJUGATE_CC_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API multiply_conjugate_cc_impl : public multiply_conjugate_cc { size_t d_vlen; public: multiply_conjugate_cc_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_MULTIPLY_CONJUGATE_CC_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/stream_to_streams_impl.h0000664000175000017500000000254012207440367022710 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_STREAM_TO_STREAMS_IMPL_H #define INCLUDED_STREAM_TO_STREAMS_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API stream_to_streams_impl : public stream_to_streams { public: stream_to_streams_impl(size_t itemsize, size_t nstreams); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_STREAM_TO_STREAMS_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/repeat_impl.h0000664000175000017500000000247612207440367020445 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_REPEAT_IMPL_H #define INCLUDED_REPEAT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API repeat_impl : public repeat { size_t d_itemsize; int d_interp; public: repeat_impl(size_t itemsize, int d_interp); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_REPEAT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/stream_to_vector_impl.h0000664000175000017500000000254112207440367022535 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_STREAM_TO_VECTOR_IMPL_H #define INCLUDED_STREAM_TO_VECTOR_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API stream_to_vector_impl : public stream_to_vector { public: stream_to_vector_impl(size_t itemsize, size_t nitems_per_block); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_STREAM_TO_VECTOR_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/CMakeLists.txt0000664000175000017500000002463112245466767020546 0ustar jcorganjcorgan# Copyright 2012-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup compatibility checks and defines ######################################################################## include(${CMAKE_CURRENT_SOURCE_DIR}/ConfigChecks.cmake) ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict(name, sig, 'blocks') build_utils.expand_template(d, inp, '_impl') ") macro(expand_cc_h_impl root) #make a list of all the generated files unset(expanded_files_cc_impl) unset(expanded_files_h_impl) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_cc_impl ${CMAKE_CURRENT_BINARY_DIR}/${name}_impl.cc) list(APPEND expanded_files_h_impl ${CMAKE_CURRENT_BINARY_DIR}/${name}_impl.h) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/../include/${name}.h) endforeach(sig) #create a command to generate the _impl.cc files add_custom_command( OUTPUT ${expanded_files_cc_impl} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}_impl.cc.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}_impl.cc.t ${ARGN} ) #create a command to generate the _impl.h files add_custom_command( OUTPUT ${expanded_files_h_impl} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}_impl.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}_impl.h.t ${ARGN} ) #make _impl.cc source files depend on headers to force generation set_source_files_properties(${expanded_files_cc_impl} PROPERTIES OBJECT_DEPENDS "${expanded_files_h_impl}" ) #make _impl.h source files depend on headers to force generation set_source_files_properties(${expanded_files_h_impl} PROPERTIES OBJECT_DEPENDS "${expanded_files_h}" ) #install rules for the generated cc files list(APPEND generated_sources ${expanded_files_cc_impl}) endmacro(expand_cc_h_impl) ######################################################################## # Invoke macro to generate various sources ######################################################################## expand_cc_h_impl(add_XX ss ii cc) expand_cc_h_impl(add_const_XX bb ss ii ff cc) expand_cc_h_impl(add_const_vXX bb ss ii ff cc) expand_cc_h_impl(and_XX bb ss ii) expand_cc_h_impl(and_const_XX bb ss ii) expand_cc_h_impl(argmax_XX fs is ss) expand_cc_h_impl(divide_XX ss ii ff cc) expand_cc_h_impl(integrate_XX ss ii ff cc) expand_cc_h_impl(max_XX ff ii ss) expand_cc_h_impl(moving_average_XX ss ii ff cc) expand_cc_h_impl(multiply_XX ss ii) expand_cc_h_impl(multiply_const_XX ss ii) expand_cc_h_impl(multiply_const_vXX ss ii ff cc) expand_cc_h_impl(mute_XX ss ii ff cc) expand_cc_h_impl(not_XX bb ss ii) expand_cc_h_impl(or_XX bb ss ii) expand_cc_h_impl(peak_detector_XX fb ib sb) expand_cc_h_impl(probe_signal_X b s i f c) expand_cc_h_impl(probe_signal_vX b s i f c) expand_cc_h_impl(sample_and_hold_XX bb ss ii ff) expand_cc_h_impl(sub_XX ss ii ff cc) expand_cc_h_impl(xor_XX bb ss ii) expand_cc_h_impl(packed_to_unpacked_XX bb ss ii) expand_cc_h_impl(unpacked_to_packed_XX bb ss ii) expand_cc_h_impl(vector_insert_X b s i f c) expand_cc_h_impl(vector_sink_X b s i f c) expand_cc_h_impl(vector_source_X b s i f c) ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/../include ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${VOLK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND gr_blocks_sources ${generated_sources} control_loop.cc count_bits.cc file_sink_base.cc wavfile.cc add_ff_impl.cc annotator_1to1_impl.cc annotator_alltoall_impl.cc annotator_raw_impl.cc bin_statistics_f_impl.cc burst_tagger_impl.cc char_to_float_impl.cc char_to_short_impl.cc check_lfsr_32k_s_impl.cc complex_to_interleaved_short_impl.cc complex_to_float_impl.cc complex_to_real_impl.cc complex_to_imag_impl.cc complex_to_mag_impl.cc complex_to_mag_squared_impl.cc complex_to_arg_impl.cc conjugate_cc_impl.cc copy_impl.cc deinterleave_impl.cc delay_impl.cc endian_swap_impl.cc file_descriptor_sink_impl.cc file_descriptor_source_impl.cc file_sink_impl.cc file_source_impl.cc file_meta_sink_impl.cc file_meta_source_impl.cc float_to_char_impl.cc float_to_complex_impl.cc float_array_to_int.cc float_to_int_impl.cc float_to_short_impl.cc float_array_to_uchar.cc float_to_uchar_impl.cc head_impl.cc int_to_float_impl.cc interleave_impl.cc interleaved_short_array_to_complex.cc interleaved_short_to_complex_impl.cc interleaved_char_to_complex_impl.cc keep_m_in_n_impl.cc keep_one_in_n_impl.cc lfsr_32k_source_s_impl.cc message_debug_impl.cc message_sink_impl.cc message_source_impl.cc message_strobe_impl.cc message_burst_source_impl.cc multiply_cc_impl.cc multiply_ff_impl.cc multiply_conjugate_cc_impl.cc multiply_const_cc_impl.cc multiply_const_ff_impl.cc nlog10_ff_impl.cc nop_impl.cc null_sink_impl.cc null_source_impl.cc pack_k_bits_bb_impl.cc patterned_interleaver_impl.cc pdu.cc tag_debug_impl.cc pdu_to_tagged_stream_impl.cc peak_detector2_fb_impl.cc random_pdu_impl.cc plateau_detector_fb_impl.cc probe_rate_impl.cc regenerate_bb_impl.cc repack_bits_bb_impl.cc repeat_impl.cc rms_cf_impl.cc rms_ff_impl.cc short_to_char_impl.cc short_to_float_impl.cc skiphead_impl.cc socket_pdu_impl.cc stream_mux_impl.cc stream_pdu_base.cc stream_to_streams_impl.cc stream_to_tagged_stream_impl.cc stream_to_vector_impl.cc streams_to_stream_impl.cc streams_to_vector_impl.cc stretch_ff_impl.cc tagged_file_sink_impl.cc tagged_stream_to_pdu_impl.cc tags_strobe_impl.cc threshold_ff_impl.cc throttle_impl.cc transcendental_impl.cc tcp_connection.cc tuntap_pdu_impl.cc tag_gate_impl.cc tagged_stream_mux_impl.cc uchar_array_to_float.cc uchar_to_float_impl.cc udp_sink_impl.cc udp_source_impl.cc unpack_k_bits_bb_impl.cc vco_f_impl.cc vco_c_impl.cc vector_map_impl.cc vector_to_stream_impl.cc vector_to_streams_impl.cc wavfile_sink_impl.cc wavfile_source_impl.cc ) if(ENABLE_GR_CTRLPORT) list(APPEND gr_blocks_sources ctrlport_probe_c_impl.cc ctrlport_probe2_c_impl.cc ctrlport_probe2_f_impl.cc ctrlport_probe2_s_impl.cc ctrlport_probe2_i_impl.cc ctrlport_probe2_b_impl.cc ) endif(ENABLE_GR_CTRLPORT) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-blocks.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-blocks.rc @ONLY) list(APPEND gr_blocks_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-blocks.rc ) ENDIF(MSVC) list(APPEND blocks_libs gnuradio-runtime volk ${Boost_LIBRARIES} ${BLOCKS_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_library(gnuradio-blocks SHARED ${gr_blocks_sources}) add_dependencies(gnuradio-blocks blocks_generated_includes) target_link_libraries(gnuradio-blocks ${blocks_libs}) GR_LIBRARY_FOO(gnuradio-blocks RUNTIME_COMPONENT "blocks_runtime" DEVEL_COMPONENT "blocks_devel") ######################################################################## # QA C++ Code for gr-blocks ######################################################################## if(ENABLE_TESTING) include(GrTest) include_directories( ${GR_BLOCKS_INCLUDE_DIRS} ${CPPUNIT_INCLUDE_DIRS}) link_directories(${CPPUNIT_LIBRARY_DIRS}) list(APPEND test_gr_blocks_sources ${CMAKE_CURRENT_SOURCE_DIR}/test_gr_blocks.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_gr_block.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_gr_top_block.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_gr_hier_block2.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_gr_hier_block2_derived.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_blocks.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_block_tags.cc ${CMAKE_CURRENT_SOURCE_DIR}/qa_rotator.cc ) add_executable(test-gr-blocks ${test_gr_blocks_sources}) list(APPEND GR_TEST_TARGET_DEPS test-gr-blocks gnuradio-blocks) target_link_libraries( test-gr-blocks gnuradio-runtime gnuradio-blocks ${Boost_LIBRARIES} ${CPPUNIT_LIBRARIES} ${LOG4CPP_LIBRARIES} ) GR_ADD_TEST(test_gr_blocks test-gr-blocks) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-blocks/lib/tags_strobe_impl.h0000664000175000017500000000332512207702530021464 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAGS_STROBE_IMPL_H #define INCLUDED_GR_TAGS_STROBE_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API tags_strobe_impl : public tags_strobe { private: size_t d_itemsize; uint64_t d_nsamps; tag_t d_tag; uint64_t d_offset; void run(); public: tags_strobe_impl(size_t sizeof_stream_item, pmt::pmt_t value, uint64_t nsamps); ~tags_strobe_impl(); void set_value(pmt::pmt_t value); pmt::pmt_t value() const { return d_tag.value; } void set_nsamps(uint64_t nsamps); uint64_t nsamps() const { return d_nsamps; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TAGS_STROBE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/and_const_XX_impl.cc.t0000664000175000017500000000371712207440367022153 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(@O_TYPE@ k) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(k)); } @NAME_IMPL@::@NAME_IMPL@(@O_TYPE@ k) : sync_block ("@NAME@", io_signature::make (1, 1, sizeof (@I_TYPE@)), io_signature::make (1, 1, sizeof (@O_TYPE@))), d_k(k) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *) input_items[0]; @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int size = noutput_items; while (size >= 8){ *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; *optr++ = *iptr++ & d_k; size -= 8; } while (size-- > 0) *optr++ = *iptr++ & d_k; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/socket_pdu_impl.cc0000664000175000017500000001624412207440367021461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "socket_pdu_impl.h" #include "tcp_connection.h" #include #include namespace gr { namespace blocks { socket_pdu::sptr socket_pdu::make(std::string type, std::string addr, std::string port, int MTU) { return gnuradio::get_initial_sptr(new socket_pdu_impl(type, addr, port, MTU)); } socket_pdu_impl::socket_pdu_impl(std::string type, std::string addr, std::string port, int MTU) : block("socket_pdu", io_signature::make (0, 0, 0), io_signature::make (0, 0, 0)) { message_port_register_in(PDU_PORT_ID); message_port_register_out(PDU_PORT_ID); if ((type == "TCP_SERVER") || (type == "TCP_CLIENT")) { boost::asio::ip::tcp::resolver resolver(d_io_service); boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), addr, port); d_tcp_endpoint = *resolver.resolve(query); } if ((type == "UDP_SERVER") || (type == "UDP_CLIENT")) { boost::asio::ip::udp::resolver resolver(d_io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), addr, port); if (type == "UDP_SERVER") d_udp_endpoint = *resolver.resolve(query); else d_udp_endpoint_other = *resolver.resolve(query); } if (type == "TCP_SERVER") { d_acceptor_tcp.reset(new boost::asio::ip::tcp::acceptor(d_io_service, d_tcp_endpoint)); d_acceptor_tcp->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); start_tcp_accept(); set_msg_handler(PDU_PORT_ID, boost::bind(&socket_pdu_impl::tcp_server_send, this, _1)); } else if (type =="TCP_CLIENT") { boost::system::error_code error = boost::asio::error::host_not_found; d_tcp_socket.reset(new boost::asio::ip::tcp::socket(d_io_service)); d_tcp_socket->connect(d_tcp_endpoint, error); if (error) throw boost::system::system_error(error); set_msg_handler(PDU_PORT_ID, boost::bind(&socket_pdu_impl::tcp_client_send, this, _1)); d_tcp_socket->async_read_some( boost::asio::buffer(d_rxbuf), boost::bind(&socket_pdu_impl::handle_tcp_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else if (type =="UDP_SERVER") { d_udp_socket.reset(new boost::asio::ip::udp::socket(d_io_service, d_udp_endpoint)); d_udp_socket->async_receive_from(boost::asio::buffer(d_rxbuf), d_udp_endpoint_other, boost::bind(&socket_pdu_impl::handle_udp_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); set_msg_handler(PDU_PORT_ID, boost::bind(&socket_pdu_impl::udp_send, this, _1)); } else if (type =="UDP_CLIENT") { d_udp_socket.reset(new boost::asio::ip::udp::socket(d_io_service, d_udp_endpoint)); d_udp_socket->async_receive_from(boost::asio::buffer(d_rxbuf), d_udp_endpoint_other, boost::bind(&socket_pdu_impl::handle_udp_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); set_msg_handler(PDU_PORT_ID, boost::bind(&socket_pdu_impl::udp_send, this, _1)); } else throw std::runtime_error("gr::blocks:socket_pdu: unknown socket type"); d_thread = gr::thread::thread(boost::bind(&socket_pdu_impl::run_io_service, this)); d_started = true; } void socket_pdu_impl::handle_tcp_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { pmt::pmt_t vector = pmt::init_u8vector(bytes_transferred, (const uint8_t *)&d_rxbuf[0]); pmt::pmt_t pdu = pmt::cons(pmt::PMT_NIL, vector); message_port_pub(PDU_PORT_ID, pdu); d_tcp_socket->async_read_some(boost::asio::buffer(d_rxbuf), boost::bind(&socket_pdu_impl::handle_tcp_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else throw boost::system::system_error(error); } void socket_pdu_impl::start_tcp_accept() { tcp_connection::sptr new_connection = tcp_connection::make(d_acceptor_tcp->get_io_service()); d_acceptor_tcp->async_accept(new_connection->socket(), boost::bind(&socket_pdu_impl::handle_tcp_accept, this, new_connection, boost::asio::placeholders::error)); } void socket_pdu_impl::tcp_server_send(pmt::pmt_t msg) { pmt::pmt_t vector = pmt::cdr(msg); for(size_t i = 0; i < d_tcp_connections.size(); i++) d_tcp_connections[i]->send(vector); } void socket_pdu_impl::handle_tcp_accept(tcp_connection::sptr new_connection, const boost::system::error_code& error) { if (!error) { new_connection->start(this); d_tcp_connections.push_back(new_connection); start_tcp_accept(); } else std::cout << error << std::endl; } void socket_pdu_impl::tcp_client_send(pmt::pmt_t msg) { pmt::pmt_t vector = pmt::cdr(msg); size_t len = pmt::length(vector); size_t offset(0); boost::array txbuf; memcpy(&txbuf[0], pmt::uniform_vector_elements(vector, offset), len); d_tcp_socket->send(boost::asio::buffer(txbuf,len)); } void socket_pdu_impl::udp_send(pmt::pmt_t msg) { pmt::pmt_t vector = pmt::cdr(msg); size_t len = pmt::length(vector); size_t offset(0); boost::array txbuf; memcpy(&txbuf[0], pmt::uniform_vector_elements(vector, offset), len); if (d_udp_endpoint_other.address().to_string() != "0.0.0.0") d_udp_socket->send_to(boost::asio::buffer(txbuf,len), d_udp_endpoint_other); } void socket_pdu_impl::handle_udp_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { pmt::pmt_t vector = pmt::init_u8vector(bytes_transferred, (const uint8_t*)&d_rxbuf[0]); pmt::pmt_t pdu = pmt::cons( pmt::PMT_NIL, vector); message_port_pub(PDU_PORT_ID, pdu); d_udp_socket->async_receive_from(boost::asio::buffer(d_rxbuf), d_udp_endpoint_other, boost::bind(&socket_pdu_impl::handle_udp_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/xor_XX_impl.cc.t0000664000175000017500000000354312207440367021010 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc ^= ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/stream_pdu_base.cc0000664000175000017500000000626312207440367021435 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef HAVE_IO_H #include #endif #ifdef HAVE_WINDOWS_H #include #endif #include #include #include "stream_pdu_base.h" #include static const long timeout_us = 100*1000; //100ms namespace gr { namespace blocks { stream_pdu_base::stream_pdu_base(int MTU) : d_fd(-1), d_started(false), d_finished(false) { // reserve space for rx buffer d_rxbuf.resize(MTU,0); } stream_pdu_base::~stream_pdu_base() { stop_rxthread(); } void stream_pdu_base::start_rxthread(basic_block *blk, pmt::pmt_t port) { d_blk = blk; d_port = port; d_thread = gr::thread::thread(boost::bind(&stream_pdu_base::run, this)); d_started = true; } void stream_pdu_base::stop_rxthread() { d_finished = true; if (d_started) { d_thread.interrupt(); d_thread.join(); } } void stream_pdu_base::run() { while(!d_finished) { if (!wait_ready()) continue; const int result = read(d_fd, &d_rxbuf[0], d_rxbuf.size()); if (result <= 0) throw std::runtime_error("stream_pdu_base, bad socket read!"); pmt::pmt_t vector = pmt::init_u8vector(result, &d_rxbuf[0]); pmt::pmt_t pdu = pmt::cons(pmt::PMT_NIL, vector); d_blk->message_port_pub(d_port, pdu); } } bool stream_pdu_base::wait_ready() { //setup timeval for timeout timeval tv; tv.tv_sec = 0; tv.tv_usec = timeout_us; //setup rset for timeout fd_set rset; FD_ZERO(&rset); FD_SET(d_fd, &rset); //call select with timeout on receive socket return ::select(d_fd+1, &rset, NULL, NULL, &tv) > 0; } void stream_pdu_base::send(pmt::pmt_t msg) { pmt::pmt_t vector = pmt::cdr(msg); size_t offset(0); size_t itemsize(pdu::itemsize(pdu::type_from_pmt(vector))); int len(pmt::length(vector)*itemsize); const int rv = write(d_fd, pmt::uniform_vector_elements(vector, offset), len); if (rv != len) { std::cerr << boost::format("WARNING: stream_pdu_base::send(pdu) write failed! (d_fd=%d, len=%d, rv=%d)") % d_fd % len % rv << std::endl; } } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_mag_squared_impl.h0000664000175000017500000000261012207440367023674 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_MAG_SQUARED_IMPL_H #define INCLUDED_COMPLEX_TO_MAG_SQUARED_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_mag_squared_impl : public complex_to_mag_squared { size_t d_vlen; public: complex_to_mag_squared_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_MAG_SQUARED_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_flowgraph.cc0000664000175000017500000001577612207440367021453 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include void qa_gr_flowgraph::t0() { gr_flowgraph_sptr fg = gr_make_flowgraph(); CPPUNIT_ASSERT(fg); } void qa_gr_flowgraph::t1_connect() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); } void qa_gr_flowgraph::t2_connect_invalid_src_port_neg() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); CPPUNIT_ASSERT_THROW(fg->connect(nop1, -1, nop2, 0), std::invalid_argument); } void qa_gr_flowgraph::t3_connect_src_port_exceeds() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr src = gr::blocks::null_source::make(sizeof(int)); block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); CPPUNIT_ASSERT_THROW(fg->connect(src, 1, dst, 0), std::invalid_argument); } void qa_gr_flowgraph::t4_connect_invalid_dst_port_neg() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); CPPUNIT_ASSERT_THROW(fg->connect(nop1, 0, nop2, -1), std::invalid_argument); } void qa_gr_flowgraph::t5_connect_dst_port_exceeds() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr src = gr::blocks::null_source::make(sizeof(int)); block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); CPPUNIT_ASSERT_THROW(fg->connect(src, 0, dst, 1), std::invalid_argument); } void qa_gr_flowgraph::t6_connect_dst_in_use() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr src1 = gr::blocks::null_source::make(sizeof(int)); block_sptr src2 = gr::blocks::null_source::make(sizeof(int)); block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); fg->connect(src1, 0, dst, 0); CPPUNIT_ASSERT_THROW(fg->connect(src2, 0, dst, 0), std::invalid_argument); } void qa_gr_flowgraph::t7_connect_one_src_two_dst() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr src = gr::blocks::null_source::make(sizeof(int)); block_sptr dst1 = gr::blocks::null_sink::make(sizeof(int)); block_sptr dst2 = gr::blocks::null_sink::make(sizeof(int)); fg->connect(src, 0, dst1, 0); fg->connect(src, 0, dst2, 0); } void qa_gr_flowgraph::t8_connect_type_mismatch() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(char)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); CPPUNIT_ASSERT_THROW(fg->connect(nop1, 0, nop2, 0), std::invalid_argument); } void qa_gr_flowgraph::t9_disconnect() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); fg->disconnect(nop1, 0, nop2, 0); } void qa_gr_flowgraph::t10_disconnect_unconnected_block() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); block_sptr nop3 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); CPPUNIT_ASSERT_THROW(fg->disconnect(nop1, 0, nop3, 0), std::invalid_argument); } void qa_gr_flowgraph::t11_disconnect_unconnected_port() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); CPPUNIT_ASSERT_THROW(fg->disconnect(nop1, 0, nop2, 1), std::invalid_argument); } void qa_gr_flowgraph::t12_validate() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); fg->validate(); } void qa_gr_flowgraph::t13_validate_missing_input_assignment() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); fg->connect(nop1, 0, nop2, 2); CPPUNIT_ASSERT_THROW(fg->validate(), std::runtime_error); } void qa_gr_flowgraph::t14_validate_missing_output_assignment() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); fg->connect(nop1, 2, nop2, 1); CPPUNIT_ASSERT_THROW(fg->validate(), std::runtime_error); } void qa_gr_flowgraph::t15_clear() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop1 = gr::blocks::nop::make(sizeof(int)); block_sptr nop2 = gr::blocks::nop::make(sizeof(int)); fg->connect(nop1, 0, nop2, 0); CPPUNIT_ASSERT(fg->edges().size() == 1); CPPUNIT_ASSERT(fg->calc_used_blocks().size() == 2); fg->clear(); CPPUNIT_ASSERT(fg->edges().size() == 0); CPPUNIT_ASSERT(fg->calc_used_blocks().size() == 0); } void qa_gr_flowgraph::t16_partition() { gr_flowgraph_sptr fg = gr_make_flowgraph(); block_sptr nop11 = gr::blocks::nop::make(sizeof(int)); block_sptr nop12 = gr::blocks::nop::make(sizeof(int)); block_sptr nop13 = gr::blocks::nop::make(sizeof(int)); block_sptr nop14 = gr::blocks::nop::make(sizeof(int)); block_sptr nop21 = gr::blocks::nop::make(sizeof(int)); block_sptr nop22 = gr::blocks::nop::make(sizeof(int)); block_sptr nop23 = gr::blocks::nop::make(sizeof(int)); block_sptr nop31 = gr::blocks::nop::make(sizeof(int)); block_sptr nop32 = gr::blocks::nop::make(sizeof(int)); // Build disjoint graph #1 fg->connect(nop11, 0, nop12, 0); fg->connect(nop12, 0, nop13, 0); fg->connect(nop13, 0, nop14, 0); // Build disjoint graph #2 fg->connect(nop21, 0, nop22, 0); fg->connect(nop22, 0, nop23, 0); // Build disjoint graph #3 fg->connect(nop31, 0, nop32, 0); std::vector graphs = fg->partition(); CPPUNIT_ASSERT(graphs.size() == 3); CPPUNIT_ASSERT(graphs[0].size() == 4); CPPUNIT_ASSERT(graphs[1].size() == 3); CPPUNIT_ASSERT(graphs[2].size() == 2); } gnuradio-3.7.2.1/gr-blocks/lib/udp_source_impl.h0000664000175000017500000000544012207440367021327 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UDP_SOURCE_IMPL_H #define INCLUDED_GR_UDP_SOURCE_IMPL_H #include #include #include #include namespace gr { namespace blocks { class udp_source_impl : public udp_source { private: size_t d_itemsize; int d_payload_size; // maximum transmission unit (packet length) bool d_eof; // look for an EOF signal bool d_connected; // are we connected? char *d_rxbuf; // get UDP buffer items char *d_residbuf; // hold buffer between calls ssize_t d_residual; // hold information about number of bytes stored in residbuf ssize_t d_sent; // track how much of d_residbuf we've outputted size_t d_offset; // point to residbuf location offset std::string d_host; unsigned short d_port; boost::asio::ip::udp::socket *d_socket; boost::asio::ip::udp::endpoint d_endpoint; boost::asio::ip::udp::endpoint d_endpoint_rcvd; boost::asio::io_service d_io_service; gr::thread::condition_variable d_cond_wait; gr::thread::mutex d_udp_mutex; gr::thread::thread d_udp_thread; void start_receive(); void handle_read(const boost::system::error_code& error, size_t bytes_transferred); void run_io_service() { d_io_service.run(); } public: udp_source_impl(size_t itemsize, const std::string &host, int port, int payload_size, bool eof); ~udp_source_impl(); void connect(const std::string &host, int port); void disconnect(); int payload_size() { return d_payload_size; } int get_port(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_UDP_SOURCE_H */ gnuradio-3.7.2.1/gr-blocks/lib/tag_debug_impl.cc0000664000175000017500000001107212237515111021225 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "tag_debug_impl.h" #include #include #include namespace gr { namespace blocks { tag_debug::sptr tag_debug::make(size_t sizeof_stream_item, const std::string &name, const std::string &key_filter) { return gnuradio::get_initial_sptr (new tag_debug_impl(sizeof_stream_item, name, key_filter)); } tag_debug_impl::tag_debug_impl(size_t sizeof_stream_item, const std::string &name, const std::string &key_filter) : sync_block("tag_debug", io_signature::make(1, -1, sizeof_stream_item), io_signature::make(0, 0, 0)), d_name(name), d_display(true) { set_key_filter(key_filter); } tag_debug_impl::~tag_debug_impl() { } std::vector tag_debug_impl::current_tags() { gr::thread::scoped_lock l(d_mutex); return d_tags; } int tag_debug_impl::num_tags() { std::vector t; get_tags_in_range(t, 0, 0, nitems_read(0)); return static_cast(t.size()); } void tag_debug_impl::set_display(bool d) { d_display = d; } void tag_debug_impl::set_key_filter(const std::string &key_filter) { if(key_filter == "") d_filter = pmt::PMT_NIL; else d_filter = pmt::intern(key_filter); } std::string tag_debug_impl::key_filter() const { return pmt::symbol_to_string(d_filter); } int tag_debug_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_mutex); std::stringstream sout; if(d_display) { sout << std::endl << "----------------------------------------------------------------------"; sout << std::endl << "Tag Debug: " << d_name << std::endl; } uint64_t abs_N, end_N; for(size_t i = 0; i < input_items.size(); i++) { abs_N = nitems_read(i); end_N = abs_N + (uint64_t)(noutput_items); d_tags.clear(); if(pmt::is_null(d_filter)) get_tags_in_range(d_tags, i, abs_N, end_N); else get_tags_in_range(d_tags, i, abs_N, end_N, d_filter); if(d_display) { sout << "Input Stream: " << std::setw(2) << std::setfill('0') << i << std::setfill(' ') << std::endl; for(d_tags_itr = d_tags.begin(); d_tags_itr != d_tags.end(); d_tags_itr++) { sout << std::setw(10) << "Offset: " << d_tags_itr->offset << std::setw(10) << "Source: " << (pmt::is_symbol(d_tags_itr->srcid) ? pmt::symbol_to_string(d_tags_itr->srcid) : "n/a") << std::setw(10) << "Key: " << pmt::symbol_to_string(d_tags_itr->key) << std::setw(10) << "Value: "; sout << d_tags_itr->value << std::endl; } } } if(d_display) { sout << "----------------------------------------------------------------------"; sout << std::endl; if(d_tags.size() > 0) std::cout << sout.str(); } return noutput_items; } void tag_debug_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "num. tags", &tag_debug::num_tags, pmt::from_long(0), pmt::from_long(10000), pmt::from_long(0), "", "Number of Tags", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/moving_average_XX_impl.cc.t0000664000175000017500000000556212207440367023174 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME_IMPL@.h" #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(int length, @O_TYPE@ scale, int max_iter) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(length, scale, max_iter)); } @NAME_IMPL@::@NAME_IMPL@(int length, @O_TYPE@ scale, int max_iter) : sync_block("@NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_length(length), d_scale(scale), d_max_iter(max_iter), d_new_length(length), d_new_scale(scale), d_updated(false) { set_history(length); } @NAME_IMPL@::~@NAME_IMPL@() { } void @NAME_IMPL@::set_length_and_scale(int length, @O_TYPE@ scale) { d_new_length = length; d_new_scale = scale; d_updated = true; } void @NAME_IMPL@::set_length(int length) { d_new_length = length; d_updated = true; } void @NAME_IMPL@::set_scale(@O_TYPE@ scale) { d_new_scale = scale; d_updated = true; } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { if(d_updated) { d_length = d_new_length; d_scale = d_new_scale; set_history(d_length); d_updated = false; return 0; // history requirements might have changed } const @I_TYPE@ *in = (const @I_TYPE@ *)input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[0]; @I_TYPE@ sum = 0; int num_iter = (noutput_items>d_max_iter) ? d_max_iter : noutput_items; for(int i = 0; i < d_length-1; i++) { sum += in[i]; } for(int i = 0; i < num_iter; i++) { sum += in[i+d_length-1]; out[i] = sum * d_scale; sum -= in[i]; } return num_iter; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/annotator_alltoall_impl.h0000664000175000017500000000316612207440367023053 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ANNOTATOR_ALLTOALL_IMPL_H #define INCLUDED_GR_ANNOTATOR_ALLTOALL_IMPL_H #include namespace gr { namespace blocks { class annotator_alltoall_impl : public annotator_alltoall { private: size_t d_itemsize; uint64_t d_when; uint64_t d_tag_counter; std::vector d_stored_tags; public: annotator_alltoall_impl(int when, size_t sizeof_stream_item); ~annotator_alltoall_impl(); std::vector data() const { return d_stored_tags; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ANNOTATOR_ALLTOALL_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/throttle_impl.cc0000664000175000017500000000727312207440367021170 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "throttle_impl.h" #include #include #include namespace gr { namespace blocks { throttle::sptr throttle::make(size_t itemsize, double samples_per_sec) { return gnuradio::get_initial_sptr (new throttle_impl(itemsize, samples_per_sec)); } throttle_impl::throttle_impl(size_t itemsize, double samples_per_second) : sync_block("throttle", io_signature::make(1, 1, itemsize), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize) { set_sample_rate(samples_per_second); } throttle_impl::~throttle_impl() { } void throttle_impl::set_sample_rate(double rate) { //changing the sample rate performs a reset of state params d_start = boost::get_system_time(); d_total_samples = 0; d_samps_per_tick = rate/boost::posix_time::time_duration::ticks_per_second(); d_samps_per_us = rate/1e6; } double throttle_impl::sample_rate() const { return d_samps_per_us * 1e6; } int throttle_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { //calculate the expected number of samples to have passed through boost::system_time now = boost::get_system_time(); boost::int64_t ticks = (now - d_start).ticks(); uint64_t expected_samps = uint64_t(d_samps_per_tick*ticks); //if the expected samples was less, we need to throttle back if(d_total_samples > expected_samps) { boost::this_thread::sleep(boost::posix_time::microseconds (long((d_total_samples - expected_samps)/d_samps_per_us))); } //copy all samples output[i] <= input[i] const char *in = (const char *)input_items[0]; char *out = (char *)output_items[0]; std::memcpy(out, in, noutput_items * d_itemsize); d_total_samples += noutput_items; return noutput_items; } void throttle_impl::setup_rpc() { #ifdef GR_CTRLPORT d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "sample_rate", &throttle::sample_rate, pmt::mp(0.0), pmt::mp(100.0e6), pmt::mp(0.0), "Hz", "Sample Rate", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "sample_rate", &throttle::set_sample_rate, pmt::mp(0.0), pmt::mp(100.0e6), pmt::mp(0.0), "Hz", "Sample Rate", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe_c_impl.cc0000664000175000017500000000561612207440367022664 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe_c_impl.h" #include namespace gr { namespace blocks { ctrlport_probe_c::sptr ctrlport_probe_c::make(const std::string &id, const std::string &desc) { return gnuradio::get_initial_sptr (new ctrlport_probe_c_impl(id, desc)); } ctrlport_probe_c_impl::ctrlport_probe_c_impl(const std::string &id, const std::string &desc) : sync_block("probe_c", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_ptr(NULL), d_ptrLen(0) { } ctrlport_probe_c_impl::~ctrlport_probe_c_impl() { } std::vector ctrlport_probe_c_impl::get() { if(d_ptr != NULL && d_ptrLen > 0) { ptrlock.lock(); std::vector vec(d_ptr, d_ptr+d_ptrLen); ptrlock.unlock(); return vec; } else { std::vector vec; return vec; } } int ctrlport_probe_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; // keep reference to symbols ptrlock.lock(); d_ptr = in; d_ptrLen = noutput_items; ptrlock.unlock(); return noutput_items; } void ctrlport_probe_c_impl::setup_rpc() { #ifdef GR_CTRLPORT d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get > >( alias(), d_id.c_str(), &ctrlport_probe_c::get, pmt::make_c32vector(0,-2), pmt::make_c32vector(0,2), pmt::make_c32vector(0,0), "volts", d_desc.c_str(), RPC_PRIVLVL_MIN, DISPXY | DISPOPTSCATTER))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/max_XX_impl.h.t0000664000175000017500000000247612207440367020633 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: size_t d_vlen; public: @NAME_IMPL@(size_t vlen); ~@NAME_IMPL@(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_top_block.cc0000664000175000017500000001700012207440367021414 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #define VERBOSE 0 void qa_top_block::t0() { if (VERBOSE) std::cout << "qa_top_block::t0()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); CPPUNIT_ASSERT(tb); } void qa_top_block::t1_run() { if (VERBOSE) std::cout << "qa_top_block::t1()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->run(); } void qa_top_block::t2_start_stop_wait() { if(VERBOSE) std::cout << "qa_top_block::t2()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->start(); tb->stop(); tb->wait(); } void qa_top_block::t3_lock_unlock() { if(VERBOSE) std::cout << "qa_top_block::t3()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); tb->connect(src, 0, dst, 0); tb->start(); tb->lock(); tb->unlock(); tb->stop(); tb->wait(); } void qa_top_block::t4_reconfigure() { if(VERBOSE) std::cout << "qa_top_block::t4()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); // Start infinite flowgraph tb->connect(src, 0, dst, 0); tb->start(); // Reconfigure with gr_head in the middle tb->lock(); tb->disconnect(src, 0, dst, 0); tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->unlock(); // Wait for flowgraph to end on its own tb->wait(); } void qa_top_block::t5_max_noutputs() { if(VERBOSE) std::cout << "qa_top_block::t5()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); // Start infinite flowgraph tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->start(100); tb->wait(); } void qa_top_block::t6_reconfig_max_noutputs() { if(VERBOSE) std::cout << "qa_top_block::t6()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); // Start infinite flowgraph tb->connect(src, 0, dst, 0); tb->start(100); // Reconfigure with gr_head in the middle tb->lock(); tb->disconnect(src, 0, dst, 0); tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->set_max_noutput_items(1000); head->set_max_noutput_items(500); tb->unlock(); // Wait for flowgraph to end on its own tb->wait(); } void qa_top_block::t7_max_noutputs_per_block() { if(VERBOSE) std::cout << "qa_top_block::t7()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); head->set_max_noutput_items(100); // Start infinite flowgraph tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->start(); tb->wait(); } void qa_top_block::t8_reconfig_max_noutputs_per_block() { if(VERBOSE) std::cout << "qa_top_block::t8()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); head->set_max_noutput_items(99); // Start infinite flowgraph tb->connect(src, 0, dst, 0); tb->start(201); // Reconfigure with gr_head in the middle tb->lock(); tb->disconnect(src, 0, dst, 0); tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->set_max_noutput_items(1023); head->set_max_noutput_items(513); tb->unlock(); // Wait for flowgraph to end on its own tb->wait(); } void qa_top_block::t9_max_output_buffer() { if(VERBOSE) std::cout << "qa_top_block::t9()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); head->set_max_output_buffer(1024); // Start infinite flowgraph tb->connect(src, 0, head, 0); tb->connect(head, 0, dst, 0); tb->start(); tb->wait(); } void qa_top_block::t10_reconfig_max_output_buffer() { if(VERBOSE) std::cout << "qa_top_block::t10()\n"; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::block_sptr head = gr::blocks::head::make(sizeof(int), 100000); gr::block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); head->set_max_output_buffer(1000); // Start infinite flowgraph tb->connect(src, 0, dst, 0); tb->start(201); // Reconfigure with gr_head in the middle tb->lock(); gr::block_sptr nop = gr::blocks::nop::make(sizeof(int)); nop->set_max_output_buffer(4000); tb->disconnect(src, 0, dst, 0); tb->connect(src, 0, head, 0); tb->connect(head, 0, nop, 0); tb->connect(nop, 0, dst, 0); tb->unlock(); // Wait for flowgraph to end on its own tb->wait(); } void qa_top_block::t11_set_block_affinity() { gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(float))); gr::block_sptr snk (gr::blocks::null_sink::make(sizeof(float))); std::vector set(1, 0), ret; src->set_processor_affinity(set); tb->connect(src, 0, snk, 0); tb->start(); tb->stop(); tb->wait(); ret = src->processor_affinity(); // We only set the core affinity to 0 because we always know at // least one thread core exists to use. CPPUNIT_ASSERT_EQUAL(set[0], ret[0]); } gnuradio-3.7.2.1/gr-blocks/lib/peak_detector_XX_impl.cc.t0000664000175000017500000000746112207440367023014 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME_IMPL@.h" #include #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(float threshold_factor_rise, float threshold_factor_fall, int look_ahead, float alpha) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(threshold_factor_rise, threshold_factor_fall, look_ahead, alpha)); } @NAME_IMPL@::@NAME_IMPL@(float threshold_factor_rise, float threshold_factor_fall, int look_ahead, float alpha) : sync_block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(char))), d_threshold_factor_rise(threshold_factor_rise), d_threshold_factor_fall(threshold_factor_fall), d_look_ahead(look_ahead), d_avg_alpha(alpha), d_avg(0), d_found(0) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@*)input_items[0]; char *optr = (char*)output_items[0]; memset(optr, 0, noutput_items*sizeof(char)); @I_TYPE@ peak_val = -(@I_TYPE@)INFINITY; int peak_ind = 0; unsigned char state = 0; int i = 0; //printf("noutput_items %d\n",noutput_items); while(i < noutput_items) { if(state == 0) { // below threshold if(iptr[i] > d_avg*d_threshold_factor_rise) { state = 1; } else { d_avg = (d_avg_alpha)*iptr[i] + (1-d_avg_alpha)*d_avg; i++; } } else if(state == 1) { // above threshold, have not found peak //printf("Entered State 1: %f i: %d noutput_items: %d\n", iptr[i], i, noutput_items); if(iptr[i] > peak_val) { peak_val = iptr[i]; peak_ind = i; d_avg = (d_avg_alpha)*iptr[i] + (1-d_avg_alpha)*d_avg; i++; } else if(iptr[i] > d_avg*d_threshold_factor_fall) { d_avg = (d_avg_alpha)*iptr[i] + (1-d_avg_alpha)*d_avg; i++; } else { optr[peak_ind] = 1; state = 0; peak_val = -(@I_TYPE@)INFINITY; //printf("Leaving State 1: Peak: %f Peak Ind: %d i: %d noutput_items: %d\n", //peak_val, peak_ind, i, noutput_items); } } } if(state == 0) { //printf("Leave in State 0, produced %d\n",noutput_items); return noutput_items; } else { // only return up to passing the threshold //printf("Leave in State 1, only produced %d of %d\n",peak_ind,noutput_items); return peak_ind+1; } } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/tuntap_pdu_impl.h0000664000175000017500000000276612207440367021352 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_TUNTAP_PDU_IMPL_H #define INCLUDED_BLOCKS_TUNTAP_PDU_IMPL_H #include #include "stream_pdu_base.h" #if (defined(linux) || defined(__linux) || defined(__linux__)) #include #endif namespace gr { namespace blocks { class tuntap_pdu_impl : public tuntap_pdu, public stream_pdu_base { #if (defined(linux) || defined(__linux) || defined(__linux__)) private: std::string d_dev; int tun_alloc(char *dev, int flags = IFF_TAP | IFF_NO_PI); public: tuntap_pdu_impl(std::string dev, int MTU); #endif }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_TUNTAP_PDU_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/char_to_short_impl.cc0000664000175000017500000000360012244272666022155 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "char_to_short_impl.h" #include #include namespace gr { namespace blocks { char_to_short::sptr char_to_short::make(size_t vlen) { return gnuradio::get_initial_sptr(new char_to_short_impl(vlen)); } char_to_short_impl::char_to_short_impl(size_t vlen) : sync_block("char_to_short", io_signature::make(1, 1, sizeof(char)*vlen), io_signature::make(1, 1, sizeof(short)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(short); set_alignment(std::max(1, alignment_multiple)); } int char_to_short_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const int8_t *in = (const int8_t *)input_items[0]; int16_t *out = (int16_t *)output_items[0]; volk_8i_convert_16i(out, in, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/plateau_detector_fb_impl.cc0000664000175000017500000000542112207440367023307 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "plateau_detector_fb_impl.h" namespace gr { namespace blocks { plateau_detector_fb::sptr plateau_detector_fb::make(int max_len, float threshold) { return gnuradio::get_initial_sptr (new plateau_detector_fb_impl(max_len, threshold)); } plateau_detector_fb_impl::plateau_detector_fb_impl(int max_len, float threshold) : block("plateau_detector_fb", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(char))), d_max_len(max_len), d_threshold(threshold) {} plateau_detector_fb_impl::~plateau_detector_fb_impl() { } void plateau_detector_fb_impl::forecast(int, gr_vector_int &ninput_items_required) { ninput_items_required[0] = 2*d_max_len; } int plateau_detector_fb_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; int flank_start; noutput_items = std::min(noutput_items, ninput_items[0]); memset((void *) out, 0x00, noutput_items); int i; for(i = 0; i < noutput_items; i++) { if(in[i] >= d_threshold) { if(noutput_items-i < 2*d_max_len) { // If we can't finish, come back later break; } flank_start = i; while(i < noutput_items && in[i] >= d_threshold) i++; if((i - flank_start) > 1) { // 1 Sample is not a plateau out[flank_start + (i-flank_start)/2] = 1; i = std::min(i+d_max_len, noutput_items-1); } } } this->consume_each(i); return i; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/integrate_XX_impl.h.t0000664000175000017500000000245412207440367022024 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { int d_decim; int d_count; public: @NAME_IMPL@(int decim); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_flowgraph.h0000664000175000017500000000457212207440367021305 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_FLOWGRAPH_H #define INCLUDED_QA_GR_FLOWGRAPH_H #include #include #include class qa_gr_flowgraph : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_gr_flowgraph); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1_connect); CPPUNIT_TEST(t2_connect_invalid_src_port_neg); CPPUNIT_TEST(t3_connect_src_port_exceeds); CPPUNIT_TEST(t4_connect_invalid_dst_port_neg); CPPUNIT_TEST(t5_connect_dst_port_exceeds); CPPUNIT_TEST(t6_connect_dst_in_use); CPPUNIT_TEST(t7_connect_one_src_two_dst); CPPUNIT_TEST(t8_connect_type_mismatch); CPPUNIT_TEST(t9_disconnect); CPPUNIT_TEST(t10_disconnect_unconnected_block); CPPUNIT_TEST(t11_disconnect_unconnected_port); CPPUNIT_TEST(t12_validate); CPPUNIT_TEST(t13_validate_missing_input_assignment); CPPUNIT_TEST(t14_validate_missing_output_assignment); CPPUNIT_TEST(t15_clear); CPPUNIT_TEST(t16_partition); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1_connect(); void t2_connect_invalid_src_port_neg(); void t3_connect_src_port_exceeds(); void t4_connect_invalid_dst_port_neg(); void t5_connect_dst_port_exceeds(); void t6_connect_dst_in_use(); void t7_connect_one_src_two_dst(); void t8_connect_type_mismatch(); void t9_disconnect(); void t10_disconnect_unconnected_block(); void t11_disconnect_unconnected_port(); void t12_validate(); void t13_validate_missing_input_assignment(); void t14_validate_missing_output_assignment(); void t15_clear(); void t16_partition(); }; #endif /* INCLUDED_QA_GR_FLOWGRAPH_H */ gnuradio-3.7.2.1/gr-blocks/lib/short_to_char_impl.h0000664000175000017500000000251112207440367022011 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SHORT_TO_CHAR_IMPL_H #define INCLUDED_SHORT_TO_CHAR_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API short_to_char_impl : public short_to_char { size_t d_vlen; public: short_to_char_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_SHORT_TO_CHAR_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/delay_impl.cc0000664000175000017500000001032212237515111020377 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "delay_impl.h" #include #include namespace gr { namespace blocks { delay::sptr delay::make(size_t itemsize, int delay) { return gnuradio::get_initial_sptr (new delay_impl(itemsize, delay)); } delay_impl::delay_impl(size_t itemsize, int delay) : block("delay", io_signature::make(1, -1, itemsize), io_signature::make(1, -1, itemsize)), d_itemsize(itemsize) { set_dly(delay); d_delta = 0; } delay_impl::~delay_impl() { } void delay_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = noutput_items; } void delay_impl::set_dly(int d) { // only set a new delta if there is a change in the delay; this // protects from quickly-repeated calls to this function that // would end with d_delta=0. if(d != dly()) { gr::thread::scoped_lock l(d_mutex_delay); int old = dly(); set_history(d+1); declare_sample_delay(history()-1); d_delta += dly() - old; } } int delay_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_mutex_delay); assert(input_items.size() == output_items.size()); const char *iptr; char *optr; int cons, ret; // No change in delay; just memcpy ins to outs if(d_delta == 0) { for(size_t i = 0; i < input_items.size(); i++) { iptr = (const char *)input_items[i]; optr = (char *)output_items[i]; std::memcpy(optr, iptr, noutput_items*d_itemsize); } cons = noutput_items; ret = noutput_items; } // Skip over d_delta items on the input else if(d_delta < 0) { int n_to_copy, n_adj; int delta = -d_delta; n_to_copy = std::max(0, noutput_items-delta); n_adj = std::min(delta, noutput_items); for(size_t i = 0; i < input_items.size(); i++) { iptr = (const char *) input_items[i]; optr = (char *) output_items[i]; std::memcpy(optr, iptr+delta*d_itemsize, n_to_copy*d_itemsize); } cons = noutput_items; ret = n_to_copy; delta -= n_adj; d_delta = -delta; } //produce but not consume (inserts zeros) else { // d_delta > 0 int n_from_input, n_padding; n_from_input = std::max(0, noutput_items-d_delta); n_padding = std::min(d_delta, noutput_items); for(size_t i = 0; i < input_items.size(); i++) { iptr = (const char *) input_items[i]; optr = (char *) output_items[i]; std::memset(optr, 0, n_padding*d_itemsize); std::memcpy(optr, iptr, n_from_input*d_itemsize); } cons = n_from_input; ret = noutput_items; d_delta -= n_padding; } consume_each(cons); return ret; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/not_XX_impl.cc.t0000664000175000017500000000336112207440367020776 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, 1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; const @I_TYPE@ *inptr = (const @I_TYPE@ *) input_items[0]; int noi = noutput_items*d_vlen; for (int i = 0; i < noi; i++) *optr++ = ~(inptr[i]); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_i_impl.cc0000664000175000017500000001202412207702530022734 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe2_i_impl.h" #include namespace gr { namespace blocks { ctrlport_probe2_i::sptr ctrlport_probe2_i::make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) { return gnuradio::get_initial_sptr (new ctrlport_probe2_i_impl(id, desc, len, disp_mask)); } ctrlport_probe2_i_impl::ctrlport_probe2_i_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) : sync_block("probe2_i", io_signature::make(1, 1, sizeof(int)), io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_len(len), d_disp_mask(disp_mask) { set_length(len); } ctrlport_probe2_i_impl::~ctrlport_probe2_i_impl() { } void ctrlport_probe2_i_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = d_len; } // boost::shared_mutex mutex_buffer; // mutable boost::mutex mutex_notify; // boost::condition_variable condition_buffer_ready; std::vector ctrlport_probe2_i_impl::get() { mutex_buffer.lock(); d_buffer.clear(); mutex_buffer.unlock(); // wait for condition boost::mutex::scoped_lock lock(mutex_notify); condition_buffer_ready.wait(lock); mutex_buffer.lock(); std::vector buf_copy = d_buffer; assert(buf_copy.size() == d_len); mutex_buffer.unlock(); return buf_copy; } void ctrlport_probe2_i_impl::set_length(int len) { if(len > 8191) { std::cerr << "probe2_i: length " << len << " exceeds maximum buffer size of 8191" << std::endl; len = 8191; } d_len = len; d_buffer.reserve(d_len); } int ctrlport_probe2_i_impl::length() const { return (int)d_len; } int ctrlport_probe2_i_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const int *in = (const int*)input_items[0]; // copy samples to get buffer if we need samples mutex_buffer.lock(); if(d_buffer.size() < d_len) { // copy smaller of remaining buffer space and num inputs to work() int num_copy = std::min( (int)(d_len - d_buffer.size()), noutput_items ); // TODO: convert this to a copy operator for speed... for(int i = 0; i < num_copy; i++) { d_buffer.push_back(in[i]); } // notify the waiting get() if we fill up the buffer if(d_buffer.size() == d_len) { condition_buffer_ready.notify_one(); } } mutex_buffer.unlock(); return noutput_items; } void ctrlport_probe2_i_impl::setup_rpc() { #ifdef GR_CTRLPORT int len = static_cast(d_len); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), d_id.c_str(), &ctrlport_probe2_i::get, pmt::mp(-32768), pmt::mp(32767), pmt::mp(0), "volts", d_desc.c_str(), RPC_PRIVLVL_MIN, d_disp_mask))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "length", &ctrlport_probe2_i::length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "get vector length", RPC_PRIVLVL_MIN, DISPNULL))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "length", &ctrlport_probe2_i::set_length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "set vector length", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/divide_XX_impl.h.t0000664000175000017500000000243512207440367021305 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/stream_mux_impl.cc0000664000175000017500000000660112207440367021501 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "stream_mux_impl.h" #include #include #include #define VERBOSE 0 namespace gr { namespace blocks { stream_mux::sptr stream_mux::make(size_t itemsize, const std::vector &lengths) { return gnuradio::get_initial_sptr(new stream_mux_impl(itemsize, lengths)); } stream_mux_impl::stream_mux_impl(size_t itemsize, const std::vector &lengths) : block("stream_mux", io_signature::make (1, -1, itemsize), io_signature::make (1, 1, itemsize)), d_itemsize(itemsize), d_stream(0), d_residual(0), d_lengths(lengths) { if(d_lengths[d_stream] == 0) { increment_stream(); } d_residual = d_lengths[d_stream]; } void stream_mux_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size (); for (unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = (d_lengths[i] == 0 ? 0 : 1); } void stream_mux_impl::increment_stream() { do { d_stream = (d_stream+1) % d_lengths.size(); } while(d_lengths[d_stream] == 0); d_residual = d_lengths[d_stream]; } int stream_mux_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *out = (char *) output_items[0]; const char *in; int out_index = 0; std::vector input_index(d_lengths.size(), 0); if(VERBOSE) { printf("mux: nouput_items: %d d_stream: %d\n", noutput_items, d_stream); for(size_t i = 0; i < d_lengths.size(); i++) printf("\tninput_items[%zu]: %d\n", i, ninput_items[i]); } while (1) { int r = std::min(noutput_items - out_index, std::min(d_residual, ninput_items[d_stream] - input_index[d_stream])); if(VERBOSE) { printf("mux: r=%d\n", r); printf("\tnoutput_items - out_index: %d\n", noutput_items - out_index); printf("\td_residual: %d\n", d_residual); printf("\tninput_items[d_stream] - input_index[d_stream]: %d\n", ninput_items[d_stream] - input_index[d_stream]); } if(r <= 0) { return out_index; } in = (const char *) input_items[d_stream] + input_index[d_stream]*d_itemsize; memcpy(&out[out_index*d_itemsize], in, r*d_itemsize); out_index += r; input_index[d_stream] += r; d_residual -= r; consume(d_stream, r); if(d_residual == 0) { increment_stream(); } } } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/float_array_to_int.cc0000664000175000017500000000253012207440367022150 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #define _ISOC9X_SOURCE #include #include #include static const int64_t MAX_INT = 2147483647; // (2^31)-1 static const int64_t MIN_INT = -2147483647; // -(2^31)-1 void float_array_to_int(const float *in, int *out, float scale, int nsamples) { for (int i = 0; i < nsamples; i++){ int64_t r = llrintf(scale * in[i]); if (r < MIN_INT) r = MIN_INT; else if (r > MAX_INT) r = MAX_INT; out[i] = static_cast(r); } } gnuradio-3.7.2.1/gr-blocks/lib/sample_and_hold_XX_impl.h.t0000664000175000017500000000246512207440367023155 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: @O_TYPE@ d_data; public: @NAME_IMPL@(); ~@NAME_IMPL@(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/file_sink_impl.cc0000664000175000017500000000504612237515111021253 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_sink_impl.h" #include #include namespace gr { namespace blocks { file_sink::sptr file_sink::make(size_t itemsize, const char *filename, bool append) { return gnuradio::get_initial_sptr (new file_sink_impl(itemsize, filename, append)); } file_sink_impl::file_sink_impl(size_t itemsize, const char *filename, bool append) : sync_block("file_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), file_sink_base(filename, true, append), d_itemsize(itemsize) { } file_sink_impl::~file_sink_impl() { } int file_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *inbuf = (char*)input_items[0]; int nwritten = 0; do_update(); // update d_fp is reqd if(!d_fp) return noutput_items; // drop output on the floor while(nwritten < noutput_items) { int count = fwrite(inbuf, d_itemsize, noutput_items - nwritten, d_fp); if(count == 0) { if(ferror(d_fp)) { std::stringstream s; s << "file_sink write failed with error " << fileno(d_fp) << std::endl; throw std::runtime_error(s.str()); } else { // is EOF break; } } nwritten += count; inbuf += count * d_itemsize; } if(d_unbuffered) fflush (d_fp); return nwritten; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/int_to_float_impl.h0000664000175000017500000000273212207440367021641 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_INT_TO_FLOAT_IMPL_H #define INCLUDED_INT_TO_FLOAT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API int_to_float_impl : public int_to_float { size_t d_vlen; float d_scale; public: int_to_float_impl(size_t vlen, float scale); virtual float scale() const { return d_scale; } virtual void set_scale(float scale) { d_scale = scale; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_INT_TO_FLOAT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/uchar_array_to_float.h0000664000175000017500000000215412207440367022324 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005, 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_UCHAR_ARRAY_TO_FLOAT_H #define INCLUDED_UCHAR_ARRAY_TO_FLOAT_H #include /* * convert array of unsigned chars to floats */ BLOCKS_API void uchar_array_to_float (const unsigned char *in, float *out, int nsamples); #endif /* INCLUDED_UCHAR_ARRAY_TO_FLOAT_H */ gnuradio-3.7.2.1/gr-blocks/lib/skiphead_impl.h0000664000175000017500000000300412207440367020741 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_SKIPHEAD_IMPL_H #define INCLUDED_GR_SKIPHEAD_IMPL_H #include namespace gr { namespace blocks { class skiphead_impl : public skiphead { private: uint64_t d_nitems_to_skip; uint64_t d_nitems; // total items seen public: skiphead_impl(size_t itemsize, uint64_t nitems_to_skip); ~skiphead_impl(); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_SKIPHEAD_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/rms_cf_impl.cc0000664000175000017500000000412312207440367020563 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "rms_cf_impl.h" #include #include namespace gr { namespace blocks { rms_cf::sptr rms_cf::make(double alpha) { return gnuradio::get_initial_sptr (new rms_cf_impl(alpha)); } rms_cf_impl::rms_cf_impl(double alpha) : sync_block("rms_cf", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(1, 1, sizeof(float))) { set_alpha(alpha); } rms_cf_impl::~rms_cf_impl() { } void rms_cf_impl::set_alpha(double alpha) { d_alpha = alpha; d_beta = 1 - d_alpha; d_avg = 0; } int rms_cf_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *)input_items[0]; float *out = (float *)output_items[0]; for(int i = 0; i < noutput_items; i++) { double mag_sqrd = in[i].real()*in[i].real() + in[i].imag()*in[i].imag(); d_avg = d_beta*d_avg + d_alpha*mag_sqrd; out[i] = sqrt(d_avg); } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/add_const_vXX_impl.cc.t0000664000175000017500000000361112207440367022320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(std::vector<@O_TYPE@> k) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(k)); } @NAME_IMPL@::@NAME_IMPL@(std::vector<@O_TYPE@> k) : sync_block ("@NAME@", io_signature::make (1, 1, sizeof (@I_TYPE@)*k.size()), io_signature::make (1, 1, sizeof (@O_TYPE@)*k.size())), d_k(k) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *)input_items[0]; @O_TYPE@ *optr = (@O_TYPE@ *)output_items[0]; int nitems_per_block = output_signature()->sizeof_stream_item(0)/sizeof(@I_TYPE@); for (int i = 0; i < noutput_items; i++) for (int j = 0; j < nitems_per_block; j++) *optr++ = *iptr++ + d_k[j]; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/skiphead_impl.cc0000664000175000017500000000547612207440367021116 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "skiphead_impl.h" #include #include namespace gr { namespace blocks { skiphead::sptr skiphead::make(size_t itemsize, uint64_t nitems_to_skip) { return gnuradio::get_initial_sptr (new skiphead_impl(itemsize, nitems_to_skip)); } skiphead_impl::skiphead_impl(size_t itemsize, uint64_t nitems_to_skip) : block("skiphead", io_signature::make(1, 1, itemsize), io_signature::make(1, 1, itemsize)), d_nitems_to_skip(nitems_to_skip), d_nitems(0) { } skiphead_impl::~skiphead_impl() { } int skiphead_impl::general_work(int noutput_items, gr_vector_int &ninput_items_, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char*)input_items[0]; char *out = (char*)output_items[0]; int ninput_items = std::min(ninput_items_[0], noutput_items); int ii = 0; // input index while (ii < ninput_items) { uint64_t ni_total = ii + d_nitems; // total items processed so far if(ni_total < d_nitems_to_skip) { // need to skip some more int n_to_skip = (int)std::min(d_nitems_to_skip - ni_total, (uint64_t)(ninput_items - ii)); ii += n_to_skip; } else { // nothing left to skip. copy away int n_to_copy = ninput_items - ii; if(n_to_copy > 0) { size_t itemsize = output_signature()->sizeof_stream_item(0); memcpy(out, in + (ii*itemsize), n_to_copy*itemsize); } d_nitems += ninput_items; consume_each(ninput_items); return n_to_copy; } } d_nitems += ninput_items; consume_each(ninput_items); return 0; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/uchar_to_float_impl.cc0000664000175000017500000000335012207440367022304 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "uchar_to_float_impl.h" #include "uchar_array_to_float.h" #include namespace gr { namespace blocks { uchar_to_float::sptr uchar_to_float::make() { return gnuradio::get_initial_sptr(new uchar_to_float_impl()); } uchar_to_float_impl::uchar_to_float_impl() : sync_block("uchar_to_float", io_signature::make (1, 1, sizeof(unsigned char)), io_signature::make (1, 1, sizeof(float))) { } int uchar_to_float_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; float *out = (float *) output_items[0]; uchar_array_to_float (in, out, noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/short_to_float_impl.h0000664000175000017500000000275012207440367022206 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_SHORT_TO_FLOAT_IMPL_H #define INCLUDED_SHORT_TO_FLOAT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API short_to_float_impl : public short_to_float { size_t d_vlen; float d_scale; public: short_to_float_impl(size_t vlen, float scale); virtual float scale() const { return d_scale; } virtual void set_scale(float scale) { d_scale = scale; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_SHORT_TO_FLOAT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/stretch_ff_impl.cc0000664000175000017500000000450212207440367021442 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "stretch_ff_impl.h" #include namespace gr { namespace blocks { stretch_ff::sptr stretch_ff::make(float lo, size_t vlen) { return gnuradio::get_initial_sptr (new stretch_ff_impl(lo, vlen)); } stretch_ff_impl::stretch_ff_impl(float lo, size_t vlen) : sync_block("stretch_ff", io_signature::make(1, 1, vlen * sizeof(float)), io_signature::make(1, 1, vlen * sizeof(float))), d_lo(lo), d_vlen(vlen) { } stretch_ff_impl::~stretch_ff_impl() { } int stretch_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; float *out = (float *)output_items[0]; for(int count = 0; count < noutput_items; count++) { float vmax = in[0] - d_lo; for(unsigned int i = 1; i < d_vlen; i++) { float vtmp = in[i] - d_lo; if(vtmp > vmax) vmax = vtmp; } if(vmax != 0.0) for(unsigned int i = 0; i < d_vlen; i++) out[i] = d_lo * (1.0 - (in[i] - d_lo) / vmax); else for(unsigned int i = 0; i < d_vlen; i++) out[i] = in[i]; in += d_vlen; out += d_vlen; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/pack_k_bits_bb_impl.cc0000664000175000017500000000427112207440367022232 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #if HAVE_CONFIG_H #include "config.h" #endif #include "pack_k_bits_bb_impl.h" #include #include #include namespace gr { namespace blocks { pack_k_bits_bb::sptr pack_k_bits_bb::make(unsigned k) { return gnuradio::get_initial_sptr (new pack_k_bits_bb_impl(k)); } pack_k_bits_bb_impl::pack_k_bits_bb_impl(unsigned k) : sync_decimator("pack_k_bits_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char)), k), d_k(k) { if(d_k == 0) throw std::out_of_range("interpolation must be > 0"); } pack_k_bits_bb_impl::~pack_k_bits_bb_impl() { } int pack_k_bits_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = 0x00; for(unsigned int j = 0; j < d_k; j++) { out[i] |= (0x01 & in[i*d_k+j])<<(d_k-j-1); } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/char_to_float_impl.cc0000664000175000017500000000377112207440367022126 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "char_to_float_impl.h" #include #include namespace gr { namespace blocks { char_to_float::sptr char_to_float::make(size_t vlen, float scale) { return gnuradio::get_initial_sptr(new char_to_float_impl(vlen, scale)); } char_to_float_impl::char_to_float_impl(size_t vlen, float scale) : sync_block("char_to_float", io_signature::make (1, -1, sizeof(char)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen), d_scale(scale) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } int char_to_float_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const int8_t *in = (const int8_t *) input_items[0]; float *out = (float *) output_items[0]; // Note: the unaligned benchmarked much faster than the aligned volk_8i_s32f_convert_32f_u(out, in, d_scale, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_b_impl.h0000664000175000017500000000402412207702530022570 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_B_IMPL_H #define INCLUDED_CTRLPORT_PROBE2_B_IMPL_H #include #include #include namespace gr { namespace blocks { class ctrlport_probe2_b_impl : public ctrlport_probe2_b { private: std::string d_id; std::string d_desc; size_t d_len; unsigned int d_disp_mask; boost::shared_mutex mutex_buffer; mutable boost::mutex mutex_notify; boost::condition_variable condition_buffer_ready; std::vector d_buffer; public: ctrlport_probe2_b_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); ~ctrlport_probe2_b_impl(); void setup_rpc(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); std::vector get(); void set_length(int len); int length() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_C_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_i_impl.h0000664000175000017500000000400412207702530022575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_I_IMPL_H #define INCLUDED_CTRLPORT_PROBE2_I_IMPL_H #include #include #include namespace gr { namespace blocks { class ctrlport_probe2_i_impl : public ctrlport_probe2_i { private: std::string d_id; std::string d_desc; size_t d_len; unsigned int d_disp_mask; boost::shared_mutex mutex_buffer; mutable boost::mutex mutex_notify; boost::condition_variable condition_buffer_ready; std::vector d_buffer; public: ctrlport_probe2_i_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); ~ctrlport_probe2_i_impl(); void setup_rpc(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); std::vector get(); void set_length(int len); int length() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_I_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/regenerate_bb_impl.h0000664000175000017500000000326312207440367021744 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_REGENERATE_BB_H #define INCLUDED_GR_REGENERATE_BB_IMPL_H #include namespace gr { namespace blocks { class regenerate_bb_impl : public regenerate_bb { private: int d_period; int d_countdown; unsigned int d_max_regen; unsigned int d_regen_count; public: regenerate_bb_impl(int period, unsigned int max_regen=500); ~regenerate_bb_impl(); void set_max_regen(unsigned int regen); void set_period(int period); unsigned int max_regen() const { return d_max_regen; }; int period() const { return d_period; }; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_REGENERATE_BB_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/random_pdu_impl.cc0000664000175000017500000000431612207440367021446 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "random_pdu_impl.h" #include #include namespace gr { namespace blocks { random_pdu::sptr random_pdu::make(int min_items, int max_items) { return gnuradio::get_initial_sptr(new random_pdu_impl(min_items, max_items)); } random_pdu_impl::random_pdu_impl(int min_items, int max_items) : block("random_pdu", io_signature::make (0, 0, 0), io_signature::make (0, 0, 0)), d_urange(min_items, max_items), d_brange(0, 255), d_rvar(d_rng, d_urange), d_bvar(d_rng, d_brange) { message_port_register_out(PDU_PORT_ID); message_port_register_in(pmt::mp("generate")); set_msg_handler(pmt::mp("generate"), boost::bind(&random_pdu_impl::generate_pdu, this, _1)); } bool random_pdu_impl::start() { output_random(); return true; } void random_pdu_impl::output_random() { // pick a random vector length int len = d_rvar(); // fill it with random bytes std::vector vec; for (int i=0; i namespace gr { namespace blocks { class BLOCKS_API float_to_int_impl : public float_to_int { size_t d_vlen; float d_scale; public: float_to_int_impl(size_t vlen, float scale); virtual float scale() const { return d_scale; } virtual void set_scale(float scale) { d_scale = scale; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_FLOAT_TO_INT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/patterned_interleaver_impl.cc0000664000175000017500000000553012207440367023703 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "patterned_interleaver_impl.h" #include namespace gr { namespace blocks { patterned_interleaver::sptr patterned_interleaver::make(size_t itemsize, std::vector pattern) { return gnuradio::get_initial_sptr(new patterned_interleaver_impl(itemsize, pattern)); } patterned_interleaver_impl::patterned_interleaver_impl(size_t itemsize, std::vector pattern) : block ("patterned_interleaver", io_signature::make (pattern_max(pattern)+1, pattern_max(pattern)+1, itemsize), io_signature::make (1, 1, itemsize)), d_pattern(pattern), d_counts( pattern_max(pattern)+1, 0), d_itemsize(itemsize) { BOOST_FOREACH( int i, d_pattern) { d_counts[i]++; } set_output_multiple(d_pattern.size()); } int patterned_interleaver_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t nblks = noutput_items/d_pattern.size(); std::vector ii; for(size_t i=0; i #include #include namespace gr { namespace blocks { class ctrlport_probe2_f_impl : public ctrlport_probe2_f { private: std::string d_id; std::string d_desc; size_t d_len; unsigned int d_disp_mask; boost::shared_mutex mutex_buffer; mutable boost::mutex mutex_notify; boost::condition_variable condition_buffer_ready; std::vector d_buffer; public: ctrlport_probe2_f_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); ~ctrlport_probe2_f_impl(); void setup_rpc(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); std::vector get(); void set_length(int len); int length() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_F_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_complex_impl.cc0000664000175000017500000000424112207440367022651 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "float_to_complex_impl.h" #include #include namespace gr { namespace blocks { float_to_complex::sptr float_to_complex::make(size_t vlen) { return gnuradio::get_initial_sptr(new float_to_complex_impl(vlen)); } float_to_complex_impl::float_to_complex_impl(size_t vlen) : sync_block("float_to_complex", io_signature::make (1, 2, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(gr_complex)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int float_to_complex_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *r = (float *)input_items[0]; float *i = (float *)input_items[1]; gr_complex *out = (gr_complex *) output_items[0]; switch (input_items.size ()){ case 1: for (size_t j = 0; j < noutput_items*d_vlen; j++) out[j] = gr_complex (r[j], 0); break; case 2: for (size_t j = 0; j < noutput_items*d_vlen; j++) out[j] = gr_complex (r[j], i[j]); break; default: assert (0); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/qa_block_tags.cc0000664000175000017500000004763712207440367021103 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include // ---------------------------------------------------------------- // set to 1 to turn on debug output // The debug output fully checks that the tags seen are what are expected. While // this behavior currently works with our implementation, there is no guarentee // that the tags will be coming in this specific order, so it's dangerous to // rely on this as a test of the tag system working. We would really want to // tags we know we should see and then test that they all occur once, but in no // particular order. #define QA_TAGS_DEBUG 0 void qa_block_tags::t0() { unsigned int N = 1000; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(int))); gr::block_sptr head (gr::blocks::head::make(sizeof(int), N)); gr::block_sptr snk (gr::blocks::null_sink::make(sizeof(int))); tb->connect(src, 0, head, 0); tb->connect(head, 0, snk, 0); //CPPUNIT_ASSERT_THROW(src->nitems_read(0), std::runtime_error); //CPPUNIT_ASSERT_THROW(src->nitems_written(0), std::runtime_error); CPPUNIT_ASSERT_EQUAL(src->nitems_read(0), (uint64_t)0); CPPUNIT_ASSERT_EQUAL(src->nitems_written(0), (uint64_t)0); tb->run(); CPPUNIT_ASSERT_THROW(src->nitems_read(0), std::invalid_argument); CPPUNIT_ASSERT(src->nitems_written(0) >= N); CPPUNIT_ASSERT_EQUAL(snk->nitems_read(0), (uint64_t)1000); CPPUNIT_ASSERT_THROW(snk->nitems_written(0), std::invalid_argument); } void qa_block_tags::t1() { int N = 40000; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(int))); gr::block_sptr head (gr::blocks::head::make(sizeof(int), N)); gr::blocks::annotator_alltoall::sptr ann0(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann1(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann2(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann3(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann4(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::block_sptr snk0 (gr::blocks::null_sink::make(sizeof(int))); gr::block_sptr snk1 (gr::blocks::null_sink::make(sizeof(int))); tb->connect(src, 0, head, 0); tb->connect(head, 0, ann0, 0); tb->connect(ann0, 0, ann1, 0); tb->connect(ann0, 1, ann2, 0); tb->connect(ann1, 0, ann3, 0); tb->connect(ann2, 0, ann4, 0); tb->connect(ann3, 0, snk0, 0); tb->connect(ann4, 0, snk1, 0); tb->run(); std::vector tags0 = ann0->data(); std::vector tags3 = ann3->data(); std::vector tags4 = ann4->data(); // The first annotator does not receive any tags from the null sink upstream CPPUNIT_ASSERT_EQUAL(tags0.size(), (size_t)0); CPPUNIT_ASSERT_EQUAL(tags3.size(), (size_t)8); CPPUNIT_ASSERT_EQUAL(tags4.size(), (size_t)8); #if QA_TAGS_DEBUG // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1, str2; str0 << ann0->name() << ann0->unique_id(); str1 << ann1->name() << ann1->unique_id(); str2 << ann2->name() << ann2->unique_id(); pmt::pmt_t expected_tags3[8]; expected_tags3[0] = mp(pmt::from_uint64(0), mp(str1.str()), mp("seq"), mp(0)); expected_tags3[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(0)); expected_tags3[2] = mp(pmt::from_uint64(10000), mp(str1.str()), mp("seq"), mp(1)); expected_tags3[3] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(2)); expected_tags3[4] = mp(pmt::from_uint64(20000), mp(str1.str()), mp("seq"), mp(2)); expected_tags3[5] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(4)); expected_tags3[6] = mp(pmt::from_uint64(30000), mp(str1.str()), mp("seq"), mp(3)); expected_tags3[7] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(6)); pmt::pmt_t expected_tags4[8]; expected_tags4[0] = mp(pmt::from_uint64(0), mp(str2.str()), mp("seq"), mp(0)); expected_tags4[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(1)); expected_tags4[2] = mp(pmt::from_uint64(10000), mp(str2.str()), mp("seq"), mp(1)); expected_tags4[3] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(3)); expected_tags4[4] = mp(pmt::from_uint64(20000), mp(str2.str()), mp("seq"), mp(2)); expected_tags4[5] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(5)); expected_tags4[6] = mp(pmt::from_uint64(30000), mp(str2.str()), mp("seq"), mp(3)); expected_tags4[7] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(7)); std::cout << std::endl << "qa_block_tags::t1" << std::endl; // For annotator 3, we know it gets tags from ann0 and ann1, test this for(size_t i = 0; i < tags3.size(); i++) { std::cout << "tags3[" << i << "] = " << tags3[i] << "\t\t" << expected_tags3[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags3[i]), pmt::write_string(expected_tags3[i])); } // For annotator 4, we know it gets tags from ann0 and ann2, test this std::cout << std::endl; for(size_t i = 0; i < tags4.size(); i++) { std::cout << "tags4[" << i << "] = " << tags4[i] << "\t\t" << expected_tags4[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags4[i]), pmt::write_string(expected_tags4[i])); } #endif } void qa_block_tags::t2 () { int N = 40000; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(int))); gr::block_sptr head (gr::blocks::head::make(sizeof(int), N)); gr::blocks::annotator_alltoall::sptr ann0(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann1(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann2(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann3(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann4(gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::block_sptr snk0 (gr::blocks::null_sink::make(sizeof(int))); gr::block_sptr snk1 (gr::blocks::null_sink::make(sizeof(int))); gr::block_sptr snk2 (gr::blocks::null_sink::make(sizeof(int))); tb->connect(src, 0, head, 0); tb->connect(head, 0, ann0, 0); tb->connect(ann0, 0, ann1, 0); tb->connect(ann0, 1, ann1, 1); tb->connect(ann1, 0, ann2, 0); tb->connect(ann1, 1, ann3, 0); tb->connect(ann1, 2, ann4, 0); tb->connect(ann2, 0, snk0, 0); tb->connect(ann3, 0, snk1, 0); tb->connect(ann4, 0, snk2, 0); tb->run(); std::vector tags0 = ann0->data(); std::vector tags1 = ann1->data(); std::vector tags2 = ann2->data(); std::vector tags3 = ann4->data(); std::vector tags4 = ann4->data(); // The first annotator does not receive any tags from the null sink upstream CPPUNIT_ASSERT_EQUAL(tags0.size(), (size_t)0); CPPUNIT_ASSERT_EQUAL(tags1.size(), (size_t)8); // Make sure the rest all have 12 tags CPPUNIT_ASSERT_EQUAL(tags2.size(), (size_t)12); CPPUNIT_ASSERT_EQUAL(tags3.size(), (size_t)12); CPPUNIT_ASSERT_EQUAL(tags4.size(), (size_t)12); #if QA_TAGS_DEBUG // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1; str0 << ann0->name() << ann0->unique_id(); str1 << ann1->name() << ann1->unique_id(); pmt::pmt_t expected_tags2[12]; expected_tags2[0] = mp(pmt::from_uint64(0), mp(str1.str()), mp("seq"), mp(0)); expected_tags2[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(0)); expected_tags2[2] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(1)); expected_tags2[3] = mp(pmt::from_uint64(10000), mp(str1.str()), mp("seq"), mp(3)); expected_tags2[4] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(2)); expected_tags2[5] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(3)); expected_tags2[6] = mp(pmt::from_uint64(20000), mp(str1.str()), mp("seq"), mp(6)); expected_tags2[7] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(4)); expected_tags2[8] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(5)); expected_tags2[9] = mp(pmt::from_uint64(30000), mp(str1.str()), mp("seq"), mp(9)); expected_tags2[10] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(6)); expected_tags2[11] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(7)); pmt::pmt_t expected_tags4[12]; expected_tags4[0] = mp(pmt::from_uint64(0), mp(str1.str()), mp("seq"), mp(2)); expected_tags4[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(0)); expected_tags4[2] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(1)); expected_tags4[3] = mp(pmt::from_uint64(10000), mp(str1.str()), mp("seq"), mp(5)); expected_tags4[4] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(2)); expected_tags4[5] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(3)); expected_tags4[6] = mp(pmt::from_uint64(20000), mp(str1.str()), mp("seq"), mp(8)); expected_tags4[7] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(4)); expected_tags4[8] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(5)); expected_tags4[9] = mp(pmt::from_uint64(30000), mp(str1.str()), mp("seq"), mp(11)); expected_tags4[10] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(6)); expected_tags4[11] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(7)); std::cout << std::endl << "qa_block_tags::t2" << std::endl; // For annotator[2-4], we know it gets tags from ann0 and ann1 // but the tags from the different outputs of ann1 are different for each. // Just testing ann2 and ann4; if they are correct it would be // inconceivable for ann3 to have it wrong. for(size_t i = 0; i < tags2.size(); i++) { std::cout << "tags2[" << i << "] = " << tags2[i] << "\t\t" << expected_tags2[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags2[i]), pmt::write_string(expected_tags2[i])); } std::cout << std::endl; for(size_t i = 0; i < tags4.size(); i++) { std::cout << "tags2[" << i << "] = " << tags4[i] << "\t\t" << expected_tags4[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags4[i]), pmt::write_string(expected_tags4[i])); } #endif } void qa_block_tags::t3() { int N = 40000; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(int))); gr::block_sptr head (gr::blocks::head::make(sizeof(int), N)); gr::blocks::annotator_1to1::sptr ann0 (gr::blocks::annotator_1to1::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann1 (gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_alltoall::sptr ann2 (gr::blocks::annotator_alltoall::make(10000, sizeof(int))); gr::blocks::annotator_1to1::sptr ann3 (gr::blocks::annotator_1to1::make(10000, sizeof(int))); gr::blocks::annotator_1to1::sptr ann4 (gr::blocks::annotator_1to1::make(10000, sizeof(int))); gr::block_sptr snk0 (gr::blocks::null_sink::make(sizeof(int))); gr::block_sptr snk1 (gr::blocks::null_sink::make(sizeof(int))); tb->connect(src, 0, head, 0); tb->connect(head, 0, ann0, 0); tb->connect(head, 0, ann0, 1); tb->connect(ann0, 0, ann1, 0); tb->connect(ann0, 1, ann2, 0); tb->connect(ann1, 0, ann3, 0); tb->connect(ann2, 0, ann4, 0); tb->connect(ann3, 0, snk0, 0); tb->connect(ann4, 0, snk1, 0); tb->run(); std::vector tags0 = ann0->data(); std::vector tags3 = ann3->data(); std::vector tags4 = ann4->data(); // The first annotator does not receive any tags from the null sink upstream CPPUNIT_ASSERT_EQUAL(tags0.size(), (size_t)0); CPPUNIT_ASSERT_EQUAL(tags3.size(), (size_t)8); CPPUNIT_ASSERT_EQUAL(tags4.size(), (size_t)8); #if QA_TAGS_DEBUG // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1, str2; str0 << ann0->name() << ann0->unique_id(); str1 << ann1->name() << ann1->unique_id(); str2 << ann2->name() << ann2->unique_id(); pmt::pmt_t expected_tags3[8]; expected_tags3[0] = mp(pmt::from_uint64(0), mp(str1.str()), mp("seq"), mp(0)); expected_tags3[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(0)); expected_tags3[2] = mp(pmt::from_uint64(10000), mp(str1.str()), mp("seq"), mp(1)); expected_tags3[3] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(2)); expected_tags3[4] = mp(pmt::from_uint64(20000), mp(str1.str()), mp("seq"), mp(2)); expected_tags3[5] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(4)); expected_tags3[6] = mp(pmt::from_uint64(30000), mp(str1.str()), mp("seq"), mp(3)); expected_tags3[7] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(6)); pmt::pmt_t expected_tags4[8]; expected_tags4[0] = mp(pmt::from_uint64(0), mp(str2.str()), mp("seq"), mp(0)); expected_tags4[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(1)); expected_tags4[2] = mp(pmt::from_uint64(10000), mp(str2.str()), mp("seq"), mp(1)); expected_tags4[3] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(3)); expected_tags4[4] = mp(pmt::from_uint64(20000), mp(str2.str()), mp("seq"), mp(2)); expected_tags4[5] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(5)); expected_tags4[6] = mp(pmt::from_uint64(30000), mp(str2.str()), mp("seq"), mp(3)); expected_tags4[7] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(7)); std::cout << std::endl << "qa_block_tags::t3" << std::endl; // For annotator 3, we know it gets tags from ann0 and ann1, test this for(size_t i = 0; i < tags3.size(); i++) { std::cout << "tags3[" << i << "] = " << tags3[i] << "\t\t" << expected_tags3[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags3[i]), pmt::write_string(expected_tags3[i])); } // For annotator 4, we know it gets tags from ann0 and ann2, test this std::cout << std::endl; for(size_t i = 0; i < tags4.size(); i++) { std::cout << "tags4[" << i << "] = " << tags4[i] << "\t\t" << expected_tags4[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags4[i]), pmt::write_string(expected_tags4[i])); } #endif } void qa_block_tags::t4() { int N = 40000; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(int))); gr::block_sptr head (gr::blocks::head::make(sizeof(int), N)); gr::blocks::annotator_1to1::sptr ann0(gr::blocks::annotator_1to1::make(10000, sizeof(int))); gr::blocks::annotator_1to1::sptr ann1(gr::blocks::annotator_1to1::make(10000, sizeof(int))); gr::blocks::annotator_1to1::sptr ann2(gr::blocks::annotator_1to1::make(10000, sizeof(int))); gr::block_sptr snk0 (gr::blocks::null_sink::make(sizeof(int))); gr::block_sptr snk1 (gr::blocks::null_sink::make(sizeof(int))); // using 1-to-1 tag propagation without having equal number of // ins and outs. Make sure this works; will just exit run early. tb->connect(src, 0, head, 0); tb->connect(head, 0, ann0, 0); tb->connect(ann0, 0, ann1, 0); tb->connect(ann0, 1, ann2, 0); tb->connect(ann1, 0, snk0, 0); tb->connect(ann2, 0, snk1, 0); std::cerr << std::endl << "NOTE: This is supposed to produce an error from block_executor" << std::endl; tb->run(); } void qa_block_tags::t5() { int N = 40000; gr::top_block_sptr tb = gr::make_top_block("top"); gr::block_sptr src (gr::blocks::null_source::make(sizeof(float))); gr::block_sptr head (gr::blocks::head::make(sizeof(float), N)); gr::blocks::annotator_alltoall::sptr ann0(gr::blocks::annotator_alltoall::make(10000, sizeof(float))); gr::blocks::annotator_alltoall::sptr ann1(gr::blocks::annotator_alltoall::make(10000, sizeof(float))); gr::blocks::annotator_alltoall::sptr ann2(gr::blocks::annotator_alltoall::make(1000, sizeof(float))); gr::block_sptr snk0 (gr::blocks::null_sink::make(sizeof(float))); // Rate change blocks gr::blocks::keep_one_in_n::sptr dec10(gr::blocks::keep_one_in_n::make(sizeof(float), 10)); tb->connect(src, 0, head, 0); tb->connect(head, 0, ann0, 0); tb->connect(ann0, 0, ann1, 0); tb->connect(ann1, 0, dec10, 0); tb->connect(dec10, 0, ann2, 0); tb->connect(ann2, 0, snk0, 0); tb->run(); std::vector tags0 = ann0->data(); std::vector tags1 = ann1->data(); std::vector tags2 = ann2->data(); // The first annotator does not receive any tags from the null sink upstream CPPUNIT_ASSERT_EQUAL(tags0.size(), (size_t)0); CPPUNIT_ASSERT_EQUAL(tags1.size(), (size_t)4); CPPUNIT_ASSERT_EQUAL(tags2.size(), (size_t)8); #if QA_TAGS_DEBUG // Kludge together the tags that we know should result from the above graph std::stringstream str0, str1, str2; str0 << ann0->name() << ann0->unique_id(); str1 << ann1->name() << ann1->unique_id(); str2 << ann2->name() << ann2->unique_id(); pmt_t expected_tags1[5]; expected_tags1[0] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(0)); expected_tags1[1] = mp(pmt::from_uint64(10000), mp(str0.str()), mp("seq"), mp(1)); expected_tags1[2] = mp(pmt::from_uint64(20000), mp(str0.str()), mp("seq"), mp(2)); expected_tags1[3] = mp(pmt::from_uint64(30000), mp(str0.str()), mp("seq"), mp(3)); pmt_t expected_tags2[10]; expected_tags2[0] = mp(pmt::from_uint64(0), mp(str1.str()), mp("seq"), mp(0)); expected_tags2[1] = mp(pmt::from_uint64(0), mp(str0.str()), mp("seq"), mp(0)); expected_tags2[2] = mp(pmt::from_uint64(1000), mp(str1.str()), mp("seq"), mp(1)); expected_tags2[3] = mp(pmt::from_uint64(1000), mp(str0.str()), mp("seq"), mp(1)); expected_tags2[4] = mp(pmt::from_uint64(2000), mp(str1.str()), mp("seq"), mp(2)); expected_tags2[5] = mp(pmt::from_uint64(2000), mp(str0.str()), mp("seq"), mp(2)); expected_tags2[6] = mp(pmt::from_uint64(3000), mp(str1.str()), mp("seq"), mp(3)); expected_tags2[7] = mp(pmt::from_uint64(3000), mp(str0.str()), mp("seq"), mp(3)); expected_tags2[8] = mp(pmt::from_uint64(4000), mp(str1.str()), mp("seq"), mp(4)); expected_tags2[9] = mp(pmt::from_uint64(4000), mp(str0.str()), mp("seq"), mp(4)); std::cout << std::endl << "qa_block_tags::t5" << std::endl; // annotator 1 gets tags from annotator 0 std::cout << "tags1.size(): " << tags1.size() << std::endl; for(size_t i = 0; i < tags1.size(); i++) { std::cout << "tags1[" << i << "] = " << tags1[i] << "\t\t" << expected_tags1[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags1[i]), pmt::write_string(expected_tags1[i])); } // annotator 2 gets tags from annotators 0 and 1 std::cout << std::endl; std::cout << "tags2.size(): " << tags2.size() << std::endl; for(size_t i = 0; i < tags2.size(); i++) { std::cout << "tags2[" << i << "] = " << tags2[i] << "\t\t" << expected_tags2[i] << std::endl; CPPUNIT_ASSERT_EQUAL(pmt::write_string(tags2[i]), pmt::write_string(expected_tags2[i])); } #endif } gnuradio-3.7.2.1/gr-blocks/lib/regenerate_bb_impl.cc0000664000175000017500000000523212207440367022100 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "regenerate_bb_impl.h" #include namespace gr { namespace blocks { regenerate_bb::sptr regenerate_bb::make(int period, unsigned int max_regen) { return gnuradio::get_initial_sptr (new regenerate_bb_impl(period, max_regen)); } regenerate_bb_impl::regenerate_bb_impl(int period, unsigned int max_regen) : sync_block("regenerate_bb", io_signature::make(1, 1, sizeof(char)), io_signature::make(1, 1, sizeof(char))), d_period(period), d_countdown(0), d_max_regen(max_regen), d_regen_count(max_regen) { } regenerate_bb_impl::~regenerate_bb_impl() { } void regenerate_bb_impl::set_max_regen(unsigned int regen) { d_max_regen = regen; d_countdown = 0; d_regen_count = d_max_regen; } void regenerate_bb_impl::set_period(int period) { d_period = period; d_countdown = 0; d_regen_count = d_max_regen; } int regenerate_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *iptr = (const char *)input_items[0]; char *optr = (char *)output_items[0]; for(int i = 0; i < noutput_items; i++) { optr[i] = 0; if(d_regen_count < d_max_regen) { d_countdown--; if(d_countdown == 0) { optr[i] = 1; d_countdown = d_period; d_regen_count++; } } if(iptr[i] == 1) { d_countdown = d_period; optr[i] = 1; d_regen_count = 0; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/float_array_to_uchar.cc0000664000175000017500000000241612207440367022463 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #define _ISOC9X_SOURCE #include #include static const int MIN_UCHAR = 0; static const int MAX_UCHAR = 255; void float_array_to_uchar(const float *in, unsigned char *out, int nsamples) { for (int i = 0; i < nsamples; i++){ long int r = (long int) rint (in[i]); if (r < MIN_UCHAR) r = MIN_UCHAR; else if (r > MAX_UCHAR) r = MAX_UCHAR; out[i] = r; } } gnuradio-3.7.2.1/gr-blocks/lib/and_const_XX_impl.h.t0000664000175000017500000000254512207440367022013 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { @O_TYPE@ d_k; public: @NAME_IMPL@(@O_TYPE@ k); @O_TYPE@ k() const { return d_k; } void set_k(@O_TYPE@ k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/control_loop.cc0000664000175000017500000001122412243165260020776 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace blocks { #define M_TWOPI (2.0f*M_PI) control_loop::control_loop(float loop_bw, float max_freq, float min_freq) : d_phase(0), d_freq(0), d_max_freq(max_freq), d_min_freq(min_freq) { // Set the damping factor for a critically damped system d_damping = sqrtf(2.0f)/2.0f; // Set the bandwidth, which will then call update_gains() set_loop_bandwidth(loop_bw); } control_loop::~control_loop() { } void control_loop::update_gains() { float denom = (1.0 + 2.0*d_damping*d_loop_bw + d_loop_bw*d_loop_bw); d_alpha = (4*d_damping*d_loop_bw) / denom; d_beta = (4*d_loop_bw*d_loop_bw) / denom; } void control_loop::advance_loop(float error) { d_freq = d_freq + d_beta * error; d_phase = d_phase + d_freq + d_alpha * error; } void control_loop::phase_wrap() { while(d_phase>M_TWOPI) d_phase -= M_TWOPI; while(d_phase<-M_TWOPI) d_phase += M_TWOPI; } void control_loop::frequency_limit() { if(d_freq > d_max_freq) d_freq = d_max_freq; else if(d_freq < d_min_freq) d_freq = d_min_freq; } /******************************************************************* * SET FUNCTIONS *******************************************************************/ void control_loop::set_loop_bandwidth(float bw) { if(bw < 0) { throw std::out_of_range ("control_loop: invalid bandwidth. Must be >= 0."); } d_loop_bw = bw; update_gains(); } void control_loop::set_damping_factor(float df) { if(df <= 0) { throw std::out_of_range ("control_loop: invalid damping factor. Must be > 0."); } d_damping = df; update_gains(); } void control_loop::set_alpha(float alpha) { if(alpha < 0 || alpha > 1.0) { throw std::out_of_range ("control_loop: invalid alpha. Must be in [0,1]."); } d_alpha = alpha; } void control_loop::set_beta(float beta) { if(beta < 0 || beta > 1.0) { throw std::out_of_range ("control_loop: invalid beta. Must be in [0,1]."); } d_beta = beta; } void control_loop::set_frequency(float freq) { if(freq > d_max_freq) d_freq = d_min_freq; else if(freq < d_min_freq) d_freq = d_max_freq; else d_freq = freq; } void control_loop::set_phase(float phase) { d_phase = phase; while(d_phase>M_TWOPI) d_phase -= M_TWOPI; while(d_phase<-M_TWOPI) d_phase += M_TWOPI; } void control_loop::set_max_freq(float freq) { d_max_freq = freq; } void control_loop::set_min_freq(float freq) { d_min_freq = freq; } /******************************************************************* * GET FUNCTIONS *******************************************************************/ float control_loop::get_loop_bandwidth() const { return d_loop_bw; } float control_loop::get_damping_factor() const { return d_damping; } float control_loop::get_alpha() const { return d_alpha; } float control_loop::get_beta() const { return d_beta; } float control_loop::get_frequency() const { return d_freq; } float control_loop::get_phase() const { return d_phase; } float control_loop::get_max_freq() const { return d_max_freq; } float control_loop::get_min_freq() const { return d_min_freq; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/annotator_raw_impl.cc0000664000175000017500000000650412207440367022175 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "annotator_raw_impl.h" #include #include #include #include #include using namespace pmt; namespace gr { namespace blocks { annotator_raw::sptr annotator_raw::make(size_t sizeof_stream_item) { return gnuradio::get_initial_sptr (new annotator_raw_impl(sizeof_stream_item)); } annotator_raw_impl::annotator_raw_impl(size_t sizeof_stream_item) : sync_block("annotator_raw", io_signature::make(1, 1, sizeof_stream_item), io_signature::make(1, 1, sizeof_stream_item)), d_itemsize(sizeof_stream_item) { set_tag_propagation_policy(TPP_ONE_TO_ONE); set_relative_rate(1.0); } annotator_raw_impl::~annotator_raw_impl() { } void annotator_raw_impl::add_tag(uint64_t offset, pmt_t key, pmt_t val) { gr::thread::scoped_lock l(d_mutex); tag_t tag; tag.srcid = pmt::intern(name()); tag.key = key; tag.value = val; tag.offset = offset; // add our new tag d_queued_tags.push_back(tag); // make sure our tags are in offset order std::sort(d_queued_tags.begin(), d_queued_tags.end(), tag_t::offset_compare); // make sure we are not adding an item in the past! if(tag.offset > nitems_read(0)) { throw std::runtime_error("annotator_raw::add_tag: item added too far in the past\n."); } } int annotator_raw_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_mutex); const char *in = (const char*)input_items[0]; char *out = (char*)output_items[0]; uint64_t start_N = nitems_read(0); uint64_t end_N = start_N + (uint64_t)(noutput_items); // locate queued tags that fall in this range and insert them when appropriate std::vector::iterator i = d_queued_tags.begin(); while( i != d_queued_tags.end() ) { if( (*i).offset >= start_N && (*i).offset < end_N) { add_item_tag(0, (*i).offset,(*i).key, (*i).value, (*i).srcid); i = d_queued_tags.erase(i); } else { break; } } // copy data across memcpy(out, in, noutput_items*d_itemsize); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ConfigChecks.cmake0000664000175000017500000000605412207440367021317 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## INCLUDE(GrMiscUtils) INCLUDE(CheckCXXSourceCompiles) IF(MSVC) #add this directory for our provided headers LIST(APPEND CMAKE_REQUIRED_INCLUDES ${CMAKE_SOURCE_DIR}/msvc) ENDIF(MSVC) GR_CHECK_HDR_N_DEF(netdb.h HAVE_NETDB_H) GR_CHECK_HDR_N_DEF(sys/time.h HAVE_SYS_TIME_H) GR_CHECK_HDR_N_DEF(sys/types.h HAVE_SYS_TYPES_H) GR_CHECK_HDR_N_DEF(sys/select.h HAVE_SYS_SELECT_H) GR_CHECK_HDR_N_DEF(sys/socket.h HAVE_SYS_SOCKET_H) GR_CHECK_HDR_N_DEF(io.h HAVE_IO_H) GR_CHECK_HDR_N_DEF(sys/mman.h HAVE_SYS_MMAN_H) GR_CHECK_HDR_N_DEF(sys/ipc.h HAVE_SYS_IPC_H) GR_CHECK_HDR_N_DEF(sys/shm.h HAVE_SYS_SHM_H) GR_CHECK_HDR_N_DEF(signal.h HAVE_SIGNAL_H) GR_CHECK_HDR_N_DEF(netinet/in.h HAVE_NETINET_IN_H) GR_CHECK_HDR_N_DEF(arpa/inet.h HAVE_ARPA_INET_H) GR_CHECK_HDR_N_DEF(byteswap.h HAVE_BYTESWAP_H) GR_CHECK_HDR_N_DEF(linux/ppdev.h HAVE_LINUX_PPDEV_H) GR_CHECK_HDR_N_DEF(dev/ppbus/ppi.h HAVE_DEV_PPBUS_PPI_H) GR_CHECK_HDR_N_DEF(unistd.h HAVE_UNISTD_H) GR_CHECK_HDR_N_DEF(malloc.h HAVE_MALLOC_H) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #include int main(){select(0, 0, 0, 0, 0); return 0;} " HAVE_SELECT ) GR_ADD_COND_DEF(HAVE_SELECT) ######################################################################## CHECK_INCLUDE_FILE_CXX(windows.h HAVE_WINDOWS_H) IF(HAVE_WINDOWS_H) ADD_DEFINITIONS(-DHAVE_WINDOWS_H -DUSING_WINSOCK) MESSAGE(STATUS "Adding windows libs to gr blocks libs...") LIST(APPEND blocks_libs WS2_32.lib WSock32.lib) ENDIF(HAVE_WINDOWS_H) ######################################################################## CHECK_CXX_SOURCE_COMPILES(" #define _GNU_SOURCE #include int main(){double x, sin, cos; sincos(x, &sin, &cos); return 0;} " HAVE_SINCOS ) GR_ADD_COND_DEF(HAVE_SINCOS) CHECK_CXX_SOURCE_COMPILES(" #define _GNU_SOURCE #include int main(){float x, sin, cos; sincosf(x, &sin, &cos); return 0;} " HAVE_SINCOSF ) GR_ADD_COND_DEF(HAVE_SINCOSF) CHECK_CXX_SOURCE_COMPILES(" #include int main(){sinf(0); return 0;} " HAVE_SINF ) GR_ADD_COND_DEF(HAVE_SINF) CHECK_CXX_SOURCE_COMPILES(" #include int main(){cosf(0); return 0;} " HAVE_COSF ) GR_ADD_COND_DEF(HAVE_COSF) gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_XX_impl.h.t0000664000175000017500000000255712207440367023133 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { @O_TYPE@ d_k; public: @NAME_IMPL@(@O_TYPE@ k); @O_TYPE@ k() const { return d_k; } void set_k(@O_TYPE@ k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/streams_to_stream_impl.h0000664000175000017500000000254012207440367022710 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_STREAMS_TO_STREAM_IMPL_H #define INCLUDED_STREAMS_TO_STREAM_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API streams_to_stream_impl : public streams_to_stream { public: streams_to_stream_impl(size_t itemsize, size_t nstreams); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_STREAMS_TO_STREAM_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/nlog10_ff_impl.h0000664000175000017500000000254312207440367020733 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_NLOG10_FF_IMPL_H #define INCLUDED_NLOG10_FF_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API nlog10_ff_impl : public nlog10_ff { float d_n; size_t d_vlen; float d_k; public: nlog10_ff_impl(float n, size_t vlen, float k); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_NLOG10_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/message_strobe_impl.cc0000664000175000017500000000460112207440367022315 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "message_strobe_impl.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace blocks { message_strobe::sptr message_strobe::make(pmt::pmt_t msg, float period_ms) { return gnuradio::get_initial_sptr (new message_strobe_impl(msg, period_ms)); } message_strobe_impl::message_strobe_impl(pmt::pmt_t msg, float period_ms) : block("message_strobe", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)), d_finished(false), d_period_ms(period_ms), d_msg(msg) { message_port_register_out(pmt::mp("strobe")); d_thread = boost::shared_ptr (new boost::thread(boost::bind(&message_strobe_impl::run, this))); message_port_register_in(pmt::mp("set_msg")); set_msg_handler(pmt::mp("set_msg"), boost::bind(&message_strobe_impl::set_msg, this, _1)); } message_strobe_impl::~message_strobe_impl() { d_finished = true; d_thread->interrupt(); d_thread->join(); } void message_strobe_impl::run() { while(!d_finished) { boost::this_thread::sleep(boost::posix_time::milliseconds(d_period_ms)); if(d_finished) { return; } message_port_pub(pmt::mp("strobe"), d_msg); } } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/check_lfsr_32k_s_impl.h0000664000175000017500000000520512207440367022262 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_CHECK_LFSR_32K_S_IMPL_H #define INCLUDED_GR_CHECK_LFSR_32K_S_IMPL_H #include #include namespace gr { namespace blocks { class check_lfsr_32k_s_impl : public check_lfsr_32k_s { private: enum state { SEARCHING, // searching for synchronization MATCH0, MATCH1, MATCH2, LOCKED // is locked }; state d_state; unsigned int d_history; // bitmask of decisions long d_ntotal; // total number of shorts long d_nright; // # of correct shorts long d_runlength; // # of correct shorts in a row static const int BUFSIZE = 2048 - 1; // ensure pattern isn't packet aligned int d_index; unsigned short d_buffer[BUFSIZE]; void enter_SEARCHING(); void enter_MATCH0(); void enter_MATCH1(); void enter_MATCH2(); void enter_LOCKED(); void right() { d_history = (d_history < 1) | 0x1; d_nright++; d_runlength++; } void wrong() { d_history = (d_history < 1) | 0x0; d_runlength = 0; } bool right_three_times() { return (d_history & 0x7) == 0x7; } bool wrong_three_times() { return (d_history & 0x7) == 0x0; } void log_error(unsigned short expected, unsigned short actual); public: check_lfsr_32k_s_impl(); ~check_lfsr_32k_s_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); long ntotal() const { return d_ntotal; } long nright() const { return d_nright; } long runlength() const { return d_runlength; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_CHECK_LFSR_32K_S_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/integrate_XX_impl.cc.t0000664000175000017500000000347012207440367022161 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(int decim) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(decim)); } @NAME_IMPL@::@NAME_IMPL@(int decim) : sync_decimator("@NAME@", io_signature::make(1, 1, sizeof (@I_TYPE@)), io_signature::make(1, 1, sizeof (@O_TYPE@)), decim), d_decim(decim), d_count(0) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const @I_TYPE@ *in = (const @I_TYPE@ *)input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[0]; for (int i = 0; i < noutput_items; i++) { out[i] = (@O_TYPE@)0; for (int j = 0; j < d_decim; j++) out[i] += in[i*d_decim+j]; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/annotator_1to1_impl.cc0000664000175000017500000000712312207440367022166 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "annotator_1to1_impl.h" #include #include #include #include namespace gr { namespace blocks { annotator_1to1::sptr annotator_1to1::make(int when, size_t sizeof_stream_item) { return gnuradio::get_initial_sptr (new annotator_1to1_impl(when, sizeof_stream_item)); } annotator_1to1_impl::annotator_1to1_impl(int when, size_t sizeof_stream_item) : sync_block("annotator_1to1", io_signature::make(1, -1, sizeof_stream_item), io_signature::make(1, -1, sizeof_stream_item)), d_itemsize(sizeof_stream_item), d_when((uint64_t)when) { set_tag_propagation_policy(TPP_ONE_TO_ONE); d_tag_counter = 0; set_relative_rate(1.0); } annotator_1to1_impl::~annotator_1to1_impl() { } int annotator_1to1_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; std::stringstream str; str << name() << unique_id(); uint64_t abs_N = 0; int ninputs = input_items.size(); for(int i = 0; i < ninputs; i++) { abs_N = nitems_read(i); std::vector all_tags; get_tags_in_range(all_tags, i, abs_N, abs_N + noutput_items); std::vector::iterator itr; for(itr = all_tags.begin(); itr != all_tags.end(); itr++) { d_stored_tags.push_back(*itr); } } // Storing the current noutput_items as the value to the "noutput_items" key pmt::pmt_t srcid = pmt::string_to_symbol(str.str()); pmt::pmt_t key = pmt::string_to_symbol("seq"); // Work does nothing to the data stream; just copy all inputs to outputs // Adds a new tag when the number of items read is a multiple of d_when abs_N = nitems_read(0); int noutputs = output_items.size(); for(int j = 0; j < noutput_items; j++) { // the min() is a hack to make sure this doesn't segfault if // there are a different number of ins and outs. This is // specifically designed to test the 1-to-1 propagation policy. for(int i = 0; i < std::min(noutputs, ninputs); i++) { if(abs_N % d_when == 0) { pmt::pmt_t value = pmt::from_uint64(d_tag_counter++); add_item_tag(i, abs_N, key, value, srcid); } in = (const float*)input_items[i]; out = (float*)output_items[i]; out[j] = in[j]; } abs_N++; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/streams_to_vector_impl.cc0000664000175000017500000000400612207440367023054 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "streams_to_vector_impl.h" #include namespace gr { namespace blocks { streams_to_vector::sptr streams_to_vector::make(size_t itemsize, size_t nstreams) { return gnuradio::get_initial_sptr(new streams_to_vector_impl(itemsize, nstreams)); } streams_to_vector_impl::streams_to_vector_impl(size_t itemsize, size_t nstreams) : sync_block ("streams_to_vector", io_signature::make (nstreams, nstreams, itemsize), io_signature::make (1, 1, nstreams * itemsize)) { } int streams_to_vector_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t itemsize = input_signature()->sizeof_stream_item(0); int nstreams = input_items.size(); const char **inv = (const char **) &input_items[0]; char *out = (char *) output_items[0]; for (int i = 0; i < noutput_items; i++){ for (int j = 0; j < nstreams; j++){ memcpy(out, inv[j], itemsize); inv[j] += itemsize; out += itemsize; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/tagged_stream_mux_impl.cc0000664000175000017500000000613112237515111023003 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "tagged_stream_mux_impl.h" namespace gr { namespace blocks { tagged_stream_mux::sptr tagged_stream_mux::make(size_t itemsize, const std::string &lengthtagname, unsigned int tag_preserve_head_pos) { return gnuradio::get_initial_sptr (new tagged_stream_mux_impl(itemsize, lengthtagname, tag_preserve_head_pos)); } tagged_stream_mux_impl::tagged_stream_mux_impl(size_t itemsize, const std::string &lengthtagname, unsigned int tag_preserve_head_pos) : tagged_stream_block("tagged_stream_mux", io_signature::make(1, -1, itemsize), io_signature::make(1, 1, itemsize), lengthtagname), d_itemsize(itemsize), d_tag_preserve_head_pos(tag_preserve_head_pos) { set_tag_propagation_policy(TPP_DONT); } tagged_stream_mux_impl::~tagged_stream_mux_impl() { } int tagged_stream_mux_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { int nout = 0; for (unsigned i = 0; i < ninput_items.size(); i++) { nout += ninput_items[i]; } return nout; } int tagged_stream_mux_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned char *out = (unsigned char *) output_items[0]; int n_produced = 0; set_relative_rate(ninput_items.size()); for (unsigned int i = 0; i < input_items.size(); i++) { const unsigned char *in = (const unsigned char *) input_items[i]; std::vector tags; get_tags_in_range(tags, i, nitems_read(i), nitems_read(i)+ninput_items[i]); for (unsigned int j = 0; j < tags.size(); j++) { uint64_t offset = tags[j].offset - nitems_read(i) + nitems_written(0) + n_produced; if (i == d_tag_preserve_head_pos && tags[j].offset == nitems_read(i)) { offset -= n_produced; } add_item_tag(0, offset, tags[j].key, tags[j].value); } memcpy((void *) out, (const void *) in, ninput_items[i] * d_itemsize); out += ninput_items[i] * d_itemsize; n_produced += ninput_items[i]; } return n_produced; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_vXX_impl.cc.t0000664000175000017500000000361112207440367023447 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(std::vector<@O_TYPE@> k) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(k)); } @NAME_IMPL@::@NAME_IMPL@(std::vector<@O_TYPE@> k) : sync_block ("@NAME@", io_signature::make (1, 1, sizeof (@I_TYPE@)*k.size()), io_signature::make (1, 1, sizeof (@O_TYPE@)*k.size())), d_k(k) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *)input_items[0]; @O_TYPE@ *optr = (@O_TYPE@ *)output_items[0]; int nitems_per_block = output_signature()->sizeof_stream_item(0)/sizeof(@I_TYPE@); for (int i = 0; i < noutput_items; i++) for (int j = 0; j < nitems_per_block; j++) *optr++ = *iptr++ * d_k[j]; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/threshold_ff_impl.cc0000664000175000017500000000432112207440367021761 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "threshold_ff_impl.h" #include namespace gr { namespace blocks { threshold_ff::sptr threshold_ff::make(float lo, float hi, float initial_state) { return gnuradio::get_initial_sptr (new threshold_ff_impl(lo, hi, initial_state)); } threshold_ff_impl::threshold_ff_impl(float lo, float hi, float initial_state) : sync_block("threshold_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), d_lo(lo), d_hi(hi), d_last_state(initial_state) { } threshold_ff_impl::~threshold_ff_impl() { } int threshold_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; float *out = (float *)output_items[0]; for(int i = 0; i < noutput_items; i++) { if(in[i] > d_hi) { out[i] = 1.0; d_last_state = 1.0; } else if(in[i] < d_lo) { out[i] = 0.0; d_last_state = 0.0; } else out[i] = d_last_state; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/int_to_float_impl.cc0000664000175000017500000000365212207440367022001 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "int_to_float_impl.h" #include #include namespace gr { namespace blocks { int_to_float::sptr int_to_float::make(size_t vlen, float scale) { return gnuradio::get_initial_sptr(new int_to_float_impl(vlen, scale)); } int_to_float_impl::int_to_float_impl(size_t vlen, float scale) : sync_block("int_to_float", io_signature::make (1, 1, sizeof(int32_t)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen), d_scale(scale) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } int int_to_float_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const int32_t *in = (const int32_t *) input_items[0]; float *out = (float *) output_items[0]; volk_32i_s32f_convert_32f(out, in, d_scale, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/qa_block_tags.h0000664000175000017500000000251412207440367020726 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_BLOCK_TAGS_H #define INCLUDED_QA_BLOCK_TAGS_H #include #include #include class qa_block_tags : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_block_tags); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1); CPPUNIT_TEST(t2); CPPUNIT_TEST(t3); CPPUNIT_TEST(t4); CPPUNIT_TEST(t5); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1(); void t2(); void t3(); void t4(); void t5(); }; #endif /* INCLUDED_QA_BLOCK_TAGS_H */ gnuradio-3.7.2.1/gr-blocks/lib/socket_pdu_impl.h0000664000175000017500000000464012207440367021320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_SOCKET_PDU_IMPL_H #define INCLUDED_BLOCKS_SOCKET_PDU_IMPL_H #include #include "stream_pdu_base.h" #include "tcp_connection.h" namespace gr { namespace blocks { class socket_pdu_impl : public socket_pdu, public stream_pdu_base { private: boost::asio::io_service d_io_service; boost::array d_rxbuf; void run_io_service() { d_io_service.run(); } // TCP specific boost::asio::ip::tcp::endpoint d_tcp_endpoint; std::vector d_tcp_connections; void handle_tcp_read(const boost::system::error_code& error, size_t bytes_transferred); // TCP server specific boost::shared_ptr d_acceptor_tcp; void start_tcp_accept(); void tcp_server_send(pmt::pmt_t msg); void handle_tcp_accept(tcp_connection::sptr new_connection, const boost::system::error_code& error); // TCP client specific boost::shared_ptr d_tcp_socket; void tcp_client_send(pmt::pmt_t msg); // UDP specific boost::asio::ip::udp::endpoint d_udp_endpoint; boost::asio::ip::udp::endpoint d_udp_endpoint_other; boost::shared_ptr d_udp_socket; void handle_udp_read(const boost::system::error_code& error, size_t bytes_transferred); void udp_send(pmt::pmt_t msg); public: socket_pdu_impl(std::string type, std::string addr, std::string port, int MTU); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_SOCKET_PDU_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/wavfile_source_impl.cc0000664000175000017500000001063612207440367022335 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "wavfile_source_impl.h" #include #include #include #include #include // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { wavfile_source::sptr wavfile_source::make(const char *filename, bool repeat) { return gnuradio::get_initial_sptr (new wavfile_source_impl(filename, repeat)); } wavfile_source_impl::wavfile_source_impl (const char *filename, bool repeat) : sync_block("wavfile_source", io_signature::make(0, 0, 0), io_signature::make(1, 2, sizeof(float))), d_fp(NULL), d_repeat(repeat), d_sample_rate(1), d_nchans(1), d_bytes_per_sample(2), d_first_sample_pos(0), d_samples_per_chan(0), d_sample_idx(0) { // we use "open" to use to the O_LARGEFILE flag int fd; if((fd = open (filename, O_RDONLY | OUR_O_LARGEFILE | OUR_O_BINARY)) < 0) { perror(filename); throw std::runtime_error("can't open file"); } if((d_fp = fdopen(fd, "rb")) == NULL) { perror(filename); throw std::runtime_error("can't open file"); } // Scan headers, check file validity if(!wavheader_parse(d_fp, d_sample_rate, d_nchans, d_bytes_per_sample, d_first_sample_pos, d_samples_per_chan)) { throw std::runtime_error("is not a valid wav file"); } if(d_samples_per_chan == 0) { throw std::runtime_error("WAV file does not contain any samples"); } if(d_bytes_per_sample == 1) { d_normalize_fac = 128; d_normalize_shift = 1; } else { d_normalize_fac = 0x7FFF; d_normalize_shift = 0; } // Re-set the output signature set_output_signature(io_signature::make(1, d_nchans, sizeof(float))); } wavfile_source_impl::~wavfile_source_impl () { fclose(d_fp); } float wavfile_source_impl::convert_to_float(short int sample) { float sample_out = (float)sample; sample_out /= d_normalize_fac; sample_out -= d_normalize_shift; return sample_out; } int wavfile_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float **out = (float**)&output_items[0]; int n_out_chans = output_items.size(); int i; short sample; for(i = 0; i < noutput_items; i++) { if(d_sample_idx >= d_samples_per_chan) { if(!d_repeat) { // if nothing was read at all, say we're done. return i ? i : -1; } if(fseek (d_fp, d_first_sample_pos, SEEK_SET) == -1) { fprintf(stderr, "[%s] fseek failed\n", __FILE__); exit(-1); } d_sample_idx = 0; } for(int chan = 0; chan < d_nchans; chan++) { sample = wav_read_sample(d_fp, d_bytes_per_sample); if(chan < n_out_chans) { out[chan][i] = convert_to_float(sample); } } d_sample_idx++; // OK, EOF is not necessarily an error. But we're not going to // deal with handling corrupt wav files, so if they give us any // trouble they won't be processed. Serves them bloody right. if(feof(d_fp) || ferror(d_fp)) { if(i == 0) { fprintf(stderr, "[%s] WAV file has corrupted header or i/o error\n", __FILE__); return -1; } return i; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/wavfile_sink_impl.h0000664000175000017500000000523012207440367021635 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_WAVFILE_SINK_IMPL_H #define INCLUDED_GR_WAVFILE_SINK_IMPL_H #include namespace gr { namespace blocks { class wavfile_sink_impl : public wavfile_sink { private: unsigned d_sample_rate; int d_nchans; unsigned d_sample_count; int d_bytes_per_sample; int d_bytes_per_sample_new; int d_max_sample_val; int d_min_sample_val; int d_normalize_shift; int d_normalize_fac; FILE *d_fp; FILE *d_new_fp; bool d_updated; boost::mutex d_mutex; /*! * \brief Convert a sample value within [-1;+1] to a corresponding * short integer value */ short convert_to_short(float sample); /*! * \brief If any file changes have occurred, update now. This is called * internally by work() and thus doesn't usually need to be called by * hand. */ void do_update(); /*! * \brief Writes information to the WAV header which is not available * a-priori (chunk size etc.) and closes the file. Not thread-safe and * assumes d_fp is a valid file pointer, should thus only be called by * other methods. */ void close_wav(); public: wavfile_sink_impl(const char *filename, int n_channels, unsigned int sample_rate, int bits_per_sample); ~wavfile_sink_impl(); bool open(const char* filename); void close(); void set_sample_rate(unsigned int sample_rate); void set_bits_per_sample(int bits_per_sample); int bits_per_sample(); unsigned int sample_rate(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_WAVFILE_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_s_impl.h0000664000175000017500000000401012207702530022604 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_S_IMPL_H #define INCLUDED_CTRLPORT_PROBE2_S_IMPL_H #include #include #include namespace gr { namespace blocks { class ctrlport_probe2_s_impl : public ctrlport_probe2_s { private: std::string d_id; std::string d_desc; size_t d_len; unsigned int d_disp_mask; boost::shared_mutex mutex_buffer; mutable boost::mutex mutex_notify; boost::condition_variable condition_buffer_ready; std::vector d_buffer; public: ctrlport_probe2_s_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); ~ctrlport_probe2_s_impl(); void setup_rpc(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); std::vector get(); void set_length(int len); int length() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_S_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_real_impl.cc0000664000175000017500000000366412207440367022477 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_real_impl.h" #include #include namespace gr { namespace blocks { complex_to_real::sptr complex_to_real::make(size_t vlen) { return gnuradio::get_initial_sptr(new complex_to_real_impl(vlen)); } complex_to_real_impl::complex_to_real_impl(size_t vlen) : sync_block("complex_to_real", io_signature::make (1, 1, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int complex_to_real_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; float *out = (float *) output_items[0]; int noi = noutput_items * d_vlen; volk_32fc_deinterleave_real_32f(out, in, noi); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_sink_impl.h0000664000175000017500000000262612237515111021116 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_SINK_IMPL_H #define INCLUDED_GR_FILE_SINK_IMPL_H #include namespace gr { namespace blocks { class file_sink_impl : public file_sink { private: size_t d_itemsize; public: file_sink_impl(size_t itemsize, const char *filename, bool append=false); ~file_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/pack_k_bits_bb_impl.h0000664000175000017500000000270512207440367022074 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PACK_K_BITS_BB_IMPL_H #define INCLUDED_GR_PACK_K_BITS_BB_IMPL_H #include namespace gr { namespace blocks { class pack_k_bits_bb_impl : public pack_k_bits_bb { private: unsigned d_k; // number of relevent bits to pack from k input bytes public: pack_k_bits_bb_impl(unsigned k); ~pack_k_bits_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_PACK_K_BITS_BB_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_char_impl.h0000664000175000017500000000274112207440367021764 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FLOAT_TO_CHAR_IMPL_H #define INCLUDED_FLOAT_TO_CHAR_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API float_to_char_impl : public float_to_char { size_t d_vlen; float d_scale; public: float_to_char_impl(size_t vlen, float scale); virtual float scale() const { return d_scale; } virtual void set_scale(float scale) { d_scale = scale; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_FLOAT_TO_CHAR_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/conjugate_cc_impl.h0000664000175000017500000000243512207440367021604 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CONJUGATE_CC_IMPL_H #define INCLUDED_CONJUGATE_CC_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API conjugate_cc_impl : public conjugate_cc { public: conjugate_cc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CONJUGATE_CC_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/delay_impl.h0000664000175000017500000000325712207440367020261 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_DELAY_IMPL_H #define INCLUDED_GR_DELAY_IMPL_H #include #include namespace gr { namespace blocks { class delay_impl : public delay { private: void forecast(int noutput_items, gr_vector_int &ninput_items_required); size_t d_itemsize; int d_delta; gr::thread::mutex d_mutex_delay; public: delay_impl(size_t itemsize, int delay); ~delay_impl(); int dly() const { return history()-1; } void set_dly(int d); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_DELAY_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_f_impl.cc0000664000175000017500000001207712207702530022741 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe2_f_impl.h" #include namespace gr { namespace blocks { ctrlport_probe2_f::sptr ctrlport_probe2_f::make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) { return gnuradio::get_initial_sptr (new ctrlport_probe2_f_impl(id, desc, len, disp_mask)); } ctrlport_probe2_f_impl::ctrlport_probe2_f_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) : sync_block("probe2_f", io_signature::make(1, 1, sizeof(float)), io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_len(len), d_disp_mask(disp_mask) { set_length(len); } ctrlport_probe2_f_impl::~ctrlport_probe2_f_impl() { } void ctrlport_probe2_f_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = d_len; } // boost::shared_mutex mutex_buffer; // mutable boost::mutex mutex_notify; // boost::condition_variable condition_buffer_ready; std::vector ctrlport_probe2_f_impl::get() { mutex_buffer.lock(); d_buffer.clear(); mutex_buffer.unlock(); // wait for condition boost::mutex::scoped_lock lock(mutex_notify); condition_buffer_ready.wait(lock); mutex_buffer.lock(); std::vector buf_copy = d_buffer; assert(buf_copy.size() == d_len); mutex_buffer.unlock(); return buf_copy; } void ctrlport_probe2_f_impl::set_length(int len) { if(len > 8191) { std::cerr << "probe2_f: length " << len << " exceeds maximum buffer size of 8191" << std::endl; len = 8191; } d_len = len; d_buffer.reserve(d_len); } int ctrlport_probe2_f_impl::length() const { return (int)d_len; } int ctrlport_probe2_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; // copy samples to get buffer if we need samples mutex_buffer.lock(); if(d_buffer.size() < d_len) { // copy smaller of remaining buffer space and num inputs to work() int num_copy = std::min( (int)(d_len - d_buffer.size()), noutput_items ); // TODO: convert this to a copy operator for speed... for(int i = 0; i < num_copy; i++) { d_buffer.push_back(in[i]); } // notify the waiting get() if we fill up the buffer if(d_buffer.size() == d_len) { condition_buffer_ready.notify_one(); } } mutex_buffer.unlock(); return noutput_items; } void ctrlport_probe2_f_impl::setup_rpc() { #ifdef GR_CTRLPORT int len = static_cast(d_len); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), d_id.c_str(), &ctrlport_probe2_f::get, pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f), // pmt::make_f32vector(1,-2), // pmt::make_f32vector(1,2), // pmt::make_f32vector(1,0), "volts", d_desc.c_str(), RPC_PRIVLVL_MIN, d_disp_mask))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "length", &ctrlport_probe2_f::length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "get vector length", RPC_PRIVLVL_MIN, DISPNULL))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "length", &ctrlport_probe2_f::set_length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "set vector length", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_XX_impl.h.t0000664000175000017500000000243412207440367021717 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_hier_block2_derived.cc0000664000175000017500000000465712207440367023343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include // Declare a test C++ hierarchical block class gr_derived_block; typedef boost::shared_ptr gr_derived_block_sptr; gr_derived_block_sptr gr_make_derived_block(); class gr_derived_block : public gr::hier_block2 { private: friend gr_derived_block_sptr gr_make_derived_block(); gr_derived_block(); public: ~gr_derived_block(); }; gr_derived_block_sptr gr_make_derived_block() { return gnuradio::get_initial_sptr(new gr_derived_block()); } gr_derived_block::gr_derived_block() : gr::hier_block2("gr_derived_block", gr::io_signature::make(1, 1, sizeof(int)), // Input signature gr::io_signature::make(1, 1, sizeof(int))) // Output signature { gr::block_sptr copy(gr::blocks::copy::make(sizeof(int))); connect(self(), 0, copy, 0); connect(copy, 0, self(), 0); } gr_derived_block::~gr_derived_block() { } void qa_hier_block2_derived::test_1() { gr::top_block_sptr tb(gr::make_top_block("test")); gr::block_sptr src(gr::blocks::null_source::make(sizeof(int))); gr::block_sptr head(gr::blocks::head::make(sizeof(int), 1000)); gr_derived_block_sptr blk(gr_make_derived_block()); gr::block_sptr dst(gr::blocks::null_sink::make(sizeof(int))); tb->connect(src, 0, head, 0); tb->connect(head, 0, blk, 0); tb->connect(blk, 0, dst, 0); tb->run(); } gnuradio-3.7.2.1/gr-blocks/lib/qa_set_msg_handler.cc0000664000175000017500000000445512207440367022120 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #define VERBOSE 0 /* * The gr::block::nop block has been instrumented so that it counts * the number of messages sent to it. We use this feature to confirm * that gr::blocks::nop's call to set_msg_handler is working correctly. */ void qa_set_msg_handler::t0() { static const int NMSGS = 10; if (VERBOSE) std::cout << "qa_set_msg_handler::t0()\n"; top_block_sptr tb = make_top_block("top"); block_sptr src = gr::blocks::null_source::make(sizeof(int)); gr::blocks::nop::sptr nop = gr::blocks::nop::make(sizeof(int)); block_sptr dst = gr::blocks::null_sink::make(sizeof(int)); tb->connect(src, 0, nop, 0); tb->connect(nop, 0, dst, 0); // Must start graph before sending messages tb->start(); // Send them... pmt::pmt_t port(pmt::intern("port")); for (int i = 0; i < NMSGS; i++){ send(nop, port, pmt::mp(pmt::mp("example-msg"), pmt::mp(i))); } // Give the messages a chance to be processed boost::this_thread::sleep(boost::posix_time::milliseconds(100)); tb->stop(); tb->wait(); // Confirm that the nop block received the right number of messages. CPPUNIT_ASSERT_EQUAL(NMSGS, nop->nmsgs_received()); } gnuradio-3.7.2.1/gr-blocks/lib/null_source_impl.h0000664000175000017500000000254012207440367021507 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_NULL_SOURCE_IMPL_H #define INCLUDED_GR_NULL_SOURCE_IMPL_H #include namespace gr { namespace blocks { class null_source_impl : public null_source { public: null_source_impl(size_t sizeof_stream_item); ~null_source_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_NULL_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/interleaved_char_to_complex_impl.h0000664000175000017500000000271112207702530024676 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_INTERLEAVED_CHAR_TO_COMPLEX_IMPL_H #define INCLUDED_INTERLEAVED_CHAR_TO_COMPLEX_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API interleaved_char_to_complex_impl : public interleaved_char_to_complex { private: bool d_vector_input; public: interleaved_char_to_complex_impl(bool vector_input=false); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_INTERLEAVED_CHAR_TO_COMPLEX_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/short_to_float_impl.cc0000664000175000017500000000367112207440367022347 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "short_to_float_impl.h" #include #include namespace gr { namespace blocks { short_to_float::sptr short_to_float::make(size_t vlen, float scale) { return gnuradio::get_initial_sptr(new short_to_float_impl(vlen, scale)); } short_to_float_impl::short_to_float_impl(size_t vlen, float scale) : sync_block("short_to_float", io_signature::make (1, 1, sizeof(short)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen), d_scale(scale) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } int short_to_float_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short *) input_items[0]; float *out = (float *) output_items[0]; volk_16i_s32f_convert_32f(out, in, d_scale, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/interleave_impl.h0000664000175000017500000000256312207440367021320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_INTERLEAVE_IMPL_H #define INCLUDED_INTERLEAVE_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API interleave_impl : public interleave { size_t d_itemsize; public: interleave_impl(size_t itemsize); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_INTERLEAVE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/short_to_char_impl.cc0000664000175000017500000000357112207440367022156 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "short_to_char_impl.h" #include #include namespace gr { namespace blocks { short_to_char::sptr short_to_char::make(size_t vlen) { return gnuradio::get_initial_sptr(new short_to_char_impl(vlen)); } short_to_char_impl::short_to_char_impl(size_t vlen) : sync_block("short_to_char", io_signature::make (1, 1, sizeof(short)*vlen), io_signature::make (1, 1, sizeof(char)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(char); set_alignment(std::max(1, alignment_multiple)); } int short_to_char_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const int16_t *in = (const int16_t *) input_items[0]; int8_t *out = (int8_t *) output_items[0]; volk_16i_convert_8i(out, in, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/message_debug_impl.cc0000664000175000017500000000652712207440367022116 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "message_debug_impl.h" #include #include #include namespace gr { namespace blocks { message_debug::sptr message_debug::make() { return gnuradio::get_initial_sptr (new message_debug_impl()); } void message_debug_impl::print(pmt::pmt_t msg) { std::cout << "******* MESSAGE DEBUG PRINT ********\n"; pmt::print(msg); std::cout << "************************************\n"; } void message_debug_impl::store(pmt::pmt_t msg) { gr::thread::scoped_lock guard(d_mutex); d_messages.push_back(msg); } void message_debug_impl::print_pdu(pmt::pmt_t pdu) { pmt::pmt_t meta = pmt::car(pdu); pmt::pmt_t vector = pmt::cdr(pdu); std::cout << "* MESSAGE DEBUG PRINT PDU VERBOSE *\n"; pmt::print(meta); size_t len = pmt::length(vector); std::cout << "pdu_length = " << len << std::endl; std::cout << "contents = " << std::endl; size_t offset(0); const uint8_t* d = (const uint8_t*) pmt::uniform_vector_elements(vector, offset); for(size_t i=0; i= d_messages.size()) { throw std::runtime_error("message_debug: index for message out of bounds.\n"); } return d_messages[i]; } message_debug_impl::message_debug_impl() : block("message_debug", io_signature::make(0, 0, 0), io_signature::make(0, 0, 0)) { message_port_register_in(pmt::mp("print")); set_msg_handler(pmt::mp("print"), boost::bind(&message_debug_impl::print, this, _1)); message_port_register_in(pmt::mp("store")); set_msg_handler(pmt::mp("store"), boost::bind(&message_debug_impl::store, this, _1)); message_port_register_in(pmt::mp("print_pdu")); set_msg_handler(pmt::mp("print_pdu"), boost::bind(&message_debug_impl::print_pdu, this, _1)); } message_debug_impl::~message_debug_impl() { } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_descriptor_source_impl.cc0000664000175000017500000001026012207440367024046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_descriptor_source_impl.h" #include #include #include #include #include #include #include #include #include #ifdef HAVE_IO_H #include #endif namespace gr { namespace blocks { file_descriptor_source::sptr file_descriptor_source::make(size_t itemsize, int fd, bool repeat) { return gnuradio::get_initial_sptr (new file_descriptor_source_impl(itemsize, fd, repeat)); } file_descriptor_source_impl::file_descriptor_source_impl(size_t itemsize, int fd, bool repeat) : sync_block("file_descriptor_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_fd(fd), d_repeat(repeat), d_residue(new unsigned char[itemsize]), d_residue_len (0) { } file_descriptor_source_impl::~file_descriptor_source_impl() { close(d_fd); delete [] d_residue; } int file_descriptor_source_impl::read_items(char *buf, int nitems) { assert(nitems > 0); assert(d_residue_len < d_itemsize); int nbytes_read = 0; if(d_residue_len > 0) { memcpy(buf, d_residue, d_residue_len); nbytes_read = d_residue_len; d_residue_len = 0; } int r = read(d_fd, buf + nbytes_read, nitems * d_itemsize - nbytes_read); if(r <= 0) { handle_residue(buf, nbytes_read); return r; } r = handle_residue(buf, r + nbytes_read); if(r == 0) // block until we get something return read_items(buf, nitems); return r; } int file_descriptor_source_impl::handle_residue(char *buf, int nbytes_read) { assert(nbytes_read >= 0); int nitems_read = nbytes_read / d_itemsize; d_residue_len = nbytes_read % d_itemsize; if(d_residue_len > 0) { // fprintf (stderr, "handle_residue: %d\n", d_residue_len); memcpy(d_residue, buf + nbytes_read - d_residue_len, d_residue_len); } return nitems_read; } int file_descriptor_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { assert(noutput_items > 0); char *o = (char*)output_items[0]; int nread = 0; while(1) { int r = read_items(o, noutput_items - nread); if(r == -1) { if(errno == EINTR) continue; else { perror("file_descriptor_source[read]"); return -1; } } else if(r == 0) { // end of file if(!d_repeat) break; else { flush_residue(); if(lseek(d_fd, 0, SEEK_SET) == -1) { perror("file_descriptor_source[lseek]"); return -1; } } } else { o += r * d_itemsize; nread += r; break; } } if(nread == 0) // EOF return -1; return nread; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/unpacked_to_packed_XX_impl.h.t0000664000175000017500000000332612207440367023644 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006.2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: unsigned int d_bits_per_chunk; endianness_t d_endianness; unsigned int d_index; public: @NAME_IMPL@(unsigned int bits_per_chunk, endianness_t endianness); ~@NAME_IMPL@(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); bool check_topology(int ninputs, int noutputs) { return ninputs == noutputs; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/qa_rotator.h0000664000175000017500000000217012207440367020306 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_GR_ROTATOR_H_ #define _QA_GR_ROTATOR_H_ #include #include class qa_rotator : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_rotator); CPPUNIT_TEST(t1); CPPUNIT_TEST_SUITE_END(); private: void t1(); }; #endif /* _QA_GR_ROTATOR_H_ */ gnuradio-3.7.2.1/gr-blocks/lib/tuntap_pdu_impl.cc0000664000175000017500000001031212207440367021472 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "tuntap_pdu_impl.h" #include #include #include #include #include #include #if (defined(linux) || defined(__linux) || defined(__linux__)) #include #include #include #endif namespace gr { namespace blocks { tuntap_pdu::sptr tuntap_pdu::make(std::string dev, int MTU) { #if (defined(linux) || defined(__linux) || defined(__linux__)) return gnuradio::get_initial_sptr(new tuntap_pdu_impl(dev, MTU)); #else throw std::runtime_error("tuntap_pdu not implemented on this platform"); #endif } #if (defined(linux) || defined(__linux) || defined(__linux__)) tuntap_pdu_impl::tuntap_pdu_impl(std::string dev, int MTU) : block("tuntap_pdu", io_signature::make (0, 0, 0), io_signature::make (0, 0, 0)), stream_pdu_base(MTU), d_dev(dev) { // make the tuntap char dev_cstr[1024]; memset(dev_cstr, 0x00, 1024); strncpy(dev_cstr, dev.c_str(), std::min(sizeof(dev_cstr), dev.size())); d_fd = tun_alloc(dev_cstr); if (d_fd <= 0) throw std::runtime_error("gr::tuntap_pdu::make: tun_alloc failed (are you running as root?)"); std::cout << boost::format( "Allocated virtual ethernet interface: %s\n" "You must now use ifconfig to set its IP address. E.g.,\n" " $ sudo ifconfig %s 192.168.200.1\n" "Be sure to use a different address in the same subnet for each machine.\n" ) % dev % dev << std::endl; // set up output message port message_port_register_out(PDU_PORT_ID); start_rxthread(this, PDU_PORT_ID); // set up input message port message_port_register_in(PDU_PORT_ID); set_msg_handler(PDU_PORT_ID, boost::bind(&tuntap_pdu_impl::send, this, _1)); } int tuntap_pdu_impl::tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; const char *clonedev = "/dev/net/tun"; /* Arguments taken by the function: * * char *dev: the name of an interface (or '\0'). MUST have enough * space to hold the interface name if '\0' is passed * int flags: interface flags (eg, IFF_TUN etc.) */ /* open the clone device */ if ((fd = open(clonedev, O_RDWR)) < 0) return fd; /* preparation of the struct ifr, of type "struct ifreq" */ memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = flags; /* IFF_TUN or IFF_TAP, plus maybe IFF_NO_PI */ /* if a device name was specified, put it in the structure; otherwise, * the kernel will try to allocate the "next" device of the * specified type */ if (*dev) strncpy(ifr.ifr_name, dev, IFNAMSIZ); /* try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { close(fd); return err; } /* if the operation was successful, write back the name of the * interface to the variable "dev", so the caller can know * it. Note that the caller MUST reserve space in *dev (see calling * code below) */ strcpy(dev, ifr.ifr_name); /* this is the special file descriptor that the caller will use to talk * with the virtual interface */ return fd; } #endif } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/message_debug_impl.h0000664000175000017500000000565212207440367021756 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_DEBUG_IMPL_H #define INCLUDED_GR_MESSAGE_DEBUG_IMPL_H #include #include #include #include namespace gr { namespace blocks { class message_debug_impl : public message_debug { private: /*! * \brief Messages received in this port are printed to stdout. * * This port receives messages from the scheduler's message * handling mechanism and prints it to stdout. This message * handler function is only meant to be used by the scheduler to * handle messages posted to port 'print'. * * \param msg A pmt message passed from the scheduler's message handling. */ void print(pmt::pmt_t msg); /*! * \brief PDU formatted messages received in this port are printed to stdout. * * This port receives messages from the scheduler's message * handling mechanism and prints it to stdout. This message * handler function is only meant to be used by the scheduler to * handle messages posted to port 'print'. * * \param pdu A PDU message passed from the scheduler's message handling. */ void print_pdu(pmt::pmt_t pdu); /*! * \brief Messages received in this port are stored in a vector. * * This port receives messages from the scheduler's message * handling mechanism and stores it in a vector. Messages can be * retrieved later using the 'get_message' function. This * message handler function is only meant to be used by the * scheduler to handle messages posted to port 'store'. * * \param msg A pmt message passed from the scheduler's message handling. */ void store(pmt::pmt_t msg); gr::thread::mutex d_mutex; std::vector d_messages; public: message_debug_impl(); ~message_debug_impl(); int num_messages(); pmt::pmt_t get_message(int i); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_DEBUG_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/interleaved_short_to_complex_impl.cc0000664000175000017500000000377712207440367025302 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "interleaved_short_to_complex_impl.h" #include "interleaved_short_array_to_complex.h" #include namespace gr { namespace blocks { interleaved_short_to_complex::sptr interleaved_short_to_complex::make(bool vector_input) { return gnuradio::get_initial_sptr(new interleaved_short_to_complex_impl(vector_input)); } interleaved_short_to_complex_impl::interleaved_short_to_complex_impl(bool vector_input) : sync_decimator("interleaved_short_to_complex", gr::io_signature::make (1, 1, (vector_input?2:1)*sizeof(short)), gr::io_signature::make (1, 1, sizeof(gr_complex)), vector_input?1:2), d_vector_input(vector_input) { } int interleaved_short_to_complex_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; interleaved_short_array_to_complex (in, out, 2 * noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vco_c_impl.h0000664000175000017500000000275712207702530020251 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_VCO_F_IMPL_H #define INCLUDED_GR_VCO_F_IMPL_H #include #include namespace gr { namespace blocks { class vco_c_impl : public vco_c { private: double d_sampling_rate; double d_sensitivity; double d_amplitude; double d_k; gr::fxpt_vco d_vco; public: vco_c_impl(double sampling_rate, double sensitivity, double amplitude); ~vco_c_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_VCO_C_H */ gnuradio-3.7.2.1/gr-blocks/lib/add_const_XX_impl.cc.t0000664000175000017500000000373612207440367022142 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(@O_TYPE@ k) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(k)); } @NAME_IMPL@::@NAME_IMPL@(@O_TYPE@ k) : sync_block ("@NAME@", io_signature::make (1, 1, sizeof (@I_TYPE@)), io_signature::make (1, 1, sizeof (@O_TYPE@))), d_k(k) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *) input_items[0]; @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int size = noutput_items; while (size >= 8){ *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; *optr++ = *iptr++ + d_k; size -= 8; } while (size-- > 0) *optr++ = *iptr++ + d_k; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/moving_average_XX_impl.h.t0000664000175000017500000000333412207440367023031 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: int d_length; @O_TYPE@ d_scale; int d_max_iter; int d_new_length; @O_TYPE@ d_new_scale; bool d_updated; public: @NAME_IMPL@(int length, @O_TYPE@ scale, int max_iter = 4096); ~@NAME_IMPL@(); int length() const { return d_new_length; } @O_TYPE@ scale() const { return d_new_scale; } void set_length_and_scale(int length, @O_TYPE@ scale); void set_length(int length); void set_scale(@O_TYPE@ scale); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_conjugate_cc_impl.cc0000664000175000017500000000423612245466767023720 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace blocks { multiply_conjugate_cc::sptr multiply_conjugate_cc::make(size_t vlen) { return gnuradio::get_initial_sptr(new multiply_conjugate_cc_impl(vlen)); } multiply_conjugate_cc_impl::multiply_conjugate_cc_impl(size_t vlen) : sync_block("multiply_conjugate_cc", io_signature::make (2, 2, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(gr_complex)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } int multiply_conjugate_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *in0 = (gr_complex *) input_items[0]; gr_complex *in1 = (gr_complex *) input_items[1]; gr_complex *out = (gr_complex *) output_items[0]; int noi = d_vlen*noutput_items; if(is_unaligned()) { volk_32fc_x2_multiply_conjugate_32fc_u(out, in0, in1, noi); } else { volk_32fc_x2_multiply_conjugate_32fc_a(out, in0, in1, noi); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/rms_ff_impl.cc0000664000175000017500000000403212207440367020565 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "rms_ff_impl.h" #include #include namespace gr { namespace blocks { rms_ff::sptr rms_ff::make(double alpha) { return gnuradio::get_initial_sptr (new rms_ff_impl(alpha)); } rms_ff_impl::rms_ff_impl(double alpha) : sync_block("rms_ff", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))) { set_alpha(alpha); } rms_ff_impl::~rms_ff_impl() { } void rms_ff_impl::set_alpha(double alpha) { d_alpha = alpha; d_beta = 1 - d_alpha; d_avg = 0; } int rms_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; float *out = (float *)output_items[0]; for(int i = 0; i < noutput_items; i++) { double mag_sqrd = in[i]*in[i]; d_avg = d_beta*d_avg + d_alpha*mag_sqrd; out[i] = sqrt(d_avg); } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vector_to_stream_impl.h0000664000175000017500000000254112207440367022535 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VECTOR_TO_STREAM_IMPL_H #define INCLUDED_VECTOR_TO_STREAM_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API vector_to_stream_impl : public vector_to_stream { public: vector_to_stream_impl(size_t itemsize, size_t nitems_per_block); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_VECTOR_TO_STREAM_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/not_XX_impl.h.t0000664000175000017500000000242312207440367020636 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/tag_debug_impl.h0000664000175000017500000000357012237515111021073 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAG_DEBUG_IMPL_H #define INCLUDED_GR_TAG_DEBUG_IMPL_H #include #include #include namespace gr { namespace blocks { class tag_debug_impl : public tag_debug { private: std::string d_name; std::vector d_tags; std::vector::iterator d_tags_itr; bool d_display; pmt::pmt_t d_filter; gr::thread::mutex d_mutex; public: tag_debug_impl(size_t sizeof_stream_item, const std::string &name, const std::string &key_filter=""); ~tag_debug_impl(); void setup_rpc(); std::vector current_tags(); int num_tags(); void set_display(bool d); void set_key_filter(const std::string &key_filter); std::string key_filter() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TAG_DEBUG_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/streams_to_stream_impl.cc0000664000175000017500000000416012207440367023046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "streams_to_stream_impl.h" #include namespace gr { namespace blocks { streams_to_stream::sptr streams_to_stream::make(size_t itemsize, size_t nstreams) { return gnuradio::get_initial_sptr(new streams_to_stream_impl(itemsize, nstreams)); } streams_to_stream_impl::streams_to_stream_impl(size_t itemsize, size_t nstreams) : sync_interpolator ("streams_to_stream", io_signature::make (nstreams, nstreams, itemsize), io_signature::make (1, 1, itemsize), nstreams) { } int streams_to_stream_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t itemsize = output_signature()->sizeof_stream_item (0); const char **inv = (const char **) &input_items[0]; char *out = (char *) output_items[0]; int nstreams = input_items.size(); assert (noutput_items % nstreams == 0); int ni = noutput_items / nstreams; for (int i = 0; i < ni; i++){ for (int j = 0; j < nstreams; j++){ memcpy(out, inv[j], itemsize); out += itemsize; inv[j] += itemsize; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/mute_XX_impl.cc.t0000664000175000017500000000433612207440367021153 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(bool mute) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(mute)); } @NAME_IMPL@::@NAME_IMPL@(bool mute) : sync_block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_mute(mute) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *)input_items[0]; @O_TYPE@ *optr = (@O_TYPE@ *)output_items[0]; int size = noutput_items; if(d_mute) { memset(optr, 0, noutput_items * sizeof(@O_TYPE@)); } else { while(size >= 8) { *optr++ = *iptr++; *optr++ = *iptr++; *optr++ = *iptr++; *optr++ = *iptr++; *optr++ = *iptr++; *optr++ = *iptr++; *optr++ = *iptr++; *optr++ = *iptr++; size -= 8; } while(size-- > 0) *optr++ = *iptr++; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/add_XX_impl.cc.t0000664000175000017500000000356212207440367020731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc += ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_arg_impl.h0000664000175000017500000000252012207440367022155 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_ARG_IMPL_H #define INCLUDED_COMPLEX_TO_ARG_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_arg_impl : public complex_to_arg { size_t d_vlen; public: complex_to_arg_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_ARG_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/stream_to_streams_impl.cc0000664000175000017500000000424112207440367023046 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "stream_to_streams_impl.h" #include #include namespace gr { namespace blocks { stream_to_streams::sptr stream_to_streams::make(size_t itemsize, size_t nstreams) { return gnuradio::get_initial_sptr (new stream_to_streams_impl(itemsize, nstreams)); } stream_to_streams_impl::stream_to_streams_impl(size_t itemsize, size_t nstreams) : sync_decimator("stream_to_streams", io_signature::make(1, 1, itemsize), io_signature::make(nstreams, nstreams, itemsize), nstreams) { } int stream_to_streams_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t item_size = output_signature()->sizeof_stream_item(0); const char *in = (const char *)input_items[0]; char **outv = (char **)&output_items[0]; int nstreams = output_items.size(); for (int i = 0; i < noutput_items; i++) { for (int j = 0; j < nstreams; j++) { memcpy(outv[j], in, item_size); outv[j] += item_size; in += item_size; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vector_map_impl.cc0000664000175000017500000001121212207440367021446 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vector_map_impl.h" #include #include namespace gr { namespace blocks { std::vector get_in_sizeofs(size_t item_size, std::vector in_vlens) { std::vector in_sizeofs; for(unsigned int i = 0; i < in_vlens.size(); i++) { in_sizeofs.push_back(in_vlens[i]*item_size); } return in_sizeofs; } std::vector get_out_sizeofs(size_t item_size, std::vector< std::vector< std::vector > > mapping) { std::vector out_sizeofs; for(unsigned int i = 0; i < mapping.size(); i++) { out_sizeofs.push_back(mapping[i].size()*item_size); } return out_sizeofs; } vector_map::sptr vector_map::make(size_t item_size, std::vector in_vlens, std::vector< std::vector< std::vector > > mapping) { return gnuradio::get_initial_sptr (new vector_map_impl(item_size, in_vlens, mapping)); } vector_map_impl::vector_map_impl(size_t item_size, std::vector in_vlens, std::vector< std::vector< std::vector > > mapping) : sync_block("vector_map", io_signature::makev(in_vlens.size(), in_vlens.size(), get_in_sizeofs(item_size, in_vlens)), io_signature::makev(mapping.size(), mapping.size(), get_out_sizeofs(item_size, mapping))), d_item_size(item_size), d_in_vlens(in_vlens) { set_mapping(mapping); } vector_map_impl::~vector_map_impl() { } void vector_map_impl::set_mapping(std::vector< std::vector< std::vector > > mapping) { // Make sure the contents of the mapping vectors are possible. for(unsigned int i=0; i= d_in_vlens.size()) { throw std::runtime_error("Stream numbers in mapping must be less than the number of input streams."); } if((index < 0) || (index >= d_in_vlens[s])) { throw std::runtime_error ("Indices in mapping must be greater than 0 and less than the input vector lengths."); } } } gr::thread::scoped_lock guard(d_mutex); d_mapping = mapping; } int vector_map_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char **inv = (const char**)&input_items[0]; char **outv = (char**)&output_items[0]; for(unsigned int n = 0; n < (unsigned int)(noutput_items); n++) { for(unsigned int i = 0; i < d_mapping.size(); i++) { unsigned int out_vlen = d_mapping[i].size(); for(unsigned int j = 0; j < out_vlen; j++) { unsigned int s = d_mapping[i][j][0]; unsigned int k = d_mapping[i][j][1]; memcpy(outv[i] + out_vlen*d_item_size*n + d_item_size*j, inv[s] + d_in_vlens[s]*d_item_size*n + k*d_item_size, d_item_size); } } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/copy_impl.h0000664000175000017500000000323112207440367020125 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_COPY_IMPL_H #define INCLUDED_GR_COPY_IMPL_H #include namespace gr { namespace blocks { class copy_impl : public copy { private: size_t d_itemsize; bool d_enabled; public: copy_impl(size_t itemsize); ~copy_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); bool check_topology(int ninputs, int noutputs); void set_enabled(bool enable) { d_enabled = enable; } bool enabled() const { return d_enabled;} int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_COPY_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vector_to_streams_impl.cc0000664000175000017500000000401012207440367023047 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vector_to_streams_impl.h" #include namespace gr { namespace blocks { vector_to_streams::sptr vector_to_streams::make(size_t itemsize, size_t nstreams) { return gnuradio::get_initial_sptr(new vector_to_streams_impl(itemsize, nstreams)); } vector_to_streams_impl::vector_to_streams_impl(size_t itemsize, size_t nstreams) : sync_block ("vector_to_streams", io_signature::make (1, 1, nstreams * itemsize), io_signature::make (nstreams, nstreams, itemsize)) { } int vector_to_streams_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t itemsize = output_signature()->sizeof_stream_item(0); int nstreams = output_items.size(); const char *in = (const char *) input_items[0]; char **outv = (char **) &output_items[0]; for (int i = 0; i < noutput_items; i++){ for (int j = 0; j < nstreams; j++){ memcpy(outv[j], in, itemsize); outv[j] += itemsize; in += itemsize; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/add_const_XX_impl.h.t0000664000175000017500000000255712207440367022004 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { @O_TYPE@ d_k; public: @NAME_IMPL@(@O_TYPE@ k); @O_TYPE@ k() const { return d_k; } void set_k(@O_TYPE@ k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/interleaved_short_to_complex_impl.h0000664000175000017500000000272012207440367025127 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_INTERLEAVED_SHORT_TO_COMPLEX_IMPL_H #define INCLUDED_INTERLEAVED_SHORT_TO_COMPLEX_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API interleaved_short_to_complex_impl : public interleaved_short_to_complex { private: bool d_vector_input; public: interleaved_short_to_complex_impl(bool vector_input=false); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_INTERLEAVED_SHORT_TO_COMPLEX_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/check_lfsr_32k_s_impl.cc0000664000175000017500000001035012207440367022415 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "check_lfsr_32k_s_impl.h" #include #include #include namespace gr { namespace blocks { check_lfsr_32k_s::sptr check_lfsr_32k_s::make() { return gnuradio::get_initial_sptr (new check_lfsr_32k_s_impl()); } check_lfsr_32k_s_impl::check_lfsr_32k_s_impl() : sync_block("check_lfsr_32k", io_signature::make(1, 1, sizeof(short)), io_signature::make(0, 0, 0)), d_state(SEARCHING), d_history(0), d_ntotal(0), d_nright(0), d_runlength(0), d_index(0) { lfsr_32k lfsr; for(int i = 0; i < BUFSIZE; i++) d_buffer[i] = lfsr.next_short(); enter_SEARCHING(); } check_lfsr_32k_s_impl::~check_lfsr_32k_s_impl() { } int check_lfsr_32k_s_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned short *in = (unsigned short*)input_items[0]; for(int i = 0; i < noutput_items; i++) { unsigned short x = in[i]; unsigned short expected; switch(d_state) { case MATCH0: if(x == d_buffer[0]) enter_MATCH1(); break; case MATCH1: if(x == d_buffer[1]) enter_MATCH2(); else enter_MATCH0(); break; case MATCH2: if(x == d_buffer[2]) enter_LOCKED(); else enter_MATCH0(); break; case LOCKED: expected = d_buffer[d_index]; d_index = d_index + 1; if(d_index >= BUFSIZE) d_index = 0; if(x == expected) right(); else { wrong(); log_error(expected, x); if(wrong_three_times()) enter_SEARCHING(); } break; default: abort(); } d_ntotal++; } return noutput_items; } void check_lfsr_32k_s_impl::enter_SEARCHING() { d_state = SEARCHING; wrong(); // reset history wrong(); wrong(); d_runlength = 0; d_index = 0; // reset LFSR to beginning if(0) fprintf(stdout, "check_lfsr_32k: enter_SEARCHING at offset %8ld (0x%08lx)\n", d_ntotal, d_ntotal); enter_MATCH0(); } void check_lfsr_32k_s_impl::enter_MATCH0() { d_state = MATCH0; } void check_lfsr_32k_s_impl::enter_MATCH1() { d_state = MATCH1; } void check_lfsr_32k_s_impl::enter_MATCH2() { d_state = MATCH2; } void check_lfsr_32k_s_impl::enter_LOCKED() { d_state = LOCKED; right(); // setup history right(); right(); d_index = 3; // already matched first 3 items if(0) fprintf(stdout, "check_lfsr_32k: enter_LOCKED at offset %8ld (0x%08lx)\n", d_ntotal, d_ntotal); } void check_lfsr_32k_s_impl::log_error(unsigned short expected, unsigned short actual) { if(0) fprintf(stdout, "check_lfsr_32k: expected %5d (0x%04x) got %5d (0x%04x) offset %8ld (0x%08lx)\n", expected, expected, actual, actual, d_ntotal, d_ntotal); } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/probe_signal_vX_impl.cc.t0000664000175000017500000000343612207440367022703 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @BASE_NAME@::make(size_t size) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(size)); } @NAME_IMPL@::@NAME_IMPL@(size_t size) : sync_block("@BASE_NAME@", io_signature::make(1, 1, size*sizeof(@TYPE@)), io_signature::make(0, 0, 0)), d_level(size, 0), d_size(size) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const @TYPE@ *in = (const @TYPE@ *)input_items[0]; for(size_t i=0; i #include "tag_gate_impl.h" namespace gr { namespace blocks { tag_gate::sptr tag_gate::make(size_t item_size, bool propagate_tags) { return gnuradio::get_initial_sptr (new tag_gate_impl(item_size, propagate_tags)); } tag_gate_impl::tag_gate_impl(size_t item_size, bool propagate_tags) : gr::sync_block("tag_gate", gr::io_signature::make(1, 1, item_size), gr::io_signature::make(1, 1, item_size)), d_item_size(item_size), d_propagate_tags(propagate_tags) { if (!d_propagate_tags) { set_tag_propagation_policy(TPP_DONT); } } tag_gate_impl::~tag_gate_impl() { } void tag_gate_impl::set_propagation(bool propagate_tags) { if (propagate_tags) { set_tag_propagation_policy(TPP_ALL_TO_ALL); } else { set_tag_propagation_policy(TPP_DONT); } } int tag_gate_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; memcpy((void *) out, (void *) in, d_item_size * noutput_items); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/float_array_to_uchar.h0000664000175000017500000000221112207440367022316 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FLOAT_ARRAY_TO_UCHAR_H #define INCLUDED_FLOAT_ARRAY_TO_UCHAR_H #include /*! * convert array of floats to unsigned chars with rounding and saturation. */ BLOCKS_API void float_array_to_uchar (const float *in, unsigned char *out, int nsamples); #endif /* INCLUDED_FLOAT_ARRAY_TO_UCHAR_H */ gnuradio-3.7.2.1/gr-blocks/lib/repack_bits_bb_impl.h0000664000175000017500000000355512207440367022115 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_REPACK_BITS_BB_IMPL_H #define INCLUDED_BLOCKS_REPACK_BITS_BB_IMPL_H #include namespace gr { namespace blocks { class repack_bits_bb_impl : public repack_bits_bb { private: const int d_k; //! Bits on input stream const int d_l; //! Bits on output stream const bool d_packet_mode; int d_in_index; // Current bit of input byte int d_out_index; // Current bit of output byte bool d_align_output; //! true if the output shall be aligned, false if the input shall be aligned protected: int calculate_output_stream_length(const gr_vector_int &ninput_items); public: repack_bits_bb_impl(int k, int l, const std::string &len_tag_key, bool align_output); ~repack_bits_bb_impl(); int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_REPACK_BITS_BB_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vector_sink_X_impl.h.t0000664000175000017500000000277412207440367022245 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: std::vector<@TYPE@> d_data; std::vector d_tags; int d_vlen; public: @NAME_IMPL@(int vlen); ~@NAME_IMPL@(); void reset() { d_data.clear(); } std::vector<@TYPE@> data() const; std::vector tags() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/lfsr_32k_source_s_impl.h0000664000175000017500000000311312207440367022501 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_LFSR_32K_SOURCE_S_IMPL_H #define INCLUDED_GR_LFSR_32K_SOURCE_S_IMPL_H #include #include #include namespace gr { namespace blocks { class lfsr_32k_source_s_impl : public lfsr_32k_source_s { private: static const int BUFSIZE = 2048 - 1; // ensure pattern isn't packet aligned int d_index; short d_buffer[BUFSIZE]; public: lfsr_32k_source_s_impl(); ~lfsr_32k_source_s_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_LFSR_32K_SOURCE_S_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/wavfile_sink_impl.cc0000664000175000017500000001554712207440367022007 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "wavfile_sink_impl.h" #include #include #include #include #include #include #include #include #include // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { wavfile_sink::sptr wavfile_sink::make(const char *filename, int n_channels, unsigned int sample_rate, int bits_per_sample) { return gnuradio::get_initial_sptr (new wavfile_sink_impl(filename, n_channels, sample_rate, bits_per_sample)); } wavfile_sink_impl::wavfile_sink_impl(const char *filename, int n_channels, unsigned int sample_rate, int bits_per_sample) : sync_block("wavfile_sink", io_signature::make(1, n_channels, sizeof(float)), io_signature::make(0, 0, 0)), d_sample_rate(sample_rate), d_nchans(n_channels), d_fp(0), d_new_fp(0), d_updated(false) { if(bits_per_sample != 8 && bits_per_sample != 16) { throw std::runtime_error("Invalid bits per sample (supports 8 and 16)"); } d_bytes_per_sample = bits_per_sample / 8; d_bytes_per_sample_new = d_bytes_per_sample; if(!open(filename)) { throw std::runtime_error("can't open file"); } if(bits_per_sample == 8) { d_max_sample_val = 0xFF; d_min_sample_val = 0; d_normalize_fac = d_max_sample_val/2; d_normalize_shift = 1; } else { d_max_sample_val = 0x7FFF; d_min_sample_val = -0x7FFF; d_normalize_fac = d_max_sample_val; d_normalize_shift = 0; if(bits_per_sample != 16) { fprintf(stderr, "Invalid bits per sample value requested, using 16"); } } } bool wavfile_sink_impl::open(const char* filename) { gr::thread::scoped_lock guard(d_mutex); // we use the open system call to get access to the O_LARGEFILE flag. int fd; if((fd = ::open(filename, O_WRONLY|O_CREAT|O_TRUNC|OUR_O_LARGEFILE|OUR_O_BINARY, 0664)) < 0) { perror(filename); return false; } if(d_new_fp) { // if we've already got a new one open, close it fclose(d_new_fp); d_new_fp = 0; } if((d_new_fp = fdopen (fd, "wb")) == NULL) { perror(filename); ::close(fd); // don't leak file descriptor if fdopen fails. return false; } d_updated = true; if(!wavheader_write(d_new_fp, d_sample_rate, d_nchans, d_bytes_per_sample_new)) { fprintf(stderr, "[%s] could not write to WAV file\n", __FILE__); exit(-1); } return true; } void wavfile_sink_impl::close() { gr::thread::scoped_lock guard(d_mutex); if(!d_fp) return; close_wav(); } void wavfile_sink_impl::close_wav() { unsigned int byte_count = d_sample_count * d_bytes_per_sample; wavheader_complete(d_fp, byte_count); fclose(d_fp); d_fp = NULL; } wavfile_sink_impl::~wavfile_sink_impl() { if(d_new_fp) { fclose(d_new_fp); } close(); } int wavfile_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float **in = (float**)&input_items[0]; int n_in_chans = input_items.size(); short int sample_buf_s; int nwritten; gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this block do_update(); // update: d_fp is reqd if(!d_fp) // drop output on the floor return noutput_items; for(nwritten = 0; nwritten < noutput_items; nwritten++) { for(int chan = 0; chan < d_nchans; chan++) { // Write zeros to channels which are in the WAV file // but don't have any inputs here if(chan < n_in_chans) { sample_buf_s = convert_to_short(in[chan][nwritten]); } else { sample_buf_s = 0; } wav_write_sample(d_fp, sample_buf_s, d_bytes_per_sample); if(feof(d_fp) || ferror(d_fp)) { fprintf(stderr, "[%s] file i/o error\n", __FILE__); close(); exit(-1); } d_sample_count++; } } return nwritten; } short int wavfile_sink_impl::convert_to_short(float sample) { sample += d_normalize_shift; sample *= d_normalize_fac; if(sample > d_max_sample_val) { sample = d_max_sample_val; } else if(sample < d_min_sample_val) { sample = d_min_sample_val; } return (short int)boost::math::iround(sample); } void wavfile_sink_impl::set_bits_per_sample(int bits_per_sample) { gr::thread::scoped_lock guard(d_mutex); if(bits_per_sample == 8 || bits_per_sample == 16) { d_bytes_per_sample_new = bits_per_sample / 8; } } void wavfile_sink_impl::set_sample_rate(unsigned int sample_rate) { gr::thread::scoped_lock guard(d_mutex); d_sample_rate = sample_rate; } int wavfile_sink_impl::bits_per_sample() { return d_bytes_per_sample_new; } unsigned int wavfile_sink_impl::sample_rate() { return d_sample_rate; } void wavfile_sink_impl::do_update() { if(!d_updated) { return; } if(d_fp) { close_wav(); } d_fp = d_new_fp; // install new file pointer d_new_fp = 0; d_sample_count = 0; d_bytes_per_sample = d_bytes_per_sample_new; if(d_bytes_per_sample == 1) { d_max_sample_val = UCHAR_MAX; d_min_sample_val = 0; d_normalize_fac = d_max_sample_val/2; d_normalize_shift = 1; } else if(d_bytes_per_sample == 2) { d_max_sample_val = SHRT_MAX; d_min_sample_val = SHRT_MIN; d_normalize_fac = d_max_sample_val; d_normalize_shift = 0; } d_updated = false; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_interleaved_short_impl.h0000664000175000017500000000262112207440367025127 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_INTERLEAVED_SHORT_IMPL_H #define INCLUDED_COMPLEX_TO_INTERLEAVED_SHORT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_interleaved_short_impl : public complex_to_interleaved_short { public: complex_to_interleaved_short_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_INTERLEAVED_SHORT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/keep_one_in_n_impl.cc0000664000175000017500000000617112207440367022107 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "keep_one_in_n_impl.h" #include namespace gr { namespace blocks { keep_one_in_n::sptr keep_one_in_n::make(size_t itemsize, int n) { return gnuradio::get_initial_sptr(new keep_one_in_n_impl(itemsize, n)); } keep_one_in_n_impl::keep_one_in_n_impl(size_t itemsize, int n) : block("keep_one_in_n", io_signature::make (1, 1, itemsize), io_signature::make (1, 1, itemsize)), d_count(n) { // To avoid bad behavior with using set_relative_rate in this block with // VERY large values of n, we will keep track of things ourselves. Using // this to turn off automatic tag propagation, which will be handled // locally in general_work(). set_tag_propagation_policy(TPP_DONT); set_n(n); } void keep_one_in_n_impl::set_n(int n) { if (n < 1) n = 1; d_n = n; d_count = n; // keep our internal understanding of the relative rate of this block // don't set the relative rate, though, and we will handle our own // tag propagation. d_decim_rate = 1.0/(float)d_n; } int keep_one_in_n_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char *) input_items[0]; char *out = (char *) output_items[0]; size_t item_size = input_signature ()->sizeof_stream_item (0); int ni = 0; int no = 0; while (ni < ninput_items[0] && no < noutput_items){ d_count--; if (d_count <= 0){ memcpy (out, in, item_size); // copy 1 item out += item_size; no++; d_count = d_n; } in += item_size; ni++; } // Because we have set TPP_DONT, we have to propagate the tags here manually. // Adjustment of the tag sample value is done using the float d_decim_rate. std::vector tags; std::vector::iterator t; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0)+ni); for(t = tags.begin(); t != tags.end(); t++) { tag_t new_tag = *t; new_tag.offset *= d_decim_rate; add_item_tag(0, new_tag); } consume_each (ni); return no; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/or_XX_impl.h.t0000664000175000017500000000242312207440367020456 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/qa_set_msg_handler.h0000664000175000017500000000230212207440367021747 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_SET_MSG_HANDLER_H #define INCLUDED_QA_SET_MSG_HANDLER_H #include #include #include class qa_set_msg_handler : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_set_msg_handler); CPPUNIT_TEST(t0); CPPUNIT_TEST_SUITE_END(); private: void t0(); }; #endif /* INCLUDED_QA_SET_MSG_HANDLER_H */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_XX_impl.cc.t0000664000175000017500000000373612207440367023271 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(@O_TYPE@ k) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(k)); } @NAME_IMPL@::@NAME_IMPL@(@O_TYPE@ k) : sync_block ("@NAME@", io_signature::make (1, 1, sizeof (@I_TYPE@)), io_signature::make (1, 1, sizeof (@O_TYPE@))), d_k(k) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *) input_items[0]; @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int size = noutput_items; while (size >= 8){ *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; *optr++ = *iptr++ * d_k; size -= 8; } while (size-- > 0) *optr++ = *iptr++ * d_k; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/stream_to_tagged_stream_impl.h0000664000175000017500000000321412237515111024030 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_STREAM_TO_TAGGED_STREAM_IMPL_H #define INCLUDED_BLOCKS_STREAM_TO_TAGGED_STREAM_IMPL_H #include namespace gr { namespace blocks { class stream_to_tagged_stream_impl : public stream_to_tagged_stream { private: size_t d_itemsize; unsigned d_packet_len; pmt::pmt_t d_packet_len_pmt; pmt::pmt_t d_len_tag_key; uint64_t d_next_tag_pos; public: stream_to_tagged_stream_impl(size_t itemsize, int vlen, unsigned packet_len, const std::string &tag_len_key); ~stream_to_tagged_stream_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_STREAM_TO_TAGGED_STREAM_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/add_ff_impl.cc0000664000175000017500000000411012245466767020527 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "add_ff_impl.h" #include #include namespace gr { namespace blocks { add_ff::sptr add_ff::make(size_t vlen) { return gnuradio::get_initial_sptr(new add_ff_impl(vlen)); } add_ff_impl::add_ff_impl(size_t vlen) : sync_block("add_ff", io_signature::make (1, -1, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } int add_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *out = (float *) output_items[0]; int noi = d_vlen*noutput_items; memcpy(out, input_items[0], noi*sizeof(float)); if(is_unaligned()) { for(size_t i = 1; i < input_items.size(); i++) volk_32f_x2_add_32f_u(out, out, (const float*)input_items[i], noi); } else { for(size_t i = 1; i < input_items.size(); i++) volk_32f_x2_add_32f_a(out, out, (const float*)input_items[i], noi); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/throttle_impl.h0000664000175000017500000000312312207440367021020 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005-2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_THROTTLE_IMPL_H #define INCLUDED_GR_THROTTLE_IMPL_H #include namespace gr { namespace blocks { class throttle_impl : public throttle { private: boost::system_time d_start; size_t d_itemsize; uint64_t d_total_samples; double d_samps_per_tick, d_samps_per_us; public: throttle_impl(size_t itemsize, double samples_per_sec); ~throttle_impl(); void setup_rpc(); void set_sample_rate(double rate); double sample_rate() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_THROTTLE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/max_XX_impl.cc.t0000664000175000017500000000416612207440367020767 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block("@BASE_NAME@", io_signature::make(1, -1, vlen*sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_vlen(vlen) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *)output_items[0]; int ninputs = input_items.size(); for(int i = 0; i < noutput_items; i++) { @I_TYPE@ max = ((@I_TYPE@ *)input_items[0])[i*d_vlen]; for(int j = 0; j < (int)d_vlen; j++ ) { for(int k = 0; k < ninputs; k++) { if(((@I_TYPE@ *)input_items[k])[i*d_vlen + j] > max) { max = ((@I_TYPE@*)input_items[k])[i*d_vlen + j]; } } } *optr++ = (@O_TYPE@)max; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/threshold_ff_impl.h0000664000175000017500000000341012207440367021621 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_THRESHOLD_FF_IMPL_H #define INCLUDED_GR_THRESHOLD_FF_IMPL_H #include namespace gr { namespace blocks { class threshold_ff_impl : public threshold_ff { private: float d_lo, d_hi; // the constant float d_last_state; public: threshold_ff_impl(float lo, float hi, float initial_state=0); ~threshold_ff_impl(); float lo() const { return d_lo; } void set_lo(float lo) { d_lo = lo; } float hi() const { return d_hi; } void set_hi(float hi) { d_hi = hi; } float last_state() const { return d_last_state; } void set_last_state(float last_state) { d_last_state = last_state; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_THRESHOLD_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vector_source_X_impl.h.t0000664000175000017500000000335312207440367022573 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: std::vector<@TYPE@> d_data; bool d_repeat; unsigned int d_offset; int d_vlen; bool d_settags; std::vector d_tags; unsigned int d_tagpos; public: @NAME_IMPL@(const std::vector<@TYPE@> &data, bool repeat, int vlen, const std::vector &tags); ~@NAME_IMPL@(); void rewind() { d_offset=0; } void set_data(const std::vector<@TYPE@> &data, const std::vector &tags); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/probe_signal_X_impl.h.t0000664000175000017500000000255112207440367022354 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: @TYPE@ d_level; public: @NAME_IMPL@(); ~@NAME_IMPL@(); @TYPE@ level() const { return d_level; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/bin_statistics_f_impl.h0000664000175000017500000000465512207440367022515 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_BIN_STATISTICS_F_IMPL_H #define INCLUDED_GR_BIN_STATISTICS_F_IMPL_H #include #include #include #include namespace gr { namespace blocks { class bin_statistics_f_impl : public bin_statistics_f { private: enum state_t { ST_INIT, ST_TUNE_DELAY, ST_DWELL_DELAY }; size_t d_vlen; msg_queue::sptr d_msgq; feval_dd *d_tune; size_t d_tune_delay; size_t d_dwell_delay; double d_center_freq; state_t d_state; size_t d_delay; // nsamples remaining to state transition void enter_init(); void enter_tune_delay(); void enter_dwell_delay(); void leave_dwell_delay(); protected: std::vector d_max; // per bin maxima size_t vlen() const { return d_vlen; } double center_freq() const { return d_center_freq; } msg_queue::sptr msgq() const { return d_msgq; } virtual void reset_stats(); virtual void accrue_stats(const float *input); virtual void send_stats(); public: bin_statistics_f_impl(unsigned int vlen, msg_queue::sptr msgq, feval_dd *tune, size_t tune_delay, size_t dwell_delay); ~bin_statistics_f_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_BIN_STATISTICS_F_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vco_c_impl.cc0000664000175000017500000000402212207702530020372 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vco_c_impl.h" #include #include namespace gr { namespace blocks { vco_c::sptr vco_c::make(double sampling_rate, double sensitivity, double amplitude) { return gnuradio::get_initial_sptr (new vco_c_impl(sampling_rate, sensitivity, amplitude)); } vco_c_impl::vco_c_impl(double sampling_rate, double sensitivity, double amplitude) : sync_block("vco_c", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(gr_complex))), d_sampling_rate(sampling_rate), d_sensitivity(sensitivity), d_amplitude(amplitude), d_k(d_sensitivity/d_sampling_rate) { } vco_c_impl::~vco_c_impl() { } int vco_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *input = (const float*)input_items[0]; gr_complex *output = (gr_complex*)output_items[0]; d_vco.sincos(output, input, noutput_items, d_k, d_amplitude); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/endian_swap_impl.cc0000664000175000017500000000634712245466767021632 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "endian_swap_impl.h" #include #include namespace gr { namespace blocks { endian_swap::sptr endian_swap::make(size_t item_size_bytes) { return gnuradio::get_initial_sptr (new endian_swap_impl(item_size_bytes)); } endian_swap_impl::endian_swap_impl (size_t item_size_bytes) : sync_block("endian_swap_impl", io_signature::make(1, 1, item_size_bytes), io_signature::make(1, 1, item_size_bytes)) { const int alignment_multiple = volk_get_alignment(); set_alignment(std::max(1, alignment_multiple)); } endian_swap_impl::~endian_swap_impl() { } int endian_swap_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char*)input_items[0]; char *out = (char*)output_items[0]; int nbytes(output_signature()->sizeof_stream_item(0)); if(is_unaligned()) { switch(nbytes){ case 1: memcpy(out,in,noutput_items); break; case 2: memcpy(out,in,2*noutput_items); volk_16u_byteswap_u((uint16_t*)out,noutput_items); break; case 4: memcpy(out,in,4*noutput_items); volk_32u_byteswap_u((uint32_t*)out,noutput_items); break; case 8: memcpy(out,in,8*noutput_items); volk_64u_byteswap_u((uint64_t*)out,noutput_items); break; default: throw std::runtime_error("itemsize is not valid for endian_swap!"); } } else { switch(nbytes) { case 1: memcpy(out,in,noutput_items); break; case 2: memcpy(out,in,2*noutput_items); volk_16u_byteswap_a((uint16_t*)out,noutput_items); break; case 4: memcpy(out,in,4*noutput_items); volk_32u_byteswap_a((uint32_t*)out,noutput_items); break; case 8: memcpy(out,in,8*noutput_items); volk_64u_byteswap_a((uint64_t*)out,noutput_items); break; default: throw std::runtime_error("itemsize is not valid for endian_swap!"); } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/gnuradio-blocks.rc.in0000664000175000017500000000332512207440367022003 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-blocks" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-blocks.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-blocks.dll" VALUE "ProductName", "gnuradio-blocks" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-blocks/lib/unpack_k_bits_bb_impl.h0000664000175000017500000000272212207440367022436 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UNPACK_K_BITS_BB_IMPL_H #define INCLUDED_GR_UNPACK_K_BITS_BB_IMPL_H #include namespace gr { namespace blocks { class unpack_k_bits_bb_impl : public unpack_k_bits_bb { private: unsigned d_k; // number of relevent bits to unpack into k output bytes public: unpack_k_bits_bb_impl(unsigned k); ~unpack_k_bits_bb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_UNPACK_K_BITS_BB_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vco_f_impl.h0000664000175000017500000000276412207440367020261 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_VCO_F_IMPL_H #define INCLUDED_GR_VCO_F_IMPL_H #include #include namespace gr { namespace blocks { class vco_f_impl : public vco_f { private: double d_sampling_rate; double d_sensitivity; double d_amplitude; double d_k; gr::fxpt_vco d_vco; public: vco_f_impl(double sampling_rate, double sensitivity, double amplitude); ~vco_f_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_VCO_F_H */ gnuradio-3.7.2.1/gr-blocks/lib/message_sink_impl.cc0000664000175000017500000001062512207440367021766 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "message_sink_impl.h" #include #include #include #include #include #include #include #include namespace gr { namespace blocks { message_sink::sptr message_sink::make(size_t itemsize, msg_queue::sptr msgq, bool dont_block) { return gnuradio::get_initial_sptr (new message_sink_impl(itemsize, msgq, dont_block)); } message_sink::sptr message_sink::make(size_t itemsize, msg_queue::sptr msgq, bool dont_block, const std::string& lengthtagname) { return gnuradio::get_initial_sptr (new message_sink_impl(itemsize, msgq, dont_block, lengthtagname)); } message_sink_impl::message_sink_impl(size_t itemsize, msg_queue::sptr msgq, bool dont_block) : sync_block("message_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_msgq(msgq), d_dont_block(dont_block), d_tags(false), d_items_read(0) { } message_sink_impl::message_sink_impl(size_t itemsize, msg_queue::sptr msgq, bool dont_block, const std::string& lengthtagname) : sync_block("message_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_msgq(msgq), d_dont_block(dont_block), d_tags(true), d_lengthtagname(lengthtagname), d_items_read(0) { } message_sink_impl::~message_sink_impl() { } int message_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char *) input_items[0]; if (d_tags) { long packet_length = 0; std::vector tags; this->get_tags_in_range(tags, 0, d_items_read, d_items_read+1); //const size_t ninput_items = noutput_items; //assumption for sync block, this can change for (unsigned int i = 0; i < tags.size(); i++) { if (pmt::symbol_to_string(tags[i].key) == d_lengthtagname) { packet_length = pmt::to_long(tags[i].value); } } assert(packet_length != 0); // FIXME run this multiple times if input_items >= N * packet_length if (noutput_items >= packet_length ) { // If the message queue is full we drop the packet. if (!d_msgq->full_p()) { message::sptr msg = message::make(0, // msg type d_itemsize, // arg1 for other end packet_length, // arg2 for other end (redundant) packet_length * d_itemsize); // len of msg memcpy(msg->msg(), in, packet_length * d_itemsize); d_msgq->handle(msg); // send it } d_items_read += packet_length; return packet_length; } else { return 0; } } else { // If the queue if full we drop all the data we got. if (!d_msgq->full_p()) { // build a message to hold whatever we've got message::sptr msg = message::make(0, // msg type d_itemsize, // arg1 for other end noutput_items, // arg2 for other end (redundant) noutput_items * d_itemsize); // len of msg memcpy(msg->msg(), in, noutput_items * d_itemsize); d_msgq->handle(msg); // send it } return noutput_items; } } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_arg_impl.cc0000664000175000017500000000406412207440367022320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_arg_impl.h" #include #include #include namespace gr { namespace blocks { complex_to_arg::sptr complex_to_arg::make(size_t vlen) { return gnuradio::get_initial_sptr(new complex_to_arg_impl(vlen)); } complex_to_arg_impl::complex_to_arg_impl(size_t vlen) : sync_block("complex_to_arg", io_signature::make (1, 1, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int complex_to_arg_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; float *out = (float *) output_items[0]; int noi = noutput_items * d_vlen; // The fast_atan2f is faster than Volk for (int i = 0; i < noi; i++){ // out[i] = std::arg (in[i]); out[i] = gr::fast_atan2f(in[i]); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_c_impl.h0000664000175000017500000000402712207702530022574 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE2_C_IMPL_H #define INCLUDED_CTRLPORT_PROBE2_C_IMPL_H #include #include #include namespace gr { namespace blocks { class ctrlport_probe2_c_impl : public ctrlport_probe2_c { private: std::string d_id; std::string d_desc; size_t d_len; unsigned int d_disp_mask; boost::shared_mutex mutex_buffer; mutable boost::mutex mutex_notify; boost::condition_variable condition_buffer_ready; std::vector d_buffer; public: ctrlport_probe2_c_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask); ~ctrlport_probe2_c_impl(); void setup_rpc(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); std::vector get(); void set_length(int len); int length() const; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_PROBE2_C_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/annotator_raw_impl.h0000664000175000017500000000314712207440367022037 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ANNOTATOR_RAW_IMPL_H #define INCLUDED_GR_ANNOTATOR_RAW_IMPL_H #include #include namespace gr { namespace blocks { class annotator_raw_impl : public annotator_raw { private: size_t d_itemsize; std::vector d_queued_tags; gr::thread::mutex d_mutex; public: annotator_raw_impl(size_t sizeof_stream_item); ~annotator_raw_impl(); // insert a tag to be added void add_tag(uint64_t offset, pmt::pmt_t key, pmt::pmt_t val); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ANNOTATOR_RAW_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/interleaved_short_array_to_complex.cc0000664000175000017500000000223312207440367025441 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "interleaved_short_array_to_complex.h" #include #include void interleaved_short_array_to_complex (const short *in, gr_complex *out, int nsamples) { assert (nsamples % 2 == 0); volk_16i_s32f_convert_32f_u( (float*)out, (const int16_t*) in, 1, nsamples ); } gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_vXX_impl.h.t0000664000175000017500000000265012207440367023313 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { std::vector<@O_TYPE@> d_k; public: @NAME_IMPL@(std::vector<@O_TYPE@> k); std::vector<@O_TYPE@> k() const { return d_k; } void set_k(std::vector<@O_TYPE@> k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_float_impl.h0000664000175000017500000000253612207440367022520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_FLOAT_IMPL_H #define INCLUDED_COMPLEX_TO_FLOAT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_float_impl : public complex_to_float { size_t d_vlen; public: complex_to_float_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_FLOAT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/argmax_XX_impl.h.t0000664000175000017500000000247612207440367021325 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: size_t d_vlen; public: @NAME_IMPL@(size_t vlen); ~@NAME_IMPL@(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/tcp_connection.cc0000664000175000017500000000516012207440367021300 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "tcp_connection.h" #include #include namespace gr { namespace blocks { tcp_connection::sptr tcp_connection::make(boost::asio::io_service& io_service) { return sptr(new tcp_connection(io_service)); } tcp_connection::tcp_connection(boost::asio::io_service& io_service) : d_socket(io_service) { } void tcp_connection::send(pmt::pmt_t vector) { size_t len = pmt::length(vector); size_t offset(0); boost::array txbuf; memcpy(&txbuf[0], pmt::uniform_vector_elements(vector, offset), len); boost::asio::async_write(d_socket, boost::asio::buffer(txbuf, len), boost::bind(&tcp_connection::handle_write, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void tcp_connection::start(gr::basic_block *block) { d_block = block; d_socket.async_read_some(boost::asio::buffer(d_buf), boost::bind(&tcp_connection::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void tcp_connection::handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { pmt::pmt_t vector = pmt::init_u8vector(bytes_transferred, (const uint8_t*)&d_buf[0]); pmt::pmt_t pdu = pmt::cons( pmt::PMT_NIL, vector); d_block->message_port_pub(PDU_PORT_ID, pdu); d_socket.async_read_some(boost::asio::buffer(d_buf), boost::bind(&tcp_connection::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/pdu_to_tagged_stream_impl.h0000664000175000017500000000300112207440367023326 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PDU_TO_TAGGED_STREAM_IMPL_H #define INCLUDED_PDU_TO_TAGGED_STREAM_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API pdu_to_tagged_stream_impl : public pdu_to_tagged_stream { size_t d_itemsize; pdu::vector_type d_type; std::vector d_remain; pmt::pmt_t d_tag; public: pdu_to_tagged_stream_impl(pdu::vector_type type, const std::string& lengthtagname="packet_len"); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-blocks/lib/complex_to_float_impl.cc0000664000175000017500000000423312207440367022652 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_float_impl.h" #include #include namespace gr { namespace blocks { complex_to_float::sptr complex_to_float::make(size_t vlen) { return gnuradio::get_initial_sptr(new complex_to_float_impl(vlen)); } complex_to_float_impl::complex_to_float_impl(size_t vlen) : sync_block("complex_to_float", io_signature::make (1, 1, sizeof(gr_complex)*vlen), io_signature::make (1, 2, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int complex_to_float_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; float *out0 = (float *) output_items[0]; float* out1; int noi = noutput_items * d_vlen; switch (output_items.size ()){ case 1: volk_32fc_deinterleave_real_32f(out0, in, noi); break; case 2: out1 = (float *) output_items[1]; volk_32fc_deinterleave_32f_x2(out0, out1, in, noi); break; default: abort (); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/add_ff_impl.h0000664000175000017500000000245512207440367020365 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_ADD_FF_IMPL_H #define INCLUDED_BLOCKS_ADD_FF_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API add_ff_impl : public add_ff { size_t d_vlen; public: add_ff_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_ADD_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/count_bits.cc0000664000175000017500000000371612207440367020451 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2003,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include /* * these are slow and obvious. If you need something faster, fix these * * Can probably replace with VOLK's popcount */ namespace gr { namespace blocks { unsigned int count_bits8(unsigned int x) { int count = 0; for(int i = 0; i < 8; i++) { if(x & (1 << i)) count++; } return count; } unsigned int count_bits16(unsigned int x) { int count = 0; for(int i = 0; i < 16; i++) { if(x & (1 << i)) count++; } return count; } unsigned int count_bits32(unsigned int x) { unsigned res = (x & 0x55555555) + ((x >> 1) & 0x55555555); res = (res & 0x33333333) + ((res >> 2) & 0x33333333); res = (res & 0x0F0F0F0F) + ((res >> 4) & 0x0F0F0F0F); res = (res & 0x00FF00FF) + ((res >> 8) & 0x00FF00FF); return (res & 0x0000FFFF) + ((res >> 16) & 0x0000FFFF); } unsigned int count_bits64(unsigned long long x) { return count_bits32((x >> 32) & 0xffffffff) + \ count_bits32(x & 0xffffffff); } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_meta_source_impl.cc0000664000175000017500000002525712207440367022632 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_meta_source_impl.h" #include #include #include #include #include #include #include // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { file_meta_source::sptr file_meta_source::make(const std::string &filename, bool repeat, bool detached_header, const std::string &hdr_filename) { return gnuradio::get_initial_sptr (new file_meta_source_impl(filename, repeat, detached_header, hdr_filename)); } file_meta_source_impl::file_meta_source_impl(const std::string &filename, bool repeat, bool detached_header, const std::string &hdr_filename) : sync_block("file_meta_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, 1)), d_itemsize(0), d_samp_rate(0), d_seg_size(0), d_updated(false), d_repeat(repeat) { d_fp = 0; d_new_fp = 0; d_hdr_fp = 0; d_new_hdr_fp = 0; if(detached_header == true) { d_state = STATE_DETACHED; } else d_state = STATE_INLINE; if(!open(filename, hdr_filename)) throw std::runtime_error("file_meta_source: can't open file\n"); do_update(); pmt::pmt_t hdr = pmt::PMT_NIL, extras = pmt::PMT_NIL; if(read_header(hdr, extras)) { parse_header(hdr, 0, d_tags); parse_extras(extras, 0, d_tags); } else throw std::runtime_error("file_meta_source: could not read header.\n"); // Set output signature based on itemsize info in header set_output_signature(io_signature::make(1, 1, d_itemsize)); } file_meta_source_impl::~file_meta_source_impl() { close(); if(d_fp) { fclose(d_fp); d_fp = 0; } if(d_state == STATE_DETACHED) { if(d_hdr_fp) { fclose(d_hdr_fp); d_hdr_fp = 0; } } } bool file_meta_source_impl::read_header(pmt::pmt_t &hdr, pmt::pmt_t &extras) { // Select which file handle to read from. FILE *fp; if(d_state == STATE_DETACHED) fp = d_hdr_fp; else fp = d_fp; size_t ret; size_t size = 0; std::string str; char *hdr_buffer = new char[METADATA_HEADER_SIZE]; while(size < METADATA_HEADER_SIZE) { ret = fread(&hdr_buffer[size], sizeof(char), METADATA_HEADER_SIZE-size, fp); if(ret == 0) { delete [] hdr_buffer; if(feof(fp)) return false; else { std::stringstream s; s << "file_meta_source: error occurred extracting header: " << strerror(errno) << std::endl; throw std::runtime_error(s.str()); } } size += ret; } // Convert to string or the char array gets confused by the \0 str.insert(0, hdr_buffer, METADATA_HEADER_SIZE); hdr = pmt::deserialize_str(str); delete [] hdr_buffer; uint64_t seg_start, extra_len; pmt::pmt_t r, dump; if(pmt::dict_has_key(hdr, pmt::string_to_symbol("strt"))) { r = pmt::dict_ref(hdr, pmt::string_to_symbol("strt"), dump); seg_start = pmt::to_uint64(r); extra_len = seg_start - METADATA_HEADER_SIZE; } if(extra_len > 0) { size = 0; hdr_buffer = new char[extra_len]; while(size < extra_len) { ret = fread(&hdr_buffer[size], sizeof(char), extra_len-size, fp); if(ret == 0) { delete [] hdr_buffer; if(feof(fp)) return false; else { std::stringstream s; s << "file_meta_source: error occurred extracting extras: " << strerror(errno) << std::endl; throw std::runtime_error(s.str()); } } size += ret; } str.clear(); str.insert(0, hdr_buffer, extra_len); extras = pmt::deserialize_str(str); delete [] hdr_buffer; } return true; } void file_meta_source_impl::parse_header(pmt::pmt_t hdr, uint64_t offset, std::vector &tags) { pmt::pmt_t r, key; // GET SAMPLE RATE key = pmt::string_to_symbol("rx_rate"); if(pmt::dict_has_key(hdr, key)) { r = pmt::dict_ref(hdr, key, pmt::PMT_NIL); d_samp_rate = pmt::to_double(r); tag_t t; t.offset = offset; t.key = key; t.value = r; t.srcid = alias_pmt(); tags.push_back(t); } else { throw std::runtime_error("file_meta_source: Could not extract sample rate.\n"); } // GET TIME STAMP key = pmt::string_to_symbol("rx_time"); if(pmt::dict_has_key(hdr, key)) { d_time_stamp = pmt::dict_ref(hdr, key, pmt::PMT_NIL); tag_t t; t.offset = offset; t.key = key; t.value = d_time_stamp; t.srcid = alias_pmt(); tags.push_back(t); } else { throw std::runtime_error("file_meta_source: Could not extract time stamp.\n"); } // GET ITEM SIZE OF DATA if(pmt::dict_has_key(hdr, pmt::string_to_symbol("size"))) { d_itemsize = pmt::to_long(pmt::dict_ref(hdr, pmt::string_to_symbol("size"), pmt::PMT_NIL)); } else { throw std::runtime_error("file_meta_source: Could not extract item size.\n"); } // GET SEGMENT SIZE if(pmt::dict_has_key(hdr, pmt::string_to_symbol("bytes"))) { d_seg_size = pmt::to_uint64(pmt::dict_ref(hdr, pmt::string_to_symbol("bytes"), pmt::PMT_NIL)); // Convert from bytes to items d_seg_size /= d_itemsize; } else { throw std::runtime_error("file_meta_source: Could not extract segment size.\n"); } } void file_meta_source_impl::parse_extras(pmt::pmt_t extras, uint64_t offset, std::vector &tags) { pmt::pmt_t item, key, val; size_t nitems = pmt::length(extras); for(size_t i = 0; i < nitems; i++) { item = pmt::nth(i, extras); key = pmt::car(item); val = pmt::cdr(item); tag_t t; t.offset = offset; t.key = key; t.value = val; t.srcid = alias_pmt(); tags.push_back(t); } } bool file_meta_source_impl::open(const std::string &filename, const std::string &hdr_filename) { bool ret = true; if(d_state == STATE_DETACHED) { std::string s; if(hdr_filename == "") s = filename + ".hdr"; else s = hdr_filename; ret = _open(&d_new_hdr_fp, s.c_str()); } ret = ret && _open(&d_new_fp, filename.c_str()); d_updated = true; return ret; } bool file_meta_source_impl::_open(FILE **fp, const char *filename) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function bool ret = true; int fd; if((fd = ::open(filename, O_RDONLY|OUR_O_LARGEFILE|OUR_O_BINARY)) < 0) { perror(filename); return false; } if(*fp) { // if we've already got a new one open, close it fclose(*fp); fp = 0; } if((*fp = fdopen(fd, "rb")) == NULL) { perror(filename); ::close(fd); // don't leak file descriptor if fdopen fails. } ret = fp != 0; return ret; } void file_meta_source_impl::close() { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function if(d_state == STATE_DETACHED) { if(d_new_hdr_fp) { fclose(d_new_hdr_fp); d_new_hdr_fp = 0; } } if(d_new_fp) { fclose(d_new_fp); d_new_fp = 0; } d_updated = true; } void file_meta_source_impl::do_update() { if(d_updated) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this block if(d_state == STATE_DETACHED) { if(d_hdr_fp) fclose(d_hdr_fp); d_hdr_fp = d_new_hdr_fp; // install new file pointer d_new_hdr_fp = 0; } if(d_fp) fclose(d_fp); d_fp = d_new_fp; // install new file pointer d_new_fp = 0; d_updated = false; } } int file_meta_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // We've reached the end of a segment; parse the next header and get // the new tags to send and set the next segment size. if(d_seg_size == 0) { pmt::pmt_t hdr=pmt::PMT_NIL, extras=pmt::PMT_NIL; if(read_header(hdr, extras)) { parse_header(hdr, nitems_written(0), d_tags); parse_extras(extras, nitems_written(0), d_tags); } else { if(!d_repeat) return -1; else { if(fseek(d_fp, 0, SEEK_SET) == -1) { std::stringstream s; s << "[" << __FILE__ << "]" << " fseek failed" << std::endl; throw std::runtime_error(s.str()); } } } } char *out = (char*)output_items[0]; int i; int seg_size = std::min(noutput_items, (int)d_seg_size); int size = seg_size; do_update(); // update d_fp is reqd if(d_fp == NULL) throw std::runtime_error("work with file not open"); // Push all tags onto the stream and remove them from the vector while(!d_tags.empty()) { add_item_tag(0, d_tags.back()); d_tags.pop_back(); } gr::thread::scoped_lock lock(d_mutex); // hold for the rest of this function while(size) { i = fread(out, d_itemsize, size, d_fp); size -= i; d_seg_size -= i; out += i * d_itemsize; if(size == 0) // done break; if(i > 0) // short read, try again continue; // We got a zero from fread. This is either EOF or error. In // any event, if we're in repeat mode, seek back to the beginning // of the file and try again, else break if(!d_repeat) break; if(fseek(d_fp, 0, SEEK_SET) == -1) { std::stringstream s; s << "[" << __FILE__ << "]" << " fseek failed" << std::endl; throw std::runtime_error(s.str()); } } if(size > 0) { // EOF or error if(size == seg_size) // we didn't read anything; say we're done return -1; return seg_size - size; // else return partial result } return seg_size; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_s_impl.cc0000664000175000017500000001204212207702530022746 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe2_s_impl.h" #include namespace gr { namespace blocks { ctrlport_probe2_s::sptr ctrlport_probe2_s::make(const std::string &id, const std::string &desc, int len, unsigned disp_mask) { return gnuradio::get_initial_sptr (new ctrlport_probe2_s_impl(id, desc, len, disp_mask)); } ctrlport_probe2_s_impl::ctrlport_probe2_s_impl(const std::string &id, const std::string &desc, int len, unsigned disp_mask) : sync_block("probe2_s", io_signature::make(1, 1, sizeof(short)), io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_len(len), d_disp_mask(disp_mask) { set_length(len); } ctrlport_probe2_s_impl::~ctrlport_probe2_s_impl() { } void ctrlport_probe2_s_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = d_len; } // boost::shared_mutex mutex_buffer; // mutable boost::mutex mutex_notify; // boost::condition_variable condition_buffer_ready; std::vector ctrlport_probe2_s_impl::get() { mutex_buffer.lock(); d_buffer.clear(); mutex_buffer.unlock(); // wait for condition boost::mutex::scoped_lock lock(mutex_notify); condition_buffer_ready.wait(lock); mutex_buffer.lock(); std::vector buf_copy = d_buffer; assert(buf_copy.size() == d_len); mutex_buffer.unlock(); return buf_copy; } void ctrlport_probe2_s_impl::set_length(int len) { if(len > 8191) { std::cerr << "probe2_s: length " << len << " exceeds maximum buffer size of 8191" << std::endl; len = 8191; } d_len = len; d_buffer.reserve(d_len); } int ctrlport_probe2_s_impl::length() const { return (int)d_len; } int ctrlport_probe2_s_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; // copy samples to get buffer if we need samples mutex_buffer.lock(); if(d_buffer.size() < d_len) { // copy smaller of remaining buffer space and num inputs to work() int num_copy = std::min( (int)(d_len - d_buffer.size()), noutput_items ); // TODO: convert this to a copy operator for speed... for(int i = 0; i < num_copy; i++) { d_buffer.push_back(in[i]); } // notify the waiting get() if we fill up the buffer if(d_buffer.size() == d_len) { condition_buffer_ready.notify_one(); } } mutex_buffer.unlock(); return noutput_items; } void ctrlport_probe2_s_impl::setup_rpc() { #ifdef GR_CTRLPORT int len = static_cast(d_len); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), d_id.c_str(), &ctrlport_probe2_s::get, pmt::mp(-32768), pmt::mp(32767), pmt::mp(0), "volts", d_desc.c_str(), RPC_PRIVLVL_MIN, d_disp_mask))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "length", &ctrlport_probe2_s::length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "get vector length", RPC_PRIVLVL_MIN, DISPNULL))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "length", &ctrlport_probe2_s::set_length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "set vector length", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/keep_m_in_n_impl.h0000664000175000017500000000323312236015267021417 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_KEEP_M_IN_N_IMPL_H #define INCLUDED_KEEP_M_IN_N_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API keep_m_in_n_impl : public keep_m_in_n { int d_m; int d_n; int d_offset; int d_itemsize; void forecast(int noutput_items, gr_vector_int &ninput_items_required); public: keep_m_in_n_impl(size_t itemsize, int m, int n, int offset); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void set_m(int m) { d_m = m; } void set_n(int n) { d_n = n; } void set_offset(int offset) { d_offset = offset; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_KEEP_M_IN_N_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/lfsr_32k_source_s_impl.cc0000664000175000017500000000422312207440367022642 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "lfsr_32k_source_s_impl.h" #include #include namespace gr { namespace blocks { lfsr_32k_source_s::sptr lfsr_32k_source_s::make() { return gnuradio::get_initial_sptr (new lfsr_32k_source_s_impl()); } lfsr_32k_source_s_impl::lfsr_32k_source_s_impl() : sync_block("lfsr_32k_source_s", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(short))), d_index(0) { lfsr_32k lfsr; for(int i = 0; i < BUFSIZE; i++) d_buffer[i] = lfsr.next_short(); } lfsr_32k_source_s_impl::~lfsr_32k_source_s_impl() { } int lfsr_32k_source_s_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { short *out = (short*)output_items[0]; short *buf = d_buffer; int index = d_index; for(int i = 0; i < noutput_items; i++) { out[i] = buf[index]; // index = (index + 1) & (BUFSIZE - 1); index = index + 1; if(index >= BUFSIZE) index = 0; } d_index = index; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_c_impl.cc0000664000175000017500000001214312207702530022730 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe2_c_impl.h" #include namespace gr { namespace blocks { ctrlport_probe2_c::sptr ctrlport_probe2_c::make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) { return gnuradio::get_initial_sptr (new ctrlport_probe2_c_impl(id, desc, len, disp_mask)); } ctrlport_probe2_c_impl::ctrlport_probe2_c_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) : sync_block("probe2_c", io_signature::make(1, 1, sizeof(gr_complex)), io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_len(len), d_disp_mask(disp_mask) { set_length(len); } ctrlport_probe2_c_impl::~ctrlport_probe2_c_impl() { } void ctrlport_probe2_c_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = d_len; } // boost::shared_mutex mutex_buffer; // mutable boost::mutex mutex_notify; // boost::condition_variable condition_buffer_ready; std::vector ctrlport_probe2_c_impl::get() { mutex_buffer.lock(); d_buffer.clear(); mutex_buffer.unlock(); // wait for condition boost::mutex::scoped_lock lock(mutex_notify); condition_buffer_ready.wait(lock); mutex_buffer.lock(); std::vector buf_copy = d_buffer; assert(buf_copy.size() == d_len); mutex_buffer.unlock(); return buf_copy; } void ctrlport_probe2_c_impl::set_length(int len) { if(len > 8191) { std::cerr << "probe2_c: length " << len << " exceeds maximum buffer size of 8191" << std::endl; len = 8191; } d_len = len; d_buffer.reserve(d_len); } int ctrlport_probe2_c_impl::length() const { return (int)d_len; } int ctrlport_probe2_c_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex*)input_items[0]; // copy samples to get buffer if we need samples mutex_buffer.lock(); if(d_buffer.size() < d_len) { // copy smaller of remaining buffer space and num inputs to work() int num_copy = std::min( (int)(d_len - d_buffer.size()), noutput_items ); // TODO: convert this to a copy operator for speed... for(int i = 0; i < num_copy; i++) { d_buffer.push_back(in[i]); } // notify the waiting get() if we fill up the buffer if(d_buffer.size() == d_len) { condition_buffer_ready.notify_one(); } } mutex_buffer.unlock(); return noutput_items; } void ctrlport_probe2_c_impl::setup_rpc() { #ifdef GR_CTRLPORT int len = static_cast(d_len); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get > >( alias(), d_id.c_str(), &ctrlport_probe2_c::get, pmt::mp(-2), pmt::mp(2), pmt::mp(0), "volts", d_desc.c_str(), RPC_PRIVLVL_MIN, d_disp_mask | DISPOPTCPLX))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "length", &ctrlport_probe2_c::length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "get vector length", RPC_PRIVLVL_MIN, DISPNULL))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "length", &ctrlport_probe2_c::set_length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "set vector length", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/deinterleave_impl.h0000664000175000017500000000260112207440367021622 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_DEINTERLEAVE_IMPL_H #define INCLUDED_DEINTERLEAVE_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API deinterleave_impl : public deinterleave { size_t d_itemsize; public: deinterleave_impl(size_t itemsize); bool check_topology(int ninputs, int noutputs); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_DEINTERLEAVE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_int_impl.cc0000664000175000017500000000475512207440367022006 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "float_to_int_impl.h" #include "float_array_to_int.h" #include #include namespace gr { namespace blocks { float_to_int::sptr float_to_int::make(size_t vlen, float scale) { return gnuradio::get_initial_sptr(new float_to_int_impl(vlen, scale)); } float_to_int_impl::float_to_int_impl(size_t vlen, float scale) : sync_block("float_to_int", io_signature::make (1, 1, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(int)*vlen)), d_vlen(vlen), d_scale(scale) { const int alignment_multiple = volk_get_alignment() / sizeof(int); set_alignment(std::max(1, alignment_multiple)); } int float_to_int_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // Disable the Volk for now. There is a problem for large 32-bit ints that // are not properly represented by the precisions of a single float, which // can cause wrapping from large, positive numbers to negative. // In gri_float_to_int, the value is first promoted to a 64-bit // value, clipped, then converted to a float. #if 0 const float *in = (const float *) input_items[0]; int32_t *out = (int32_t *) output_items[0]; volk_32f_s32f_convert_32i(out, in, d_scale, d_vlen*noutput_items); #else const float *in = (const float *) input_items[0]; int *out = (int *) output_items[0]; float_array_to_int (in, out, d_scale, d_vlen*noutput_items); #endif return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/head_impl.h0000664000175000017500000000275312207440367020064 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_HEAD_IMPL_H #define INCLUDED_GR_HEAD_IMPL_H #include namespace gr { namespace blocks { class head_impl : public head { private: uint64_t d_nitems; uint64_t d_ncopied_items; public: head_impl(size_t sizeof_stream_item, uint64_t nitems); ~head_impl(); void reset() { d_ncopied_items = 0; } void set_length(int nitems) { d_nitems = nitems; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_HEAD_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/tcp_connection.h0000664000175000017500000000346112207440367021144 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TCP_CONNECTION_H #define INCLUDED_TCP_CONNECTION_H #include #include #include namespace gr { class basic_block; namespace blocks { class tcp_connection { private: boost::asio::ip::tcp::socket d_socket; boost::array d_buf; std::string d_message; basic_block *d_block; tcp_connection(boost::asio::io_service& io_service); public: typedef boost::shared_ptr sptr; static sptr make(boost::asio::io_service& io_service); boost::asio::ip::tcp::socket& socket() { return d_socket; }; void start(gr::basic_block *block); void send(pmt::pmt_t vector); void handle_read(const boost::system::error_code& error, size_t bytes_transferred); void handle_write(const boost::system::error_code& error, size_t bytes_transferred) { } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_TCP_CONNECTION_H */ gnuradio-3.7.2.1/gr-blocks/lib/vector_source_X_impl.cc.t0000664000175000017500000001015712207440367022731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include #endif #include <@NAME_IMPL@.h> #include #include #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(const std::vector<@TYPE@> &data, bool repeat, int vlen, const std::vector &tags) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(data, repeat, vlen, tags)); } @NAME_IMPL@::@NAME_IMPL@(const std::vector<@TYPE@> &data, bool repeat, int vlen, const std::vector &tags) : sync_block("@BASE_NAME@", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof(@TYPE@) * vlen)), d_data(data), d_repeat(repeat), d_offset(0), d_vlen(vlen), d_tags(tags), d_tagpos(0) { if(tags.size() == 0) { d_settags = 0; } else { d_settags = 1; set_output_multiple(data.size() / vlen); } if((data.size() % vlen) != 0) throw std::invalid_argument("data length must be a multiple of vlen"); } @NAME_IMPL@::~@NAME_IMPL@() {} void @NAME_IMPL@::set_data (const std::vector<@TYPE@> &data, const std::vector &tags) { d_data = data; d_tags = tags; rewind(); if(tags.size() == 0) { d_settags = false; } else { d_settags = true; } } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @TYPE@ *optr = (@TYPE@ *) output_items[0]; if(d_repeat) { unsigned int size = d_data.size (); unsigned int offset = d_offset; if(size == 0) return -1; if(d_settags) { int n_outputitems_per_vector = d_data.size() / d_vlen; for(int i = 0; i < noutput_items; i += n_outputitems_per_vector) { // FIXME do proper vector copy memcpy((void *) optr, (const void*)&d_data[0], size*sizeof (@TYPE@)); optr += size; for(unsigned t = 0; t < d_tags.size(); t++) { add_item_tag(0, nitems_written(0)+i+d_tags[t].offset, d_tags[t].key, d_tags[t].value); } } } else { for(int i = 0; i < noutput_items*d_vlen; i++) { optr[i] = d_data[offset++]; if(offset >= size) { offset = 0; } } } d_offset = offset; return noutput_items; } else { if(d_offset >= d_data.size ()) return -1; // Done! unsigned n = std::min((unsigned)d_data.size() - d_offset, (unsigned)noutput_items*d_vlen); for(unsigned i = 0; i < n; i++) { optr[i] = d_data[d_offset + i]; } for(unsigned t = 0; t < d_tags.size(); t++) { if((d_tags[t].offset >= d_offset) && (d_tags[t].offset < d_offset+n)) add_item_tag(0, d_tags[t].offset, d_tags[t].key, d_tags[t].value); } d_offset += n; return n/d_vlen; } } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/head_impl.cc0000664000175000017500000000404012207440367020211 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "head_impl.h" #include #include namespace gr { namespace blocks { head::sptr head::make(size_t sizeof_stream_item, uint64_t nitems) { return gnuradio::get_initial_sptr (new head_impl(sizeof_stream_item, nitems)); } head_impl::head_impl(size_t sizeof_stream_item, uint64_t nitems) : sync_block("head", io_signature::make(1, 1, sizeof_stream_item), io_signature::make(1, 1, sizeof_stream_item)), d_nitems(nitems), d_ncopied_items(0) { } head_impl::~head_impl() { } int head_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { if(d_ncopied_items >= d_nitems) return -1; // Done! unsigned n = std::min(d_nitems - d_ncopied_items, (uint64_t)noutput_items); if(n == 0) return 0; memcpy(output_items[0], input_items[0], n * input_signature()->sizeof_stream_item (0)); d_ncopied_items += n; return n; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/copy_impl.cc0000664000175000017500000000464512207440367020275 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "copy_impl.h" #include #include namespace gr { namespace blocks { copy::sptr copy::make(size_t itemsize) { return gnuradio::get_initial_sptr (new copy_impl(itemsize)); } copy_impl::copy_impl(size_t itemsize) : block("copy", io_signature::make(1, -1, itemsize), io_signature::make(1, -1, itemsize)), d_itemsize(itemsize), d_enabled(true) { } copy_impl::~copy_impl() { } void copy_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { unsigned ninputs = ninput_items_required.size(); for (unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = noutput_items; } bool copy_impl::check_topology(int ninputs, int noutputs) { return ninputs == noutputs; } int copy_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const uint8_t **in = (const uint8_t**)&input_items[0]; uint8_t **out = (uint8_t**)&output_items[0]; int n = 0; if(d_enabled) { int ninputs = input_items.size(); for(int i = 0; i < ninputs; i++) { memcpy(out[i], in[i], noutput_items*d_itemsize); } n = noutput_items; } consume_each(noutput_items); return n; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/tagged_stream_mux_impl.h0000664000175000017500000000315212237515111022645 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TAGGED_STREAM_MUX_IMPL_H #define INCLUDED_TAGGED_STREAM_MUX_IMPL_H #include #include namespace gr { namespace blocks { class tagged_stream_mux_impl : public tagged_stream_mux { private: size_t d_itemsize; unsigned int d_tag_preserve_head_pos; protected: int calculate_output_stream_length(const gr_vector_int &ninput_items); public: tagged_stream_mux_impl(size_t itemsize, const std::string &lengthtagname, unsigned int d_tag_preserve_head_pos); ~tagged_stream_mux_impl(); int work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace blocks } // namespace gr #endif gnuradio-3.7.2.1/gr-blocks/lib/packed_to_unpacked_XX_impl.cc.t0000664000175000017500000001102712207440367023777 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME_IMPL@.h" #include #include #include namespace gr { namespace blocks { static const unsigned int BITS_PER_TYPE = sizeof(@I_TYPE@) * 8; static const unsigned int LOG2_L_TYPE = log2_const(); @NAME@::sptr @NAME@::make(unsigned int bits_per_chunk, endianness_t endianness) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(bits_per_chunk, endianness)); } @NAME_IMPL@::@NAME_IMPL@(unsigned int bits_per_chunk, endianness_t endianness) : block("@NAME@", io_signature::make(1, -1, sizeof(@I_TYPE@)), io_signature::make(1, -1, sizeof(@O_TYPE@))), d_bits_per_chunk(bits_per_chunk), d_endianness(endianness), d_index(0) { assert(bits_per_chunk <= BITS_PER_TYPE); assert(bits_per_chunk > 0); set_relative_rate((1.0 * BITS_PER_TYPE) / bits_per_chunk); } @NAME_IMPL@::~@NAME_IMPL@() { } void @NAME_IMPL@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = (int)ceil((d_index + noutput_items * d_bits_per_chunk) / (1.0 * BITS_PER_TYPE)); unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = input_required; //printf("Forecast wants %d needs %d\n",noutput_items,ninput_items_required[i]); } } unsigned int get_bit_le(const @I_TYPE@ *in_vector, unsigned int bit_addr) { @I_TYPE@ x = in_vector[bit_addr >> LOG2_L_TYPE]; return (x >> (bit_addr & (BITS_PER_TYPE-1))) & 1; } unsigned int get_bit_be(const @I_TYPE@ *in_vector, unsigned int bit_addr) { @I_TYPE@ x = in_vector[bit_addr >> LOG2_L_TYPE]; return (x >> ((BITS_PER_TYPE-1) - (bit_addr & (BITS_PER_TYPE-1)))) & 1; } int @NAME_IMPL@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned int index_tmp = d_index; assert(input_items.size() == output_items.size()); int nstreams = input_items.size(); for (int m=0; m < nstreams; m++){ const @I_TYPE@ *in = (@I_TYPE@ *)input_items[m]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[m]; index_tmp = d_index; // per stream processing switch(d_endianness) { case GR_MSB_FIRST: for(int i = 0; i < noutput_items; i++) { //printf("here msb %d\n",i); @O_TYPE@ x = 0; for(unsigned int j = 0; j < d_bits_per_chunk; j++, index_tmp++) x = (x<<1) | get_bit_be(in, index_tmp); out[i] = x; } break; case GR_LSB_FIRST: for(int i = 0; i < noutput_items; i++) { //printf("here lsb %d\n",i); @O_TYPE@ x = 0; for(unsigned int j = 0; j < d_bits_per_chunk; j++, index_tmp++) x = (x<<1) | get_bit_le(in, index_tmp); out[i] = x; } break; default: assert(0); } //printf("almost got to end\n"); assert(ninput_items[m] >= (int)((d_index+(BITS_PER_TYPE-1)) >> LOG2_L_TYPE)); } d_index = index_tmp; consume_each(d_index >> LOG2_L_TYPE); d_index = d_index & (BITS_PER_TYPE-1); //printf("got to end\n"); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/message_burst_source_impl.cc0000664000175000017500000001102712207440367023536 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "message_burst_source_impl.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace blocks { message_burst_source::sptr message_burst_source::make(size_t itemsize, int msgq_limit) { return gnuradio::get_initial_sptr (new message_burst_source_impl(itemsize, msgq_limit)); } message_burst_source::sptr message_burst_source::make(size_t itemsize, msg_queue::sptr msgq) { return gnuradio::get_initial_sptr (new message_burst_source_impl(itemsize, msgq)); } message_burst_source_impl::message_burst_source_impl(size_t itemsize, int msgq_limit) : sync_block("message_burst_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_msgq(msg_queue::make(msgq_limit)), d_msg_offset(0), d_eof(false) { std::stringstream id; id << name() << unique_id(); d_me = pmt::string_to_symbol(id.str()); } message_burst_source_impl::message_burst_source_impl(size_t itemsize, msg_queue::sptr msgq) : sync_block("message_burst_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_msgq(msgq), d_msg_offset(0), d_eof(false) { std::stringstream id; id << name() << unique_id(); d_me = pmt::string_to_symbol(id.str()); } message_burst_source_impl::~message_burst_source_impl() { } int message_burst_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *out = (char*)output_items[0]; int nn = 0; uint64_t abs_sample_count = nitems_written(0); while(nn < noutput_items) { if(d_msg) { // // Consume whatever we can from the current message // int mm = std::min(noutput_items - nn, (int)((d_msg->length() - d_msg_offset) / d_itemsize)); memcpy(out, &(d_msg->msg()[d_msg_offset]), mm * d_itemsize); nn += mm; out += mm * d_itemsize; d_msg_offset += mm * d_itemsize; assert(d_msg_offset <= d_msg->length()); if(d_msg_offset == d_msg->length()) { if(d_msg->type() == 1) // type == 1 sets EOF d_eof = true; d_msg.reset(); //tag end of burst add_item_tag(0, //stream ID abs_sample_count+nn-1, //sample number pmt::string_to_symbol("tx_eob"), pmt::from_bool(1), d_me); //block src id } } else { // // No current message // if(d_msgq->empty_p() && nn > 0) { // no more messages in the queue, return what we've got break; } if(d_eof) return -1; d_msg = d_msgq->delete_head(); // block, waiting for a message d_msg_offset = 0; //tag start of burst add_item_tag(0, //stream ID abs_sample_count+nn, //sample number pmt::string_to_symbol("tx_sob"), pmt::from_bool(1), d_me); //block src id if((d_msg->length() % d_itemsize) != 0) throw std::runtime_error("msg length is not a multiple of d_itemsize"); } } return nn; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_uchar_impl.cc0000664000175000017500000000334512207440367022310 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "float_to_uchar_impl.h" #include "float_array_to_uchar.h" #include namespace gr { namespace blocks { float_to_uchar::sptr float_to_uchar::make() { return gnuradio::get_initial_sptr(new float_to_uchar_impl()); } float_to_uchar_impl::float_to_uchar_impl() : sync_block("float_to_uchar", io_signature::make (1, 1, sizeof(float)), io_signature::make (1, 1, sizeof(unsigned char))) { } int float_to_uchar_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; float_array_to_uchar(in, out, noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/nlog10_ff_impl.cc0000664000175000017500000000354112207440367021070 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "nlog10_ff_impl.h" #include namespace gr { namespace blocks { nlog10_ff::sptr nlog10_ff::make(float n, size_t vlen, float k) { return gnuradio::get_initial_sptr(new nlog10_ff_impl(n, vlen, k)); } nlog10_ff_impl::nlog10_ff_impl(float n, size_t vlen, float k) : sync_block("nlog10_ff", io_signature::make (1, 1, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_n(n), d_vlen(vlen), d_k(k) { } int nlog10_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; int noi = noutput_items * d_vlen; float n = d_n; float k = d_k; for (int i = 0; i < noi; i++) out[i] = n * log10(std::max(in[i], (float) 1e-18)) + k; return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/divide_XX_impl.cc.t0000664000175000017500000000356212207440367021445 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc /= ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/annotator_1to1_impl.h0000664000175000017500000000312612207440367022027 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ANNOTATOR_1TO1_IMPL_H #define INCLUDED_GR_ANNOTATOR_1TO1_IMPL_H #include namespace gr { namespace blocks { class annotator_1to1_impl : public annotator_1to1 { private: size_t d_itemsize; uint64_t d_when; uint64_t d_tag_counter; std::vector d_stored_tags; public: annotator_1to1_impl(int when, size_t sizeof_stream_item); ~annotator_1to1_impl(); std::vector data() const { return d_stored_tags; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ANNOTATOR_1TO1_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/argmax_XX_impl.cc.t0000664000175000017500000000444512207440367021461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block("@BASE_NAME@", io_signature::make(1, -1, vlen*sizeof(@I_TYPE@)), io_signature::make(2, 2, sizeof(@O_TYPE@))), d_vlen(vlen) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ninputs = input_items.size (); @O_TYPE@ *x_optr = (@O_TYPE@ *)output_items[0]; @O_TYPE@ *y_optr = (@O_TYPE@ *)output_items[1]; for(int i = 0; i < noutput_items; i++) { @I_TYPE@ max = ((@I_TYPE@ *)input_items[0])[i*d_vlen]; int x = 0; int y = 0; for(int j = 0; j < (int)d_vlen; j++ ) { for(int k = 0; k < ninputs; k++) { if(((@I_TYPE@ *)input_items[k])[i*d_vlen + j] > max) { max = ((@I_TYPE@ *)input_items[k])[i*d_vlen + j]; x = j; y = k; } } } *x_optr++ = (@O_TYPE@)x; *y_optr++ = (@O_TYPE@)y; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/repack_bits_bb_impl.cc0000664000175000017500000000675212207440367022255 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "repack_bits_bb_impl.h" namespace gr { namespace blocks { repack_bits_bb::sptr repack_bits_bb::make(int k, int l, const std::string &len_tag_key, bool align_output) { return gnuradio::get_initial_sptr (new repack_bits_bb_impl(k, l, len_tag_key, align_output)); } repack_bits_bb_impl::repack_bits_bb_impl(int k, int l, const std::string &len_tag_key, bool align_output) : tagged_stream_block("repack_bits_bb", io_signature::make(1, 1, sizeof (char)), io_signature::make(1, 1, sizeof (char)), len_tag_key), d_k(k), d_l(l), d_packet_mode(!len_tag_key.empty()), d_in_index(0), d_out_index(0), d_align_output(align_output) { if (d_k > 8 || d_k < 1 || d_l > 8 || d_l < 1) { throw std::invalid_argument("k and l must be in [1, 8]"); } set_relative_rate((double) d_k / d_l); } repack_bits_bb_impl::~repack_bits_bb_impl() { } int repack_bits_bb_impl::calculate_output_stream_length(const gr_vector_int &ninput_items) { int n_out_bytes_required = (ninput_items[0] * d_k) / d_l; if ((ninput_items[0] * d_k) % d_l && (!d_packet_mode || (d_packet_mode && !d_align_output))) { n_out_bytes_required++; } return n_out_bytes_required; } int repack_bits_bb_impl::work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; int bytes_to_write = noutput_items; if (d_packet_mode) { // noutput_items could be larger than necessary int bytes_to_read = ninput_items[0]; bytes_to_write = bytes_to_read * d_k / d_l; if (!d_align_output && (((bytes_to_read * d_k) % d_l) != 0)) { bytes_to_write++; } } int n_read = 0; int n_written = 0; while(n_written < bytes_to_write && n_read < ninput_items[0]) { if (d_out_index == 0) { // Starting a fresh byte out[n_written] = 0; } out[n_written] |= ((in[n_read] >> d_in_index) & 0x01) << d_out_index; d_in_index = (d_in_index + 1) % d_k; d_out_index = (d_out_index + 1) % d_l; if (d_in_index == 0) { n_read++; d_in_index = 0; } if (d_out_index == 0) { n_written++; d_out_index = 0; } } if (d_packet_mode) { if (d_out_index) { n_written++; d_out_index = 0; } } else { consume_each(n_read); } return n_written; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_hier_block2.h0000664000175000017500000000230712207440367021471 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_HIER_BLOCK2_H #define INCLUDED_QA_GR_HIER_BLOCK2_H #include #include #include class qa_hier_block2 : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_hier_block2); CPPUNIT_TEST(test_make); CPPUNIT_TEST_SUITE_END(); private: void test_make(); }; #endif /* INCLUDED_QA_GR_HIER_BLOCK2_H */ gnuradio-3.7.2.1/gr-blocks/lib/keep_m_in_n_impl.cc0000664000175000017500000000474312207440367021565 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "keep_m_in_n_impl.h" #include namespace gr { namespace blocks { keep_m_in_n::sptr keep_m_in_n::make(size_t itemsize, int m, int n, int offset) { return gnuradio::get_initial_sptr(new keep_m_in_n_impl(itemsize, m, n, offset)); } keep_m_in_n_impl::keep_m_in_n_impl(size_t itemsize, int m, int n, int offset) : block("keep_m_in_n", io_signature::make (1, 1, itemsize), io_signature::make (1, 1, itemsize)), d_m(m), d_n(n), d_offset(offset), d_itemsize(itemsize) { // sanity checking assert(d_m > 0); assert(d_n > 0); assert(d_m <= d_n); assert(d_offset <= (d_n-d_m)); set_output_multiple(m); } void keep_m_in_n_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { ninput_items_required[0] = d_n*(noutput_items/d_m); } int keep_m_in_n_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { uint8_t* out = (uint8_t*)output_items[0]; const uint8_t* in = (const uint8_t*)input_items[0]; // iterate over data blocks of size {n, input : m, output} int blks = std::min(noutput_items/d_m, ninput_items[0]/d_n); for(int i=0; i #include // for FILE namespace gr { namespace blocks { class wavfile_source_impl : public wavfile_source { private: FILE *d_fp; bool d_repeat; unsigned d_sample_rate; int d_nchans; int d_bytes_per_sample; int d_first_sample_pos; unsigned d_samples_per_chan; unsigned d_sample_idx; int d_normalize_shift; int d_normalize_fac; /*! * \brief Convert an integer sample value to a float value within [-1;1] */ float convert_to_float(short int sample); public: wavfile_source_impl(const char *filename, bool repeat); ~wavfile_source_impl(); unsigned int sample_rate() const { return d_sample_rate; }; int bits_per_sample() const { return d_bytes_per_sample * 8; }; int channels() const { return d_nchans; }; int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_WAVFILE_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/add_XX_impl.h.t0000664000175000017500000000245212207440367020570 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { private: size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/stream_to_tagged_stream_impl.cc0000664000175000017500000000470412237515111024173 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 <+YOU OR YOUR COMPANY+>. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include "stream_to_tagged_stream_impl.h" namespace gr { namespace blocks { stream_to_tagged_stream::sptr stream_to_tagged_stream::make(size_t itemsize, int vlen, unsigned packet_len, const std::string &len_tag_key) { return gnuradio::get_initial_sptr (new stream_to_tagged_stream_impl(itemsize, vlen, packet_len, len_tag_key)); } stream_to_tagged_stream_impl::stream_to_tagged_stream_impl(size_t itemsize, int vlen, unsigned packet_len, const std::string &len_tag_key) : gr::sync_block("stream_to_tagged_stream", gr::io_signature::make(1, 1, itemsize * vlen), gr::io_signature::make(1, 1, itemsize * vlen)), d_itemsize(itemsize * vlen), d_packet_len(packet_len), d_packet_len_pmt(pmt::from_long(packet_len)), d_len_tag_key(pmt::string_to_symbol(len_tag_key)), d_next_tag_pos(0) {} stream_to_tagged_stream_impl::~stream_to_tagged_stream_impl() { } int stream_to_tagged_stream_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; // Copy data memcpy(out, in, noutput_items * d_itemsize); // Add tags every d_packet_len while(d_next_tag_pos < nitems_written(0) + noutput_items) { add_item_tag(0, d_next_tag_pos, d_len_tag_key, d_packet_len_pmt); d_next_tag_pos += d_packet_len; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/streams_to_vector_impl.h0000664000175000017500000000254012207440367022717 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_STREAMS_TO_VECTOR_IMPL_H #define INCLUDED_STREAMS_TO_VECTOR_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API streams_to_vector_impl : public streams_to_vector { public: streams_to_vector_impl(size_t itemsize, size_t nstreams); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_STREAMS_TO_VECTOR_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_imag_impl.h0000664000175000017500000000252712207440367022330 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_IMAG_IMPL_H #define INCLUDED_COMPLEX_TO_IMAG_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_imag_impl : public complex_to_imag { size_t d_vlen; public: complex_to_imag_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_IMAG_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_ff_impl.cc0000664000175000017500000000415212245466767021664 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace blocks { multiply_ff::sptr multiply_ff::make(size_t vlen) { return gnuradio::get_initial_sptr(new multiply_ff_impl(vlen)); } multiply_ff_impl::multiply_ff_impl(size_t vlen) : sync_block("multiply_ff", io_signature::make (1, -1, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1, alignment_multiple)); } int multiply_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *out = (float *) output_items[0]; int noi = d_vlen*noutput_items; memcpy(out, input_items[0], noi*sizeof(float)); if(is_unaligned()) { for(size_t i = 1; i < input_items.size(); i++) volk_32f_x2_multiply_32f_u(out, out, (float*)input_items[i], noi); } else { for(size_t i = 1; i < input_items.size(); i++) volk_32f_x2_multiply_32f_a(out, out, (float*)input_items[i], noi); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/unpack_k_bits_bb_impl.cc0000664000175000017500000000440612207440367022575 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #if HAVE_CONFIG_H #include "config.h" #endif #include "unpack_k_bits_bb_impl.h" #include #include #include namespace gr { namespace blocks { unpack_k_bits_bb::sptr unpack_k_bits_bb::make(unsigned k) { return gnuradio::get_initial_sptr (new unpack_k_bits_bb_impl(k)); } unpack_k_bits_bb_impl::unpack_k_bits_bb_impl(unsigned k) : sync_interpolator("unpack_k_bits_bb", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(unsigned char)), k), d_k(k) { if(d_k == 0) throw std::out_of_range("interpolation must be > 0"); } unpack_k_bits_bb_impl::~unpack_k_bits_bb_impl() { } int unpack_k_bits_bb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *)input_items[0]; unsigned char *out = (unsigned char *)output_items[0]; int n = 0; for(unsigned int i = 0; i < noutput_items/d_k; i++) { unsigned int t = in[i]; for(int j = d_k - 1; j >= 0; j--) out[n++] = (t >> j) & 0x01; } assert(n == noutput_items); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vector_to_stream_impl.cc0000664000175000017500000000362512207440367022677 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vector_to_stream_impl.h" #include namespace gr { namespace blocks { vector_to_stream::sptr vector_to_stream::make(size_t itemsize, size_t nitems_per_block) { return gnuradio::get_initial_sptr(new vector_to_stream_impl(itemsize, nitems_per_block)); } vector_to_stream_impl::vector_to_stream_impl(size_t itemsize, size_t nitems_per_block) : sync_interpolator ("vector_to_stream", io_signature::make (1, 1, itemsize * nitems_per_block), io_signature::make (1, 1, itemsize), nitems_per_block) { } int vector_to_stream_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t block_size = output_signature()->sizeof_stream_item (0); const char *in = (const char *) input_items[0]; char *out = (char *) output_items[0]; memcpy (out, in, noutput_items * block_size); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vco_f_impl.cc0000664000175000017500000000402012207440367020402 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vco_f_impl.h" #include #include namespace gr { namespace blocks { vco_f::sptr vco_f::make(double sampling_rate, double sensitivity, double amplitude) { return gnuradio::get_initial_sptr (new vco_f_impl(sampling_rate, sensitivity, amplitude)); } vco_f_impl::vco_f_impl(double sampling_rate, double sensitivity, double amplitude) : sync_block("vco_f", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(float))), d_sampling_rate(sampling_rate), d_sensitivity(sensitivity), d_amplitude(amplitude), d_k(d_sensitivity/d_sampling_rate) { } vco_f_impl::~vco_f_impl() { } int vco_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *input = (const float*)input_items[0]; float *output = (float*)output_items[0]; d_vco.cos(output, input, noutput_items, d_k, d_amplitude); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/and_XX_impl.h.t0000664000175000017500000000242312207440367020600 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/bin_statistics_f_impl.cc0000664000175000017500000001150312207440367022641 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "bin_statistics_f_impl.h" #include #include namespace gr { namespace blocks { bin_statistics_f::sptr bin_statistics_f::make(unsigned int vlen, msg_queue::sptr msgq, feval_dd *tune, size_t tune_delay, size_t dwell_delay) { return gnuradio::get_initial_sptr (new bin_statistics_f_impl(vlen, msgq, tune, tune_delay, dwell_delay)); } bin_statistics_f_impl::bin_statistics_f_impl(unsigned int vlen, msg_queue::sptr msgq, feval_dd *tune, size_t tune_delay, size_t dwell_delay) : sync_block("bin_statistics_f", io_signature::make(1, 1, sizeof(float) * vlen), io_signature::make(0, 0, 0)), d_vlen(vlen), d_msgq(msgq), d_tune(tune), d_tune_delay(tune_delay), d_dwell_delay(dwell_delay), d_center_freq(0), d_delay(0), d_max(vlen) { enter_init(); } bin_statistics_f_impl::~bin_statistics_f_impl() { } void bin_statistics_f_impl::enter_init() { d_state = ST_INIT; d_delay = 0; } void bin_statistics_f_impl::enter_tune_delay() { d_state = ST_TUNE_DELAY; d_delay = d_tune_delay; d_center_freq = d_tune->calleval(0); } void bin_statistics_f_impl::enter_dwell_delay() { d_state = ST_DWELL_DELAY; d_delay = d_dwell_delay; reset_stats(); } void bin_statistics_f_impl::leave_dwell_delay() { send_stats(); } int bin_statistics_f_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *input = (const float*)input_items[0]; size_t vlen = d_max.size(); int n = 0; int t; while(n < noutput_items) { switch(d_state) { case ST_INIT: enter_tune_delay(); break; case ST_TUNE_DELAY: t = std::min(noutput_items - n, int(d_delay)); n += t; d_delay -= t; assert(d_delay >= 0); if(d_delay == 0) enter_dwell_delay(); break; case ST_DWELL_DELAY: t = std::min(noutput_items - n, int(d_delay)); for(int i = 0; i < t; i++) { accrue_stats(&input[n * vlen]); n++; } d_delay -= t; assert(d_delay >= 0); if(d_delay == 0) { leave_dwell_delay(); enter_tune_delay(); } break; default: assert(0); } } return noutput_items; } ////////////////////////////////////////////////////////////////////////// // virtual methods for gathering stats ////////////////////////////////////////////////////////////////////////// void bin_statistics_f_impl::reset_stats() { for (size_t i = 0; i < vlen(); i++){ d_max[i] = 0; } } void bin_statistics_f_impl::accrue_stats(const float *input) { for(size_t i = 0; i < vlen(); i++) { d_max[i] = std::max(d_max[i], input[i]); // compute per bin maxima } } void bin_statistics_f_impl::send_stats() { if(msgq()->full_p()) // if the queue is full, don't block, drop the data... return; // build & send a message message::sptr msg = message::make(0, center_freq(), vlen(), vlen() * sizeof(float)); memcpy(msg->msg(), &d_max[0], vlen() * sizeof(float)); msgq()->insert_tail(msg); } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe2_b_impl.cc0000664000175000017500000001201712207702530022727 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ctrlport_probe2_b_impl.h" #include namespace gr { namespace blocks { ctrlport_probe2_b::sptr ctrlport_probe2_b::make(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) { return gnuradio::get_initial_sptr (new ctrlport_probe2_b_impl(id, desc, len, disp_mask)); } ctrlport_probe2_b_impl::ctrlport_probe2_b_impl(const std::string &id, const std::string &desc, int len, unsigned int disp_mask) : sync_block("probe2_b", io_signature::make(1, 1, sizeof(char)), io_signature::make(0, 0, 0)), d_id(id), d_desc(desc), d_len(len), d_disp_mask(disp_mask) { set_length(len); } ctrlport_probe2_b_impl::~ctrlport_probe2_b_impl() { } void ctrlport_probe2_b_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { // make sure all inputs have noutput_items available unsigned ninputs = ninput_items_required.size(); for(unsigned i = 0; i < ninputs; i++) ninput_items_required[i] = d_len; } // boost::shared_mutex mutex_buffer; // mutable boost::mutex mutex_notify; // boost::condition_variable condition_buffer_ready; std::vector ctrlport_probe2_b_impl::get() { mutex_buffer.lock(); d_buffer.clear(); mutex_buffer.unlock(); // wait for condition boost::mutex::scoped_lock lock(mutex_notify); condition_buffer_ready.wait(lock); mutex_buffer.lock(); std::vector buf_copy = d_buffer; assert(buf_copy.size() == d_len); mutex_buffer.unlock(); return buf_copy; } void ctrlport_probe2_b_impl::set_length(int len) { if(len > 8191) { std::cerr << "probe2_b: length " << len << " exceeds maximum buffer size of 8191" << std::endl; len = 8191; } d_len = len; d_buffer.reserve(d_len); } int ctrlport_probe2_b_impl::length() const { return (int)d_len; } int ctrlport_probe2_b_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char*)input_items[0]; // copy samples to get buffer if we need samples mutex_buffer.lock(); if(d_buffer.size() < d_len) { // copy smaller of remaining buffer space and num inputs to work() int num_copy = std::min( (int)(d_len - d_buffer.size()), noutput_items ); // TODO: convert this to a copy operator for speed... for(int i = 0; i < num_copy; i++) { d_buffer.push_back(in[i]); } // notify the waiting get() if we fill up the buffer if(d_buffer.size() == d_len) { condition_buffer_ready.notify_one(); } } mutex_buffer.unlock(); return noutput_items; } void ctrlport_probe2_b_impl::setup_rpc() { #ifdef GR_CTRLPORT int len = static_cast(d_len); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get >( alias(), d_id.c_str(), &ctrlport_probe2_b::get, pmt::mp(-128), pmt::mp(127), pmt::mp(0), "volts", d_desc.c_str(), RPC_PRIVLVL_MIN, d_disp_mask))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "length", &ctrlport_probe2_b::length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "get vector length", RPC_PRIVLVL_MIN, DISPNULL))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "length", &ctrlport_probe2_b::set_length, pmt::mp(1), pmt::mp(10*len), pmt::mp(len), "samples", "set vector length", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/message_source_impl.cc0000664000175000017500000001064412207440367022323 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "message_source_impl.h" #include #include #include #include #include #include #include #include namespace gr { namespace blocks { message_source::sptr message_source::make(size_t itemsize, int msgq_limit) { return gnuradio::get_initial_sptr (new message_source_impl(itemsize, msgq_limit)); } message_source::sptr message_source::make(size_t itemsize, msg_queue::sptr msgq) { return gnuradio::get_initial_sptr (new message_source_impl(itemsize, msgq)); } message_source::sptr message_source::make(size_t itemsize, msg_queue::sptr msgq, const std::string& lengthtagname) { return gnuradio::get_initial_sptr (new message_source_impl(itemsize, msgq, lengthtagname)); } message_source_impl::message_source_impl(size_t itemsize, int msgq_limit) : sync_block("message_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_msgq(msg_queue::make(msgq_limit)), d_msg_offset(0), d_eof(false), d_tags(false) { } message_source_impl::message_source_impl(size_t itemsize, msg_queue::sptr msgq) : sync_block("message_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_msgq(msgq), d_msg_offset(0), d_eof(false), d_tags(false) { } message_source_impl::message_source_impl(size_t itemsize, msg_queue::sptr msgq, const std::string& lengthtagname) : sync_block("message_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_msgq(msgq), d_msg_offset(0), d_eof(false), d_tags(true), d_lengthtagname(lengthtagname) { } message_source_impl::~message_source_impl() { } int message_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *out = (char*)output_items[0]; int nn = 0; while(nn < noutput_items) { if (d_msg){ // // Consume whatever we can from the current message // int mm = std::min(noutput_items - nn, (int)((d_msg->length() - d_msg_offset) / d_itemsize)); memcpy (out, &(d_msg->msg()[d_msg_offset]), mm * d_itemsize); if (d_tags && (d_msg_offset == 0)) { const uint64_t offset = this->nitems_written(0) + nn; pmt::pmt_t key = pmt::string_to_symbol(d_lengthtagname); pmt::pmt_t value = pmt::from_long(d_msg->length()); this->add_item_tag(0, offset, key, value); } nn += mm; out += mm * d_itemsize; d_msg_offset += mm * d_itemsize; assert(d_msg_offset <= d_msg->length()); if (d_msg_offset == d_msg->length()){ if (d_msg->type() == 1) // type == 1 sets EOF d_eof = true; d_msg.reset(); } } else { // // No current message // if (d_msgq->empty_p() && nn > 0){ // no more messages in the queue, return what we've got break; } if (d_eof) return -1; d_msg = d_msgq->delete_head(); // block, waiting for a message d_msg_offset = 0; if ((d_msg->length() % d_itemsize) != 0) throw std::runtime_error("msg length is not a multiple of d_itemsize"); } } return nn; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/tagged_stream_to_pdu_impl.cc0000664000175000017500000001046712207440367023502 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "tagged_stream_to_pdu_impl.h" #include #include namespace gr { namespace blocks { tagged_stream_to_pdu::sptr tagged_stream_to_pdu::make(pdu::vector_type type, const std::string& lengthtagname) { return gnuradio::get_initial_sptr(new tagged_stream_to_pdu_impl(type, lengthtagname)); } tagged_stream_to_pdu_impl::tagged_stream_to_pdu_impl(pdu::vector_type type, const std::string& lengthtagname) : sync_block("tagged_stream_to_pdu", io_signature::make(1, 1, pdu::itemsize(type)), io_signature::make(0, 0, 0)), d_itemsize(pdu::itemsize(type)), d_inpdu(false), d_type(type), d_pdu_meta(pmt::PMT_NIL), d_pdu_vector(pmt::PMT_NIL), d_tag(pmt::mp(lengthtagname)) { message_port_register_out(PDU_PORT_ID); } int tagged_stream_to_pdu_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const uint8_t *in = (const uint8_t*) input_items[0]; uint64_t abs_N = nitems_read(0); // if we are not in a pdu already, start a new one if (!d_inpdu) { bool found_length_tag(false); get_tags_in_range(d_tags, 0, abs_N, abs_N+1); for (d_tags_itr = d_tags.begin(); (d_tags_itr != d_tags.end()) && (!found_length_tag); d_tags_itr++) { if (pmt::eq((*d_tags_itr).key, d_tag)) { if ((*d_tags_itr).offset != abs_N ) throw std::runtime_error("expected next pdu length tag on a different item..."); found_length_tag = true; d_pdu_length = pmt::to_long((*d_tags_itr).value); d_pdu_remain = d_pdu_length; d_pdu_meta = pmt::make_dict(); break; } // if have length tag } // iter over tags if (!found_length_tag) throw std::runtime_error("tagged stream does not contain a pdu_length tag"); } size_t ncopy = std::min((size_t)noutput_items, d_pdu_remain); // copy any tags in this range into our meta object get_tags_in_range(d_tags, 0, abs_N, abs_N+ncopy); for (d_tags_itr = d_tags.begin(); d_tags_itr != d_tags.end(); d_tags_itr++) if(!pmt::eq((*d_tags_itr).key, d_tag )) d_pdu_meta = dict_add(d_pdu_meta, (*d_tags_itr).key, (*d_tags_itr).value); // copy samples for this vector into either a pmt or our save buffer if (ncopy == d_pdu_remain) { // we will send this pdu if (d_save.size() == 0) { d_pdu_vector = pdu::make_pdu_vector(d_type, in, ncopy); send_message(); } else { size_t oldsize = d_save.size(); d_save.resize((oldsize + ncopy)*d_itemsize, 0); memcpy(&d_save[oldsize*d_itemsize], in, ncopy*d_itemsize); d_pdu_vector = pdu::make_pdu_vector(d_type, &d_save[0], d_pdu_length); send_message(); d_save.clear(); } } else { d_inpdu = true; size_t oldsize = d_save.size(); d_save.resize((oldsize+ncopy)*d_itemsize); memcpy(&d_save[oldsize*d_itemsize], in, ncopy*d_itemsize); d_pdu_remain -= ncopy; } return ncopy; } void tagged_stream_to_pdu_impl::send_message() { if (pmt::length(d_pdu_vector) != d_pdu_length) throw std::runtime_error("msg length not correct"); pmt::pmt_t msg = pmt::cons(d_pdu_meta, d_pdu_vector); message_port_pub(PDU_PORT_ID, msg); d_pdu_meta = pmt::PMT_NIL; d_pdu_vector = pmt::PMT_NIL; d_pdu_length = 0; d_pdu_remain = 0; d_inpdu = false; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_meta_source_impl.h0000664000175000017500000000464212207440367022467 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FILE_META_SOURCE_IMPL_H #define INCLUDED_BLOCKS_FILE_META_SOURCE_IMPL_H #include #include #include #include #include using namespace pmt; namespace gr { namespace blocks { class file_meta_source_impl : public file_meta_source { private: enum meta_state_t { STATE_INLINE=0, STATE_DETACHED }; size_t d_itemsize; double d_samp_rate; pmt_t d_time_stamp; size_t d_seg_size; bool d_updated; bool d_repeat; gr::thread::mutex d_mutex; FILE *d_new_fp, *d_new_hdr_fp; FILE *d_fp, *d_hdr_fp; meta_state_t d_state; std::vector d_tags; protected: bool _open(FILE **fp, const char *filename); bool read_header(pmt_t &hdr, pmt_t &extras); void parse_header(pmt_t hdr, uint64_t offset, std::vector &tags); void parse_extras(pmt_t extras, uint64_t offset, std::vector &tags); public: file_meta_source_impl(const std::string &filename, bool repeat=false, bool detached_header=false, const std::string &hdr_filename=""); ~file_meta_source_impl(); bool open(const std::string &filename, const std::string &hdr_filename=""); void close(); void do_update(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FILE_META_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/packed_to_unpacked_XX_impl.h.t0000664000175000017500000000332612207440367023644 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: unsigned int d_bits_per_chunk; endianness_t d_endianness; unsigned int d_index; public: @NAME_IMPL@(unsigned int bits_per_chunk, endianness_t endianness); ~@NAME_IMPL@(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); bool check_topology(int ninputs, int noutputs) { return ninputs == noutputs; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/null_source_impl.cc0000664000175000017500000000351112207440367021644 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "null_source_impl.h" #include #include namespace gr { namespace blocks { null_source::sptr null_source::make(size_t sizeof_stream_item) { return gnuradio::get_initial_sptr (new null_source_impl(sizeof_stream_item)); } null_source_impl::null_source_impl (size_t sizeof_stream_item) : sync_block("null_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof_stream_item)) { } null_source_impl::~null_source_impl() { } int null_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { void *optr = (void*)output_items[0]; memset(optr, 0, noutput_items * output_signature()->sizeof_stream_item(0)); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/transcendental_impl.h0000664000175000017500000000306612207440367022166 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TRANSCENDENTAL_IMPL_H #define INCLUDED_GR_TRANSCENDENTAL_IMPL_H #include namespace gr { namespace blocks { typedef int(*work_fcn_type)(int, gr_vector_const_void_star &, gr_vector_void_star &); class transcendental_impl : public transcendental { private: const work_fcn_type &_work_fcn; public: transcendental_impl(const work_fcn_type &work_fcn, const size_t io_size); ~transcendental_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TRANSCENDENTAL_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_imag_impl.cc0000664000175000017500000000366412207440367022471 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_imag_impl.h" #include #include namespace gr { namespace blocks { complex_to_imag::sptr complex_to_imag::make(size_t vlen) { return gnuradio::get_initial_sptr(new complex_to_imag_impl(vlen)); } complex_to_imag_impl::complex_to_imag_impl(size_t vlen) : sync_block("complex_to_imag", io_signature::make (1, 1, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int complex_to_imag_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; float *out = (float *) output_items[0]; int noi = noutput_items * d_vlen; volk_32fc_deinterleave_imag_32f(out, in, noi); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/sub_XX_impl.cc.t0000664000175000017500000000356212207440367020772 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc -= ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_cc_impl.h0000664000175000017500000000252012207440367021477 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_MULTIPLY_CC_IMPL_H #define INCLUDED_BLOCKS_MULTIPLY_CC_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API multiply_cc_impl : public multiply_cc { size_t d_vlen; public: multiply_cc_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_MULTIPLY_CC_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/patterned_interleaver_impl.h0000664000175000017500000000342612207440367023547 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PATTERNED_INTERLEAVER_IMPL_H #define INCLUDED_PATTERNED_INTERLEAVER_IMPL_H #include #include namespace gr { namespace blocks { class BLOCKS_API patterned_interleaver_impl : public patterned_interleaver { public: patterned_interleaver_impl(size_t itemsize, std::vector pattern); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); int pattern_max(std::vector pattern){ int mval(0); BOOST_FOREACH( int i, pattern) { mval = std::max(mval, i); } return mval; } void forecast (int noutput_items, gr_vector_int &ninput_items_required); std::vector d_pattern; std::vector d_counts; size_t d_itemsize; }; } /* namespace blocks */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-blocks/lib/tagged_file_sink_impl.h0000664000175000017500000000322012207440367022427 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_TAGGED_FILE_SINK_IMPL_H #define INCLUDED_GR_TAGGED_FILE_SINK_IMPL_H #include #include // for FILE namespace gr { namespace blocks { class tagged_file_sink_impl : public tagged_file_sink { private: enum { NOT_IN_BURST = 0, IN_BURST }; size_t d_itemsize; int d_state; FILE *d_handle; int d_n; double d_sample_rate; uint64_t d_last_N; double d_timeval; public: tagged_file_sink_impl(size_t itemsize, double samp_rate); ~tagged_file_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_TAGGED_FILE_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vector_insert_X_impl.h.t0000664000175000017500000000321212207440367022571 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: std::vector<@TYPE@> d_data; int d_offset; int d_periodicity; public: @NAME_IMPL@(const std::vector<@TYPE@> &data, int periodicity, int offset); ~@NAME_IMPL@(); void rewind() { d_offset=0; } void set_data(const std::vector<@TYPE@> &data) { d_data = data; rewind(); } int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/message_source_impl.h0000664000175000017500000000360712207440367022166 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_SOURCE_IMPL_H #define INCLUDED_GR_MESSAGE_SOURCE_IMPL_H #include #include namespace gr { namespace blocks { class message_source_impl : public message_source { private: size_t d_itemsize; msg_queue::sptr d_msgq; message::sptr d_msg; unsigned d_msg_offset; bool d_eof; bool d_tags; // FIXME: Is this adequate tagname length. std::string d_lengthtagname; public: message_source_impl(size_t itemsize, int msgq_limit); message_source_impl(size_t itemsize, msg_queue::sptr msgq); message_source_impl(size_t itemsize, msg_queue::sptr msgq, const std::string& lengthtagname); ~message_source_impl(); msg_queue::sptr msgq() const { return d_msgq; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_cc_impl.h0000664000175000017500000000301612207440367022706 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef INCLUDED_MULTIPLY_CONST_CC_IMPL_H #define INCLUDED_MULTIPLY_CONST_CC_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API multiply_const_cc_impl : public multiply_const_cc { gr_complex d_k; size_t d_vlen; public: multiply_const_cc_impl(gr_complex k, size_t vlen); void setup_rpc(); gr_complex k() const { return d_k; } void set_k(gr_complex k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_MULTIPLY_CONST_CC_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/udp_sink_impl.cc0000664000175000017500000001067412241760655021141 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "udp_sink_impl.h" #include #include #include #include #include #include #include #include namespace gr { namespace blocks { udp_sink::sptr udp_sink::make(size_t itemsize, const std::string &host, int port, int payload_size, bool eof) { return gnuradio::get_initial_sptr (new udp_sink_impl(itemsize, host, port, payload_size, eof)); } udp_sink_impl::udp_sink_impl(size_t itemsize, const std::string &host, int port, int payload_size, bool eof) : sync_block("udp_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_payload_size(payload_size), d_eof(eof), d_connected(false) { // Get the destination address connect(host, port); } // public constructor that returns a shared_ptr udp_sink_impl::~udp_sink_impl() { if(d_connected) disconnect(); } void udp_sink_impl::connect(const std::string &host, int port) { if(d_connected) disconnect(); std::string s_port = (boost::format("%d")%port).str(); if(host.size() > 0) { boost::asio::ip::udp::resolver resolver(d_io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), host, s_port, boost::asio::ip::resolver_query_base::passive); d_endpoint = *resolver.resolve(query); d_socket = new boost::asio::ip::udp::socket(d_io_service); d_socket->open(boost::asio::ip::udp::v4()); boost::asio::socket_base::reuse_address roption(true); d_socket->set_option(roption); d_connected = true; } } void udp_sink_impl::disconnect() { if(!d_connected) return; gr::thread::scoped_lock guard(d_mutex); // protect d_socket from work() // Send a few zero-length packets to signal receiver we are done boost::array send_buf = {{ 0 }}; if(d_eof) { int i; for(i = 0; i < 3; i++) d_socket->send_to(boost::asio::buffer(send_buf), d_endpoint); } d_socket->close(); delete d_socket; d_connected = false; } int udp_sink_impl::work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char *) input_items[0]; ssize_t r=0, bytes_sent=0, bytes_to_send=0; ssize_t total_size = noutput_items*d_itemsize; gr::thread::scoped_lock guard(d_mutex); // protect d_socket while(bytes_sent < total_size) { bytes_to_send = std::min((ssize_t)d_payload_size, (total_size-bytes_sent)); if(d_connected) { try { r = d_socket->send_to(boost::asio::buffer((void*)(in+bytes_sent), bytes_to_send), d_endpoint); } catch(std::exception& e) { GR_LOG_ERROR(d_logger, boost::format("send error: %s") % e.what()); return -1; } } else r = bytes_to_send; // discarded for lack of connection bytes_sent += r; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vector_sink_X_impl.cc.t0000664000175000017500000000417612207440367022401 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include #endif #include <@NAME_IMPL@.h> #include #include #include namespace gr { namespace blocks { @NAME@::sptr @BASE_NAME@::make(int vlen) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(int vlen) : sync_block("@NAME@", io_signature::make(1, 1, sizeof(@TYPE@) * vlen), io_signature::make(0, 0, 0)), d_vlen(vlen) { } @NAME_IMPL@::~@NAME_IMPL@() {} std::vector<@TYPE@> @NAME_IMPL@::data() const { return d_data; } std::vector @NAME_IMPL@::tags() const { return d_tags; } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @TYPE@ *iptr = (@TYPE@*)input_items[0]; for(int i = 0; i < noutput_items * d_vlen; i++) d_data.push_back (iptr[i]); std::vector tags; get_tags_in_range(tags, 0, nitems_read(0), nitems_read(0) + noutput_items); d_tags.insert(d_tags.end(), tags.begin(), tags.end()); return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_interleaved_short_impl.cc0000664000175000017500000000364612207440367025275 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_interleaved_short_impl.h" #include namespace gr { namespace blocks { complex_to_interleaved_short::sptr complex_to_interleaved_short::make() { return gnuradio::get_initial_sptr(new complex_to_interleaved_short_impl()); } complex_to_interleaved_short_impl::complex_to_interleaved_short_impl() : sync_interpolator("complex_to_interleaved_short", io_signature::make (1, 1, sizeof(gr_complex)), io_signature::make (1, 1, sizeof(short)), 2) { } int complex_to_interleaved_short_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; short *out = (short *) output_items[0]; for (int i = 0; i < noutput_items/2; i++){ *out++ = (short) lrintf(in[i].real()); // FIXME saturate? *out++ = (short) lrintf(in[i].imag()); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_XX_impl.cc.t0000664000175000017500000000356212207440367022060 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc *= ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/nop_impl.h0000664000175000017500000000335112207440367017752 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_NOP_IMPL_H #define INCLUDED_GR_NOP_IMPL_H #include namespace gr { namespace blocks { class nop_impl : public nop { protected: int d_nmsgs_recvd; int d_ctrlport_test; // Method that just counts any received messages. void count_received_msgs(pmt::pmt_t msg); public: nop_impl(size_t sizeof_stream_item); ~nop_impl(); void setup_rpc(); int nmsgs_received() const { return d_nmsgs_recvd; } int ctrlport_test() const { return d_ctrlport_test; } void set_ctrlport_test(int x) { d_ctrlport_test = x; } int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_NOP_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/char_to_float_impl.h0000664000175000017500000000274112207440367021764 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHAR_TO_FLOAT_IMPL_H #define INCLUDED_CHAR_TO_FLOAT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API char_to_float_impl : public char_to_float { size_t d_vlen; float d_scale; public: char_to_float_impl(size_t vlen, float scale); virtual float scale() const { return d_scale; } virtual void set_scale(float scale) { d_scale = scale; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CHAR_TO_FLOAT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/interleaved_short_array_to_complex.h0000664000175000017500000000246212207440367025307 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_INTERLEAVED_SHORT_ARRAY_TO_COMPLEX_H #define INCLUDED_INTERLEAVED_SHORT_ARRAY_TO_COMPLEX_H #include #include /* * convert array of interleaved shorts to complex. * the shorts contains real, imaginary, real, imaginary... * nsamples is the number of shorts; it must be even. */ BLOCKS_API void interleaved_short_array_to_complex (const short *in, gr_complex *out, int nsamples); #endif /* INCLUDED_INTERLEAVED_SHORT_ARRAY_TO_COMPLEX_H */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_hier_block2.cc0000664000175000017500000000334312207440367021630 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2008,2009 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include void qa_hier_block2::test_make() { gr::hier_block2_sptr src1(gr::make_hier_block2("test", gr::io_signature::make(1, 1, 1 * sizeof(int)), gr::io_signature::make(1, 1, 1 * sizeof(int)))); CPPUNIT_ASSERT(src1); CPPUNIT_ASSERT_EQUAL(std::string("test"), src1->name()); CPPUNIT_ASSERT_EQUAL(1 * (int) sizeof(int), src1->input_signature()->sizeof_stream_item(0)); CPPUNIT_ASSERT_EQUAL(1, src1->input_signature()->min_streams()); CPPUNIT_ASSERT_EQUAL(1, src1->input_signature()->max_streams()); CPPUNIT_ASSERT_EQUAL(1 * (int) sizeof(int), src1->output_signature()->sizeof_stream_item(0)); CPPUNIT_ASSERT_EQUAL(1, src1->output_signature()->min_streams()); CPPUNIT_ASSERT_EQUAL(1, src1->output_signature()->max_streams()); } gnuradio-3.7.2.1/gr-blocks/lib/complex_to_mag_impl.cc0000664000175000017500000000374612207440367022321 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_mag_impl.h" #include #include namespace gr { namespace blocks { complex_to_mag::sptr complex_to_mag::make(size_t vlen) { return gnuradio::get_initial_sptr(new complex_to_mag_impl(vlen)); } complex_to_mag_impl::complex_to_mag_impl(size_t vlen) : sync_block("complex_to_mag", io_signature::make (1, 1, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int complex_to_mag_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; float *out = (float *) output_items[0]; int noi = noutput_items * d_vlen; // turned out to be faster than aligned/unaligned switching volk_32fc_magnitude_32f_u(out, in, noi); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/endian_swap_impl.h0000664000175000017500000000255312236015303021437 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_ENDIAN_SWAP_IMPL_H #define INCLUDED_GR_ENDIAN_SWAP_IMPL_H #include namespace gr { namespace blocks { class endian_swap_impl : public endian_swap { private: public: endian_swap_impl(size_t item_size_bytes); ~endian_swap_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_ENDIAN_SWAP_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/burst_tagger_impl.h0000664000175000017500000000325512207440367021651 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_BURST_TAGGER_IMPL_H #define INCLUDED_GR_BURST_TAGGER_IMPL_H #include namespace gr { namespace blocks { class burst_tagger_impl : public burst_tagger { private: size_t d_itemsize; bool d_state; pmt::pmt_t d_true_key; pmt::pmt_t d_true_value; pmt::pmt_t d_false_key; pmt::pmt_t d_false_value; pmt::pmt_t d_id; public: burst_tagger_impl(size_t itemsize); ~burst_tagger_impl(); void set_true_tag(const std::string &key, bool value); void set_false_tag(const std::string &key, bool value); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_BURST_TAGGER_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/wavfile.cc0000664000175000017500000001734612241734122017732 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2008,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include //BOOST_BIG_ENDIAN namespace gr { namespace blocks { #define VALID_COMPRESSION_TYPE 0x0001 // Basically, this is the opposite of htonx() and ntohx() // Define host to/from worknet (little endian) short and long #ifdef BOOST_BIG_ENDIAN static inline uint16_t __gri_wav_bs16(uint16_t x) { return (x>>8) | (x<<8); } static inline uint32_t __gri_wav_bs32(uint32_t x) { return (uint32_t(__gri_wav_bs16(uint16_t(x&0xfffful)))<<16) | (__gri_wav_bs16(uint16_t(x>>16))); } #define htowl(x) __gri_wav_bs32(x) #define wtohl(x) __gri_wav_bs32(x) #define htows(x) __gri_wav_bs16(x) #define wtohs(x) __gri_wav_bs16(x) #else #define htowl(x) uint32_t(x) #define wtohl(x) uint32_t(x) #define htows(x) uint16_t(x) #define wtohs(x) uint16_t(x) #endif // BOOST_BIG_ENDIAN // WAV files are always little-endian, so we need some byte switching macros static inline uint32_t host_to_wav(uint32_t x) { return htowl(x); } static inline uint16_t host_to_wav(uint16_t x) { return htows(x); } static inline int16_t host_to_wav(int16_t x) { return htows(x); } static inline uint32_t wav_to_host(uint32_t x) { return wtohl(x); } static inline uint16_t wav_to_host(uint16_t x) { return wtohs(x); } static inline int16_t wav_to_host(int16_t x) { return wtohs(x); } bool wavheader_parse(FILE *fp, unsigned int &sample_rate_o, int &nchans_o, int &bytes_per_sample_o, int &first_sample_pos_o, unsigned int &samples_per_chan_o) { // _o variables take return values char str_buf[8] = {0}; uint32_t file_size; uint32_t fmt_hdr_skip; uint16_t compression_type; uint16_t nchans; uint32_t sample_rate; uint32_t avg_bytes_per_sec; uint16_t block_align; uint16_t bits_per_sample; uint32_t chunk_size; size_t fresult; fresult = fread(str_buf, 1, 4, fp); if(fresult != 4 || strncmp(str_buf, "RIFF", 4) || feof(fp)) { return false; } fresult = fread(&file_size, 1, 4, fp); fresult = fread(str_buf, 1, 8, fp); if(fresult != 8 || strncmp(str_buf, "WAVEfmt ", 8) || feof(fp)) { return false; } fresult = fread(&fmt_hdr_skip, 1, 4, fp); fresult = fread(&compression_type, 1, 2, fp); if(wav_to_host(compression_type) != VALID_COMPRESSION_TYPE) { return false; } fresult = fread(&nchans, 1, 2, fp); fresult = fread(&sample_rate, 1, 4, fp); fresult = fread(&avg_bytes_per_sec, 1, 4, fp); fresult = fread(&block_align, 1, 2, fp); fresult = fread(&bits_per_sample, 1, 2, fp); if(ferror(fp)) { return false; } fmt_hdr_skip = wav_to_host(fmt_hdr_skip); nchans = wav_to_host(nchans); sample_rate = wav_to_host(sample_rate); bits_per_sample = wav_to_host(bits_per_sample); if(bits_per_sample != 8 && bits_per_sample != 16) { return false; } fmt_hdr_skip -= 16; if(fmt_hdr_skip) { if (fseek(fp, fmt_hdr_skip, SEEK_CUR) != 0) { return false; } } // find data chunk fresult = fread(str_buf, 1, 4, fp); // keep parsing chunk until we hit the data chunk while(fresult != 4 || strncmp(str_buf, "data", 4)) { // all good? if(fresult != 4 || ferror(fp) || feof(fp)) { return false; } // get chunk body size and skip fresult = fread(&chunk_size, 1, 4, fp); if(fresult != 4 || ferror(fp) || feof(fp)) { return false; } chunk_size = wav_to_host(chunk_size); if(fseek(fp, chunk_size, SEEK_CUR) != 0) { return false; } // read next chunk type fresult = fread(str_buf, 1, 4, fp); } fresult = fread(&chunk_size, 1, 4, fp); if(ferror(fp)) { return false; } // More byte swapping chunk_size = wav_to_host(chunk_size); // Output values sample_rate_o = (unsigned)sample_rate; nchans_o = (int)nchans; bytes_per_sample_o = (int)(bits_per_sample / 8); first_sample_pos_o = (int)ftell(fp); samples_per_chan_o = (unsigned)(chunk_size / (bytes_per_sample_o * nchans)); return true; } short int wav_read_sample(FILE *fp, int bytes_per_sample) { int16_t buf_16bit; if(fread(&buf_16bit, bytes_per_sample, 1, fp) != 1) { return 0; } if(bytes_per_sample == 1) { return (short)buf_16bit; } return (short)wav_to_host(buf_16bit); } bool wavheader_write(FILE *fp, unsigned int sample_rate, int nchans, int bytes_per_sample) { const int header_len = 44; char wav_hdr[header_len] = "RIFF\0\0\0\0WAVEfmt \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0data\0\0\0"; uint16_t nchans_f = (uint16_t) nchans; uint32_t sample_rate_f = (uint32_t) sample_rate; uint16_t block_align = bytes_per_sample * nchans; uint32_t avg_bytes = sample_rate * block_align; uint16_t bits_per_sample = bytes_per_sample * 8; nchans_f = host_to_wav(nchans_f); sample_rate_f = host_to_wav(sample_rate_f); block_align = host_to_wav(block_align); avg_bytes = host_to_wav(avg_bytes); bits_per_sample = host_to_wav(bits_per_sample); wav_hdr[16] = 0x10; // no extra bytes wav_hdr[20] = 0x01; // no compression memcpy((void*)(wav_hdr + 22), (void*)&nchans_f, 2); memcpy((void*)(wav_hdr + 24), (void*)&sample_rate_f, 4); memcpy((void*)(wav_hdr + 28), (void*)&avg_bytes, 4); memcpy((void*)(wav_hdr + 32), (void*)&block_align, 2); memcpy((void*)(wav_hdr + 34), (void*)&bits_per_sample, 2); fwrite(&wav_hdr, 1, header_len, fp); if(ferror(fp)) { return false; } return true; } void wav_write_sample(FILE *fp, short int sample, int bytes_per_sample) { void *data_ptr; unsigned char buf_8bit; int16_t buf_16bit; if(bytes_per_sample == 1) { buf_8bit = (unsigned char)sample; data_ptr = (void*)&buf_8bit; } else { buf_16bit = host_to_wav((int16_t) sample); data_ptr = (void *) &buf_16bit; } fwrite(data_ptr, 1, bytes_per_sample, fp); } bool wavheader_complete(FILE *fp, unsigned int byte_count) { uint32_t chunk_size = (uint32_t)byte_count; chunk_size = host_to_wav(chunk_size); if (fseek(fp, 40, SEEK_SET) != 0) { return false; } fwrite(&chunk_size, 1, 4, fp); chunk_size = (uint32_t)byte_count + 36; // fmt chunk and data header chunk_size = host_to_wav(chunk_size); if (fseek(fp, 4, SEEK_SET) != 0) { return false; } fwrite(&chunk_size, 1, 4, fp); if(ferror(fp)) { return false; } return true; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/peak_detector2_fb_impl.h0000664000175000017500000000400512207440367022515 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PEAK_DETECTOR2_FB_IMPL_H #define INCLUDED_GR_PEAK_DETECTOR2_FB_IMPL_H #include namespace gr { namespace blocks { class peak_detector2_fb_impl : public peak_detector2_fb { private: float d_threshold_factor_rise; int d_look_ahead; int d_look_ahead_remaining; int d_peak_ind; float d_peak_val; float d_alpha; float d_avg; bool d_found; public: peak_detector2_fb_impl(float threshold_factor_rise, int look_ahead, float alpha); ~peak_detector2_fb_impl(); void set_threshold_factor_rise(float thr) { d_threshold_factor_rise = thr; } void set_look_ahead(int look) { d_look_ahead = look; } void set_alpha(int alpha) { d_alpha = alpha; } float threshold_factor_rise() { return d_threshold_factor_rise; } int look_ahead() { return d_look_ahead; } float alpha() { return d_alpha; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_PEAK_DETECTOR2_FB_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/ctrlport_probe_c_impl.h0000664000175000017500000000330712207440367022521 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CTRLPORT_PROBE_C_IMPL_H #define INCLUDED_CTRLPORT_PROBE_C_IMPL_H #include #include #include namespace gr { namespace blocks { class ctrlport_probe_c_impl : public ctrlport_probe_c { private: boost::shared_mutex ptrlock; std::string d_id; std::string d_desc; const gr_complex* d_ptr; size_t d_ptrLen; public: ctrlport_probe_c_impl(const std::string &id, const std::string &desc); ~ctrlport_probe_c_impl(); void setup_rpc(); std::vector get(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CTRLPORT_GR_CTRLPORT_PROBE_C_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/tagged_stream_to_pdu_impl.h0000664000175000017500000000345312207440367023341 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TAGGED_STREAM_TO_PDU_IMPL_H #define INCLUDED_TAGGED_STREAM_TO_PDU_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API tagged_stream_to_pdu_impl : public tagged_stream_to_pdu { size_t d_itemsize; size_t d_pdu_length; size_t d_pdu_remain; bool d_inpdu; pdu::vector_type d_type; std::vector d_save; pmt::pmt_t d_pdu_meta; pmt::pmt_t d_pdu_vector; pmt::pmt_t d_tag; std::vector::iterator d_tags_itr; std::vector d_tags; public: tagged_stream_to_pdu_impl(pdu::vector_type type, const std::string& lengthtagname); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void send_message(); }; } /* namespace blocks */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-blocks/lib/xor_XX_impl.h.t0000664000175000017500000000242312207440367020646 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_ff_impl.h0000664000175000017500000000252012207440367021505 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_MULTIPLY_FF_IMPL_H #define INCLUDED_BLOCKS_MULTIPLY_FF_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API multiply_ff_impl : public multiply_ff { size_t d_vlen; public: multiply_ff_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_MULTIPLY_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/uchar_array_to_float.cc0000664000175000017500000000217112207440367022461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include void uchar_array_to_float (const unsigned char *in, float *out, int nsamples) { while (nsamples >= 4){ out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; out += 4; in += 4; nsamples -= 4; } while (nsamples-- > 0) *out++ = *in++; } gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_hier_block2_derived.h0000664000175000017500000000237612207440367023201 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2008 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_HIER_BLOCK2_DERIVED_H #define INCLUDED_QA_GR_HIER_BLOCK2_DERIVED_H #include #include #include // Declare a QA test case class qa_hier_block2_derived : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_hier_block2_derived); CPPUNIT_TEST(test_1); CPPUNIT_TEST_SUITE_END(); private: void test_1(); }; #endif /* INCLUDED_QA_GR_HIER_BLOCK2_DERIVED_H */ gnuradio-3.7.2.1/gr-blocks/lib/pdu_to_tagged_stream_impl.cc0000664000175000017500000000733312243430635023475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pdu_to_tagged_stream_impl.h" #include #include namespace gr { namespace blocks { pdu_to_tagged_stream::sptr pdu_to_tagged_stream::make(pdu::vector_type type, const std::string& lengthtagname) { return gnuradio::get_initial_sptr(new pdu_to_tagged_stream_impl(type, lengthtagname)); } pdu_to_tagged_stream_impl::pdu_to_tagged_stream_impl(pdu::vector_type type, const std::string& lengthtagname) : sync_block("pdu_to_tagged_stream", io_signature::make(0, 0, 0), io_signature::make(1, 1, pdu::itemsize(type))), d_itemsize(pdu::itemsize(type)), d_type(type), d_tag(pmt::mp(lengthtagname)) { message_port_register_in(PDU_PORT_ID); } int pdu_to_tagged_stream_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *out = (char *)output_items[0]; int nout = 0; // if we have remaining output, send it if (d_remain.size() > 0) { nout = std::min((size_t)d_remain.size()/d_itemsize, (size_t)noutput_items); memcpy(out, &d_remain[0], nout*d_itemsize); d_remain.erase(d_remain.begin(), d_remain.begin()+nout*d_itemsize); noutput_items -= nout; out += nout*d_itemsize; } // if we have space for at least one item output as much as we can if (noutput_items > 0) { // grab a message if one exists pmt::pmt_t msg(delete_head_nowait(PDU_PORT_ID)); if (msg.get() == NULL) return nout; // make sure type is valid if (!pmt::is_pair(msg)) // TODO: implement pdu::is_valid() throw std::runtime_error("received a malformed pdu message"); // grab the components of the pdu message pmt::pmt_t meta(pmt::car(msg)); pmt::pmt_t vect(pmt::cdr(msg)); // compute offset for output tag uint64_t offset = nitems_written(0) + nout; // add a tag for pdu length add_item_tag(0, offset, d_tag, pmt::from_long(pmt::length(vect)), pmt::mp(alias())); // if we recieved metadata add it as tags if (!pmt::eq(meta, pmt::PMT_NIL) ) { pmt::pmt_t klist(pmt::dict_keys(meta)); for(size_t i=0; i 0) { d_remain.resize(nsave*d_itemsize, 0); memcpy(&d_remain[0], ptr + ncopy*d_itemsize, nsave*d_itemsize); } } return nout; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/vector_map_impl.h0000664000175000017500000000340712207440367021317 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_VECTOR_MAP_IMPL_H #define INCLUDED_GR_VECTOR_MAP_IMPL_H #include #include namespace gr { namespace blocks { class vector_map_impl : public vector_map { private: size_t d_item_size; std::vector d_in_vlens; std::vector< std::vector< std::vector > > d_mapping; gr::thread::mutex d_mutex; // mutex to protect set/work access public: vector_map_impl(size_t item_size, std::vector in_vlens, std::vector< std::vector< std::vector > > mapping); ~vector_map_impl(); void set_mapping(std::vector< std::vector< std::vector > > mapping); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_VECTOR_MAP_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/keep_one_in_n_impl.h0000664000175000017500000000271712207440367021753 0ustar jcorganjcorgan /* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_KEEP_ONE_IN_N_IMPL_H #define INCLUDED_KEEP_ONE_IN_N_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API keep_one_in_n_impl : public keep_one_in_n { int d_n; int d_count; float d_decim_rate; public: keep_one_in_n_impl(size_t itemsize,int n); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); void set_n(int n); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_KEEP_ONE_IN_N_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/null_sink_impl.h0000664000175000017500000000252012207440367021151 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_NULL_SINK_IMPL_H #define INCLUDED_GR_NULL_SINK_IMPL_H #include namespace gr { namespace blocks { class null_sink_impl : public null_sink { public: null_sink_impl(size_t sizeof_stream_item); ~null_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_NULL_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/annotator_alltoall_impl.cc0000664000175000017500000000722012207440367023204 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "annotator_alltoall_impl.h" #include #include #include #include namespace gr { namespace blocks { annotator_alltoall::sptr annotator_alltoall::make(int when, size_t sizeof_stream_item) { return gnuradio::get_initial_sptr (new annotator_alltoall_impl(when, sizeof_stream_item)); } annotator_alltoall_impl::annotator_alltoall_impl(int when, size_t sizeof_stream_item) : sync_block("annotator_alltoall", io_signature::make(1, -1, sizeof_stream_item), io_signature::make(1, -1, sizeof_stream_item)), d_itemsize(sizeof_stream_item), d_when((uint64_t)when) { set_tag_propagation_policy(TPP_ALL_TO_ALL); d_tag_counter = 0; } annotator_alltoall_impl::~annotator_alltoall_impl() { } int annotator_alltoall_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float*)input_items[0]; float *out = (float*)output_items[0]; std::stringstream str; str << name() << unique_id(); uint64_t abs_N = 0, end_N; int ninputs = input_items.size(); for(int i = 0; i < ninputs; i++) { abs_N = nitems_read(i); end_N = abs_N + (uint64_t)(noutput_items); std::vector all_tags; get_tags_in_range(all_tags, i, abs_N, end_N); std::vector::iterator itr; for(itr = all_tags.begin(); itr != all_tags.end(); itr++) { d_stored_tags.push_back(*itr); } } // Source ID and key for any tag that might get applied from this block pmt::pmt_t srcid = pmt::string_to_symbol(str.str()); pmt::pmt_t key = pmt::string_to_symbol("seq"); // Work does nothing to the data stream; just copy all inputs to // outputs Adds a new tag when the number of items read is a // multiple of d_when abs_N = nitems_written(0); int noutputs = output_items.size(); for(int j = 0; j < noutput_items; j++) { for(int i = 0; i < noutputs; i++) { if(abs_N % d_when == 0) { pmt::pmt_t value = pmt::from_uint64(d_tag_counter++); add_item_tag(i, abs_N, key, value, srcid); } // Sum all of the inputs together for each output. Just 'cause. out = (float*)output_items[i]; out[j] = 0; for(int ins = 0; ins < ninputs; ins++) { in = (const float*)input_items[ins]; out[j] += in[j]; } } abs_N++; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/peak_detector_XX_impl.h.t0000664000175000017500000000411312207440367022645 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: float d_threshold_factor_rise; float d_threshold_factor_fall; int d_look_ahead; float d_avg_alpha; float d_avg; unsigned char d_found; public: @NAME_IMPL@(float threshold_factor_rise, float threshold_factor_fall, int look_ahead, float alpha); ~@NAME_IMPL@(); void set_threshold_factor_rise(float thr) { d_threshold_factor_rise = thr; } void set_threshold_factor_fall(float thr) { d_threshold_factor_fall = thr; } void set_look_ahead(int look) { d_look_ahead = look; } void set_alpha(int alpha) { d_avg_alpha = alpha; } float threshold_factor_rise() { return d_threshold_factor_rise; } float threshold_factor_fall() { return d_threshold_factor_fall; } int look_ahead() { return d_look_ahead; } float alpha() { return d_avg_alpha; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/uchar_to_float_impl.h0000664000175000017500000000245712207440367022155 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_UCHAR_TO_FLOAT_IMPL_H #define INCLUDED_UCHAR_TO_FLOAT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API uchar_to_float_impl : public uchar_to_float { public: uchar_to_float_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_UCHAR_TO_FLOAT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/char_to_short_impl.h0000664000175000017500000000251112207440367022011 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CHAR_TO_SHORT_IMPL_H #define INCLUDED_CHAR_TO_SHORT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API char_to_short_impl : public char_to_short { size_t d_vlen; public: char_to_short_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_CHAR_TO_SHORT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_short_impl.h0000664000175000017500000000275012207440367022206 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FLOAT_TO_SHORT_IMPL_H #define INCLUDED_FLOAT_TO_SHORT_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API float_to_short_impl : public float_to_short { size_t d_vlen; float d_scale; public: float_to_short_impl(size_t vlen, float scale); virtual float scale() const { return d_scale; } virtual void set_scale(float scale) { d_scale = scale; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_FLOAT_TO_SHORT_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/udp_source_impl.cc0000664000175000017500000001540712241760655021474 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "udp_source_impl.h" #include #include #include #include #include #include namespace gr { namespace blocks { udp_source::sptr udp_source::make(size_t itemsize, const std::string &ipaddr, int port, int payload_size, bool eof) { return gnuradio::get_initial_sptr (new udp_source_impl(itemsize, ipaddr, port, payload_size, eof)); } udp_source_impl::udp_source_impl(size_t itemsize, const std::string &host, int port, int payload_size, bool eof) : sync_block("udp_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_payload_size(payload_size), d_eof(eof), d_connected(false), d_residual(0), d_sent(0), d_offset(0) { // Give us some more room to play. d_rxbuf = new char[4*d_payload_size]; d_residbuf = new char[50*d_payload_size]; connect(host, port); } udp_source_impl::~udp_source_impl() { if(d_connected) disconnect(); delete [] d_rxbuf; delete [] d_residbuf; } void udp_source_impl::connect(const std::string &host, int port) { if(d_connected) disconnect(); d_host = host; d_port = static_cast(port); std::string s_port; s_port = (boost::format("%d")%d_port).str(); if(host.size() > 0) { boost::asio::ip::udp::resolver resolver(d_io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), d_host, s_port, boost::asio::ip::resolver_query_base::passive); d_endpoint = *resolver.resolve(query); d_socket = new boost::asio::ip::udp::socket(d_io_service); d_socket->open(d_endpoint.protocol()); boost::asio::socket_base::linger loption(true, 0); d_socket->set_option(loption); boost::asio::socket_base::reuse_address roption(true); d_socket->set_option(roption); d_socket->bind(d_endpoint); start_receive(); d_udp_thread = gr::thread::thread(boost::bind(&udp_source_impl::run_io_service, this)); d_connected = true; } } void udp_source_impl::disconnect() { gr::thread::scoped_lock lock(d_setlock); if(!d_connected) return; d_io_service.reset(); d_io_service.stop(); d_udp_thread.join(); d_socket->close(); delete d_socket; d_connected = false; } // Return port number of d_socket int udp_source_impl::get_port(void) { //return d_endpoint.port(); return d_socket->local_endpoint().port(); } void udp_source_impl::start_receive() { d_socket->async_receive_from(boost::asio::buffer((void*)d_rxbuf, d_payload_size), d_endpoint_rcvd, boost::bind(&udp_source_impl::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void udp_source_impl::handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if(!error) { { boost::lock_guard lock(d_udp_mutex); if(d_eof && (bytes_transferred == 1) && (d_rxbuf[0] == 0x00)) { // If we are using EOF notification, test for it and don't // add anything to the output. d_residual = -1; d_cond_wait.notify_one(); return; } else { // Make sure we never go beyond the boundary of the // residual buffer. This will just drop the last bit of // data in the buffer if we've run out of room. if((int)(d_residual + bytes_transferred) >= (50*d_payload_size)) { GR_LOG_WARN(d_logger, "Too much data; dropping packet."); } else { // otherwise, copy received data into local buffer for // copying later. memcpy(d_residbuf+d_residual, d_rxbuf, bytes_transferred); d_residual += bytes_transferred; } } d_cond_wait.notify_one(); } } start_receive(); } int udp_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr::thread::scoped_lock l(d_setlock); char *out = (char*)output_items[0]; // Use async receive_from to get data from UDP buffer and wait // on a conditional signal before proceeding. We use this // because the conditional wait is interruptable while a // synchronous receive_from is not. boost::unique_lock lock(d_udp_mutex); //use timed_wait to avoid permanent blocking in the work function d_cond_wait.timed_wait(lock, boost::posix_time::milliseconds(10)); if(d_residual < 0) return -1; int to_be_sent = (int)(d_residual - d_sent); int to_send = std::min(noutput_items, to_be_sent); // Copy the received data in the residual buffer to the output stream memcpy(out, d_residbuf+d_sent, to_send); int nitems = to_send/d_itemsize; // Keep track of where we are if we don't have enough output // space to send all the data in the residbuf. if(to_send == to_be_sent) { d_residual = 0; d_sent = 0; } else { d_sent += to_send; } return nitems; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/conjugate_cc_impl.cc0000664000175000017500000000370012245466767021754 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "conjugate_cc_impl.h" #include #include namespace gr { namespace blocks { conjugate_cc::sptr conjugate_cc::make() { return gnuradio::get_initial_sptr(new conjugate_cc_impl()); } conjugate_cc_impl::conjugate_cc_impl() : sync_block("conjugate_cc", io_signature::make (1, 1, sizeof(gr_complex)), io_signature::make (1, 1, sizeof(gr_complex))) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } int conjugate_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *iptr = (gr_complex *) input_items[0]; gr_complex *optr = (gr_complex *) output_items[0]; if(is_unaligned()) { volk_32fc_conjugate_32fc_u(optr, iptr, noutput_items); } else { volk_32fc_conjugate_32fc_a(optr, iptr, noutput_items); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_descriptor_sink_impl.h0000664000175000017500000000273012207440367023357 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_DESCRIPTOR_SINK_IMPL_H #define INCLUDED_GR_FILE_DESCRIPTOR_SINK_IMPL_H #include namespace gr { namespace blocks { class file_descriptor_sink_impl : public file_descriptor_sink { private: size_t d_itemsize; int d_fd; public: file_descriptor_sink_impl(size_t itemsize, int fd); ~file_descriptor_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_DESCRIPTOR_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/file_source_impl.cc0000664000175000017500000001117612207440367021617 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "file_source_impl.h" #include #include #include #include #include #include #include // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { file_source::sptr file_source::make(size_t itemsize, const char *filename, bool repeat) { return gnuradio::get_initial_sptr (new file_source_impl(itemsize, filename, repeat)); } file_source_impl::file_source_impl(size_t itemsize, const char *filename, bool repeat) : sync_block("file_source", io_signature::make(0, 0, 0), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_fp(0), d_new_fp(0), d_repeat(repeat), d_updated(false) { open(filename, repeat); } file_source_impl::~file_source_impl() { if(d_fp) fclose ((FILE*)d_fp); if(d_new_fp) fclose ((FILE*)d_new_fp); } bool file_source_impl::seek(long seek_point, int whence) { return fseek((FILE*)d_fp, seek_point *d_itemsize, whence) == 0; } void file_source_impl::open(const char *filename, bool repeat) { // obtain exclusive access for duration of this function gr::thread::scoped_lock lock(fp_mutex); int fd; // we use "open" to use to the O_LARGEFILE flag if((fd = ::open(filename, O_RDONLY | OUR_O_LARGEFILE | OUR_O_BINARY)) < 0) { perror(filename); throw std::runtime_error("can't open file"); } if(d_new_fp) { fclose(d_new_fp); d_new_fp = 0; } if((d_new_fp = fdopen (fd, "rb")) == NULL) { perror(filename); ::close(fd); // don't leak file descriptor if fdopen fails throw std::runtime_error("can't open file"); } d_updated = true; d_repeat = repeat; } void file_source_impl::close() { // obtain exclusive access for duration of this function gr::thread::scoped_lock lock(fp_mutex); if(d_new_fp != NULL) { fclose(d_new_fp); d_new_fp = NULL; } d_updated = true; } void file_source_impl::do_update() { if(d_updated) { gr::thread::scoped_lock lock(fp_mutex); // hold while in scope if(d_fp) fclose(d_fp); d_fp = d_new_fp; // install new file pointer d_new_fp = 0; d_updated = false; } } int file_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *o = (char*)output_items[0]; int i; int size = noutput_items; do_update(); // update d_fp is reqd if(d_fp == NULL) throw std::runtime_error("work with file not open"); gr::thread::scoped_lock lock(fp_mutex); // hold for the rest of this function while(size) { i = fread(o, d_itemsize, size, (FILE*)d_fp); size -= i; o += i * d_itemsize; if(size == 0) // done break; if(i > 0) // short read, try again continue; // We got a zero from fread. This is either EOF or error. In // any event, if we're in repeat mode, seek back to the beginning // of the file and try again, else break if(!d_repeat) break; if(fseek ((FILE *) d_fp, 0, SEEK_SET) == -1) { fprintf(stderr, "[%s] fseek failed\n", __FILE__); exit(-1); } } if(size > 0) { // EOF or error if(size == noutput_items) // we didn't read anything; say we're done return -1; return noutput_items - size; // else return partial result } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/interleave_impl.cc0000664000175000017500000000406712207440367021457 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "interleave_impl.h" #include namespace gr { namespace blocks { interleave::sptr interleave::make(size_t itemsize) { return gnuradio::get_initial_sptr(new interleave_impl(itemsize)); } interleave_impl::interleave_impl(size_t itemsize) : sync_interpolator("interleave", io_signature::make (1, io_signature::IO_INFINITE, itemsize), io_signature::make (1, 1, itemsize), 1), d_itemsize(itemsize) { } bool interleave_impl::check_topology(int ninputs, int noutputs) { set_interpolation(ninputs); return true; } int interleave_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { size_t nchan = input_items.size(); size_t itemsize = d_itemsize; const char **in = (const char **)&input_items[0]; char *out = (char *)output_items[0]; for (int i = 0; i < noutput_items; i += nchan) { for (unsigned int n = 0; n < nchan; n++) { memcpy (out, in[n], itemsize); out += itemsize; in[n] += itemsize; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/stretch_ff_impl.h0000664000175000017500000000304312207440367021303 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2008,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_STRETCH_FF_IMPL_H #define INCLUDED_GR_STRETCH_FF_IMPL_H #include namespace gr { namespace blocks { class stretch_ff_impl : public stretch_ff { private: float d_lo; // the constant size_t d_vlen; public: stretch_ff_impl(float lo, size_t vlen); ~stretch_ff_impl(); float lo() const { return d_lo; } void set_lo(float lo) { d_lo = lo; } size_t vlen() const { return d_vlen; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_STRETCH_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/qa_blocks.h0000664000175000017500000000222512207440367020072 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_GR_BLOCKS_H_ #define _QA_GR_BLOCKS_H_ #include #include //! collect all the tests for the gr-blocks directory class __GR_ATTR_EXPORT qa_blocks { public: //! return suite of tests for all of gr-blocks directory static CppUnit::TestSuite *suite(); }; #endif /* _QA_GR_BLOCKS_H_ */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_ff_impl.cc0000664000175000017500000000411212245466767023066 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace blocks { multiply_const_ff::sptr multiply_const_ff::make(float k, size_t vlen) { return gnuradio::get_initial_sptr(new multiply_const_ff_impl(k, vlen)); } multiply_const_ff_impl::multiply_const_ff_impl(float k, size_t vlen) : sync_block ("multiply_const_ff", io_signature::make (1, 1, sizeof (float)*vlen), io_signature::make (1, 1, sizeof (float)*vlen)), d_k(k), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int multiply_const_ff_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; float *out = (float *) output_items[0]; int noi = d_vlen*noutput_items; if(is_unaligned()) { volk_32f_s32f_multiply_32f_u(out, in, d_k, noi); } else { volk_32f_s32f_multiply_32f_a(out, in, d_k, noi); } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/udp_sink_impl.h0000664000175000017500000000405312207440367020772 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007-2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UDP_SINK_IMPL_H #define INCLUDED_GR_UDP_SINK_IMPL_H #include #include namespace gr { namespace blocks { class udp_sink_impl : public udp_sink { private: size_t d_itemsize; int d_payload_size; // maximum transmission unit (packet length) bool d_eof; // send zero-length packet on disconnect bool d_connected; // are we connected? gr::thread::mutex d_mutex; // protects d_socket and d_connected boost::asio::ip::udp::socket *d_socket; // handle to socket boost::asio::ip::udp::endpoint d_endpoint; boost::asio::io_service d_io_service; public: udp_sink_impl(size_t itemsize, const std::string &host, int port, int payload_size, bool eof); ~udp_sink_impl(); int payload_size() { return d_payload_size; } void connect(const std::string &host, int port); void disconnect(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_UDP_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/pdu.cc0000664000175000017500000000431312207440367017062 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include namespace gr { namespace blocks { namespace pdu { size_t itemsize(vector_type type) { switch(type) { case byte_t: return sizeof(char); case float_t: return sizeof(float); case complex_t: return sizeof(gr_complex); default: throw std::runtime_error("bad PDU type"); } } bool type_matches(vector_type type, pmt::pmt_t v) { switch(type) { case byte_t: return pmt::is_u8vector(v); case float_t: return pmt::is_f32vector(v); case complex_t: return pmt::is_c32vector(v); default: throw std::runtime_error("bad PDU type"); } } pmt::pmt_t make_pdu_vector(vector_type type, const uint8_t *buf, size_t items) { switch(type) { case byte_t: return pmt::init_u8vector(items, buf); case float_t: return pmt::init_f32vector(items, (const float *)buf); case complex_t: return pmt::init_c32vector(items, (const gr_complex *)buf); default: throw std::runtime_error("bad PDU type"); } } vector_type type_from_pmt(pmt::pmt_t vector) { if(pmt::is_u8vector(vector)) return byte_t; if(pmt::is_f32vector(vector)) return float_t; if(pmt::is_c32vector(vector)) return complex_t; throw std::runtime_error("bad PDU type"); } } /* namespace pdu */ } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/probe_rate_impl.cc0000664000175000017500000000740612207440367021443 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "probe_rate_impl.h" #include namespace gr { namespace blocks { probe_rate::sptr probe_rate::make(size_t itemsize, double update_rate_ms, double alpha) { return gnuradio::get_initial_sptr (new probe_rate_impl(itemsize,update_rate_ms,alpha)); } probe_rate_impl::probe_rate_impl(size_t itemsize, double update_rate_ms, double alpha) : sync_block("probe_rate", io_signature::make(1,1,itemsize), io_signature::make(0,0,itemsize)), d_alpha(alpha), d_beta(1.0-alpha), d_avg(0), d_min_update_time(update_rate_ms), d_lastthru(0), d_itemsize(itemsize) { } probe_rate_impl::~probe_rate_impl(){} int probe_rate_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items){ d_lastthru += noutput_items; boost::posix_time::ptime now(boost::posix_time::microsec_clock::local_time()); boost::posix_time::time_duration diff = now - d_last_update; double diff_ms = diff.total_milliseconds(); if(diff_ms >= d_min_update_time){ double rate_this_update = d_lastthru *1e3 / diff_ms; d_lastthru = 0; d_last_update = now; if(d_avg == 0){ d_avg = rate_this_update; } else { d_avg = rate_this_update*d_alpha + d_avg*d_beta; } } return noutput_items; } void probe_rate_impl::setup_rpc(){ #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "rate_items", &probe_rate_impl::rate, pmt::mp(0), pmt::mp(1e6), pmt::mp(1), "items/sec", "Item rate", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "timesincelast", &probe_rate_impl::timesincelast, pmt::mp(0), pmt::mp(d_min_update_time*2), pmt::mp(0), "ms", "Time since last update", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); #endif } void probe_rate_impl::set_alpha(double alpha){ d_alpha = alpha; } double probe_rate_impl::rate(){ return d_avg; } double probe_rate_impl::timesincelast(){ boost::posix_time::ptime now(boost::posix_time::microsec_clock::local_time()); boost::posix_time::time_duration diff = now - d_last_update; return diff.total_milliseconds(); } bool probe_rate_impl::start(){ d_avg = 0; d_lastthru = 0; d_last_update = boost::posix_time::microsec_clock::local_time(); return true; } bool probe_rate_impl::stop(){ return true; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_meta_sink_impl.cc0000664000175000017500000003207712207440367022274 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_meta_sink_impl.h" #include #include #include #include #include #include #include // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { file_meta_sink::sptr file_meta_sink::make(size_t itemsize, const std::string &filename, double samp_rate, double relative_rate, gr_file_types type, bool complex, size_t max_segment_size, const std::string &extra_dict, bool detached_header) { return gnuradio::get_initial_sptr (new file_meta_sink_impl(itemsize, filename, samp_rate, relative_rate, type, complex, max_segment_size, extra_dict, detached_header)); } file_meta_sink_impl::file_meta_sink_impl(size_t itemsize, const std::string &filename, double samp_rate, double relative_rate, gr_file_types type, bool complex, size_t max_segment_size, const std::string &extra_dict, bool detached_header) : sync_block("file_meta_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_samp_rate(samp_rate), d_relative_rate(relative_rate), d_max_seg_size(max_segment_size), d_total_seg_size(0), d_updated(false), d_unbuffered(false) { d_fp = 0; d_new_fp = 0; d_hdr_fp = 0; d_new_hdr_fp = 0; if(detached_header == true) d_state = STATE_DETACHED; else d_state = STATE_INLINE; if(!open(filename)) throw std::runtime_error("file_meta_sink: can't open file\n"); pmt::pmt_t timestamp = pmt::make_tuple(pmt::from_uint64(0), pmt::from_double(0)); // handle extra dictionary d_extra = pmt::make_dict(); if(extra_dict.size() > 0) { pmt::pmt_t extras = pmt::deserialize_str(extra_dict); pmt::pmt_t keys = pmt::dict_keys(extras); pmt::pmt_t vals = pmt::dict_values(extras); size_t nitems = pmt::length(keys); for(size_t i = 0; i < nitems; i++) { d_extra = pmt::dict_add(d_extra, pmt::nth(i, keys), pmt::nth(i, vals)); } } d_extra_size = pmt::serialize_str(d_extra).size(); d_header = pmt::make_dict(); d_header = pmt::dict_add(d_header, pmt::mp("version"), pmt::mp(METADATA_VERSION)); d_header = pmt::dict_add(d_header, pmt::mp("rx_rate"), pmt::mp(samp_rate)); d_header = pmt::dict_add(d_header, pmt::mp("rx_time"), timestamp); d_header = pmt::dict_add(d_header, pmt::mp("size"), pmt::from_long(d_itemsize)); d_header = pmt::dict_add(d_header, pmt::mp("type"), pmt::from_long(type)); d_header = pmt::dict_add(d_header, pmt::mp("cplx"), complex ? pmt::PMT_T : pmt::PMT_F); d_header = pmt::dict_add(d_header, pmt::mp("strt"), pmt::from_uint64(METADATA_HEADER_SIZE+d_extra_size)); d_header = pmt::dict_add(d_header, mp("bytes"), pmt::from_uint64(0)); do_update(); if(d_state == STATE_DETACHED) write_header(d_hdr_fp, d_header, d_extra); else write_header(d_fp, d_header, d_extra); } file_meta_sink_impl::~file_meta_sink_impl() { close(); if(d_fp) { fclose(d_fp); d_fp = 0; } if(d_state == STATE_DETACHED) { if(d_hdr_fp) { fclose(d_hdr_fp); d_hdr_fp = 0; } } } bool file_meta_sink_impl::open(const std::string &filename) { bool ret = true; if(d_state == STATE_DETACHED) { std::string s = filename + ".hdr"; ret = _open(&d_new_hdr_fp, s.c_str()); } ret = ret && _open(&d_new_fp, filename.c_str()); d_updated = true; return ret; } bool file_meta_sink_impl::_open(FILE **fp, const char *filename) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function bool ret = true; int fd; if((fd = ::open(filename, O_WRONLY|O_CREAT|O_TRUNC|OUR_O_LARGEFILE|OUR_O_BINARY, 0664)) < 0){ perror(filename); return false; } if(*fp) { // if we've already got a new one open, close it fclose(*fp); fp = 0; } if((*fp = fdopen(fd, "wb")) == NULL) { perror(filename); ::close(fd); // don't leak file descriptor if fdopen fails. } ret = fp != 0; return ret; } void file_meta_sink_impl::close() { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function update_last_header(); if(d_state == STATE_DETACHED) { if(d_new_hdr_fp) { fclose(d_new_hdr_fp); d_new_hdr_fp = 0; } } if(d_new_fp) { fclose(d_new_fp); d_new_fp = 0; } d_updated = true; } void file_meta_sink_impl::do_update() { if(d_updated) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this block if(d_state == STATE_DETACHED) { if(d_hdr_fp) fclose(d_hdr_fp); d_hdr_fp = d_new_hdr_fp; // install new file pointer d_new_hdr_fp = 0; } if(d_fp) fclose(d_fp); d_fp = d_new_fp; // install new file pointer d_new_fp = 0; d_updated = false; } } void file_meta_sink_impl::write_header(FILE *fp, pmt::pmt_t header, pmt::pmt_t extra) { std::string header_str = pmt::serialize_str(header); std::string extra_str = pmt::serialize_str(extra); if((header_str.size() != METADATA_HEADER_SIZE) && (extra_str.size() != d_extra_size)) throw std::runtime_error("file_meta_sink: header or extras is wrong size.\n"); size_t nwritten = 0; while(nwritten < header_str.size()) { std::string sub = header_str.substr(nwritten); int count = fwrite(sub.c_str(), sizeof(char), sub.size(), fp); nwritten += count; if((count == 0) && (ferror(fp))) { fclose(fp); throw std::runtime_error("file_meta_sink: error writing header to file.\n"); } } nwritten = 0; while(nwritten < extra_str.size()) { std::string sub = extra_str.substr(nwritten); int count = fwrite(sub.c_str(), sizeof(char), sub.size(), fp); nwritten += count; if((count == 0) && (ferror(fp))) { fclose(fp); throw std::runtime_error("file_meta_sink: error writing extra to file.\n"); } } fflush(fp); } void file_meta_sink_impl::update_header(pmt::pmt_t key, pmt::pmt_t value) { // Special handling caveat to transform rate from radio source into // the rate at this sink. if(pmt::eq(key, mp("rx_rate"))) { d_samp_rate = pmt::to_double(value); value = pmt::from_double(d_samp_rate*d_relative_rate); } // If the tag is not part of the standard header, we put it into the // extra data, which either updates the current dictionary or adds a // new item. if(pmt::dict_has_key(d_header, key)) { d_header = pmt::dict_add(d_header, key, value); } else { d_extra = pmt::dict_add(d_extra, key, value); d_extra_size = pmt::serialize_str(d_extra).size(); } } void file_meta_sink_impl::update_last_header() { if(d_state == STATE_DETACHED) update_last_header_detached(); else update_last_header_inline(); } void file_meta_sink_impl::update_last_header_inline() { // Update the last header info with the number of samples this // block represents. size_t hdrlen = pmt::to_uint64(pmt::dict_ref(d_header, mp("strt"), pmt::PMT_NIL)); size_t seg_size = d_itemsize*d_total_seg_size; pmt::pmt_t s = pmt::from_uint64(seg_size); update_header(mp("bytes"), s); update_header(mp("strt"), pmt::from_uint64(METADATA_HEADER_SIZE+d_extra_size)); fseek(d_fp, -seg_size-hdrlen, SEEK_CUR); write_header(d_fp, d_header, d_extra); fseek(d_fp, seg_size, SEEK_CUR); } void file_meta_sink_impl::update_last_header_detached() { // Update the last header info with the number of samples this // block represents. size_t hdrlen = pmt::to_uint64(pmt::dict_ref(d_header, mp("strt"), pmt::PMT_NIL)); size_t seg_size = d_itemsize*d_total_seg_size; pmt::pmt_t s = pmt::from_uint64(seg_size); update_header(mp("bytes"), s); update_header(mp("strt"), pmt::from_uint64(METADATA_HEADER_SIZE+d_extra_size)); fseek(d_hdr_fp, -hdrlen, SEEK_CUR); write_header(d_hdr_fp, d_header, d_extra); } void file_meta_sink_impl::write_and_update() { // New header, so set current size of chunk to 0 and start of chunk // based on current index + header size. //uint64_t loc = get_last_header_loc(); pmt::pmt_t s = pmt::from_uint64(0); update_header(mp("bytes"), s); // If we have multiple tags on the same offset, this makes // sure we just overwrite the same header each time instead // of creating a new header per tag. s = pmt::from_uint64(METADATA_HEADER_SIZE + d_extra_size); update_header(mp("strt"), s); if(d_state == STATE_DETACHED) write_header(d_hdr_fp, d_header, d_extra); else write_header(d_fp, d_header, d_extra); } void file_meta_sink_impl::update_rx_time() { pmt::pmt_t rx_time = pmt::string_to_symbol("rx_time"); pmt::pmt_t r = pmt::dict_ref(d_header, rx_time, pmt::PMT_NIL); uint64_t secs = pmt::to_uint64(pmt::tuple_ref(r, 0)); double fracs = pmt::to_double(pmt::tuple_ref(r, 1)); double diff = d_total_seg_size / (d_samp_rate*d_relative_rate); //std::cerr << "old secs: " << secs << std::endl; //std::cerr << "old fracs: " << fracs << std::endl; //std::cerr << "seg size: " << d_total_seg_size << std::endl; //std::cerr << "diff: " << diff << std::endl; fracs += diff; uint64_t new_secs = static_cast(fracs); secs += new_secs; fracs -= new_secs; //std::cerr << "new secs: " << secs << std::endl; //std::cerr << "new fracs: " << fracs << std::endl << std::endl; r = pmt::make_tuple(pmt::from_uint64(secs), pmt::from_double(fracs)); d_header = pmt::dict_add(d_header, rx_time, r); } int file_meta_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *inbuf = (char*)input_items[0]; int nwritten = 0; do_update(); // update d_fp is reqd if(!d_fp) return noutput_items; // drop output on the floor uint64_t abs_N = nitems_read(0); uint64_t end_N = abs_N + (uint64_t)(noutput_items); std::vector all_tags; get_tags_in_range(all_tags, 0, abs_N, end_N); std::vector::iterator itr; for(itr = all_tags.begin(); itr != all_tags.end(); itr++) { int item_offset = (int)(itr->offset - abs_N); // Write date to file up to the next tag location while(nwritten < item_offset) { size_t towrite = std::min(d_max_seg_size - d_total_seg_size, (size_t)(item_offset - nwritten)); int count = fwrite(inbuf, d_itemsize, towrite, d_fp); if(count == 0) // FIXME add error handling break; nwritten += count; inbuf += count * d_itemsize; d_total_seg_size += count; // Only add a new header if we are not at the position of the // next tag if((d_total_seg_size == d_max_seg_size) && (nwritten < item_offset)) { update_last_header(); update_rx_time(); write_and_update(); d_total_seg_size = 0; } } if(d_total_seg_size > 0) { update_last_header(); update_header(itr->key, itr->value); write_and_update(); d_total_seg_size = 0; } else { update_header(itr->key, itr->value); update_last_header(); } } // Finish up the rest of the data after tags while(nwritten < noutput_items) { size_t towrite = std::min(d_max_seg_size - d_total_seg_size, (size_t)(noutput_items - nwritten)); int count = fwrite(inbuf, d_itemsize, towrite, d_fp); if(count == 0) // FIXME add error handling break; nwritten += count; inbuf += count * d_itemsize; d_total_seg_size += count; if(d_total_seg_size == d_max_seg_size) { update_last_header(); update_rx_time(); write_and_update(); d_total_seg_size = 0; } } if(d_unbuffered) fflush(d_fp); return nwritten; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/sub_XX_impl.h.t0000664000175000017500000000243512207440367020632 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { size_t d_vlen; public: @NAME_IMPL@(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/file_meta_sink_impl.h0000664000175000017500000000521512207440367022130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FILE_META_SINK_IMPL_H #define INCLUDED_BLOCKS_FILE_META_SINK_IMPL_H #include #include #include using namespace pmt; namespace gr { namespace blocks { class file_meta_sink_impl : public file_meta_sink { private: enum meta_state_t { STATE_INLINE=0, STATE_DETACHED }; size_t d_itemsize; double d_samp_rate; double d_relative_rate; size_t d_max_seg_size; size_t d_total_seg_size; pmt_t d_header; pmt_t d_extra; size_t d_extra_size; bool d_updated; bool d_unbuffered; boost::mutex d_mutex; FILE *d_new_fp, *d_new_hdr_fp; FILE *d_fp, *d_hdr_fp; meta_state_t d_state; protected: void write_header(FILE *fp, pmt_t header, pmt_t extra); void update_header(pmt_t key, pmt_t value); void update_last_header(); void update_last_header_inline(); void update_last_header_detached(); void write_and_update(); void update_rx_time(); bool _open(FILE **fp, const char *filename); public: file_meta_sink_impl(size_t itemsize, const std::string &filename, double samp_rate=1, double relative_rate=1, gr_file_types type=GR_FILE_FLOAT, bool complex=true, size_t max_segment_size=1000000, const std::string &extra_dict="", bool detached_header=false); ~file_meta_sink_impl(); bool open(const std::string &filename); void close(); void do_update(); void set_unbuffered(bool unbuffered) { d_unbuffered = unbuffered; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FILE_META_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/mute_XX_impl.h.t0000664000175000017500000000263012207440367021010 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: bool d_mute; public: @NAME_IMPL@(bool mute); ~@NAME_IMPL@(); bool mute() const { return d_mute; } void set_mute(bool mute) { d_mute = mute; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_block.h0000664000175000017500000000240212207440367020374 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_BLOCK_H #define INCLUDED_QA_GR_BLOCK_H #include #include #include class qa_block : public CppUnit::TestCase { CPPUNIT_TEST_SUITE (qa_block); CPPUNIT_TEST (t0); CPPUNIT_TEST (t1); CPPUNIT_TEST (t2); CPPUNIT_TEST (t3); CPPUNIT_TEST_SUITE_END (); private: void t0 (); void t1 (); void t2 (); void t3 (); }; #endif /* INCLUDED_QA_GR_BLOCK_H */ gnuradio-3.7.2.1/gr-blocks/lib/file_descriptor_source_impl.h0000664000175000017500000000337112207440367023715 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_FILE_DESCRIPTOR_SOURCE_IMPL_H #define INCLUDED_GR_FILE_DESCRIPTOR_SOURCE_IMPL_H #include namespace gr { namespace blocks { class file_descriptor_source_impl : public file_descriptor_source { private: size_t d_itemsize; int d_fd; bool d_repeat; unsigned char *d_residue; unsigned long d_residue_len; protected: int read_items(char *buf, int nitems); int handle_residue(char *buf, int nbytes_read); void flush_residue() { d_residue_len = 0; } public: file_descriptor_source_impl(size_t itemsize, int fd, bool repeat); ~file_descriptor_source_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_FILE_DESCRIPTOR_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/stream_mux_impl.h0000664000175000017500000000335212207440367021343 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_STREAM_MUX_IMPL_H #define INCLUDED_STREAM_MUX_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API stream_mux_impl : public stream_mux { private: size_t d_itemsize; unsigned int d_stream; // index of currently selected stream int d_residual; // number if items left to put into current stream gr_vector_int d_lengths; // number if items to pack per stream void increment_stream(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); public: stream_mux_impl(size_t itemsize, const std::vector &lengths); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_STREAM_MUX_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/tags_strobe_impl.cc0000664000175000017500000000530012207702530021615 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "tags_strobe_impl.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace blocks { tags_strobe::sptr tags_strobe::make(size_t sizeof_stream_item, pmt::pmt_t value, uint64_t nsamps) { return gnuradio::get_initial_sptr (new tags_strobe_impl(sizeof_stream_item, value, nsamps)); } tags_strobe_impl::tags_strobe_impl(size_t sizeof_stream_item, pmt::pmt_t value, uint64_t nsamps) : sync_block("tags_strobe", io_signature::make(0, 0, 0), io_signature::make(1, 1, sizeof_stream_item)), d_itemsize(sizeof_stream_item) { set_value(value); set_nsamps(nsamps); } tags_strobe_impl::~tags_strobe_impl() { } void tags_strobe_impl::set_value(pmt::pmt_t value) { d_tag.offset = 0; d_tag.key = pmt::intern("strobe"); d_tag.value = value; d_tag.srcid = alias_pmt(); } void tags_strobe_impl::set_nsamps(uint64_t nsamps) { d_nsamps = nsamps; d_offset = 0; } int tags_strobe_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { void *optr = (void*)output_items[0]; memset(optr, 0, noutput_items * d_itemsize); uint64_t nitems = static_cast(noutput_items) + nitems_written(0); while((nitems - d_offset) > d_nsamps) { d_offset += d_nsamps; d_tag.offset = d_offset; add_item_tag(0, d_tag); } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_short_impl.cc0000664000175000017500000000366312207440367022350 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "float_to_short_impl.h" #include #include namespace gr { namespace blocks { float_to_short::sptr float_to_short::make(size_t vlen, float scale) { return gnuradio::get_initial_sptr(new float_to_short_impl(vlen, scale)); } float_to_short_impl::float_to_short_impl(size_t vlen, float scale) : sync_block("float_to_short", io_signature::make (1, 1, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(short)*vlen)), d_vlen(vlen), d_scale(scale) { const int alignment_multiple = volk_get_alignment() / sizeof(short); set_alignment(std::max(1, alignment_multiple)); } int float_to_short_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; short *out = (short *) output_items[0]; volk_32f_s32f_convert_16i(out, in, d_scale, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/transcendental_impl.cc0000664000175000017500000001255512207440367022327 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "transcendental_impl.h" #include #include #include //complex math #include //real math #include namespace gr { namespace blocks { /*********************************************************************** * work function creation and registration **********************************************************************/ struct map_val_type { work_fcn_type work_fcn; size_t io_size; }; typedef std::map map_type; //construct map on first use idiom static map_type & get_map(void) { static map_type map; return map; } //static initialization of this object registers a function struct transcendental_registrant { transcendental_registrant(const std::string &key, const work_fcn_type &work_fcn, const size_t io_size) { map_val_type val; val.work_fcn = work_fcn; val.io_size = io_size; get_map()[key] = val; } }; //macro to create a work function and register it #define REGISTER_FUNCTION(__fcn__, __type__, __key__) \ static int __key__ ## _work( \ int noutput_items, \ gr_vector_const_void_star &input_items, \ gr_vector_void_star &output_items) \ { \ const __type__ *in = (const __type__ *) input_items[0]; \ __type__ *out = (__type__ *) output_items[0]; \ for (size_t i = 0; i < size_t(noutput_items); i++){ \ out[i] = std::__fcn__(in[i]); \ } \ return noutput_items; \ } \ transcendental_registrant __key__ ## _registrant(#__key__, &__key__ ## _work, sizeof(__type__)); //register work functions for real types #define REGISTER_REAL_FUNCTIONS(__fcn__) \ REGISTER_FUNCTION(__fcn__, float, __fcn__ ## _float) \ REGISTER_FUNCTION(__fcn__, double, __fcn__ ## _double) //register work functions for complex types #define REGISTER_COMPLEX_FUNCTIONS(__fcn__) \ REGISTER_FUNCTION(__fcn__, std::complex, __fcn__ ## _complex_float) \ REGISTER_FUNCTION(__fcn__, std::complex, __fcn__ ## _complex_double) //register both complex and real #define REGISTER_FUNCTIONS(__fcn__) \ REGISTER_REAL_FUNCTIONS(__fcn__) \ REGISTER_COMPLEX_FUNCTIONS(__fcn__) //create and register transcendental work functions REGISTER_FUNCTIONS(cos) REGISTER_FUNCTIONS(sin) REGISTER_FUNCTIONS(tan) REGISTER_REAL_FUNCTIONS(acos) REGISTER_REAL_FUNCTIONS(asin) REGISTER_REAL_FUNCTIONS(atan) REGISTER_FUNCTIONS(cosh) REGISTER_FUNCTIONS(sinh) REGISTER_FUNCTIONS(tanh) REGISTER_FUNCTIONS(exp) REGISTER_FUNCTIONS(log) REGISTER_FUNCTIONS(log10) REGISTER_FUNCTIONS(sqrt) transcendental::sptr transcendental::make(const std::string &name, const std::string &type) { //search for an entry in the map const std::string key = name + "_" + type; const bool has_key = get_map().count(key) != 0; if(!has_key) throw std::runtime_error("could not find transcendental function for " + key); //make a new block with found work function return gnuradio::get_initial_sptr (new transcendental_impl(get_map()[key].work_fcn, get_map()[key].io_size)); } transcendental_impl::transcendental_impl(const work_fcn_type &work_fcn, const size_t io_size) : sync_block("transcendental", io_signature::make(1, 1, io_size), io_signature::make(1, 1, io_size)), _work_fcn(work_fcn) { // NOP } transcendental_impl::~transcendental_impl() { } int transcendental_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { return _work_fcn(noutput_items, input_items, output_items); } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/rms_cf_impl.h0000664000175000017500000000274312207440367020433 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_RMS_CF_IMPL_H #define INCLUDED_BLOCKS_RMS_CF_IMPL_H #include namespace gr { namespace blocks { /*! * \brief RMS average power * \ingroup math_blk */ class rms_cf_impl : public rms_cf { private: double d_alpha, d_beta, d_avg; public: rms_cf_impl(double alpha = 0.0001); ~rms_cf_impl(); void set_alpha(double alpha); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_RMS_CF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/tag_gate_impl.h0000664000175000017500000000267412207440367020740 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_TAG_GATE_IMPL_H #define INCLUDED_BLOCKS_TAG_GATE_IMPL_H #include namespace gr { namespace blocks { class tag_gate_impl : public tag_gate { private: size_t d_item_size; bool d_propagate_tags; public: tag_gate_impl(size_t item_size, bool propagate_tags); ~tag_gate_impl(); void set_propagation(bool propagate_tags); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_TAG_GATE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_real_impl.h0000664000175000017500000000252712207440367022336 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_COMPLEX_TO_REAL_IMPL_H #define INCLUDED_COMPLEX_TO_REAL_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API complex_to_real_impl : public complex_to_real { size_t d_vlen; public: complex_to_real_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_COMPLEX_TO_REAL_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/qa_rotator.cc0000664000175000017500000000403412207440367020445 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include // error vector magnitude __GR_ATTR_UNUSED static float error_vector_mag(gr_complex a, gr_complex b) { return abs(a-b); } void qa_rotator::t1() { static const unsigned int N = 100000; gr::blocks::rotator r; double phase_incr = 2*M_PI / 1003; double phase = 0; // Old code: We increment then return the rotated value, thus we // need to start one tick back r.set_phase(gr_complex(1,0) * // conj(gr_expj(phase_incr))); r.set_phase(gr_complex(1,0)); r.set_phase_incr(gr_expj(phase_incr)); for(unsigned i = 0; i < N; i++) { gr_complex expected = gr_expj(phase); gr_complex actual = r.rotate(gr_complex(1, 0)); #if 0 float evm = error_vector_mag(expected, actual); printf("[%6d] expected: (%8.6f, %8.6f) actual: (%8.6f, %8.6f) evm: %8.6f\n", i, expected.real(), expected.imag(), actual.real(), actual.imag(), evm); #endif CPPUNIT_ASSERT_COMPLEXES_EQUAL(expected, actual, 0.0001); phase += phase_incr; if(phase >= 2*M_PI) phase -= 2*M_PI; } } gnuradio-3.7.2.1/gr-blocks/lib/stream_pdu_base.h0000664000175000017500000000305712207440367021275 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_STREAM_PDU_BASE_H #define INCLUDED_STREAM_PDU_BASE_H #include #include class basic_block; namespace gr { namespace blocks { class stream_pdu_base { public: stream_pdu_base(int MTU=10000); ~stream_pdu_base(); protected: int d_fd; bool d_started; bool d_finished; std::vector d_rxbuf; gr::thread::thread d_thread; pmt::pmt_t d_port; basic_block *d_blk; void run(); void send(pmt::pmt_t msg); bool wait_ready(); void start_rxthread(basic_block *blk, pmt::pmt_t rxport); void stop_rxthread(); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_STREAM_PDU_BASE_H */ gnuradio-3.7.2.1/gr-blocks/lib/peak_detector2_fb_impl.cc0000664000175000017500000000704012207440367022655 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "peak_detector2_fb_impl.h" #include #include namespace gr { namespace blocks { peak_detector2_fb::sptr peak_detector2_fb::make(float threshold_factor_rise, int look_ahead, float alpha) { return gnuradio::get_initial_sptr (new peak_detector2_fb_impl(threshold_factor_rise, look_ahead, alpha)); } peak_detector2_fb_impl::peak_detector2_fb_impl(float threshold_factor_rise, int look_ahead, float alpha) : sync_block("peak_detector2_fb", io_signature::make(1, 1, sizeof(float)), io_signature::make2(1, 2, sizeof(char), sizeof(float))), d_threshold_factor_rise(threshold_factor_rise), d_look_ahead(look_ahead), d_alpha(alpha), d_avg(0.0f), d_found(false) { } peak_detector2_fb_impl::~peak_detector2_fb_impl() { } int peak_detector2_fb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *iptr = (float *)input_items[0]; char *optr = (char *)output_items[0]; assert(noutput_items >= 2); memset(optr, 0, noutput_items*sizeof(char)); for(int i = 0; i < noutput_items; i++) { if(!d_found) { // Have not yet detected presence of peak if(iptr[i] > d_avg * (1.0f + d_threshold_factor_rise)) { d_found = true; d_look_ahead_remaining = d_look_ahead; d_peak_val = -(float)INFINITY; } else { d_avg = d_alpha*iptr[i] + (1.0f - d_alpha)*d_avg; } } else { // Detected presence of peak if(iptr[i] > d_peak_val) { d_peak_val = iptr[i]; d_peak_ind = i; } else if(d_look_ahead_remaining <= 0) { optr[d_peak_ind] = 1; d_found = false; d_avg = iptr[i]; } // Have not yet located peak, loop and keep searching. d_look_ahead_remaining--; } // Every iteration of the loop, write debugging signal out if // connected: if(output_items.size() == 2) { float *sigout = (float *)output_items[1]; sigout[i] = d_avg; } } // loop if(!d_found) return noutput_items; // else if detected presence, keep searching during the next call to work. int tmp = d_peak_ind; d_peak_ind = 1; return tmp - 1; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/probe_signal_X_impl.cc.t0000664000175000017500000000333212207440367022510 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @BASE_NAME@::make() { return gnuradio::get_initial_sptr (new @NAME_IMPL@()); } @NAME_IMPL@::@NAME_IMPL@() : sync_block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@TYPE@)), io_signature::make(0, 0, 0)), d_level(0) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const @TYPE@ *in = (const @TYPE@ *)input_items[0]; if(noutput_items > 0) d_level = in[noutput_items-1]; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_cc_impl.cc0000664000175000017500000000567212245466767023074 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace blocks { multiply_const_cc::sptr multiply_const_cc::make(gr_complex k, size_t vlen) { return gnuradio::get_initial_sptr(new multiply_const_cc_impl(k, vlen)); } multiply_const_cc_impl::multiply_const_cc_impl(gr_complex k, size_t vlen) : sync_block ("multiply_const_cc", io_signature::make (1, 1, sizeof (gr_complex)*vlen), io_signature::make (1, 1, sizeof (gr_complex)*vlen)), d_k(k), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1,alignment_multiple)); } int multiply_const_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; gr_complex *out = (gr_complex *) output_items[0]; int noi = d_vlen*noutput_items; if(is_unaligned()) { volk_32fc_s32fc_multiply_32fc_u(out, in, d_k, noi); } else { volk_32fc_s32fc_multiply_32fc_a(out, in, d_k, noi); } return noutput_items; } void multiply_const_cc_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "Constant", &multiply_const_cc::k, pmt::from_complex(-1000.0f, 0.0f), pmt::from_complex(1000.0f, 0.0f), pmt::from_complex(0.0f, 0.0f), "", "Constant to multiply", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTCPLX | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "Constant", &multiply_const_cc::set_k, pmt::from_complex(-1000.0f, 0.0f), pmt::from_complex(1000.0f, 0.0f), pmt::from_complex(0.0f, 0.0f), "", "Constant to multiply", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/burst_tagger_impl.cc0000664000175000017500000000625412207440367022011 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "burst_tagger_impl.h" #include #include namespace gr { namespace blocks { burst_tagger::sptr burst_tagger::make(size_t itemsize) { return gnuradio::get_initial_sptr (new burst_tagger_impl(itemsize)); } burst_tagger_impl::burst_tagger_impl(size_t itemsize) : sync_block("burst_tagger", io_signature::make2(2, 2, itemsize, sizeof(short)), io_signature::make(1, 1, itemsize)), d_itemsize(itemsize), d_state(false) { std::stringstream str; str << name() << unique_id(); d_true_key = pmt::string_to_symbol("burst"); d_true_value = pmt::PMT_T; d_false_key = pmt::string_to_symbol("burst"); d_false_value = pmt::PMT_F; d_id = pmt::string_to_symbol(str.str()); } burst_tagger_impl::~burst_tagger_impl() { } void burst_tagger_impl::set_true_tag(const std::string &key, bool value) { d_true_key = pmt::string_to_symbol(key); if(value == true) { d_true_value = pmt::PMT_T; } else { d_true_value = pmt::PMT_F; } } void burst_tagger_impl::set_false_tag (const std::string &key, bool value) { d_false_key = pmt::string_to_symbol(key); if(value == true) { d_false_value = pmt::PMT_T; } else { d_false_value = pmt::PMT_F; } } int burst_tagger_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *signal = (const char*)input_items[0]; const short *trigger = (const short*)input_items[1]; char *out = (char*)output_items[0]; memcpy(out, signal, noutput_items * d_itemsize); for(int i = 0; i < noutput_items; i++) { if(trigger[i] > 0) { if(d_state == false) { d_state = true; add_item_tag(0, nitems_written(0)+i, d_true_key, d_true_value, d_id); } } else { if(d_state == true) { d_state = false; add_item_tag(0, nitems_written(0)+i, d_false_key, d_false_value, d_id); } } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/float_array_to_int.h0000664000175000017500000000221612207440367022013 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FLOAT_ARRAY_TO_INT_H #define INCLUDED_BLOCKS_FLOAT_ARRAY_TO_INT_H #include /*! * convert array of floats to int with rounding and saturation. */ BLOCKS_API void float_array_to_int (const float *in, int *out, float scale, int nsamples); #endif /* INCLUDED_BLOCKS_FLOAT_ARRAY_TO_INT_H */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_cc_impl.cc0000664000175000017500000000422612245466767021660 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include namespace gr { namespace blocks { multiply_cc::sptr multiply_cc::make(size_t vlen) { return gnuradio::get_initial_sptr(new multiply_cc_impl(vlen)); } multiply_cc_impl::multiply_cc_impl(size_t vlen) : sync_block("multiply_cc", io_signature::make (1, -1, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(gr_complex)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } int multiply_cc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { gr_complex *out = (gr_complex *) output_items[0]; int noi = d_vlen*noutput_items; memcpy(out, input_items[0], noi*sizeof(gr_complex)); if(is_unaligned()) { for(size_t i = 1; i < input_items.size(); i++) volk_32fc_x2_multiply_32fc_u(out, out, (gr_complex*)input_items[i], noi); } else { for(size_t i = 1; i < input_items.size(); i++) volk_32fc_x2_multiply_32fc_a(out, out, (gr_complex*)input_items[i], noi); } return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/probe_rate_impl.h0000664000175000017500000000325412207440367021302 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_PROBE_RATE_IMPL_H #define INCLUDED_GR_PROBE_RATE_IMPL_H #include namespace gr { namespace blocks { class probe_rate_impl : public probe_rate { private: double d_alpha, d_beta, d_avg; double d_min_update_time; boost::posix_time::ptime d_last_update; uint64_t d_lastthru; size_t d_itemsize; void setup_rpc(); public: probe_rate_impl(size_t itemsize, double update_rate_ms, double alpha = 0.0001); ~probe_rate_impl(); void set_alpha(double alpha); double rate(); double timesincelast(); bool start(); bool stop(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; // end class } /* namespace blocks */ } /* namespace gr */ #endif gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_block.cc0000664000175000017500000000601312207440367020534 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004.2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include // ---------------------------------------------------------------- void qa_block::t0 () { // test creation of sources gr::block_sptr src1(gr::blocks::null_source::make(sizeof (int))); CPPUNIT_ASSERT_EQUAL(std::string("null_source"), src1->name ()); CPPUNIT_ASSERT_EQUAL(0, src1->input_signature()->max_streams ()); CPPUNIT_ASSERT_EQUAL(1, src1->output_signature()->min_streams ()); CPPUNIT_ASSERT_EQUAL(1, src1->output_signature()->max_streams ()); CPPUNIT_ASSERT_EQUAL((int) sizeof(int), src1->output_signature()->sizeof_stream_item (0)); gr::block_sptr src2(gr::blocks::null_source::make(sizeof(short))); CPPUNIT_ASSERT_EQUAL(std::string ("null_source"), src2->name ()); CPPUNIT_ASSERT_EQUAL(0, src2->input_signature()->max_streams ()); CPPUNIT_ASSERT_EQUAL(1, src2->output_signature()->min_streams ()); CPPUNIT_ASSERT_EQUAL(1, src2->output_signature()->max_streams ()); CPPUNIT_ASSERT_EQUAL((int)sizeof (short), src2->output_signature()->sizeof_stream_item (0)); } void qa_block::t1 () { // test creation of sinks gr::block_sptr dst1 (gr::blocks::null_sink::make (sizeof (int))); CPPUNIT_ASSERT_EQUAL (std::string ("null_sink"), dst1->name ()); CPPUNIT_ASSERT_EQUAL (1, dst1->input_signature()->min_streams ()); CPPUNIT_ASSERT_EQUAL (1, dst1->input_signature()->max_streams ()); CPPUNIT_ASSERT_EQUAL ((int) sizeof (int), dst1->input_signature()->sizeof_stream_item (0)); CPPUNIT_ASSERT_EQUAL (0, dst1->output_signature()->max_streams ()); gr::block_sptr dst2 (gr::blocks::null_sink::make (sizeof (short))); CPPUNIT_ASSERT_EQUAL (std::string ("null_sink"), dst2->name ()); CPPUNIT_ASSERT_EQUAL (1, dst2->input_signature()->min_streams ()); CPPUNIT_ASSERT_EQUAL (1, dst2->input_signature()->max_streams ()); CPPUNIT_ASSERT_EQUAL ((int) sizeof (short), dst2->input_signature()->sizeof_stream_item (0)); CPPUNIT_ASSERT_EQUAL (0, dst2->output_signature()->max_streams ()); } void qa_block::t2 () { } void qa_block::t3 () { } gnuradio-3.7.2.1/gr-blocks/lib/test_gr_blocks.cc0000664000175000017500000000256712207440367021307 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include int main(int argc, char **argv) { CppUnit::TextTestRunner runner; std::ofstream xmlfile(get_unittest_path("blocks.xml").c_str()); CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); runner.addTest(qa_blocks::suite()); runner.setOutputter(xmlout); bool was_successful = runner.run("", false); return was_successful ? 0 : 1; } gnuradio-3.7.2.1/gr-blocks/lib/add_const_vXX_impl.h.t0000664000175000017500000000265012207440367022164 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include namespace gr { namespace blocks { class BLOCKS_API @NAME_IMPL@ : public @NAME@ { std::vector<@O_TYPE@> d_k; public: @NAME_IMPL@(std::vector<@O_TYPE@> k); std::vector<@O_TYPE@> k() const { return d_k; } void set_k(std::vector<@O_TYPE@> k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/and_XX_impl.cc.t0000664000175000017500000000354312207440367020742 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc &= ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/message_sink_impl.h0000664000175000017500000000330712207440367021627 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_SINK_IMPL_H #define INCLUDED_GR_MESSAGE_SINK_IMPL_H #include namespace gr { namespace blocks { class message_sink_impl : public message_sink { private: size_t d_itemsize; msg_queue::sptr d_msgq; bool d_dont_block; bool d_tags; std::string d_lengthtagname; uint64_t d_items_read; public: message_sink_impl(size_t itemsize, msg_queue::sptr msgq, bool dont_block); message_sink_impl(size_t itemsize, msg_queue::sptr msgq, bool dont_block, const std::string& lengthtagname); ~message_sink_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_SINK_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/message_strobe_impl.h0000664000175000017500000000315412207440367022161 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_STROBE_IMPL_H #define INCLUDED_GR_MESSAGE_STROBE_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API message_strobe_impl : public message_strobe { private: boost::shared_ptr d_thread; bool d_finished; float d_period_ms; pmt::pmt_t d_msg; void run(); public: message_strobe_impl(pmt::pmt_t msg, float period_ms); ~message_strobe_impl(); void set_msg(pmt::pmt_t msg) { d_msg = msg; } pmt::pmt_t msg() const { return d_msg; } void set_period(float period_ms) { d_period_ms = period_ms; } float period() const { return d_period_ms; } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_STROBE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/rms_ff_impl.h0000664000175000017500000000273512207440367020437 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_RMS_FF_IMPL_H #define INCLUDED_BLOCKS_RMS_FF_IMPL_H #include namespace gr { namespace blocks { /*! * \brief RMS average power * \ingroup math_blk */ class rms_ff_impl : public rms_ff { private: double d_alpha, d_beta, d_avg; public: rms_ff_impl(double alpha = 0.0001); ~rms_ff_impl(); void set_alpha(double alpha); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_RMS_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/interleaved_char_to_complex_impl.cc0000664000175000017500000000412612207702530025036 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "interleaved_char_to_complex_impl.h" #include #include namespace gr { namespace blocks { interleaved_char_to_complex::sptr interleaved_char_to_complex::make(bool vector_input) { return gnuradio::get_initial_sptr(new interleaved_char_to_complex_impl(vector_input)); } interleaved_char_to_complex_impl::interleaved_char_to_complex_impl(bool vector_input) : sync_decimator("interleaved_char_to_complex", gr::io_signature::make (1, 1, (vector_input?2:1)*sizeof(char)), gr::io_signature::make (1, 1, sizeof(gr_complex)), vector_input?1:2), d_vector_input(vector_input) { const int alignment_multiple = volk_get_alignment() / sizeof(gr_complex); set_alignment(std::max(1, alignment_multiple)); } int interleaved_char_to_complex_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const int8_t *in = (const int8_t *) input_items[0]; float *out = (float *) output_items[0]; volk_8i_s32f_convert_32f_u(out, in, 1.0, 2*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/complex_to_mag_squared_impl.cc0000664000175000017500000000375412207440367024044 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "complex_to_mag_squared_impl.h" #include #include namespace gr { namespace blocks { complex_to_mag_squared::sptr complex_to_mag_squared::make(size_t vlen) { return gnuradio::get_initial_sptr(new complex_to_mag_squared_impl(vlen)); } complex_to_mag_squared_impl::complex_to_mag_squared_impl(size_t vlen) : sync_block("complex_to_mag_squared", io_signature::make (1, 1, sizeof(gr_complex)*vlen), io_signature::make (1, 1, sizeof(float)*vlen)), d_vlen(vlen) { const int alignment_multiple = volk_get_alignment() / sizeof(float); set_alignment(std::max(1,alignment_multiple)); } int complex_to_mag_squared_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_complex *in = (const gr_complex *) input_items[0]; float *out = (float *) output_items[0]; int noi = noutput_items * d_vlen; volk_32fc_magnitude_squared_32f(out, in, noi); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_descriptor_sink_impl.cc0000664000175000017500000000471512207440367023522 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_descriptor_sink_impl.h" #include #include #include #include #include #include #include #include #ifdef HAVE_IO_H #include #endif namespace gr { namespace blocks { file_descriptor_sink::sptr file_descriptor_sink::make(size_t itemsize, int fd) { return gnuradio::get_initial_sptr (new file_descriptor_sink_impl(itemsize, fd)); } file_descriptor_sink_impl::file_descriptor_sink_impl(size_t itemsize, int fd) : sync_block("file_descriptor_sink", io_signature::make(1, 1, itemsize), io_signature::make(0, 0, 0)), d_itemsize(itemsize), d_fd(fd) { } file_descriptor_sink_impl::~file_descriptor_sink_impl() { close(d_fd); } int file_descriptor_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { char *inbuf = (char*)input_items[0]; unsigned long byte_size = noutput_items * d_itemsize; while(byte_size > 0) { ssize_t r; r = write(d_fd, inbuf, byte_size); if(r == -1) { if(errno == EINTR) continue; else { perror("file_descriptor_sink"); return -1; // indicate we're done } } else { byte_size -= r; inbuf += r; } } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/or_XX_impl.cc.t0000664000175000017500000000354312207440367020620 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(size_t vlen) { return gnuradio::get_initial_sptr(new @NAME_IMPL@(vlen)); } @NAME_IMPL@::@NAME_IMPL@(size_t vlen) : sync_block ("@NAME@", io_signature::make (1, -1, sizeof (@I_TYPE@)*vlen), io_signature::make (1, 1, sizeof (@O_TYPE@)*vlen)), d_vlen(vlen) { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @O_TYPE@ *optr = (@O_TYPE@ *) output_items[0]; int ninputs = input_items.size (); for (size_t i = 0; i < noutput_items*d_vlen; i++){ @I_TYPE@ acc = ((@I_TYPE@ *) input_items[0])[i]; for (int j = 1; j < ninputs; j++) acc |= ((@I_TYPE@ *) input_items[j])[i]; *optr++ = (@O_TYPE@) acc; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_source_impl.h0000664000175000017500000000330712207440367021456 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_FILE_SOURCE_IMPL_H #define INCLUDED_BLOCKS_FILE_SOURCE_IMPL_H #include #include namespace gr { namespace blocks { class BLOCKS_API file_source_impl : public file_source { private: size_t d_itemsize; FILE *d_fp; FILE *d_new_fp; bool d_repeat; bool d_updated; boost::mutex fp_mutex; void do_update(); public: file_source_impl(size_t itemsize, const char *filename, bool repeat); ~file_source_impl(); bool seek(long seek_point, int whence); void open(const char *filename, bool repeat); void close(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_FILE_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/qa_gr_top_block.h0000664000175000017500000000371212207440367021263 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QA_GR_TOP_BLOCK_H #define INCLUDED_QA_GR_TOP_BLOCK_H #include #include #include class qa_top_block : public CppUnit::TestCase { CPPUNIT_TEST_SUITE(qa_top_block); CPPUNIT_TEST(t0); CPPUNIT_TEST(t1_run); CPPUNIT_TEST(t2_start_stop_wait); CPPUNIT_TEST(t3_lock_unlock); CPPUNIT_TEST(t4_reconfigure); // triggers 'join never returns' bug CPPUNIT_TEST(t5_max_noutputs); CPPUNIT_TEST(t6_reconfig_max_noutputs); CPPUNIT_TEST(t7_max_noutputs_per_block); CPPUNIT_TEST(t8_reconfig_max_noutputs_per_block); CPPUNIT_TEST(t9_max_output_buffer); CPPUNIT_TEST(t10_reconfig_max_output_buffer); CPPUNIT_TEST(t11_set_block_affinity); CPPUNIT_TEST_SUITE_END(); private: void t0(); void t1_run(); void t2_start_stop_wait(); void t3_lock_unlock(); void t4_reconfigure(); void t5_max_noutputs(); void t6_reconfig_max_noutputs(); void t7_max_noutputs_per_block(); void t8_reconfig_max_noutputs_per_block(); void t9_max_output_buffer(); void t10_reconfig_max_output_buffer(); void t11_set_block_affinity(); }; #endif /* INCLUDED_QA_GR_TOP_BLOCK_H */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_uchar_impl.h0000664000175000017500000000245712207440367022155 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FLOAT_TO_UCHAR_IMPL_H #define INCLUDED_FLOAT_TO_UCHAR_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API float_to_uchar_impl : public float_to_uchar { public: float_to_uchar_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_FLOAT_TO_UCHAR_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/random_pdu_impl.h0000664000175000017500000000331512207440367021306 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_SOCKET_PDU_IMPL_H #define INCLUDED_BLOCKS_RANDOM_PDU_IMPL_H #include #include #include namespace gr { namespace blocks { class random_pdu_impl : public random_pdu { private: boost::mt19937 d_rng; boost::uniform_int<> d_urange; boost::uniform_int<> d_brange; boost::variate_generator< boost::mt19937, boost::uniform_int<> > d_rvar; // pdu length boost::variate_generator< boost::mt19937, boost::uniform_int<> > d_bvar; // pdu contents public: random_pdu_impl(int min_items, int max_items); bool start(); void output_random(); void generate_pdu(pmt::pmt_t msg) { output_random(); } void generate_pdu() { output_random(); } }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_BLOCKS_RANDOM_PDU_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/qa_blocks.cc0000664000175000017500000000233212207440367020227 0ustar jcorganjcorgan/* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ /* * This class gathers together all the test cases for the gr-blocks * directory into a single test suite. As you create new test cases, * add them here. */ #include #include #include CppUnit::TestSuite * qa_blocks::suite() { CppUnit::TestSuite *s = new CppUnit::TestSuite("gr-blocks"); s->addTest(qa_block_tags::suite()); s->addTest(qa_rotator::suite()); return s; } gnuradio-3.7.2.1/gr-blocks/lib/plateau_detector_fb_impl.h0000664000175000017500000000311712207440367023151 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_BLOCKS_PLATEAU_DETECTOR_FB_IMPL_H #define INCLUDED_BLOCKS_PLATEAU_DETECTOR_FB_IMPL_H #include namespace gr { namespace blocks { class plateau_detector_fb_impl : public plateau_detector_fb { private: int d_max_len; float d_threshold; public: plateau_detector_fb_impl(int max_len, float threshold); ~plateau_detector_fb_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace blocks } // namespace gr #endif /* INCLUDED_BLOCKS_PLATEAU_DETECTOR_FB_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_complex_impl.h0000664000175000017500000000253612207440367022520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FLOAT_TO_COMPLEX_IMPL_H #define INCLUDED_FLOAT_TO_COMPLEX_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API float_to_complex_impl : public float_to_complex { size_t d_vlen; public: float_to_complex_impl(size_t vlen); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_FLOAT_TO_COMPLEX_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/nop_impl.cc0000664000175000017500000000564112207440367020114 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include #endif #include "nop_impl.h" #include #include namespace gr { namespace blocks { nop::sptr nop::make(size_t sizeof_stream_item) { return gnuradio::get_initial_sptr (new nop_impl(sizeof_stream_item)); } nop_impl::nop_impl (size_t sizeof_stream_item) : block("nop", io_signature::make(0, -1, sizeof_stream_item), io_signature::make(0, -1, sizeof_stream_item)), d_nmsgs_recvd(0) { // Arrange to have count_received_msgs called when messages are received. message_port_register_in(pmt::mp("port")); set_msg_handler(pmt::mp("port"), boost::bind(&nop_impl::count_received_msgs, this, _1)); } nop_impl::~nop_impl() { } // Trivial message handler that just counts them. // (N.B., This feature is used in qa_set_msg_handler) void nop_impl::count_received_msgs(pmt::pmt_t msg) { d_nmsgs_recvd++; } int nop_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { // eat any input that's available for(unsigned i = 0; i < ninput_items.size (); i++) consume(i, ninput_items[i]); return noutput_items; } void nop_impl::setup_rpc() { #ifdef GR_CTRLPORT d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_get( alias(), "test", &nop::ctrlport_test, pmt::mp(-256), pmt::mp(255), pmt::mp(0), "", "Simple testing variable", RPC_PRIVLVL_MIN, DISPNULL))); d_rpc_vars.push_back( rpcbasic_sptr(new rpcbasic_register_set( alias(), "test", &nop::set_ctrlport_test, pmt::mp(-256), pmt::mp(255), pmt::mp(0), "", "Simple testing variable", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/unpacked_to_packed_XX_impl.cc.t0000664000175000017500000001056312207440367024003 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME_IMPL@.h" #include #include namespace gr { namespace blocks { static const unsigned int BITS_PER_TYPE = sizeof(@O_TYPE@) * 8; @NAME@::sptr @NAME@::make(unsigned int bits_per_chunk, endianness_t endianness) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(bits_per_chunk, endianness)); } @NAME_IMPL@::@NAME_IMPL@(unsigned int bits_per_chunk, endianness_t endianness) : block("@NAME@", io_signature::make(1, -1, sizeof(@I_TYPE@)), io_signature::make(1, -1, sizeof(@O_TYPE@))), d_bits_per_chunk(bits_per_chunk), d_endianness(endianness), d_index(0) { assert(bits_per_chunk <= BITS_PER_TYPE); assert(bits_per_chunk > 0); set_relative_rate(bits_per_chunk/(1.0 * BITS_PER_TYPE)); } @NAME_IMPL@::~@NAME_IMPL@() { } void @NAME_IMPL@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = (int)ceil((d_index+noutput_items * 1.0 * BITS_PER_TYPE) / d_bits_per_chunk); unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = input_required; } } unsigned int get_bit_be1(const @I_TYPE@ *in_vector, unsigned int bit_addr, unsigned int bits_per_chunk) { unsigned int byte_addr = (int)bit_addr/bits_per_chunk; @I_TYPE@ x = in_vector[byte_addr]; unsigned int residue = bit_addr - byte_addr * bits_per_chunk; //printf("Bit addr %d byte addr %d residue %d val %d\n",bit_addr,byte_addr,residue,(x>>(bits_per_chunk-1-residue))&1); return (x >> (bits_per_chunk-1-residue)) & 1; } int @NAME_IMPL@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned int index_tmp = d_index; assert(input_items.size() == output_items.size()); int nstreams = input_items.size(); for(int m=0; m< nstreams; m++) { const @I_TYPE@ *in = (@I_TYPE@ *)input_items[m]; @O_TYPE@ *out = (@O_TYPE@ *)output_items[m]; index_tmp=d_index; // per stream processing //assert((ninput_items[m]-d_index)*d_bits_per_chunk >= noutput_items*BITS_PER_TYPE); switch(d_endianness) { case GR_MSB_FIRST: for(int i = 0; i < noutput_items; i++) { @O_TYPE@ tmp=0; for(unsigned int j = 0; j < BITS_PER_TYPE; j++) { tmp = (tmp<<1) | get_bit_be1(in, index_tmp, d_bits_per_chunk); index_tmp++; } out[i] = tmp; } break; case GR_LSB_FIRST: for(int i = 0; i < noutput_items; i++) { unsigned long tmp=0; for(unsigned int j = 0; j < BITS_PER_TYPE; j++) { tmp = (tmp>>1) | (get_bit_be1(in, index_tmp, d_bits_per_chunk) << (BITS_PER_TYPE-1)); index_tmp++; } out[i] = tmp; } break; default: assert(0); } } d_index = index_tmp; consume_each((int)(d_index/d_bits_per_chunk)); d_index = d_index%d_bits_per_chunk; return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/probe_signal_vX_impl.h.t0000664000175000017500000000266512207440367022550 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME_IMPL@ #define @GUARD_NAME_IMPL@ #include #include namespace gr { namespace blocks { class @NAME_IMPL@ : public @NAME@ { private: std::vector<@TYPE@> d_level; size_t d_size; public: @NAME_IMPL@(size_t size); ~@NAME_IMPL@(); std::vector<@TYPE@> level() const { return d_level; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* @GUARD_NAME_IMPL@ */ gnuradio-3.7.2.1/gr-blocks/lib/float_to_char_impl.cc0000664000175000017500000000365612207440367022130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "float_to_char_impl.h" #include #include namespace gr { namespace blocks { float_to_char::sptr float_to_char::make(size_t vlen, float scale) { return gnuradio::get_initial_sptr(new float_to_char_impl(vlen, scale)); } float_to_char_impl::float_to_char_impl(size_t vlen, float scale) : sync_block("float_to_char", io_signature::make (1, 1, sizeof(float)*vlen), io_signature::make (1, 1, sizeof(char)*vlen)), d_vlen(vlen), d_scale(scale) { const int alignment_multiple = volk_get_alignment() / sizeof(char); set_alignment(std::max(1, alignment_multiple)); } int float_to_char_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const float *in = (const float *) input_items[0]; int8_t *out = (int8_t *) output_items[0]; volk_32f_s32f_convert_8i(out, in, d_scale, d_vlen*noutput_items); return noutput_items; } } /* namespace blocks */ }/* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/sample_and_hold_XX_impl.cc.t0000664000175000017500000000363512207440367023313 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <@NAME_IMPL@.h> #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make() { return gnuradio::get_initial_sptr (new @NAME_IMPL@()); } @NAME_IMPL@::@NAME_IMPL@() : sync_block("@BASE_NAME@", io_signature::make2(2, 2, sizeof(@I_TYPE@), sizeof(char)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_data(0) { } @NAME_IMPL@::~@NAME_IMPL@() { } int @NAME_IMPL@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @I_TYPE@ *iptr = (@I_TYPE@ *)input_items[0]; const char *ctrl = (const char *)input_items[1]; @O_TYPE@ *optr = (@O_TYPE@ *)output_items[0]; for(int i = 0; i < noutput_items; i++) { if(ctrl[i]) { d_data = iptr[i]; } optr[i] = d_data; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/file_sink_base.cc0000664000175000017500000000662212237515111021225 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2007,2009,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #include #include #include #include #include // win32 (mingw/msvc) specific #ifdef HAVE_IO_H #include #endif #ifdef O_BINARY #define OUR_O_BINARY O_BINARY #else #define OUR_O_BINARY 0 #endif // should be handled via configure #ifdef O_LARGEFILE #define OUR_O_LARGEFILE O_LARGEFILE #else #define OUR_O_LARGEFILE 0 #endif namespace gr { namespace blocks { file_sink_base::file_sink_base(const char *filename, bool is_binary, bool append) : d_fp(0), d_new_fp(0), d_updated(false), d_is_binary(is_binary), d_append(append) { if (!open(filename)) throw std::runtime_error ("can't open file"); } file_sink_base::~file_sink_base() { close(); if(d_fp) { fclose(d_fp); d_fp = 0; } } bool file_sink_base::open(const char *filename) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function // we use the open system call to get access to the O_LARGEFILE flag. int fd; int flags; if(d_append) { flags = O_WRONLY|O_CREAT|O_APPEND|OUR_O_LARGEFILE|OUR_O_BINARY; } else { flags = O_WRONLY|O_CREAT|O_TRUNC|OUR_O_LARGEFILE|OUR_O_BINARY; } if((fd = ::open(filename, flags, 0664)) < 0){ perror(filename); return false; } if(d_new_fp) { // if we've already got a new one open, close it fclose(d_new_fp); d_new_fp = 0; } if((d_new_fp = fdopen (fd, d_is_binary ? "wb" : "w")) == NULL) { perror (filename); ::close(fd); // don't leak file descriptor if fdopen fails. } d_updated = true; return d_new_fp != 0; } void file_sink_base::close() { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this function if(d_new_fp) { fclose(d_new_fp); d_new_fp = 0; } d_updated = true; } void file_sink_base::do_update() { if(d_updated) { gr::thread::scoped_lock guard(d_mutex); // hold mutex for duration of this block if(d_fp) fclose(d_fp); d_fp = d_new_fp; // install new file pointer d_new_fp = 0; d_updated = false; } } void file_sink_base::set_unbuffered(bool unbuffered) { d_unbuffered = unbuffered; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/multiply_const_ff_impl.h0000664000175000017500000000274112207440367022720 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef INCLUDED_MULTIPLY_CONST_FF_IMPL_H #define INCLUDED_MULTIPLY_CONST_FF_IMPL_H #include namespace gr { namespace blocks { class BLOCKS_API multiply_const_ff_impl : public multiply_const_ff { float d_k; size_t d_vlen; public: multiply_const_ff_impl(float k, size_t vlen); float k() const { return d_k; } void set_k(float k) { d_k = k; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_MULTIPLY_CONST_FF_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/vector_insert_X_impl.cc.t0000664000175000017500000000733312207440367022737 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include #endif #include <@NAME_IMPL@.h> #include #include #include #include namespace gr { namespace blocks { @NAME@::sptr @NAME@::make(const std::vector<@TYPE@> &data, int periodicity, int offset) { return gnuradio::get_initial_sptr (new @NAME_IMPL@(data, periodicity, offset)); } @NAME_IMPL@::@NAME_IMPL@(const std::vector<@TYPE@> &data, int periodicity, int offset) : block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@TYPE@)), io_signature::make(1, 1, sizeof(@TYPE@))), d_data(data), d_offset(offset), d_periodicity(periodicity) { //printf("INITIAL: periodicity = %d, offset = %d\n", periodicity, offset); // some sanity checks assert(offset < periodicity); assert(offset >= 0); assert((size_t)periodicity > data.size()); } @NAME_IMPL@::~@NAME_IMPL@() {} int @NAME_IMPL@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { @TYPE@ *out = (@TYPE@ *)output_items[0]; const @TYPE@ *in = (const @TYPE@ *)input_items[0]; int ii(0), oo(0); while((oo < noutput_items) && (ii < ninput_items[0])) { //printf("oo = %d, ii = %d, d_offset = %d, noutput_items = %d, ninput_items[0] = %d", oo, ii, d_offset, noutput_items, ninput_items[0]); //printf(", d_periodicity = %d\n", d_periodicity); if(d_offset >= ((int)d_data.size())) { // if we are in the copy region int max_copy = std::min(std::min(noutput_items - oo, ninput_items[0] - ii), d_periodicity - d_offset); //printf("copy %d from input\n", max_copy); memcpy( &out[oo], &in[ii], sizeof(@TYPE@)*max_copy ); //printf(" * memcpy returned.\n"); ii += max_copy; oo += max_copy; d_offset = (d_offset + max_copy)%d_periodicity; } else { // if we are in the insertion region int max_copy = std::min(noutput_items - oo, ((int)d_data.size()) - d_offset); //printf("copy %d from d_data[%d] to out[%d]\n", max_copy, d_offset, oo); memcpy(&out[oo], &d_data[d_offset], sizeof(@TYPE@)*max_copy); //printf(" * memcpy returned.\n"); oo += max_copy; d_offset = (d_offset + max_copy)%d_periodicity; //printf(" ## (inelse) oo = %d, d_offset = %d\n", oo, d_offset); } //printf(" # exit else, on to next loop.\n"); } //printf(" # got out of loop\n"); //printf("consume = %d, produce = %d\n", ii, oo); consume_each(ii); return oo; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/lib/message_burst_source_impl.h0000664000175000017500000000336512207440367023406 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_MESSAGE_BURST_SOURCE_IMPL_H #define INCLUDED_GR_MESSAGE_BURST_SOURCE_IMPL_H #include #include namespace gr { namespace blocks { class message_burst_source_impl : public message_burst_source { private: size_t d_itemsize; msg_queue::sptr d_msgq; message::sptr d_msg; unsigned d_msg_offset; bool d_eof; pmt::pmt_t d_me; public: message_burst_source_impl(size_t itemsize, int msgq_limit); message_burst_source_impl(size_t itemsize, msg_queue::sptr msgq); ~message_burst_source_impl(); msg_queue::sptr msgq() const { return d_msgq; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace blocks */ } /* namespace gr */ #endif /* INCLUDED_GR_MESSAGE_BURST_SOURCE_IMPL_H */ gnuradio-3.7.2.1/gr-blocks/lib/repeat_impl.cc0000664000175000017500000000354512207440367020601 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "repeat_impl.h" #include namespace gr { namespace blocks { repeat::sptr repeat::make(size_t itemsize, int interp) { return gnuradio::get_initial_sptr(new repeat_impl(itemsize, interp)); } repeat_impl::repeat_impl(size_t itemsize, int interp) : sync_interpolator("repeat", io_signature::make (1, 1, itemsize), io_signature::make (1, 1, itemsize), interp), d_itemsize(itemsize), d_interp(interp) { } int repeat_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const char *in = (const char *) input_items[0]; char *out = (char *)output_items[0]; for (int i = 0; i < noutput_items/d_interp; i++) { for (int j = 0; j < d_interp; j++) { memcpy(out, in, d_itemsize); out += d_itemsize; } in += d_itemsize; } return noutput_items; } } /* namespace blocks */ } /* namespace gr */ gnuradio-3.7.2.1/gr-blocks/gnuradio-blocks.pc.in0000664000175000017500000000037512207440367021235 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-blocks Description: GNU Radio basic block library Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-blocks Cflags: -I${includedir} gnuradio-3.7.2.1/gr-blocks/swig/0000775000175000017500000000000012245466767016203 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/swig/CMakeLists.txt0000664000175000017500000000545612207440367020737 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/blocks_swig.py.in ${CMAKE_CURRENT_BINARY_DIR}/blocks_swig.py @ONLY) # We split up the swig files into multiple sections to minimize the # memory overhead. If a .i file grows too large, create a new file # named 'blocks_swigN.i' and add it to this list. # # Also add the line "from swig_blocksN import *" line to # blocks_swig.py.in. set(GR_SWIG_BLOCK_IFILES blocks_swig0 blocks_swig1 blocks_swig2 blocks_swig3 blocks_swig4 blocks_swig5 ) foreach(swigfile ${GR_SWIG_BLOCK_IFILES}) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/${swigfile}_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/blocks ${CMAKE_CURRENT_BINARY_DIR}/../include/gnuradio/blocks ) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_TARGET_DEPS blocks_generated_includes) set(GR_SWIG_LIBRARIES gnuradio-blocks) GR_SWIG_MAKE(${swigfile} ${swigfile}.i) GR_SWIG_INSTALL( TARGETS ${swigfile} DESTINATION ${GR_PYTHON_DIR}/gnuradio/blocks COMPONENT "blocks_python") list(APPEND SWIGFILES ${swigfile}.i) list(APPEND SWIGDOCFILES ${CMAKE_CURRENT_BINARY_DIR}/${swigfile}_doc.i) endforeach(swigfile) install( FILES ${SWIGFILES} ${SWIGDOCFILES} DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "blocks_swig" ) # Install the Python file that pulls in the swig built files. GR_PYTHON_INSTALL( FILES ${CMAKE_CURRENT_BINARY_DIR}/blocks_swig.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/blocks COMPONENT "blocks_python" ) gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig1.i0000664000175000017500000001152012237515112020717 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define BLOCKS_API %include "gnuradio.i" %include "blocks_swig1_doc.i" %{ #include "gnuradio/blocks/skiphead.h" #include "gnuradio/blocks/stream_mux.h" #include "gnuradio/blocks/stream_to_streams.h" #include "gnuradio/blocks/stream_to_tagged_stream.h" #include "gnuradio/blocks/stream_to_vector.h" #include "gnuradio/blocks/streams_to_stream.h" #include "gnuradio/blocks/streams_to_vector.h" #include "gnuradio/blocks/tag_debug.h" #include "gnuradio/blocks/tagged_file_sink.h" #include "gnuradio/blocks/throttle.h" #include "gnuradio/blocks/vector_map.h" #include "gnuradio/blocks/vector_to_stream.h" #include "gnuradio/blocks/vector_to_streams.h" #include "gnuradio/blocks/vector_insert_b.h" #include "gnuradio/blocks/vector_insert_s.h" #include "gnuradio/blocks/vector_insert_i.h" #include "gnuradio/blocks/vector_insert_f.h" #include "gnuradio/blocks/vector_insert_c.h" #include "gnuradio/blocks/vector_sink_b.h" #include "gnuradio/blocks/vector_sink_s.h" #include "gnuradio/blocks/vector_sink_i.h" #include "gnuradio/blocks/vector_sink_f.h" #include "gnuradio/blocks/vector_sink_c.h" #include "gnuradio/blocks/vector_source_b.h" #include "gnuradio/blocks/vector_source_s.h" #include "gnuradio/blocks/vector_source_i.h" #include "gnuradio/blocks/vector_source_f.h" #include "gnuradio/blocks/vector_source_c.h" #include "gnuradio/blocks/wavfile_sink.h" #include "gnuradio/blocks/wavfile_source.h" %} %include "gnuradio/blocks/skiphead.h" %include "gnuradio/blocks/stream_mux.h" %include "gnuradio/blocks/stream_to_streams.h" %include "gnuradio/blocks/stream_to_tagged_stream.h" %include "gnuradio/blocks/stream_to_vector.h" %include "gnuradio/blocks/streams_to_stream.h" %include "gnuradio/blocks/streams_to_vector.h" %include "gnuradio/blocks/tag_debug.h" %include "gnuradio/blocks/tagged_file_sink.h" %include "gnuradio/blocks/throttle.h" %include "gnuradio/blocks/vector_map.h" %include "gnuradio/blocks/vector_to_stream.h" %include "gnuradio/blocks/vector_to_streams.h" %include "gnuradio/blocks/vector_insert_b.h" %include "gnuradio/blocks/vector_insert_s.h" %include "gnuradio/blocks/vector_insert_i.h" %include "gnuradio/blocks/vector_insert_f.h" %include "gnuradio/blocks/vector_insert_c.h" %include "gnuradio/blocks/vector_sink_b.h" %include "gnuradio/blocks/vector_sink_s.h" %include "gnuradio/blocks/vector_sink_i.h" %include "gnuradio/blocks/vector_sink_f.h" %include "gnuradio/blocks/vector_sink_c.h" %include "gnuradio/blocks/vector_source_b.h" %include "gnuradio/blocks/vector_source_s.h" %include "gnuradio/blocks/vector_source_i.h" %include "gnuradio/blocks/vector_source_f.h" %include "gnuradio/blocks/vector_source_c.h" %include "gnuradio/blocks/wavfile_sink.h" %include "gnuradio/blocks/wavfile_source.h" GR_SWIG_BLOCK_MAGIC2(blocks, skiphead); GR_SWIG_BLOCK_MAGIC2(blocks, stream_mux); GR_SWIG_BLOCK_MAGIC2(blocks, stream_to_streams); GR_SWIG_BLOCK_MAGIC2(blocks, stream_to_tagged_stream); GR_SWIG_BLOCK_MAGIC2(blocks, stream_to_vector); GR_SWIG_BLOCK_MAGIC2(blocks, streams_to_stream); GR_SWIG_BLOCK_MAGIC2(blocks, streams_to_vector); GR_SWIG_BLOCK_MAGIC2(blocks, tag_debug); GR_SWIG_BLOCK_MAGIC2(blocks, tagged_file_sink); GR_SWIG_BLOCK_MAGIC2(blocks, throttle); GR_SWIG_BLOCK_MAGIC2(blocks, vector_map); GR_SWIG_BLOCK_MAGIC2(blocks, vector_to_stream); GR_SWIG_BLOCK_MAGIC2(blocks, vector_to_streams); GR_SWIG_BLOCK_MAGIC2(blocks, vector_insert_b); GR_SWIG_BLOCK_MAGIC2(blocks, vector_insert_s); GR_SWIG_BLOCK_MAGIC2(blocks, vector_insert_i); GR_SWIG_BLOCK_MAGIC2(blocks, vector_insert_f); GR_SWIG_BLOCK_MAGIC2(blocks, vector_insert_c); GR_SWIG_BLOCK_MAGIC2(blocks, vector_sink_b); GR_SWIG_BLOCK_MAGIC2(blocks, vector_sink_s); GR_SWIG_BLOCK_MAGIC2(blocks, vector_sink_i); GR_SWIG_BLOCK_MAGIC2(blocks, vector_sink_f); GR_SWIG_BLOCK_MAGIC2(blocks, vector_sink_c); GR_SWIG_BLOCK_MAGIC2(blocks, vector_source_b); GR_SWIG_BLOCK_MAGIC2(blocks, vector_source_s); GR_SWIG_BLOCK_MAGIC2(blocks, vector_source_i); GR_SWIG_BLOCK_MAGIC2(blocks, vector_source_f); GR_SWIG_BLOCK_MAGIC2(blocks, vector_source_c); GR_SWIG_BLOCK_MAGIC2(blocks, wavfile_sink); GR_SWIG_BLOCK_MAGIC2(blocks, wavfile_source); gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig4.i0000664000175000017500000001141412207440367020732 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define BLOCKS_API %include "gnuradio.i" %include "gnuradio/blocks/pdu.h" %include //load generated python docstrings %include "blocks_swig4_doc.i" %{ #include "gnuradio/blocks/nlog10_ff.h" #include "gnuradio/blocks/not_bb.h" #include "gnuradio/blocks/not_ss.h" #include "gnuradio/blocks/not_ii.h" #include "gnuradio/blocks/patterned_interleaver.h" #include "gnuradio/blocks/pack_k_bits_bb.h" #include "gnuradio/blocks/packed_to_unpacked_bb.h" #include "gnuradio/blocks/packed_to_unpacked_ss.h" #include "gnuradio/blocks/packed_to_unpacked_ii.h" #include "gnuradio/blocks/pdu_to_tagged_stream.h" #include "gnuradio/blocks/peak_detector_fb.h" #include "gnuradio/blocks/peak_detector_ib.h" #include "gnuradio/blocks/peak_detector_sb.h" #include "gnuradio/blocks/peak_detector2_fb.h" #include "gnuradio/blocks/plateau_detector_fb.h" #include "gnuradio/blocks/probe_rate.h" #include "gnuradio/blocks/probe_signal_b.h" #include "gnuradio/blocks/probe_signal_s.h" #include "gnuradio/blocks/probe_signal_i.h" #include "gnuradio/blocks/probe_signal_f.h" #include "gnuradio/blocks/probe_signal_c.h" #include "gnuradio/blocks/probe_signal_vb.h" #include "gnuradio/blocks/probe_signal_vs.h" #include "gnuradio/blocks/probe_signal_vi.h" #include "gnuradio/blocks/probe_signal_vf.h" #include "gnuradio/blocks/probe_signal_vc.h" #include "gnuradio/blocks/or_bb.h" #include "gnuradio/blocks/or_ss.h" #include "gnuradio/blocks/or_ii.h" %} %include "gnuradio/blocks/nlog10_ff.h" %include "gnuradio/blocks/not_bb.h" %include "gnuradio/blocks/not_ss.h" %include "gnuradio/blocks/not_ii.h" %include "gnuradio/blocks/probe_signal_b.h" %include "gnuradio/blocks/probe_signal_s.h" %include "gnuradio/blocks/probe_signal_i.h" %include "gnuradio/blocks/probe_signal_f.h" %include "gnuradio/blocks/probe_signal_c.h" %include "gnuradio/blocks/probe_signal_vb.h" %include "gnuradio/blocks/probe_signal_vs.h" %include "gnuradio/blocks/probe_signal_vi.h" %include "gnuradio/blocks/probe_signal_vf.h" %include "gnuradio/blocks/probe_signal_vc.h" %include "gnuradio/blocks/or_bb.h" %include "gnuradio/blocks/or_ss.h" %include "gnuradio/blocks/or_ii.h" %include "gnuradio/blocks/pack_k_bits_bb.h" %include "gnuradio/blocks/packed_to_unpacked_bb.h" %include "gnuradio/blocks/packed_to_unpacked_ss.h" %include "gnuradio/blocks/packed_to_unpacked_ii.h" %include "gnuradio/blocks/patterned_interleaver.h" %include "gnuradio/blocks/pdu_to_tagged_stream.h" %include "gnuradio/blocks/peak_detector_fb.h" %include "gnuradio/blocks/peak_detector_ib.h" %include "gnuradio/blocks/peak_detector_sb.h" %include "gnuradio/blocks/peak_detector2_fb.h" %include "gnuradio/blocks/plateau_detector_fb.h" %include "gnuradio/blocks/probe_rate.h" GR_SWIG_BLOCK_MAGIC2(blocks, nlog10_ff); GR_SWIG_BLOCK_MAGIC2(blocks, not_bb); GR_SWIG_BLOCK_MAGIC2(blocks, not_ss); GR_SWIG_BLOCK_MAGIC2(blocks, not_ii); GR_SWIG_BLOCK_MAGIC2(blocks, patterned_interleaver); GR_SWIG_BLOCK_MAGIC2(blocks, pack_k_bits_bb); GR_SWIG_BLOCK_MAGIC2(blocks, packed_to_unpacked_bb); GR_SWIG_BLOCK_MAGIC2(blocks, packed_to_unpacked_ss); GR_SWIG_BLOCK_MAGIC2(blocks, packed_to_unpacked_ii); GR_SWIG_BLOCK_MAGIC2(blocks, peak_detector_fb); GR_SWIG_BLOCK_MAGIC2(blocks, peak_detector_ib); GR_SWIG_BLOCK_MAGIC2(blocks, peak_detector_sb); GR_SWIG_BLOCK_MAGIC2(blocks, peak_detector2_fb); GR_SWIG_BLOCK_MAGIC2(blocks, plateau_detector_fb); GR_SWIG_BLOCK_MAGIC2(blocks, pdu_to_tagged_stream); GR_SWIG_BLOCK_MAGIC2(blocks, probe_rate); GR_SWIG_BLOCK_MAGIC2(blocks, or_bb); GR_SWIG_BLOCK_MAGIC2(blocks, or_ss); GR_SWIG_BLOCK_MAGIC2(blocks, or_ii); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_b); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_s); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_i); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_f); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_c); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_vb); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_vs); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_vi); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_vf); GR_SWIG_BLOCK_MAGIC2(blocks, probe_signal_vc); gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig.py.in0000664000175000017500000000166112207440367021456 0ustar jcorganjcorgan# # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from blocks_swig0 import * from blocks_swig1 import * from blocks_swig2 import * from blocks_swig3 import * from blocks_swig4 import * from blocks_swig5 import * gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig3.i0000664000175000017500000001421612207702530020725 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define BLOCKS_API %include "gnuradio.i" //load generated python docstrings %include "blocks_swig3_doc.i" %{ #include "gnuradio/blocks/float_to_char.h" #include "gnuradio/blocks/float_to_complex.h" #include "gnuradio/blocks/float_to_int.h" #include "gnuradio/blocks/float_to_short.h" #include "gnuradio/blocks/float_to_uchar.h" #include "gnuradio/blocks/int_to_float.h" #include "gnuradio/blocks/integrate_ss.h" #include "gnuradio/blocks/integrate_ii.h" #include "gnuradio/blocks/integrate_ff.h" #include "gnuradio/blocks/integrate_cc.h" #include "gnuradio/blocks/interleave.h" #include "gnuradio/blocks/interleaved_short_to_complex.h" #include "gnuradio/blocks/interleaved_char_to_complex.h" #include "gnuradio/blocks/keep_m_in_n.h" #include "gnuradio/blocks/keep_one_in_n.h" #include "gnuradio/blocks/lfsr_32k_source_s.h" #include "gnuradio/blocks/max_ff.h" #include "gnuradio/blocks/max_ii.h" #include "gnuradio/blocks/max_ss.h" #include "gnuradio/blocks/moving_average_cc.h" #include "gnuradio/blocks/moving_average_ff.h" #include "gnuradio/blocks/moving_average_ii.h" #include "gnuradio/blocks/moving_average_ss.h" #include "gnuradio/blocks/multiply_ss.h" #include "gnuradio/blocks/multiply_ii.h" #include "gnuradio/blocks/multiply_ff.h" #include "gnuradio/blocks/multiply_cc.h" #include "gnuradio/blocks/multiply_conjugate_cc.h" #include "gnuradio/blocks/multiply_const_ss.h" #include "gnuradio/blocks/multiply_const_ii.h" #include "gnuradio/blocks/multiply_const_ff.h" #include "gnuradio/blocks/multiply_const_cc.h" #include "gnuradio/blocks/multiply_const_vss.h" #include "gnuradio/blocks/multiply_const_vii.h" #include "gnuradio/blocks/multiply_const_vff.h" #include "gnuradio/blocks/multiply_const_vcc.h" #include "gnuradio/blocks/mute_ss.h" #include "gnuradio/blocks/mute_ii.h" #include "gnuradio/blocks/mute_ff.h" #include "gnuradio/blocks/mute_cc.h" %} %include "gnuradio/blocks/float_to_char.h" %include "gnuradio/blocks/float_to_complex.h" %include "gnuradio/blocks/float_to_int.h" %include "gnuradio/blocks/float_to_short.h" %include "gnuradio/blocks/float_to_uchar.h" %include "gnuradio/blocks/int_to_float.h" %include "gnuradio/blocks/integrate_ss.h" %include "gnuradio/blocks/integrate_ii.h" %include "gnuradio/blocks/integrate_ff.h" %include "gnuradio/blocks/integrate_cc.h" %include "gnuradio/blocks/interleave.h" %include "gnuradio/blocks/interleaved_short_to_complex.h" %include "gnuradio/blocks/interleaved_char_to_complex.h" %include "gnuradio/blocks/keep_m_in_n.h" %include "gnuradio/blocks/keep_one_in_n.h" %include "gnuradio/blocks/lfsr_32k_source_s.h" %include "gnuradio/blocks/max_ff.h" %include "gnuradio/blocks/max_ii.h" %include "gnuradio/blocks/max_ss.h" %include "gnuradio/blocks/moving_average_cc.h" %include "gnuradio/blocks/moving_average_ff.h" %include "gnuradio/blocks/moving_average_ii.h" %include "gnuradio/blocks/moving_average_ss.h" %include "gnuradio/blocks/multiply_ss.h" %include "gnuradio/blocks/multiply_ii.h" %include "gnuradio/blocks/multiply_ff.h" %include "gnuradio/blocks/multiply_cc.h" %include "gnuradio/blocks/multiply_conjugate_cc.h" %include "gnuradio/blocks/multiply_const_ss.h" %include "gnuradio/blocks/multiply_const_ii.h" %include "gnuradio/blocks/multiply_const_ff.h" %include "gnuradio/blocks/multiply_const_cc.h" %include "gnuradio/blocks/multiply_const_vss.h" %include "gnuradio/blocks/multiply_const_vii.h" %include "gnuradio/blocks/multiply_const_vff.h" %include "gnuradio/blocks/multiply_const_vcc.h" %include "gnuradio/blocks/mute_ss.h" %include "gnuradio/blocks/mute_ii.h" %include "gnuradio/blocks/mute_ff.h" %include "gnuradio/blocks/mute_cc.h" GR_SWIG_BLOCK_MAGIC2(blocks, float_to_char); GR_SWIG_BLOCK_MAGIC2(blocks, float_to_complex); GR_SWIG_BLOCK_MAGIC2(blocks, float_to_int); GR_SWIG_BLOCK_MAGIC2(blocks, float_to_short); GR_SWIG_BLOCK_MAGIC2(blocks, float_to_uchar); GR_SWIG_BLOCK_MAGIC2(blocks, int_to_float); GR_SWIG_BLOCK_MAGIC2(blocks, integrate_ss); GR_SWIG_BLOCK_MAGIC2(blocks, integrate_ii); GR_SWIG_BLOCK_MAGIC2(blocks, integrate_ff); GR_SWIG_BLOCK_MAGIC2(blocks, integrate_cc); GR_SWIG_BLOCK_MAGIC2(blocks, interleave); GR_SWIG_BLOCK_MAGIC2(blocks, interleaved_short_to_complex); GR_SWIG_BLOCK_MAGIC2(blocks, interleaved_char_to_complex); GR_SWIG_BLOCK_MAGIC2(blocks, keep_m_in_n); GR_SWIG_BLOCK_MAGIC2(blocks, keep_one_in_n); GR_SWIG_BLOCK_MAGIC2(blocks, lfsr_32k_source_s); GR_SWIG_BLOCK_MAGIC2(blocks, max_ff); GR_SWIG_BLOCK_MAGIC2(blocks, max_ii); GR_SWIG_BLOCK_MAGIC2(blocks, max_ss); GR_SWIG_BLOCK_MAGIC2(blocks, moving_average_cc); GR_SWIG_BLOCK_MAGIC2(blocks, moving_average_ff); GR_SWIG_BLOCK_MAGIC2(blocks, moving_average_ii); GR_SWIG_BLOCK_MAGIC2(blocks, moving_average_ss); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_ss); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_ii); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_ff); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_cc); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_conjugate_cc); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_ss); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_ii); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_ff); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_cc); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_vss); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_vii); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_vff); GR_SWIG_BLOCK_MAGIC2(blocks, multiply_const_vcc); GR_SWIG_BLOCK_MAGIC2(blocks, mute_ss); GR_SWIG_BLOCK_MAGIC2(blocks, mute_ii); GR_SWIG_BLOCK_MAGIC2(blocks, mute_ff); GR_SWIG_BLOCK_MAGIC2(blocks, mute_cc); gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig5.i0000664000175000017500000001310612245466767020751 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define BLOCKS_API %include "gnuradio.i" %include "gnuradio/blocks/pdu.h" %include //load generated python docstrings %include "blocks_swig5_doc.i" %{ #include "gnuradio/blocks/random_pdu.h" #include "gnuradio/blocks/regenerate_bb.h" #include "gnuradio/blocks/repack_bits_bb.h" #include "gnuradio/blocks/repeat.h" #include "gnuradio/blocks/rms_cf.h" #include "gnuradio/blocks/rms_ff.h" #include "gnuradio/blocks/sample_and_hold_bb.h" #include "gnuradio/blocks/sample_and_hold_ss.h" #include "gnuradio/blocks/sample_and_hold_ii.h" #include "gnuradio/blocks/sample_and_hold_ff.h" #include "gnuradio/blocks/short_to_char.h" #include "gnuradio/blocks/short_to_float.h" #include "gnuradio/blocks/socket_pdu.h" #include "gnuradio/blocks/stretch_ff.h" #include "gnuradio/blocks/sub_ff.h" #include "gnuradio/blocks/sub_ss.h" #include "gnuradio/blocks/sub_ii.h" #include "gnuradio/blocks/sub_cc.h" #include "gnuradio/blocks/tag_gate.h" #include "gnuradio/blocks/tagged_stream_mux.h" #include "gnuradio/blocks/tagged_stream_to_pdu.h" #include "gnuradio/blocks/tags_strobe.h" #include "gnuradio/blocks/threshold_ff.h" #include "gnuradio/blocks/transcendental.h" #include "gnuradio/blocks/tuntap_pdu.h" #include "gnuradio/blocks/uchar_to_float.h" #include "gnuradio/blocks/udp_sink.h" #include "gnuradio/blocks/udp_source.h" #include "gnuradio/blocks/unpack_k_bits_bb.h" #include "gnuradio/blocks/unpacked_to_packed_bb.h" #include "gnuradio/blocks/unpacked_to_packed_ss.h" #include "gnuradio/blocks/unpacked_to_packed_ii.h" #include "gnuradio/blocks/vco_f.h" #include "gnuradio/blocks/vco_c.h" #include "gnuradio/blocks/xor_bb.h" #include "gnuradio/blocks/xor_ss.h" #include "gnuradio/blocks/xor_ii.h" %} %include "gnuradio/blocks/random_pdu.h" %include "gnuradio/blocks/regenerate_bb.h" %include "gnuradio/blocks/repack_bits_bb.h" %include "gnuradio/blocks/repeat.h" %include "gnuradio/blocks/rms_cf.h" %include "gnuradio/blocks/rms_ff.h" %include "gnuradio/blocks/sample_and_hold_bb.h" %include "gnuradio/blocks/sample_and_hold_ss.h" %include "gnuradio/blocks/sample_and_hold_ii.h" %include "gnuradio/blocks/sample_and_hold_ff.h" %include "gnuradio/blocks/short_to_char.h" %include "gnuradio/blocks/short_to_float.h" %include "gnuradio/blocks/socket_pdu.h" %include "gnuradio/blocks/stretch_ff.h" %include "gnuradio/blocks/sub_ff.h" %include "gnuradio/blocks/sub_ss.h" %include "gnuradio/blocks/sub_ii.h" %include "gnuradio/blocks/sub_cc.h" %include "gnuradio/blocks/tag_gate.h" %include "gnuradio/blocks/tagged_stream_mux.h" %include "gnuradio/blocks/tagged_stream_to_pdu.h" %include "gnuradio/blocks/tags_strobe.h" %include "gnuradio/blocks/threshold_ff.h" %include "gnuradio/blocks/transcendental.h" %include "gnuradio/blocks/tuntap_pdu.h" %include "gnuradio/blocks/uchar_to_float.h" %include "gnuradio/blocks/udp_sink.h" %include "gnuradio/blocks/udp_source.h" %include "gnuradio/blocks/unpack_k_bits_bb.h" %include "gnuradio/blocks/unpacked_to_packed_bb.h" %include "gnuradio/blocks/unpacked_to_packed_ss.h" %include "gnuradio/blocks/unpacked_to_packed_ii.h" %include "gnuradio/blocks/vco_f.h" %include "gnuradio/blocks/vco_c.h" %include "gnuradio/blocks/xor_bb.h" %include "gnuradio/blocks/xor_ss.h" %include "gnuradio/blocks/xor_ii.h" GR_SWIG_BLOCK_MAGIC2(blocks, random_pdu); GR_SWIG_BLOCK_MAGIC2(blocks, regenerate_bb); GR_SWIG_BLOCK_MAGIC2(blocks, repack_bits_bb); GR_SWIG_BLOCK_MAGIC2(blocks, repeat); GR_SWIG_BLOCK_MAGIC2(blocks, rms_cf); GR_SWIG_BLOCK_MAGIC2(blocks, rms_ff); GR_SWIG_BLOCK_MAGIC2(blocks, sample_and_hold_bb); GR_SWIG_BLOCK_MAGIC2(blocks, sample_and_hold_ss); GR_SWIG_BLOCK_MAGIC2(blocks, sample_and_hold_ii); GR_SWIG_BLOCK_MAGIC2(blocks, sample_and_hold_ff); GR_SWIG_BLOCK_MAGIC2(blocks, short_to_char); GR_SWIG_BLOCK_MAGIC2(blocks, short_to_float); GR_SWIG_BLOCK_MAGIC2(blocks, socket_pdu); GR_SWIG_BLOCK_MAGIC2(blocks, stretch_ff); GR_SWIG_BLOCK_MAGIC2(blocks, sub_ff); GR_SWIG_BLOCK_MAGIC2(blocks, sub_ss); GR_SWIG_BLOCK_MAGIC2(blocks, sub_ii); GR_SWIG_BLOCK_MAGIC2(blocks, sub_cc); GR_SWIG_BLOCK_MAGIC2(blocks, tag_gate); GR_SWIG_BLOCK_MAGIC2(blocks, tagged_stream_mux); GR_SWIG_BLOCK_MAGIC2(blocks, tagged_stream_to_pdu); GR_SWIG_BLOCK_MAGIC2(blocks, tags_strobe); GR_SWIG_BLOCK_MAGIC2(blocks, threshold_ff); GR_SWIG_BLOCK_MAGIC2(blocks, transcendental); GR_SWIG_BLOCK_MAGIC2(blocks, tuntap_pdu); GR_SWIG_BLOCK_MAGIC2(blocks, uchar_to_float); GR_SWIG_BLOCK_MAGIC2(blocks, udp_sink); GR_SWIG_BLOCK_MAGIC2(blocks, udp_source); GR_SWIG_BLOCK_MAGIC2(blocks, unpack_k_bits_bb); GR_SWIG_BLOCK_MAGIC2(blocks, unpacked_to_packed_bb); GR_SWIG_BLOCK_MAGIC2(blocks, unpacked_to_packed_ss); GR_SWIG_BLOCK_MAGIC2(blocks, unpacked_to_packed_ii); GR_SWIG_BLOCK_MAGIC2(blocks, vco_f); GR_SWIG_BLOCK_MAGIC2(blocks, vco_c); GR_SWIG_BLOCK_MAGIC2(blocks, xor_bb); GR_SWIG_BLOCK_MAGIC2(blocks, xor_ss); GR_SWIG_BLOCK_MAGIC2(blocks, xor_ii); gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig0.i0000664000175000017500000001112612207702530020717 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define BLOCKS_API %include "gnuradio.i" %include "blocks_swig0_doc.i" %{ #include "gnuradio/blocks/annotator_1to1.h" #include "gnuradio/blocks/annotator_alltoall.h" #include "gnuradio/blocks/annotator_raw.h" #include "gnuradio/blocks/control_loop.h" #include "gnuradio/blocks/copy.h" #include "gnuradio/blocks/delay.h" #include "gnuradio/blocks/endian_swap.h" #include "gnuradio/blocks/file_descriptor_sink.h" #include "gnuradio/blocks/file_descriptor_source.h" #include "gnuradio/blocks/file_sink_base.h" #include "gnuradio/blocks/file_sink.h" #include "gnuradio/blocks/file_source.h" #include "gnuradio/blocks/file_meta_sink.h" #include "gnuradio/blocks/file_meta_source.h" #include "gnuradio/blocks/head.h" #include "gnuradio/blocks/message_debug.h" #include "gnuradio/blocks/message_sink.h" #include "gnuradio/blocks/message_source.h" #include "gnuradio/blocks/message_strobe.h" #include "gnuradio/blocks/message_burst_source.h" #include "gnuradio/blocks/nop.h" #include "gnuradio/blocks/null_sink.h" #include "gnuradio/blocks/null_source.h" %} %include "gnuradio/blocks/annotator_1to1.h" %include "gnuradio/blocks/annotator_alltoall.h" %include "gnuradio/blocks/annotator_raw.h" %include "gnuradio/blocks/control_loop.h" %include "gnuradio/blocks/copy.h" %include "gnuradio/blocks/delay.h" %include "gnuradio/blocks/endian_swap.h" %include "gnuradio/blocks/file_descriptor_sink.h" %include "gnuradio/blocks/file_descriptor_source.h" %include "gnuradio/blocks/file_sink_base.h" %include "gnuradio/blocks/file_sink.h" %include "gnuradio/blocks/file_source.h" %include "gnuradio/blocks/file_meta_sink.h" %include "gnuradio/blocks/file_meta_source.h" %include "gnuradio/blocks/head.h" %include "gnuradio/blocks/message_debug.h" %include "gnuradio/blocks/message_sink.h" %include "gnuradio/blocks/message_source.h" %include "gnuradio/blocks/message_strobe.h" %include "gnuradio/blocks/message_burst_source.h" %include "gnuradio/blocks/nop.h" %include "gnuradio/blocks/null_sink.h" %include "gnuradio/blocks/null_source.h" GR_SWIG_BLOCK_MAGIC2(blocks, annotator_1to1); GR_SWIG_BLOCK_MAGIC2(blocks, annotator_alltoall); GR_SWIG_BLOCK_MAGIC2(blocks, annotator_raw); GR_SWIG_BLOCK_MAGIC2(blocks, copy); GR_SWIG_BLOCK_MAGIC2(blocks, delay); GR_SWIG_BLOCK_MAGIC2(blocks, endian_swap); GR_SWIG_BLOCK_MAGIC2(blocks, file_descriptor_sink); GR_SWIG_BLOCK_MAGIC2(blocks, file_descriptor_source); GR_SWIG_BLOCK_MAGIC2(blocks, file_sink); GR_SWIG_BLOCK_MAGIC2(blocks, file_source); GR_SWIG_BLOCK_MAGIC2(blocks, file_meta_sink); GR_SWIG_BLOCK_MAGIC2(blocks, file_meta_source); GR_SWIG_BLOCK_MAGIC2(blocks, head); GR_SWIG_BLOCK_MAGIC2(blocks, message_debug); GR_SWIG_BLOCK_MAGIC2(blocks, message_sink); GR_SWIG_BLOCK_MAGIC2(blocks, message_source); GR_SWIG_BLOCK_MAGIC2(blocks, message_strobe); GR_SWIG_BLOCK_MAGIC2(blocks, message_burst_source); GR_SWIG_BLOCK_MAGIC2(blocks, nop); GR_SWIG_BLOCK_MAGIC2(blocks, null_sink); GR_SWIG_BLOCK_MAGIC2(blocks, null_source); #ifdef GR_CTRLPORT %{ #include "gnuradio/blocks/ctrlport_probe_c.h" #include "gnuradio/blocks/ctrlport_probe2_c.h" #include "gnuradio/blocks/ctrlport_probe2_f.h" #include "gnuradio/blocks/ctrlport_probe2_s.h" #include "gnuradio/blocks/ctrlport_probe2_i.h" #include "gnuradio/blocks/ctrlport_probe2_b.h" %} %include "gnuradio/blocks/ctrlport_probe_c.h" %include "gnuradio/blocks/ctrlport_probe2_c.h" %include "gnuradio/blocks/ctrlport_probe2_f.h" %include "gnuradio/blocks/ctrlport_probe2_s.h" %include "gnuradio/blocks/ctrlport_probe2_i.h" %include "gnuradio/blocks/ctrlport_probe2_b.h" GR_SWIG_BLOCK_MAGIC2(blocks, ctrlport_probe_c); GR_SWIG_BLOCK_MAGIC2(blocks, ctrlport_probe2_c); GR_SWIG_BLOCK_MAGIC2(blocks, ctrlport_probe2_f); GR_SWIG_BLOCK_MAGIC2(blocks, ctrlport_probe2_s); GR_SWIG_BLOCK_MAGIC2(blocks, ctrlport_probe2_i); GR_SWIG_BLOCK_MAGIC2(blocks, ctrlport_probe2_b); #endif /* GR_CTRLPORT */ gnuradio-3.7.2.1/gr-blocks/swig/blocks_swig2.i0000664000175000017500000001410312207440367020726 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define BLOCKS_API #define GR_RUNTIME_API %include "gnuradio.i" //load generated python docstrings %include "blocks_swig2_doc.i" %include "feval.i" %{ #include "gnuradio/blocks/add_ff.h" #include "gnuradio/blocks/add_ss.h" #include "gnuradio/blocks/add_ii.h" #include "gnuradio/blocks/add_cc.h" #include "gnuradio/blocks/add_const_bb.h" #include "gnuradio/blocks/add_const_ff.h" #include "gnuradio/blocks/add_const_ss.h" #include "gnuradio/blocks/add_const_ii.h" #include "gnuradio/blocks/add_const_cc.h" #include "gnuradio/blocks/add_const_vbb.h" #include "gnuradio/blocks/add_const_vff.h" #include "gnuradio/blocks/add_const_vss.h" #include "gnuradio/blocks/add_const_vii.h" #include "gnuradio/blocks/add_const_vcc.h" #include "gnuradio/blocks/and_bb.h" #include "gnuradio/blocks/and_ss.h" #include "gnuradio/blocks/and_ii.h" #include "gnuradio/blocks/and_const_bb.h" #include "gnuradio/blocks/and_const_ss.h" #include "gnuradio/blocks/and_const_ii.h" #include "gnuradio/blocks/argmax_fs.h" #include "gnuradio/blocks/argmax_is.h" #include "gnuradio/blocks/argmax_ss.h" #include "gnuradio/blocks/bin_statistics_f.h" #include "gnuradio/blocks/burst_tagger.h" #include "gnuradio/blocks/char_to_float.h" #include "gnuradio/blocks/char_to_short.h" #include "gnuradio/blocks/check_lfsr_32k_s.h" #include "gnuradio/blocks/complex_to_interleaved_short.h" #include "gnuradio/blocks/complex_to_float.h" #include "gnuradio/blocks/complex_to_real.h" #include "gnuradio/blocks/complex_to_imag.h" #include "gnuradio/blocks/complex_to_mag.h" #include "gnuradio/blocks/complex_to_mag_squared.h" #include "gnuradio/blocks/complex_to_arg.h" #include "gnuradio/blocks/conjugate_cc.h" #include "gnuradio/blocks/deinterleave.h" #include "gnuradio/blocks/divide_ff.h" #include "gnuradio/blocks/divide_ss.h" #include "gnuradio/blocks/divide_ii.h" #include "gnuradio/blocks/divide_cc.h" %} %include "gnuradio/blocks/add_ff.h" %include "gnuradio/blocks/add_ss.h" %include "gnuradio/blocks/add_ii.h" %include "gnuradio/blocks/add_cc.h" %include "gnuradio/blocks/add_const_bb.h" %include "gnuradio/blocks/add_const_ff.h" %include "gnuradio/blocks/add_const_ss.h" %include "gnuradio/blocks/add_const_ii.h" %include "gnuradio/blocks/add_const_cc.h" %include "gnuradio/blocks/add_const_vbb.h" %include "gnuradio/blocks/add_const_vff.h" %include "gnuradio/blocks/add_const_vss.h" %include "gnuradio/blocks/add_const_vii.h" %include "gnuradio/blocks/add_const_vcc.h" %include "gnuradio/blocks/and_bb.h" %include "gnuradio/blocks/and_ss.h" %include "gnuradio/blocks/and_ii.h" %include "gnuradio/blocks/and_const_bb.h" %include "gnuradio/blocks/and_const_ss.h" %include "gnuradio/blocks/and_const_ii.h" %include "gnuradio/blocks/argmax_fs.h" %include "gnuradio/blocks/argmax_is.h" %include "gnuradio/blocks/argmax_ss.h" %include "gnuradio/blocks/char_to_float.h" %include "gnuradio/blocks/bin_statistics_f.h" %include "gnuradio/blocks/burst_tagger.h" %include "gnuradio/blocks/char_to_short.h" %include "gnuradio/blocks/check_lfsr_32k_s.h" %include "gnuradio/blocks/complex_to_interleaved_short.h" %include "gnuradio/blocks/complex_to_float.h" %include "gnuradio/blocks/complex_to_real.h" %include "gnuradio/blocks/complex_to_imag.h" %include "gnuradio/blocks/complex_to_mag.h" %include "gnuradio/blocks/complex_to_mag_squared.h" %include "gnuradio/blocks/complex_to_arg.h" %include "gnuradio/blocks/conjugate_cc.h" %include "gnuradio/blocks/deinterleave.h" %include "gnuradio/blocks/divide_ff.h" %include "gnuradio/blocks/divide_ss.h" %include "gnuradio/blocks/divide_ii.h" %include "gnuradio/blocks/divide_cc.h" GR_SWIG_BLOCK_MAGIC2(blocks, add_ff); GR_SWIG_BLOCK_MAGIC2(blocks, add_ss); GR_SWIG_BLOCK_MAGIC2(blocks, add_ii); GR_SWIG_BLOCK_MAGIC2(blocks, add_cc); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_bb); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_ff); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_ss); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_ii); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_cc); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_vbb); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_vff); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_vss); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_vii); GR_SWIG_BLOCK_MAGIC2(blocks, add_const_vcc); GR_SWIG_BLOCK_MAGIC2(blocks, and_bb); GR_SWIG_BLOCK_MAGIC2(blocks, and_ss); GR_SWIG_BLOCK_MAGIC2(blocks, and_ii); GR_SWIG_BLOCK_MAGIC2(blocks, and_const_bb); GR_SWIG_BLOCK_MAGIC2(blocks, and_const_ss); GR_SWIG_BLOCK_MAGIC2(blocks, and_const_ii); GR_SWIG_BLOCK_MAGIC2(blocks, argmax_fs); GR_SWIG_BLOCK_MAGIC2(blocks, argmax_is); GR_SWIG_BLOCK_MAGIC2(blocks, argmax_ss); GR_SWIG_BLOCK_MAGIC2(blocks, bin_statistics_f); GR_SWIG_BLOCK_MAGIC2(blocks, burst_tagger); GR_SWIG_BLOCK_MAGIC2(blocks, char_to_float); GR_SWIG_BLOCK_MAGIC2(blocks, char_to_short); GR_SWIG_BLOCK_MAGIC2(blocks, check_lfsr_32k_s); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_interleaved_short); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_float); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_real); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_imag); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_mag); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_mag_squared); GR_SWIG_BLOCK_MAGIC2(blocks, complex_to_arg); GR_SWIG_BLOCK_MAGIC2(blocks, conjugate_cc); GR_SWIG_BLOCK_MAGIC2(blocks, deinterleave); GR_SWIG_BLOCK_MAGIC2(blocks, divide_ff); GR_SWIG_BLOCK_MAGIC2(blocks, divide_ss); GR_SWIG_BLOCK_MAGIC2(blocks, divide_ii); GR_SWIG_BLOCK_MAGIC2(blocks, divide_cc); gnuradio-3.7.2.1/gr-blocks/tests/0000775000175000017500000000000012207440367016356 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/tests/CMakeLists.txt0000664000175000017500000000370712207440367021125 0ustar jcorganjcorgan# Copyright 2010-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrMiscUtils) #check n def GR_CHECK_HDR_N_DEF(sys/resource.h HAVE_SYS_RESOURCE_H) ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${CPPUNIT_INCLUDE_DIRS} ) link_directories( ${Boost_LIBRARY_DIRS} ${CPPUNIT_LIBRARY_DIRS} ) include_directories(${LOG4CPP_INCLUDE_DIRS}) link_directories(${LOG4CPP_LIBRARY_DIRS}) ######################################################################## # Build benchmarks and non-registered tests ######################################################################## set(tests_not_run #single source per test benchmark_nco.cc benchmark_vco.cc ) foreach(test_not_run_src ${tests_not_run}) get_filename_component(name ${test_not_run_src} NAME_WE) add_executable(${name} ${test_not_run_src}) target_link_libraries(${name} test-gnuradio-runtime gnuradio-blocks ${LOG4CPP_LIBRARIES}) endforeach(test_not_run_src) gnuradio-3.7.2.1/gr-blocks/tests/benchmark_vco.cc0000664000175000017500000000757012207440367021477 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004,2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #ifdef HAVE_SYS_RESOURCE_H #include #endif #include #include #include #include #define ITERATIONS 5000000 #define BLOCK_SIZE (10 * 1000) // fits in cache #define FREQ 5003.123 #define K 4.9999999 #define AMPLITUDE 2.444444444 static double timeval_to_double(const struct timeval *tv) { return (double) tv->tv_sec + (double) tv->tv_usec * 1e-6; } static void benchmark(void test (float *x, const float *y), const char *implementation_name) { #ifdef HAVE_SYS_RESOURCE_H struct rusage rusage_start; struct rusage rusage_stop; #else double clock_start; double clock_end; #endif float output[BLOCK_SIZE]; float input[BLOCK_SIZE]; // touch memory memset(output, 0, BLOCK_SIZE*sizeof(float)); for(int i = 0; i 2 * M_PI) phase -= 2 * M_PI; while(phase < -2 * M_PI) phase += 2 * M_PI; } } } void native_vco(float *output, const float *input) { gr::blocks::vco vco; for(int j = 0; j < ITERATIONS/BLOCK_SIZE; j++) { vco.cos(output, input, BLOCK_SIZE, K, AMPLITUDE); } } void fxpt_vco(float *output, const float *input) { gr::blocks::fxpt_vco vco; for(int j = 0; j < ITERATIONS/BLOCK_SIZE; j++) { vco.cos(output, input, BLOCK_SIZE, K, AMPLITUDE); } } // ---------------------------------------------------------------- void nop_fct(float *x, const float *y) { } void nop_loop(float *x, const float *y) { for(int i = 0; i < ITERATIONS; i++) { nop_fct(x, y); } } int main(int argc, char **argv) { benchmark(nop_loop, "nop loop"); benchmark(basic_vco, "basic vco"); benchmark(native_vco, "native vco"); benchmark(fxpt_vco, "fxpt vco"); } gnuradio-3.7.2.1/gr-blocks/tests/benchmark_nco.cc0000664000175000017500000001156612207440367021467 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2004,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include #include #ifdef HAVE_SYS_RESOURCE_H #include #endif #include #include #include #include #define ITERATIONS 20000000 #define BLOCK_SIZE (10 * 1000) // fits in cache #define FREQ 5003.123 static double timeval_to_double(const struct timeval *tv) { return (double)tv->tv_sec + (double)tv->tv_usec * 1e-6; } static void benchmark(void test (float *x, float *y), const char *implementation_name) { #ifdef HAVE_SYS_RESOURCE_H struct rusage rusage_start; struct rusage rusage_stop; #else double clock_start; double clock_end; #endif float output[2*BLOCK_SIZE]; float *x = &output[0], *y = &output[BLOCK_SIZE]; // touch memory memset(output, 0, 2*BLOCK_SIZE*sizeof(float)); // get starting CPU usage #ifdef HAVE_SYS_RESOURCE_H if(getrusage(RUSAGE_SELF, &rusage_start) < 0) { perror("getrusage"); exit(1); } #else clock_start = (double)clock() * (1000000. / CLOCKS_PER_SEC); #endif // do the actual work test(x, y); // get ending CPU usage #ifdef HAVE_SYS_RESOURCE_H if(getrusage(RUSAGE_SELF, &rusage_stop) < 0) { perror("getrusage"); exit(1); } // compute results double user = timeval_to_double(&rusage_stop.ru_utime) - timeval_to_double(&rusage_start.ru_utime); double sys = timeval_to_double(&rusage_stop.ru_stime) - timeval_to_double(&rusage_start.ru_stime); double total = user + sys; #else clock_end = (double)clock() * (1000000. / CLOCKS_PER_SEC); double total = clock_end - clock_start; #endif printf("%18s: cpu: %6.3f steps/sec: %10.3e\n", implementation_name, total, ITERATIONS / total); } // ---------------------------------------------------------------- // Don't compare the _vec with other functions since memory store's // are involved. void basic_sincos_vec(float *x, float *y) { gr::blocks::nco nco; nco.set_freq(2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS/BLOCK_SIZE; i++) { for(int j = 0; j < BLOCK_SIZE; j++) { nco.sincos(&x[2*j+1], &x[2*j]); nco.step(); } } } void native_sincos_vec(float *x, float *y) { gr::blocks::nco nco; nco.set_freq(2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS/BLOCK_SIZE; i++) { nco.sincos((gr_complex*)x, BLOCK_SIZE); } } void fxpt_sincos_vec(float *x, float *y) { gr::blocks::fxpt_nco nco; nco.set_freq (2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS/BLOCK_SIZE; i++) { nco.sincos((gr_complex*)x, BLOCK_SIZE); } } // ---------------------------------------------------------------- void native_sincos(float *x, float *y) { gr::blocks::nco nco; nco.set_freq(2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS; i++) { nco.sincos(x, y); nco.step(); } } void fxpt_sincos(float *x, float *y) { gr::blocks::fxpt_nco nco; nco.set_freq(2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS; i++) { nco.sincos(x, y); nco.step(); } } // ---------------------------------------------------------------- void native_sin(float *x, float *y) { gr::blocks::nco nco; nco.set_freq(2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS; i++) { *x = nco.sin(); nco.step(); } } void fxpt_sin(float *x, float *y) { gr::blocks::fxpt_nco nco; nco.set_freq(2 * M_PI / FREQ); for(int i = 0; i < ITERATIONS; i++) { *x = nco.sin(); nco.step(); } } // ---------------------------------------------------------------- void nop_fct(float *x, float *y) { } void nop_loop(float *x, float *y) { for(int i = 0; i < ITERATIONS; i++) { nop_fct(x, y); } } int main(int argc, char **argv) { benchmark(nop_loop, "nop loop"); benchmark(native_sin, "native sine"); benchmark(fxpt_sin, "fxpt sine"); benchmark(native_sincos, "native sin/cos"); benchmark(fxpt_sincos, "fxpt sin/cos"); benchmark(basic_sincos_vec, "basic sin/cos vec"); benchmark(native_sincos_vec, "native sin/cos vec"); benchmark(fxpt_sincos_vec, "fxpt sin/cos vec"); } gnuradio-3.7.2.1/gr-blocks/tests/nco_results0000664000175000017500000000357512207440367020653 0ustar jcorganjcorgan================================================================ These are on a 1.4 GHz Pentium M using g++ 3.4.1 ================================================================ Default compiler options -O2 nop loop: cpu: 0.015 steps/sec: 6.668e+08 native sine: cpu: 0.900 steps/sec: 1.111e+07 fxpt sine: cpu: 0.281 steps/sec: 3.559e+07 native sin/cos: cpu: 1.138 steps/sec: 8.789e+06 fxpt sin/cos: cpu: 0.550 steps/sec: 1.818e+07 -O2 -march=pentium-m -fomit-frame-pointer nop loop: cpu: 0.015 steps/sec: 6.668e+08 native sine: cpu: 0.903 steps/sec: 1.108e+07 fxpt sine: cpu: 0.271 steps/sec: 3.691e+07 native sin/cos: cpu: 1.092 steps/sec: 9.159e+06 fxpt sin/cos: cpu: 0.542 steps/sec: 1.845e+07 Inlined fxpt::sin & cos -O2 -march=pentium-m -fomit-frame-pointer nop loop: cpu: 0.015 steps/sec: 6.668e+08 native sine: cpu: 0.904 steps/sec: 1.106e+07 fxpt sine: cpu: 0.187 steps/sec: 5.348e+07 native sin/cos: cpu: 1.091 steps/sec: 9.167e+06 fxpt sin/cos: cpu: 0.373 steps/sec: 2.681e+07 ================================================================ These are on a 1.5 GHz Athon MP 1800+ ================================================================ Default compiler options: -O2 nop loop: cpu: 0.013 steps/sec: 7.693e+08 native sine: cpu: 0.733 steps/sec: 1.364e+07 fxpt sine: cpu: 0.210 steps/sec: 4.763e+07 native sin/cos: cpu: 1.183 steps/sec: 8.454e+06 fxpt sin/cos: cpu: 0.420 steps/sec: 2.381e+07 -O2 -fomit-frame-pointer -march=athlon-mp nop loop: cpu: 0.013 steps/sec: 7.693e+08 native sine: cpu: 0.679 steps/sec: 1.473e+07 fxpt sine: cpu: 0.200 steps/sec: 5.001e+07 native sin/cos: cpu: 1.147 steps/sec: 8.720e+06 fxpt sin/cos: cpu: 0.444 steps/sec: 2.253e+07 gnuradio-3.7.2.1/gr-blocks/examples/0000775000175000017500000000000012207440367017032 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/examples/CMakeLists.txt0000664000175000017500000000161212207440367021572 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. add_subdirectory(metadata) add_subdirectory(tags) if(ENABLE_GR_CTRLPORT) add_subdirectory(ctrlport) endif(ENABLE_GR_CTRLPORT) gnuradio-3.7.2.1/gr-blocks/examples/tags/0000775000175000017500000000000012207440367017770 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/examples/tags/CMakeLists.txt0000664000175000017500000000163312207440367022533 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS test_file_tags.py DESTINATION ${GR_PKG_DATA_DIR}/examples/tags COMPONENT "blocks_python" ) gnuradio-3.7.2.1/gr-blocks/examples/tags/test_file_tags.py0000775000175000017500000000305712207440367023346 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import blocks import sys try: import scipy except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) def main(): data = scipy.arange(0, 32000, 1).tolist() trig = 100*[0,] + 100*[1,] src = blocks.vector_source_s(data, True) trigger = blocks.vector_source_s(trig, True) thr = blocks.throttle(gr.sizeof_short, 10e3) ann = blocks.annotator_alltoall(1000000, gr.sizeof_short) tagger = blocks.burst_tagger(gr.sizeof_short) fsnk = blocks.tagged_file_sink(gr.sizeof_short, 1) tb = gr.top_block() tb.connect(src, thr, (tagger, 0)) tb.connect(trigger, (tagger, 1)) tb.connect(tagger, fsnk) tb.run() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-blocks/examples/metadata/0000775000175000017500000000000012207440367020612 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/examples/metadata/CMakeLists.txt0000664000175000017500000000176712207440367023365 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) install( FILES file_metadata_sink.grc file_metadata_source.grc file_metadata_vector_sink.grc file_metadata_vector_source.grc DESTINATION ${GR_PKG_DATA_DIR}/examples/metadata COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gr-blocks/examples/metadata/file_metadata_vector_source.grc0000664000175000017500000001565412207440367027043 0ustar jcorganjcorgan Fri Dec 14 17:11:02 2012 options id file_metadata_vector_source _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 200000 _coordinate (208, 11) _rotation 0 blocks_file_sink id blocks_file_sink_1 _enabled True file /tmp/received_data.out type complex vlen 10 unbuffered False _coordinate (564, 215) _rotation 0 blocks_tag_debug id blocks_tag_debug_0 _enabled True type complex name Test num_inputs 1 vlen 10 display True _coordinate (563, 298) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 bw samp_rate nconnections 1 gui_hint _coordinate (746, 116) _rotation 0 blocks_vector_to_stream id blocks_vector_to_stream_0 _enabled True type complex num_items 10 vlen 1 _coordinate (526, 132) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 10 _coordinate (322, 223) _rotation 0 blocks_file_meta_source id blocks_file_meta_source_0 _enabled True type complex file /tmp/metadat_vector.out repeat False detached True hdr_file vlen 10 _coordinate (42, 199) _rotation 0 blocks_throttle_0 blocks_file_sink_1 0 0 blocks_throttle_0 blocks_tag_debug_0 0 0 blocks_vector_to_stream_0 qtgui_time_sink_x_0 0 0 blocks_throttle_0 blocks_vector_to_stream_0 0 0 blocks_file_meta_source_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/metadata/file_metadata_sink.grc0000664000175000017500000004321312207440367025115 0ustar jcorganjcorgan Sun Mar 17 20:44:09 2013 options id file_metadata_sink _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable_qtgui_range id qt_samp_rate _enabled True label value samp_rate start 200000 stop 5000000 step 200000 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (330, 259) _rotation 0 variable id samp_rate _enabled True value 200000 _coordinate (208, 11) _rotation 0 blocks_file_meta_sink id blocks_file_meta_sink_0 _enabled True file /tmp/metadat_file.out type complex samp_rate samp_rate rel_rate 1 vlen 1 max_seg_size 1000000 extra_dict "" detached True unbuffered False _coordinate (569, 124) _rotation 0 blocks_head id blocks_head_0 _enabled True type complex num_items 20000000 vlen 1 _coordinate (309, 172) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled False type fc32 otw stream_args dev_addr addr=192.168.11.2 sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate qt_samp_rate center_freq0 98.9e6 gain0 30 ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (53, 269) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq 1000 amp 1 offset 0 _coordinate (48, 115) _rotation 0 uhd_usrp_source_0 blocks_head_0 0 0 blocks_head_0 blocks_file_meta_sink_0 0 0 analog_sig_source_x_0 blocks_head_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/metadata/file_metadata_source.grc0000664000175000017500000001614712207440367025457 0ustar jcorganjcorgan Fri Dec 14 17:08:09 2012 options id file_metadata_source _enabled True title author description window_size 1280, 1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 200000 _coordinate (208, 11) _rotation 0 blocks_tag_debug id blocks_tag_debug_0 _enabled True type complex name Test num_inputs 1 vlen 1 display True _coordinate (561, 290) _rotation 0 analog_agc2_xx id analog_agc2_xx_0 _enabled True type complex attack_rate 1e-1 decay_rate 1e-2 reference 1.0 gain 1.0 max_gain 0.0 _coordinate (561, 82) _rotation 0 qtgui_time_sink_x id qtgui_time_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 bw samp_rate nconnections 1 gui_hint _coordinate (776, 98) _rotation 0 blocks_file_sink id blocks_file_sink_1 _enabled True file /tmp/received_data.out type complex vlen 1 unbuffered False _coordinate (564, 215) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (322, 222) _rotation 0 blocks_file_meta_source id blocks_file_meta_source_0 _enabled True type complex file /tmp/metadat_file.out repeat False detached True hdr_file vlen 1 _coordinate (50, 198) _rotation 0 blocks_throttle_0 blocks_file_sink_1 0 0 blocks_throttle_0 blocks_tag_debug_0 0 0 blocks_throttle_0 analog_agc2_xx_0 0 0 analog_agc2_xx_0 qtgui_time_sink_x_0 0 0 blocks_file_meta_source_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/metadata/file_metadata_vector_sink.grc0000664000175000017500000001062612207440367026501 0ustar jcorganjcorgan Fri Dec 14 17:08:29 2012 options id file_metadata_vector_sink _enabled True title author description window_size 1280, 1024 generate_options no_gui category Custom run_options run run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 200000 _coordinate (208, 11) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0 _enabled True type complex vector 10*[0,1,2,3,4,5,6,7,8,9] repeat True vlen 10 _coordinate (67, 100) _rotation 0 blocks_head id blocks_head_0 _enabled True type complex num_items 10010000 vlen 10 _coordinate (325, 108) _rotation 0 blocks_file_meta_sink id blocks_file_meta_sink_0 _enabled True file /tmp/metadat_vector.out type complex samp_rate samp_rate rel_rate 1 vlen 10 max_seg_size 1000000 extra_dict "" detached True unbuffered False _coordinate (544, 60) _rotation 0 blocks_vector_source_x_0 blocks_head_0 0 0 blocks_head_0 blocks_file_meta_sink_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/ctrlport/0000775000175000017500000000000012207440367020703 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/examples/ctrlport/CMakeLists.txt0000664000175000017500000000161212207440367023443 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL(PROGRAMS DESTINATION ${GR_PKG_CTRLPORT_EXAMPLES_DIR} COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gr-blocks/examples/ctrlport/pfb_sync_test.grc0000664000175000017500000003264312207440367024252 0ustar jcorganjcorgan Sun Mar 17 21:01:36 2013 options id pfb_sync_test _enabled True title author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 import id import_0 _enabled True import import random, math, cmath _coordinate (14, 77) _rotation 0 variable id samp_rate _enabled True value 300000 _coordinate (14, 124) _rotation 0 variable id graymap _enabled True value [[3,1,0,2]] _coordinate (32, 387) _rotation 0 variable id amps _enabled True value [1] _coordinate (32, 451) _rotation 0 variable id nfilts _enabled True value 32 _coordinate (99, 451) _rotation 0 digital_costas_loop_cc id digital_costas_loop_cc_0 _enabled True w 6.28/100.0 order 4 _coordinate (626, 223) _rotation 0 variable id sps _enabled True value 2 _coordinate (105, 126) _rotation 0 blocks_null_sink id blocks_null_sink_0 _enabled True type complex vlen 1 _coordinate (964, 200) _rotation 0 variable_slider id noise _enabled True label value 0.05 min 0.00000001 max 2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (281, 406) _rotation 0 variable_slider id phase _enabled True label value 0 min 0 max 2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (167, 405) _rotation 0 digital_pfb_clock_sync_xxx id digital_pfb_clock_sync_xxx_0 _enabled True type ccf sps sps loop_bw 2*3.14/100.0 taps firdes.root_raised_cosine(nfilts, nfilts,1.0/sps, 0.35, int(22*sps*nfilts)) filter_size nfilts init_phase nfilts/2 max_dev 1.5 osps 1 _coordinate (322, 231) _rotation 0 digital_psk_mod id digital_psk_mod_0 _enabled True constellation_points 4 mod_code "gray" differential True samples_per_symbol sps excess_bw 0.35 verbose False log False _coordinate (846, 32) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise freq_offset 0.0 epsilon 1.0 taps cmath.exp(1j*phase) seed 0 _coordinate (73, 247) _rotation 0 blocks_file_source id blocks_file_source_0 _enabled True file /dev/urandom type byte repeat True vlen 1 _coordinate (229, 56) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type byte samples_per_second samp_rate vlen 1 _coordinate (623, 64) _rotation 0 blocks_packed_to_unpacked_xx id blocks_packed_to_unpacked_xx_0 _enabled True type byte bits_per_chunk 8 endianness gr.GR_MSB_FIRST num_ports 1 _coordinate (415, 56) _rotation 0 blocks_ctrlport_monitor id blocks_ctrlport_monitor_0 _enabled True en True _coordinate (229, 7) _rotation 0 blocks_throttle_0 digital_psk_mod_0 0 0 digital_pfb_clock_sync_xxx_0 digital_costas_loop_cc_0 0 0 digital_costas_loop_cc_0 blocks_null_sink_0 0 0 channels_channel_model_0 digital_pfb_clock_sync_xxx_0 0 0 digital_psk_mod_0 channels_channel_model_0 0 0 blocks_file_source_0 blocks_packed_to_unpacked_xx_0 0 0 blocks_packed_to_unpacked_xx_0 blocks_throttle_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/ctrlport/comparing_resamplers.grc0000664000175000017500000002007112207440367025614 0ustar jcorganjcorgan Thu May 23 22:25:13 2013 options id comparing_resamplers _enabled True title author description window_size 570,390 generate_options no_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type complex samples_per_second samp_rate vlen 1 _coordinate (191, 125) _rotation 0 blocks_ctrlport_probe2_c id probe_arc_resamp _enabled True name arb_resampler desc PFB Arbitrary Resampler len 1024 _coordinate (9, 296) _rotation 180 variable id resamp_rate _enabled True value 1.25 _coordinate (272, 9) _rotation 0 pfb_arb_resampler_xxx id pfb_arb_resampler_xxx_0 _enabled True type ccf rrate resamp_rate taps nfilts 32 atten 60 _coordinate (305, 280) _rotation 180 variable id samp_rate _enabled True value 30e6 _coordinate (181, 10) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq samp_rate/10 amp 1 offset 0 _coordinate (11, 93) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage 0.1 freq_offset 0.0 epsilon 1.0 taps [1,] seed 0 _coordinate (382, 93) _rotation 0 fractional_resampler_xx id fractional_resampler_xx_0 _enabled True type complex phase_shift 0 resamp_ratio resamp_rate _coordinate (354, 212) _rotation 180 blocks_ctrlport_probe2_c id probe_frac_resamp _enabled True name fractional_resamp desc Fractional Resampler len 1024 _coordinate (10, 204) _rotation 180 analog_sig_source_x_0 blocks_throttle_0 0 0 blocks_throttle_0 channels_channel_model_0 0 0 channels_channel_model_0 pfb_arb_resampler_xxx_0 0 0 channels_channel_model_0 fractional_resampler_xx_0 0 0 pfb_arb_resampler_xxx_0 probe_arc_resamp 0 0 fractional_resampler_xx_0 probe_frac_resamp 0 0 gnuradio-3.7.2.1/gr-blocks/examples/ctrlport/pfb_sync_test-qt.grc0000664000175000017500000004305512207440367024673 0ustar jcorganjcorgan Sun Mar 17 21:00:28 2013 options id pfb_sync_test_qt _enabled True title author description window_size 1280,1024 generate_options qt_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id sps _enabled True value 2 _coordinate (105, 126) _rotation 0 variable id samp_rate _enabled True value 300000 _coordinate (14, 124) _rotation 0 import id import_0 _enabled True import import random, math, cmath _coordinate (14, 77) _rotation 0 blocks_packed_to_unpacked_xx id blocks_packed_to_unpacked_xx_0 _enabled True type byte bits_per_chunk 8 endianness gr.GR_MSB_FIRST num_ports 1 _coordinate (419, 10) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type byte samples_per_second samp_rate vlen 1 _coordinate (436, 97) _rotation 0 digital_psk_mod id digital_psk_mod_0 _enabled True constellation_points 4 mod_code "gray" differential True samples_per_symbol sps excess_bw 0.35 verbose False log False _coordinate (627, 65) _rotation 0 digital_pfb_clock_sync_xxx id digital_pfb_clock_sync_xxx_0 _enabled True type ccf sps sps loop_bw 2*3.14/100.0 taps firdes.root_raised_cosine(nfilts, nfilts,1.0/sps, 0.35, int(22*sps*nfilts)) filter_size nfilts init_phase nfilts/2 max_dev 1.5 osps 1 _coordinate (339, 195) _rotation 0 variable id nfilts _enabled True value 32 _coordinate (74, 390) _rotation 0 variable id amps _enabled True value [1] _coordinate (7, 390) _rotation 0 variable id graymap _enabled True value [[3,1,0,2]] _coordinate (7, 326) _rotation 0 qtgui_const_sink_x id qtgui_const_sink_x_0 _enabled True type complex name QT GUI Plot size 1024 ymin -2 ymax 2 xmin -2 xmax 2 nconnections 2 update_time 0.10 gui_hint _coordinate (752, 196) _rotation 0 channels_channel_model id channels_channel_model_0 _enabled True noise_voltage noise freq_offset 0.0 epsilon 1.0 taps cmath.exp(1j*phase) seed 0 _coordinate (68, 211) _rotation 0 blocks_ctrlport_probe2_c id received_probe2 _enabled True name received desc Constellation Points len 1024 _coordinate (195, 519) _rotation 0 variable_qtgui_range id phase _enabled True label Phase value 0.5 start 0 stop 2 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (266, 344) _rotation 0 blocks_ctrlport_probe2_c id time_probe2 _enabled True name time locked desc Constellation Points len 1024 _coordinate (447, 440) _rotation 0 variable_qtgui_range id noise _enabled True label Noise value 0.050 start 0.0001 stop 2 step 0.01 widget counter_slider orient Qt.Horizontal min_len 200 gui_hint _coordinate (7, 455) _rotation 0 digital_costas_loop_cc id digital_costas_loop_cc_0 _enabled True w 6.28/100.0 order 4 _coordinate (610, 279) _rotation 0 blocks_null_sink id blocks_null_sink_0 _enabled True type complex vlen 1 _coordinate (859, 279) _rotation 0 blocks_ctrlport_probe2_c id phase_probe2 _enabled True name phase locked desc Constellation Points len 1024 _coordinate (681, 379) _rotation 0 blocks_vector_source_x id blocks_vector_source_x_0 _enabled True type byte vector (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50) tags [] repeat True vlen 1 _coordinate (190, 71) _rotation 0 blocks_ctrlport_monitor id blocks_ctrlport_monitor_0 _enabled True en True _coordinate (193, 7) _rotation 0 blocks_throttle_0 digital_psk_mod_0 0 0 digital_pfb_clock_sync_xxx_0 qtgui_const_sink_x_0 0 0 digital_costas_loop_cc_0 qtgui_const_sink_x_0 0 1 digital_costas_loop_cc_0 blocks_null_sink_0 0 0 channels_channel_model_0 digital_pfb_clock_sync_xxx_0 0 0 digital_psk_mod_0 channels_channel_model_0 0 0 digital_costas_loop_cc_0 phase_probe2 0 0 blocks_packed_to_unpacked_xx_0 blocks_throttle_0 0 0 blocks_vector_source_x_0 blocks_packed_to_unpacked_xx_0 0 0 channels_channel_model_0 received_probe2 0 0 digital_pfb_clock_sync_xxx_0 time_probe2 0 0 digital_pfb_clock_sync_xxx_0 digital_costas_loop_cc_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/msg_passing/0000775000175000017500000000000012207440367021344 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/examples/msg_passing/CMakeLists.txt0000664000175000017500000000162112207440367024104 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) install( FILES strobe.grc DESTINATION ${GR_PKG_DATA_DIR}/examples/msg_passing COMPONENT "runtime_python" ) gnuradio-3.7.2.1/gr-blocks/examples/msg_passing/strobe.grc0000664000175000017500000001322012207440367023335 0ustar jcorganjcorgan Sun Mar 17 20:42:59 2013 options id strobe _enabled True title author description window_size 1280, 1024 generate_options no_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samp_rate _enabled True value 32000 _coordinate (10, 170) _rotation 0 blocks_message_debug id blocks_message_debug_0 _enabled True _coordinate (1049, 176) _rotation 0 blocks_pdu_to_tagged_stream id blocks_pdu_to_tagged_stream_0 _enabled True type byte _coordinate (388, 85) _rotation 0 blocks_message_strobe id blocks_message_strobe_0_0 _enabled True msg pmt.cons( pmt.PMT_NIL, pmt.make_u8vector(512,0) ) period 750 _coordinate (95, 95) _rotation 0 blocks_copy id blocks_copy_0 _enabled True type byte enabled True vlen 1 _coordinate (629, 81) _rotation 0 blocks_tagged_stream_to_pdu id blocks_tagged_stream_to_pdu_0 _enabled True type byte _coordinate (837, 47) _rotation 0 blocks_message_strobe id blocks_message_strobe_0 _enabled True msg pmt.intern("TEST") period 1000 _coordinate (423, 164) _rotation 0 blocks_message_strobe_0 blocks_message_debug_0 0 0 blocks_message_strobe_0_0 blocks_pdu_to_tagged_stream_0 0 0 blocks_tagged_stream_to_pdu_0 blocks_message_debug_0 0 2 blocks_copy_0 blocks_tagged_stream_to_pdu_0 0 0 blocks_pdu_to_tagged_stream_0 blocks_copy_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/msg_passing/hier/0000775000175000017500000000000012207440367022273 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-blocks/examples/msg_passing/hier/test_msg_hier.grc0000664000175000017500000001363512207440367025634 0ustar jcorganjcorgan Mon Dec 10 19:56:24 2012 options id test_msg_hier _enabled True title author description window_size 1280, 1024 generate_options hb category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 pad_source id pad_source_0 _enabled True label TEST_PORT type message vlen 1 optional False _coordinate (234, 145) _rotation 0 pad_source id pad_source_0_0 _enabled True label TEST_PORT2 type message vlen 1 optional False _coordinate (167, 54) _rotation 0 blocks_message_strobe id blocks_message_strobe_0 _enabled True msg pmt.cons(pmt.PMT_NIL, pmt.make_u8vector(16,0x77)) period 200 _coordinate (362, 81) _rotation 0 pad_sink id pad_sink_0 _enabled True label TEST_PORT type message vlen 1 optional True _coordinate (618, 87) _rotation 0 blocks_message_strobe id blocks_message_strobe_0_1 _enabled True msg pmt.intern("OUTPUT2") period 100 _coordinate (400, 156) _rotation 0 pad_sink id pad_sink_0_0 _enabled True label TEST_PORT3 type message vlen 1 optional True _coordinate (695, 172) _rotation 0 pad_source_0_0 blocks_message_strobe_0 0 0 pad_source_0 blocks_message_strobe_0 0 0 blocks_message_strobe_0 pad_sink_0 0 0 blocks_message_strobe_0_1 pad_sink_0 0 0 blocks_message_strobe_0_1 pad_sink_0_0 0 0 gnuradio-3.7.2.1/gr-blocks/examples/msg_passing/hier/test_msg_hier_topblock.grc0000664000175000017500000001004612207440367027522 0ustar jcorganjcorgan Mon Dec 10 19:56:42 2012 options id test_msg_hier_topblock _enabled True title author description window_size 1280, 1024 generate_options no_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 blocks_message_strobe id blocks_message_strobe_0_0 _enabled True msg pmt.intern("UPDATED2") period 3000 _coordinate (51, 88) _rotation 0 blocks_message_strobe id blocks_message_strobe_0 _enabled True msg pmt.intern("UPDATED") period 2000 _coordinate (211, 168) _rotation 0 blocks_message_debug id blocks_message_debug_0 _enabled True _coordinate (758, 71) _rotation 0 TEST_MSG_HIER id TEST_MSG_HIER_0 _enabled True _coordinate (402, 52) _rotation 0 TEST_MSG_HIER_0 blocks_message_debug_0 0 0 blocks_message_strobe_0 TEST_MSG_HIER_0 0 0 blocks_message_strobe_0_0 TEST_MSG_HIER_0 0 1 TEST_MSG_HIER_0 blocks_message_debug_0 0 1 TEST_MSG_HIER_0 blocks_message_debug_0 1 0 gnuradio-3.7.2.1/.gitattributes0000644000175000017500000000050311700377700016215 0ustar jcorganjcorgan# # The following turn off LF->CRLF conversion for some files on Windows. # these conversions cause syntax errors on MinGW/MSYS. They should not # have any effect on non-Windows systems or on Cygwin. Any files that # required svn:eof-style=lf under subversion should be included here. # *.m4 -crlf *.ac -crlf *.scm -crlf gnuradio-3.7.2.1/gr-trellis/0000755000175000017500000000000012207440367015413 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/CMakeLists.txt0000664000175000017500000000770312207440367020164 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-trellis" ENABLE_GR_TRELLIS Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_ANALOG ENABLE_GR_BLOCKS ENABLE_GR_DIGITAL ) GR_SET_GLOBAL(GR_TRELLIS_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) GR_SET_GLOBAL(GR_TRELLIS_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/swig ) SET(GR_PKG_TRELLIS_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/trellis) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_TRELLIS) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_TRELLIS_DESCRIPTION "GNU Radio Trellis Blocks") CPACK_COMPONENT("trellis_docs" GROUP "Trellis" DISPLAY_NAME "Documentation" DESCRIPTION "Doxygen HTML and XML" ) CPACK_COMPONENT("trellis_runtime" GROUP "Trellis" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("trellis_devel" GROUP "Trellis" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("trellis_python" GROUP "Trellis" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime" DEPENDS "runtime_python;trellis_runtime" ) CPACK_COMPONENT("trellis_examples" GROUP "Trellis" DISPLAY_NAME "Examples" DESCRIPTION "Python examples for trellis" DEPENDS "trellis_python" ) CPACK_COMPONENT("trellis_swig" GROUP "Trellis" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;trellis_python;trellis_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/trellis) add_subdirectory(lib) add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/trellis) add_subdirectory(examples/python) add_subdirectory(examples/grc) add_subdirectory(grc) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-trellis.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-trellis.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-trellis.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "trellis_devel" ) endif(ENABLE_GR_TRELLIS) gnuradio-3.7.2.1/gr-trellis/include/0000775000175000017500000000000012207440367017040 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/include/gnuradio/0000775000175000017500000000000012207440367020650 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/0000775000175000017500000000000012207440367022326 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/CMakeLists.txt0000664000175000017500000000657512207440367025103 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # generate helper scripts to expand templated files ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_dict2(name, sig, 'trellis') build_utils.expand_template(d, inp) ") macro(expand_h root) #make a list of all the generated files unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the files add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #install rules for the generated h files list(APPEND generated_includes ${expanded_files_h}) endmacro(expand_h) ######################################################################## # Invoke macro to generate various sources ####################################################################### expand_h(encoder_XX bb bs bi ss si ii) expand_h(sccc_encoder_XX bb bs bi ss si ii) expand_h(pccc_encoder_XX bb bs bi ss si ii) expand_h(metrics_X s i f c) expand_h(viterbi_X b s i) expand_h(viterbi_combined_XX sb ss si ib is ii fb fs fi cb cs ci) expand_h(sccc_decoder_X b s i) expand_h(sccc_decoder_combined_XX fb fs fi cb cs ci) expand_h(pccc_decoder_X b s i) expand_h(pccc_decoder_combined_XX fb fs fi cb cs ci) add_custom_target(trellis_generated_includes DEPENDS ${generated_includes} ) ######################################################################## # Install header files ######################################################################## install(FILES ${generated_includes} api.h base.h calc_metric.h constellation_metrics_cf.h core_algorithms.h fsm.h interleaver.h permutation.h quicksort_index.h siso_type.h siso_combined_f.h siso_f.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/trellis COMPONENT "trellis_devel" ) gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/sccc_decoder_combined_XX.h.t0000664000175000017500000000466312207440367027631 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling); virtual fsm FSMo() const = 0; virtual fsm FSMi() const = 0; virtual int STo0() const = 0; virtual int SToK() const = 0; virtual int STi0() const = 0; virtual int STiK() const = 0; virtual interleaver INTERLEAVER() const = 0; virtual int blocklength() const = 0; virtual int repetitions() const = 0; virtual int D() const = 0; virtual std::vector<@I_TYPE@> TABLE() const = 0; virtual digital::trellis_metric_type_t METRIC_TYPE() const = 0; virtual siso_type_t SISO_TYPE() const = 0; virtual float scaling() const = 0; virtual void set_scaling(float scaling) = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/encoder_XX.h.t0000664000175000017500000000271112207440367025000 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace trellis { /*! * \brief Convolutional encoder. * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public sync_block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSM, int ST); virtual fsm FSM() const = 0; virtual int ST() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/siso_type.h0000664000175000017500000000215212207440367024515 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_SISO_TYPE_H #define INCLUDED_TRELLIS_SISO_TYPE_H namespace gr { namespace trellis { typedef enum { TRELLIS_MIN_SUM = 200, TRELLIS_SUM_PRODUCT } siso_type_t; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_SISO_TYPE_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/interleaver.h0000664000175000017500000000334112207440367025020 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_INTERLEAVER_H #define INCLUDED_TRELLIS_INTERLEAVER_H #include #include namespace gr { namespace trellis { /*! * \brief INTERLEAVER class * \ingroup trellis_coding_blk */ class TRELLIS_API interleaver { private: int d_K; std::vector d_INTER; std::vector d_DEINTER; public: interleaver(); interleaver(const interleaver & INTERLEAVER); interleaver(int K, const std::vector & INTER); interleaver(const char *name); interleaver(int K, int seed); int K () const { return d_K; } const std::vector & INTER() const { return d_INTER; } const std::vector & DEINTER() const { return d_DEINTER; } void write_interleaver_txt(std::string filename); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_INTERLEAVER_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/fsm.h0000664000175000017500000001363412207440367023273 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2011-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_FSM_H #define INCLUDED_TRELLIS_FSM_H #include #include #include namespace gr { namespace trellis { /*! * \brief Finite State Machine Specification class. * \ingroup trellis_coding_blk * * \details * An instance of this class represents a finite state machine * specification (FSMS) rather than the FSM itself. It particular * the state of the FSM is not stored within an instance of this * class. */ class TRELLIS_API fsm { private: // Input alphabet cardinality. int d_I; // Number of states. int d_S; // Output alphabet cardinality. int d_O; // NS means Next State. // next_state = d_NS[current_state * d_I + input_symbol] std::vector d_NS; // OS means Output Symbol. // output_symbol = d_OS[current_state * d_I + input_symbol] std::vector d_OS; // PS means Previous State. std::vector< std::vector > d_PS; // PI means Previous Input Symbol. // d_PS[current_state][k] and d_PI[current_state][k], is a pair of the form // (previous_state, previous_input_symbol) that could have produced the // current state. std::vector< std::vector > d_PI; // TM means Termination matrix. // d_TMl[s*d_S+es] is the shortest number of steps to get from state s to // state es. std::vector d_TMl; // d_TMi[s*d_S+es] is the input symbol required to set off on the shortest // path from state s to es. std::vector d_TMi; void generate_PS_PI (); void generate_TM (); bool find_es(int es); public: /*! * \brief Constructor to create an uninitialized FSMS. */ fsm(); /*! * \brief Constructor to copy an FSMS. */ fsm(const fsm &FSM); /*! * \brief Constructor to to create an FSMS. * * \param I The number of possible input symbols. * \param S The number of possible FSM states. * \param O The number of possible output symbols. * \param NS A mapping from (current state, input symbol) to next state. * next_state = NS[current_state * I + input_symbol] * \param OS A mapping from (current state, input symbol) to output symbol. * output_symbol = OS[current_state * I + input_symbol] * */ fsm(int I, int S, int O, const std::vector &NS, const std::vector &OS); /*! * \brief Constructor to create an FSMS from file contents. * * \param name filename * */ fsm(const char *name); /*! * \brief Creates an FSMS from the generator matrix of a (n, k) binary convolutional code. * * \param k ??? * \param n ??? * \param G ??? * */ fsm(int k, int n, const std::vector &G); /*! * \brief Creates an FSMS describing ISI. * * \param mod_size modulation size * \param ch_length channel length * */ fsm(int mod_size, int ch_length); /*! * \brief Creates an FSMS describing the trellis for a CPM. * * \param P ???? h=K/P (relatively prime) * \param M alphabet size * \param L pulse duration * * This FSM is based on the paper by B. Rimoldi * "A decomposition approach to CPM", IEEE Trans. Info Theory, March 1988 * See also my own notes at http://www.eecs.umich.edu/~anastas/docs/cpm.pdf */ fsm(int P, int M, int L); /*! * \brief Creates an FSMS describing the joint trellis of two FSMs. * * \param FSM1 first FSMS * \param FSM2 second FSMS */ fsm(const fsm &FSM1, const fsm &FSM2); /*! * \brief Creates an FSMS representing n stages through the originial FSM (AKA radix-n FSM). * * \param FSM Original FSMs * \param n Number of stages. */ fsm(const fsm &FSM, int n); int I() const { return d_I; } int S() const { return d_S; } int O() const { return d_O; } const std::vector & NS() const { return d_NS; } const std::vector & OS() const { return d_OS; } const std::vector< std::vector > & PS() const { return d_PS; } const std::vector< std::vector > & PI() const { return d_PI; } const std::vector & TMi() const { return d_TMi; } const std::vector & TMl() const { return d_TMl; } /*! * \brief Creates an svg image of the trellis representation. * * \param filename filename * \param number_stages ???? */ void write_trellis_svg(std::string filename ,int number_stages); /*! * \brief Write the FSMS to a file. * * \param filename filename */ void write_fsm_txt(std::string filename); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_FSM_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/sccc_encoder_XX.h.t0000664000175000017500000000341312207440367025773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include namespace gr { namespace trellis { /*! * \brief SCCC encoder. * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public sync_block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSMo, int STo, const fsm &FSMi, int STi, const interleaver &INTERLEAVER, int blocklength); virtual fsm FSMo() const = 0; virtual int STo() const = 0; virtual fsm FSMi() const = 0; virtual int STi() const = 0; virtual interleaver INTERLEAVER() const = 0; virtual int blocklength() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/base.h0000664000175000017500000000255512207440367023420 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_BASE_H #define INCLUDED_TRELLIS_BASE_H #include namespace gr { namespace trellis { /*! * \brief change base */ bool dec2base(unsigned int num, int base, std::vector &s); bool dec2bases(unsigned int num, const std::vector &bases, std::vector &s); unsigned int base2dec(const std::vector &s, int base); unsigned int bases2dec(const std::vector &s, const std::vector &bases); } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_BASE_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/constellation_metrics_cf.h0000664000175000017500000000321212207440367027551 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_CONSTELLATION_METRICS_CF_H #define INCLUDED_TRELLIS_CONSTELLATION_METRICS_CF_H #include #include #include #include namespace gr { namespace trellis { /*! * \brief Evaluate metrics for use by the Viterbi algorithm. * \ingroup trellis_coding_blk */ class TRELLIS_API constellation_metrics_cf : virtual public block { public: // gr::trellis::constellation_metrics_cf::sptr typedef boost::shared_ptr sptr; static sptr make(digital::constellation_sptr constellation, digital::trellis_metric_type_t TYPE); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_CONSTELLATION_METRICS_CF_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/siso_f.h0000664000175000017500000000343412207440367023765 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_SISO_F_H #define INCLUDED_TRELLIS_SISO_F_H #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API siso_f : virtual public block { public: // gr::trellis::siso_f::sptr typedef boost::shared_ptr sptr; static sptr make(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t d_SISO_TYPE); virtual fsm FSM() const = 0; virtual int K() const = 0; virtual int S0() const = 0; virtual int SK() const = 0; virtual bool POSTI() const = 0; virtual bool POSTO() const = 0; virtual siso_type_t SISO_TYPE() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_SISO_F_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/quicksort_index.h0000664000175000017500000000230412207440367025711 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_QUICKSORT_INDEX_H #define INCLUDED_QUICKSORT_INDEX_H #include namespace gr { namespace trellis { template void SWAP(T &a, T &b); template void quicksort_index(std::vector &p, std::vector &index, int left, int right); } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_QUICKSORT_INDEX_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/viterbi_combined_XX.h.t0000664000175000017500000000361612207440367026672 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSM, int K, int S0, int SK, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE); virtual fsm FSM() const = 0; virtual int K() const = 0; virtual int S0() const = 0; virtual int SK() const = 0; virtual int D() const = 0; virtual std::vector<@I_TYPE@> TABLE() const = 0; virtual digital::trellis_metric_type_t TYPE() const = 0; virtual void set_TABLE (const std::vector<@I_TYPE@> &table) = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/metrics_X.h.t0000664000175000017500000000334412207440367024702 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include namespace gr { namespace trellis { /*! * \brief Evaluate metrics for use by the Viterbi algorithm. * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(int O, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE); virtual int O() const = 0; virtual int D() const = 0; virtual digital::trellis_metric_type_t TYPE() const = 0; virtual std::vector<@I_TYPE@> TABLE() const = 0; virtual void set_TABLE(const std::vector<@I_TYPE@> &table) = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/permutation.h0000664000175000017500000000321512207440367025047 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_PERMUTATION_H #define INCLUDED_TRELLIS_PERMUTATION_H #include #include #include namespace gr { namespace trellis { /*! * \brief Permutation. * \ingroup trellis_coding_blk */ class TRELLIS_API permutation : virtual public sync_block { public: // gr::trellis::permutation::sptr typedef boost::shared_ptr sptr; static sptr make(int K, const std::vector &TABLE, int SYMS_PER_BLOCK, size_t NBYTES); virtual int K() const = 0; virtual const std::vector & TABLE() const = 0; virtual int SYMS_PER_BLOCK() const = 0; virtual size_t BYTES_PER_SYMBOL() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_PERMUTATION_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/calc_metric.h0000664000175000017500000000354312207440367024751 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CALC_METRIC_H #define INCLUDED_CALC_METRIC_H #include #include #include namespace gr { namespace trellis { template void calc_metric(int O, int D, const std::vector &TABLE, const T *input, float *metric, digital::trellis_metric_type_t type); /* void calc_metric(int O, int D, const std::vector &TABLE, const short *input, float *metric, digital::trellis_metric_type_t type); void calc_metric(int O, int D, const std::vector &TABLE, const int *input, float *metric, digital::trellis_metric_type_t type); void calc_metric(int O, int D, const std::vector &TABLE, const float *input, float *metric, digital::trellis_metric_type_t type); */ void calc_metric(int O, int D, const std::vector &TABLE, const gr_complex *input, float *metric, digital::trellis_metric_type_t type); } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_CALC_METRIC_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/siso_combined_f.h0000664000175000017500000000416712207440367025631 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_SISO_COMBINED_F_H #define INCLUDED_TRELLIS_SISO_COMBINED_F_H #include #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API siso_combined_f : virtual public block { public: // gr::trellis::siso_combined_f::sptr typedef boost::shared_ptr sptr; static sptr make(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t d_SISO_TYPE, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE); virtual fsm FSM() const = 0; virtual int K() const = 0; virtual int S0() const = 0; virtual int SK() const = 0; virtual bool POSTI() const = 0; virtual bool POSTO() const = 0; virtual siso_type_t SISO_TYPE() const = 0; virtual int D() const = 0; virtual std::vector TABLE() const = 0; virtual digital::trellis_metric_type_t TYPE() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_SISO_COMBINED_F_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/sccc_decoder_X.h.t0000664000175000017500000000400412207440367025626 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE); virtual fsm FSMo() const = 0; virtual fsm FSMi() const = 0; virtual int STo0() const = 0; virtual int SToK() const = 0; virtual int STi0() const = 0; virtual int STiK() const = 0; virtual interleaver INTERLEAVER() const = 0; virtual int blocklength() const = 0; virtual int repetitions() const = 0; virtual siso_type_t SISO_TYPE() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/core_algorithms.h0000664000175000017500000001024012207440367025655 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_CORE_ALGORITHMS_H #define INCLUDED_CORE_ALGORITHMS_H #include #include #include #include #include namespace gr { namespace trellis { float min(float a, float b); float min_star(float a, float b); template void viterbi_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, const float *in, T *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const Ti *in, To *out); void siso_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), const float *priori, const float *prioro, float *post); template void siso_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *priori, const T *observations, float *post); template void sccc_decoder(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *iprioro, T *data); template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const Ti *observations, To *data); template void pccc_decoder(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *cprioro, T *data); template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const Ti *observations, To *data); } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_CORE_ALGORITHMS_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/pccc_decoder_combined_XX.h.t0000664000175000017500000000465512207440367027627 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling); virtual fsm FSM1() const = 0; virtual fsm FSM2() const = 0; virtual int ST10() const = 0; virtual int ST1K() const = 0; virtual int ST20() const = 0; virtual int ST2K() const = 0; virtual interleaver INTERLEAVER() const = 0; virtual int blocklength() const = 0; virtual int repetitions() const = 0; virtual int D() const = 0; virtual std::vector<@I_TYPE@> TABLE() const = 0; virtual digital::trellis_metric_type_t METRIC_TYPE() const = 0; virtual siso_type_t SISO_TYPE() const = 0; virtual float scaling() const = 0; virtual void set_scaling(float scaling) = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/pccc_encoder_XX.h.t0000664000175000017500000000341312207440367025770 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include namespace gr { namespace trellis { /*! * \brief PCCC encoder. * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public sync_block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSM1, int ST1, const fsm &FSM2, int ST2, const interleaver &INTERLEAVER, int blocklength); virtual fsm FSM1() const = 0; virtual int ST1() const = 0; virtual fsm FSM2() const = 0; virtual int ST2() const = 0; virtual interleaver INTERLEAVER() const = 0; virtual int blocklength() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/api.h0000664000175000017500000000204512207440367023251 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_API_H #define INCLUDED_TRELLIS_API_H #include #ifdef gnuradio_trellis_EXPORTS # define TRELLIS_API __GR_ATTR_EXPORT #else # define TRELLIS_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_TRELLIS_API_H */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/viterbi_X.h.t0000664000175000017500000000304412207440367024675 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSM, int K, int S0, int SK); virtual fsm FSM() const = 0; virtual int K() const = 0; virtual int S0() const = 0; virtual int SK() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/include/gnuradio/trellis/pccc_decoder_X.h.t0000664000175000017500000000400412207440367025623 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include #include #include #include #include #include namespace gr { namespace trellis { /*! * \ingroup trellis_coding_blk */ class TRELLIS_API @NAME@ : virtual public block { public: // gr::trellis::@BASE_NAME@::sptr typedef boost::shared_ptr<@BASE_NAME@> sptr; static sptr make(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE); virtual fsm FSM1() const = 0; virtual fsm FSM2() const = 0; virtual int ST10() const = 0; virtual int ST1K() const = 0; virtual int ST20() const = 0; virtual int ST2K() const = 0; virtual interleaver INTERLEAVER() const = 0; virtual int blocklength() const = 0; virtual int repetitions() const = 0; virtual siso_type_t SISO_TYPE() const = 0; }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/grc/0000755000175000017500000000000012207440367016166 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/grc/CMakeLists.txt0000644000175000017500000000236211700377701020727 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install(FILES trellis_encoder_xx.xml trellis_siso_combined_f.xml trellis_viterbi_x.xml trellis_metrics_x.xml trellis_siso_f.xml trellis_permutation.xml trellis_viterbi_combined_xx.xml trellis_sccc_encoder_xx.xml trellis_sccc_decoder_x.xml trellis_sccc_decoder_combined_xx.xml trellis_pccc_encoder_xx.xml trellis_pccc_decoder_x.xml trellis_pccc_decoder_combined_xx.xml DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "trellis_python" ) gnuradio-3.7.2.1/gr-trellis/grc/trellis_metrics_x.xml0000664000175000017500000000341312207440367022446 0ustar jcorganjcorgan Trellis Metrics trellis_metrics_x Trellis Coding from gnuradio import trellis, digital trellis.metrics_$(type)($card, $dim, $table, $metric_type) set_TABLE($table) Type type enum Output Cardinality card int Dimensionality dim int Constellation table $type.table Metric Type metric_type enum in $type.io out float Generate metrics required for Viterbi or SISO algorithms. gnuradio-3.7.2.1/gr-trellis/grc/trellis_siso_f.xml0000664000175000017500000000332112207440367021731 0ustar jcorganjcorgan SISO trellis_siso_f Trellis Coding from gnuradio import trellis trellis.siso_f(trellis.fsm($fsm_args), $block_size, $init_state, $final_state, $a_post_in, $a_post_out, $siso_type) FSM Args fsm_args raw Block Size block_size int Initial State init_state 0 int Final State final_state -1 int A-posteriori In a_post_in enum A-posteriori Out a_post_out enum SISO Type siso_type enum in float out float BCJR Algorithm. \ The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/grc/trellis_pccc_decoder_x.xml0000664000175000017500000000447112207440367023402 0ustar jcorganjcorgan PCCC Decoder trellis_pccc_decoder_x Trellis Coding from gnuradio import trellis trellis.pccc_decoder_$(out_type)( trellis.fsm($o_fsm_args), $o_init_state, $o_final_state, trellis.fsm($i_fsm_args), $i_init_state, $i_final_state, trellis.interleaver($interleaver), $block_size, $iterations, $siso_type) Output Type out_type enum FSM 1 o_fsm_args raw Initial State 1 o_init_state 0 int Final State 1 o_final_state -1 int FSM 2 i_fsm_args raw Initial State 2 i_init_state 0 int Final State 2 i_final_state -1 int Interleaver interleaver raw Block Size block_size int Iterations iterations 10 int SISO Type siso_type enum in float out $out_type.io PCCC turbo Decoder. The fsm and interleaver arguments are passed directly to the trellis.fsm() and trellis.interleaver() constructors. gnuradio-3.7.2.1/gr-trellis/grc/trellis_pccc_decoder_combined_xx.xml0000664000175000017500000000660212207440367025430 0ustar jcorganjcorgan PCCC Decoder Combo trellis_pccc_decoder_combined_xx Trellis Coding from gnuradio import trellis, digital trellis.pccc_decoder_combined_$(type)$(out_type)( trellis.fsm($o_fsm_args), $o_init_state, $o_final_state, trellis.fsm($i_fsm_args), $i_init_state, $i_final_state, trellis.interleaver($interleaver), $block_size, $iterations, $siso_type, $dim, $table, $metric_type, $scaling) set_TABLE($table) Input Type type enum Output Type out_type enum FSM 1 o_fsm_args raw Initial State 1 o_init_state 0 int Final State 1 o_final_state -1 int FSM 2 i_fsm_args raw Initial State 2 i_init_state 0 int Final State 2 i_final_state -1 int Interleaver interleaver raw Block Size block_size int Iterations iterations 10 int Dimensionality dim int Constellation table $type.table Metric Type metric_type enum SISO Type siso_type enum Scaling scaling 1.0 real in $type.io out $out_type.io PCCC turbo Decoder combined with metric calculation. The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/grc/trellis_sccc_decoder_combined_xx.xml0000664000175000017500000000663212207440367025436 0ustar jcorganjcorgan SCCC Decoder Combo trellis_sccc_decoder_combined_xx Trellis Coding from gnuradio import trellis, digital trellis.sccc_decoder_combined_$(type)$(out_type)( trellis.fsm($o_fsm_args), $o_init_state, $o_final_state, trellis.fsm($i_fsm_args), $i_init_state, $i_final_state, trellis.interleaver($interleaver), $block_size, $iterations, $siso_type, $dim, $table, $metric_type, $scaling) set_TABLE($table) Input Type type enum Output Type out_type enum Outer FSM o_fsm_args raw Outer Initial State o_init_state 0 int Outer Final State o_final_state -1 int Inner FSM i_fsm_args raw Inner Initial State i_init_state 0 int Inner Final State i_final_state -1 int Interleaver interleaver raw Block Size block_size int Iterations iterations 10 int Dimensionality dim int Constellation table $type.table Metric Type metric_type enum SISO Type siso_type enum Scaling scaling 1.0 real in $type.io out $out_type.io SCCC turbo Decoder combined with metric calculation. The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/grc/trellis_sccc_encoder_xx.xml0000664000175000017500000000410512207440367023601 0ustar jcorganjcorgan SCCC Encoder trellis_sccc_encoder_xx Trellis Coding from gnuradio import trellis trellis.sccc_encoder_$(type)(trellis.fsm($o_fsm_args), $o_init_state, trellis.fsm($i_fsm_args), $i_init_state, trellis.interleaver($interleaver_args), $bl) Type type enum Outer FSM o_fsm_args raw Outer Initial State o_init_state 0 int Inner FSM i_fsm_args raw Inner Initial State i_init_state 0 int Interleaver interleaver_args raw Blocklength bl int in $type.input out $type.output The fsm and interleaver arguments are passed directly to the trellis.fsm() and trellis.interleaver() constructors. gnuradio-3.7.2.1/gr-trellis/grc/trellis_siso_combined_f.xml0000664000175000017500000000451212207440367023574 0ustar jcorganjcorgan SISO Combo trellis_siso_combined_f Trellis Coding from gnuradio import trellis trellis.siso_combined_f(trellis.fsm($fsm_args), $block_size, $init_state, $final_state, $a_post_in, $a_post_out, $siso_type, $dim, $table, $metric_type) FSM Args fsm_args raw Block Size block_size int Initial State init_state 0 int Final State final_state -1 int A-posteriori In a_post_in enum A-posteriori Out a_post_out enum SISO Type siso_type enum Dimensionality dim int Constellation table real_vector Metric Type metric_type enum in float out float BCJR Algorithm combined with metric calculation. \ The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/grc/trellis_permutation.xml0000664000175000017500000000322412207440367023020 0ustar jcorganjcorgan Trellis Permutation trellis_permutation Trellis Coding from gnuradio import trellis trellis.permutation($interleaver_size, $table, $syms_per_block, $type.size*$vlen) Type type enum Interleaver Size interleaver_size int Table table int_vector Symbols per Block syms_per_block int Vec Length vlen 1 int $vlen > 0 in $type $vlen out $type $vlen Interleaver size is given in blocks. One Symbol = (in/out type) * (vector length) gnuradio-3.7.2.1/gr-trellis/grc/trellis_encoder_xx.xml0000664000175000017500000000306412207440367022611 0ustar jcorganjcorgan Trellis Encoder trellis_encoder_xx Trellis Coding from gnuradio import trellis trellis.encoder_$(type)(trellis.fsm($fsm_args), $init_state) Type type enum FSM Args fsm_args raw Initial State init_state 0 int in $type.input out $type.output The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/grc/trellis_sccc_decoder_x.xml0000664000175000017500000000452112207440367023401 0ustar jcorganjcorgan SCCC Decoder trellis_sccc_decoder_x Trellis Coding from gnuradio import trellis trellis.sccc_decoder_$(out_type)( trellis.fsm($o_fsm_args), $o_init_state, $o_final_state, trellis.fsm($i_fsm_args), $i_init_state, $i_final_state, trellis.interleaver($interleaver), $block_size, $iterations, $siso_type) Output Type out_type enum Outer FSM o_fsm_args raw Outer Initial State o_init_state 0 int Outer Final State o_final_state -1 int Inner FSM i_fsm_args raw Inner Initial State i_init_state 0 int Inner Final State i_final_state -1 int Interleaver interleaver raw Block Size block_size int Iterations iterations 10 int SISO Type siso_type enum in float out $out_type.io SCCC turbo Decoder. The fsm and interleaver arguments are passed directly to the trellis.fsm() and trellis.interleaver() constructors. gnuradio-3.7.2.1/gr-trellis/grc/trellis_pccc_encoder_xx.xml0000664000175000017500000000406612207440367023604 0ustar jcorganjcorgan PCCC Encoder trellis_pccc_encoder_xx Trellis Coding from gnuradio import trellis trellis.pccc_encoder_$(type)(trellis.fsm($o_fsm_args), $o_init_state, trellis.fsm($i_fsm_args), $i_init_state, trellis.interleaver($interleaver_args), $bl) Type type enum FSM 1 o_fsm_args raw Initial State 1 o_init_state 0 int FSM 2 i_fsm_args raw Initial State 2 i_init_state 0 int Interleaver interleaver_args raw Blocklength bl int in $type.input out $type.output The fsm and interleaver arguments are passed directly to the trellis.fsm() and trellis.interleaver() constructors. gnuradio-3.7.2.1/gr-trellis/grc/trellis_viterbi_combined_xx.xml0000664000175000017500000000507312207440367024500 0ustar jcorganjcorgan Viterbi Combo trellis_viterbi_combined_xx Trellis Coding from gnuradio import trellis, digital trellis.viterbi_combined_$(type)$(out_type)(trellis.fsm($fsm_args), $block_size, $init_state, $final_state, $dim, $table, $metric_type) set_TABLE($table) Input Type type enum Output Type out_type enum FSM Args fsm_args raw Block Size block_size int Initial State init_state 0 int Final State final_state -1 int Dimensionality dim int Constellation table $type.table Metric Type metric_type enum in $type.io out $out_type.io Viterbi Decoder combined with metric calculation. \ The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/grc/trellis_viterbi_x.xml0000664000175000017500000000251012207440367022441 0ustar jcorganjcorgan Viterbi trellis_viterbi_x Trellis Coding from gnuradio import trellis trellis.viterbi_$(type)(trellis.fsm($fsm_args), $block_size, $init_state, $final_state) Type type enum FSM Args fsm_args raw Block Size block_size int Initial State init_state 0 int Final State final_state -1 int in float out $type.io Viterbi Decoder. \ The fsm arguments are passed directly to the trellis.fsm() constructor. gnuradio-3.7.2.1/gr-trellis/doc/0000755000175000017500000000000012207440367016160 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/doc/make_numbered_listing.py0000755000175000017500000000225011744612271023063 0ustar jcorganjcorgan#!/usr/bin/env python import sys import os, os.path from optparse import OptionParser def quote_line (line): line = line.replace ('&', '&') line = line.replace ('<', '<') line = line.replace ('>', '>') line = line.replace ("'", ''') line = line.replace ('"', '"') return line def generate_listing (input_filename, title=None): inf = open (input_filename, "r") output_filename = os.path.basename (input_filename) + '.xml' outf = open (output_filename, "w") outf.write ('\n') # outf.write ('\n' % (input_filename,)) # if not title: # title = input_filename # outf.write ('') # outf.write (title) # outf.write ('\n') outf.write ('\n'); lineno = 0 for line in inf: line = line.expandtabs (8) line = quote_line (line) lineno = lineno + 1 outf.write ('%3d %s' % (lineno, line)) outf.write ('\n') # outf.write ('\n') def main (): for file in sys.argv[1:]: generate_listing (file) if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-trellis/doc/CMakeLists.txt0000644000175000017500000000531411744612271020723 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) ######################################################################## # Generate HTML doc with xmlto ######################################################################## find_program(XMLTO_EXECUTABLE xmlto) if(XMLTO_EXECUTABLE) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/gr-trellis.html DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/gr-trellis.xml COMMAND ${XMLTO_EXECUTABLE} html-nochunks ${CMAKE_CURRENT_SOURCE_DIR}/gr-trellis.xml ) add_custom_target(gr_trellis_html ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/gr-trellis.html) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gr-trellis.html DESTINATION ${GR_PKG_DOC_DIR}/html COMPONENT "trellis_docs" ) endif(XMLTO_EXECUTABLE) ######################################################################## # Generate xml doc ######################################################################## add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_tcm.py.xml DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test_tcm.py DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/make_numbered_listing.py COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/make_numbered_listing.py ${CMAKE_CURRENT_SOURCE_DIR}/test_tcm.py ) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_viterbi_equalization1.py.xml DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test_viterbi_equalization1.py DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/make_numbered_listing.py COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/make_numbered_listing.py ${CMAKE_CURRENT_SOURCE_DIR}/test_viterbi_equalization1.py ) add_custom_target(gr_trellis_xml ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/test_tcm.py.xml ${CMAKE_CURRENT_BINARY_DIR}/test_viterbi_equalization1.py.xml ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/test_tcm.py.xml ${CMAKE_CURRENT_BINARY_DIR}/test_viterbi_equalization1.py.xml DESTINATION ${GR_PKG_DOC_DIR}/xml COMPONENT "trellis_docs" ) gnuradio-3.7.2.1/gr-trellis/doc/gr-trellis.xml0000664000175000017500000010724212207440367020776 0ustar jcorganjcorgan ]>
Trellis-based algorithms for GNU Radio Achilleas Anastasopoulos
anastas@umich.edu
This document provides a description of the Finite State Machine (FSM) implementation and the related trellis-based encoding and decoding algorithms for GNU Radio.
Introduction The basic goal of the implementation is to have a generic way of describing an FSM that is decoupled from whether it describes a convolutional code (CC), a trellis code (TC), an inter-symbol interference (ISI) channel, or any other communication system that can be modeled with an FSM. To achieve this goal, we need to separate the pure FSM descrition from the rest of the model details. For instance, in the case of a rate 2/3 TC, the FSM should not involve details about the modulation used (it can be an 8-ary PAM, or 8-PSK, etc). Similarly, when attempting maximum likelihood sequence detection (MLSD)--using for instance the Viterbi algorithm (VA)-- the VA implementation should not be concerned with the channel details (such as modulations, channel type, hard or soft inputs, etc). Clearly, having generality as the primary goal implies some penalty on the code efficiency, as compared to fully custom implementations. We will now describe the implementation of the basic ingedient, the FSM. The FSM class An FSM describes the evolution of a system with inputs xk, states sk and outputs yk. At time k the FSM state is sk. Upon reception of a new input symbol xk, it outputs an output symbol yk which is a function of both xk and sk. It will then move to a next state sk+1. An FSM has a finite number of states, input and output symbols. All these are formally described as follows: The input alphabet AI={0,1,2,...,I-1}, with cardinality I, so that xk takes values in AI. The state alphabet AS={0,1,2,...,S-1}, with cardinality S, so that sk takes values in AS. The output alphabet AO={0,1,2,...,O-1}, with cardinality O, so that yk takes values in AO The "next-state" function NS: AS x AI --> AS, with the meaning sk+1 = NS(sk, xk) The "output-symbol" function OS: AS x AI --> AS, with the meaning yk = OS(sk, xk) Thus, a complete description of the FSM is given by the the five-tuple (I,S,O,NS,OS). Observe that implementation details are hidden in how the outside world interprets these input and output integer symbols. Here is an example of an FSM describing the (2,1) CC with constraint length 3 and generator polynomial matrix (1+D+D2 , 1+D2) from Proakis-Salehi pg. 779. (2,1) CC with generator polynomials (1+D+D<superscript>2</superscript> , 1+D<superscript>2</superscript>) This CC accepts 1 bit at a time, and outputs 2 bits at a time. It has a shift register storing the last two input bits. In particular, bk(0)=xk+ xk-1+xk-2, and bk(1)=xk+ xk-2, where addition is mod-2. We can represent the state of this system as sk = (xk-1 xk-2)10. In addition we can represent its output symbol as yk = (bk(1) bk(0))10. Based on the above assumptions, the input alphabet AI={0,1}, so I=2; the state alphabet AS={0,1,2,3}, so S=4; and the output alphabet AO={0,1,2,3}, so O=4. The "next-state" function NS(,) is given by sk xk sk+1 0 0 0 0 1 2 1 0 0 1 1 2 2 0 1 2 1 3 3 0 1 3 1 3 The "output-symbol" function OS(,) can be given by sk xk yk 0 0 0 0 1 3 1 0 3 1 1 0 2 0 1 2 1 2 3 0 2 3 1 1 Note that although the CC outputs 2 bits per time period, following our approach, there is only one (quaternary) output symbol per time period (for instance, here we use the decimal representation of the 2-bits). Also note that the modulation used is not part of the FSM description: it can be BPSK, OOK, BFSK, QPSK with or without Gray mapping, etc; it is up to the rest of the program to interpret the meaning of the symbol yk. The C++ implementation of the FSM class keeps private information about I,S,O,NS,OS and public methods to read and write them. The NS and OS matrices are implemented as STL 1-dimensional vectors. class fsm { private: int d_I; int d_S; int d_O; std::vector<int> d_NS; std::vector<int> d_OS; std::vector<int> d_PS; std::vector<int> d_PI; std::vector<int> d_TMi; std::vector<int> d_TMl; void generate_PS_PI (); void generate_TM (); bool find_es(int es); public: fsm(); fsm(const fsm &FSM); fsm(int I, int S, int O, const std::vector<int> &NS, const std::vector<int> &OS); fsm(const char *name); fsm(int k, int n, const std::vector<int> &G); fsm(int mod_size, int ch_length); int I () const { return d_I; } int S () const { return d_S; } int O () const { return d_O; } const std::vector<int> & NS () const { return d_NS; } const std::vector<int> & OS () const { return d_OS; } const std::vector<int> & PS () const { return d_PS; } const std::vector<int> & PI () const { return d_PI; } const std::vector<int> & TMi () const { return d_TMi; } const std::vector<int> & TMl () const { return d_TMl; } }; As can be seen, other than the trivial and the copy constructor, there are three additional ways to construct an FSM. Supplying the parameters I,S,O,NS,OS: fsm(const int I, const int S, const int O, const std::vector<int> &NS, const std::vector<int> &OS); Giving a filename containing all the FSM information: fsm(const char *name); This information has to be in the following format: I S O NS(0,0) NS(0,1) ... NS(0,I-1) NS(1,0) NS(1,1) ... NS(1,I-1) ... NS(S-1,0) NS(S-1,1) ... NS(S-1,I-1) OS(0,0) OS(0,1) ... OS(0,I-1) OS(1,0) OS(1,1) ... OS(1,I-1) ... OS(S-1,0) OS(S-1,1) ... OS(S-1,I-1) For instance, the file containing the information for the example mentioned above is of the form: 2 4 4 0 2 0 2 1 3 1 3 0 3 3 0 1 2 2 1 The third way is specific to FSMs representing binary (n,k) conolutional codes. These FSMs are specified by the number of input bits k, the number of output bits n, and the generator matrix, which is a k x n matrix of integers G = [gi,j]i=1:k, j=1:n, given as an one-dimensional STL vector. Each integer gi,j is the decimal representation of the polynomial gi,j(D) (e.g., gi,j= 6 = 1102 is interpreted as gi,j(D)=1+D) describing the connections from the sequence xi to yj (e.g., in the above example yj(k) = xi(k) + xi(k-1)). fsm(int k, int n, const std::vector<int> &G); The fourth way is specific to FSMs resulting from shift registers, and the output symbol being the entire transition (ie, current_state and current_input). These FSMs are usefull when describibg ISI channels. In particular the state is comprised of the input symbols x(k-1), x(k-2),...,x(k-L), where L = ch_length-1 and each x(i) belongs to an alphabet of size mod_size. The output is taken to be x(k), x(k-1), x(k-2),...,x(k-L) (in decimal format) fsm(const int mod_size, const int ch_length); I have added other constructors as well, eg, one that constructs an FSM appropriate for modeling an arbitrary CPM scheme; one that constructs the radix-n version of a given FSM; one that constructs the "concatenation" of two FSMs, etc. As can be seen from the above description, there are two more variables included in the FSM class implementation, the PS and the PI matrices. These are computed internally when an FSM is instantiated and their meaning is as follows. Sometimes (eg, in the traceback operation of the VA) we need to trace the history of the state or the input sequence. To do this we would like to know for a given state sk, what are the possible previous states sk-1 and what input symbols xk-1 will get us from sk-1 to sk. This information can be derived from NS; however we want to have it ready in a convenient format. In the following we assume that for any state, the number of incoming transitions is the same as the number of outgoing transitions, ie, equal to I. All applications of interest have FSMs satisfying this requirement. If we arbitrarily index the incoming transitions to the current state by "i", then as i goes from 0 to I-1, PS(sk,i) gives all previous states sk-1, and PI(sk,i) gives all previous inputs xk-1. In other words, for any given sk and any index i=0,1,...I-1, starting from sk-1=PS(sk,i) with input xk-1=PI(sk,i) will get us to the state sk. More formally, for any i=0,1,...I-1 we have sk = NS(PS(sk,i),PI(sk,i)). Finally, there are two more variables included in the FSM class implementation, the TMl and the TMi matrices. These are both S x S matrices (represented as STL vectors) computed internally when an FSM is instantiated and their meaning is as follows. TMl(i,j) is the minimum number of trellis steps required to go from state i to state j. Similarly, TMi(i,j) is the initial input required to get you from state i to state j in the minimum number of steps. As an example, if TMl(1,4)=2, it means that you need 2 steps in the trellis to get from state 1 to state 4. Further, if TMi(1,4)=0 it means that the first such step will be followed if when at state 1 the input is 0. Furthermore, suppose that NS(1,0)=2. Then, TMl(2,4) should be 1 (ie, one more step is needed when starting from state 2 and having state 4 as the final destination). Finally, TMi(2,4) will give us the second input required to complete the path from 1 to 4. These matrices are useful when we want to implement an encoder with proper state termination. For instance, based on these matrices we can evaluate how many additional input symbols (and which particular inputs) are required to be appended at the end of an input sequence so that the final state is always 0. Blocks Using the FSM structure In this section we give a brief description of the basic blocks implemented that make use of the previously described FSM structure. Trellis Encoder The trellis.encoder_XX(FSM, ST) block instantiates an FSM encoder corresponding to the fsm FSM and having initial state ST. The input and output is a sequence of bytes, shorts or integers. Viterbi Decoder The trellis.viterbi_X(FSM, K, S0, SK) block instantiates a Viterbi decoder for a sequence of K trellis steps generated by the given FSM and with initial and final states set to S0 and SK, respectively (S0 and/or SK are set to -1 if the corresponding states are not fixed/known at the receiver side). The output of this block is a sequence of K bytes, shorts or integers representing the estimated input (i.e., uncoded) sequence. The input is a sequence of K x FSM.O( ) floats, where the k x K + i float represents the cost associated with the k-th step in the trellis and the i-th FSM output. Observe that these inputs are generated externally and thus the Viterbi block is not informed of their meaning (they can be genarated as soft or hard inputs, etc); the only requirement is that they represent additive costs. Metrics Calculator The trellis.metrics_X(O,D,TABLE,TYPE) block is responsible for transforming the channel output to the stream of metrics appropriate as inputs to the Viterbi block described above. For each D input bytes/shorts/integers/floats/complexes it produces O output floats The parameter TYPE dictates how these metrics are generated: TRELLIS_EUCLIDEAN: for each D-dimensional vector rk= (rk,1,rk,2,...,rk,D) evaluates ||rk-ci||2 = sumj=1D |rk,j-ci,j|2 for each of the O hypothesized ouput symbols ci = (ci,1,ci,2,...,ci,D) defined in the vector TABLE, where TABLE[i * D + j] = ci,j. TRELLIS_HARD_SYMBOL: for each D-dimensional vector rk= (rk,1,rk,2,...,rk,D) evaluates i0= argmini ||rk-ci||2 = argmini sumj=1D |rk,j-ci,j|2 and outputs a sequence of O floats of the form (0,...,0,1,0,...,0), where the i0 position is set to 1. This corresponds to generating hard inputs (based on the symbol-wise Hamming distance) to the Viterbi algorithm. TRELLIS_HARD_BIT (not yet implemented): for each D-dimensional vector rk= (rk,1,rk,2,...,rk,D) evaluates i0= argmini ||rk-ci||2 = argmini sumj=1D (rk,j-ci,j)2 and outputs a sequence of O floats of the form (d1,d2,...,dO), where the di is the bitwise Hamming distance between i and i0. This corresponds to generating hard inputs (based on the bit-wise Hamming distance) to the Viterbi algorithm. Combined Metrics Calculator and Viterbi Decoder Although the separation of metric calculation and Viterbi algorithm blocks is consistent with our goal of providing general blocks that can be easily reused, this separation might result in large input/output buffer sizes betwen blocks. Indeed for an FSM with a large output alphabet, the output of the metric block/input of the Viterbi block is FSM.O( ) floats for each trellis step. Sometimes this results in buffer overflow even for moderate sequence lengths. To overcome this problem we provide a block that incorporates the metric calculation and Viterbi algorithm into a single GNU Radio block, namely trellis.viterbi_combined_X( FSM, K, S0, SK, D, TABLE, TYPE) where the arguments are exactly those used in the aforementioned two blocks. A Complete Example: Trellis Coded Modulation (TCM) We now discuss through a concrete example how the above FSM model can be used in GNU Radio. The communication system that we want to simulate consists of a source generating the input information in packets, a CC encoding each packet separately, a memoryless modulator, an additive white Gaussian noise (AWGN) channel, and the VA performing MLSD. The program source is as follows. &test_tcm_listing; The program is called by ./test_tcm.py fsm_fname Es/No_db repetitions where "fsm_fname" is the file containing the FSM specification of the tested TCM code, "Es/No_db" is the SNR in dB, and "repetitions" are the number of packets to be transmitted and received in order to collect sufficient number of errors for an accurate estimate of the error rate. The FSM is first intantiated in "main" by 62 f=trellis.fsm(fname) # get the FSM specification from a file Each packet has size Kb bits (we choose Kb to be a multiple of 16 so that all bits fit nicely into shorts and can be generated by the lfsr GNU Radio). Assuming that the FSM input has cardinality I, each input symbol consists of bitspersymbol=log2( I ). The Kb/16 shorts are now unpacked to K=Kb/bitspersymbol input symbols that will drive the FSM encoder. 63 Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) 64 bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol 65 K=Kb/bitspersymbol # packet size in trellis steps The FSM will produce K output symbols (remeber the FSM produces always one output symbol for each input symbol). Each of these symbols needs to be modulated. Since we are simulating the communication system, we need not simulate the actual waveforms. An M-ary, D-dimensional modulation is completely specified by a set of M, D-dimensional real vectors. In "fsm_utils.py" file we give a number of useful modulations with the following format: modulation = (D,constellation), where constellation=[c11,c12,...,c1D,c21,c22,...,c2D,...,cM1,cM2,...cMD]. The meaning of the above is that every constellation point c_i is an D-dimnsional vector c_i=(ci1,ci2,...,ciD) For instance, 4-ary PAM is represented as (1,[-3, -1, 1, 3]), while QPSK is represented as (2,[1, 0, 0, 1, 0, -1, -1, 0]). In our example we choose QPSK modulation. Clearly, M should be equal to the cardinality of the FSM output, O. Finally the average symbol energy and noise variance are calculated. 66 modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations 67 dimensionality = modulation[0] 68 constellation = modulation[1] 69 if len(constellation)/dimensionality != f.O(): 70 sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') 71 sys.exit (1) 72 # calculate average symbol energy 73 Es = 0 74 for i in range(len(constellation)): 75 Es = Es + constellation[i]**2 76 Es = Es / (len(constellation)/dimensionality) 77 N0=Es/pow(10.0,esn0_db/10.0); # noise variance Then, "run_test" is called with a different "seed" so that we get different noise realizations. 82 (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations Let us examine now the "run_test" function. First we set up the transmitter blocks. The Kb/16 shorts are first unpacked to symbols consistent with the FSM input alphabet. The FSm encoder requires the FSM specification, and an initial state (which is set to 0 in this example). 15 # TX 16 src = blocks.lfsr_32k_source_s() 17 src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts 18 s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality 19 enc = trellis.encoder_ss(f,0) # initial state = 0 We now need to modulate the FSM output symbols. The "chunks_to_symbols_sf" is essentially a memoryless mapper which for each input symbol y_k outputs a sequence of D numbers ci1,ci2,...,ciD representing the coordianates of the constellation symbol c_i with i=y_k. 20 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) The channel is AWGN with appropriate noise variance. For each transmitted symbol c_k=(ck1,ck2,...,ckD) we receive a noisy version r_k=(rk1,rk2,...,rkD). 22 # CHANNEL 23 add = blocks.add_ff() 24 noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) Part of the design methodology was to decouple the FSM and VA from the details of the modulation, channel, receiver front-end etc. In order for the VA to run, we only need to provide it with a number representing a cost associated with each transition in the trellis. Then the VA will find the sequence with the smallest total cost through the trellis. The cost associated with a transition (s_k,x_k) is only a function of the output y_k = OS(s_k,x_k), and the observation vector r_k. Thus, for each time period, k, we need to label each of the SxI transitions with such a cost. This means that for each time period we need to evaluate O such numbers (one for each possible output symbol y_k). This is done in "metrics_f". In particular, metrics_f is a memoryless device taking D inputs at a time and producing O outputs. The D inputs are rk1,rk2,...,rkD. The O outputs are the costs associated with observations rk1,rk2,...,rkD and hypothesized output symbols c_1,c_2,...,c_M. For instance, if we choose to perform soft-input VA, we need to evaluate the Euclidean distance between r_k and each of c_1,c_2,...,c_M, for each of the K transmitted symbols. Other options are available as well; for instance, we can do hard decision demodulation and feed the VA with symbol Hamming distances, or even bit Hamming distances, etc. These are all implemented in "metrics_f". 26 # RX 27 metrics = trellis.metrics_f(f.O(),dimensionality,constellation,trellis.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi Now the VA can run once it is supplied by the initial and final states. The initial state is known to be 0; the final state is usually forced to some value by padding the information sequence appropriately. In this example, we always send the the same info sequence (we only randomize noise) so we can evaluate off line the final state and then provide it to the VA (a value of -1 signifies that there is no fixed initial or final state). The VA outputs the estimates of the symbols x_k which are then packed to shorts and compared with the transmitted sequence. 28 va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. 29 fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts 30 dst = blocks.check_lfsr_32k_s(); The function returns the number of shorts and the number of shorts in error. Observe that this way the estimated error rate refers to 16-bit-symbol error rate. 48 return (ntotal,ntotal-nright) Another Complete Example: Viterbi Equalization We now discuss through another concrete example how the above FSM model can be used in GNU Radio. The communication system that we want to simulate consists of a source generating the input information in packets, an ISI channel with additive white Gaussian noise (AWGN), and the VA performing MLSD. The program source is as follows. &test_viterbi_equalization1_listing; The program is called by ./test_viterbi_equalization1.py Es/No_db repetitions where "Es/No_db" is the SNR in dB, and "repetitions" are the number of packets to be transmitted and received in order to collect sufficient number of errors for an accurate estimate of the error rate. Each packet has size Kb bits. The modulation is chosen to be 4-PAM in this example and the channel is chosen to be one of the test channels defined in fsm_utils.py 71 Kb=2048 # packet size in bits 72 modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations 73 channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels The FSM is instantiated in 74 f=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically and generated automatically given the channel length and the modulation size. Since in this example the channel has length 5 and the modulation is 4-ary, the corresponding FSM has 45-1=256 states and 45=1024 outputs (see the documentation on FSM for more explanation). Assuming that the FSM input has cardinality I, each input symbol consists of bitspersymbol=log2( I ) bits, and thus correspond to K = Kb/bitspersymbol symbols. 75 bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol 76 K=Kb/bitspersymbol # packet size in trellis steps The overall system with input the 4-ary input symbols xk, modulated to the 4-PAM symbols sk and passed through the ISI channel to produce the noise-free observations zk = sumj=0L-1 cj sk-j (where L is the channel length) can be modeled as a FSM followed by a memoryless modulation. In particular, the FSM input is the sequence xk and its output is the "combined" symbol yk= (xk,xk-1,...,xk-L+1) (actually its decimal representation). The memoryless modulator maps every "combined" symbol yk to zk = sumj=0L-1 cj sk-j Clearly this modulation is memoryless since each zk depends only on yk; the memory inherent in the ISI is hidden in the FSM structure. This memoryless modulator is automatically generated by a helper function in fsm_utils.py given the channel and modulation as in line 78, and has the familiar format tot_channel=(dimensionality,tot_constellation) as described in the TCM example. This is exactly what the metrics block (or the viterbi_combined block) require in order to evaluate the VA metrics from the noisy observations. 78 tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) 79 dimensionality = tot_channel[0] 80 tot_constellation = tot_channel[1] 81 N0=pow(10.0,-esn0_db/10.0); # noise variance 82 if len(tot_constellation)/dimensionality != f.O(): 83 sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') 84 sys.exit (1) Then, "run_test" is called with a different "seed" so that we get different data and noise realizations. 91 (s,e)=run_test(f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,-long(666+i)) # run experiment with different seed to get different data and noise realizations Let us examine now the "run_test" function. First we set up the transmitter blocks. We generate a packet of K random symbols and add a head and a tail of L zeros, L being the channel length. This is sufficient to drive the initial and final states to 0. 14 L = len(channel) 15 16 # TX 17 # this for loop is TOO slow in python!!! 18 packet = [0]*(K+2*L) 19 random.seed(seed) 20 for i in range(len(packet)): 21 packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols 22 for i in range(L): # first/last L symbols set to 0 23 packet[i] = 0 24 packet[len(packet)-i-1] = 0 25 src = blocks.vector_source_s(packet,False) 26 mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) The modulated symbols are filtered by the ISI channel and AWGN with appropriate noise variance is added. 28 # CHANNEL 29 isi = filter.fir_filter_fff(1,channel) 30 add = blocks.add_ff() 31 noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) Since the output alphabet of the equivalent FSM is quite large (1024) we chose to utilize the combined metrics calculator and Viterbi algorithm block. Also note that the first L observations are irrelevant and thus can be skipped. 33 # RX 34 skip = blocks.skiphead(gr.sizeof_float, L) # skip the first L samples since you know they are coming from the L zero symbols 35 #metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,trellis.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi 36 #va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set. 37 va = trellis.viterbi_combined_s(f,K+L,0,0,dimensionality,tot_constellation,trellis.TRELLIS_EUCLIDEAN) # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application... 38 dst = blocks.vector_sink_s() Now the VA can run once it is supplied by the initial and final states. In this example both the initial and final states are set to 0. The VA outputs the estimates of the input symbols which are then compared with the transmitted sequence. 49 data = dst.data() 50 ntotal = len(data) - L 51 nright=0 52 for i in range(ntotal): 53 if packet[i+L]==data[i]: 54 nright=nright+1 55 #else: 56 #print "Error in ", i The function returns the number of symbols and the number of symbols in error. Observe that this way the estimated error rate refers to 2-bit-symbol error rate. 58 return (ntotal,ntotal-nright) Support for Concatenated Coding and Turbo Decoding Soft versions of the algorithms have been implemented. Also examples of turbo equalization/decoding and of sccc can be found in the examples directory. Recently we added gnuradio blocks for sccc and pccc encoders and turbo decoders. Although these can be generated by existing gr-trellis blocks (in particular, the SISO blocks, as done in some of the python examples) there is an advantage in having this functionality as a single block. To see why, think of a turbo decoder with 10 iterations. Previously we needed to concatenate 10 x 2 SISO blocks (for a sccc decoder) to emulate the passing of soft information between SISOs over 10 iterartions. With the new block however, only a single such block is needed that internally loops through 10 iterations; this results in space savings and possibly time saving as well (since queueing at the input/ouput of the gr-blocks is avoided). Still need to document them... Future Work Improve the documentation :-) automate fsm generation from rational functions (feedback form). Optimize the VA code if possible. A host of suboptimal decoders, eg, sphere decoding, M- and T- algorithms, sequential decoding, etc. can be implemented. Although turbo decoding is rediculously slow in software, we can design it in principle. One question is, whether we should use the encoder, and SISO blocks and connect them through GNU radio or we should implement turbo-decoding as a single block (issues with buffering between blocks). So far the former has been implemented.
gnuradio-3.7.2.1/gr-trellis/doc/test_tcm.py.xml0000664000175000017500000000760212207440367021162 0ustar jcorganjcorgan 1 #!/usr/bin/env python 2 3 from gnuradio import gr 4 from gnuradio import audio 5 from gnuradio import trellis, digital, analog, blocks 6 from gnuradio import eng_notation 7 import math 8 import sys 9 import random 10 import fsm_utils 11 12 def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): 13 tb = gr.top_block () 14 15 # TX 16 src = blocks.lfsr_32k_source_s() 17 src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts 18 s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality 19 enc = trellis.encoder_ss(f,0) # initial state = 0 20 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) 21 22 # CHANNEL 23 add = blocks.add_ff() 24 noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) 25 26 # RX 27 metrics = trellis.metrics_f(f.O(),dimensionality,constellation,trellis.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi 28 va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. 29 fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts 30 dst = blocks.check_lfsr_32k_s(); 31 32 tb.connect (src,src_head,s2fsmi,enc,mod) 33 tb.connect (mod,(add,0)) 34 tb.connect (noise,(add,1)) 35 tb.connect (add,metrics) 36 tb.connect (metrics,va,fsmi2s,dst) 37 38 tb.run() 39 40 # A bit of cheating: run the program once and print the 41 # final encoder state. 42 # Then put it as the last argument in the viterbi block 43 #print "final state = " , enc.ST() 44 45 ntotal = dst.ntotal () 46 nright = dst.nright () 47 runlength = dst.runlength () 48 return (ntotal,ntotal-nright) 49 50 51 def main(args): 52 nargs = len (args) 53 if nargs == 3: 54 fname=args[0] 55 esn0_db=float(args[1]) # Es/No in dB 56 rep=int(args[2]) # number of times the experiment is run to collect enough errors 57 else: 58 sys.stderr.write ('usage: test_tcm.py fsm_fname Es/No_db repetitions\n') 59 sys.exit (1) 60 61 # system parameters 62 f=trellis.fsm(fname) # get the FSM specification from a file 63 Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) 64 bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol 65 K=Kb/bitspersymbol # packet size in trellis steps 66 modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations 67 dimensionality = modulation[0] 68 constellation = modulation[1] 69 if len(constellation)/dimensionality != f.O(): 70 sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') 71 sys.exit (1) 72 # calculate average symbol energy 73 Es = 0 74 for i in range(len(constellation)): 75 Es = Es + constellation[i]**2 76 Es = Es / (len(constellation)/dimensionality) 77 N0=Es/pow(10.0,esn0_db/10.0); # noise variance 78 79 tot_s=0 80 terr_s=0 81 for i in range(rep): 82 (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations 83 tot_s=tot_s+s 84 terr_s=terr_s+e 85 if (i%100==0): 86 print i,s,e,tot_s,terr_s, '%e' % ((1.0*terr_s)/tot_s) 87 # estimate of the (short) error rate 88 print tot_s,terr_s, '%e' % ((1.0*terr_s)/tot_s) 89 90 91 if __name__ == '__main__': 92 main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/doc/test_viterbi_equalization1.py.xml0000664000175000017500000001112012207440367024677 0ustar jcorganjcorgan 1 #!/usr/bin/env python 2 3 from gnuradio import gr 4 from gnuradio import audio 5 from gnuradio import trellis, digital, analog, filter, blocks 6 from gnuradio import eng_notation 7 import math 8 import sys 9 import random 10 import fsm_utils 11 12 def run_test (f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,seed): 13 tb = gr.top_block () 14 L = len(channel) 15 16 # TX 17 # this for loop is TOO slow in python!!! 18 packet = [0]*(K+2*L) 19 random.seed(seed) 20 for i in range(len(packet)): 21 packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols 22 for i in range(L): # first/last L symbols set to 0 23 packet[i] = 0 24 packet[len(packet)-i-1] = 0 25 src = blocks.vector_source_s(packet,False) 26 mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) 27 28 # CHANNEL 29 isi = filter.fir_filter_fff(1,channel) 30 add = blocs.add_ff() 31 noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) 32 33 # RX 34 skip = blocks.skiphead(gr.sizeof_float, L) # skip the first L samples since you know they are coming from the L zero symbols 35 #metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,trellis.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi 36 #va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set. 37 va = trellis.viterbi_combined_s(f,K+L,0,0,dimensionality,tot_constellation,trellis.TRELLIS_EUCLIDEAN) # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application... 38 dst = blocks.vector_sink_s() 39 40 tb.connect (src,mod) 41 tb.connect (mod,isi,(add,0)) 42 tb.connect (noise,(add,1)) 43 #tb.connect (add,metrics) 44 #tb.connect (metrics,va,dst) 45 tb.connect (add,skip,va,dst) 46 47 tb.run() 48 49 data = dst.data() 50 ntotal = len(data) - L 51 nright=0 52 for i in range(ntotal): 53 if packet[i+L]==data[i]: 54 nright=nright+1 55 #else: 56 #print "Error in ", i 57 58 return (ntotal,ntotal-nright) 59 60 61 def main(args): 62 nargs = len (args) 63 if nargs == 2: 64 esn0_db=float(args[0]) 65 rep=int(args[1]) 66 else: 67 sys.stderr.write ('usage: test_viterbi_equalization1.py Es/No_db repetitions\n') 68 sys.exit (1) 69 70 # system parameters 71 Kb=2048 # packet size in bits 72 modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations 73 channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels 74 f=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically 75 bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol 76 K=Kb/bitspersymbol # packet size in trellis steps 77 78 tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) 79 dimensionality = tot_channel[0] 80 tot_constellation = tot_channel[1] 81 N0=pow(10.0,-esn0_db/10.0); # noise variance 82 if len(tot_constellation)/dimensionality != f.O(): 83 sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') 84 sys.exit (1) 85 86 tot_s=0 # total number of transmitted shorts 87 terr_s=0 # total number of shorts in error 88 terr_p=0 # total number of packets in error 89 90 for i in range(rep): 91 (s,e)=run_test(f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,-long(666+i)) # run experiment with different seed to get different data and noise realizations 92 tot_s=tot_s+s 93 terr_s=terr_s+e 94 terr_p=terr_p+(terr_s!=0) 95 if ((i+1)%100==0) : # display progress 96 print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) 97 # estimate of the (short or symbol) error rate 98 print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) 99 100 101 if __name__ == '__main__': 102 main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/doc/test_tcm.py0000664000175000017500000000671012207440367020362 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import audio from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality enc = trellis.encoder_ss(f,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics = trellis.metrics_f(f.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s(); tb.connect (src,src_head,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics) tb.connect (metrics,va,fsmi2s,dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state. # Then put it as the last argument in the viterbi block #print "final state = " , enc.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 3: fname=args[0] esn0_db=float(args[1]) # Es/No in dB rep=int(args[2]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_tcm.py fsm_fname Es/No_db repetitions\n') sys.exit (1) # system parameters f=trellis.fsm(fname) # get the FSM specification from a file Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # noise variance tot_s=0 terr_s=0 for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e if (i%100==0): print i,s,e,tot_s,terr_s, '%e' % ((1.0*terr_s)/tot_s) # estimate of the (short) error rate print tot_s,terr_s, '%e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/doc/test_viterbi_equalization1.py0000775000175000017500000001012512207440367024107 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import audio from gnuradio import trellis, digital, filter, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,seed): tb = gr.top_block () L = len(channel) # TX # this for loop is TOO slow in python!!! packet = [0]*(K+2*L) random.seed(seed) for i in range(len(packet)): packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols for i in range(L): # first/last L symbols set to 0 packet[i] = 0 packet[len(packet)-i-1] = 0 src = blocks.vector_source_s(packet,False) mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) # CHANNEL isi = filter.fir_filter_fff(1,channel) add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX skip = blocks.skiphead(gr.sizeof_float, L) # skip the first L samples since you know they are coming from the L zero symbols #metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi #va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set. va = trellis.viterbi_combined_s(f,K+L,0,0,dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application... dst = blocks.vector_sink_s() tb.connect (src,mod) tb.connect (mod,isi,(add,0)) tb.connect (noise,(add,1)) #tb.connect (add,metrics) #tb.connect (metrics,va,dst) tb.connect (add,skip,va,dst) tb.run() data = dst.data() ntotal = len(data) - L nright=0 for i in range(ntotal): if packet[i+L]==data[i]: nright=nright+1 #else: #print "Error in ", i return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 2: esn0_db=float(args[0]) rep=int(args[1]) else: sys.stderr.write ('usage: test_viterbi_equalization1.py Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=2048 # packet size in bits modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels f=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) dimensionality = tot_channel[0] tot_constellation = tot_channel[1] N0=pow(10.0,-esn0_db/10.0); # noise variance if len(tot_constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') sys.exit (1) tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,-long(666+i)) # run experiment with different seed to get different data and noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or symbol) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/python/0000775000175000017500000000000012207440367016736 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/python/trellis/0000775000175000017500000000000012207440367020414 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/python/trellis/CMakeLists.txt0000664000175000017500000000333212207440367023155 0ustar jcorganjcorgan# Copyright 2011-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/trellis COMPONENT "trellis_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-trellis/python/trellis/qa_trellis.py0000775000175000017500000001137212207440367023134 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2010,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math import os from gnuradio import gr, gr_unittest, trellis, digital, analog, blocks fsm_args = {"awgn1o2_4": (2, 4, 4, (0, 2, 0, 2, 1, 3, 1, 3), (0, 3, 3, 0, 1, 2, 2, 1), ), "rep2": (2, 1, 4, (0, 0), (0, 3)), "nothing": (2, 1, 2, (0, 0), (0, 1)), } constells = {2: digital.constellation_bpsk(), 4: digital.constellation_qpsk(), } class test_trellis (gr_unittest.TestCase): def test_001_fsm (self): f = trellis.fsm(*fsm_args["awgn1o2_4"]) self.assertEqual(fsm_args["awgn1o2_4"],(f.I(),f.S(),f.O(),f.NS(),f.OS())) def test_002_fsm (self): f = trellis.fsm(*fsm_args["awgn1o2_4"]) g = trellis.fsm(f) self.assertEqual((g.I(),g.S(),g.O(),g.NS(),g.OS()),(f.I(),f.S(),f.O(),f.NS(),f.OS())) def test_003_fsm (self): # FIXME: no file "awgn1o2_4.fsm" #f = trellis.fsm("awgn1o2_4.fsm") #self.assertEqual(fsm_args["awgn1o2_4"],(f.I(),f.S(),f.O(),f.NS(),f.OS())) pass def test_004_fsm(self): """ Test to make sure fsm works with a single state fsm.""" # Just checking that it initializes properly. f = trellis.fsm(*fsm_args["rep2"]) def test_001_interleaver (self): K = 5 IN = (1,2,3,4,0) DIN = (4,0,1,2,3) i = trellis.interleaver(K,IN) self.assertEqual((K,IN,DIN),(i.K(),i.INTER(),i.DEINTER())) def test_001_viterbi(self): """ Runs some coding/decoding tests with a few different FSM specs. """ for name, args in fsm_args.items(): constellation = constells[args[2]] fsms = trellis.fsm(*args) noise = 0.1 tb = trellis_tb(constellation, fsms, noise) tb.run() # Make sure all packets succesfully transmitted. self.assertEqual(tb.dst.ntotal(), tb.dst.nright()) class trellis_tb(gr.top_block): """ A simple top block for use testing gr-trellis. """ def __init__(self, constellation, f, N0=0.25, seed=-666L): """ constellation - a constellation object used for modulation. f - a finite state machine specification used for coding. N0 - noise level seed - random seed """ super(trellis_tb, self).__init__() # packet size in bits (make it multiple of 16 so it can be packed in a short) packet_size = 1024*16 # bits per FSM input symbol bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol # packet size in trellis steps K = packet_size/bitspersymbol # TX src = blocks.lfsr_32k_source_s() # packet size in shorts src_head = blocks.head(gr.sizeof_short, packet_size/16) # unpack shorts to symbols compatible with the FSM input cardinality s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol, gr.GR_MSB_FIRST) # initial FSM state = 0 enc = trellis.encoder_ss(f, 0) mod = digital.chunks_to_symbols_sc(constellation.points(), 1) # CHANNEL add = blocks.add_cc() noise = analog.noise_source_c(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX # data preprocessing to generate metrics for Viterbi metrics = trellis.constellation_metrics_cf(constellation.base(), digital.TRELLIS_EUCLIDEAN) # Put -1 if the Initial/Final states are not set. va = trellis.viterbi_s(f, K, 0, -1) # pack FSM input symbols to shorts fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol, gr.GR_MSB_FIRST) # check the output self.dst = blocks.check_lfsr_32k_s() self.connect (src, src_head, s2fsmi, enc, mod) self.connect (mod, (add, 0)) self.connect (noise, (add, 1)) self.connect (add, metrics, va, fsmi2s, self.dst) if __name__ == '__main__': gr_unittest.run(test_trellis, "test_trellis.xml") gnuradio-3.7.2.1/gr-trellis/python/trellis/awgn1o2_4.fsm0000664000175000017500000000011612207440367022622 0ustar jcorganjcorgan2 4 4 0 2 0 2 1 3 1 3 0 3 3 0 1 2 2 1 AWGN CC from Proakis-Salehi pg 779 gnuradio-3.7.2.1/gr-trellis/python/trellis/__init__.py0000664000175000017500000000217112207440367022526 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks and utilities for trellis coding and related. ''' # The presence of this file turns this directory into a Python package import os try: from trellis_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from trellis_swig import * gnuradio-3.7.2.1/gr-trellis/lib/0000775000175000017500000000000012207440367016163 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/lib/CMakeLists.txt0000664000175000017500000001245112207440367020726 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_BINARY_DIR}/../include ${GR_TRELLIS_INCLUDE_DIRS} ${GR_DIGITAL_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${LOG4CXX_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${Boost_LIBRARY_DIRS}) link_directories(${LOG4CXX_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ####################################################################### # generate the python helper script which calls into the build utils ######################################################################## include(GrPython) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py " #!${PYTHON_EXECUTABLE} import sys, os, re sys.path.append('${GR_RUNTIME_PYTHONPATH}') os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}' os.chdir('${CMAKE_CURRENT_BINARY_DIR}') if __name__ == '__main__': import build_utils root, inp = sys.argv[1:3] for sig in sys.argv[3:]: name = re.sub ('X+', sig, root) d = build_utils.standard_impl_dict2(name, sig, 'trellis') build_utils.expand_template(d, inp) ") macro(expand_cc root) #make a list of all the generated files unset(expanded_files_cc) unset(expanded_files_h) foreach(sig ${ARGN}) string(REGEX REPLACE "X+" ${sig} name ${root}) list(APPEND expanded_files_cc ${CMAKE_CURRENT_BINARY_DIR}/${name}.cc) list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h) endforeach(sig) #create a command to generate the source files add_custom_command( OUTPUT ${expanded_files_cc} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.cc.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.cc.t ${ARGN} ) #create a command to generate the header file add_custom_command( OUTPUT ${expanded_files_h} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py ${root} ${root}.h.t ${ARGN} ) #make source files depends on headers to force generation set_source_files_properties(${expanded_files_cc} PROPERTIES OBJECT_DEPENDS "${expanded_files_h}" ) #install rules for the generated cc files list(APPEND generated_sources ${expanded_files_cc}) list(APPEND generated_headers ${expanded_files_h}) endmacro(expand_cc) ######################################################################## # Invoke macro to generate various sources ######################################################################## expand_cc(encoder_XX_impl bb bs bi ss si ii) expand_cc(sccc_encoder_XX_impl bb bs bi ss si ii) expand_cc(pccc_encoder_XX_impl bb bs bi ss si ii) expand_cc(metrics_X_impl s i f c) expand_cc(viterbi_X_impl b s i) expand_cc(viterbi_combined_XX_impl sb ss si ib is ii fb fs fi cb cs ci) expand_cc(sccc_decoder_X_impl b s i) expand_cc(sccc_decoder_combined_XX_impl fb fs fi cb cs ci) expand_cc(pccc_decoder_X_impl b s i) expand_cc(pccc_decoder_combined_XX_impl fb fs fi cb cs ci) ######################################################################## # Setup library ######################################################################## list(APPEND trellis_sources ${generated_sources} base.cc calc_metric.cc core_algorithms.cc fsm.cc interleaver.cc quicksort_index.cc constellation_metrics_cf_impl.cc permutation_impl.cc siso_f_impl.cc siso_combined_f_impl.cc ) list(APPEND trellis_libs gnuradio-runtime gnuradio-digital ${Boost_LIBRARIES} ) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-trellis.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-trellis.rc @ONLY) list(APPEND trellis_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-trellis.rc ) ENDIF(MSVC) add_library(gnuradio-trellis SHARED ${trellis_sources}) target_link_libraries(gnuradio-trellis ${trellis_libs}) GR_LIBRARY_FOO(gnuradio-trellis RUNTIME_COMPONENT "trellis_runtime" DEVEL_COMPONENT "trellis_devel") add_dependencies(gnuradio-trellis trellis_generated_includes trellis_generated_swigs gnuradio-runtime gnuradio-digital) gnuradio-3.7.2.1/gr-trellis/lib/pccc_decoder_combined_XX_impl.cc.t0000664000175000017500000000770312207440367024640 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling) { return gnuradio::get_initial_sptr (new @NAME@(FSMo, STo0, SToK, FSMi, STi0, STiK, INTERLEAVER, blocklength, repetitions, SISO_TYPE, D, TABLE,METRIC_TYPE, scaling)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling) : block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_FSMo(FSMo), d_STo0(STo0), d_SToK(SToK), d_FSMi(FSMi), d_STi0(STi0), d_STiK(STiK), d_INTERLEAVER(INTERLEAVER), d_blocklength(blocklength), d_repetitions(repetitions), d_SISO_TYPE(SISO_TYPE), d_D(D), d_TABLE(TABLE), d_METRIC_TYPE(METRIC_TYPE), d_scaling(scaling) { assert(d_FSMo.I() == d_FSMi.I()); set_relative_rate (1.0 / ((double) d_D)); set_output_multiple (d_blocklength); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_scaling(float scaling) { d_scaling = scaling; } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_D * noutput_items; ninput_items_required[0] = input_required; } //=========================================================== int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nblocks = noutput_items / d_blocklength; float (*p2min)(float, float) = NULL; if(d_SISO_TYPE == TRELLIS_MIN_SUM) p2min = &min; else if(d_SISO_TYPE == TRELLIS_SUM_PRODUCT) p2min = &min_star; const @I_TYPE@ *in = (const @I_TYPE@ *) input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *) output_items[0]; for (int n=0;n #include namespace gr { namespace trellis { @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSM, int ST) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSM,ST)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSM, int ST) : sync_block("@BASE_NAME@", io_signature::make(1, -1, sizeof(@I_TYPE@)), io_signature::make(1, -1, sizeof(@O_TYPE@))), d_FSM(FSM), d_ST(ST) { } @IMPL_NAME@::~@IMPL_NAME@() { } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ST_tmp = 0; int nstreams = input_items.size(); for(int m=0;m #include #include #include #include namespace gr { namespace trellis { class siso_f_impl : public siso_f { private: fsm d_FSM; int d_K; int d_S0; int d_SK; bool d_POSTI; bool d_POSTO; siso_type_t d_SISO_TYPE; //std::vector d_alpha; //std::vector d_beta; public: siso_f_impl(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t d_SISO_TYPE); ~siso_f_impl(); fsm FSM() const { return d_FSM; } int K() const { return d_K; } int S0() const { return d_S0; } int SK() const { return d_SK; } bool POSTI() const { return d_POSTI; } bool POSTO() const { return d_POSTO; } siso_type_t SISO_TYPE() const { return d_SISO_TYPE; } void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_SISO_F_IMPL_H */ gnuradio-3.7.2.1/gr-trellis/lib/sccc_encoder_XX_impl.h.t0000664000175000017500000000347312207440367022657 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSMo; int d_STo; fsm d_FSMi; int d_STi; interleaver d_INTERLEAVER; int d_blocklength; std::vector d_buffer; public: @IMPL_NAME@(const fsm &FSMo, int STo, const fsm &FSMi, int STi, const interleaver &INTERLEAVER, int blocklength); ~@IMPL_NAME@(); fsm FSMo() const { return d_FSMo; } int STo() const { return d_STo; } fsm FSMi() const { return d_FSMi; } int STi() const { return d_STi; } interleaver INTERLEAVER() const { return d_INTERLEAVER; } int blocklength() const { return d_blocklength; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/viterbi_combined_XX_impl.h.t0000664000175000017500000000421412207440367023543 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSM; int d_K; int d_S0; int d_SK; int d_D; std::vector<@I_TYPE@> d_TABLE; digital::trellis_metric_type_t d_TYPE; //std::vector d_trace; public: @IMPL_NAME@(const fsm &FSM, int K, int S0, int SK, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE); ~@IMPL_NAME@(); fsm FSM() const { return d_FSM; } int K() const { return d_K; } int S0() const { return d_S0; } int SK() const { return d_SK; } int D() const { return d_D; } std::vector<@I_TYPE@> TABLE() const { return d_TABLE; } digital::trellis_metric_type_t TYPE() const { return d_TYPE; } //std::vector trace() const { return d_trace; } void set_TABLE(const std::vector<@I_TYPE@> &table); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/pccc_encoder_XX_impl.h.t0000664000175000017500000000347512207440367022656 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSM1; int d_ST1; fsm d_FSM2; int d_ST2; interleaver d_INTERLEAVER; int d_blocklength; std::vector d_buffer; public: @IMPL_NAME@(const fsm &FSM1, int ST1, const fsm &FSM2, int ST2, const interleaver &INTERLEAVER, int blocklength); ~@IMPL_NAME@(); fsm FSM1() const { return d_FSM1; } int ST1() const { return d_ST1; } fsm FSM2() const { return d_FSM2; } int ST2() const { return d_ST2; } interleaver INTERLEAVER() const { return d_INTERLEAVER; } int blocklength() const { return d_blocklength; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/core_algorithms.cc0000664000175000017500000011703212207440367021657 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; float min(float a, float b) { return a <= b ? a : b; } float min_star(float a, float b) { return (a <= b ? a : b)-log(1+exp(a <= b ? a-b : b-a)); } template void viterbi_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, const float *in, T *out)//, //std::vector &trace) { std::vector trace(S*K); std::vector alpha(S*2); int alphai; float norm,mm,minm; int minmi; int st; if(S0<0) { // initial state not specified for(int i=0;i=0;k--) { // traceback int i0=trace[k*S+st]; out[k]= (T) PI[st][i0]; st=PS[st][i0]; } } template void viterbi_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, const float *in, unsigned char *out); template void viterbi_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, const float *in, short *out); template void viterbi_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, const float *in, int *out); //============================================== template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const Ti *in, To *out) { std::vector trace(S*K); std::vector alpha(S*2); float *metric = new float[O]; int alphai; float norm,mm,minm; int minmi; int st; if(S0<0) { // initial state not specified for(int i=0;i=0;k--) { // traceback int i0=trace[k*S+st]; out[k]= (To) PI[st][i0]; st=PS[st][i0]; } delete [] metric; } // Ti = s i f c // To = b s i //--------------- template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const short *in, unsigned char *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const int *in, unsigned char *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *in, unsigned char *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const gr_complex *in, unsigned char *out); //--------------- template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const short *in, short *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const int *in, short *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *in, short *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const gr_complex *in, short *out); //-------------- template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const short *in, int *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const int *in, int *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *in, int *out); template void viterbi_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const gr_complex *in, int *out); //=============================================== void siso_algorithm(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), const float *priori, const float *prioro, float *post//, //std::vector &alpha, //std::vector &beta ) { float norm,mm,minm; std::vector alpha(S*(K+1)); std::vector beta(S*(K+1)); if(S0<0) { // initial state not specified for(int i=0;i=0;k--) { // backward recursion norm=INF; for(int j=0;j void siso_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *priori, const T *observations, float *post) { float norm,mm,minm; std::vector alpha(S*(K+1)); std::vector beta(S*(K+1)); float *prioro = new float[O*K]; if(S0<0) { // initial state not specified for(int i=0;i=0;k--) { // backward recursion norm=INF; for(int j=0;j(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *priori, const short *observations, float *post); template void siso_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *priori, const int *observations, float *post); template void siso_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *priori, const float *observations, float *post); template void siso_algorithm_combined(int I, int S, int O, const std::vector &NS, const std::vector &OS, const std::vector< std::vector > &PS, const std::vector< std::vector > &PI, int K, int S0,int SK, bool POSTI, bool POSTO, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE, const float *priori, const gr_complex *observations, float *post); //========================================================= template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const Ti *observations, To *data) { //allocate space for priori, prioro and posti of inner FSM std::vector ipriori(blocklength*FSMi.I(),0.0); std::vector iprioro(blocklength*FSMi.O()); std::vector iposti(blocklength*FSMi.I()); //allocate space for priori, prioro and posto of outer FSM std::vector opriori(blocklength*FSMo.I(),0.0); std::vector oprioro(blocklength*FSMo.O()); std::vector oposti(blocklength*FSMo.I()); std::vector oposto(blocklength*FSMo.O()); // turn observations to neg-log-priors for(int k=0;k outer for(int k=0;k inner for(int k=0;k(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const float *observations, unsigned char *data); template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const float *observations, short *data); template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const float *observations, int *data); template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const gr_complex *observations, unsigned char *data ); template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const gr_complex *observations, short *data); template void sccc_decoder_combined(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const gr_complex *observations, int *data); //========================================================= template void sccc_decoder(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *iprioro, T *data) { //allocate space for priori, and posti of inner FSM std::vector ipriori(blocklength*FSMi.I(),0.0); std::vector iposti(blocklength*FSMi.I()); //allocate space for priori, prioro and posto of outer FSM std::vector opriori(blocklength*FSMo.I(),0.0); std::vector oprioro(blocklength*FSMo.O()); std::vector oposti(blocklength*FSMo.I()); std::vector oposto(blocklength*FSMo.O()); for(int rep=0;rep outer for(int k=0;k inner for(int k=0;k(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *iprioro, unsigned char *data); template void sccc_decoder(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *iprioro, short *data); template void sccc_decoder(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *iprioro, int *data); //==================================================== template void pccc_decoder(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *cprioro, T *data) { //allocate space for priori, prioro and posti of FSM1 std::vector priori1(blocklength*FSM1.I(),0.0); std::vector prioro1(blocklength*FSM1.O()); std::vector posti1(blocklength*FSM1.I()); //allocate space for priori, prioro and posti of FSM2 std::vector priori2(blocklength*FSM2.I(),0.0); std::vector prioro2(blocklength*FSM2.O()); std::vector posti2(blocklength*FSM2.I()); //generate prioro1,2 (metrics are not updated per iteration: this is not the best you can do...) for(int k=0;k 2 for(int k=0;k 1 for(int k=0;k(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *cprioro, unsigned char *data); template void pccc_decoder(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *cprioro, short *data); template void pccc_decoder(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), const float *cprioro, int *data); //---------------- template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const Ti *observations, To *data) { //allocate space for cprioro std::vector cprioro(blocklength*FSM1.O()*FSM2.O(),0.0); //allocate space for priori, prioro and posti of FSM1 std::vector priori1(blocklength*FSM1.I(),0.0); std::vector prioro1(blocklength*FSM1.O()); std::vector posti1(blocklength*FSM1.I()); //allocate space for priori, prioro and posti of FSM2 std::vector priori2(blocklength*FSM2.I(),0.0); std::vector prioro2(blocklength*FSM2.O()); std::vector posti2(blocklength*FSM2.I()); // turn observations to neg-log-priors for cprioiro int O=FSM1.O()*FSM2.O(); for(int k=0;k 2 for(int k=0;k 1 for(int k=0;k &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const float *observations, unsigned char *data); template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const float *observations, short *data); template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const float *observations, int *data); template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const gr_complex *observations, unsigned char *data); template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const gr_complex *observations, short *data); template void pccc_decoder_combined(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int iterations, float (*p2mymin)(float,float), int D, const std::vector &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling, const gr_complex *observations, int *data); } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/permutation_impl.cc0000664000175000017500000000523712207440367022071 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "permutation_impl.h" #include #include #include namespace gr { namespace trellis { permutation::sptr permutation::make(int K, const std::vector &TABLE, int SYMS_PER_BLOCK, size_t BYTES_PER_SYMBOL) { return gnuradio::get_initial_sptr (new permutation_impl(K,TABLE,SYMS_PER_BLOCK,BYTES_PER_SYMBOL)); } permutation_impl::permutation_impl(int K, const std::vector &TABLE, int SYMS_PER_BLOCK, size_t BYTES_PER_SYMBOL) : sync_block("permutation", io_signature::make(1, -1, BYTES_PER_SYMBOL), io_signature::make(1, -1, BYTES_PER_SYMBOL)), d_K(K), d_TABLE(TABLE), d_SYMS_PER_BLOCK(SYMS_PER_BLOCK), d_BYTES_PER_SYMBOL(BYTES_PER_SYMBOL) { set_output_multiple(d_K*SYMS_PER_BLOCK); //std::cout << d_K << "\n"; } permutation_impl::~permutation_impl() { } int permutation_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nstreams = input_items.size(); for(int m=0;m #include namespace gr { namespace trellis { @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSMo, int STo, const fsm &FSMi, int STi, const interleaver &INTERLEAVER, int blocklength) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSMo, STo, FSMi, STi, INTERLEAVER, blocklength)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSMo, int STo, const fsm &FSMi, int STi, const interleaver &INTERLEAVER, int blocklength) : sync_block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_FSMo(FSMo), d_STo(STo), d_FSMi(FSMi), d_STi(STi), d_INTERLEAVER(INTERLEAVER), d_blocklength(blocklength) { set_output_multiple(d_blocklength); d_buffer.resize(d_blocklength); } @IMPL_NAME@::~@IMPL_NAME@() { } int @IMPL_NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { for(int b = 0; b < noutput_items/d_blocklength; b++) { const @I_TYPE@ *in = (const @I_TYPE@*)input_items[0]+b*d_blocklength; @O_TYPE@ *out = (@O_TYPE@*)output_items[0]+b*d_blocklength; int STo_tmp = d_STo; for(int i = 0; i < d_blocklength; i++) { d_buffer[i] = d_FSMo.OS()[STo_tmp*d_FSMo.I()+in[i]]; STo_tmp = (int) d_FSMo.NS()[STo_tmp*d_FSMo.I()+in[i]]; } int STi_tmp = d_STi; for(int i = 0; i < d_blocklength; i++) { int k = d_INTERLEAVER.INTER()[i]; out[i] = (@O_TYPE@) d_FSMi.OS()[STi_tmp*d_FSMi.I()+d_buffer[k]]; STi_tmp = (int) d_FSMi.NS()[STi_tmp*d_FSMi.I()+d_buffer[k]]; } } return noutput_items; } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/permutation_impl.h0000664000175000017500000000342612207440367021731 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_PERMUTATION_IMPL_H #define INCLUDED_TRELLIS_PERMUTATION_IMPL_H #include #include namespace gr { namespace trellis { class permutation_impl : public permutation { private: int d_K; std::vector d_TABLE; int d_SYMS_PER_BLOCK; size_t d_BYTES_PER_SYMBOL; public: permutation_impl(int K, const std::vector &TABLE, int SYMS_PER_BLOCK, size_t NBYTES); ~permutation_impl(); int K() const { return d_K; } const std::vector & TABLE() const { return d_TABLE; } int SYMS_PER_BLOCK() const { return d_SYMS_PER_BLOCK; } size_t BYTES_PER_SYMBOL() const { return d_BYTES_PER_SYMBOL; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_PERMUTATION_IMPL_H */ gnuradio-3.7.2.1/gr-trellis/lib/siso_combined_f_impl.h0000664000175000017500000000467112207440367022507 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_SISO_COMBINED_F_IMPL_H #define INCLUDED_TRELLIS_SISO_COMBINED_F_IMPL_H #include namespace gr { namespace trellis { class siso_combined_f_impl : public siso_combined_f { private: fsm d_FSM; int d_K; int d_S0; int d_SK; bool d_POSTI; bool d_POSTO; siso_type_t d_SISO_TYPE; int d_D; std::vector d_TABLE; digital::trellis_metric_type_t d_TYPE; //std::vector d_alpha; //std::vector d_beta; public: siso_combined_f_impl(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t d_SISO_TYPE, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE); ~siso_combined_f_impl(); fsm FSM() const { return d_FSM; } int K() const { return d_K; } int S0() const { return d_S0; } int SK() const { return d_SK; } bool POSTI() const { return d_POSTI; } bool POSTO() const { return d_POSTO; } siso_type_t SISO_TYPE() const { return d_SISO_TYPE; } int D() const { return d_D; } std::vector TABLE() const { return d_TABLE; } digital::trellis_metric_type_t TYPE() const { return d_TYPE; } void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_SISO_COMBINED_F_IMPL_H */ gnuradio-3.7.2.1/gr-trellis/lib/viterbi_X_impl.cc.t0000664000175000017500000000526212207440367021715 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSM, int K, int S0, int SK) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSM, K, S0, SK)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSM, int K, int S0, int SK) : block("@BASE_NAME@", io_signature::make(1, -1, sizeof(float)), io_signature::make(1, -1, sizeof(@TYPE@))), d_FSM(FSM), d_K(K), d_S0(S0), d_SK(SK)//, //d_trace(FSM.S()*K) { set_relative_rate(1.0 / ((double)d_FSM.O())); set_output_multiple(d_K); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_FSM.O() * noutput_items; unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = input_required; } } int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nstreams = input_items.size(); int nblocks = noutput_items / d_K; for(int m = 0; m < nstreams; m++) { const float *in = (const float*)input_items[m]; @TYPE@ *out = (@TYPE@*)output_items[m]; for(int n = 0; n < nblocks; n++) { viterbi_algorithm(d_FSM.I(), d_FSM.S(), d_FSM.O(), d_FSM.NS(), d_FSM.OS(), d_FSM.PS(), d_FSM.PI(), d_K,d_S0, d_SK, &(in[n*d_K*d_FSM.O()]), &(out[n*d_K])); } } consume_each(d_FSM.O() * noutput_items); return noutput_items; } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/pccc_decoder_combined_XX_impl.h.t0000664000175000017500000000546512207440367024505 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSMo; int d_STo0; int d_SToK; fsm d_FSMi; int d_STi0; int d_STiK; interleaver d_INTERLEAVER; int d_blocklength; int d_repetitions; siso_type_t d_SISO_TYPE; int d_D; std::vector<@I_TYPE@> d_TABLE; digital::trellis_metric_type_t d_METRIC_TYPE; float d_scaling; std::vector d_buffer; public: @IMPL_NAME@(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling); ~@IMPL_NAME@(); fsm FSM1() const { return d_FSMo; } fsm FSM2() const { return d_FSMi; } int ST10() const { return d_STo0; } int ST1K() const { return d_SToK; } int ST20() const { return d_STi0; } int ST2K() const { return d_STiK; } interleaver INTERLEAVER() const { return d_INTERLEAVER; } int blocklength() const { return d_blocklength; } int repetitions() const { return d_repetitions; } int D() const { return d_D; } std::vector<@I_TYPE@> TABLE() const { return d_TABLE; } digital::trellis_metric_type_t METRIC_TYPE() const { return d_METRIC_TYPE; } siso_type_t SISO_TYPE() const { return d_SISO_TYPE; } float scaling() const { return d_scaling; } void set_scaling(float scaling); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/encoder_XX_impl.h.t0000664000175000017500000000262412207440367021661 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSM; int d_ST; public: @IMPL_NAME@(const fsm &FSM, int ST); ~@IMPL_NAME@(); fsm FSM() const { return d_FSM; } int ST() const { return d_ST; } int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/pccc_decoder_X_impl.cc.t0000664000175000017500000000665712207440367022657 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSM1, ST10, ST1K, FSM2, ST20, ST2K, INTERLEAVER, blocklength, repetitions, SISO_TYPE)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE) : block("@BASE_NAME@", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_FSM1(FSM1), d_ST10(ST10), d_ST1K(ST1K), d_FSM2(FSM2), d_ST20(ST20), d_ST2K(ST2K), d_INTERLEAVER(INTERLEAVER), d_blocklength(blocklength), d_repetitions(repetitions), d_SISO_TYPE(SISO_TYPE) { set_relative_rate (1.0 / ((double) d_FSM1.O() * d_FSM2.O())); set_output_multiple (d_blocklength); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_FSM1.O() * d_FSM2.O() * noutput_items; ninput_items_required[0] = input_required; } //=========================================================== int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nblocks = noutput_items / d_blocklength; float (*p2min)(float, float) = NULL; if(d_SISO_TYPE == TRELLIS_MIN_SUM) p2min = &min; else if(d_SISO_TYPE == TRELLIS_SUM_PRODUCT) p2min = &min_star; const float *in = (const float *) input_items[0]; @O_TYPE@ *out = (@O_TYPE@ *) output_items[0]; for(int n=0;n namespace gr { namespace trellis { template void SWAP(T & a, T & b) { T temp = a; a = b; b = temp; } template void quicksort_index (std::vector & p, std::vector & index, int left, int right) { if(left < right) { int i = left; int j = right + 1; T pivot = p[left]; do { do i++; while ((p[i] < pivot) && (i < right)); do j--; while ((p[j] > pivot) && (j > left)); if (i < j) { SWAP (p[i],p[j]); SWAP (index[i],index[j]); } } while (i < j); SWAP (p[left], p[j]); SWAP (index[left], index[j]); quicksort_index (p,index, left, j-1); quicksort_index (p,index, j+1, right); } } // instantiate an version of the quicksort_index //template void SWAP (int & a, int & b); template void quicksort_index(std::vector & p, std::vector & index, int left, int right); } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/siso_f_impl.cc0000664000175000017500000001230412207440367020775 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "siso_f_impl.h" #include #include #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; siso_f::sptr siso_f::make(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t SISO_TYPE) { return gnuradio::get_initial_sptr (new siso_f_impl(FSM, K, S0, SK, POSTI, POSTO, SISO_TYPE)); } siso_f_impl::siso_f_impl(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t SISO_TYPE) : block("siso_f", io_signature::make(1, -1, sizeof(float)), io_signature::make(1, -1, sizeof(float))), d_FSM(FSM), d_K(K), d_S0(S0),d_SK(SK), d_POSTI(POSTI), d_POSTO(POSTO), d_SISO_TYPE(SISO_TYPE)//, //d_alpha(FSM.S()*(K+1)), //d_beta(FSM.S()*(K+1)) { int multiple; if(d_POSTI && d_POSTO) multiple = d_FSM.I()+d_FSM.O(); else if(d_POSTI) multiple = d_FSM.I(); else if(d_POSTO) multiple = d_FSM.O(); else throw std::runtime_error ("Not both POSTI and POSTO can be false."); //printf("constructor: Multiple = %d\n",multiple); set_output_multiple (d_K*multiple); //what is the meaning of relative rate for a block with 2 inputs? //set_relative_rate ( multiple / ((double) d_FSM.I()) ); // it turns out that the above gives problems in the scheduler, so // let's try (assumption O>I) //set_relative_rate ( multiple / ((double) d_FSM.O()) ); // I am tempted to automate like this if(d_FSM.I() <= d_FSM.O()) set_relative_rate(multiple / ((double) d_FSM.O())); else set_relative_rate(multiple / ((double) d_FSM.I())); } siso_f_impl::~siso_f_impl() { } void siso_f_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int multiple; if(d_POSTI && d_POSTO) multiple = d_FSM.I()+d_FSM.O(); else if(d_POSTI) multiple = d_FSM.I(); else if(d_POSTO) multiple = d_FSM.O(); else throw std::runtime_error ("Not both POSTI and POSTO can be false."); //printf("forecast: Multiple = %d\n",multiple); int input_required1 = d_FSM.I() * (noutput_items/multiple) ; int input_required2 = d_FSM.O() * (noutput_items/multiple) ; //printf("forecast: Output requirements: %d\n",noutput_items); //printf("forecast: Input requirements: %d %d\n",input_required1,input_required2); unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs/2; i++) { ninput_items_required[2*i] = input_required1; ninput_items_required[2*i+1] = input_required2; } } int siso_f_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nstreams = output_items.size(); //printf("general_work:Streams: %d\n",nstreams); int multiple; if(d_POSTI && d_POSTO) multiple = d_FSM.I()+d_FSM.O(); else if(d_POSTI) multiple = d_FSM.I(); else if(d_POSTO) multiple = d_FSM.O(); else throw std::runtime_error("siso_f_impl: Not both POSTI and POSTO can be false.\n"); int nblocks = noutput_items / (d_K*multiple); //printf("general_work:Blocks: %d\n",nblocks); //for(int i=0;i #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSMo, STo0, SToK, FSMi, STi0, STiK, INTERLEAVER, blocklength, repetitions, SISO_TYPE)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE) : block("@BASE_NAME@", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_FSMo(FSMo), d_STo0(STo0), d_SToK(SToK), d_FSMi(FSMi), d_STi0(STi0), d_STiK(STiK), d_INTERLEAVER(INTERLEAVER), d_blocklength(blocklength), d_repetitions(repetitions), d_SISO_TYPE(SISO_TYPE) { set_relative_rate(1.0 / ((double) d_FSMi.O())); set_output_multiple(d_blocklength); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_FSMi.O() * noutput_items ; ninput_items_required[0] = input_required; } //=========================================================== int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nblocks = noutput_items / d_blocklength; float (*p2min)(float, float) = NULL; if(d_SISO_TYPE == TRELLIS_MIN_SUM) p2min = &min; else if(d_SISO_TYPE == TRELLIS_SUM_PRODUCT) p2min = &min_star; const float *in = (const float*)input_items[0]; @O_TYPE@ *out = (@O_TYPE@*)output_items[0]; for(int n = 0; n < nblocks; n++) { sccc_decoder(d_FSMo, d_STo0, d_SToK, d_FSMi, d_STi0, d_STiK, d_INTERLEAVER, d_blocklength, d_repetitions, p2min, &(in[n*d_blocklength*d_FSMi.O()]), &(out[n*d_blocklength])); } consume_each(d_FSMi.O() * noutput_items ); return noutput_items; } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/viterbi_combined_XX_impl.cc.t0000664000175000017500000000605612207440367023707 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSM, int K, int S0, int SK, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE) { return gnuradio::get_initial_sptr (new @NAME@(FSM, K, S0, SK, D, TABLE,TYPE)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSM, int K, int S0, int SK, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE) : block("@BASE_NAME@", io_signature::make(1, -1, sizeof(@I_TYPE@)), io_signature::make(1, -1, sizeof(@O_TYPE@))), d_FSM(FSM), d_K(K), d_S0(S0), d_SK(SK), d_D(D), d_TABLE(TABLE), d_TYPE(TYPE)//, //d_trace(FSM.S()*K) { set_relative_rate(1.0 / ((double)d_D)); set_output_multiple(d_K); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_TABLE(const std::vector<@I_TYPE@> &table) { d_TABLE = table; } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_D * noutput_items; unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) { ninput_items_required[i] = input_required; } } int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nstreams = input_items.size(); int nblocks = noutput_items / d_K; for(int m=0;m #include #include namespace gr { namespace trellis { template void calc_metric(int O, int D, const std::vector &TABLE, const T *input, float *metric, digital::trellis_metric_type_t type) { float minm = FLT_MAX; int minmi = 0; switch(type) { case digital::TRELLIS_EUCLIDEAN: for(int o = 0; o < O; o++) { metric[o] = 0.0; for(int m = 0; m < D; m++) { T s = input[m]-TABLE[o*D+m]; //gr_complex sc(1.0*s,0); //metric[o] += (sc*conj(sc)).real(); metric[o] += s * s; } } break; case digital::TRELLIS_HARD_SYMBOL: for(int o = 0; o < O; o++) { metric[o] = 0.0; for(int m = 0; m < D; m++) { T s = input[m]-TABLE[o*D+m]; //gr_complex sc(1.0*s,0); //metric[o] + =(sc*conj(sc)).real(); metric[o] += s * s; } if(metric[o] < minm) { minm = metric[o]; minmi = o; } } for(int o = 0; o < O; o++) { metric[o] = (o == minmi ? 0.0 : 1.0); } break; case digital::TRELLIS_HARD_BIT: throw std::runtime_error("calc_metric: Invalid metric type (not yet implemented)."); break; default: throw std::runtime_error("calc_metric: Invalid metric type."); } } template void calc_metric(int O, int D, const std::vector &TABLE, const short *input, float *metric, digital::trellis_metric_type_t type); template void calc_metric(int O, int D, const std::vector &TABLE, const int *input, float *metric, digital::trellis_metric_type_t type); template void calc_metric(int O, int D, const std::vector &TABLE, const float *input, float *metric, digital::trellis_metric_type_t type); void calc_metric(int O, int D, const std::vector &TABLE, const short *input, float *metric, digital::trellis_metric_type_t type) { float minm = FLT_MAX; int minmi = 0; switch(type) { case digital::TRELLIS_EUCLIDEAN: for(int o = 0; o < O; o++) { metric[o] = 0.0; for(int m = 0; m < D; m++) { float s = input[m]-TABLE[o*D+m]; metric[o] += s*s; } } break; case digital::TRELLIS_HARD_SYMBOL: for(int o = 0; o < O; o++) { metric[o] = 0.0; for(int m = 0; m < D; m++) { float s = input[m]-TABLE[o*D+m]; metric[o] += s*s; } if(metric[o] < minm) { minm = metric[o]; minmi = o; } } for(int o = 0; o < O; o++) { metric[o] = (o == minmi ? 0.0 : 1.0); } break; case digital::TRELLIS_HARD_BIT: throw std::runtime_error("calc_metric: Invalid metric type (not yet implemented)."); break; default: throw std::runtime_error("calc_metric: Invalid metric type."); } } /* void calc_metric(int O, int D, const std::vector &TABLE, const int *input, float *metric, digital::trellis_metric_type_t type) { float minm = FLT_MAX; int minmi = 0; switch(type){ case digital::TRELLIS_EUCLIDEAN: for(int o=0;o &TABLE, const float *input, float *metric, digital::trellis_metric_type_t type) { float minm = FLT_MAX; int minmi = 0; switch(type) { case digital::TRELLIS_EUCLIDEAN: for(int o=0;o &TABLE, const gr_complex *input, float *metric, digital::trellis_metric_type_t type) { float minm = FLT_MAX; int minmi = 0; switch(type) { case digital::TRELLIS_EUCLIDEAN: for(int o = 0; o < O; o++) { metric[o] = 0.0; for(int m = 0; m < D; m++) { gr_complex s = input[m]-TABLE[o*D+m]; metric[o] += s.real()*s.real()+s.imag()*s.imag(); } } break; case digital::TRELLIS_HARD_SYMBOL: for(int o = 0; o < O; o++) { metric[o] = 0.0; for(int m = 0; m < D; m++) { gr_complex s = input[m]-TABLE[o*D+m]; metric[o] += s.real()*s.real()+s.imag()*s.imag(); } if(metric[o] < minm) { minm = metric[o]; minmi = o; } } for(int o = 0; o < O; o++) { metric[o] = (o == minmi ? 0.0 : 1.0); } break; case digital::TRELLIS_HARD_BIT: throw std::runtime_error("calc_metric: Invalid metric type (not yet implemented)."); break; default: throw std::runtime_error("calc_metric: Invalid metric type."); } } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/base.cc0000664000175000017500000000412612207440367017407 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include namespace gr { namespace trellis { bool dec2base(unsigned int num, int base, std::vector &s) { int l = s.size(); unsigned int n=num; for(int i=0;i &s, int base) { int l = s.size(); unsigned int num=0; for(int i=0;i &bases, std::vector &s) { int l = s.size(); unsigned int n=num; for(int i=0;i &s, const std::vector &bases) { int l = s.size(); unsigned int num=0; for(int i=0;i #include #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; siso_combined_f::sptr siso_combined_f::make(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t SISO_TYPE, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE) { return gnuradio::get_initial_sptr (new siso_combined_f_impl(FSM, K, S0, SK, POSTI, POSTO, SISO_TYPE, D, TABLE, TYPE)); } siso_combined_f_impl::siso_combined_f_impl(const fsm &FSM, int K, int S0, int SK, bool POSTI, bool POSTO, siso_type_t SISO_TYPE, int D, const std::vector &TABLE, digital::trellis_metric_type_t TYPE) : block("siso_combined_f", io_signature::make(1, -1, sizeof(float)), io_signature::make(1, -1, sizeof(float))), d_FSM(FSM), d_K(K), d_S0(S0), d_SK(SK), d_POSTI(POSTI), d_POSTO(POSTO), d_SISO_TYPE(SISO_TYPE), d_D(D), d_TABLE(TABLE), d_TYPE(TYPE)//, //d_alpha(FSM.S()*(K+1)), //d_beta(FSM.S()*(K+1)) { int multiple; if(d_POSTI && d_POSTO) multiple = d_FSM.I()+d_FSM.O(); else if(d_POSTI) multiple = d_FSM.I(); else if(d_POSTO) multiple = d_FSM.O(); else throw std::runtime_error ("Not both POSTI and POSTO can be false."); //printf("constructor: Multiple = %d\n",multiple); set_output_multiple(d_K*multiple); //what is the meaning of relative rate for a block with 2 inputs? //set_relative_rate ( multiple / ((double) d_FSM.I()) ); // it turns out that the above gives problems in the scheduler, so // let's try (assumption O>I) //set_relative_rate ( multiple / ((double) d_FSM.O()) ); // I am tempted to automate like this if(d_FSM.I() <= d_D) set_relative_rate(multiple / ((double)d_D)); else set_relative_rate(multiple / ((double)d_FSM.I())); } siso_combined_f_impl::~siso_combined_f_impl() { } void siso_combined_f_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int multiple; if(d_POSTI && d_POSTO) multiple = d_FSM.I()+d_FSM.O(); else if(d_POSTI) multiple = d_FSM.I(); else if(d_POSTO) multiple = d_FSM.O(); else throw std::runtime_error ("Not both POSTI and POSTO can be false."); //printf("forecast: Multiple = %d\n",multiple); int input_required1 = d_FSM.I() * (noutput_items/multiple) ; int input_required2 = d_D * (noutput_items/multiple) ; //printf("forecast: Output requirements: %d\n",noutput_items); //printf("forecast: Input requirements: %d %d\n",input_required1,input_required2); unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs/2; i++) { ninput_items_required[2*i] = input_required1; ninput_items_required[2*i+1] = input_required2; } } int siso_combined_f_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nstreams = output_items.size(); //printf("general_work:Streams: %d\n",nstreams); int multiple; if(d_POSTI && d_POSTO) multiple = d_FSM.I()+d_FSM.O(); else if(d_POSTI) multiple = d_FSM.I(); else if(d_POSTO) multiple = d_FSM.O(); else throw std::runtime_error("siso_combined_f_impl:: Not both POSTI and POSTO can be false."); int nblocks = noutput_items / (d_K*multiple); //printf("general_work:Blocks: %d\n",nblocks); //for(int i=0;i namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSM; int d_K; int d_S0; int d_SK; //std::vector d_trace; public: @IMPL_NAME@(const fsm &FSM, int K, int S0, int SK); ~@IMPL_NAME@(); fsm FSM() const { return d_FSM; } int K() const { return d_K; } int S0() const { return d_S0; } int SK() const { return d_SK; } //std::vector trace () const { return d_trace; } void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/sccc_decoder_combined_XX_impl.cc.t0000664000175000017500000000763612207440367024650 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include #include namespace gr { namespace trellis { static const float INF = 1.0e9; @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSMo, STo0, SToK, FSMi, STi0, STiK, INTERLEAVER, blocklength, repetitions, SISO_TYPE, D, TABLE,METRIC_TYPE, scaling)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling) : block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_FSMo(FSMo), d_STo0(STo0), d_SToK(SToK), d_FSMi(FSMi), d_STi0(STi0), d_STiK(STiK), d_INTERLEAVER(INTERLEAVER), d_blocklength(blocklength), d_repetitions(repetitions), d_SISO_TYPE(SISO_TYPE), d_D(D), d_TABLE(TABLE), d_METRIC_TYPE(METRIC_TYPE), d_scaling(scaling) { set_relative_rate(1.0 / ((double) d_D)); set_output_multiple(d_blocklength); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_scaling(float scaling) { d_scaling = scaling; } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_D * noutput_items ; ninput_items_required[0] = input_required; } //=========================================================== int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nblocks = noutput_items / d_blocklength; float (*p2min)(float, float) = NULL; if(d_SISO_TYPE == TRELLIS_MIN_SUM) p2min = &min; else if(d_SISO_TYPE == TRELLIS_SUM_PRODUCT) p2min = &min_star; const @I_TYPE@ *in = (const @I_TYPE@*)input_items[0]; @O_TYPE@ *out = (@O_TYPE@*)output_items[0]; for(int n = 0; n < nblocks; n++) { sccc_decoder_combined(d_FSMo, d_STo0, d_SToK, d_FSMi, d_STi0, d_STiK, d_INTERLEAVER, d_blocklength, d_repetitions, p2min, d_D,d_TABLE, d_METRIC_TYPE, d_scaling, &(in[n*d_blocklength*d_D]), &(out[n*d_blocklength])); } consume_each(d_D * noutput_items); return noutput_items; } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/pccc_encoder_XX_impl.cc.t0000664000175000017500000000521412207440367023005 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include namespace gr { namespace trellis { @BASE_NAME@::sptr @BASE_NAME@::make(const fsm &FSM1, int ST1, const fsm &FSM2, int ST2, const interleaver &INTERLEAVER, int blocklength) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(FSM1, ST1, FSM2, ST2, INTERLEAVER, blocklength)); } @IMPL_NAME@::@IMPL_NAME@(const fsm &FSM1, int ST1, const fsm &FSM2, int ST2, const interleaver &INTERLEAVER, int blocklength) : sync_block("@BASE_NAME@", io_signature::make(1, 1, sizeof(@I_TYPE@)), io_signature::make(1, 1, sizeof(@O_TYPE@))), d_FSM1(FSM1), d_ST1(ST1), d_FSM2(FSM2), d_ST2(ST2), d_INTERLEAVER(INTERLEAVER), d_blocklength(blocklength) { assert(d_FSM1.I() == d_FSM2.I()); set_output_multiple(d_blocklength); d_buffer.resize(d_blocklength); } @IMPL_NAME@::~@IMPL_NAME@() { } int @NAME@::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { for(int b = 0 ; b namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSM1; int d_ST10; int d_ST1K; fsm d_FSM2; int d_ST20; int d_ST2K; interleaver d_INTERLEAVER; int d_blocklength; int d_repetitions; siso_type_t d_SISO_TYPE; std::vector d_buffer; public: @IMPL_NAME@(const fsm &FSM1, int ST10, int ST1K, const fsm &FSM2, int ST20, int ST2K, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE); ~@IMPL_NAME@(); fsm FSM1() const { return d_FSM1; } fsm FSM2() const { return d_FSM2; } int ST10() const { return d_ST10; } int ST1K() const { return d_ST1K; } int ST20() const { return d_ST20; } int ST2K() const { return d_ST2K; } interleaver INTERLEAVER() const { return d_INTERLEAVER; } int blocklength() const { return d_blocklength; } int repetitions() const { return d_repetitions; } siso_type_t SISO_TYPE() const { return d_SISO_TYPE; } void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/constellation_metrics_cf_impl.h0000664000175000017500000000351612207440367024436 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010-2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_TRELLIS_CONSTELLATION_METRICS_CF_IMPL_H #define INCLUDED_TRELLIS_CONSTELLATION_METRICS_CF_IMPL_H #include #include namespace gr { namespace trellis { class constellation_metrics_cf_impl : public constellation_metrics_cf { private: digital::constellation_sptr d_constellation; digital::trellis_metric_type_t d_TYPE; unsigned int d_O; unsigned int d_D; public: constellation_metrics_cf_impl(digital::constellation_sptr constellation, digital::trellis_metric_type_t TYPE); ~constellation_metrics_cf_impl(); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* INCLUDED_TRELLIS_CONSTELLATION_METRICS_CF_IMPL_H */ gnuradio-3.7.2.1/gr-trellis/lib/interleaver.cc0000664000175000017500000001037712207440367021022 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include namespace gr { namespace trellis { interleaver::interleaver() { d_K=0; d_INTER.resize(0); d_DEINTER.resize(0); } interleaver::interleaver(const interleaver &INTERLEAVER) { d_K=INTERLEAVER.K(); d_INTER=INTERLEAVER.INTER(); d_DEINTER=INTERLEAVER.DEINTER(); } interleaver::interleaver(int K, const std::vector &INTER) { d_K=K; d_INTER=INTER; d_DEINTER.resize(d_K); // generate DEINTER table for(int i=0;i=0) srand((unsigned int)seed); std::vector tmp(d_K); for(int i=0;i (tmp,d_INTER,0,d_K-1); // generate DEINTER table for(int i=0;i #include #include #include namespace gr { namespace trellis { constellation_metrics_cf::sptr constellation_metrics_cf::make(digital::constellation_sptr constellation, digital::trellis_metric_type_t TYPE) { return gnuradio::get_initial_sptr (new constellation_metrics_cf_impl(constellation, TYPE)); } constellation_metrics_cf_impl::constellation_metrics_cf_impl(digital::constellation_sptr constellation, digital::trellis_metric_type_t TYPE) : block("constellation_metrics_cf", io_signature::make(1, -1, sizeof(gr_complex)), io_signature::make(1, -1, sizeof(float))), d_constellation(constellation), d_TYPE(TYPE), d_O(constellation->arity()), d_D(constellation->dimensionality()) { set_relative_rate(1.0 * d_O / ((double) d_D)); set_output_multiple((int)d_O); } constellation_metrics_cf_impl::~constellation_metrics_cf_impl() { } void constellation_metrics_cf_impl::forecast(int noutput_items, gr_vector_int &ninput_items_required) { assert(noutput_items % d_O == 0); unsigned int input_required = d_D * noutput_items / d_O; unsigned int ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) ninput_items_required[i] = input_required; } int constellation_metrics_cf_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned int nstreams = input_items.size(); for(unsigned int m=0;mcalc_metric(&(in[i*d_D]), &(out[i*d_O]), d_TYPE); } } consume_each(d_D * noutput_items / d_O); return noutput_items; } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/sccc_decoder_combined_XX_impl.h.t0000664000175000017500000000546512207440367024510 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSMo; int d_STo0; int d_SToK; fsm d_FSMi; int d_STi0; int d_STiK; interleaver d_INTERLEAVER; int d_blocklength; int d_repetitions; siso_type_t d_SISO_TYPE; int d_D; std::vector<@I_TYPE@> d_TABLE; digital::trellis_metric_type_t d_METRIC_TYPE; float d_scaling; std::vector d_buffer; public: @IMPL_NAME@(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t METRIC_TYPE, float scaling); ~@IMPL_NAME@(); fsm FSMo() const { return d_FSMo; } fsm FSMi() const { return d_FSMi; } int STo0() const { return d_STo0; } int SToK() const { return d_SToK; } int STi0() const { return d_STi0; } int STiK() const { return d_STiK; } interleaver INTERLEAVER() const { return d_INTERLEAVER; } int blocklength() const { return d_blocklength; } int repetitions() const { return d_repetitions; } int D() const { return d_D; } std::vector<@I_TYPE@> TABLE() const { return d_TABLE; } digital::trellis_metric_type_t METRIC_TYPE() const { return d_METRIC_TYPE; } siso_type_t SISO_TYPE() const { return d_SISO_TYPE; } float scaling() const { return d_scaling; } void set_scaling(float scaling); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/metrics_X_impl.cc.t0000664000175000017500000000533612207440367021721 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "@NAME@.h" #include #include #include #include namespace gr { namespace trellis { @BASE_NAME@::sptr @BASE_NAME@::make(int O, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE) { return gnuradio::get_initial_sptr (new @IMPL_NAME@(O,D,TABLE,TYPE)); } @IMPL_NAME@::@IMPL_NAME@(int O, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE) : block("@BASE_NAME@", io_signature::make(1, -1, sizeof (@I_TYPE@)), io_signature::make(1, -1, sizeof (float))), d_O(O), d_D(D), d_TYPE(TYPE), d_TABLE(TABLE) { set_relative_rate (1.0 * d_O / ((double) d_D)); set_output_multiple ((int)d_O); } @IMPL_NAME@::~@IMPL_NAME@() { } void @IMPL_NAME@::set_TABLE(const std::vector<@I_TYPE@> &table) { d_TABLE = table; } void @IMPL_NAME@::forecast(int noutput_items, gr_vector_int &ninput_items_required) { int input_required = d_D * noutput_items / d_O; unsigned ninputs = ninput_items_required.size(); for(unsigned int i = 0; i < ninputs; i++) ninput_items_required[i] = input_required; } int @IMPL_NAME@::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int nstreams = input_items.size(); for(int m = 0; m < nstreams; m++) { const @I_TYPE@ *in = (@I_TYPE@*)input_items[m]; float *out = (float*)output_items[m]; for(int i = 0; i < noutput_items / d_O ; i++) { calc_metric(d_O, d_D, d_TABLE,&(in[i*d_D]), &(out[i*d_O]), d_TYPE); } } consume_each(d_D * noutput_items / d_O); return noutput_items; } } /* namespace trellis */ } /* namespace gr */ gnuradio-3.7.2.1/gr-trellis/lib/sccc_decoder_X_impl.h.t0000664000175000017500000000446212207440367022514 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // @WARNING@ #ifndef @GUARD_NAME@ #define @GUARD_NAME@ #include namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: fsm d_FSMo; int d_STo0; int d_SToK; fsm d_FSMi; int d_STi0; int d_STiK; interleaver d_INTERLEAVER; int d_blocklength; int d_repetitions; siso_type_t d_SISO_TYPE; std::vector d_buffer; public: @IMPL_NAME@(const fsm &FSMo, int STo0, int SToK, const fsm &FSMi, int STi0, int STiK, const interleaver &INTERLEAVER, int blocklength, int repetitions, siso_type_t SISO_TYPE); ~@IMPL_NAME@(); fsm FSMo() const { return d_FSMo; } fsm FSMi() const { return d_FSMi; } int STo0() const { return d_STo0; } int SToK() const { return d_SToK; } int STi0() const { return d_STi0; } int STiK() const { return d_STiK; } interleaver INTERLEAVER() const { return d_INTERLEAVER; } int blocklength() const { return d_blocklength; } int repetitions() const { return d_repetitions; } siso_type_t SISO_TYPE() const { return d_SISO_TYPE; } void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/lib/gnuradio-trellis.rc.in0000664000175000017500000000333212207440367022403 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-trellis" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-trellis.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-trellis.dll" VALUE "ProductName", "gnuradio-trellis" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-trellis/lib/fsm.cc0000664000175000017500000003764012207440367017271 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2002,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include namespace gr { namespace trellis { fsm::fsm() { d_I=0; d_S=0; d_O=0; d_NS.resize(0); d_OS.resize(0); d_PS.resize(0); d_PI.resize(0); d_TMi.resize(0); d_TMl.resize(0); } fsm::fsm(const fsm &FSM) { d_I=FSM.I(); d_S=FSM.S(); d_O=FSM.O(); d_NS=FSM.NS(); d_OS=FSM.OS(); d_PS=FSM.PS(); // is this going to make a deep copy? d_PI=FSM.PI(); d_TMi=FSM.TMi(); d_TMl=FSM.TMl(); } fsm::fsm(int I, int S, int O, const std::vector &NS, const std::vector &OS) { d_I=I; d_S=S; d_O=O; d_NS=NS; d_OS=OS; generate_PS_PI(); generate_TM(); } //###################################################################### //# Read an FSM specification from a file. //# Format (hopefully will become more flexible in the future...): //# I S O (in the first line) //# blank line //# Next state matrix (S lines, each with I integers separated by spaces) //# blank line //# output symbol matrix (S lines, each with I integers separated by spaces) //# optional comments //###################################################################### fsm::fsm(const char *name) { FILE *fsmfile; if((fsmfile=fopen(name,"r"))==NULL) throw std::runtime_error ("fsm::fsm(const char *name): file open error\n"); //printf("file open error in fsm()\n"); if(fscanf(fsmfile,"%d %d %d\n",&d_I,&d_S,&d_O) == EOF) { if(ferror(fsmfile) != 0) throw std::runtime_error ("fsm::fsm(const char *name): file read error\n"); } d_NS.resize(d_I*d_S); d_OS.resize(d_I*d_S); for(int i=0;i &G) { // calculate maximum memory requirements for each input stream std::vector max_mem_x(k,-1); int max_mem = -1; for(int i=0;imax_mem_x[i]) max_mem_x[i]=mem; if(mem>max_mem) max_mem=mem; } } //printf("max_mem_x\n"); //for(int j=0;j > Gb(k*n); for(int j=0;j bases_x(k); for(int j=0;j sx(k); std::vector nsx(k); std::vector tx(k); std::vector > tb(k); for(int j=0;j inb(k); std::vector outb(n); for(int s=0;s ii(n); dec2base(i,FSM.I(),ii); std::vector oo(n); int ns=s; for(int k=0;k 1) { //throw std::runtime_error ("fsm::generate_TM(): FSM appears to be disconnected\n"); printf("fsm::generate_TM(): FSM appears to be disconnected\n"); printf("state %d cannot be reached from all other states\n",s); } } } // find a path from any state to the ending state "es" bool fsm::find_es(int es) { bool done = true; for(int s=0;s" << std::endl; for(int stage_num = 0;stage_num < number_stages;stage_num ++) { // draw states for(int state_num = 0;state_num < d_S ; state_num ++ ) { trellis_fname << "" << std::endl; //draw branches if(stage_num != number_stages-1) { for(int branch_num = 0;branch_num < d_I; branch_num++) { trellis_fname << "" << std::endl; } } } } // label the stages trellis_fname << "" << std::endl; for(int stage_num = 0;stage_num < number_stages ;stage_num ++) { trellis_fname << "" << std::endl; trellis_fname << stage_num << std::endl; trellis_fname << "" << std::endl; } trellis_fname << "" << std::endl; // label the states trellis_fname << "" << std::endl; for(int state_num = 0;state_num < d_S ; state_num ++) { trellis_fname << "" << std::endl; trellis_fname << state_num << std::endl; trellis_fname << "" << std::endl; } trellis_fname << "" << std::endl; trellis_fname << "" << std::endl; // std::cout << "################## END SVG TRELLIS PIC ##################### " << std::endl; trellis_fname.close(); } //###################################################################### //# Write trellis specification to a text file, //# in the same format used when reading FSM files //###################################################################### void fsm::write_fsm_txt(std::string filename) { std::ofstream trellis_fname (filename.c_str()); if(!trellis_fname) { std::cout << "file not found " << std::endl ; exit(-1); } trellis_fname << d_I << ' ' << d_S << ' ' << d_O << std::endl; trellis_fname << std::endl; for(int i=0;i namespace gr { namespace trellis { class @IMPL_NAME@ : public @BASE_NAME@ { private: int d_O; int d_D; digital::trellis_metric_type_t d_TYPE; std::vector<@I_TYPE@> d_TABLE; public: @IMPL_NAME@(int O, int D, const std::vector<@I_TYPE@> &TABLE, digital::trellis_metric_type_t TYPE); ~@IMPL_NAME@(); int O() const { return d_O; } int D() const { return d_D; } digital::trellis_metric_type_t TYPE() const { return d_TYPE; } std::vector<@I_TYPE@> TABLE() const { return d_TABLE; } void set_TABLE(const std::vector<@I_TYPE@> &table); void forecast(int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace trellis */ } /* namespace gr */ #endif /* @GUARD_NAME@ */ gnuradio-3.7.2.1/gr-trellis/gnuradio-trellis.pc.in0000664000175000017500000000041712207440367021634 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-trellis Description: GNU Radio blocks for trellis coded modulation Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-trellis Cflags: -I${includedir} gnuradio-3.7.2.1/gr-trellis/swig/0000775000175000017500000000000012207440367016366 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/swig/CMakeLists.txt0000664000175000017500000000403512207440367021130 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_TRELLIS_INCLUDE_DIRS} ${GR_DIGITAL_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) set(GR_SWIG_LIBRARIES gnuradio-trellis gnuradio-digital) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) # Setup swig docs to depend on includes and pull in from build directory set(GR_SWIG_TARGET_DEPS trellis_generated_includes) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/trellis_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/trellis ${CMAKE_CURRENT_BINARY_DIR}/../include/gnuradio/trellis ) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) GR_SWIG_MAKE(trellis_swig trellis_swig.i) GR_SWIG_INSTALL( TARGETS trellis_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/trellis COMPONENT "trellis_python" ) install( FILES trellis_swig.i ${CMAKE_CURRENT_BINARY_DIR}/trellis_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "trellis_swig" ) gnuradio-3.7.2.1/gr-trellis/swig/trellis_swig.i0000664000175000017500000002263712207440367021261 0ustar jcorganjcorgan/* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define TRELLIS_API #define DIGITAL_API %include "gnuradio.i" //load generated python docstrings %include "trellis_swig_doc.i" %include "gnuradio/digital/metric_type.h" %include "gnuradio/digital/constellation.h" %include "gnuradio/trellis/siso_type.h" %include "gnuradio/trellis/fsm.h" %include "gnuradio/trellis/interleaver.h" %{ #include "gnuradio/trellis/constellation_metrics_cf.h" #include "gnuradio/trellis/permutation.h" #include "gnuradio/trellis/siso_combined_f.h" #include "gnuradio/trellis/siso_f.h" #include "gnuradio/trellis/encoder_bb.h" #include "gnuradio/trellis/encoder_bs.h" #include "gnuradio/trellis/encoder_bi.h" #include "gnuradio/trellis/encoder_ss.h" #include "gnuradio/trellis/encoder_si.h" #include "gnuradio/trellis/encoder_ii.h" #include "gnuradio/trellis/sccc_encoder_bb.h" #include "gnuradio/trellis/sccc_encoder_bs.h" #include "gnuradio/trellis/sccc_encoder_bi.h" #include "gnuradio/trellis/sccc_encoder_ss.h" #include "gnuradio/trellis/sccc_encoder_si.h" #include "gnuradio/trellis/sccc_encoder_ii.h" #include "gnuradio/trellis/pccc_encoder_bb.h" #include "gnuradio/trellis/pccc_encoder_bs.h" #include "gnuradio/trellis/pccc_encoder_bi.h" #include "gnuradio/trellis/pccc_encoder_ss.h" #include "gnuradio/trellis/pccc_encoder_si.h" #include "gnuradio/trellis/pccc_encoder_ii.h" #include "gnuradio/trellis/metrics_s.h" #include "gnuradio/trellis/metrics_i.h" #include "gnuradio/trellis/metrics_f.h" #include "gnuradio/trellis/metrics_c.h" #include "gnuradio/trellis/pccc_decoder_b.h" #include "gnuradio/trellis/pccc_decoder_s.h" #include "gnuradio/trellis/pccc_decoder_i.h" #include "gnuradio/trellis/pccc_decoder_combined_fb.h" #include "gnuradio/trellis/pccc_decoder_combined_fs.h" #include "gnuradio/trellis/pccc_decoder_combined_fi.h" #include "gnuradio/trellis/pccc_decoder_combined_cb.h" #include "gnuradio/trellis/pccc_decoder_combined_cs.h" #include "gnuradio/trellis/pccc_decoder_combined_ci.h" #include "gnuradio/trellis/viterbi_b.h" #include "gnuradio/trellis/viterbi_s.h" #include "gnuradio/trellis/viterbi_i.h" #include "gnuradio/trellis/viterbi_combined_sb.h" #include "gnuradio/trellis/viterbi_combined_ss.h" #include "gnuradio/trellis/viterbi_combined_si.h" #include "gnuradio/trellis/viterbi_combined_ib.h" #include "gnuradio/trellis/viterbi_combined_is.h" #include "gnuradio/trellis/viterbi_combined_ii.h" #include "gnuradio/trellis/viterbi_combined_fb.h" #include "gnuradio/trellis/viterbi_combined_fs.h" #include "gnuradio/trellis/viterbi_combined_fi.h" #include "gnuradio/trellis/viterbi_combined_cb.h" #include "gnuradio/trellis/viterbi_combined_cs.h" #include "gnuradio/trellis/viterbi_combined_ci.h" #include "gnuradio/trellis/sccc_decoder_b.h" #include "gnuradio/trellis/sccc_decoder_s.h" #include "gnuradio/trellis/sccc_decoder_i.h" #include "gnuradio/trellis/sccc_decoder_combined_fb.h" #include "gnuradio/trellis/sccc_decoder_combined_fs.h" #include "gnuradio/trellis/sccc_decoder_combined_fi.h" #include "gnuradio/trellis/sccc_decoder_combined_cb.h" #include "gnuradio/trellis/sccc_decoder_combined_cs.h" #include "gnuradio/trellis/sccc_decoder_combined_ci.h" %} %include "gnuradio/trellis/constellation_metrics_cf.h" %include "gnuradio/trellis/permutation.h" %include "gnuradio/trellis/siso_combined_f.h" %include "gnuradio/trellis/siso_f.h" %include "gnuradio/trellis/encoder_bb.h" %include "gnuradio/trellis/encoder_bs.h" %include "gnuradio/trellis/encoder_bi.h" %include "gnuradio/trellis/encoder_ss.h" %include "gnuradio/trellis/encoder_si.h" %include "gnuradio/trellis/encoder_ii.h" %include "gnuradio/trellis/sccc_encoder_bb.h" %include "gnuradio/trellis/sccc_encoder_bs.h" %include "gnuradio/trellis/sccc_encoder_bi.h" %include "gnuradio/trellis/sccc_encoder_ss.h" %include "gnuradio/trellis/sccc_encoder_si.h" %include "gnuradio/trellis/sccc_encoder_ii.h" %include "gnuradio/trellis/pccc_encoder_bb.h" %include "gnuradio/trellis/pccc_encoder_bs.h" %include "gnuradio/trellis/pccc_encoder_bi.h" %include "gnuradio/trellis/pccc_encoder_ss.h" %include "gnuradio/trellis/pccc_encoder_si.h" %include "gnuradio/trellis/pccc_encoder_ii.h" %include "gnuradio/trellis/metrics_s.h" %include "gnuradio/trellis/metrics_i.h" %include "gnuradio/trellis/metrics_f.h" %include "gnuradio/trellis/metrics_c.h" %include "gnuradio/trellis/pccc_decoder_b.h" %include "gnuradio/trellis/pccc_decoder_s.h" %include "gnuradio/trellis/pccc_decoder_i.h" %include "gnuradio/trellis/pccc_decoder_combined_fb.h" %include "gnuradio/trellis/pccc_decoder_combined_fs.h" %include "gnuradio/trellis/pccc_decoder_combined_fi.h" %include "gnuradio/trellis/pccc_decoder_combined_cb.h" %include "gnuradio/trellis/pccc_decoder_combined_cs.h" %include "gnuradio/trellis/pccc_decoder_combined_ci.h" %include "gnuradio/trellis/viterbi_b.h" %include "gnuradio/trellis/viterbi_s.h" %include "gnuradio/trellis/viterbi_i.h" %include "gnuradio/trellis/viterbi_combined_sb.h" %include "gnuradio/trellis/viterbi_combined_ss.h" %include "gnuradio/trellis/viterbi_combined_si.h" %include "gnuradio/trellis/viterbi_combined_ib.h" %include "gnuradio/trellis/viterbi_combined_is.h" %include "gnuradio/trellis/viterbi_combined_ii.h" %include "gnuradio/trellis/viterbi_combined_fb.h" %include "gnuradio/trellis/viterbi_combined_fs.h" %include "gnuradio/trellis/viterbi_combined_fi.h" %include "gnuradio/trellis/viterbi_combined_cb.h" %include "gnuradio/trellis/viterbi_combined_cs.h" %include "gnuradio/trellis/viterbi_combined_ci.h" %include "gnuradio/trellis/sccc_decoder_b.h" %include "gnuradio/trellis/sccc_decoder_s.h" %include "gnuradio/trellis/sccc_decoder_i.h" %include "gnuradio/trellis/sccc_decoder_combined_fb.h" %include "gnuradio/trellis/sccc_decoder_combined_fs.h" %include "gnuradio/trellis/sccc_decoder_combined_fi.h" %include "gnuradio/trellis/sccc_decoder_combined_cb.h" %include "gnuradio/trellis/sccc_decoder_combined_cs.h" %include "gnuradio/trellis/sccc_decoder_combined_ci.h" GR_SWIG_BLOCK_MAGIC2(trellis, constellation_metrics_cf); GR_SWIG_BLOCK_MAGIC2(trellis, permutation); GR_SWIG_BLOCK_MAGIC2(trellis, siso_combined_f); GR_SWIG_BLOCK_MAGIC2(trellis, siso_f); GR_SWIG_BLOCK_MAGIC2(trellis, encoder_bb); GR_SWIG_BLOCK_MAGIC2(trellis, encoder_bs); GR_SWIG_BLOCK_MAGIC2(trellis, encoder_bi); GR_SWIG_BLOCK_MAGIC2(trellis, encoder_ss); GR_SWIG_BLOCK_MAGIC2(trellis, encoder_si); GR_SWIG_BLOCK_MAGIC2(trellis, encoder_ii); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_encoder_bb); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_encoder_bs); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_encoder_bi); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_encoder_ss); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_encoder_si); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_encoder_ii); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_encoder_bb); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_encoder_bs); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_encoder_bi); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_encoder_ss); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_encoder_si); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_encoder_ii); GR_SWIG_BLOCK_MAGIC2(trellis, metrics_s); GR_SWIG_BLOCK_MAGIC2(trellis, metrics_i); GR_SWIG_BLOCK_MAGIC2(trellis, metrics_f); GR_SWIG_BLOCK_MAGIC2(trellis, metrics_c); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_b); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_s); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_i); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_combined_fb); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_combined_fs); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_combined_fi); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_combined_cb); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_combined_cs); GR_SWIG_BLOCK_MAGIC2(trellis, pccc_decoder_combined_ci); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_b); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_s); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_i); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_sb); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_ss); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_si); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_ib); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_is); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_ii); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_fb); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_fs); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_fi); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_cb); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_cs); GR_SWIG_BLOCK_MAGIC2(trellis, viterbi_combined_ci); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_b); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_s); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_i); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_combined_fb); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_combined_fs); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_combined_fi); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_combined_cb); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_combined_cs); GR_SWIG_BLOCK_MAGIC2(trellis, sccc_decoder_combined_ci); gnuradio-3.7.2.1/gr-trellis/README0000644000175000017500000000204611744612271016275 0ustar jcorganjcorgan# # Copyright 2005,2006 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # The doc directory is not built by default. This is to avoid spurious build problems on systems that don't have xmlto installed. If you have xmlto and its dependencies installed, you can build the html version of the gr-trellis article by cd'ing to doc and invoking make. gnuradio-3.7.2.1/gr-trellis/examples/0000775000175000017500000000000012207440367017233 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/examples/grc/0000775000175000017500000000000012207440367020006 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/examples/grc/CMakeLists.txt0000664000175000017500000000172712207440367022555 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES interference_cancellation.grc pccc1.grc pccc.grc sccc1.grc sccc.grc readme.txt DESTINATION ${GR_PKG_TRELLIS_EXAMPLES_DIR} COMPONENT "trellis-examples" ) gnuradio-3.7.2.1/gr-trellis/examples/grc/sccc.grc0000664000175000017500000004323312207440367021423 0ustar jcorganjcorgan Sat Nov 10 15:34:26 2012 options id sccc _enabled True title Serially Concatenated Convolutional Code author AA description gnuradio flow graph window_size 2048, 2048 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id noisevar _enabled True value 10**(-snr_db/10) _coordinate (389, 15) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type short min 0 max 2 num_samps 1000 repeat True _coordinate (21, 170) _rotation 0 variable id prefix _enabled True value "/n/harrisville/x/anastas/gnuradio_trunk/" _coordinate (590, 15) _rotation 0 variable id block _enabled True value 1000 _coordinate (764, 16) _rotation 0 blocks_sub_xx id blocks_sub_xx_0 _enabled True type short vlen 1 num_inputs 2 _coordinate (445, 517) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_2_0 _enabled True type short num_inputs 2 vlen 1 _coordinate (228.25, 798.39170361874085) _rotation 0 blocks_short_to_float id blocks_short_to_float_1_0 _enabled True vlen 1 scale 1 _coordinate (416, 815) _rotation 0 variable_slider id snr_db _enabled True label SNR (dB) value 5 min -10 max 10 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (229, 13) _rotation 0 variable id R _enabled True value 10e3 _coordinate (482, 17) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type complex title Scope Plot samp_rate R v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode True num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (952, 73) _rotation 0 trellis_sccc_encoder_xx id trellis_sccc_encoder_xx_0 _enabled True type ss o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn2o3_4.fsm" i_init_state 0 interleaver_args trellis.interleaver(block,666) bl block _coordinate (242, 154) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_3_0 _enabled True type float title BER units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 1,0,1,1 notebook _coordinate (688, 572) _rotation 0 trellis_sccc_decoder_combined_xx id trellis_sccc_decoder_combined_xx_0 _enabled True type c out_type s o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 o_final_state -1 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn2o3_4.fsm" i_init_state 0 i_final_state -1 interleaver trellis.interleaver(block,666) block_size block iterations 5 dim 2 table 1,0,1j,0,-1j,0,-1,0, 0,1,0,1j,0,-1j,0,-1 metric_type digital.TRELLIS_EUCLIDEAN siso_type trellis.TRELLIS_SUM_PRODUCT scaling 1.0 _coordinate (159, 335) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type short samples_per_second R vlen 1 _coordinate (514, 105) _rotation 0 blocks_add_xx id blocks_add_xx_1 _enabled True type complex num_inputs 2 vlen 1 _coordinate (951, 256) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0 _enabled True in_type short out_type complex symbol_table 1,0,1j,0,-1j,0,-1,0,0,1,0,1j,0,-1j,0,01 dimension 2 num_ports 1 _coordinate (551, 181) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type complex noise_type analog.GR_GAUSSIAN amp noisevar seed -42 _coordinate (651, 270) _rotation 0 analog_random_source_x_0 blocks_sub_xx_0 0 0 blocks_add_xx_1 wxgui_scopesink2_0 0 0 analog_random_source_x_0 trellis_sccc_encoder_xx_0 0 0 trellis_sccc_encoder_xx_0 blocks_throttle_0 0 0 blocks_add_xx_1 trellis_sccc_decoder_combined_xx_0 0 0 trellis_sccc_decoder_combined_xx_0 blocks_sub_xx_0 0 1 blocks_multiply_xx_2_0 blocks_short_to_float_1_0 0 0 blocks_short_to_float_1_0 wxgui_numbersink2_3_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 1 blocks_throttle_0 digital_chunks_to_symbols_xx_0 0 0 analog_noise_source_x_0 blocks_add_xx_1 0 1 digital_chunks_to_symbols_xx_0 blocks_add_xx_1 0 0 gnuradio-3.7.2.1/gr-trellis/examples/grc/pccc.grc0000664000175000017500000004331512207440367021421 0ustar jcorganjcorgan Thu Dec 27 13:49:53 2012 options id sccc1 _enabled True title Serially Concatenated Convolutional Code author AA description gnuradio flow graph window_size 2048, 2048 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id noisevar _enabled True value 10**(-snr_db/10) _coordinate (389, 15) _rotation 0 variable id prefix _enabled True value "/n/harrisville/x/anastas/gnuradio_trunk/" _coordinate (590, 15) _rotation 0 variable id block _enabled True value 1000 _coordinate (764, 16) _rotation 0 variable_slider id snr_db _enabled True label SNR (dB) value 5 min -10 max 10 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (229, 13) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_2_0 _enabled True type short num_inputs 2 vlen 1 _coordinate (392, 591) _rotation 0 blocks_short_to_float id blocks_short_to_float_1_0 _enabled True vlen 1 scale 1 _coordinate (535, 609) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_3_0 _enabled True type float title BER units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 1,0,1,1 notebook _coordinate (713, 426) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type float title Scope Plot samp_rate R v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (952, 73) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type short min 0 max 2 num_samps 1000 repeat True _coordinate (21, 170) _rotation 0 trellis_pccc_encoder_xx id trellis_pccc_encoder_xx_0 _enabled True type ss o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" i_init_state 0 interleaver_args trellis.interleaver(block,666) bl block _coordinate (236, 147) _rotation 0 variable id R _enabled True value 100e3 _coordinate (482, 17) _rotation 0 trellis_pccc_decoder_combined_xx id trellis_pccc_decoder_combined_xx_0 _enabled True type f out_type s o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 o_final_state -1 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" i_init_state 0 i_final_state -1 interleaver trellis.interleaver(block,666) block_size block iterations 10 dim 2 table -7,0, -5,0, -3,0, -1,0, 1,0, 3,0, 5,0, 7,0, 0,-7,0, -5,0, -3,0, -1,0, 1,0, 3,0, 5,0, 7 metric_type digital.TRELLIS_EUCLIDEAN siso_type trellis.TRELLIS_MIN_SUM scaling 1.0 _coordinate (196, 274) _rotation 0 blocks_sub_xx id blocks_sub_xx_0 _enabled True type short vlen 1 num_inputs 2 _coordinate (217, 597) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type float noise_type analog.GR_GAUSSIAN amp noisevar seed -42 _coordinate (584, 259) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type short samples_per_second R vlen 1 _coordinate (517, 103) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0 _enabled True in_type short out_type float symbol_table -7,0,-5,0,-3,0,-1,0,1,0,3,0,5,0,7,0,-7,0,-5,0,-3,0,-1,0,1,0,3,0,5,0,7 dimension 2 num_ports 1 _coordinate (559, 180) _rotation 0 blocks_add_xx id blocks_add_xx_1 _enabled True type float num_inputs 2 vlen 1 _coordinate (951, 256) _rotation 0 analog_random_source_x_0 blocks_sub_xx_0 0 0 blocks_add_xx_1 wxgui_scopesink2_0 0 0 blocks_multiply_xx_2_0 blocks_short_to_float_1_0 0 0 blocks_short_to_float_1_0 wxgui_numbersink2_3_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 1 analog_random_source_x_0 trellis_pccc_encoder_xx_0 0 0 trellis_pccc_encoder_xx_0 blocks_throttle_0 0 0 blocks_add_xx_1 trellis_pccc_decoder_combined_xx_0 0 0 trellis_pccc_decoder_combined_xx_0 blocks_sub_xx_0 0 1 analog_noise_source_x_0 blocks_add_xx_1 0 1 blocks_throttle_0 digital_chunks_to_symbols_xx_0 0 0 digital_chunks_to_symbols_xx_0 blocks_add_xx_1 0 0 gnuradio-3.7.2.1/gr-trellis/examples/grc/interference_cancellation.grc0000664000175000017500000013673112207440367025703 0ustar jcorganjcorgan Sat Nov 10 15:39:57 2012 options id int_cancellation _enabled True title Superposition Coding author AA description gnuradio flow graph window_size 2048, 2048 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable_slider id alpha _enabled True label P1/P value 0.6 min 0 max 1.0 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (243, 11) _rotation 0 variable_slider id snr_db _enabled True label P/sigma^2 (dB) value 16 min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (447, 14) _rotation 0 variable id noisevar _enabled True value 10**(-snr_db/10) _coordinate (637, 13) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type short min 0 max 2 num_samps 1000 repeat True _coordinate (21, 170) _rotation 0 analog_random_source_x id analog_random_source_x_1 _enabled True type short min 0 max 2 num_samps 1000 repeat True _coordinate (25, 291) _rotation 0 blocks_sub_xx id blocks_sub_xx_0 _enabled True type short vlen 1 num_inputs 2 _coordinate (536, 529) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_0 _enabled True type short num_inputs 2 vlen 1 _coordinate (771, 525) _rotation 0 blocks_short_to_float id blocks_short_to_float_0 _enabled True vlen 1 scale 1 _coordinate (994, 545) _rotation 0 blocks_sub_xx id blocks_sub_xx_3 _enabled True type short vlen 1 num_inputs 2 _coordinate (535, 792) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_1 _enabled True type short num_inputs 2 vlen 1 _coordinate (785, 779) _rotation 0 blocks_short_to_float id blocks_short_to_float_2 _enabled True vlen 1 scale 1 _coordinate (1005, 798) _rotation 0 blocks_sub_xx id blocks_sub_xx_2 _enabled True type complex vlen 1 num_inputs 2 _coordinate (944, 978) _rotation 0 blocks_sub_xx id blocks_sub_xx_1 _enabled True type short vlen 1 num_inputs 2 _coordinate (540, 1141) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_2 _enabled True type short num_inputs 2 vlen 1 _coordinate (796, 1136) _rotation 0 blocks_short_to_float id blocks_short_to_float_1 _enabled True vlen 1 scale 1 _coordinate (1009, 1156) _rotation 0 blocks_sub_xx id blocks_sub_xx_2_0 _enabled True type complex vlen 1 num_inputs 2 _coordinate (975, 1342) _rotation 0 blocks_sub_xx id blocks_sub_xx_1_0 _enabled True type short vlen 1 num_inputs 2 _coordinate (559, 1536) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_2_0 _enabled True type short num_inputs 2 vlen 1 _coordinate (771, 1530) _rotation 0 blocks_short_to_float id blocks_short_to_float_1_0 _enabled True vlen 1 scale 1 _coordinate (1010, 1551) _rotation 0 trellis_viterbi_combined_xx id trellis_viterbi_combined_xx_1 _enabled True type c out_type s fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" block_size 1000 init_state -1 final_state -1 dim 1 table alpha**0.5*1,alpha**0.5*1j,alpha**0.5*(-1j),alpha**0.5*(-1) metric_type digital.TRELLIS_EUCLIDEAN _coordinate (79, 501) _rotation 0 trellis_viterbi_combined_xx id trellis_viterbi_combined_xx_2 _enabled True type c out_type s fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" block_size 1000 init_state -1 final_state -1 dim 1 table (1-alpha)**0.5*1,(1-alpha)**0.5*1j,(1-alpha)**0.5*(-1j),(1-alpha)**0.5*(-1) metric_type digital.TRELLIS_EUCLIDEAN _coordinate (82, 766) _rotation 0 trellis_viterbi_combined_xx id trellis_viterbi_combined_xx_0 _enabled True type c out_type s fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" block_size 1000 init_state -1 final_state -1 dim 1 table (1-alpha)**0.5*1,(1-alpha)**0.5*1j,(1-alpha)**0.5*(-1j),(1-alpha)**0.5*(-1) metric_type digital.TRELLIS_EUCLIDEAN _coordinate (83, 1111) _rotation 0 trellis_viterbi_combined_xx id trellis_viterbi_combined_xx_0_0 _enabled True type c out_type s fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" block_size 1000 init_state -1 final_state -1 dim 1 table alpha**0.5*1,alpha**0.5*1j,alpha**0.5*(-1j),alpha**0.5*(-1) metric_type digital.TRELLIS_EUCLIDEAN _coordinate (75, 1495) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title Scope Plot samp_rate R v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode True num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (1533, 149) _rotation 0 variable id prefix _enabled True value "/n/harrisville/x/anastas/gnuradio_trunk/" _coordinate (871, 14) _rotation 0 trellis_encoder_xx id trellis_encoder_xx_0 _enabled True type ss fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" init_state 0 _coordinate (340, 187) _rotation 0 variable id R _enabled True value 100e3 _coordinate (748, 12) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_0 _enabled True type float title BER 1 (raw) units BER samp_rate R min_value 0 max_value 1 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 0,0,1,1 notebook _coordinate (1267, 410) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_2 _enabled True type float title BER 2 (raw) units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 0,1,1,1 notebook _coordinate (1260, 659) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_3 _enabled True type float title BER 2 (after cancelling user 1) units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 1,1,1,1 notebook _coordinate (1262, 1020) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_3_0 _enabled True type float title BER 1 (after cancelling user 2) units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 1,0,1,1 notebook _coordinate (1269, 1417) _rotation 0 blocks_add_xx id blocks_add_xx_1 _enabled True type complex num_inputs 2 vlen 1 _coordinate (1400, 262) _rotation 0 blocks_add_xx id blocks_add_xx_0 _enabled True type complex num_inputs 2 vlen 1 _coordinate (1224, 245) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type complex noise_type analog.GR_GAUSSIAN amp noisevar seed -42 _coordinate (1178, 321) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type short samples_per_second R vlen 1 _coordinate (579, 143) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const alpha**0.5 vlen 1 _coordinate (988, 196) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0 _enabled True in_type short out_type complex symbol_table 1,1j,-1j,-1 dimension 1 num_ports 1 _coordinate (703, 211) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_1 _enabled True type complex const (1-alpha)**0.5 vlen 1 _coordinate (994, 319) _rotation 0 trellis_encoder_xx id trellis_encoder_xx_1 _enabled True type ss fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" init_state 0 _coordinate (336, 311) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0_0 _enabled True in_type short out_type complex symbol_table 1,1j,-1j,-1 dimension 1 num_ports 1 _coordinate (703, 311) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0_0_0 _enabled True in_type short out_type complex symbol_table 1,1j,-1j,-1 dimension 1 num_ports 1 _coordinate (418, 1000) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_2 _enabled True type complex const alpha**0.5 vlen 1 _coordinate (710, 1008) _rotation 0 trellis_encoder_xx id trellis_encoder_xx_2 _enabled True type ss fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" init_state 0 _coordinate (89, 1000) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_2_0 _enabled True type complex const (1-alpha)**0.5 vlen 1 _coordinate (733, 1374) _rotation 0 trellis_encoder_xx id trellis_encoder_xx_2_0 _enabled True type ss fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_16.fsm" init_state 0 _coordinate (103, 1366) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0_0_1 _enabled True in_type short out_type complex symbol_table 1,1j,-1j,-1 dimension 1 num_ports 1 _coordinate (420, 1366) _rotation 0 analog_random_source_x_1 trellis_encoder_xx_1 0 0 blocks_multiply_const_vxx_0 blocks_add_xx_0 0 0 blocks_add_xx_0 blocks_add_xx_1 0 0 blocks_multiply_const_vxx_1 blocks_add_xx_0 0 1 blocks_sub_xx_0 blocks_multiply_xx_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_0 0 1 blocks_multiply_xx_0 blocks_short_to_float_0 0 0 blocks_short_to_float_0 wxgui_numbersink2_0 0 0 blocks_multiply_xx_2 blocks_short_to_float_1 0 0 analog_random_source_x_0 trellis_encoder_xx_0 0 0 blocks_add_xx_1 trellis_viterbi_combined_xx_1 0 0 analog_random_source_x_0 blocks_sub_xx_0 0 0 trellis_viterbi_combined_xx_1 blocks_sub_xx_0 0 1 trellis_viterbi_combined_xx_0 blocks_sub_xx_1 0 1 analog_random_source_x_1 blocks_sub_xx_1 0 0 blocks_sub_xx_1 blocks_multiply_xx_2 0 0 blocks_sub_xx_1 blocks_multiply_xx_2 0 1 blocks_sub_xx_2 trellis_viterbi_combined_xx_0 0 0 blocks_add_xx_1 blocks_sub_xx_2 0 0 blocks_multiply_const_vxx_2 blocks_sub_xx_2 0 1 trellis_viterbi_combined_xx_1 trellis_encoder_xx_2 0 0 blocks_multiply_xx_1 blocks_short_to_float_2 0 0 blocks_short_to_float_2 wxgui_numbersink2_2 0 0 trellis_viterbi_combined_xx_2 blocks_sub_xx_3 0 1 blocks_sub_xx_3 blocks_multiply_xx_1 0 0 blocks_sub_xx_3 blocks_multiply_xx_1 0 1 blocks_add_xx_1 trellis_viterbi_combined_xx_2 0 0 analog_random_source_x_1 blocks_sub_xx_3 0 0 blocks_short_to_float_1 wxgui_numbersink2_3 0 0 trellis_viterbi_combined_xx_2 trellis_encoder_xx_2_0 0 0 blocks_multiply_xx_2_0 blocks_short_to_float_1_0 0 0 trellis_viterbi_combined_xx_0_0 blocks_sub_xx_1_0 0 1 blocks_sub_xx_1_0 blocks_multiply_xx_2_0 0 0 blocks_sub_xx_1_0 blocks_multiply_xx_2_0 0 1 blocks_sub_xx_2_0 trellis_viterbi_combined_xx_0_0 0 0 blocks_short_to_float_1_0 wxgui_numbersink2_3_0 0 0 blocks_add_xx_1 blocks_sub_xx_2_0 0 0 analog_random_source_x_0 blocks_sub_xx_1_0 0 0 blocks_multiply_const_vxx_2_0 blocks_sub_xx_2_0 0 1 blocks_add_xx_1 wxgui_scopesink2_0 0 0 trellis_encoder_xx_0 blocks_throttle_0 0 0 analog_noise_source_x_0 blocks_add_xx_1 0 1 blocks_throttle_0 digital_chunks_to_symbols_xx_0 0 0 digital_chunks_to_symbols_xx_0 blocks_multiply_const_vxx_0 0 0 digital_chunks_to_symbols_xx_0_0 blocks_multiply_const_vxx_1 0 0 trellis_encoder_xx_1 digital_chunks_to_symbols_xx_0_0 0 0 trellis_encoder_xx_2 digital_chunks_to_symbols_xx_0_0_0 0 0 digital_chunks_to_symbols_xx_0_0_0 blocks_multiply_const_vxx_2 0 0 trellis_encoder_xx_2_0 digital_chunks_to_symbols_xx_0_0_1 0 0 digital_chunks_to_symbols_xx_0_0_1 blocks_multiply_const_vxx_2_0 0 0 gnuradio-3.7.2.1/gr-trellis/examples/grc/pccc1.grc0000664000175000017500000004434512207440367021506 0ustar jcorganjcorgan Sat Nov 10 15:36:08 2012 options id sccc1 _enabled True title Serially Concatenated Convolutional Code author AA description gnuradio flow graph window_size 2048, 2048 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id noisevar _enabled True value 10**(-snr_db/10) _coordinate (389, 15) _rotation 0 variable id prefix _enabled True value "/n/harrisville/x/anastas/gnuradio_trunk/" _coordinate (590, 15) _rotation 0 variable id block _enabled True value 1000 _coordinate (764, 16) _rotation 0 variable_slider id snr_db _enabled True label SNR (dB) value 5 min -10 max 10 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (229, 13) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_2_0 _enabled True type short num_inputs 2 vlen 1 _coordinate (392, 591) _rotation 0 blocks_short_to_float id blocks_short_to_float_1_0 _enabled True vlen 1 scale 1 _coordinate (535, 609) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_3_0 _enabled True type float title BER units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 1,0,1,1 notebook _coordinate (713, 426) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type float title Scope Plot samp_rate R v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (952, 73) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type short min 0 max 2 num_samps 1000 repeat True _coordinate (21, 170) _rotation 0 blocks_sub_xx id blocks_sub_xx_0 _enabled True type short vlen 1 num_inputs 2 _coordinate (217, 597) _rotation 0 trellis_pccc_encoder_xx id trellis_pccc_encoder_xx_0 _enabled True type ss o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" i_init_state 0 interleaver_args trellis.interleaver(block,666) bl block _coordinate (236, 147) _rotation 0 trellis_pccc_decoder_x id trellis_pccc_decoder_x_0 _enabled True out_type s o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 o_final_state -1 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" i_init_state 0 i_final_state -1 interleaver trellis.interleaver(block,666) block_size block iterations 10 siso_type trellis.TRELLIS_MIN_SUM _coordinate (357, 304) _rotation 0 trellis_metrics_x id trellis_metrics_x_0 _enabled True type f card 16 dim 2 table -7,0, -5,0, -3,0, -1,0, 1,0, 3,0, 5,0, 7,0, 0,-7,0, -5,0, -3,0, -1,0, 1,0, 3,0, 5,0, 7 metric_type digital.TRELLIS_EUCLIDEAN _coordinate (58, 354) _rotation 0 variable id R _enabled True value 100e3 _coordinate (482, 17) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type short samples_per_second R vlen 1 _coordinate (517, 103) _rotation 0 blocks_add_xx id blocks_add_xx_1 _enabled True type float num_inputs 2 vlen 1 _coordinate (951, 256) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0 _enabled True in_type short out_type float symbol_table -7,0,-5,0,-3,0,-1,0,1,0,3,0,5,0,7,0,-7,0,-5,0,-3,0,-1,0,1,0,3,0,5,0,7 dimension 2 num_ports 1 _coordinate (552, 178) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type float noise_type analog.GR_GAUSSIAN amp noisevar seed -42 _coordinate (622, 257) _rotation 0 analog_random_source_x_0 blocks_sub_xx_0 0 0 blocks_add_xx_1 wxgui_scopesink2_0 0 0 blocks_multiply_xx_2_0 blocks_short_to_float_1_0 0 0 blocks_short_to_float_1_0 wxgui_numbersink2_3_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 1 blocks_add_xx_1 trellis_metrics_x_0 0 0 analog_random_source_x_0 trellis_pccc_encoder_xx_0 0 0 trellis_pccc_encoder_xx_0 blocks_throttle_0 0 0 trellis_metrics_x_0 trellis_pccc_decoder_x_0 0 0 trellis_pccc_decoder_x_0 blocks_sub_xx_0 0 1 blocks_throttle_0 digital_chunks_to_symbols_xx_0 0 0 digital_chunks_to_symbols_xx_0 blocks_add_xx_1 0 0 analog_noise_source_x_0 blocks_add_xx_1 0 1 gnuradio-3.7.2.1/gr-trellis/examples/grc/readme.txt0000664000175000017500000000275112207440367022011 0ustar jcorganjcorganThese are examples of using gr-trellis in grc. INTERFERENCE CANCELLATION ------------------------- Two users are transmitting simultaneously using convolutionally encoded QPSK, each with power P1=alpha*P and P2=(1-alpha)*P. The combined signal is observed in noise and four different receivers are considered: 1) A viterbi decoder decoding user 1 assuming user 2 is noise 2) A viterbi decoder decoding user 2 assuming user 1 is noise 3) A viterbi decoder decoding user 1 first and then reencoding this signal, subtracting it from the observation and then running a Viterbi decoder decoding user 2 4) A viterbi decoder decoding user 2 first and then reencoding this signal, subtracting it from the observation and then running a Viterbi decoder decoding user 1 You can change the signal to noise ratio P/sigma^2 and the allocation of power to the two users, alpha. Serially Concatenated Convolutional Codes ----------------------------------------- An SCCC can be defined by an outer and an inner FSM together with an interleaver and a modulation type. You can change the SNR and observe the estimated BER. In sccc.grc the decoding and metric calculation are combined; in sccc1.grc they are separate. Parallel Concatenated Convolutional Codes ----------------------------------------- A PCCC can be defined by two FSMs together with an interleaver and a modulation type. You can change the SNR and observe the estimated BER. In pccc1.grc the decoding and metric calculation are separate. Enjoy. gnuradio-3.7.2.1/gr-trellis/examples/grc/sccc1.grc0000664000175000017500000004416312207440367021507 0ustar jcorganjcorgan Sat Nov 10 15:41:10 2012 options id sccc1 _enabled True title Serially Concatenated Convolutional Code author AA description gnuradio flow graph window_size 2048, 2048 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id noisevar _enabled True value 10**(-snr_db/10) _coordinate (389, 15) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type short min 0 max 2 num_samps 1000 repeat True _coordinate (21, 170) _rotation 0 variable id prefix _enabled True value "/n/harrisville/x/anastas/gnuradio_trunk/" _coordinate (590, 15) _rotation 0 variable id block _enabled True value 1000 _coordinate (764, 16) _rotation 0 variable_slider id snr_db _enabled True label SNR (dB) value 5 min -10 max 10 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (229, 13) _rotation 0 variable id R _enabled True value 10e3 _coordinate (482, 17) _rotation 0 trellis_sccc_encoder_xx id trellis_sccc_encoder_xx_0 _enabled True type ss o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn2o3_4.fsm" i_init_state 0 interleaver_args trellis.interleaver(block,666) bl block _coordinate (242, 154) _rotation 0 trellis_sccc_decoder_x id trellis_sccc_decoder_x_0 _enabled True out_type s o_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn1o2_4.fsm" o_init_state 0 o_final_state -1 i_fsm_args prefix+"gr-trellis/src/examples/fsm_files/awgn2o3_4.fsm" i_init_state 0 i_final_state -1 interleaver trellis.interleaver(block,666) block_size block iterations 10 siso_type trellis.TRELLIS_MIN_SUM _coordinate (333, 305) _rotation 0 blocks_sub_xx id blocks_sub_xx_0 _enabled True type short vlen 1 num_inputs 2 _coordinate (217, 597) _rotation 0 blocks_multiply_xx id blocks_multiply_xx_2_0 _enabled True type short num_inputs 2 vlen 1 _coordinate (392, 591) _rotation 0 blocks_short_to_float id blocks_short_to_float_1_0 _enabled True vlen 1 scale 1 _coordinate (535, 609) _rotation 0 wxgui_numbersink2 id wxgui_numbersink2_3_0 _enabled True type float title BER units BER samp_rate R min_value 0 max_value 1.0 factor 1.0 decimal_places 6 ref_level 0 number_rate 15 peak_hold False average True avg_alpha 0.001 show_gauge True win_size grid_pos 1,0,1,1 notebook _coordinate (713, 426) _rotation 0 trellis_metrics_x id trellis_metrics_x_0 _enabled True type f card 8 dim 1 table -7, -5, -3, -1, 1, 3, 5, 7 metric_type digital.TRELLIS_EUCLIDEAN _coordinate (58, 354) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type float title Scope Plot samp_rate R v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (952, 73) _rotation 0 blocks_throttle id blocks_throttle_0 _enabled True type short samples_per_second R vlen 1 _coordinate (517, 103) _rotation 0 digital_chunks_to_symbols_xx id digital_chunks_to_symbols_xx_0 _enabled True in_type short out_type float symbol_table -7,-5,-3,-1,1,3,5,7 dimension 1 num_ports 1 _coordinate (607, 175) _rotation 0 blocks_add_xx id blocks_add_xx_1 _enabled True type float num_inputs 2 vlen 1 _coordinate (951, 256) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type float noise_type analog.GR_GAUSSIAN amp noisevar seed -42 _coordinate (632, 254) _rotation 0 analog_random_source_x_0 blocks_sub_xx_0 0 0 blocks_add_xx_1 wxgui_scopesink2_0 0 0 analog_random_source_x_0 trellis_sccc_encoder_xx_0 0 0 trellis_sccc_encoder_xx_0 blocks_throttle_0 0 0 blocks_multiply_xx_2_0 blocks_short_to_float_1_0 0 0 blocks_short_to_float_1_0 wxgui_numbersink2_3_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 0 blocks_sub_xx_0 blocks_multiply_xx_2_0 0 1 blocks_add_xx_1 trellis_metrics_x_0 0 0 trellis_metrics_x_0 trellis_sccc_decoder_x_0 0 0 trellis_sccc_decoder_x_0 blocks_sub_xx_0 0 1 blocks_throttle_0 digital_chunks_to_symbols_xx_0 0 0 digital_chunks_to_symbols_xx_0 blocks_add_xx_1 0 0 analog_noise_source_x_0 blocks_add_xx_1 0 1 gnuradio-3.7.2.1/gr-trellis/examples/python/0000775000175000017500000000000012207440367020554 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/examples/python/CMakeLists.txt0000664000175000017500000000346512207440367023324 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL( PROGRAMS fsm_utils.py test_tcm.py test_tcm_parallel.py test_tcm_combined.py test_sccc_hard.py test_sccc_soft.py test_sccc_turbo.py test_viterbi_equalization1.py test_viterbi_equalization.py test_turbo_equalization.py test_turbo_equalization1.py test_turbo_equalization2.py DESTINATION ${GR_PKG_TRELLIS_EXAMPLES_DIR} COMPONENT "trellis_examples" ) install( FILES README DESTINATION ${GR_PKG_DATA_DIR}/examples/trellis COMPONENT "trellis_examples" ) install( FILES fsm_files/awgn1o2_128.fsm fsm_files/awgn1o2_16.fsm fsm_files/awgn1o2_4.fsm fsm_files/awgn1o2_8.fsm fsm_files/awgn2o3_16.fsm fsm_files/awgn2o3_4.fsm fsm_files/awgn2o3_4_msb.fsm fsm_files/awgn2o3_4_msbG.fsm fsm_files/awgn2o3_8.fsm fsm_files/awgn2o4_4.fsm fsm_files/disconnected.fsm fsm_files/rep3.fsm fsm_files/rep5.fsm fsm_files/simple.fsm DESTINATION ${GR_PKG_TRELLIS_EXAMPLES_DIR}/fsm_files COMPONENT "trellis_examples" ) gnuradio-3.7.2.1/gr-trellis/examples/python/test_tcm_combined.py0000775000175000017500000001014712207440367024616 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import fsm_utils from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality enc = trellis.encoder_ss(f,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX va = trellis.viterbi_combined_fs(f,K,0,-1,dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s(); tb.connect (src,src_head,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,va,fsmi2s,dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state.. # Then put it as the last argument in the viterbi block #print "final state = " , enc.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-f", "--fsm_file", type="string", default="fsm_files/awgn1o2_4.fsm", help="Filename containing the fsm specification, e.g. -f fsm_files/awgn1o2_4.fsm (default=fsm_files/awgn1o2_4.fsm)") parser.add_option("-e", "--esn0", type="eng_float", default=10.0, help="Symbol energy to noise PSD level ratio in dB, e.g., -e 10.0 (default=10.0)") parser.add_option("-r", "--repetitions", type="int", default=100, help="Number of packets to be generated for the simulation, e.g., -r 100 (default=100)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 fname=options.fsm_file esn0_db=float(options.esn0) rep=int(options.repetitions) # system parameters f=trellis.fsm(fname) # get the FSM specification from a file (will hopefully be automated in the future...) Kb=1024*16 # packet size in bits (make it multiple of 16) bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps modulation = fsm_utils.psk4 # see fsm_utils.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-trellis/examples/python/test_turbo_equalization1.py0000775000175000017500000001255012207440367026174 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, filter, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def make_rx(tb,fo,fi,dimensionality,tot_constellation,K,interleaver,IT,Es,N0,type): metrics_in = trellis.metrics_f(fi.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner SISO scale = blocks.multiply_const_ff(1.0/N0) gnd = blocks.vector_source_f([0],True); inter=[] deinter=[] siso_in=[] siso_out=[] # generate all blocks for it in range(IT): inter.append( trellis.permutation(interleaver.K(),interleaver.INTER(),fi.I(),gr.sizeof_float) ) siso_in.append( trellis.siso_f(fi,K,0,-1,True,False,type) ) deinter.append( trellis.permutation(interleaver.K(),interleaver.DEINTER(),fi.I(),gr.sizeof_float) ) if it < IT-1: siso_out.append( trellis.siso_f(fo,K,0,-1,False,True,type) ) else: siso_out.append( trellis.viterbi_s(fo,K,0,-1) ) # no soft outputs needed # connect first stage tb.connect (gnd,inter[0]) tb.connect (metrics_in,scale) tb.connect (scale,(siso_in[0],1)) # connect the rest for it in range(IT): if it < IT-1: tb.connect (scale,(siso_in[it+1],1)) tb.connect (siso_in[it],deinter[it],(siso_out[it],1)) tb.connect (gnd,(siso_out[it],0)) tb.connect (siso_out[it],inter[it+1]) tb.connect (inter[it],(siso_in[it],0)) else: tb.connect (siso_in[it],deinter[it],siso_out[it]) tb.connect (inter[it],(siso_in[it],0)) return (metrics_in,siso_out[IT-1]) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,Es,N0,IT,seed): tb = gr.top_block () L = len(channel) # TX # this for loop is TOO slow in python!!! packet = [0]*(K) random.seed(seed) for i in range(len(packet)): packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols src = blocks.vector_source_s(packet,False) enc_out = trellis.encoder_ss(fo,0) # initial state = 0 inter = trellis.permutation(interleaver.K(),interleaver.INTER(),1,gr.sizeof_short) mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) # CHANNEL isi = filter.fir_filter_fff(1,channel) add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX (head,tail) = make_rx(tb,fo,fi,dimensionality,tot_constellation,K,interleaver,IT,Es,N0,trellis.TRELLIS_MIN_SUM) dst = blocks.vector_sink_s(); tb.connect (src,enc_out,inter,mod) tb.connect (mod,isi,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,head) tb.connect (tail,dst) tb.run() data = dst.data() ntotal = len(data) nright=0 for i in range(ntotal): if packet[i]==data[i]: nright=nright+1 #else: #print "Error in ", i return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 3: fname_out=args[0] esn0_db=float(args[1]) rep=int(args[2]) else: sys.stderr.write ('usage: test_turbo_equalization.py fsm_name_out Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=64*16 # packet size in bits (multiple of 16) modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) dimensionality = tot_channel[0] tot_constellation = tot_channel[1] if len(tot_constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') sys.exit (1) N0=pow(10.0,-esn0_db/10.0); # noise variance IT = 3 # number of turbo iterations tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,1,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_turbo_equalization.py0000775000175000017500000001311712207440367026113 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def make_rx(tb,fo,fi,dimensionality,tot_constellation,K,interleaver,IT,Es,N0,type): metrics_in = trellis.metrics_f(fi.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner SISO scale = blocks.multiply_const_ff(1.0/N0) gnd = blocks.vector_source_f([0],True); inter=[] deinter=[] siso_in=[] siso_out=[] # generate all blocks for it in range(IT): inter.append( trellis.permutation(interleaver.K(),interleaver.INTER(),fi.I(),gr.sizeof_float) ) siso_in.append( trellis.siso_f(fi,K,0,-1,True,False,type) ) deinter.append( trellis.permutation(interleaver.K(),interleaver.DEINTER(),fi.I(),gr.sizeof_float) ) if it < IT-1: siso_out.append( trellis.siso_f(fo,K,0,-1,False,True,type) ) else: siso_out.append( trellis.viterbi_s(fo,K,0,-1) ) # no soft outputs needed # connect first stage tb.connect (gnd,inter[0]) tb.connect (metrics_in,scale) tb.connect (scale,(siso_in[0],1)) # connect the rest for it in range(IT): if it < IT-1: tb.connect (metrics_in,(siso_in[it+1],1)) tb.connect (siso_in[it],deinter[it],(siso_out[it],1)) tb.connect (gnd,(siso_out[it],0)) tb.connect (siso_out[it],inter[it+1]) tb.connect (inter[it],(siso_in[it],0)) else: tb.connect (siso_in[it],deinter[it],siso_out[it]) tb.connect (inter[it],(siso_in[it],0)) return (metrics_in,siso_out[IT-1]) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,tot_constellation,Es,N0,IT,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the iouter FSM input cardinality enc_out = trellis.encoder_ss(fo,0) # initial state = 0 inter = trellis.permutation(interleaver.K(),interleaver.INTER(),1,gr.sizeof_short) enc_in = trellis.encoder_ss(fi,0) # initial state = 0 # essentially here we implement the combination of modulation and channel as a memoryless modulation (the memory induced by the channel is hidden in the innner FSM) mod = digital.chunks_to_symbols_sf(tot_constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX (head,tail) = make_rx(tb,fo,fi,dimensionality,tot_constellation,K,interleaver,IT,Es,N0,trellis.TRELLIS_MIN_SUM) fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s(); tb.connect (src,src_head,s2fsmi,enc_out,inter,enc_in,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,head) tb.connect (tail,fsmi2s,dst) tb.run() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () #print ntotal,nright,runlength return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 3: fname_out=args[0] esn0_db=float(args[1]) rep=int(args[2]) else: sys.stderr.write ('usage: test_turbo_equalization.py fsm_name_out Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=64*16 # packet size in bits (multiple of 16) modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps print 'size = ',K interleaver=trellis.interleaver(K,666) # construct a random interleaver tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) dimensionality = tot_channel[0] tot_constellation = tot_channel[1] if len(tot_constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') sys.exit (1) N0=pow(10.0,-esn0_db/10.0); # noise variance IT = 3 # number of turbo iterations tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,tot_constellation,1,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations print s tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_cpm.py0000775000175000017500000001260412207440367022752 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: CPM test # Author: Achilleas Anastasopoulos # Description: gnuradio flow graph # Generated: Thu Feb 19 23:16:23 2009 ################################################## from gnuradio import gr from gnuradio import trellis, digital, filter, blocks from grc_gnuradio import blks2 as grc_blks2 import math import numpy import fsm_utils from gnuradio import trellis try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) try: import scipy.stats except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) def run_test(seed,blocksize): tb = gr.top_block() ################################################## # Variables ################################################## M = 2 K = 1 P = 2 h = (1.0*K)/P L = 3 Q = 4 frac = 0.99 f = trellis.fsm(P,M,L) # CPFSK signals #p = numpy.ones(Q)/(2.0) #q = numpy.cumsum(p)/(1.0*Q) # GMSK signals BT=0.3; tt=numpy.arange(0,L*Q)/(1.0*Q)-L/2.0; #print tt p=(0.5*scipy.special.erfc(2*math.pi*BT*(tt-0.5)/math.sqrt(math.log(2.0))/math.sqrt(2.0))-0.5*scipy.special.erfc(2*math.pi*BT*(tt+0.5)/math.sqrt(math.log(2.0))/math.sqrt(2.0)))/2.0; p=p/sum(p)*Q/2.0; #print p q=numpy.cumsum(p)/Q; q=q/q[-1]/2.0; #print q (f0T,SS,S,F,Sf,Ff,N) = fsm_utils.make_cpm_signals(K,P,M,L,q,frac) #print N #print Ff Ffa = numpy.insert(Ff,Q,numpy.zeros(N),axis=0) #print Ffa MF = numpy.fliplr(numpy.transpose(Ffa)) #print MF E = numpy.sum(numpy.abs(Sf)**2,axis=0) Es = numpy.sum(E)/f.O() #print Es constellation = numpy.reshape(numpy.transpose(Sf),N*f.O()) #print Ff #print Sf #print constellation #print numpy.max(numpy.abs(SS - numpy.dot(Ff , Sf))) EsN0_db = 10.0 N0 = Es * 10.0**(-(1.0*EsN0_db)/10.0) #N0 = 0.0 #print N0 head = 4 tail = 4 numpy.random.seed(seed*666) data = numpy.random.randint(0, M, head+blocksize+tail+1) #data = numpy.zeros(blocksize+1+head+tail,'int') for i in range(head): data[i]=0 for i in range(tail+1): data[-i]=0 ################################################## # Blocks ################################################## random_source_x_0 = blocks.vector_source_b(data.tolist(), False) digital_chunks_to_symbols_xx_0 = digital.chunks_to_symbols_bf((-1, 1), 1) filter_interp_fir_filter_xxx_0 = filter.interp_fir_filter_fff(Q, p) analog_frequency_modulator_fc_0 = analog.frequency_modulator_fc(2*math.pi*h*(1.0/Q)) blocks_add_vxx_0 = blocks.add_vcc(1) analog_noise_source_x_0 = analog.noise_source_c(analog.GR_GAUSSIAN, (N0/2.0)**0.5, -long(seed)) blokcs_multiply_vxx_0 = blocks.multiply_vcc(1) analog_sig_source_x_0 = analog.sig_source_c(Q, analog.GR_COS_WAVE, -f0T, 1, 0) # only works for N=2, do it manually for N>2... filter_fir_filter_xxx_0_0 = filter.fir_filter_ccc(Q, MF[0].conjugate()) filter_fir_filter_xxx_0_0_0 = filter.fir_filter_ccc(Q, MF[1].conjugate()) blocks_streams_to_stream_0 = blocks.streams_to_stream(gr.sizeof_gr_complex*1, int(N)) blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*1, int(N*(1+0))) viterbi = trellis.viterbi_combined_cb(f, head+blocksize+tail, 0, -1, int(N), constellation, digital.TRELLIS_EUCLIDEAN) blocks_vector_sink_x_0 = blocks.vector_sink_b() ################################################## # Connections ################################################## tb.connect((random_source_x_0, 0), (digital_chunks_to_symbols_xx_0, 0)) tb.connect((digital_chunks_to_symbols_xx_0, 0), (filter_interp_fir_filter_xxx_0, 0)) tb.connect((filter_interp_fir_filter_xxx_0, 0), (analog_frequency_modulator_fc_0, 0)) tb.connect((analog_frequency_modulator_fc_0, 0), (blocks_add_vxx_0, 0)) tb.connect((analog_noise_source_x_0, 0), (blocks_add_vxx_0, 1)) tb.connect((blocks_add_vxx_0, 0), (blocks_multiply_vxx_0, 0)) tb.connect((analog_sig_source_x_0, 0), (blocks_multiply_vxx_0, 1)) tb.connect((blocks_multiply_vxx_0, 0), (filter_fir_filter_xxx_0_0, 0)) tb.connect((blocks_multiply_vxx_0, 0), (filter_fir_filter_xxx_0_0_0, 0)) tb.connect((filter_fir_filter_xxx_0_0, 0), (blocks_streams_to_stream_0, 0)) tb.connect((filter_fir_filter_xxx_0_0_0, 0), (blocks_streams_to_stream_0, 1)) tb.connect((blocks_streams_to_stream_0, 0), (blocks_skiphead_0, 0)) tb.connect((blocks_skiphead_0, 0), (viterbi, 0)) tb.connect((viterbi, 0), (blocks_vector_sink_x_0, 0)) tb.run() dataest = blocks_vector_sink_x_0.data() #print data #print numpy.array(dataest) perr = 0 err = 0 for i in range(blocksize): if data[head+i] != dataest[head+i]: #print i err += 1 if err != 0 : perr = 1 return (err,perr) if __name__ == '__main__': blocksize = 1000 ss=0 ee=0 for i in range(10000): (s,e) = run_test(i,blocksize) ss += s ee += e if (i+1) % 100 == 0: print i+1,ss,ee,(1.0*ss)/(i+1)/(1.0*blocksize),(1.0*ee)/(i+1) print i+1,ss,ee,(1.0*ss)/(i+1)/(1.0*blocksize),(1.0*ee)/(i+1) gnuradio-3.7.2.1/gr-trellis/examples/python/test_sccc_turbo.py0000775000175000017500000001311512207440367024317 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def make_rx(tb,fo,fi,dimensionality,constellation,K,interleaver,IT,Es,N0,type): metrics_in = trellis.metrics_f(fi.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner Viterbi scale = blocks.multiply_const_ff(1.0/N0) gnd = blocks.vector_source_f([0],True); inter=[] deinter=[] siso_in=[] siso_out=[] # generate all blocks for it in range(IT): inter.append( trellis.permutation(interleaver.K(),interleaver.INTER(),fi.I(),gr.sizeof_float) ) siso_in.append( trellis.siso_f(fi,K,0,-1,True,False,type) ) deinter.append( trellis.permutation(interleaver.K(),interleaver.DEINTER(),fi.I(),gr.sizeof_float) ) if it < IT-1: siso_out.append( trellis.siso_f(fo,K,0,-1,False,True,type) ) else: siso_out.append( trellis.viterbi_s(fo,K,0,-1) ) # no soft outputs needed # connect first stage tb.connect (gnd,inter[0]) tb.connect (metrics_in,scale) tb.connect (scale,(siso_in[0],1)) # connect the rest for it in range(IT): if it < IT-1: tb.connect (metrics_in,(siso_in[it+1],1)) tb.connect (siso_in[it],deinter[it],(siso_out[it],1)) tb.connect (gnd,(siso_out[it],0)) tb.connect (siso_out[it],inter[it+1]) tb.connect (inter[it],(siso_in[it],0)) else: tb.connect (siso_in[it],deinter[it],siso_out[it]) tb.connect (inter[it],(siso_in[it],0)) return (metrics_in,siso_out[IT-1]) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality enc_out = trellis.encoder_ss(fo,0) # initial state = 0 inter = trellis.permutation(interleaver.K(),interleaver.INTER(),1,gr.sizeof_short) enc_in = trellis.encoder_ss(fi,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX (head,tail) = make_rx(tb,fo,fi,dimensionality,constellation,K,interleaver,IT,Es,N0,trellis.TRELLIS_MIN_SUM) #(head,tail) = make_rx(tb,fo,fi,dimensionality,constellation,K,interleaver,IT,Es,N0,trellis.TRELLIS_SUM_PRODUCT) fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() tb.connect (src,src_head,s2fsmi,enc_out,inter,enc_in,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,head) tb.connect (tail,fsmi2s,dst) tb.run() #print enc_out.ST(), enc_in.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 5: fname_out=args[0] fname_in=args[1] esn0_db=float(args[2]) # Es/No in dB IT=int(args[3]) rep=int(args[4]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_sccc_turbo.py fsm_name_out fsm_fname_in Es/No_db iterations repetitions\n') sys.exit (1) # system parameters Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(fname_in) # get the innner FSM specification from a file bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver modulation = fsm_utils.psk8 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0): # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_tcm_bit.py0000775000175000017500000001202412207440367023610 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): tb = gr.top_block () # TX packet = [0]*Kb # this for loop is TOO slow!!! for i in range(Kb-1*16): # last 16 bits = 0 to drive the final state to 0 packet[i] = random.randint(0, 1) # random 0s and 1s src = blocks.vector_source_s(packet,False) #src = blocks.lfsr_32k_source_s() #src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts b2s = blocks.unpacked_to_packed_ss(1,gr.GR_MSB_FIRST) # pack bits in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality enc = trellis.encoder_ss(f,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics = trellis.metrics_f(f.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts s2b = blocks.packed_to_unpacked_ss(1,gr.GR_MSB_FIRST) # unpack shorts to bits dst = blocks.vector_sink_s(); #dst = blocks.check_lfsr_32k_s(); #tb.connect (src,src_head,s2fsmi,enc,mod) tb.connect (src,b2s,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics) #tb.connect (metrics,va,fsmi2s,dst) tb.connect (metrics,va,fsmi2s,s2b,dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state.. # Then put it as the last argument in the viterbi block #print "final state = " , enc.ST() #ntotal = dst.ntotal () #nright = dst.nright () #runlength = dst.runlength () ntotal = len(packet) if len(dst.data()) != ntotal: print "Error: not enough data\n" nright = 0; # this for loop is TOO slow!!! for i in range(ntotal): if packet[i]==dst.data()[i]: nright=nright+1 #else: #print "Error in ", i return (ntotal,ntotal-nright) def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-f", "--fsm_file", type="string", default="fsm_files/awgn1o2_4.fsm", help="Filename containing the fsm specification, e.g. -f fsm_files/awgn1o2_4.fsm (default=fsm_files/awgn1o2_4.fsm)") parser.add_option("-e", "--esn0", type="eng_float", default=10.0, help="Symbol energy to noise PSD level ratio in dB, e.g., -e 10.0 (default=10.0)") parser.add_option("-r", "--repetitions", type="int", default=100, help="Number of packets to be generated for the simulation, e.g., -r 100 (default=100)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 fname=options.fsm_file esn0_db=float(options.esn0) rep=int(options.repetitions) # system parameters f=trellis.fsm(fname) # get the FSM specification from a file Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%1==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-trellis/examples/python/test_sccc_soft.py0000775000175000017500000001063312207440367024141 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality enc_out = trellis.encoder_ss(fo,0) # initial state = 0 inter = trellis.permutation(interleaver.K(),interleaver.INTER(),1,gr.sizeof_short) enc_in = trellis.encoder_ss(fi,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics_in = trellis.metrics_f(fi.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner Viterbi gnd = blocks.vector_source_f([0],True); siso_in = trellis.siso_f(fi,K,0,-1,True,False,trellis.TRELLIS_MIN_SUM) # Put -1 if the Initial/Final states are not set. deinter = trellis.permutation(interleaver.K(),interleaver.DEINTER(),fi.I(),gr.sizeof_float) va_out = trellis.viterbi_s(fo,K,0,-1) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() tb.connect (src,src_head,s2fsmi,enc_out,inter,enc_in,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics_in) tb.connect (gnd,(siso_in,0)) tb.connect (metrics_in,(siso_in,1)) tb.connect (siso_in,deinter,va_out,fsmi2s,dst) tb.run() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 4: fname_out=args[0] fname_in=args[1] esn0_db=float(args[2]) # Es/No in dB rep=int(args[3]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_tcm.py fsm_name_out fsm_fname_in Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(fname_in) # get the innner FSM specification from a file bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver modulation = fsm_utils.psk8 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_pccc_turbo1.py0000775000175000017500000001131112207440367024371 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality #src = blocks.vector_source_s([0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1],False) enc = trellis.pccc_encoder_ss(fo,0,fi,0,interleaver,K) code = blocks.vector_sink_s() mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics_in = trellis.metrics_f(fi.O()*fo.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner SISO scale = blocks.multiply_const_ff(1.0/N0) dec = trellis.pccc_decoder_s(fo,0,-1,fi,0,-1,interleaver,K,IT,trellis.TRELLIS_MIN_SUM) fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() tb.connect (src,src_head,s2fsmi,enc,mod) #tb.connect (src,enc,mod) #tb.connect(enc,code) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics_in,scale,dec,fsmi2s,dst) tb.run() #print code.data() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 5: fname_out=args[0] fname_in=args[1] esn0_db=float(args[2]) # Es/No in dB IT=int(args[3]) rep=int(args[4]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_pccc_turbo.py fsm_name_1 fsm_fname_2 Es/No_db iterations repetitions\n') sys.exit (1) # system parameters Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(fname_in) # get the innner FSM specification from a file bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol if fo.I() != fi.I(): sys.stderr.write ('Incompatible input cardinality between two FSMs.\n') sys.exit (1) K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver #modulation = fsm_utils.psk8 # see fsm_utlis.py for available predefined modulations dimensionality = 4 constellation = [ 1, 0, 1, 0,\ 1, 0,-1, 0,\ 1, 0, 0, 1,\ 1, 0, 0,-1,\ -1, 0, 1, 0,\ -1, 0,-1, 0,\ -1, 0, 0, 1,\ -1, 0, 0,-1,\ 0, 1, 1, 0,\ 0, 1,-1, 0,\ 0, 1, 0, 1,\ 0, 1, 0,-1,\ 0,-1, 1, 0,\ 0,-1,-1, 0,\ 0,-1, 0, 1,\ 0,-1, 0,-1,] # equivalent to 2 QPSK symbols if len(constellation)/dimensionality != fi.O()*fo.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0): # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_sccc_turbo1.py0000775000175000017500000000775012207440367024410 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality enc = trellis.sccc_encoder_ss(fo,0,fi,0,interleaver,K) mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX dec = trellis.sccc_decoder_combined_fs(fo,0,-1,fi,0,-1,interleaver,K,IT,trellis.TRELLIS_MIN_SUM,dimensionality,constellation,digital.TRELLIS_EUCLIDEAN,1.0) fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() #tb.connect (src,src_head,s2fsmi,enc_out,inter,enc_in,mod) tb.connect (src,src_head,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) #tb.connect (add,head) #tb.connect (tail,fsmi2s,dst) tb.connect (add,dec,fsmi2s,dst) tb.run() #print enc_out.ST(), enc_in.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 5: fname_out=args[0] fname_in=args[1] esn0_db=float(args[2]) # Es/No in dB IT=int(args[3]) rep=int(args[4]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_tcm.py fsm_name_out fsm_fname_in Es/No_db iterations repetitions\n') sys.exit (1) # system parameters Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(fname_in) # get the innner FSM specification from a file bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver modulation = fsm_utils.psk8 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0): # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_sccc_hard.py0000775000175000017500000001066112207440367024105 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality enc_out = trellis.encoder_ss(fo,0) # initial state = 0 inter = trellis.permutation(interleaver.K(),interleaver.INTER(),1,gr.sizeof_short) enc_in = trellis.encoder_ss(fi,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics_in = trellis.metrics_f(fi.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner Viterbi va_in = trellis.viterbi_s(fi,K,0,-1) # Put -1 if the Initial/Final states are not set. deinter = trellis.permutation(interleaver.K(),interleaver.DEINTER(),1,gr.sizeof_short) metrics_out = trellis.metrics_s(fo.O(),1,[0,1,2,3],digital.TRELLIS_HARD_SYMBOL) # data preprocessing to generate metrics for outer Viterbi (hard decisions) va_out = trellis.viterbi_s(fo,K,0,-1) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() tb.connect (src,src_head,s2fsmi,enc_out,inter,enc_in,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics_in) tb.connect (metrics_in,va_in,deinter,metrics_out,va_out,fsmi2s,dst) tb.run() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 4: fname_out=args[0] fname_in=args[1] esn0_db=float(args[2]) # Es/No in dB rep=int(args[3]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_tcm.py fsm_name_out fsm_fname_in Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(fname_in) # get the innner FSM specification from a file bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver modulation = fsm_utils.psk8 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_tcm.py0000775000175000017500000001207012207440367022753 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed): tb = gr.top_block () # TX #packet = [0]*Kb #for i in range(Kb-1*16): # last 16 bits = 0 to drive the final state to 0 #packet[i] = random.randint(0, 1) # random 0s and 1s #src = blocks.vector_source_s(packet,False) src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts #b2s = blocks.unpacked_to_packed_ss(1,gr.GR_MSB_FIRST) # pack bits in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality enc = trellis.encoder_ss(f,0) # initial state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics = trellis.metrics_f(f.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts #s2b = blocks.packed_to_unpacked_ss(1,gr.GR_MSB_FIRST) # unpack shorts to bits #dst = blocks.vector_sink_s(); dst = blocks.check_lfsr_32k_s() tb.connect (src,src_head,s2fsmi,enc,mod) #tb.connect (src,b2s,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics) tb.connect (metrics,va,fsmi2s,dst) #tb.connect (metrics,va,fsmi2s,s2b,dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state.. # Then put it as the last argument in the viterbi block #print "final state = " , enc.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () #ntotal = len(packet) #if len(dst.data()) != ntotal: #print "Error: not enough data\n" #nright = 0; #for i in range(ntotal): #if packet[i]==dst.data()[i]: #nright=nright+1 #else: #print "Error in ", i return (ntotal,ntotal-nright) def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-f", "--fsm_file", type="string", default="fsm_files/awgn1o2_4.fsm", help="Filename containing the fsm specification, e.g. -f fsm_files/awgn1o2_4.fsm (default=fsm_files/awgn1o2_4.fsm)") parser.add_option("-e", "--esn0", type="eng_float", default=10.0, help="Symbol energy to noise PSD level ratio in dB, e.g., -e 10.0 (default=10.0)") parser.add_option("-r", "--repetitions", type="int", default=100, help="Number of packets to be generated for the simulation, e.g., -r 100 (default=100)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 fname=options.fsm_file esn0_db=float(options.esn0) rep=int(options.repetitions) # system parameters f=trellis.fsm(fname) # get the FSM specification from a file # alternatively you can specify the fsm from its generator matrix #f=trellis.fsm(1,2,[5,7]) Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-trellis/examples/python/test_turbo_equalization2.py0000775000175000017500000001254512207440367026201 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, filter, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def make_rx(tb,fo,fi,dimensionality,tot_constellation,K,interleaver,IT,Es,N0,type): scale = blocks.multiply_const_ff(math.sqrt(1.0/N0)) gnd = blocks.vector_source_f([0],True); inter=[] deinter=[] siso_in=[] siso_out=[] # generate all blocks for it in range(IT): inter.append( trellis.permutation(interleaver.K(),interleaver.INTER(),fi.I(),gr.sizeof_float) ) siso_in.append( trellis.siso_combined_f(fi,K,0,-1,True,False,type,dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) ) deinter.append( trellis.permutation(interleaver.K(),interleaver.DEINTER(),fi.I(),gr.sizeof_float) ) if it < IT-1: siso_out.append( trellis.siso_f(fo,K,0,-1,False,True,type) ) else: siso_out.append( trellis.viterbi_s(fo,K,0,-1) ) # no soft outputs needed # connect first stage tb.connect (gnd,inter[0]) tb.connect (scale,(siso_in[0],1)) # connect the rest for it in range(IT): if it < IT-1: tb.connect (scale,(siso_in[it+1],1)) tb.connect (siso_in[it],deinter[it],(siso_out[it],1)) tb.connect (gnd,(siso_out[it],0)) tb.connect (siso_out[it],inter[it+1]) tb.connect (inter[it],(siso_in[it],0)) else: tb.connect (siso_in[it],deinter[it],siso_out[it]) tb.connect (inter[it],(siso_in[it],0)) return (scale,siso_out[IT-1]) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,Es,N0,IT,seed): tb = gr.top_block () L = len(channel) # TX # this for loop is TOO slow in python!!! packet = [0]*(K) random.seed(seed) for i in range(len(packet)): packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols src = blocks.vector_source_s(packet,False) enc_out = trellis.encoder_ss(fo,0) # initial state = 0 inter = trellis.permutation(interleaver.K(),interleaver.INTER(),1,gr.sizeof_short) mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) # CHANNEL isi = filter.fir_filter_fff(1,channel) add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX (head,tail) = make_rx(tb,fo,fi,dimensionality,tot_constellation,K,interleaver,IT,Es,N0,trellis.TRELLIS_MIN_SUM) dst = blocks.vector_sink_s(); tb.connect (src,enc_out,inter,mod) tb.connect (mod,isi,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,head) tb.connect (tail,dst) tb.run() data = dst.data() ntotal = len(data) nright=0 for i in range(ntotal): if packet[i]==data[i]: nright=nright+1 #else: #print "Error in ", i return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 3: fname_out=args[0] esn0_db=float(args[1]) rep=int(args[2]) else: sys.stderr.write ('usage: test_turbo_equalization.py fsm_name_out Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=64*16 # packet size in bits (multiple of 16) modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) dimensionality = tot_channel[0] N0=pow(10.0,-esn0_db/10.0); # noise variance tot_constellation =[0]*len(tot_channel[1]) for i in range(len(tot_channel[1])): tot_constellation[i] = tot_channel[1][i] * math.sqrt(1.0/N0) if len(tot_constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') sys.exit (1) IT = 3 # number of turbo iterations tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,1,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_viterbi_equalization.py0000775000175000017500000000720612207440367026426 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,dimensionality,tot_constellation,N0,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head (gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality enc = trellis.encoder_ss(f,0) # initial state = 0 # essentially here we implement the combination of modulation and channel as a memoryless modulation (the memory induced by the channel is hidden in the FSM) mod = digital.chunks_to_symbols_sf(tot_constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s(); tb.connect (src,src_head,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) tb.connect (add,metrics) tb.connect (metrics,va,fsmi2s,dst) tb.run() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () #print ntotal,nright,runlength return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 2: esn0_db=float(args[0]) rep=int(args[1]) else: sys.stderr.write ('usage: test_viterbi_equalization.py Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=128*16 # packet size in bits (multiple of 16) modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels f=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) dimensionality = tot_channel[0] tot_constellation = tot_channel[1] N0=pow(10.0,-esn0_db/10.0); # noise variance if len(tot_constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') sys.exit (1) tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,tot_constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_sccc_turbo2.py0000775000175000017500000001017412207440367024403 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,seed): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16) # packet size in shorts s2fsmi = blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the outer FSM input cardinality enc = trellis.sccc_encoder_ss(fo,0,fi,0,interleaver,K) mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add = blocks.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX metrics_in = trellis.metrics_f(fi.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for innner SISO scale = blocks.multiply_const_ff(1.0/N0) dec = trellis.sccc_decoder_s(fo,0,-1,fi,0,-1,interleaver,K,IT,trellis.TRELLIS_MIN_SUM) fsmi2s = blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() #tb.connect (src,src_head,s2fsmi,enc_out,inter,enc_in,mod) tb.connect (src,src_head,s2fsmi,enc,mod) tb.connect (mod,(add,0)) tb.connect (noise,(add,1)) #tb.connect (add,head) #tb.connect (tail,fsmi2s,dst) tb.connect (add,metrics_in,scale,dec,fsmi2s,dst) tb.run() #print enc_out.ST(), enc_in.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 5: fname_out=args[0] fname_in=args[1] esn0_db=float(args[2]) # Es/No in dB IT=int(args[3]) rep=int(args[4]) # number of times the experiment is run to collect enough errors else: sys.stderr.write ('usage: test_tcm.py fsm_name_out fsm_fname_in Es/No_db iterations repetitions\n') sys.exit (1) # system parameters Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) fo=trellis.fsm(fname_out) # get the outer FSM specification from a file fi=trellis.fsm(fname_in) # get the innner FSM specification from a file bitspersymbol = int(round(math.log(fo.I())/math.log(2))) # bits per FSM input symbol if fo.O() != fi.I(): sys.stderr.write ('Incompatible cardinality between outer and inner FSM.\n') sys.exit (1) K=Kb/bitspersymbol # packet size in trellis steps interleaver=trellis.interleaver(K,666) # construct a random interleaver modulation = fsm_utils.psk8 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != fi.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(fo,fi,interleaver,Kb,bitspersymbol,K,dimensionality,constellation,Es,N0,IT,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%10==0): # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/0000775000175000017500000000000012207440367022523 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/disconnected.fsm0000664000175000017500000000003012207440367025665 0ustar jcorganjcorgan1 4 1 1 0 3 2 0 0 0 0 gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/rep5.fsm0000664000175000017500000000004712207440367024106 0ustar jcorganjcorgan2 1 32 0 0 0 31 1/5 repetition code gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn2o3_4_msbG.fsm0000664000175000017500000000120612207440367025704 0ustar jcorganjcorgan4 4 8 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 4 2 6 5 1 3 7 3 7 5 1 This is generated by the 1/2 AWGN code (5 7) operated twice, ie, (xk+1 xki) [xk-1 xk-2] -> [xk+1 xki]. We also puncture the first (MSB) bit and Gray map the symbols. intermediate states: 00 21 02 23 00 21 02 23 10 31 12 33 10 31 12 33 output before puncturing: 00 31 03 32 30 01 33 02 13 22 10 21 23 12 20 11 output after punturing the MSB: 00 11 03 12 10 01 13 02 13 02 10 01 03 12 00 11 and in decimal: 0 5 3 6 4 1 7 2 7 2 4 1 3 6 0 5 After Gray mapping: label -> phase 0 -> 0 1 -> 0 2 -> 7 3 -> 2 4 -> 5 5 -> 4 6 -> 6 7 -> 3 0 4 2 6 5 1 3 7 3 7 5 1 2 6 0 4 gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn1o2_16.fsm0000664000175000017500000000061712207440367025022 0ustar jcorganjcorgan2 16 4 0 8 0 8 1 9 1 9 2 10 2 10 3 11 3 11 4 12 4 12 5 13 5 13 6 14 6 14 7 15 7 15 0 3 3 0 1 2 2 1 1 2 2 1 0 3 3 0 2 1 1 2 3 0 0 3 3 0 0 3 2 1 1 2 GM1o2_16=[1+D+D^4 1+D^2+D^3+D^4 ] = [25,23] (decimal) gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn2o4_4.fsm0000664000175000017500000000062112207440367024735 0ustar jcorganjcorgan4 4 16 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 13 3 14 12 1 15 2 7 10 4 9 11 6 8 5 This is generated by the 1/2 AWGN code (5 7) operated twice, ie, (xk+1 xki) [xk-1 xk-2] -> [xk+1 xki]. intermediate states: 00 21 02 23 00 21 02 23 10 31 12 33 10 31 12 33 output: 00 31 03 32 30 01 33 02 13 22 10 21 23 12 20 11 and in decimal: 0 13 3 14 12 1 15 2 7 10 4 9 11 6 8 5 gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/joint_4_16.fsm0000664000175000017500000000321212207440367025104 0ustar jcorganjcorgan4 64 16 0 8 32 40 0 8 32 40 1 9 33 41 1 9 33 41 2 10 34 42 2 10 34 42 3 11 35 43 3 11 35 43 4 12 36 44 4 12 36 44 5 13 37 45 5 13 37 45 6 14 38 46 6 14 38 46 7 15 39 47 7 15 39 47 0 8 32 40 0 8 32 40 1 9 33 41 1 9 33 41 2 10 34 42 2 10 34 42 3 11 35 43 3 11 35 43 4 12 36 44 4 12 36 44 5 13 37 45 5 13 37 45 6 14 38 46 6 14 38 46 7 15 39 47 7 15 39 47 16 24 48 56 16 24 48 56 17 25 49 57 17 25 49 57 18 26 50 58 18 26 50 58 19 27 51 59 19 27 51 59 20 28 52 60 20 28 52 60 21 29 53 61 21 29 53 61 22 30 54 62 22 30 54 62 23 31 55 63 23 31 55 63 16 24 48 56 16 24 48 56 17 25 49 57 17 25 49 57 18 26 50 58 18 26 50 58 19 27 51 59 19 27 51 59 20 28 52 60 20 28 52 60 21 29 53 61 21 29 53 61 22 30 54 62 22 30 54 62 23 31 55 63 23 31 55 63 0 3 12 15 3 0 15 12 1 2 13 14 2 1 14 13 1 2 13 14 2 1 14 13 0 3 12 15 3 0 15 12 2 1 14 13 1 2 13 14 3 0 15 12 0 3 12 15 3 0 15 12 0 3 12 15 2 1 14 13 1 2 13 14 12 15 0 3 15 12 3 0 13 14 1 2 14 13 2 1 13 14 1 2 14 13 2 1 12 15 0 3 15 12 3 0 14 13 2 1 13 14 1 2 15 12 3 0 12 15 0 3 15 12 3 0 12 15 0 3 14 13 2 1 13 14 1 2 4 7 8 11 7 4 11 8 5 6 9 10 6 5 10 9 5 6 9 10 6 5 10 9 4 7 8 11 7 4 11 8 6 5 10 9 5 6 9 10 7 4 11 8 4 7 8 11 7 4 11 8 4 7 8 11 6 5 10 9 5 6 9 10 8 11 4 7 11 8 7 4 9 10 5 6 10 9 6 5 9 10 5 6 10 9 6 5 8 11 4 7 11 8 7 4 10 9 6 5 9 10 5 6 11 8 7 4 8 11 4 7 11 8 7 4 8 11 4 7 10 9 6 5 9 10 5 6 This is the joint trellis of two trellises described in awgn1o2_4.fsm and awgn1o2_16.fsm It is useful for application of joint decoding... It can be generated in python as follows: > import trellis > f1=trellis.fsm('awgn1o2_4.fsm') > f2=trellis.fsm('awgn1o2_16.fsm') > f=trellis.fsm(f1,f2) > f.write_fsm_txt('joint_4_16.fsm') gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn2o3_16.fsm0000664000175000017500000000167112207440367025025 0ustar jcorganjcorgan4 16 8 0 8 4 12 0 8 4 12 0 8 4 12 0 8 4 12 1 9 5 13 1 9 5 13 1 9 5 13 1 9 5 13 2 10 6 14 2 10 6 14 2 10 6 14 2 10 6 14 3 11 7 15 3 11 7 15 3 11 7 15 3 11 7 15 0 1 7 6 6 7 1 0 3 2 4 5 5 4 2 3 2 3 5 4 4 5 3 2 1 0 6 7 7 6 0 1 4 5 3 2 2 3 5 4 7 6 0 1 1 0 6 7 6 7 1 0 0 1 7 6 5 4 2 3 3 2 4 5 2/3 code generated from the awgn 1/2 code with 16 states and puncturing the 4th bit. d_free= gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn1o2_4.fsm0000664000175000017500000000017412207440367024735 0ustar jcorganjcorgan2 4 4 0 2 0 2 1 3 1 3 0 3 3 0 1 2 2 1 AWGN CC from Proakis-Salehi pg 779 GM1o2_4=[1+D^2, 1+D+D^2] = [5, 7] (in decimal); gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/simple.fsm0000664000175000017500000000016112207440367024521 0ustar jcorganjcorgan1 4 1 1 2 3 0 0 0 0 0 essentially this fsm has no inputs and no outputs; it just cycles through all 4 states. gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn1o2_8.fsm0000664000175000017500000000040412207440367024735 0ustar jcorganjcorgan2 8 4 0 4 0 4 1 5 1 5 2 6 2 6 3 7 3 7 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 1/2 8-state code (Proakis pg. 493) GM1o2_8=[ 1+D+D^3 1+D+D^2+D^3] =[13 , 15] (decimal) gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn2o3_8.fsm0000664000175000017500000000102012207440367024732 0ustar jcorganjcorgan4 8 8 0 4 2 6 0 4 2 6 0 4 2 6 0 4 2 6 1 5 3 7 1 5 3 7 1 5 3 7 1 5 3 7 0 1 7 6 6 7 1 0 3 2 4 5 5 4 2 3 6 7 1 0 0 1 7 6 5 4 2 3 3 2 4 5 This is generated by the 1/2 8-state AWGN code (15 17) by puncturing the fourth bit. --> d_free=??? gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/joint_16_16.fsm0000664000175000017500000001434712207440367025202 0ustar jcorganjcorgan4 256 16 0 8 128 136 0 8 128 136 1 9 129 137 1 9 129 137 2 10 130 138 2 10 130 138 3 11 131 139 3 11 131 139 4 12 132 140 4 12 132 140 5 13 133 141 5 13 133 141 6 14 134 142 6 14 134 142 7 15 135 143 7 15 135 143 0 8 128 136 0 8 128 136 1 9 129 137 1 9 129 137 2 10 130 138 2 10 130 138 3 11 131 139 3 11 131 139 4 12 132 140 4 12 132 140 5 13 133 141 5 13 133 141 6 14 134 142 6 14 134 142 7 15 135 143 7 15 135 143 16 24 144 152 16 24 144 152 17 25 145 153 17 25 145 153 18 26 146 154 18 26 146 154 19 27 147 155 19 27 147 155 20 28 148 156 20 28 148 156 21 29 149 157 21 29 149 157 22 30 150 158 22 30 150 158 23 31 151 159 23 31 151 159 16 24 144 152 16 24 144 152 17 25 145 153 17 25 145 153 18 26 146 154 18 26 146 154 19 27 147 155 19 27 147 155 20 28 148 156 20 28 148 156 21 29 149 157 21 29 149 157 22 30 150 158 22 30 150 158 23 31 151 159 23 31 151 159 32 40 160 168 32 40 160 168 33 41 161 169 33 41 161 169 34 42 162 170 34 42 162 170 35 43 163 171 35 43 163 171 36 44 164 172 36 44 164 172 37 45 165 173 37 45 165 173 38 46 166 174 38 46 166 174 39 47 167 175 39 47 167 175 32 40 160 168 32 40 160 168 33 41 161 169 33 41 161 169 34 42 162 170 34 42 162 170 35 43 163 171 35 43 163 171 36 44 164 172 36 44 164 172 37 45 165 173 37 45 165 173 38 46 166 174 38 46 166 174 39 47 167 175 39 47 167 175 48 56 176 184 48 56 176 184 49 57 177 185 49 57 177 185 50 58 178 186 50 58 178 186 51 59 179 187 51 59 179 187 52 60 180 188 52 60 180 188 53 61 181 189 53 61 181 189 54 62 182 190 54 62 182 190 55 63 183 191 55 63 183 191 48 56 176 184 48 56 176 184 49 57 177 185 49 57 177 185 50 58 178 186 50 58 178 186 51 59 179 187 51 59 179 187 52 60 180 188 52 60 180 188 53 61 181 189 53 61 181 189 54 62 182 190 54 62 182 190 55 63 183 191 55 63 183 191 64 72 192 200 64 72 192 200 65 73 193 201 65 73 193 201 66 74 194 202 66 74 194 202 67 75 195 203 67 75 195 203 68 76 196 204 68 76 196 204 69 77 197 205 69 77 197 205 70 78 198 206 70 78 198 206 71 79 199 207 71 79 199 207 64 72 192 200 64 72 192 200 65 73 193 201 65 73 193 201 66 74 194 202 66 74 194 202 67 75 195 203 67 75 195 203 68 76 196 204 68 76 196 204 69 77 197 205 69 77 197 205 70 78 198 206 70 78 198 206 71 79 199 207 71 79 199 207 80 88 208 216 80 88 208 216 81 89 209 217 81 89 209 217 82 90 210 218 82 90 210 218 83 91 211 219 83 91 211 219 84 92 212 220 84 92 212 220 85 93 213 221 85 93 213 221 86 94 214 222 86 94 214 222 87 95 215 223 87 95 215 223 80 88 208 216 80 88 208 216 81 89 209 217 81 89 209 217 82 90 210 218 82 90 210 218 83 91 211 219 83 91 211 219 84 92 212 220 84 92 212 220 85 93 213 221 85 93 213 221 86 94 214 222 86 94 214 222 87 95 215 223 87 95 215 223 96 104 224 232 96 104 224 232 97 105 225 233 97 105 225 233 98 106 226 234 98 106 226 234 99 107 227 235 99 107 227 235 100 108 228 236 100 108 228 236 101 109 229 237 101 109 229 237 102 110 230 238 102 110 230 238 103 111 231 239 103 111 231 239 96 104 224 232 96 104 224 232 97 105 225 233 97 105 225 233 98 106 226 234 98 106 226 234 99 107 227 235 99 107 227 235 100 108 228 236 100 108 228 236 101 109 229 237 101 109 229 237 102 110 230 238 102 110 230 238 103 111 231 239 103 111 231 239 112 120 240 248 112 120 240 248 113 121 241 249 113 121 241 249 114 122 242 250 114 122 242 250 115 123 243 251 115 123 243 251 116 124 244 252 116 124 244 252 117 125 245 253 117 125 245 253 118 126 246 254 118 126 246 254 119 127 247 255 119 127 247 255 112 120 240 248 112 120 240 248 113 121 241 249 113 121 241 249 114 122 242 250 114 122 242 250 115 123 243 251 115 123 243 251 116 124 244 252 116 124 244 252 117 125 245 253 117 125 245 253 118 126 246 254 118 126 246 254 119 127 247 255 119 127 247 255 0 3 12 15 3 0 15 12 1 2 13 14 2 1 14 13 1 2 13 14 2 1 14 13 0 3 12 15 3 0 15 12 2 1 14 13 1 2 13 14 3 0 15 12 0 3 12 15 3 0 15 12 0 3 12 15 2 1 14 13 1 2 13 14 12 15 0 3 15 12 3 0 13 14 1 2 14 13 2 1 13 14 1 2 14 13 2 1 12 15 0 3 15 12 3 0 14 13 2 1 13 14 1 2 15 12 3 0 12 15 0 3 15 12 3 0 12 15 0 3 14 13 2 1 13 14 1 2 4 7 8 11 7 4 11 8 5 6 9 10 6 5 10 9 5 6 9 10 6 5 10 9 4 7 8 11 7 4 11 8 6 5 10 9 5 6 9 10 7 4 11 8 4 7 8 11 7 4 11 8 4 7 8 11 6 5 10 9 5 6 9 10 8 11 4 7 11 8 7 4 9 10 5 6 10 9 6 5 9 10 5 6 10 9 6 5 8 11 4 7 11 8 7 4 10 9 6 5 9 10 5 6 11 8 7 4 8 11 4 7 11 8 7 4 8 11 4 7 10 9 6 5 9 10 5 6 4 7 8 11 7 4 11 8 5 6 9 10 6 5 10 9 5 6 9 10 6 5 10 9 4 7 8 11 7 4 11 8 6 5 10 9 5 6 9 10 7 4 11 8 4 7 8 11 7 4 11 8 4 7 8 11 6 5 10 9 5 6 9 10 8 11 4 7 11 8 7 4 9 10 5 6 10 9 6 5 9 10 5 6 10 9 6 5 8 11 4 7 11 8 7 4 10 9 6 5 9 10 5 6 11 8 7 4 8 11 4 7 11 8 7 4 8 11 4 7 10 9 6 5 9 10 5 6 0 3 12 15 3 0 15 12 1 2 13 14 2 1 14 13 1 2 13 14 2 1 14 13 0 3 12 15 3 0 15 12 2 1 14 13 1 2 13 14 3 0 15 12 0 3 12 15 3 0 15 12 0 3 12 15 2 1 14 13 1 2 13 14 12 15 0 3 15 12 3 0 13 14 1 2 14 13 2 1 13 14 1 2 14 13 2 1 12 15 0 3 15 12 3 0 14 13 2 1 13 14 1 2 15 12 3 0 12 15 0 3 15 12 3 0 12 15 0 3 14 13 2 1 13 14 1 2 8 11 4 7 11 8 7 4 9 10 5 6 10 9 6 5 9 10 5 6 10 9 6 5 8 11 4 7 11 8 7 4 10 9 6 5 9 10 5 6 11 8 7 4 8 11 4 7 11 8 7 4 8 11 4 7 10 9 6 5 9 10 5 6 4 7 8 11 7 4 11 8 5 6 9 10 6 5 10 9 5 6 9 10 6 5 10 9 4 7 8 11 7 4 11 8 6 5 10 9 5 6 9 10 7 4 11 8 4 7 8 11 7 4 11 8 4 7 8 11 6 5 10 9 5 6 9 10 12 15 0 3 15 12 3 0 13 14 1 2 14 13 2 1 13 14 1 2 14 13 2 1 12 15 0 3 15 12 3 0 14 13 2 1 13 14 1 2 15 12 3 0 12 15 0 3 15 12 3 0 12 15 0 3 14 13 2 1 13 14 1 2 0 3 12 15 3 0 15 12 1 2 13 14 2 1 14 13 1 2 13 14 2 1 14 13 0 3 12 15 3 0 15 12 2 1 14 13 1 2 13 14 3 0 15 12 0 3 12 15 3 0 15 12 0 3 12 15 2 1 14 13 1 2 13 14 12 15 0 3 15 12 3 0 13 14 1 2 14 13 2 1 13 14 1 2 14 13 2 1 12 15 0 3 15 12 3 0 14 13 2 1 13 14 1 2 15 12 3 0 12 15 0 3 15 12 3 0 12 15 0 3 14 13 2 1 13 14 1 2 0 3 12 15 3 0 15 12 1 2 13 14 2 1 14 13 1 2 13 14 2 1 14 13 0 3 12 15 3 0 15 12 2 1 14 13 1 2 13 14 3 0 15 12 0 3 12 15 3 0 15 12 0 3 12 15 2 1 14 13 1 2 13 14 8 11 4 7 11 8 7 4 9 10 5 6 10 9 6 5 9 10 5 6 10 9 6 5 8 11 4 7 11 8 7 4 10 9 6 5 9 10 5 6 11 8 7 4 8 11 4 7 11 8 7 4 8 11 4 7 10 9 6 5 9 10 5 6 4 7 8 11 7 4 11 8 5 6 9 10 6 5 10 9 5 6 9 10 6 5 10 9 4 7 8 11 7 4 11 8 6 5 10 9 5 6 9 10 7 4 11 8 4 7 8 11 7 4 11 8 4 7 8 11 6 5 10 9 5 6 9 10 This is the joint trellis of two trellises described in awgn1o2_16.fsm It is useful for application of joint decoding... It can be generated in python as follows: > import trellis > f1=trellis.fsm('awgn1o2_16.fsm') > f=trellis.fsm(f1,f1) > f.write_fsm_txt('joint_16_16.fsm') gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn2o3_4.fsm0000664000175000017500000000051212207440367024733 0ustar jcorganjcorgan4 4 8 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 7 4 3 3 4 7 0 5 2 1 6 6 1 2 5 I don't remeber how I generated this one... it is a bit better than awgn2o3_4_msb and worse than awgn2o3_4_msbG. gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn1o2_128.fsm0000664000175000017500000000263012207440367025103 0ustar jcorganjcorgan2 128 4 0 64 0 64 1 65 1 65 2 66 2 66 3 67 3 67 4 68 4 68 5 69 5 69 6 70 6 70 7 71 7 71 8 72 8 72 9 73 9 73 10 74 10 74 11 75 11 75 12 76 12 76 13 77 13 77 14 78 14 78 15 79 15 79 16 80 16 80 17 81 17 81 18 82 18 82 19 83 19 83 20 84 20 84 21 85 21 85 22 86 22 86 23 87 23 87 24 88 24 88 25 89 25 89 26 90 26 90 27 91 27 91 28 92 28 92 29 93 29 93 30 94 30 94 31 95 31 95 32 96 32 96 33 97 33 97 34 98 34 98 35 99 35 99 36 100 36 100 37 101 37 101 38 102 38 102 39 103 39 103 40 104 40 104 41 105 41 105 42 106 42 106 43 107 43 107 44 108 44 108 45 109 45 109 46 110 46 110 47 111 47 111 48 112 48 112 49 113 49 113 50 114 50 114 51 115 51 115 52 116 52 116 53 117 53 117 54 118 54 118 55 119 55 119 56 120 56 120 57 121 57 121 58 122 58 122 59 123 59 123 60 124 60 124 61 125 61 125 62 126 62 126 63 127 63 127 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 1 2 2 1 0 3 3 0 2 1 1 2 3 0 0 3 1 2 2 1 0 3 3 0 2 1 1 2 3 0 0 3 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 2 1 1 2 3 0 0 3 1 2 2 1 0 3 3 0 3 0 0 3 2 1 1 2 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 0 3 3 0 1 2 2 1 2 1 1 2 3 0 0 3 1 2 2 1 0 3 3 0 2 1 1 2 3 0 0 3 1 2 2 1 0 3 3 0 3 0 0 3 2 1 1 2 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 0 3 3 0 1 2 2 1 2 1 1 2 3 0 0 3 1 2 2 1 0 3 3 0 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 1 2 2 1 0 3 3 0 2 1 1 2 3 0 0 3 1 2 2 1 0 3 3 0 2 1 1 2 3 0 0 3 0 3 3 0 1 2 2 1 3 0 0 3 2 1 1 2 GM1o2_128=[1+D+D^2+D^5+D^7 1+D^3+D^4+D^5+D^6+D^7] =[11100101 10011111] =[229 159] gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/awgn2o3_4_msb.fsm0000664000175000017500000000120612207440367025575 0ustar jcorganjcorgan4 4 8 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 5 3 6 4 1 7 2 7 2 4 1 3 6 0 5 This is generated by the 1/2 AWGN code (5 7) operated twice, ie, (xk+1 xki) [xk-1 xk-2] -> [xk+1 xki]. We also puncture the first (MSB) bit. This code is worse than awgn2o3_4_msbG and slightly worse than awgn2o3_4, BUT seems to be a good innner code for sctcm (with 8PSK natural). intermediate states: 00 21 02 23 00 21 02 23 10 31 12 33 10 31 12 33 output before puncturing: 00 31 03 32 30 01 33 02 13 22 10 21 23 12 20 11 output after punturing the MSB: 00 11 03 12 10 01 13 02 13 02 10 01 03 12 00 11 and in decimal: 0 5 3 6 4 1 7 2 7 2 4 1 3 6 0 5 gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/irregular.fsm0000664000175000017500000000017312207440367025227 0ustar jcorganjcorgan2 2 2 0 0 0 1 0 1 0 1 useless irregular FSM for testing. state 0 has 3 incoming edges and state 1 has 1 incoming edge. gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_files/rep3.fsm0000664000175000017500000000020212207440367024075 0ustar jcorganjcorgan2 1 8 0 0 0 7 1/3 repetition code (with binary input). There is only one state, since this is essentially a memoryless system. gnuradio-3.7.2.1/gr-trellis/examples/python/README0000664000175000017500000000253212207440367021436 0ustar jcorganjcorganHere we have several test programs for use with the gr-trellis implementation. Documentation can be found in http://gnuradio.utah.edu/svn/gnuradio/trunk/gr-trellis/doc/gr-trellis.html fsm_utils.py contains several useful functions. fsm_files is a directory with some FSM definitions If you just want to see what these programs do run them; in your terminal you will see something like this: $ ./test_tcm.py --esn0 6.0 --repetitions 1000 100 98 9.80e-01 102400 9 8.79e-05 200 198 9.90e-01 204800 20 9.77e-05 300 298 9.93e-01 307200 40 1.30e-04 400 398 9.95e-01 409600 1074 2.62e-03 500 498 9.96e-01 512000 1081 2.11e-03 600 598 9.97e-01 614400 1090 1.77e-03 700 698 9.97e-01 716800 1097 1.53e-03 800 798 9.98e-01 819200 1107 1.35e-03 900 898 9.98e-01 921600 1120 1.22e-03 1000 998 9.98e-01 1024000 1129 1.10e-03 1000 998 9.98e-01 1024000 1129 1.10e-03 which gives you information about the: number of transmitted packets number of packets in error estimated packet error rate number of transmitted shorts (or symbols, or bits, depending on the specific program) number of shorts (or symbols, or bits) in error estimated short (or symbol, or bit) error rate for instance, the final number 1.10e-03 is the error rate estimate by sending 1000 packets of 1024 shorts each, using an 1/2 4-state convolutional code and QPSK modulation through an AWGN with Es/N0 = 6.0 dB gnuradio-3.7.2.1/gr-trellis/examples/python/test_viterbi_equalization1.py0000775000175000017500000001011112207440367026474 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, filter, blocks from gnuradio import eng_notation import math import sys import random import fsm_utils try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,seed): tb = gr.top_block () L = len(channel) # TX # this for loop is TOO slow in python!!! packet = [0]*(K+2*L) random.seed(seed) for i in range(len(packet)): packet[i] = random.randint(0, 2**bitspersymbol - 1) # random symbols for i in range(L): # first/last L symbols set to 0 packet[i] = 0 packet[len(packet)-i-1] = 0 src = blocks.vector_source_s(packet,False) mod = digital.chunks_to_symbols_sf(modulation[1],modulation[0]) # CHANNEL isi = filter.fir_filter_fff(1,channel) add = blockss.add_ff() noise = analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed) # RX skip = blocks.skiphead(gr.sizeof_float, L) # skip the first L samples since you know they are coming from the L zero symbols #metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi #va = trellis.viterbi_s(f,K+L,-1,0) # Put -1 if the Initial/Final states are not set. va = trellis.viterbi_combined_fs(f,K+L,0,0,dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # using viterbi_combined_fs instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application... dst = blocks.vector_sink_s() tb.connect (src,mod) tb.connect (mod,isi,(add,0)) tb.connect (noise,(add,1)) #tb.connect (add,metrics) #tb.connect (metrics,va,dst) tb.connect (add,skip,va,dst) tb.run() data = dst.data() ntotal = len(data) - L nright=0 for i in range(ntotal): if packet[i+L]==data[i]: nright=nright+1 #else: #print "Error in ", i return (ntotal,ntotal-nright) def main(args): nargs = len (args) if nargs == 2: esn0_db=float(args[0]) rep=int(args[1]) else: sys.stderr.write ('usage: test_viterbi_equalization1.py Es/No_db repetitions\n') sys.exit (1) # system parameters Kb=128*16 # packet size in bits (multiple of 16) modulation = fsm_utils.pam4 # see fsm_utlis.py for available predefined modulations channel = fsm_utils.c_channel # see fsm_utlis.py for available predefined test channels f=trellis.fsm(len(modulation[1]),len(channel)) # generate the FSM automatically bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps tot_channel = fsm_utils.make_isi_lookup(modulation,channel,True) # generate the lookup table (normalize energy to 1) dimensionality = tot_channel[0] tot_constellation = tot_channel[1] N0=pow(10.0,-esn0_db/10.0); # noise variance if len(tot_constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and lookup table size.\n') sys.exit (1) tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,channel,modulation,dimensionality,tot_constellation,N0,-long(666+i)) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or symbol) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main (sys.argv[1:]) gnuradio-3.7.2.1/gr-trellis/examples/python/test_tcm_parallel.py0000775000175000017500000001112712207440367024631 0ustar jcorganjcorgan#!/usr/bin/env python from gnuradio import gr from gnuradio import trellis, digital, blocks from gnuradio import eng_notation import math import sys import fsm_utils from gnuradio.eng_option import eng_option from optparse import OptionParser try: from gnuradio import analog except ImportError: sys.stderr.write("Error: Program requires gr-analog.\n") sys.exit(1) def run_test (f,Kb,bitspersymbol,K,dimensionality,constellation,N0,seed,P): tb = gr.top_block () # TX src = blocks.lfsr_32k_source_s() src_head = blocks.head(gr.sizeof_short,Kb/16*P) # packet size in shorts s2fsmi=blocks.packed_to_unpacked_ss(bitspersymbol,gr.GR_MSB_FIRST) # unpack shorts to symbols compatible with the FSM input cardinality s2p = blocks.stream_to_streams(gr.sizeof_short,P) # serial to parallel enc = trellis.encoder_ss(f,0) # initiali state = 0 mod = digital.chunks_to_symbols_sf(constellation,dimensionality) # CHANNEL add=[] noise=[] for i in range(P): add.append(blocks.add_ff()) noise.append(analog.noise_source_f(analog.GR_GAUSSIAN,math.sqrt(N0/2),seed)) # RX metrics = trellis.metrics_f(f.O(),dimensionality,constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi va = trellis.viterbi_s(f,K,0,-1) # Put -1 if the Initial/Final states are not set. p2s = block.streams_to_stream(gr.sizeof_short,P) # parallel to serial fsmi2s=blocks.unpacked_to_packed_ss(bitspersymbol,gr.GR_MSB_FIRST) # pack FSM input symbols to shorts dst = blocks.check_lfsr_32k_s() tb.connect (src,src_head,s2fsmi,s2p) for i in range(P): tb.connect ((s2p,i),(enc,i),(mod,i)) tb.connect ((mod,i),(add[i],0)) tb.connect (noise[i],(add[i],1)) tb.connect (add[i],(metrics,i)) tb.connect ((metrics,i),(va,i),(p2s,i)) tb.connect (p2s,fsmi2s,dst) tb.run() # A bit of cheating: run the program once and print the # final encoder state. # Then put it as the last argument in the viterbi block #print "final state = " , enc.ST() ntotal = dst.ntotal () nright = dst.nright () runlength = dst.runlength () return (ntotal,ntotal-nright) def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-f", "--fsm_file", type="string", default="fsm_files/awgn1o2_4.fsm", help="Filename containing the fsm specification, e.g. -f fsm_files/awgn1o2_4.fsm (default=fsm_files/awgn1o2_4.fsm)") parser.add_option("-e", "--esn0", type="eng_float", default=10.0, help="Symbol energy to noise PSD level ratio in dB, e.g., -e 10.0 (default=10.0)") parser.add_option("-r", "--repetitions", type="int", default=100, help="Number of packets to be generated for the simulation, e.g., -r 100 (default=100)") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() raise SystemExit, 1 fname=options.fsm_file esn0_db=float(options.esn0) rep=int(options.repetitions) # system parameters f=trellis.fsm(fname) # get the FSM specification from a file P=4 # how many parallel streams? Kb=1024*16 # packet size in bits (make it multiple of 16 so it can be packed in a short) bitspersymbol = int(round(math.log(f.I())/math.log(2))) # bits per FSM input symbol K=Kb/bitspersymbol # packet size in trellis steps modulation = fsm_utils.psk4 # see fsm_utlis.py for available predefined modulations dimensionality = modulation[0] constellation = modulation[1] if len(constellation)/dimensionality != f.O(): sys.stderr.write ('Incompatible FSM output cardinality and modulation size.\n') sys.exit (1) # calculate average symbol energy Es = 0 for i in range(len(constellation)): Es = Es + constellation[i]**2 Es = Es / (len(constellation)/dimensionality) N0=Es/pow(10.0,esn0_db/10.0); # calculate noise variance tot_s=0 # total number of transmitted shorts terr_s=0 # total number of shorts in error terr_p=0 # total number of packets in error for i in range(rep): (s,e)=run_test(f,Kb,bitspersymbol,K,dimensionality,constellation,N0,-long(666+i),P) # run experiment with different seed to get different noise realizations tot_s=tot_s+s terr_s=terr_s+e terr_p=terr_p+(terr_s!=0) if ((i+1)%100==0) : # display progress print i+1,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) # estimate of the (short or bit) error rate print rep,terr_p, '%.2e' % ((1.0*terr_p)/(i+1)),tot_s,terr_s, '%.2e' % ((1.0*terr_s)/tot_s) if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-trellis/examples/python/fsm_utils.py0000775000175000017500000001557612207440367023154 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import re import math import sys import operator import numpy from gnuradio import trellis try: import scipy.linalg except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) ###################################################################### # Decimal to any base conversion. # Convert 'num' to a list of 'l' numbers representing 'num' # to base 'base' (most significant symbol first). ###################################################################### def dec2base(num,base,l): s=range(l) n=num for i in range(l): s[l-i-1]=n%base n=int(n/base) if n!=0: print 'Number ', num, ' requires more than ', l, 'digits.' return s ###################################################################### # Conversion from any base to decimal. # Convert a list 's' of symbols to a decimal number # (most significant symbol first) ###################################################################### def base2dec(s,base): num=0 for i in range(len(s)): num=num*base+s[i] return num ###################################################################### # Automatically generate the lookup table that maps the FSM outputs # to channel inputs corresponding to a channel 'channel' and a modulation # 'mod'. Optional normalization of channel to unit energy. # This table is used by the 'metrics' block to translate # channel outputs to metrics for use with the Viterbi algorithm. # Limitations: currently supports only one-dimensional modulations. ###################################################################### def make_isi_lookup(mod,channel,normalize): dim=mod[0] constellation = mod[1] if normalize: p = 0 for i in range(len(channel)): p = p + channel[i]**2 for i in range(len(channel)): channel[i] = channel[i]/math.sqrt(p) lookup=range(len(constellation)**len(channel)) for o in range(len(constellation)**len(channel)): ss=dec2base(o,len(constellation),len(channel)) ll=0 for i in range(len(channel)): ll=ll+constellation[ss[i]]*channel[i] lookup[o]=ll return (1,lookup) ###################################################################### # Automatically generate the signals appropriate for CPM # decomposition. # This decomposition is based on the paper by B. Rimoldi # "A decomposition approach to CPM", IEEE Trans. Info Theory, March 1988 # See also my own notes at http://www.eecs.umich.edu/~anastas/docs/cpm.pdf ###################################################################### def make_cpm_signals(K,P,M,L,q,frac): Q=numpy.size(q)/L h=(1.0*K)/P f0=-h*(M-1)/2 dt=0.0; # maybe start at t=0.5 t=(dt+numpy.arange(0,Q))/Q qq=numpy.zeros(Q) for m in range(L): qq=qq + q[m*Q:m*Q+Q] w=math.pi*h*(M-1)*t-2*math.pi*h*(M-1)*qq+math.pi*h*(L-1)*(M-1) X=(M**L)*P PSI=numpy.empty((X,Q)) for x in range(X): xv=dec2base(x/P,M,L) xv=numpy.append(xv, x%P) qq1=numpy.zeros(Q) for m in range(L): qq1=qq1+xv[m]*q[m*Q:m*Q+Q] psi=2*math.pi*h*xv[-1]+4*math.pi*h*qq1+w #print psi PSI[x]=psi PSI = numpy.transpose(PSI) SS=numpy.exp(1j*PSI) # contains all signals as columns #print SS # Now we need to orthogonalize the signals F = scipy.linalg.orth(SS) # find an orthonormal basis for SS #print numpy.dot(numpy.transpose(F.conjugate()),F) # check for orthonormality S = numpy.dot(numpy.transpose(F.conjugate()),SS) #print F #print S # We only want to keep those dimensions that contain most # of the energy of the overall constellation (eg, frac=0.9 ==> 90%) # evaluate mean energy in each dimension E=numpy.sum(numpy.absolute(S)**2,axis=1)/Q E=E/numpy.sum(E) #print E Es = -numpy.sort(-E) Esi = numpy.argsort(-E) #print Es #print Esi Ecum=numpy.cumsum(Es) #print Ecum v0=numpy.searchsorted(Ecum,frac) N = v0+1 #print v0 #print Esi[0:v0+1] Ff=numpy.transpose(numpy.transpose(F)[Esi[0:v0+1]]) #print Ff Sf = S[Esi[0:v0+1]] #print Sf return (f0,SS,S,F,Sf,Ff,N) #return f0 ###################################################################### # A list of common modulations. # Format: (dimensionality,constellation) ###################################################################### pam2 = (1,[-1, 1]) pam4 = (1,[-3, -1, 3, 1]) # includes Gray mapping pam8 = (1,[-7, -5, -3, -1, 1, 3, 5, 7]) psk4=(2,[1, 0, \ 0, 1, \ 0, -1,\ -1, 0]) # includes Gray mapping psk8=(2,[math.cos(2*math.pi*0/8), math.sin(2*math.pi*0/8), \ math.cos(2*math.pi*1/8), math.sin(2*math.pi*1/8), \ math.cos(2*math.pi*2/8), math.sin(2*math.pi*2/8), \ math.cos(2*math.pi*3/8), math.sin(2*math.pi*3/8), \ math.cos(2*math.pi*4/8), math.sin(2*math.pi*4/8), \ math.cos(2*math.pi*5/8), math.sin(2*math.pi*5/8), \ math.cos(2*math.pi*6/8), math.sin(2*math.pi*6/8), \ math.cos(2*math.pi*7/8), math.sin(2*math.pi*7/8)]) orth2 = (2,[1, 0, \ 0, 1]) orth4=(4,[1, 0, 0, 0, \ 0, 1, 0, 0, \ 0, 0, 1, 0, \ 0, 0, 0, 1]) ###################################################################### # A list of channels to be tested ###################################################################### # C test channel (J. Proakis, Digital Communications, McGraw-Hill Inc., 2001) c_channel = [0.227, 0.460, 0.688, 0.460, 0.227] if __name__ == '__main__': f1=trellis.fsm('fsm_files/awgn1o2_4.fsm') #f2=trellis.fsm('fsm_files/awgn2o3_4.fsm') #print f1.I(), f1.S(), f1.O() #print f1.NS() #print f1.OS() #print f2.I(), f2.S(), f2.O() #print f2.NS() #print f2.OS() ##f1.write_trellis_svg('f1.svg',4) #f2.write_trellis_svg('f2.svg',4) #f=fsm_concatenate(f1,f2) #f=fsm_radix(f1,2) #print "----------\n" #print f.I(), f.S(), f.O() #print f.NS() #print f.OS() #f.write_trellis_svg('f.svg',4) q=numpy.arange(0,8)/(2.0*8) (f0,SS,S,F,Sf,Ff,N) = make_cpm_signals(1,2,2,1,q,0.99) gnuradio-3.7.2.1/gr-video-sdl/0000755000175000017500000000000012207440367015623 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/CMakeLists.txt0000664000175000017500000000661612207440367020376 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) find_package(SDL) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-video-sdl" ENABLE_GR_VIDEO_SDL SDL_FOUND Boost_FOUND ENABLE_GNURADIO_RUNTIME ) GR_SET_GLOBAL(GR_VIDEO_SDL_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_VIDEO_SDL) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_VIDEO_SDL_DESCRIPTION "GNU Radio Video SDL Blocks") CPACK_COMPONENT("video_sdl_runtime" GROUP "Video SDL" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("video_sdl_devel" GROUP "Video SDL" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("video_sdl_python" GROUP "Video SDL" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;video_sdl_runtime" ) CPACK_COMPONENT("video_sdl_swig" GROUP "Video SDL" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;video_sdl_python;video_sdl_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/video_sdl) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/video_sdl) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-video-sdl.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-video-sdl.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-video-sdl.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "video_sdl_devel" ) endif(ENABLE_GR_VIDEO_SDL) gnuradio-3.7.2.1/gr-video-sdl/include/0000775000175000017500000000000012207440367017250 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/include/gnuradio/0000775000175000017500000000000012207440367021060 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/include/gnuradio/video_sdl/0000775000175000017500000000000012207440367023030 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/include/gnuradio/video_sdl/CMakeLists.txt0000664000175000017500000000210412207440367025565 0ustar jcorganjcorgan# Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h sink_s.h sink_uc.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/video_sdl COMPONENT "video_sdl_devel" ) gnuradio-3.7.2.1/gr-video-sdl/include/gnuradio/video_sdl/sink_s.h0000664000175000017500000000335212207440367024472 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VIDEO_SDL_SINK_S_H #define INCLUDED_VIDEO_SDL_SINK_S_H #include #include namespace gr { namespace video_sdl { /*! * \brief video sink using SDL * * input signature is one, two or three streams of signed short. * One stream: stream is grey (Y) * two streems: first is grey (Y), second is alternating U and V * Three streams: first is grey (Y), second is U, third is V * Input samples must be in the range [0,255]. */ class VIDEO_SDL_API sink_s : virtual public sync_block { public: // gr::video_sdl::sink_s::sptr typedef boost::shared_ptr sptr; static sptr make(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height); }; } /* namespace video_sdl */ } /* namespace gr */ #endif /* INCLUDED_VIDEO_SDL_SINK_S_H */ gnuradio-3.7.2.1/gr-video-sdl/include/gnuradio/video_sdl/sink_uc.h0000664000175000017500000000335112207440367024636 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VIDEO_SDL_SINK_UC_H #define INCLUDED_VIDEO_SDL_SINK_UC_H #include #include namespace gr { namespace video_sdl { /*! * \brief video sink using SDL * * input signature is one, two or three streams of uchar. * One stream: stream is grey (Y) * two streems: first is grey (Y), second is alternating U and V * Three streams: first is grey (Y), second is U, third is V * Input samples must be in the range [0,255]. */ class VIDEO_SDL_API sink_uc : virtual public sync_block { public: // gr::video_sdl::sink_uc::sptr typedef boost::shared_ptr sptr; static sptr make(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height); }; } /* namespace video_sdl */ } /* namespace gr */ #endif /* INCLUDED_VIDEO_SDL_SINK_UC_H */ gnuradio-3.7.2.1/gr-video-sdl/include/gnuradio/video_sdl/api.h0000664000175000017500000000206112207440367023751 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VIDEO_SDL_API_H #define INCLUDED_VIDEO_SDL_API_H #include #ifdef gnuradio_video_sdl_EXPORTS # define VIDEO_SDL_API __GR_ATTR_EXPORT #else # define VIDEO_SDL_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_VIDEO_SDL_API_H */ gnuradio-3.7.2.1/gr-video-sdl/gnuradio-video-sdl.pc.in0000664000175000017500000000041612207440367022253 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-video-sdl Description: GNU Radio blocks for the SDL library Requires: gnuradio-runtime sdl Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-video-sdl Cflags: -I${includedir} gnuradio-3.7.2.1/gr-video-sdl/python/0000775000175000017500000000000012207440367017146 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/python/video_sdl/0000775000175000017500000000000012207440367021116 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/python/video_sdl/CMakeLists.txt0000664000175000017500000000333112207440367023656 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/video_sdl COMPONENT "video_sdl_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-video-sdl/python/video_sdl/qa_video_sdl.py0000775000175000017500000000236212207440367024127 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, video_sdl class test_video_sdl (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_000_nop (self): """Just see if we can import the module... They may not have video drivers, etc. Don't try to run anything""" pass if __name__ == '__main__': gr_unittest.run(test_video_sdl, "test_video_sdl.xml") gnuradio-3.7.2.1/gr-video-sdl/python/video_sdl/__init__.py0000664000175000017500000000216212207440367023230 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Blocks and utilities for Video SDL module ''' # The presence of this file turns this directory into a Python package import os try: from video_sdl_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from video_sdl_swig import * gnuradio-3.7.2.1/gr-video-sdl/lib/0000775000175000017500000000000012207440367016373 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/lib/sink_s_impl.cc0000664000175000017500000002521112207440367021212 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sink_s_impl.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace video_sdl { sink_s::sptr sink_s::make(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height) { return gnuradio::get_initial_sptr (new sink_s_impl(framerate, width, height,format, dst_width, dst_height)); } sink_s_impl::sink_s_impl(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height) : sync_block("video_sdl_sink_s", io_signature::make(1, 3, sizeof(short)), io_signature::make(0, 0, 0)), d_chunk_size(width*height), d_framerate(framerate), d_wanted_frametime_ms(0), d_width(width), d_height(height), d_dst_width(dst_width), d_dst_height(dst_height), d_format(format), d_current_line(0), d_screen(NULL), d_image(NULL), d_avg_delay(0.0), d_wanted_ticks(0) { if(framerate <= 0.0) d_wanted_frametime_ms = 0; //Go as fast as possible else d_wanted_frametime_ms = (int)(1000.0/framerate); if(dst_width < 0) d_dst_width = d_width; if(dst_height < 0) d_dst_height = d_height; if(0 == format) d_format = IMGFMT_YV12; atexit(SDL_Quit); //check if this is the way to do this if(SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "video_sdl::sink_s: Couldn't initialize SDL:" << SDL_GetError() << " \n SDL_Init(SDL_INIT_VIDEO) failed\n"; throw std::runtime_error("video_sdl::sink_s"); }; /* accept any depth */ d_screen = SDL_SetVideoMode(dst_width, dst_height, 0, SDL_SWSURFACE|SDL_RESIZABLE|SDL_ANYFORMAT);//SDL_DOUBLEBUF |SDL_SWSURFACE| SDL_HWSURFACE||SDL_FULLSCREEN if(d_screen == NULL) { std::cerr << "Unable to set SDL video mode: " << SDL_GetError() << "\n SDL_SetVideoMode() Failed \n"; exit(1); } if(d_image) { SDL_FreeYUVOverlay(d_image); } /* Initialize and create the YUV Overlay used for video out */ if(!(d_image = SDL_CreateYUVOverlay(d_width, d_height, SDL_YV12_OVERLAY, d_screen))) { std::cerr << "SDL: Couldn't create a YUV overlay: \n"<< SDL_GetError() << "\n"; throw std::runtime_error("video_sdl::sink_s"); } printf("SDL screen_mode %d bits-per-pixel\n", d_screen->format->BitsPerPixel); printf("SDL overlay_mode %i \n", d_image->format); d_chunk_size = std::min(1, 16384/width); //width*16; d_chunk_size = d_chunk_size*width; //d_chunk_size = (int) (width); set_output_multiple(d_chunk_size); /* Set the default playback area */ d_dst_rect.x = 0; d_dst_rect.y = 0; d_dst_rect.w = d_dst_width; d_dst_rect.h = d_dst_height; //clear the surface to grey if(SDL_LockYUVOverlay(d_image)) { std::cerr << "SDL: Couldn't lock YUV overlay: \n" << SDL_GetError() << "\n"; throw std::runtime_error("video_sdl::sink_s"); } memset(d_image->pixels[0], 128, d_image->pitches[0]*d_height); memset(d_image->pixels[1], 128, d_image->pitches[1]*d_height/2); memset(d_image->pixels[2], 128, d_image->pitches[2]*d_height/2); SDL_UnlockYUVOverlay( d_image ); } sink_s_impl::~sink_s_impl() { SDL_Quit(); } void sink_s_impl::copy_line_pixel_interleaved(unsigned char *dst_pixels_u, unsigned char *dst_pixels_v, const short * src_pixels, int src_width) { for(int i = 0; i < src_width; i++) { dst_pixels_u[i]=(unsigned char)src_pixels[i*2]; dst_pixels_v[i]=(unsigned char)src_pixels[i*2+1]; } } void sink_s_impl::copy_line_line_interleaved(unsigned char *dst_pixels_u, unsigned char *dst_pixels_v, const short * src_pixels, int src_width) { for(int i = 0; i < src_width; i++) { dst_pixels_u[i] = (unsigned char)src_pixels[i]; dst_pixels_v[i] = (unsigned char)src_pixels[i+src_width]; } for(int i = src_width; i < src_width*2; i++) { dst_pixels_v[i] = (unsigned char)src_pixels[i]; } } void sink_s_impl::copy_line_single_plane(unsigned char *dst_pixels, const short * src_pixels, int src_width) { for(int i = 0; i < src_width; i++) { dst_pixels[i] = (unsigned char)src_pixels[i]; } } void sink_s_impl::copy_line_single_plane_dec2(unsigned char *dst_pixels, const short * src_pixels, int src_width) { for(int i = 0, j = 0; i < src_width; i += 2, j++) { dst_pixels[j] = (unsigned char)src_pixels[i]; } } int sink_s_impl::copy_plane_to_surface(int plane,int noutput_items, const short * src_pixels) { const int first_dst_plane = (12 == plane || 1122 == plane) ? 1 : plane; const int second_dst_plane = (12 == plane || 1122 == plane) ? 2 : plane; int current_line = (0 == plane) ? d_current_line : d_current_line/2; unsigned char * dst_pixels = (unsigned char *)d_image->pixels[first_dst_plane]; dst_pixels =& dst_pixels[current_line*d_image->pitches[first_dst_plane]]; unsigned char * dst_pixels_2 = (unsigned char *)d_image->pixels[second_dst_plane]; dst_pixels_2 =& dst_pixels_2[current_line*d_image->pitches[second_dst_plane]]; int src_width = (0 == plane || 12 == plane || 1122 == plane) ? d_width:d_width/2; int noutput_items_produced = 0; int max_height = (0 == plane) ? d_height-1 : d_height/2-1; for(int i = 0; i < noutput_items; i += src_width) { //output one line at a time if(12==plane) { copy_line_pixel_interleaved(dst_pixels, dst_pixels_2, src_pixels, src_width); dst_pixels_2 += d_image->pitches[second_dst_plane]; } else if(1122 == plane) { copy_line_line_interleaved(dst_pixels, dst_pixels_2, src_pixels, src_width); dst_pixels_2 += d_image->pitches[second_dst_plane]; src_pixels += src_width; } else if(0==plane) copy_line_single_plane(dst_pixels, src_pixels, src_width); else /* 1==plane || 2==plane*/ copy_line_single_plane_dec2(dst_pixels, src_pixels, src_width); //decimate by two horizontally src_pixels += src_width; dst_pixels += d_image->pitches[first_dst_plane]; noutput_items_produced += src_width; current_line++; if(current_line > max_height) { //Start new frame //TODO, do this all in a seperate thread current_line=0; dst_pixels=d_image->pixels[first_dst_plane]; dst_pixels_2=d_image->pixels[second_dst_plane]; if(0 == plane) { SDL_DisplayYUVOverlay(d_image, &d_dst_rect); //SDL_Flip(d_screen); unsigned int ticks = SDL_GetTicks();//milliseconds d_wanted_ticks += d_wanted_frametime_ms; float avg_alpha = 0.1; int time_diff = d_wanted_ticks-ticks; d_avg_delay = time_diff*avg_alpha +d_avg_delay*(1.0-avg_alpha); } } } if(0==plane) d_current_line=current_line; return noutput_items_produced; } int sink_s_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { short *src_pixels_0,*src_pixels_1,*src_pixels_2; int noutput_items_produced = 0; int plane; int delay = (int)d_avg_delay; if(0 == d_wanted_ticks) d_wanted_ticks = SDL_GetTicks(); if(delay > 0) SDL_Delay((unsigned int)delay); //compensate if running too fast if(SDL_LockYUVOverlay(d_image)) { return 0; } switch(input_items.size ()) { case 3: // first channel=Y, second channel is U , third channel is V src_pixels_0 = (short *)input_items[0]; src_pixels_1 = (short *)input_items[1]; src_pixels_2 = (short *)input_items[2]; for(int i = 0; i < noutput_items; i += d_chunk_size) { copy_plane_to_surface(1,d_chunk_size, src_pixels_1); copy_plane_to_surface(2,d_chunk_size, src_pixels_2); noutput_items_produced += copy_plane_to_surface(0,d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; src_pixels_1 += d_chunk_size; src_pixels_2 += d_chunk_size; } break; case 2: if(1) { //if(pixel_interleaved_uv) // first channel=Y, second channel is alternating pixels U and V src_pixels_0 = (short *)input_items[0]; src_pixels_1 = (short *)input_items[1]; for(int i = 0; i < noutput_items; i += d_chunk_size) { copy_plane_to_surface(12, d_chunk_size/2, src_pixels_1); noutput_items_produced += copy_plane_to_surface(0, d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; src_pixels_1 += d_chunk_size; } } else { // first channel=Y, second channel is alternating lines U and V src_pixels_0 = (short *)input_items[0]; src_pixels_1 = (short *)input_items[1]; for(int i = 0; i < noutput_items; i += d_chunk_size) { copy_plane_to_surface(1222, d_chunk_size/2, src_pixels_1); noutput_items_produced += copy_plane_to_surface(0, d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; src_pixels_1 += d_chunk_size; } } break; case 1: // grey (Y) input /* Y component */ plane=0; src_pixels_0 = (short *)input_items[plane]; for(int i = 0; i < noutput_items; i += d_chunk_size) { noutput_items_produced += copy_plane_to_surface(plane, d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; } break; default: //0 or more then 3 channels std::cerr << "video_sdl::sink_s: Wrong number of channels: "; std::cerr << "1, 2 or 3 channels are supported.\n Requested number of channels is " << input_items.size () << "\n"; throw std::runtime_error("video_sdl::sink_s"); } SDL_UnlockYUVOverlay(d_image); return noutput_items_produced; } } /* namespace video_sdl */ } /* namespace gr */ gnuradio-3.7.2.1/gr-video-sdl/lib/CMakeLists.txt0000664000175000017500000000443512207440367021141 0ustar jcorganjcorgan# Copyright 2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_VIDEO_SDL_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${LOG4CXX_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${SDL_INCLUDE_DIR} ) link_directories(${LOG4CXX_LIBRARY_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) ######################################################################## # Setup library ######################################################################## list(APPEND video_sdl_sources sink_s_impl.cc sink_uc_impl.cc ) list(APPEND video_sdl_libs gnuradio-runtime ${Boost_LIBRARIES} ${SDL_LIBRARY} ) #Add Windows DLL resource file if using MSVC IF(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-video-sdl.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-video-sdl.rc @ONLY) list(APPEND video_sdl_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-video-sdl.rc ) ENDIF(MSVC) add_library(gnuradio-video-sdl SHARED ${video_sdl_sources}) target_link_libraries(gnuradio-video-sdl ${video_sdl_libs}) GR_LIBRARY_FOO(gnuradio-video-sdl RUNTIME_COMPONENT "video_sdl_runtime" DEVEL_COMPONENT "video_sdl_devel") add_dependencies(gnuradio-video-sdl gnuradio-runtime) gnuradio-3.7.2.1/gr-video-sdl/lib/sink_uc_impl.h0000664000175000017500000000520712207440367021224 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VIDEO_SDL_SINK_UC_IMPL_H #define INCLUDED_VIDEO_SDL_SINK_UC_IMPL_H #include #include namespace gr { namespace video_sdl { /* fourcc (four character code) */ #define vid_fourcc(a,b,c,d) (((unsigned)(a)<<0) | ((unsigned)(b)<<8) | ((unsigned)(c)<<16) | ((unsigned)(d)<<24)) #define IMGFMT_YV12 vid_fourcc('Y','V','1','2') /* 12 YVU 4:2:0 */ class sink_uc_impl : public sink_uc { private: int d_chunk_size; protected: void copy_line_pixel_interleaved(unsigned char *dst_pixels_u,unsigned char *dst_pixels_v, const unsigned char * src_pixels,int src_width); void copy_line_line_interleaved(unsigned char *dst_pixels_u,unsigned char *dst_pixels_v, const unsigned char * src_pixels,int src_width); void copy_line_single_plane(unsigned char *dst_pixels,const unsigned char * src_pixels,int src_width); void copy_line_single_plane_dec2(unsigned char *dst_pixels,const unsigned char * src_pixels,int src_width); int copy_plane_to_surface(int plane,int noutput_items, const unsigned char * src_pixels); float d_framerate; int d_wanted_frametime_ms; int d_width; int d_height; int d_dst_width; int d_dst_height; int d_format; int d_current_line; SDL_Surface *d_screen; SDL_Overlay *d_image; SDL_Rect d_dst_rect; float d_avg_delay; unsigned int d_wanted_ticks; public: sink_uc_impl(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height); ~sink_uc_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace video_sdl */ } /* namespace gr */ #endif /* INCLUDED_VIDEO_SDL_SINK_UC_IMPL_H */ gnuradio-3.7.2.1/gr-video-sdl/lib/gnuradio-video-sdl.rc.in0000664000175000017500000000334212207440367023024 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-video-sdl" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-video-sdl.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-video-sdl.dll" VALUE "ProductName", "gnuradio-video-sdl" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-video-sdl/lib/sink_s_impl.h0000664000175000017500000000512412207440367021055 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VIDEO_SDL_SINK_S_IMPL_H #define INCLUDED_VIDEO_SDL_SINK_S_IMPL_H #include #include namespace gr { namespace video_sdl { /* fourcc (four character code) */ #define vid_fourcc(a,b,c,d) (((unsigned)(a)<<0) | ((unsigned)(b)<<8) | ((unsigned)(c)<<16) | ((unsigned)(d)<<24)) #define IMGFMT_YV12 vid_fourcc('Y','V','1','2') /* 12 YVU 4:2:0 */ class sink_s_impl : public sink_s { private: int d_chunk_size; protected: void copy_line_pixel_interleaved(unsigned char *dst_pixels_u,unsigned char *dst_pixels_v, const short * src_pixels,int src_width); void copy_line_line_interleaved(unsigned char *dst_pixels_u,unsigned char *dst_pixels_v, const short * src_pixels,int src_width); void copy_line_single_plane(unsigned char *dst_pixels,const short * src_pixels,int src_width); void copy_line_single_plane_dec2(unsigned char *dst_pixels,const short * src_pixels,int src_width); int copy_plane_to_surface(int plane,int noutput_items, const short * src_pixels); float d_framerate; int d_wanted_frametime_ms; int d_width; int d_height; int d_dst_width; int d_dst_height; int d_format; int d_current_line; SDL_Surface *d_screen; SDL_Overlay *d_image; SDL_Rect d_dst_rect; float d_avg_delay; unsigned int d_wanted_ticks; public: sink_s_impl(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height); ~sink_s_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace video_sdl */ } /* namespace gr */ #endif /* INCLUDED_VIDEO_SDL_SINK_S_IMPL_H */ gnuradio-3.7.2.1/gr-video-sdl/lib/sink_uc_impl.cc0000664000175000017500000002501112207440367021355 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sink_uc_impl.h" #include #include #include #include #include #include #include #include #include namespace gr { namespace video_sdl { sink_uc::sptr sink_uc::make(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height) { return gnuradio::get_initial_sptr (new sink_uc_impl(framerate, width, height, format, dst_width, dst_height)); } sink_uc_impl::sink_uc_impl(double framerate, int width, int height, unsigned int format, int dst_width, int dst_height) : sync_block("video_sdl_sink_uc", io_signature::make(1, 3, sizeof(unsigned char)), io_signature::make(0, 0, 0)), d_chunk_size(width*height), d_framerate(framerate), d_wanted_frametime_ms(0), d_width(width), d_height(height), d_dst_width(dst_width), d_dst_height(dst_height), d_format(format), d_current_line(0), d_screen(NULL), d_image(NULL), d_avg_delay(0.0), d_wanted_ticks(0) { if(framerate <= 0.0) d_wanted_frametime_ms = 0; //Go as fast as possible else d_wanted_frametime_ms = (int)(1000.0/framerate); if(dst_width < 0) d_dst_width = d_width; if(dst_height < 0) d_dst_height = d_height; if(0==format) d_format= IMGFMT_YV12; atexit(SDL_Quit); //check if this is the way to do this if(SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "video_sdl::sink_uc: Couldn't initialize SDL:" << SDL_GetError() << " \n SDL_Init(SDL_INIT_VIDEO) failed\n"; throw std::runtime_error ("video_sdl::sink_uc"); } /* accept any depth */ d_screen = SDL_SetVideoMode(dst_width, dst_height, 0, SDL_SWSURFACE|SDL_RESIZABLE|SDL_ANYFORMAT);//SDL_DOUBLEBUF |SDL_SWSURFACE| SDL_HWSURFACE||SDL_FULLSCREEN if(d_screen == NULL) { std::cerr << "Unable to set SDL video mode: " << SDL_GetError() <<"\n SDL_SetVideoMode() Failed \n"; exit(1); } if(d_image) { SDL_FreeYUVOverlay(d_image); } /* Initialize and create the YUV Overlay used for video out */ if(!(d_image = SDL_CreateYUVOverlay(d_width, d_height, SDL_YV12_OVERLAY, d_screen))) { std::cerr << "SDL: Couldn't create a YUV overlay: \n"<< SDL_GetError() <<"\n"; throw std::runtime_error("video_sdl::sink_uc"); } printf("SDL screen_mode %d bits-per-pixel\n", d_screen->format->BitsPerPixel); printf("SDL overlay_mode %i \n", d_image->format); d_chunk_size = std::min(1,16384/width); //width*16; d_chunk_size = d_chunk_size*width; //d_chunk_size = (int)(width); set_output_multiple(d_chunk_size); /* Set the default playback area */ d_dst_rect.x = 0; d_dst_rect.y = 0; d_dst_rect.w = d_dst_width; d_dst_rect.h = d_dst_height; //clear the surface to grey if(SDL_LockYUVOverlay(d_image)) { std::cerr << "SDL: Couldn't lock YUV overlay: \n" << SDL_GetError() << "\n"; throw std::runtime_error ("video_sdl::sink_uc"); } memset(d_image->pixels[0], 128, d_image->pitches[0]*d_height); memset(d_image->pixels[1], 128, d_image->pitches[1]*d_height/2); memset(d_image->pixels[2], 128, d_image->pitches[2]*d_height/2); SDL_UnlockYUVOverlay(d_image); } sink_uc_impl::~sink_uc_impl() { SDL_Quit(); } void sink_uc_impl::copy_line_pixel_interleaved(unsigned char *dst_pixels_u, unsigned char *dst_pixels_v, const unsigned char *src_pixels, int src_width) { for(int i=0;ipixels[first_dst_plane]; dst_pixels =& dst_pixels[current_line*d_image->pitches[first_dst_plane]]; unsigned char * dst_pixels_2 = (unsigned char *)d_image->pixels[second_dst_plane]; dst_pixels_2 =& dst_pixels_2[current_line*d_image->pitches[second_dst_plane]]; int src_width = (0 == plane || 12 == plane || 1122 == plane) ? d_width : d_width/2; int noutput_items_produced = 0; int max_height = (0 == plane)? d_height-1 : d_height/2-1; for(int i = 0; i < noutput_items; i += src_width) { //output one line at a time if(12 == plane) { copy_line_pixel_interleaved(dst_pixels, dst_pixels_2, src_pixels, src_width); dst_pixels_2 += d_image->pitches[second_dst_plane]; } else if(1122 == plane) { copy_line_line_interleaved(dst_pixels, dst_pixels_2, src_pixels, src_width); dst_pixels_2 += d_image->pitches[second_dst_plane]; src_pixels += src_width; } else if(0 == plane) copy_line_single_plane(dst_pixels, src_pixels, src_width); else /* 1==plane || 2==plane*/ copy_line_single_plane_dec2(dst_pixels, src_pixels, src_width); //decimate by two horizontally src_pixels += src_width; dst_pixels += d_image->pitches[first_dst_plane]; noutput_items_produced+=src_width; current_line++; if(current_line > max_height) { //Start new frame //TODO, do this all in a seperate thread current_line = 0; dst_pixels = d_image->pixels[first_dst_plane]; dst_pixels_2 = d_image->pixels[second_dst_plane]; if(0 == plane) { SDL_DisplayYUVOverlay(d_image, &d_dst_rect); //SDL_Flip(d_screen); unsigned int ticks = SDL_GetTicks();//milliseconds d_wanted_ticks += d_wanted_frametime_ms; float avg_alpha = 0.1; int time_diff = d_wanted_ticks-ticks; d_avg_delay = time_diff*avg_alpha + d_avg_delay*(1.0-avg_alpha); } } } if(0==plane) d_current_line=current_line; return noutput_items_produced; } int sink_uc_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { unsigned char *src_pixels_0,*src_pixels_1,*src_pixels_2; int noutput_items_produced = 0; int plane; int delay = (int)d_avg_delay; if(0 == d_wanted_ticks) d_wanted_ticks=SDL_GetTicks(); if(delay > 0) SDL_Delay((unsigned int)delay);//compensate if running too fast if(SDL_LockYUVOverlay(d_image)) { return 0; } switch(input_items.size ()) { case 3: // first channel=Y, second channel is U , third channel is V src_pixels_0 = (unsigned char *) input_items[0]; src_pixels_1 = (unsigned char *) input_items[1]; src_pixels_2 = (unsigned char *) input_items[2]; for(int i = 0; i < noutput_items; i += d_chunk_size) { copy_plane_to_surface (1,d_chunk_size, src_pixels_1); copy_plane_to_surface (2,d_chunk_size, src_pixels_2); noutput_items_produced+=copy_plane_to_surface(0,d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; src_pixels_1 += d_chunk_size; src_pixels_2 += d_chunk_size; } break; case 2: if(1) {//if(pixel_interleaved_uv) // first channel=Y, second channel is alternating pixels U and V src_pixels_0 = (unsigned char *) input_items[0]; src_pixels_1 = (unsigned char *) input_items[1]; for(int i = 0; i < noutput_items; i += d_chunk_size) { copy_plane_to_surface(12, d_chunk_size/2, src_pixels_1); noutput_items_produced += copy_plane_to_surface(0, d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; src_pixels_1 += d_chunk_size; } } else { // first channel=Y, second channel is alternating lines U and V src_pixels_0 = (unsigned char*)input_items[0]; src_pixels_1 = (unsigned char*)input_items[1]; for(int i = 0; i < noutput_items; i += d_chunk_size) { copy_plane_to_surface (1222,d_chunk_size/2, src_pixels_1); noutput_items_produced += copy_plane_to_surface(0, d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; src_pixels_1 += d_chunk_size; } } break; case 1: // grey (Y) input /* Y component */ plane=0; src_pixels_0 = (unsigned char*)input_items[plane]; for(int i = 0; i < noutput_items; i += d_chunk_size) { noutput_items_produced += copy_plane_to_surface(plane, d_chunk_size, src_pixels_0); src_pixels_0 += d_chunk_size; } break; default: //0 or more then 3 channels std::cerr << "video_sdl::sink_uc: Wrong number of channels: "; std::cerr <<"1, 2 or 3 channels are supported.\n Requested number of channels is " << input_items.size () <<"\n"; throw std::runtime_error("video_sdl::sink_uc"); } SDL_UnlockYUVOverlay(d_image); return noutput_items_produced; } } /* namespace video_sdl */ } /* namespace gr */ gnuradio-3.7.2.1/gr-video-sdl/swig/0000775000175000017500000000000012207440367016576 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-video-sdl/swig/CMakeLists.txt0000664000175000017500000000376112207440367021345 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_VIDEO_SDL_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) set(GR_SWIG_LIBRARIES gnuradio-video-sdl) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) # Setup swig docs to depend on includes and pull in from build directory set(GR_SWIG_TARGET_DEPS video_sdl_generated_includes) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/video_sdl_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/video_sdl) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-video-sdl) GR_SWIG_MAKE(video_sdl_swig video_sdl_swig.i) GR_SWIG_INSTALL( TARGETS video_sdl_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/video_sdl COMPONENT "video_sdl_python" ) install( FILES video_sdl_swig.i ${CMAKE_CURRENT_BINARY_DIR}/video_sdl_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "video_sdl_swig" ) gnuradio-3.7.2.1/gr-video-sdl/swig/video_sdl_swig.i0000664000175000017500000000224112207440367021750 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define VIDEO_SDL_API %include "gnuradio.i" //load generated python docstrings %include "video_sdl_swig_doc.i" %{ #include "gnuradio/video_sdl/sink_uc.h" #include "gnuradio/video_sdl/sink_s.h" %} %include "gnuradio/video_sdl/sink_uc.h" %include "gnuradio/video_sdl/sink_s.h" GR_SWIG_BLOCK_MAGIC2(video_sdl, sink_uc); GR_SWIG_BLOCK_MAGIC2(video_sdl, sink_s); gnuradio-3.7.2.1/gr-uhd/0000755000175000017500000000000012207440367014515 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/CMakeLists.txt0000664000175000017500000000723612207440367017267 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) find_package(UHD) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-uhd" ENABLE_GR_UHD Boost_FOUND UHD_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_FILTER ENABLE_GR_BLOCKS ENABLE_GR_ANALOG ) GR_SET_GLOBAL(GR_UHD_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ) SET(GR_PKG_UHD_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/uhd) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_UHD) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_UHD_DESCRIPTION "GNU Radio UHD Blocks") CPACK_COMPONENT("uhd_runtime" GROUP "UHD" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("uhd_devel" GROUP "UHD" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("uhd_python" GROUP "UHD" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;uhd_runtime" ) CPACK_COMPONENT("uhd_examples" GROUP "UHD" DISPLAY_NAME "Examples" DESCRIPTION "Example programs" DEPENDS "uhd_runtime" ) CPACK_COMPONENT("uhd_swig" GROUP "UHD" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;uhd_python;uhd_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/uhd) add_subdirectory(lib) add_subdirectory(doc) add_subdirectory(examples/c++) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/uhd) add_subdirectory(grc) add_subdirectory(apps) add_subdirectory(examples/python) add_subdirectory(examples/grc) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-uhd.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-uhd.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-uhd.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "uhd_devel" ) endif(ENABLE_GR_UHD) gnuradio-3.7.2.1/gr-uhd/include/0000775000175000017500000000000012207440367016142 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/include/gnuradio/0000775000175000017500000000000012207440367017752 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/include/gnuradio/uhd/0000775000175000017500000000000012224021502020513 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/include/gnuradio/uhd/CMakeLists.txt0000664000175000017500000000212012207440367023265 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h usrp_source.h usrp_sink.h amsg_source.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/uhd COMPONENT "uhd_devel" ) gnuradio-3.7.2.1/gr-uhd/include/gnuradio/uhd/amsg_source.h0000664000175000017500000000401212224021502023170 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UHD_AMSG_SOURCE_H #define INCLUDED_GR_UHD_AMSG_SOURCE_H #include #include #include namespace gr { namespace uhd { class uhd_amsg_source; class GR_UHD_API amsg_source { public: // gr::uhd::amsg_source::sptr typedef boost::shared_ptr sptr; /*! * \brief Destructor * * This must be explicitly defined because there is no block inheritance * for this class, and thus no virtual destructor pulled into the class * hierarchy for sub-classes. */ virtual ~amsg_source(){} /*! * \brief Make a new USRP asynchronous message-based source block. * \ingroup uhd_blk */ static sptr make(const ::uhd::device_addr_t &device_addr, msg_queue::sptr msgq); /*! * Convert a raw asynchronous message to an asynchronous metatdata object. * \return The asynchronous metadata object. */ static ::uhd::async_metadata_t msg_to_async_metadata_t(const message::sptr msg); }; } /* namespace uhd */ } /* namespace gr */ #endif /* INCLUDED_GR_UHD_AMSG_SOURCE_H */ gnuradio-3.7.2.1/gr-uhd/include/gnuradio/uhd/usrp_sink.h0000664000175000017500000004463012207440367022727 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UHD_USRP_SINK_H #define INCLUDED_GR_UHD_USRP_SINK_H #include #include #include #ifndef INCLUDED_UHD_STREAM_HPP namespace uhd { struct GR_UHD_API stream_args_t { stream_args_t(const std::string &cpu = "", const std::string &otw = "") { cpu_format = cpu; otw_format = otw; } std::string cpu_format; std::string otw_format; device_addr_t args; std::vector channels; }; } # define INCLUDED_UHD_STREAM_HPP #else # define GR_UHD_USE_STREAM_API #endif namespace gr { namespace uhd { class uhd_usrp_sink; class GR_UHD_API usrp_sink : virtual public sync_block { public: // gr::uhd::usrp_sink::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a new USRP sink block. * \ingroup uhd_blk * * The USRP sink block reads a stream and transmits the samples. * The sink block also provides API calls for transmitter settings. * * TX Stream tagging: * * The following tag keys will be consumed by the work function: * - pmt::string_to_symbol("tx_sob") * - pmt::string_to_symbol("tx_eob") * - pmt::string_to_symbol("tx_time") * * The sob and eob (start and end of burst) tag values are pmt booleans. * When present, burst tags should be set to true (pmt::PMT_T). * * The timstamp tag value is a pmt tuple of the following: * (uint64 seconds, and double fractional seconds). * * See the UHD manual for more detailed documentation: * http://code.ettus.com/redmine/ettus/projects/uhd/wiki * * \param device_addr the address to identify the hardware * \param io_type the desired input data type * \param num_channels number of stream from the device * \return a new USRP sink block object */ static sptr make(const ::uhd::device_addr_t &device_addr, const ::uhd::io_type_t &io_type, size_t num_channels); /*! * \brief Make a new USRP sink block. * * The USRP sink block reads a stream and transmits the samples. * The sink block also provides API calls for transmitter settings. * * TX Stream tagging: * * The following tag keys will be consumed by the work function: * - pmt::string_to_symbol("tx_sob") * - pmt::string_to_symbol("tx_eob") * - pmt::string_to_symbol("tx_time") * * The sob and eob (start and end of burst) tag values are pmt booleans. * When present, burst tags should be set to true (pmt::PMT_T). * * The timstamp tag value is a pmt tuple of the following: * (uint64 seconds, and double fractional seconds). * * See the UHD manual for more detailed documentation: * http://code.ettus.com/redmine/ettus/projects/uhd/wiki * * \param device_addr the address to identify the hardware * \param stream_args the IO format and channel specification * \return a new USRP sink block object */ static sptr make(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args); /*! * Set the start time for outgoing samples. * To control when samples are transmitted, * set this value before starting the flow graph. * The value is cleared after each run. * When not specified, the start time will be: * - Immediately for the one channel case * - in the near future for multi-channel * * \param time the absolute time for transmission to begin */ virtual void set_start_time(const ::uhd::time_spec_t &time) = 0; /*! * Returns identifying information about this USRP's configuration. * Returns motherboard ID, name, and serial. * Returns daughterboard TX ID, subdev name and spec, serial, and antenna. * \param chan channel index 0 to N-1 * \return TX info */ virtual ::uhd::dict get_usrp_info(size_t chan = 0) = 0; /*! * Set the frontend specification. * \param spec the subdev spec markup string * \param mboard the motherboard index 0 to M-1 */ virtual void set_subdev_spec(const std::string &spec, size_t mboard = 0) = 0; /*! * Get the TX frontend specification. * \param mboard the motherboard index 0 to M-1 * \return the frontend specification in use */ virtual std::string get_subdev_spec (size_t mboard = 0) = 0; /*! * Set the sample rate for the usrp device. * \param rate a new rate in Sps */ virtual void set_samp_rate(double rate) = 0; /*! * Get the sample rate for the usrp device. * This is the actual sample rate and may differ from the rate set. * \return the actual rate in Sps */ virtual double get_samp_rate(void) = 0; /*! * Get the possible sample rates for the usrp device. * \return a range of rates in Sps */ virtual ::uhd::meta_range_t get_samp_rates(void) = 0; /*! * Tune the usrp device to the desired center frequency. * \param tune_request the tune request instructions * \param chan the channel index 0 to N-1 * \return a tune result with the actual frequencies */ virtual ::uhd::tune_result_t set_center_freq (const ::uhd::tune_request_t tune_request, size_t chan = 0) = 0; /*! * Tune the usrp device to the desired center frequency. * This is a wrapper around set center freq so that in this case, * the user can pass a single frequency in the call through swig. * \param freq the desired frequency in Hz * \param chan the channel index 0 to N-1 * \return a tune result with the actual frequencies */ ::uhd::tune_result_t set_center_freq(double freq, size_t chan = 0) { return set_center_freq(::uhd::tune_request_t(freq), chan); } /*! * Get the center frequency. * \param chan the channel index 0 to N-1 * \return the frequency in Hz */ virtual double get_center_freq(size_t chan = 0) = 0; /*! * Get the tunable frequency range. * \param chan the channel index 0 to N-1 * \return the frequency range in Hz */ virtual ::uhd::freq_range_t get_freq_range(size_t chan = 0) = 0; /*! * Set the gain for the dboard. * \param gain the gain in dB * \param chan the channel index 0 to N-1 */ virtual void set_gain(double gain, size_t chan = 0) = 0; /*! * Set the named gain on the dboard. * \param gain the gain in dB * \param name the name of the gain stage * \param chan the channel index 0 to N-1 */ virtual void set_gain(double gain, const std::string &name, size_t chan = 0) = 0; /*! * Get the actual dboard gain setting. * \param chan the channel index 0 to N-1 * \return the actual gain in dB */ virtual double get_gain(size_t chan = 0) = 0; /*! * Get the actual dboard gain setting of named stage. * \param name the name of the gain stage * \param chan the channel index 0 to N-1 * \return the actual gain in dB */ virtual double get_gain(const std::string &name, size_t chan = 0) = 0; /*! * Get the actual dboard gain setting of named stage. * \param chan the channel index 0 to N-1 * \return the actual gain in dB */ virtual std::vector get_gain_names(size_t chan = 0) = 0; /*! * Get the settable gain range. * \param chan the channel index 0 to N-1 * \return the gain range in dB */ virtual ::uhd::gain_range_t get_gain_range(size_t chan = 0) = 0; /*! * Get the settable gain range. * \param name the name of the gain stage * \param chan the channel index 0 to N-1 * \return the gain range in dB */ virtual ::uhd::gain_range_t get_gain_range(const std::string &name, size_t chan = 0) = 0; /*! * Set the antenna to use. * \param ant the antenna string * \param chan the channel index 0 to N-1 */ virtual void set_antenna(const std::string &ant, size_t chan = 0) = 0; /*! * Get the antenna in use. * \param chan the channel index 0 to N-1 * \return the antenna string */ virtual std::string get_antenna(size_t chan = 0) = 0; /*! * Get a list of possible antennas. * \param chan the channel index 0 to N-1 * \return a vector of antenna strings */ virtual std::vector get_antennas(size_t chan = 0) = 0; /*! * Set the bandpass filter on the RF frontend. * \param chan the channel index 0 to N-1 * \param bandwidth the filter bandwidth in Hz */ virtual void set_bandwidth(double bandwidth, size_t chan = 0) = 0; /*! * Get the bandpass filter setting on the RF frontend. * \param chan the channel index 0 to N-1 * \return bandwidth of the filter in Hz */ virtual double get_bandwidth(size_t chan = 0) = 0; /*! * Get the bandpass filter range of the RF frontend. * \param chan the channel index 0 to N-1 * \return the range of the filter bandwidth in Hz */ virtual ::uhd::freq_range_t get_bandwidth_range(size_t chan = 0) = 0; /*! * Set a constant DC offset value. * The value is complex to control both I and Q. * \param offset the dc offset (1.0 is full-scale) * \param chan the channel index 0 to N-1 */ virtual void set_dc_offset(const std::complex &offset, size_t chan = 0) = 0; /*! * Set the RX frontend IQ imbalance correction. * Use this to adjust the magnitude and phase of I and Q. * * \param correction the complex correction (1.0 is full-scale) * \param chan the channel index 0 to N-1 */ virtual void set_iq_balance(const std::complex &correction, size_t chan = 0) = 0; /*! * Get an RF frontend sensor value. * \param name the name of the sensor * \param chan the channel index 0 to N-1 * \return a sensor value object */ virtual ::uhd::sensor_value_t get_sensor(const std::string &name, size_t chan = 0) = 0; /*! * Get a list of possible RF frontend sensor names. * \param chan the channel index 0 to N-1 * \return a vector of sensor names */ virtual std::vector get_sensor_names(size_t chan = 0) = 0; //! DEPRECATED use get_sensor ::uhd::sensor_value_t get_dboard_sensor(const std::string &name, size_t chan = 0) { return this->get_sensor(name, chan); } //! DEPRECATED use get_sensor_names std::vector get_dboard_sensor_names(size_t chan = 0) { return this->get_sensor_names(chan); } /*! * Get a motherboard sensor value. * \param name the name of the sensor * \param mboard the motherboard index 0 to M-1 * \return a sensor value object */ virtual ::uhd::sensor_value_t get_mboard_sensor(const std::string &name, size_t mboard = 0) = 0; /*! * Get a list of possible motherboard sensor names. * \param mboard the motherboard index 0 to M-1 * \return a vector of sensor names */ virtual std::vector get_mboard_sensor_names(size_t mboard = 0) = 0; /*! * Set the clock configuration. * DEPRECATED for set_time/clock_source. * \param clock_config the new configuration * \param mboard the motherboard index 0 to M-1 */ virtual void set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard = 0) = 0; /*! * Set the time source for the usrp device. * This sets the method of time synchronization, * typically a pulse per second or an encoded time. * Typical options for source: external, MIMO. * \param source a string representing the time source * \param mboard which motherboard to set the config */ virtual void set_time_source(const std::string &source, const size_t mboard = 0) = 0; /*! * Get the currently set time source. * \param mboard which motherboard to get the config * \return the string representing the time source */ virtual std::string get_time_source(const size_t mboard) = 0; /*! * Get a list of possible time sources. * \param mboard which motherboard to get the list * \return a vector of strings for possible settings */ virtual std::vector get_time_sources(const size_t mboard) = 0; /*! * Set the clock source for the usrp device. * This sets the source for a 10 Mhz reference clock. * Typical options for source: internal, external, MIMO. * \param source a string representing the clock source * \param mboard which motherboard to set the config */ virtual void set_clock_source(const std::string &source, const size_t mboard = 0) = 0; /*! * Get the currently set clock source. * \param mboard which motherboard to get the config * \return the string representing the clock source */ virtual std::string get_clock_source(const size_t mboard) = 0; /*! * Get a list of possible clock sources. * \param mboard which motherboard to get the list * \return a vector of strings for possible settings */ virtual std::vector get_clock_sources(const size_t mboard) = 0; /*! * Get the master clock rate. * \param mboard the motherboard index 0 to M-1 * \return the clock rate in Hz */ virtual double get_clock_rate(size_t mboard = 0) = 0; /*! * Set the master clock rate. * \param rate the new rate in Hz * \param mboard the motherboard index 0 to M-1 */ virtual void set_clock_rate(double rate, size_t mboard = 0) = 0; /*! * Get the current time registers. * \param mboard the motherboard index 0 to M-1 * \return the current usrp time */ virtual ::uhd::time_spec_t get_time_now(size_t mboard = 0) = 0; /*! * Get the time when the last pps pulse occured. * \param mboard the motherboard index 0 to M-1 * \return the current usrp time */ virtual ::uhd::time_spec_t get_time_last_pps(size_t mboard = 0) = 0; /*! * Sets the time registers immediately. * \param time_spec the new time * \param mboard the motherboard index 0 to M-1 */ virtual void set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard = 0) = 0; /*! * Set the time registers at the next pps. * \param time_spec the new time */ virtual void set_time_next_pps(const ::uhd::time_spec_t &time_spec) = 0; /*! * Sync the time registers with an unknown pps edge. * \param time_spec the new time */ virtual void set_time_unknown_pps(const ::uhd::time_spec_t &time_spec) = 0; /*! * Set the time at which the control commands will take effect. * * A timed command will back-pressure all subsequent timed commands, * assuming that the subsequent commands occur within the time-window. * If the time spec is late, the command will be activated upon arrival. * * \param time_spec the time at which the next command will activate * \param mboard which motherboard to set the config */ virtual void set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard = 0) = 0; /*! * Clear the command time so future commands are sent ASAP. * * \param mboard which motherboard to set the config */ virtual void clear_command_time(size_t mboard = 0) = 0; /*! * Get access to the underlying uhd dboard iface object. * \return the dboard_iface object */ virtual ::uhd::usrp::dboard_iface::sptr get_dboard_iface(size_t chan = 0) = 0; /*! * Get access to the underlying uhd device object. * \return the multi usrp device object */ virtual ::uhd::usrp::multi_usrp::sptr get_device(void) = 0; /*! * Perform write on the user configuration register bus. These * only exist if the user has implemented custom setting * registers in the device FPGA. * \param addr 8-bit register address * \param data 32-bit register value * \param mboard which motherboard to set the user register */ virtual void set_user_register(const uint8_t addr, const uint32_t data, size_t mboard = 0) = 0; }; } /* namespace uhd */ } /* namespace gr */ #endif /* INCLUDED_GR_UHD_USRP_SINK_H */ gnuradio-3.7.2.1/gr-uhd/include/gnuradio/uhd/usrp_source.h0000664000175000017500000005105212207440367023257 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UHD_USRP_SOURCE_H #define INCLUDED_GR_UHD_USRP_SOURCE_H #include #include #include #ifndef INCLUDED_UHD_STREAM_HPP namespace uhd { struct GR_UHD_API stream_args_t { stream_args_t(const std::string &cpu = "", const std::string &otw = "") { cpu_format = cpu; otw_format = otw; } std::string cpu_format; std::string otw_format; device_addr_t args; std::vector channels; }; } # define INCLUDED_UHD_STREAM_HPP #else # define GR_UHD_USE_STREAM_API #endif namespace gr { namespace uhd { class uhd_usrp_source; class GR_UHD_API usrp_source : virtual public sync_block { public: // gr::uhd::usrp_source::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a new USRP source block. * \ingroup uhd_blk * * The USRP source block receives samples and writes to a stream. * The source block also provides API calls for receiver settings. * * RX Stream tagging: * * The following tag keys will be produced by the work function: * - pmt::string_to_symbol("rx_time") * - pmt::string_to_symbol("rx_rate") * - pmt::string_to_symbol("rx_freq") * * The timstamp tag value is a pmt tuple of the following: * (uint64 seconds, and double fractional seconds). * A timestamp tag is produced at start() and after overflows. * * The sample rate and center frequency tags are doubles, * representing the sample rate in Sps and frequency in Hz. * These tags are produced upon the user changing parameters. * * See the UHD manual for more detailed documentation: * http://code.ettus.com/redmine/ettus/projects/uhd/wiki * * \param device_addr the address to identify the hardware * \param io_type the desired output data type * \param num_channels number of stream from the device * \return a new USRP source block object */ static sptr make(const ::uhd::device_addr_t &device_addr, const ::uhd::io_type_t &io_type, size_t num_channels); /*! * \brief Make a new USRP source block. * * The USRP source block receives samples and writes to a stream. * The source block also provides API calls for receiver settings. * * RX Stream tagging: * * The following tag keys will be produced by the work function: * - pmt::string_to_symbol("rx_time") * * The timstamp tag value is a pmt tuple of the following: * (uint64 seconds, and double fractional seconds). * A timestamp tag is produced at start() and after overflows. * * See the UHD manual for more detailed documentation: * http://code.ettus.com/redmine/ettus/projects/uhd/wiki * * \param device_addr the address to identify the hardware * \param stream_args the IO format and channel specification * \return a new USRP source block object */ static sptr make(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args); /*! * Set the start time for incoming samples. * To control when samples are received, * set this value before starting the flow graph. * The value is cleared after each run. * When not specified, the start time will be: * - Immediately for the one channel case * - in the near future for multi-channel * * \param time the absolute time for reception to begin */ virtual void set_start_time(const ::uhd::time_spec_t &time) = 0; /*! * *Advanced use only:* * Issue a stream command to all channels in this source block. * * This method is intended to override the default "always on" * behavior. After starting the flow graph, the user should * call stop() on this block, then issue any desired arbitrary * stream_cmd_t structs to the device. The USRP will be able to * enqueue several stream commands in the FPGA. * * \param cmd the stream command to issue to all source channels */ virtual void issue_stream_cmd(const ::uhd::stream_cmd_t &cmd) = 0; /*! * Returns identifying information about this USRP's configuration. * Returns motherboard ID, name, and serial. * Returns daughterboard RX ID, subdev name and spec, serial, and antenna. * \param chan channel index 0 to N-1 * \return RX info */ virtual ::uhd::dict get_usrp_info(size_t chan = 0) = 0; /*! * Set the frontend specification. * \param spec the subdev spec markup string * \param mboard the motherboard index 0 to M-1 */ virtual void set_subdev_spec(const std::string &spec, size_t mboard = 0) = 0; /*! * Get the RX frontend specification. * \param mboard the motherboard index 0 to M-1 * \return the frontend specification in use */ virtual std::string get_subdev_spec(size_t mboard = 0) = 0; /*! * Set the sample rate for the usrp device. * \param rate a new rate in Sps */ virtual void set_samp_rate(double rate) = 0; /*! * Get the sample rate for the usrp device. * This is the actual sample rate and may differ from the rate set. * \return the actual rate in Sps */ virtual double get_samp_rate(void) = 0; /*! * Get the possible sample rates for the usrp device. * \return a range of rates in Sps */ virtual ::uhd::meta_range_t get_samp_rates(void) = 0; /*! * Tune the usrp device to the desired center frequency. * \param tune_request the tune request instructions * \param chan the channel index 0 to N-1 * \return a tune result with the actual frequencies */ virtual ::uhd::tune_result_t set_center_freq (const ::uhd::tune_request_t tune_request, size_t chan = 0) = 0; /*! * Tune the usrp device to the desired center frequency. * This is a wrapper around set center freq so that in this case, * the user can pass a single frequency in the call through swig. * \param freq the desired frequency in Hz * \param chan the channel index 0 to N-1 * \return a tune result with the actual frequencies */ ::uhd::tune_result_t set_center_freq(double freq, size_t chan = 0) { return set_center_freq(::uhd::tune_request_t(freq), chan); } /*! * Get the center frequency. * \param chan the channel index 0 to N-1 * \return the frequency in Hz */ virtual double get_center_freq(size_t chan = 0) = 0; /*! * Get the tunable frequency range. * \param chan the channel index 0 to N-1 * \return the frequency range in Hz */ virtual ::uhd::freq_range_t get_freq_range(size_t chan = 0) = 0; /*! * Set the gain for the dboard. * \param gain the gain in dB * \param chan the channel index 0 to N-1 */ virtual void set_gain(double gain, size_t chan = 0) = 0; /*! * Set the named gain on the dboard. * \param gain the gain in dB * \param name the name of the gain stage * \param chan the channel index 0 to N-1 */ virtual void set_gain(double gain, const std::string &name, size_t chan = 0) = 0; /*! * Get the actual dboard gain setting. * \param chan the channel index 0 to N-1 * \return the actual gain in dB */ virtual double get_gain(size_t chan = 0) = 0; /*! * Get the actual dboard gain setting of named stage. * \param name the name of the gain stage * \param chan the channel index 0 to N-1 * \return the actual gain in dB */ virtual double get_gain(const std::string &name, size_t chan = 0) = 0; /*! * Get the actual dboard gain setting of named stage. * \param chan the channel index 0 to N-1 * \return the actual gain in dB */ virtual std::vector get_gain_names(size_t chan = 0) = 0; /*! * Get the settable gain range. * \param chan the channel index 0 to N-1 * \return the gain range in dB */ virtual ::uhd::gain_range_t get_gain_range(size_t chan = 0) = 0; /*! * Get the settable gain range. * \param name the name of the gain stage * \param chan the channel index 0 to N-1 * \return the gain range in dB */ virtual ::uhd::gain_range_t get_gain_range(const std::string &name, size_t chan = 0) = 0; /*! * Set the antenna to use. * \param ant the antenna string * \param chan the channel index 0 to N-1 */ virtual void set_antenna(const std::string &ant, size_t chan = 0) = 0; /*! * Get the antenna in use. * \param chan the channel index 0 to N-1 * \return the antenna string */ virtual std::string get_antenna(size_t chan = 0) = 0; /*! * Get a list of possible antennas. * \param chan the channel index 0 to N-1 * \return a vector of antenna strings */ virtual std::vector get_antennas(size_t chan = 0) = 0; /*! * Set the bandpass filter on the RF frontend. * \param bandwidth the filter bandwidth in Hz * \param chan the channel index 0 to N-1 */ virtual void set_bandwidth(double bandwidth, size_t chan = 0) = 0; /*! * Get the bandpass filter setting on the RF frontend. * \param chan the channel index 0 to N-1 * \return bandwidth of the filter in Hz */ virtual double get_bandwidth(size_t chan = 0) = 0; /*! * Get the bandpass filter range of the RF frontend. * \param chan the channel index 0 to N-1 * \return the range of the filter bandwidth in Hz */ virtual ::uhd::freq_range_t get_bandwidth_range(size_t chan = 0) = 0; /*! * Enable/disable the automatic DC offset correction. * The automatic correction subtracts out the long-run average. * * When disabled, the averaging option operation is halted. * Once halted, the average value will be held constant until * the user re-enables the automatic correction or overrides the * value by manually setting the offset. * * \param enb true to enable automatic DC offset correction * \param chan the channel index 0 to N-1 */ virtual void set_auto_dc_offset(const bool enb, size_t chan = 0) = 0; /*! * Set a constant DC offset value. * The value is complex to control both I and Q. * Only set this when automatic correction is disabled. * \param offset the dc offset (1.0 is full-scale) * \param chan the channel index 0 to N-1 */ virtual void set_dc_offset(const std::complex &offset, size_t chan = 0) = 0; /*! * Set the RX frontend IQ imbalance correction. * Use this to adjust the magnitude and phase of I and Q. * * \param correction the complex correction value * \param chan the channel index 0 to N-1 */ virtual void set_iq_balance(const std::complex &correction, size_t chan = 0) = 0; /*! * Get a RF frontend sensor value. * \param name the name of the sensor * \param chan the channel index 0 to N-1 * \return a sensor value object */ virtual ::uhd::sensor_value_t get_sensor(const std::string &name, size_t chan = 0) = 0; /*! * Get a list of possible RF frontend sensor names. * \param chan the channel index 0 to N-1 * \return a vector of sensor names */ virtual std::vector get_sensor_names(size_t chan = 0) = 0; //! DEPRECATED use get_sensor ::uhd::sensor_value_t get_dboard_sensor(const std::string &name, size_t chan = 0) { return this->get_sensor(name, chan); } //! DEPRECATED use get_sensor_names std::vector get_dboard_sensor_names(size_t chan = 0) { return this->get_sensor_names(chan); } /*! * Get a motherboard sensor value. * \param name the name of the sensor * \param mboard the motherboard index 0 to M-1 * \return a sensor value object */ virtual ::uhd::sensor_value_t get_mboard_sensor(const std::string &name, size_t mboard = 0) = 0; /*! * Get a list of possible motherboard sensor names. * \param mboard the motherboard index 0 to M-1 * \return a vector of sensor names */ virtual std::vector get_mboard_sensor_names(size_t mboard = 0) = 0; /*! * Set the clock configuration. * DEPRECATED for set_time/clock_source. * \param clock_config the new configuration * \param mboard the motherboard index 0 to M-1 */ virtual void set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard = 0) = 0; /*! * Set the time source for the usrp device. * This sets the method of time synchronization, * typically a pulse per second or an encoded time. * Typical options for source: external, MIMO. * \param source a string representing the time source * \param mboard which motherboard to set the config */ virtual void set_time_source(const std::string &source, const size_t mboard = 0) = 0; /*! * Get the currently set time source. * \param mboard which motherboard to get the config * \return the string representing the time source */ virtual std::string get_time_source(const size_t mboard) = 0; /*! * Get a list of possible time sources. * \param mboard which motherboard to get the list * \return a vector of strings for possible settings */ virtual std::vector get_time_sources(const size_t mboard) = 0; /*! * Set the clock source for the usrp device. * This sets the source for a 10 Mhz reference clock. * Typical options for source: internal, external, MIMO. * \param source a string representing the clock source * \param mboard which motherboard to set the config */ virtual void set_clock_source(const std::string &source, const size_t mboard = 0) = 0; /*! * Get the currently set clock source. * \param mboard which motherboard to get the config * \return the string representing the clock source */ virtual std::string get_clock_source(const size_t mboard) = 0; /*! * Get a list of possible clock sources. * \param mboard which motherboard to get the list * \return a vector of strings for possible settings */ virtual std::vector get_clock_sources(const size_t mboard) = 0; /*! * Get the master clock rate. * \param mboard the motherboard index 0 to M-1 * \return the clock rate in Hz */ virtual double get_clock_rate(size_t mboard = 0) = 0; /*! * Set the master clock rate. * \param rate the new rate in Hz * \param mboard the motherboard index 0 to M-1 */ virtual void set_clock_rate(double rate, size_t mboard = 0) = 0; /*! * Get the current time registers. * \param mboard the motherboard index 0 to M-1 * \return the current usrp time */ virtual ::uhd::time_spec_t get_time_now(size_t mboard = 0) = 0; /*! * Get the time when the last pps pulse occured. * \param mboard the motherboard index 0 to M-1 * \return the current usrp time */ virtual ::uhd::time_spec_t get_time_last_pps(size_t mboard = 0) = 0; /*! * Sets the time registers immediately. * \param time_spec the new time * \param mboard the motherboard index 0 to M-1 */ virtual void set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard = 0) = 0; /*! * Set the time registers at the next pps. * \param time_spec the new time */ virtual void set_time_next_pps(const ::uhd::time_spec_t &time_spec) = 0; /*! * Sync the time registers with an unknown pps edge. * \param time_spec the new time */ virtual void set_time_unknown_pps(const ::uhd::time_spec_t &time_spec) = 0; /*! * Set the time at which the control commands will take effect. * * A timed command will back-pressure all subsequent timed * commands, assuming that the subsequent commands occur within * the time-window. If the time spec is late, the command will * be activated upon arrival. * * \param time_spec the time at which the next command will activate * \param mboard which motherboard to set the config */ virtual void set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard = 0) = 0; /*! * Clear the command time so future commands are sent ASAP. * * \param mboard which motherboard to set the config */ virtual void clear_command_time(size_t mboard = 0) = 0; /*! * Get access to the underlying uhd dboard iface object. * \return the dboard_iface object */ virtual ::uhd::usrp::dboard_iface::sptr get_dboard_iface(size_t chan = 0) = 0; /*! * Get access to the underlying uhd device object. * \return the multi usrp device object */ virtual ::uhd::usrp::multi_usrp::sptr get_device(void) = 0; /*! * Perform write on the user configuration register bus. These * only exist if the user has implemented custom setting * registers in the device FPGA. * \param addr 8-bit register address * \param data 32-bit register value * \param mboard which motherboard to set the user register */ virtual void set_user_register(const uint8_t addr, const uint32_t data, size_t mboard = 0) = 0; /*! * Convenience function for finite data acquisition. * This is not to be used with the scheduler; rather, * one can request samples from the USRP in python. * //TODO assumes fc32 * \param nsamps the number of samples * \return a vector of complex float samples */ virtual std::vector > finite_acquisition(const size_t nsamps) = 0; /*! * Convenience function for finite data acquisition. This is the * multi-channel version of finite_acquisition; This is not to * be used with the scheduler; rather, one can request samples * from the USRP in python. * //TODO assumes fc32 * \param nsamps the number of samples per channel * \return a vector of buffers, where each buffer represents a channel */ virtual std::vector > > finite_acquisition_v(const size_t nsamps) = 0; }; } /* namespace uhd */ } /* namespace gr */ #endif /* INCLUDED_GR_UHD_USRP_SOURCE_H */ gnuradio-3.7.2.1/gr-uhd/include/gnuradio/uhd/api.h0000664000175000017500000000201112207440367021446 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UHD_API_H #define INCLUDED_GR_UHD_API_H #include #ifdef gnuradio_uhd_EXPORTS # define GR_UHD_API UHD_EXPORT #else # define GR_UHD_API UHD_IMPORT #endif #endif /* INCLUDED_GR_UHD_API_H */ gnuradio-3.7.2.1/gr-uhd/grc/0000755000175000017500000000000012207702530015261 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/grc/CMakeLists.txt0000644000175000017500000000324511744612271020034 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Rules for generating the source and sink xml wrappers ######################################################################## include(GrPython) macro(GEN_BLOCK_XML _generator _xml_block) set(generator ${CMAKE_CURRENT_SOURCE_DIR}/${_generator}) set(xml_block ${CMAKE_CURRENT_BINARY_DIR}/${_xml_block}) list(APPEND xml_blocks ${xml_block}) add_custom_command( DEPENDS ${generator} OUTPUT ${xml_block} COMMAND ${PYTHON_EXECUTABLE} ${generator} ${xml_block} ) endmacro(GEN_BLOCK_XML) GEN_BLOCK_XML(gen_uhd_usrp_blocks.py uhd_usrp_source.xml) GEN_BLOCK_XML(gen_uhd_usrp_blocks.py uhd_usrp_sink.xml) add_custom_target(uhd_grc_xml_blocks ALL DEPENDS ${xml_blocks}) install(FILES ${xml_blocks} uhd_amsg_source.xml uhd_block_tree.xml DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "uhd_python" ) gnuradio-3.7.2.1/gr-uhd/grc/uhd_block_tree.xml0000644000175000017500000000054111700377701020761 0ustar jcorganjcorgan UHD uhd_usrp_source uhd_usrp_sink uhd_amsg_source gnuradio-3.7.2.1/gr-uhd/grc/uhd_amsg_source.xml0000644000175000017500000000077611700377701021171 0ustar jcorganjcorgan UHD: USRP Async Msg Source uhd_amsg_source from gnuradio import uhd uhd.amsg_source(device_addr=$dev_addr, msgq=$(id)_msgq_out) Device Addr dev_addr string #if $dev_addr() none #else part #end if out msg gnuradio-3.7.2.1/gr-uhd/grc/gen_uhd_usrp_blocks.py0000664000175000017500000002672712207702530021672 0ustar jcorganjcorgan""" Copyright 2010-2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA """ MAIN_TMPL = """\ UHD: USRP $sourk.title() uhd_usrp_$(sourk) 1 from gnuradio import uhd import time uhd.usrp_$(sourk)( device_addr=\$dev_addr, stream_args=uhd.stream_args( cpu_format="\$type", \#if \$otw() otw_format=\$otw, \#end if \#if \$stream_args() args=\$stream_args, \#end if \#if \$stream_chans() channels=\$stream_chans, \#else channels=range(\$nchan), \#end if ), ) \#if \$clock_rate() self.\$(id).set_clock_rate(\$clock_rate, uhd.ALL_MBOARDS) \#end if #for $m in range($max_mboards) ######################################################################## \#if \$num_mboards() > $m and \$clock_source$(m)() self.\$(id).set_clock_source(\$clock_source$(m), $m) \#end if ######################################################################## \#if \$num_mboards() > $m and \$time_source$(m)() self.\$(id).set_time_source(\$time_source$(m), $m) \#end if ######################################################################## \#if \$num_mboards() > $m and \$sd_spec$(m)() self.\$(id).set_subdev_spec(\$sd_spec$(m), $m) \#end if ######################################################################## #end for \#if \$sync() == 'sync' self.\$(id).set_time_unknown_pps(uhd.time_spec()) \#elif \$sync() == 'pc_clock' self.\$(id).set_time_now(uhd.time_spec(time.time()), uhd.ALL_MBOARDS) \#end if self.\$(id).set_samp_rate(\$samp_rate) #for $n in range($max_nchan) \#if \$nchan() > $n self.\$(id).set_center_freq(\$center_freq$(n), $n) self.\$(id).set_gain(\$gain$(n), $n) \#if \$ant$(n)() self.\$(id).set_antenna(\$ant$(n), $n) \#end if \#if \$bw$(n)() self.\$(id).set_bandwidth(\$bw$(n), $n) \#end if \#end if #end for set_samp_rate(\$samp_rate) #for $n in range($max_nchan) set_center_freq(\$center_freq$(n), $n) set_gain(\$gain$(n), $n) set_antenna(\$ant$(n), $n) set_bandwidth(\$bw$(n), $n) #end for $(direction.title())put Type type enum Wire Format otw string \#if \$otw() none \#else part \#end if Stream args stream_args string \#if \$stream_args() none \#else part \#end if Stream channels stream_chans [] int_vector \#if \$stream_chans() none \#else part \#end if Device Addr dev_addr string \#if \$dev_addr() none \#else part \#end if Sync sync enum \#if \$sync() then 'none' else 'part'# Clock Rate (Hz) clock_rate 0.0 real \#if \$clock_rate() then 'none' else 'part'# Num Mboards num_mboards 1 int part #for $m in range(1, $max_mboards+1) #end for #for $m in range($max_mboards) Mb$(m): Clock Source clock_source$(m) string \#if not \$num_mboards() > $m all \#elif \$clock_source$(m)() none \#else part \#end if Mb$(m): Time Source time_source$(m) string \#if not \$num_mboards() > $m all \#elif \$time_source$(m)() none \#else part \#end if Mb$(m): Subdev Spec sd_spec$(m) string \#if not \$num_mboards() > $m all \#elif \$sd_spec$(m)() none \#else part \#end if #end for Num Channels nchan 1 int #for $n in range(1, $max_nchan+1) #end for Samp Rate (Sps) samp_rate samp_rate real $params $max_nchan >= \$nchan \$nchan > 0 $max_mboards >= \$num_mboards \$num_mboards > 0 \$nchan >= \$num_mboards <$sourk> $direction \$type.type \$nchan The UHD USRP $sourk.title() Block: Device Address: The device address is a delimited string used to locate UHD devices on your system. \\ If left blank, the first UHD device found will be used. \\ Use the device address to specify a specific device or list of devices. USRP1 Example: serial=12345678 USRP2 Example: addr=192.168.10.2 USRP2 Example: addr0=192.168.10.2, addr1=192.168.10.3 $(direction.title()) Type: This parameter controls the data type of the stream in gnuradio. Wire Format: This parameter controls the form of the data over the bus/network. \ Complex bytes may be used to trade off precision for bandwidth. \ Not all formats are supported on all devices. Stream Args: Optional arguments to be passed in the UHD streamer object. \ Streamer args is a list of key/value pairs; usage is determined by the implementation. Ex: the scalar key affects the scaling between 16 and 8 bit integers in sc8 wire format. Num Motherboards: Selects the number of USRP motherboards in this device configuration. Reference Source: Where the motherboard should sync its time and clock references. If source and sink blocks reference the same device, it is only necessary to set the reference source on one of the blocks. Subdevice specification: Each motherboard should have its own subdevice specification \\ and all subdevice specifications should be the same length. \\ Select the subdevice or subdevices for each channel using a markup string. \\ The markup string consists of a list of dboard_slot:subdev_name pairs (one pair per channel). \\ If left blank, the UHD will try to select the first subdevice on your system. \\ See the application notes for further details. Single channel example: :AB Dual channel example: :A :B Num Channels: Selects the total number of channels in this multi-USRP configuration. Ex: 4 motherboards with 2 channels per board = 8 channels total Sample rate: The sample rate is the number of samples per second input by this block. \\ The UHD device driver will try its best to match the requested sample rate. \\ If the requested rate is not possible, the UHD block will print an error at runtime. Center frequency: The center frequency is the overall frequency of the RF chain. \\ For greater control of how the UHD tunes elements in the RF chain, \\ pass a tune_request object rather than a simple target frequency. Tuning with an LO offset example: uhd.tune_request(freq, lo_off) Tuning without DSP: uhd.tune_request(target_freq, dsp_freq=0, \\ dsp_freq_policy=uhd.tune_request.POLICY_MANUAL) Antenna: For subdevices with only one antenna, this may be left blank. \\ Otherwise, the user should specify one of the possible antenna choices. \\ See the daughterboard application notes for the possible antenna choices. Bandwidth: To use the default bandwidth filter setting, this should be zero. \\ Only certain subdevices have configurable bandwidth filters. \\ See the daughterboard application notes for possible configurations. See the UHD manual for more detailed documentation: http://code.ettus.com/redmine/ettus/projects/uhd/wiki """ PARAMS_TMPL = """ Ch$(n): Center Freq (Hz) center_freq$(n) 0 real \#if \$nchan() > $n then 'none' else 'all'# Ch$(n): Gain (dB) gain$(n) 0 real \#if \$nchan() > $n then 'none' else 'all'# Ch$(n): Antenna ant$(n) string \#if not \$nchan() > $n all \#elif \$ant$(n)() none \#else part \#end if Ch$(n): Bandwidth (Hz) bw$(n) 0 real \#if not \$nchan() > $n all \#elif \$bw$(n)() none \#else part \#end if """ def parse_tmpl(_tmpl, **kwargs): from Cheetah import Template return str(Template.Template(_tmpl, kwargs)) max_num_mboards = 8 max_num_channels = max_num_mboards*4 if __name__ == '__main__': import sys for file in sys.argv[1:]: if file.endswith ('source.xml'): sourk = 'source' direction = 'out' elif file.endswith ('sink.xml'): sourk = 'sink' direction = 'in' else: raise Exception, 'is %s a source or sink?'%file params = ''.join([parse_tmpl(PARAMS_TMPL, n=n) for n in range(max_num_channels)]) open(file, 'w').write(parse_tmpl(MAIN_TMPL, max_nchan=max_num_channels, max_mboards=max_num_mboards, params=params, sourk=sourk, direction=direction, )) gnuradio-3.7.2.1/gr-uhd/doc/0000755000175000017500000000000012207440367015262 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/doc/CMakeLists.txt0000644000175000017500000000151511744612271020024 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.uhd DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-uhd/doc/uhd.dox0000664000175000017500000000626412207440367016570 0ustar jcorganjcorgan/*! \page page_uhd UHD Interface \section Introduction This is the GNU Radio UHD package. It is the interface to the UHD library to connect to and send and receive data between the Ettus Research, LLC product line. To use the UHD blocks, the Python namespaces is in gnuradio.uhd, which would be normally imported as: \code from gnuradio import uhd \endcode The relevant blocks are listed in the \ref uhd_blk group. A quick listing of the details can be found in Python after importing by using: \code help(uhd) \endcode \section External Documentation Ettus Research keeps the comprehensive documentation to the underlying UHD driver, which can be found: http://files.ettus.com/uhd_docs/manual/html/ The UHD Doxygen page is located: http://files.ettus.com/uhd_docs/doxygen/html/index.html \section Typical Setup A typical option parser setup for a UHD device looks like \code parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") \endcode To use these options to create a UHD source object: \code self.u = uhd.usrp_source(device_addr=options.args, io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=1) self.u.set_samp_rate(options.samp_rate) # if no gain was specified, use the mid-point in dB if options.gain is None: g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 self.u.set_gain(options.gain, 0) # Set the center frequency self.u.set_center_freq(options.freq, 0) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) \endcode Frequently, your application may need a sample rate that is not supported by the UHD device. If you have extra CPU power to spare, you can easily set the sample rate you want, then ask the device what the actual sample rate set was. Then, you can easily create an arbitrary resampler to take care of the difference. \code self.u.set_samp_rate(options.samp_rate) desired_rate = options.samp_rate actual_rate = self.u.get_samp_rate() resample = desired_rate / actual_rate # Use the filter.pfb version and pass only the resample factor. # This block builds a half-band filter for you self.resampler = filter.pfb.arb_resampler_ccf(resample) \endcode */ gnuradio-3.7.2.1/gr-uhd/doc/README.uhd0000644000175000017500000000073311744612271016724 0ustar jcorganjcorganThis is the GNU Radio UHD package. It is the interface to the UHD library to connect to and send and receive data between the Ettus Research, LLC product line. To use the UHD blocks, the Python namespaces is in gnuradio.uhd, which would be normally imported as: from gnuradio import uhd See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(uhd) gnuradio-3.7.2.1/gr-uhd/python/0000775000175000017500000000000012207440367016040 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/python/uhd/0000775000175000017500000000000012214652673016623 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/python/uhd/CMakeLists.txt0000664000175000017500000000332712207440367021365 0ustar jcorganjcorgan# Copyright 2011-212 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/uhd COMPONENT "uhd_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) list(APPEND GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gr-uhd/python ${CMAKE_BINARY_DIR}/gr-uhd/swig ) list(APPEND GR_TEST_TARGET_DEPS gnuradio-uhd) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-uhd/python/uhd/qa_uhd.py0000664000175000017500000000316512207440367020440 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2008,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, uhd class test_uhd(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_000_nop (self): """Just see if we can import the module... They may not have a UHD device connected, etc. Don't try to run anything""" pass def test_stream_args_channel_foo(self): """ Try to manipulate the stream args channels for proper swig'ing checks. """ sa = uhd.stream_args_t() sa.channels.append(1) sa.channels.append(0) print sa.channels self.assertEqual(len(sa.channels), 2) self.assertEqual(sa.channels[0], 1) self.assertEqual(sa.channels[1], 0) if __name__ == '__main__': gr_unittest.run(test_uhd, "test_uhd.xml") gnuradio-3.7.2.1/gr-uhd/python/uhd/__init__.py0000664000175000017500000001461012214652673020736 0ustar jcorganjcorgan# # Copyright 2010-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Provides source and sink blocks to interface with the UHD library. Used to send and receive data between the Ettus Research, LLC product line. ''' ######################################################################## # Prepare uhd swig module to make it more pythonic ######################################################################## def _prepare_uhd_swig(): try: import uhd_swig except ImportError: import os dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) import uhd_swig #some useful typedefs for the user setattr(uhd_swig, 'freq_range_t', uhd_swig.meta_range_t) setattr(uhd_swig, 'gain_range_t', uhd_swig.meta_range_t) #Make the python tune request object inherit from float #so that it can be passed in GRC as a frequency parameter. #The type checking in GRC will accept the tune request. #Also use kwargs to construct individual struct elements. class tune_request_t(uhd_swig.tune_request_t, float): def __new__(self, *args, **kwargs): return float.__new__(self) def __float__(self): return self.target_freq def __init__(self, *args, **kwargs): super(tune_request_t, self).__init__(*args) for key, val in kwargs.iteritems(): setattr(self, key, val) setattr(uhd_swig, 'tune_request_t', tune_request_t) #Make the python tune request object inherit from string #so that it can be passed in GRC as a string parameter. #The type checking in GRC will accept the device address. #Define the set/get item special methods for dict access. class device_addr_t(uhd_swig.device_addr_t, str): def __new__(self, *args): return str.__new__(self) def __getitem__(self, key): return self.get(key) def __setitem__(self, key, val): self.set(key, val) def __init__(self, *args, **kwargs): super(device_addr_t, self).__init__(*args) if args and isinstance(args[0], device_addr_t): for key in args[0].keys(): self[key] = args[0][key] setattr(uhd_swig, 'device_addr_t', device_addr_t) #make the streamer args take **kwargs on init class stream_args_t(uhd_swig.stream_args_t): def __init__(self, *args, **kwargs): super(stream_args_t, self).__init__(*args) for key, val in kwargs.iteritems(): #for some reason, i cant assign a list in the constructor #but what i can do is append the elements individually if key == 'channels': for v in val: self.channels.append(v) elif key == 'args': self.args = device_addr_t(val) else: setattr(self, key, val) setattr(uhd_swig, 'stream_args_t', stream_args_t) #handle general things on all uhd_swig attributes #Install the __str__ and __repr__ handlers if applicable #Create aliases for uhd swig attributes to avoid the "_t" for attr in dir(uhd_swig): myobj = getattr(uhd_swig, attr) if hasattr(myobj, 'to_string'): myobj.__repr__ = lambda o: o.to_string().strip() if hasattr(myobj, 'to_pp_string'): myobj.__str__ = lambda o: o.to_pp_string().strip() if hasattr(myobj, 'to_bool'): myobj.__nonzero__ = lambda o: o.to_bool() if hasattr(myobj, 'to_int'): myobj.__int__ = lambda o: o.to_int() if hasattr(myobj, 'to_real'): myobj.__float__ = lambda o: o.to_real() if attr.endswith('_t'): setattr(uhd_swig, attr[:-2], myobj) #make a new find devices that casts everything with the pythonized device_addr_t which has __str__ def find_devices(*args, **kwargs): def to_pythonized_dev_addr(dev_addr): new_dev_addr = uhd_swig.device_addr_t() for key in dev_addr.keys(): new_dev_addr[key] = dev_addr.get(key) return new_dev_addr return __builtins__['map'](to_pythonized_dev_addr, uhd_swig.find_devices_raw(*args, **kwargs)) setattr(uhd_swig, 'find_devices', find_devices) #Cast constructor args (FIXME swig handle overloads?) for attr in ('usrp_source', 'usrp_sink', 'amsg_source'): def constructor_factory(old_constructor): def constructor_interceptor(*args, **kwargs): args = list(args) kwargs = dict(kwargs) for index, key, cast in ( (0, 'device_addr', device_addr), (1, 'io_type', io_type), ): try: if len(args) > index: args[index] = cast(args[index]) if kwargs.has_key(key): kwargs[key] = cast(kwargs[key]) except: pass #dont pass kwargs, it confuses swig, map into args list: for key in ('device_addr', 'stream_args', 'io_type', 'num_channels'): if kwargs.has_key(key): args.append(kwargs[key]) return old_constructor(*args) return constructor_interceptor setattr(uhd_swig, attr, constructor_factory(getattr(uhd_swig, attr))) #Aliases for deprecated constructors setattr(uhd_swig, 'single_usrp_source', uhd_swig.usrp_source) setattr(uhd_swig, 'single_usrp_sink', uhd_swig.usrp_sink) setattr(uhd_swig, 'multi_usrp_source', uhd_swig.usrp_source) setattr(uhd_swig, 'multi_usrp_sink', uhd_swig.usrp_sink) ######################################################################## # Initialize this module with the contents of uhd swig ######################################################################## _prepare_uhd_swig() from uhd_swig import * gnuradio-3.7.2.1/gr-uhd/lib/0000755000175000017500000000000012207702530015254 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/lib/amsg_source_impl.cc0000664000175000017500000000446512207440367021135 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "amsg_source_impl.h" #include "gr_uhd_common.h" #include namespace gr { namespace uhd { amsg_source::sptr amsg_source::make(const ::uhd::device_addr_t &device_addr, msg_queue::sptr msgq) { check_abi(); return amsg_source::sptr (new amsg_source_impl(device_addr, msgq)); } ::uhd::async_metadata_t amsg_source::msg_to_async_metadata_t(const message::sptr msg) { return *(::uhd::async_metadata_t *)msg->msg(); } amsg_source_impl::amsg_source_impl(const ::uhd::device_addr_t &device_addr, msg_queue::sptr msgq) : _msgq(msgq), _running(true) { _dev = ::uhd::usrp::multi_usrp::make(device_addr); _amsg_thread = gr::thread::thread(boost::bind(&amsg_source_impl::recv_loop, this)); } amsg_source_impl::~amsg_source_impl() { _running = false; _amsg_thread.join(); } void amsg_source_impl::recv_loop() { message::sptr msg; ::uhd::async_metadata_t *md; while(_running) { msg = message::make(0, 0.0, 0.0, sizeof(::uhd::async_metadata_t)); md = (::uhd::async_metadata_t*) msg->msg(); while(!_dev->get_device()->recv_async_msg(*md, 0.1)) { if(!_running) return; } post(msg); } } void amsg_source_impl::post(message::sptr msg) { _msgq->insert_tail(msg); } } /* namespace uhd */ } /* namespace gr */ gnuradio-3.7.2.1/gr-uhd/lib/CMakeLists.txt0000664000175000017500000000453212207440367020031 0ustar jcorganjcorgan# Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${GR_UHD_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${LOG4CXX_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${UHD_INCLUDE_DIRS} ) link_directories( ${UHD_LIBRARY_DIRS} ${LOG4CXX_LIBRARY_DIRS} ${Boost_LIBRARY_DIRS} ) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) include_directories(${LOG4CPP_INCLUDE_DIRS}) link_directories(${LOG4CPP_LIBRARY_DIRS}) ######################################################################## # Setup library ######################################################################## list(APPEND gr_uhd_sources usrp_source_impl.cc usrp_sink_impl.cc amsg_source_impl.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-uhd.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-uhd.rc @ONLY) list(APPEND gr_uhd_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-uhd.rc ) endif(MSVC) list(APPEND uhd_libs gnuradio-runtime ${Boost_LIBRARIES} ${UHD_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_library(gnuradio-uhd SHARED ${gr_uhd_sources}) target_link_libraries(gnuradio-uhd ${uhd_libs}) GR_LIBRARY_FOO(gnuradio-uhd RUNTIME_COMPONENT "uhd_runtime" DEVEL_COMPONENT "uhd_devel") gnuradio-3.7.2.1/gr-uhd/lib/usrp_sink_impl.h0000664000175000017500000001332712207440367020502 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include static const pmt::pmt_t SOB_KEY = pmt::string_to_symbol("tx_sob"); static const pmt::pmt_t EOB_KEY = pmt::string_to_symbol("tx_eob"); static const pmt::pmt_t TIME_KEY = pmt::string_to_symbol("tx_time"); namespace gr { namespace uhd { inline io_signature::sptr args_to_io_sig(const ::uhd::stream_args_t &args) { const size_t nchan = std::max(args.channels.size(), 1); #ifdef GR_UHD_USE_STREAM_API const size_t size = ::uhd::convert::get_bytes_per_item(args.cpu_format); #else size_t size = 0; if(args.cpu_format == "fc32") size = 8; if(args.cpu_format == "sc16") size = 4; #endif return io_signature::make(nchan, nchan, size); } /*********************************************************************** * UHD Multi USRP Sink Impl **********************************************************************/ class usrp_sink_impl : public usrp_sink { public: usrp_sink_impl(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args); ~usrp_sink_impl(); void setup_rpc(); ::uhd::dict get_usrp_info(size_t chan); double get_samp_rate(void); ::uhd::meta_range_t get_samp_rates(void); double get_center_freq(size_t chan); ::uhd::freq_range_t get_freq_range(size_t chan); double get_gain(size_t chan); double get_gain(const std::string &name, size_t chan); std::vector get_gain_names(size_t chan); ::uhd::gain_range_t get_gain_range(size_t chan); ::uhd::gain_range_t get_gain_range(const std::string &name, size_t chan); std::string get_antenna(size_t chan); std::vector get_antennas(size_t chan); ::uhd::sensor_value_t get_sensor(const std::string &name, size_t chan); std::vector get_sensor_names(size_t chan); ::uhd::sensor_value_t get_mboard_sensor(const std::string &name, size_t mboard); std::vector get_mboard_sensor_names(size_t mboard); std::string get_time_source(const size_t mboard); std::vector get_time_sources(const size_t mboard); std::string get_clock_source(const size_t mboard); std::vector get_clock_sources(const size_t mboard); double get_clock_rate(size_t mboard); ::uhd::time_spec_t get_time_now(size_t mboard = 0); ::uhd::time_spec_t get_time_last_pps(size_t mboard); ::uhd::usrp::dboard_iface::sptr get_dboard_iface(size_t chan); ::uhd::usrp::multi_usrp::sptr get_device(void); void set_subdev_spec(const std::string &spec, size_t mboard); std::string get_subdev_spec(size_t mboard); void set_samp_rate(double rate); ::uhd::tune_result_t set_center_freq(const ::uhd::tune_request_t tune_request, size_t chan); void set_gain(double gain, size_t chan); void set_gain(double gain, const std::string &name, size_t chan); void set_antenna(const std::string &ant, size_t chan); void set_bandwidth(double bandwidth, size_t chan); double get_bandwidth(size_t chan); ::uhd::freq_range_t get_bandwidth_range(size_t chan); void set_dc_offset(const std::complex &offset, size_t chan); void set_iq_balance(const std::complex &correction, size_t chan); void set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard); void set_time_source(const std::string &source, const size_t mboard); void set_clock_source(const std::string &source, const size_t mboard); void set_clock_rate(double rate, size_t mboard); void set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard); void set_time_next_pps(const ::uhd::time_spec_t &time_spec); void set_time_unknown_pps(const ::uhd::time_spec_t &time_spec); void set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard); void clear_command_time(size_t mboard); void set_user_register(const uint8_t addr, const uint32_t data, size_t mboard); void set_start_time(const ::uhd::time_spec_t &time); bool start(void); bool stop(void); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); inline void tag_work(int &ninput_items); private: ::uhd::usrp::multi_usrp::sptr _dev; const ::uhd::stream_args_t _stream_args; boost::shared_ptr< ::uhd::io_type_t > _type; #ifdef GR_UHD_USE_STREAM_API ::uhd::tx_streamer::sptr _tx_stream; #endif size_t _nchan; bool _stream_now; ::uhd::tx_metadata_t _metadata; double _sample_rate; ::uhd::time_spec_t _start_time; bool _start_time_set; //stream tags related stuff std::vector _tags; }; } /* namespace uhd */ } /* namespace gr */ gnuradio-3.7.2.1/gr-uhd/lib/usrp_source_impl.h0000664000175000017500000001412512207440367021033 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include static const pmt::pmt_t TIME_KEY = pmt::string_to_symbol("rx_time"); static const pmt::pmt_t RATE_KEY = pmt::string_to_symbol("rx_rate"); static const pmt::pmt_t FREQ_KEY = pmt::string_to_symbol("rx_freq"); namespace gr { namespace uhd { inline io_signature::sptr args_to_io_sig(const ::uhd::stream_args_t &args) { const size_t nchan = std::max(args.channels.size(), 1); #ifdef GR_UHD_USE_STREAM_API const size_t size = ::uhd::convert::get_bytes_per_item(args.cpu_format); #else size_t size = 0; if(args.cpu_format == "fc32") size = 8; if(args.cpu_format == "sc16") size = 4; #endif return io_signature::make(nchan, nchan, size); } /*********************************************************************** * UHD Multi USRP Source Impl **********************************************************************/ class usrp_source_impl : public usrp_source { public: usrp_source_impl(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args); ~usrp_source_impl(); void setup_rpc(); // Get Commands ::uhd::dict get_usrp_info(size_t chan); std::string get_subdev_spec(size_t mboard); double get_samp_rate(void); ::uhd::meta_range_t get_samp_rates(void); double get_center_freq(size_t chan); ::uhd::freq_range_t get_freq_range(size_t chan); double get_gain(size_t chan); double get_gain(const std::string &name, size_t chan); std::vector get_gain_names(size_t chan); ::uhd::gain_range_t get_gain_range(size_t chan); ::uhd::gain_range_t get_gain_range(const std::string &name, size_t chan); std::string get_antenna(size_t chan); std::vector get_antennas(size_t chan); ::uhd::sensor_value_t get_sensor(const std::string &name, size_t chan); std::vector get_sensor_names(size_t chan); ::uhd::sensor_value_t get_mboard_sensor(const std::string &name, size_t mboard); std::vector get_mboard_sensor_names(size_t mboard); std::string get_time_source(const size_t mboard); std::vector get_time_sources(const size_t mboard); std::string get_clock_source(const size_t mboard); std::vector get_clock_sources(const size_t mboard); double get_clock_rate(size_t mboard); ::uhd::time_spec_t get_time_now(size_t mboard = 0); ::uhd::time_spec_t get_time_last_pps(size_t mboard); ::uhd::usrp::dboard_iface::sptr get_dboard_iface(size_t chan); ::uhd::usrp::multi_usrp::sptr get_device(void); // Set Commands void set_subdev_spec(const std::string &spec, size_t mboard); void set_samp_rate(double rate); ::uhd::tune_result_t set_center_freq(const ::uhd::tune_request_t tune_request, size_t chan); void set_gain(double gain, size_t chan); void set_gain(double gain, const std::string &name, size_t chan); void set_antenna(const std::string &ant, size_t chan); void set_bandwidth(double bandwidth, size_t chan); double get_bandwidth(size_t chan); ::uhd::freq_range_t get_bandwidth_range(size_t chan); void set_auto_dc_offset(const bool enable, size_t chan); void set_dc_offset(const std::complex &offset, size_t chan); void set_iq_balance(const std::complex &correction, size_t chan); void set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard); void set_time_source(const std::string &source, const size_t mboard); void set_clock_source(const std::string &source, const size_t mboard); void set_clock_rate(double rate, size_t mboard); void set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard); void set_time_next_pps(const ::uhd::time_spec_t &time_spec); void set_time_unknown_pps(const ::uhd::time_spec_t &time_spec); void set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard); void set_user_register(const uint8_t addr, const uint32_t data, size_t mboard); void set_start_time(const ::uhd::time_spec_t &time); void issue_stream_cmd(const ::uhd::stream_cmd_t &cmd); void clear_command_time(size_t mboard); void flush(void); bool start(void); bool stop(void); std::vector > finite_acquisition(const size_t nsamps); std::vector > > finite_acquisition_v(const size_t nsamps); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); private: ::uhd::usrp::multi_usrp::sptr _dev; const ::uhd::stream_args_t _stream_args; boost::shared_ptr< ::uhd::io_type_t > _type; #ifdef GR_UHD_USE_STREAM_API ::uhd::rx_streamer::sptr _rx_stream; size_t _samps_per_packet; #endif size_t _nchan; bool _stream_now, _tag_now; ::uhd::rx_metadata_t _metadata; pmt::pmt_t _id; ::uhd::time_spec_t _start_time; bool _start_time_set; //tag shadows double _samp_rate; double _center_freq; }; } /* namespace uhd */ } /* namespace gr */ gnuradio-3.7.2.1/gr-uhd/lib/usrp_source_impl.cc0000664000175000017500000005030512207702530021162 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "usrp_source_impl.h" #include "gr_uhd_common.h" #include #include #include #include #include #include namespace gr { namespace uhd { usrp_source::sptr usrp_source::make(const ::uhd::device_addr_t &device_addr, const ::uhd::io_type_t &io_type, size_t num_channels) { //fill in the streamer args ::uhd::stream_args_t stream_args; switch(io_type.tid) { case ::uhd::io_type_t::COMPLEX_FLOAT32: stream_args.cpu_format = "fc32"; break; case ::uhd::io_type_t::COMPLEX_INT16: stream_args.cpu_format = "sc16"; break; default: throw std::runtime_error("only complex float and shorts known to work"); } stream_args.otw_format = "sc16"; //only sc16 known to work for(size_t chan = 0; chan < num_channels; chan++) stream_args.channels.push_back(chan); //linear mapping return usrp_source::make(device_addr, stream_args); } usrp_source::sptr usrp_source::make(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args) { check_abi(); return usrp_source::sptr (new usrp_source_impl(device_addr, stream_args_ensure(stream_args))); } usrp_source_impl::usrp_source_impl(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args): sync_block("gr uhd usrp source", io_signature::make(0, 0, 0), args_to_io_sig(stream_args)), _stream_args(stream_args), _nchan(stream_args.channels.size()), _stream_now(_nchan == 1), _tag_now(false), _start_time_set(false) { if(stream_args.cpu_format == "fc32") _type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_FLOAT32); if(stream_args.cpu_format == "sc16") _type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_INT16); std::stringstream str; str << name() << unique_id(); _id = pmt::string_to_symbol(str.str()); _dev = ::uhd::usrp::multi_usrp::make(device_addr); } usrp_source_impl::~usrp_source_impl() { } ::uhd::dict usrp_source_impl::get_usrp_info(size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_GET_USRP_INFO_API return _dev->get_usrp_rx_info(chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_subdev_spec(const std::string &spec, size_t mboard) { return _dev->set_rx_subdev_spec(spec, mboard); } std::string usrp_source_impl::get_subdev_spec(size_t mboard) { return _dev->get_rx_subdev_spec(mboard).to_string(); } void usrp_source_impl::set_samp_rate(double rate) { BOOST_FOREACH(const size_t chan, _stream_args.channels) { _dev->set_rx_rate(rate, chan); } _samp_rate = this->get_samp_rate(); _tag_now = true; } double usrp_source_impl::get_samp_rate(void) { return _dev->get_rx_rate(_stream_args.channels[0]); } ::uhd::meta_range_t usrp_source_impl::get_samp_rates(void) { #ifdef UHD_USRP_MULTI_USRP_GET_RATES_API return _dev->get_rx_rates(_stream_args.channels[0]); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::tune_result_t usrp_source_impl::set_center_freq(const ::uhd::tune_request_t tune_request, size_t chan) { const size_t user_chan = chan; chan = _stream_args.channels[chan]; const ::uhd::tune_result_t res = _dev->set_rx_freq(tune_request, chan); _center_freq = this->get_center_freq(user_chan); _tag_now = true; return res; } double usrp_source_impl::get_center_freq(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_freq(chan); } ::uhd::freq_range_t usrp_source_impl::get_freq_range(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_freq_range(chan); } void usrp_source_impl::set_gain(double gain, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_rx_gain(gain, chan); } void usrp_source_impl::set_gain(double gain, const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_rx_gain(gain, name, chan); } double usrp_source_impl::get_gain(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_gain(chan); } double usrp_source_impl::get_gain(const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_gain(name, chan); } std::vector usrp_source_impl::get_gain_names(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_gain_names(chan); } ::uhd::gain_range_t usrp_source_impl::get_gain_range(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_gain_range(chan); } ::uhd::gain_range_t usrp_source_impl::get_gain_range(const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_gain_range(name, chan); } void usrp_source_impl::set_antenna(const std::string &ant, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_rx_antenna(ant, chan); } std::string usrp_source_impl::get_antenna(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_antenna(chan); } std::vector usrp_source_impl::get_antennas(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_antennas(chan); } void usrp_source_impl::set_bandwidth(double bandwidth, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_rx_bandwidth(bandwidth, chan); } double usrp_source_impl::get_bandwidth(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_bandwidth(chan); } ::uhd::freq_range_t usrp_source_impl::get_bandwidth_range(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_bandwidth_range(chan); } void usrp_source_impl::set_auto_dc_offset(const bool enable, size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_rx_dc_offset(enable, chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_dc_offset(const std::complex &offset, size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_rx_dc_offset(offset, chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_iq_balance(const std::complex &correction, size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_rx_iq_balance(correction, chan); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::sensor_value_t usrp_source_impl::get_sensor(const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_sensor(name, chan); } std::vector usrp_source_impl::get_sensor_names(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_sensor_names(chan); } ::uhd::sensor_value_t usrp_source_impl::get_mboard_sensor(const std::string &name, size_t mboard) { return _dev->get_mboard_sensor(name, mboard); } std::vector usrp_source_impl::get_mboard_sensor_names(size_t mboard) { return _dev->get_mboard_sensor_names(mboard); } void usrp_source_impl::set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard) { return _dev->set_clock_config(clock_config, mboard); } void usrp_source_impl::set_time_source(const std::string &source, const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->set_time_source(source, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::string usrp_source_impl::get_time_source(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_time_source(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::vector usrp_source_impl::get_time_sources(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_time_sources(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_clock_source(const std::string &source, const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->set_clock_source(source, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::string usrp_source_impl::get_clock_source(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_clock_source(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::vector usrp_source_impl::get_clock_sources(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_clock_sources(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } double usrp_source_impl::get_clock_rate(size_t mboard) { return _dev->get_master_clock_rate(mboard); } void usrp_source_impl::set_clock_rate(double rate, size_t mboard) { return _dev->set_master_clock_rate(rate, mboard); } ::uhd::time_spec_t usrp_source_impl::get_time_now(size_t mboard) { return _dev->get_time_now(mboard); } ::uhd::time_spec_t usrp_source_impl::get_time_last_pps(size_t mboard) { return _dev->get_time_last_pps(mboard); } void usrp_source_impl::set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard) { return _dev->set_time_now(time_spec, mboard); } void usrp_source_impl::set_time_next_pps(const ::uhd::time_spec_t &time_spec) { return _dev->set_time_next_pps(time_spec); } void usrp_source_impl::set_time_unknown_pps(const ::uhd::time_spec_t &time_spec) { return _dev->set_time_unknown_pps(time_spec); } void usrp_source_impl::set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_COMMAND_TIME_API return _dev->set_command_time(time_spec, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::clear_command_time(size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_COMMAND_TIME_API return _dev->clear_command_time(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::usrp::dboard_iface::sptr usrp_source_impl::get_dboard_iface(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_rx_dboard_iface(chan); } ::uhd::usrp::multi_usrp::sptr usrp_source_impl::get_device(void) { return _dev; } void usrp_source_impl::set_user_register(const uint8_t addr, const uint32_t data, size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_USER_REGS_API _dev->set_user_register(addr, data, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_start_time(const ::uhd::time_spec_t &time) { _start_time = time; _start_time_set = true; _stream_now = false; } void usrp_source_impl::issue_stream_cmd(const ::uhd::stream_cmd_t &cmd) { for (size_t i = 0; i < _stream_args.channels.size(); i++) { _dev->issue_stream_cmd(cmd, _stream_args.channels[i]); } } bool usrp_source_impl::start(void) { #ifdef GR_UHD_USE_STREAM_API _rx_stream = _dev->get_rx_stream(_stream_args); _samps_per_packet = _rx_stream->get_max_num_samps(); #endif //setup a stream command that starts streaming slightly in the future static const double reasonable_delay = 0.1; //order of magnitude over RTT ::uhd::stream_cmd_t stream_cmd(::uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS); stream_cmd.stream_now = _stream_now; if(_start_time_set) { _start_time_set = false; //cleared for next run stream_cmd.time_spec = _start_time; } else { stream_cmd.time_spec = get_time_now() + ::uhd::time_spec_t(reasonable_delay); } this->issue_stream_cmd(stream_cmd); _tag_now = true; return true; } void usrp_source_impl::flush(void) { const size_t nbytes = 4096; gr_vector_void_star outputs; std::vector > buffs(_nchan, std::vector(nbytes)); for(size_t i = 0; i < _nchan; i++) { outputs.push_back(&buffs[i].front()); } while(true) { #ifdef GR_UHD_USE_STREAM_API const size_t bpi = ::uhd::convert::get_bytes_per_item(_stream_args.cpu_format); _rx_stream->recv(outputs, nbytes/bpi, _metadata, 0.0); #else _dev->get_device()->recv (outputs, nbytes/_type->size, _metadata, *_type, ::uhd::device::RECV_MODE_FULL_BUFF, 0.0); #endif if(_metadata.error_code == ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) break; } } bool usrp_source_impl::stop(void) { this->issue_stream_cmd(::uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS); this->flush(); return true; } std::vector > usrp_source_impl::finite_acquisition(const size_t nsamps) { if(_nchan != 1) throw std::runtime_error("finite_acquisition: usrp source has multiple channels, call finite_acquisition_v"); return finite_acquisition_v(nsamps).front(); } std::vector > > usrp_source_impl::finite_acquisition_v(const size_t nsamps) { #ifdef GR_UHD_USE_STREAM_API //kludgy way to ensure rx streamer exsists if(!_rx_stream) { this->start(); this->stop(); } //flush so there is no queued-up data this->flush(); //create a multi-dimensional container to hold an array of sample buffers std::vector > > samps(_nchan, std::vector >(nsamps)); //load the void* vector of buffer pointers std::vector buffs(_nchan); for(size_t i = 0; i < _nchan; i++) { buffs[i] = &samps[i].front(); } //tell the device to stream a finite amount ::uhd::stream_cmd_t cmd(::uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE); cmd.num_samps = nsamps; cmd.stream_now = _stream_now; static const double reasonable_delay = 0.1; //order of magnitude over RTT cmd.time_spec = get_time_now() + ::uhd::time_spec_t(reasonable_delay); this->issue_stream_cmd(cmd); //receive samples until timeout const size_t actual_num_samps = _rx_stream->recv (buffs, nsamps, _metadata, 1.0); //resize the resulting sample buffers for(size_t i = 0; i < _nchan; i++) { samps[i].resize(actual_num_samps); } return samps; #else throw std::runtime_error("not implemented in this version"); #endif } int usrp_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { #ifdef GR_UHD_USE_STREAM_API //In order to allow for low-latency: //We receive all available packets without timeout. //This call can timeout under regular operation... size_t num_samps = _rx_stream->recv (output_items, noutput_items, _metadata, 0.0); //If receive resulted in a timeout condition: //We now receive a single packet with a large timeout. if(_metadata.error_code == ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) { num_samps = _rx_stream->recv (output_items, noutput_items, _metadata, 0.1, true/*one pkt*/); } #else size_t num_samps = _dev->get_device()->recv (output_items, noutput_items, _metadata, *_type, ::uhd::device::RECV_MODE_FULL_BUFF, 0.0); if(_metadata.error_code == ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) { num_samps = _dev->get_device()->recv (output_items, noutput_items, _metadata, *_type, ::uhd::device::RECV_MODE_ONE_PACKET, 1.0); } #endif //handle possible errors conditions switch(_metadata.error_code) { case ::uhd::rx_metadata_t::ERROR_CODE_NONE: if(_tag_now) { _tag_now = false; //create a timestamp pmt for the first sample const pmt::pmt_t val = pmt::make_tuple (pmt::from_uint64(_metadata.time_spec.get_full_secs()), pmt::from_double(_metadata.time_spec.get_frac_secs())); //create a tag set for each channel for(size_t i = 0; i < _nchan; i++) { this->add_item_tag(i, nitems_written(0), TIME_KEY, val, _id); this->add_item_tag(i, nitems_written(0), RATE_KEY, pmt::from_double(_samp_rate), _id); this->add_item_tag(i, nitems_written(0), FREQ_KEY, pmt::from_double(_center_freq), _id); } } break; case ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT: //its ok to timeout, perhaps the user is doing finite streaming return 0; case ::uhd::rx_metadata_t::ERROR_CODE_OVERFLOW: _tag_now = true; //ignore overflows and try work again return work(noutput_items, input_items, output_items); default: std::cout << boost::format("UHD source block got error code 0x%x") % _metadata.error_code << std::endl; return num_samps; } return num_samps; } void usrp_source_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "samp_rate", &usrp_source::get_samp_rate, pmt::mp(100000.0f), pmt::mp(25000000.0f), pmt::mp(1000000.0f), "sps", "RX Sample Rate", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "samp_rate", &usrp_source::set_samp_rate, pmt::mp(100000.0f), pmt::mp(25000000.0f), pmt::mp(1000000.0f), "sps", "RX Sample Rate", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace uhd */ } /* namespace gr */ gnuradio-3.7.2.1/gr-uhd/lib/usrp_sink_impl.cc0000664000175000017500000004406012207702530020627 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "usrp_sink_impl.h" #include "gr_uhd_common.h" #include #include #include namespace gr { namespace uhd { usrp_sink::sptr usrp_sink::make(const ::uhd::device_addr_t &device_addr, const ::uhd::io_type_t &io_type, size_t num_channels) { //fill in the streamer args ::uhd::stream_args_t stream_args; switch(io_type.tid) { case ::uhd::io_type_t::COMPLEX_FLOAT32: stream_args.cpu_format = "fc32"; break; case ::uhd::io_type_t::COMPLEX_INT16: stream_args.cpu_format = "sc16"; break; default: throw std::runtime_error("only complex float and shorts known to work"); } stream_args.otw_format = "sc16"; //only sc16 known to work for(size_t chan = 0; chan < num_channels; chan++) stream_args.channels.push_back(chan); //linear mapping return usrp_sink::make(device_addr, stream_args); } usrp_sink::sptr usrp_sink::make(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args) { check_abi(); return usrp_sink::sptr (new usrp_sink_impl(device_addr, stream_args_ensure(stream_args))); } usrp_sink_impl::usrp_sink_impl(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args) : sync_block("gr uhd usrp sink", args_to_io_sig(stream_args), io_signature::make(0, 0, 0)), _stream_args(stream_args), _nchan(stream_args.channels.size()), _stream_now(_nchan == 1), _start_time_set(false) { if(stream_args.cpu_format == "fc32") _type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_FLOAT32); if(stream_args.cpu_format == "sc16") _type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_INT16); _dev = ::uhd::usrp::multi_usrp::make(device_addr); } usrp_sink_impl::~usrp_sink_impl() { } ::uhd::dict usrp_sink_impl::get_usrp_info(size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_GET_USRP_INFO_API return _dev->get_usrp_tx_info(chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_sink_impl::set_subdev_spec(const std::string &spec, size_t mboard) { return _dev->set_tx_subdev_spec(spec, mboard); } std::string usrp_sink_impl::get_subdev_spec(size_t mboard) { return _dev->get_tx_subdev_spec(mboard).to_string(); } void usrp_sink_impl::set_samp_rate(double rate) { BOOST_FOREACH(const size_t chan, _stream_args.channels) { _dev->set_tx_rate(rate, chan); } _sample_rate = this->get_samp_rate(); } double usrp_sink_impl::get_samp_rate(void) { return _dev->get_tx_rate(_stream_args.channels[0]); } ::uhd::meta_range_t usrp_sink_impl::get_samp_rates(void) { #ifdef UHD_USRP_MULTI_USRP_GET_RATES_API return _dev->get_tx_rates(_stream_args.channels[0]); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::tune_result_t usrp_sink_impl::set_center_freq(const ::uhd::tune_request_t tune_request, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_tx_freq(tune_request, chan); } double usrp_sink_impl::get_center_freq(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_freq(chan); } ::uhd::freq_range_t usrp_sink_impl::get_freq_range(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_freq_range(chan); } void usrp_sink_impl::set_gain(double gain, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_tx_gain(gain, chan); } void usrp_sink_impl::set_gain(double gain, const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_tx_gain(gain, name, chan); } double usrp_sink_impl::get_gain(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_gain(chan); } double usrp_sink_impl::get_gain(const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_gain(name, chan); } std::vector usrp_sink_impl::get_gain_names(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_gain_names(chan); } ::uhd::gain_range_t usrp_sink_impl::get_gain_range(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_gain_range(chan); } ::uhd::gain_range_t usrp_sink_impl::get_gain_range(const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_gain_range(name, chan); } void usrp_sink_impl::set_antenna(const std::string &ant, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_tx_antenna(ant, chan); } std::string usrp_sink_impl::get_antenna(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_antenna(chan); } std::vector usrp_sink_impl::get_antennas(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_antennas(chan); } void usrp_sink_impl::set_bandwidth(double bandwidth, size_t chan) { chan = _stream_args.channels[chan]; return _dev->set_tx_bandwidth(bandwidth, chan); } double usrp_sink_impl::get_bandwidth(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_bandwidth(chan); } ::uhd::freq_range_t usrp_sink_impl::get_bandwidth_range(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_bandwidth_range(chan); } void usrp_sink_impl::set_dc_offset(const std::complex &offset, size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_tx_dc_offset(offset, chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_sink_impl::set_iq_balance(const std::complex &correction, size_t chan) { chan = _stream_args.channels[chan]; #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_tx_iq_balance(correction, chan); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::sensor_value_t usrp_sink_impl::get_sensor(const std::string &name, size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_sensor(name, chan); } std::vector usrp_sink_impl::get_sensor_names(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_sensor_names(chan); } ::uhd::sensor_value_t usrp_sink_impl::get_mboard_sensor(const std::string &name, size_t mboard) { return _dev->get_mboard_sensor(name, mboard); } std::vector usrp_sink_impl::get_mboard_sensor_names(size_t mboard) { return _dev->get_mboard_sensor_names(mboard); } void usrp_sink_impl::set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard) { return _dev->set_clock_config(clock_config, mboard); } void usrp_sink_impl::set_time_source(const std::string &source, const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->set_time_source(source, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::string usrp_sink_impl::get_time_source(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_time_source(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::vector usrp_sink_impl::get_time_sources(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_time_sources(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_sink_impl::set_clock_source(const std::string &source, const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->set_clock_source(source, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::string usrp_sink_impl::get_clock_source(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_clock_source(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::vector usrp_sink_impl::get_clock_sources(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_clock_sources(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } double usrp_sink_impl::get_clock_rate(size_t mboard) { return _dev->get_master_clock_rate(mboard); } void usrp_sink_impl::set_clock_rate(double rate, size_t mboard) { return _dev->set_master_clock_rate(rate, mboard); } ::uhd::time_spec_t usrp_sink_impl::get_time_now(size_t mboard) { return _dev->get_time_now(mboard); } ::uhd::time_spec_t usrp_sink_impl::get_time_last_pps(size_t mboard) { return _dev->get_time_last_pps(mboard); } void usrp_sink_impl::set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard) { return _dev->set_time_now(time_spec, mboard); } void usrp_sink_impl::set_time_next_pps(const ::uhd::time_spec_t &time_spec) { return _dev->set_time_next_pps(time_spec); } void usrp_sink_impl::set_time_unknown_pps(const ::uhd::time_spec_t &time_spec) { return _dev->set_time_unknown_pps(time_spec); } void usrp_sink_impl::set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_COMMAND_TIME_API return _dev->set_command_time(time_spec, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_sink_impl::clear_command_time(size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_COMMAND_TIME_API return _dev->clear_command_time(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::usrp::dboard_iface::sptr usrp_sink_impl::get_dboard_iface(size_t chan) { chan = _stream_args.channels[chan]; return _dev->get_tx_dboard_iface(chan); } ::uhd::usrp::multi_usrp::sptr usrp_sink_impl::get_device(void) { return _dev; } void usrp_sink_impl::set_user_register(const uint8_t addr, const uint32_t data, size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_USER_REGS_API _dev->set_user_register(addr, data, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } /*********************************************************************** * Work **********************************************************************/ int usrp_sink_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { int ninput_items = noutput_items; //cuz its a sync block //send a mid-burst packet with time spec _metadata.start_of_burst = false; _metadata.end_of_burst = false; //collect tags in this work() const uint64_t samp0_count = nitems_read(0); get_tags_in_range(_tags, 0, samp0_count, samp0_count + ninput_items); if(not _tags.empty()) this->tag_work(ninput_items); #ifdef GR_UHD_USE_STREAM_API //send all ninput_items with metadata const size_t num_sent = _tx_stream->send (input_items, ninput_items, _metadata, 1.0); #else const size_t num_sent = _dev->get_device()->send (input_items, ninput_items, _metadata, *_type, ::uhd::device::SEND_MODE_FULL_BUFF, 1.0); #endif //increment the timespec by the number of samples sent _metadata.time_spec += ::uhd::time_spec_t(0, num_sent, _sample_rate); return num_sent; } /*********************************************************************** * Tag Work **********************************************************************/ void usrp_sink_impl::tag_work(int &ninput_items) { //the for loop below assumes tags sorted by count low -> high std::sort(_tags.begin(), _tags.end(), tag_t::offset_compare); //extract absolute sample counts const tag_t &tag0 = _tags.front(); const uint64_t tag0_count = tag0.offset; const uint64_t samp0_count = this->nitems_read(0); //only transmit nsamples from 0 to the first tag //this ensures that the next work starts on a tag if(samp0_count != tag0_count) { ninput_items = tag0_count - samp0_count; return; } //time will not be set unless a time tag is found _metadata.has_time_spec = false; //process all of the tags found with the same count as tag0 BOOST_FOREACH(const tag_t &my_tag, _tags) { const uint64_t my_tag_count = my_tag.offset; const pmt::pmt_t &key = my_tag.key; const pmt::pmt_t &value = my_tag.value; //determine how many samples to send... //from zero until the next tag or end of work if(my_tag_count != tag0_count) { ninput_items = my_tag_count - samp0_count; break; } //handle end of burst with a mini end of burst packet else if(pmt::equal(key, EOB_KEY)) { _metadata.end_of_burst = pmt::to_bool(value); ninput_items = 1; return; } //set the start of burst flag in the metadata else if(pmt::equal(key, SOB_KEY)) { _metadata.start_of_burst = pmt::to_bool(value); } //set the time specification in the metadata else if(pmt::equal(key, TIME_KEY)) { _metadata.has_time_spec = true; _metadata.time_spec = ::uhd::time_spec_t (pmt::to_uint64(pmt::tuple_ref(value, 0)), pmt::to_double(pmt::tuple_ref(value, 1))); } } } void usrp_sink_impl::set_start_time(const ::uhd::time_spec_t &time) { _start_time = time; _start_time_set = true; _stream_now = false; } //Send an empty start-of-burst packet to begin streaming. //Set at a time in the near future to avoid late packets. bool usrp_sink_impl::start(void) { #ifdef GR_UHD_USE_STREAM_API _tx_stream = _dev->get_tx_stream(_stream_args); #endif _metadata.start_of_burst = true; _metadata.end_of_burst = false; _metadata.has_time_spec = not _stream_now; if(_start_time_set) { _start_time_set = false; //cleared for next run _metadata.time_spec = _start_time; } else { _metadata.time_spec = get_time_now() + ::uhd::time_spec_t(0.01); } #ifdef GR_UHD_USE_STREAM_API _tx_stream->send (gr_vector_const_void_star(_nchan), 0, _metadata, 1.0); #else _dev->get_device()->send (gr_vector_const_void_star(_nchan), 0, _metadata, *_type, ::uhd::device::SEND_MODE_ONE_PACKET, 1.0); #endif return true; } //Send an empty end-of-burst packet to end streaming. //Ending the burst avoids an underflow error on stop. bool usrp_sink_impl::stop(void) { _metadata.start_of_burst = false; _metadata.end_of_burst = true; _metadata.has_time_spec = false; #ifdef GR_UHD_USE_STREAM_API _tx_stream->send(gr_vector_const_void_star(_nchan), 0, _metadata, 1.0); #else _dev->get_device()->send (gr_vector_const_void_star(_nchan), 0, _metadata, *_type, ::uhd::device::SEND_MODE_ONE_PACKET, 1.0); #endif return true; } void usrp_sink_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get( alias(), "samp_rate", &usrp_sink::get_samp_rate, pmt::mp(100000.0f), pmt::mp(25000000.0f), pmt::mp(1000000.0f), "sps", "TX Sample Rate", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set( alias(), "samp_rate", &usrp_sink::set_samp_rate, pmt::mp(100000.0f), pmt::mp(25000000.0f), pmt::mp(1000000.0f), "sps", "TX Sample Rate", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace uhd */ } /* namespace gr */ gnuradio-3.7.2.1/gr-uhd/lib/gnuradio-uhd.rc.in0000664000175000017500000000331212207440367020605 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-uhd" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-uhd.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-uhd.dll" VALUE "ProductName", "gnuradio-uhd" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-uhd/lib/gr_uhd_common.h0000664000175000017500000000407212207702530020252 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2012-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_GR_UHD_COMMON_H #define INCLUDED_GR_UHD_COMMON_H #include #include #include namespace gr { namespace uhd { static inline void check_abi(void) { #ifdef UHD_VERSION_ABI_STRING if(std::string(UHD_VERSION_ABI_STRING) == ::uhd::get_abi_string()) return; throw std::runtime_error(str(boost::format( "\nGR-UHD detected ABI compatibility mismatch with UHD library.\n" "GR-UHD was build against ABI: %s,\n" "but UHD library reports ABI: %s\n" "Suggestion: install an ABI compatible version of UHD,\n" "or rebuild GR-UHD component against this ABI version.\n" ) % UHD_VERSION_ABI_STRING % ::uhd::get_abi_string())); #endif } } /* namespace uhd */ } /* namespace gr */ /*! * The stream args ensure function sanitizes random user input. * We may extend this to handle more things in the future, * but ATM it ensures that the channels are initialized. */ static inline uhd::stream_args_t stream_args_ensure(const uhd::stream_args_t &args) { uhd::stream_args_t sanitized = args; if (sanitized.channels.empty()) { sanitized.channels.push_back(0); } return sanitized; } #endif /* INCLUDED_GR_UHD_COMMON_H */ gnuradio-3.7.2.1/gr-uhd/lib/amsg_source_impl.h0000664000175000017500000000257112207440367020773 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include namespace gr { namespace uhd { class amsg_source_impl : public amsg_source { public: amsg_source_impl(const ::uhd::device_addr_t &device_addr, msg_queue::sptr msgq); ~amsg_source_impl(); void recv_loop(); void post(message::sptr msg); protected: ::uhd::usrp::multi_usrp::sptr _dev; gr::thread::thread _amsg_thread; msg_queue::sptr _msgq; bool _running; }; } /* namespace uhd */ } /* namespace gr */ gnuradio-3.7.2.1/gr-uhd/gnuradio-uhd.pc.in0000664000175000017500000000036212207440367020037 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-uhd Description: GNU Radio blocks for UHD Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-uhd Cflags: -I${includedir} gnuradio-3.7.2.1/gr-uhd/swig/0000755000175000017500000000000012237515112015460 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/swig/CMakeLists.txt0000664000175000017500000000361012207440367020230 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_FLAGS -DGR_HAVE_UHD) #needed to parse uhd_swig.i set(GR_SWIG_INCLUDE_DIRS ${GR_UHD_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${UHD_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/uhd_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/uhd) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) link_directories(${UHD_LIBRARY_DIRS}) set(GR_SWIG_LIBRARIES gnuradio-uhd ${UHD_LIBRARIES}) GR_SWIG_MAKE(uhd_swig uhd_swig.i) GR_SWIG_INSTALL( TARGETS uhd_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/uhd COMPONENT "uhd_python" ) install( FILES uhd_swig.i ${CMAKE_CURRENT_BINARY_DIR}/uhd_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "uhd_swig" ) gnuradio-3.7.2.1/gr-uhd/swig/uhd_swig.i0000664000175000017500000001067112237515112017452 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ // Defined during configure; avoids trying to locate // header files if UHD was not installed. #ifdef GR_HAVE_UHD #define GR_UHD_API //suppress 319. No access specifier given for base class name (ignored). #pragma SWIG nowarn=319 //////////////////////////////////////////////////////////////////////// // standard includes //////////////////////////////////////////////////////////////////////// %include %include "gnuradio.i" //load generated python docstrings %include "uhd_swig_doc.i" //////////////////////////////////////////////////////////////////////// // block headers //////////////////////////////////////////////////////////////////////// %{ #include #include #include %} //////////////////////////////////////////////////////////////////////// // used types //////////////////////////////////////////////////////////////////////// %template(uhd_string_vector_t) std::vector; %template(uhd_size_vector_t) std::vector; %include %include %ignore uhd::dict::operator[]; //ignore warnings about %extend %include %template(string_string_dict_t) uhd::dict; //define after dict %extend uhd::dict{ std::string __getitem__(std::string key) {return (*self)[key];} void __setitem__(std::string key, std::string val) {(*self)[key] = val;} }; %include %include %template(range_vector_t) std::vector; //define before range %include %include %include %include %include %include %include %include %template(device_addr_vector_t) std::vector; %include %include //////////////////////////////////////////////////////////////////////// // swig dboard_iface for python access //////////////////////////////////////////////////////////////////////// %include stdint.i %include %include %template(dboard_iface_sptr) boost::shared_ptr; //////////////////////////////////////////////////////////////////////// // block magic //////////////////////////////////////////////////////////////////////// %include %include %include GR_SWIG_BLOCK_MAGIC2(uhd, usrp_source) GR_SWIG_BLOCK_MAGIC2(uhd, usrp_sink) GR_SWIG_BLOCK_MAGIC2(uhd, amsg_source) //////////////////////////////////////////////////////////////////////// // device discovery (no need to %include device.hpp) //////////////////////////////////////////////////////////////////////// %{ static uhd::device_addrs_t find_devices_raw(const uhd::device_addr_t &dev_addr = uhd::device_addr_t()){ return uhd::device::find(dev_addr); } %} static uhd::device_addrs_t find_devices_raw(const uhd::device_addr_t &dev_addr = uhd::device_addr_t()); //////////////////////////////////////////////////////////////////////// // helpful constants //////////////////////////////////////////////////////////////////////// %{ static const size_t ALL_MBOARDS = uhd::usrp::multi_usrp::ALL_MBOARDS; %} static const size_t ALL_MBOARDS; %{ #include std::string get_version_string(void){ return uhd::get_version_string(); } %} std::string get_version_string(void); #endif /* GR_HAVE_UHD */ gnuradio-3.7.2.1/gr-uhd/apps/0000755000175000017500000000000012237515112015452 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/apps/CMakeLists.txt0000644000175000017500000000466411744612271020232 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) ######################################################################## # Install some uhd apps ######################################################################## GR_PYTHON_INSTALL( FILES uhd_siggen_base.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/uhd COMPONENT "uhd_python" ) GR_PYTHON_INSTALL( PROGRAMS uhd_fft uhd_rx_cfile uhd_siggen uhd_siggen_gui uhd_rx_nogui DESTINATION ${GR_RUNTIME_DIR} COMPONENT "uhd_python" ) ######################################################################## # Install hf radio apps ######################################################################## install( FILES hf_radio/hfir.sci hf_radio/radio.xml hf_radio/README.TXT hf_radio/ssb_taps DESTINATION ${GR_PKG_DATA_DIR}/examples/hf_radio COMPONENT "uhd_python" ) GR_PYTHON_INSTALL( PROGRAMS hf_radio/input.py hf_radio/output.py hf_radio/ssbagc.py hf_radio/ssbdemod.py hf_radio/startup.py DESTINATION ${GR_PKG_DATA_DIR}/examples/hf_radio COMPONENT "uhd_python" ) GR_PYTHON_INSTALL( PROGRAMS hf_radio/radio.py hf_radio/ui.py DESTINATION ${GR_PKG_DATA_DIR}/examples/hf_radio COMPONENT "uhd_python" ) ######################################################################## # Install hf explorer ######################################################################## install( FILES hf_explorer/README hf_explorer/hfx_help DESTINATION ${GR_PKG_DATA_DIR}/examples/hf_explorer COMPONENT "uhd_python" ) GR_PYTHON_INSTALL( PROGRAMS hf_explorer/hfx.py DESTINATION ${GR_PKG_DATA_DIR}/examples/hf_explorer COMPONENT "uhd_python" ) gnuradio-3.7.2.1/gr-uhd/apps/hf_explorer/0000755000175000017500000000000012207440367017775 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/apps/hf_explorer/hfx.py0000775000175000017500000010326212207440367021145 0ustar jcorganjcorgan#!/usr/bin/env python # generated by wxGlade 0.4 on Tue Mar 14 10:16:06 2006 # # Copyright 2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # #----------------------------------------------------------------- # # +-->(fft) # | # (src)->(xlate)--+->(audio filter)--+-->(sel_am)-+--------------+ # | | | # | (pll) | # | | | # | (pll_carrier_scale) | # | | | # | (pll_carrier_filter) | # | | | # | +--(fft2) | # | | | # | +--(c2f3)--+ | # | | | | # | (phaser1) (phaser2) | # | | | | # | +--(f2c)---+ | # | | V # V +---------->(am_det) # (c2f) | # | (c2f2) # | | # +-->(sel_sb)------------>(combine) # | # V # +--------------------------(scale) # | | # | | # | +++ # V | | # (agc)<--(offset)<--(intr)<---(sqr1) # | # V # (dst) # #---------------------------------------------------------------------- # # Versions 2.2.1 adds loop antenna automatic tuner # # 2.3.1 adds web control, made AM Sync display optional, # added more comments. # # 2.4.1 updates usrp interface to support auto subdev # # 2.8.1 changed saved file format from 8-byte complex to # 4-byte short for obvious storage space savings. # Web server control disabled by default. Do not enable # until directory structure and scripts are in place. WEB_CONTROL = False # Controls display of AM Sync Carrier - turn off for smaller # window if not needed AM_SYNC_DISPLAY = False import os, wx, sys, math import wx.lib.evtmgr as em from gnuradio.wxgui import powermate, fftsink2 from gnuradio import gr, audio, eng_notation from gnuradio import analog from gnuradio import filter from gnuradio import blocks from gnuradio.eng_option import eng_option from gnuradio import uhd from optparse import OptionParser n2s = eng_notation.num_to_str ID_BUTTON_1 = wx.NewId() # LSB button ID_BUTTON_2 = wx.NewId() # USB ID_BUTTON_3 = wx.NewId() # AM ID_BUTTON_4 = wx.NewId() # CW ID_BUTTON_5 = wx.NewId() # Powermate controls: Upper audio freq cutoff ID_BUTTON_6 = wx.NewId() # " Lower audio freq cutoff ID_BUTTON_7 = wx.NewId() # " Frequency ID_BUTTON_8 = wx.NewId() # " Volume ID_BUTTON_9 = wx.NewId() # " Time ID_BUTTON_10 = wx.NewId() # Time Seek Forwards ID_BUTTON_11 = wx.NewId() # Time Seek Backwards ID_BUTTON_12 = wx.NewId() # Automatic Antenna Tune (AT) enable ID_BUTTON_13 = wx.NewId() # AT Calibrate point ID_BUTTON_14 = wx.NewId() # AT Reset ID_TEXT_1 = wx.NewId() # Band Center, USRP ddc Freq ID_SPIN_1 = wx.NewId() # Frequency display and control ID_SLIDER_1 = wx.NewId() # Upper audio freq cutoff ID_SLIDER_2 = wx.NewId() # Lower audio freq cutoff ID_SLIDER_3 = wx.NewId() # Frequency ID_SLIDER_4 = wx.NewId() # Volume ID_SLIDER_5 = wx.NewId() # Programmable Gain Amp, PGA, RF gain ID_SLIDER_6 = wx.NewId() # AM Sync carrier level ID_SLIDER_7 = wx.NewId() # AT control voltage output ID_EXIT = wx.NewId() # Menu Exit class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) # Menu Bar self.frame_1_menubar = wx.MenuBar() self.SetMenuBar(self.frame_1_menubar) wxglade_tmp_menu = wx.Menu() self.Exit = wx.MenuItem(wxglade_tmp_menu, ID_EXIT, "Exit", "Exit", wx.ITEM_NORMAL) wxglade_tmp_menu.AppendItem(self.Exit) self.frame_1_menubar.Append(wxglade_tmp_menu, "File") # Menu Bar end self.panel_1 = wx.Panel(self, -1) self.button_1 = wx.Button(self, ID_BUTTON_1, "LSB") self.button_2 = wx.Button(self, ID_BUTTON_2, "USB") self.button_3 = wx.Button(self, ID_BUTTON_3, "AM") self.button_4 = wx.Button(self, ID_BUTTON_4, "CW") self.button_5 = wx.ToggleButton(self, ID_BUTTON_5, "Upper") self.slider_fcutoff_hi = wx.Slider(self, ID_SLIDER_1, 0, -15798, 15799, style=wx.SL_HORIZONTAL|wx.SL_LABELS) self.button_6 = wx.ToggleButton(self, ID_BUTTON_6, "Lower") self.slider_fcutoff_lo = wx.Slider(self, ID_SLIDER_2, 0, -15799, 15798, style=wx.SL_HORIZONTAL|wx.SL_LABELS) self.panel_5 = wx.Panel(self, -1) self.label_1 = wx.StaticText(self, -1, " Band\nCenter") self.text_ctrl_1 = wx.TextCtrl(self, ID_TEXT_1, "") self.panel_6 = wx.Panel(self, -1) self.panel_7 = wx.Panel(self, -1) self.panel_2 = wx.Panel(self, -1) self.button_7 = wx.ToggleButton(self, ID_BUTTON_7, "Freq") self.slider_3 = wx.Slider(self, ID_SLIDER_3, 3000, 0, 6000) self.spin_ctrl_1 = wx.SpinCtrl(self, ID_SPIN_1, "", min=0, max=100) self.button_8 = wx.ToggleButton(self, ID_BUTTON_8, "Vol") self.slider_4 = wx.Slider(self, ID_SLIDER_4, 0, 0, 500) self.slider_5 = wx.Slider(self, ID_SLIDER_5, 0, 0, 20) self.button_9 = wx.ToggleButton(self, ID_BUTTON_9, "Time") self.button_11 = wx.Button(self, ID_BUTTON_11, "Rew") self.button_10 = wx.Button(self, ID_BUTTON_10, "Fwd") self.panel_3 = wx.Panel(self, -1) self.label_2 = wx.StaticText(self, -1, "PGA ") self.panel_4 = wx.Panel(self, -1) self.panel_8 = wx.Panel(self, -1) self.panel_9 = wx.Panel(self, -1) self.label_3 = wx.StaticText(self, -1, "AM Sync\nCarrier") self.slider_6 = wx.Slider(self, ID_SLIDER_6, 50, 0, 200, style=wx.SL_HORIZONTAL|wx.SL_LABELS) self.label_4 = wx.StaticText(self, -1, "Antenna Tune") self.slider_7 = wx.Slider(self, ID_SLIDER_7, 1575, 950, 2200, style=wx.SL_HORIZONTAL|wx.SL_LABELS) self.panel_10 = wx.Panel(self, -1) self.button_12 = wx.ToggleButton(self, ID_BUTTON_12, "Auto Tune") self.button_13 = wx.Button(self, ID_BUTTON_13, "Calibrate") self.button_14 = wx.Button(self, ID_BUTTON_14, "Reset") self.panel_11 = wx.Panel(self, -1) self.panel_12 = wx.Panel(self, -1) self.__set_properties() self.__do_layout() # end wxGlade parser = OptionParser (option_class=eng_option) parser.add_option("", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") parser.add_option ("-c", "--ddc-freq", type="eng_float", default=3.9e6, help="set Rx DDC frequency to FREQ", metavar="FREQ") parser.add_option ("-s", "--samp-rate", type="eng_float", default=256e3, help="set sample rate (bandwidth) [default=%default]") parser.add_option ("-a", "--audio_file", default="", help="audio output file", metavar="FILE") parser.add_option ("-r", "--radio_file", default="", help="radio output file", metavar="FILE") parser.add_option ("-i", "--input_file", default="", help="radio input file", metavar="FILE") parser.add_option ("-O", "--audio-output", type="string", default="", help="audio output device name. E.g., hw:0,0, /dev/dsp, or pulse") (options, args) = parser.parse_args () self.usrp_center = options.ddc_freq input_rate = options.samp_rate self.slider_range = input_rate * 0.9375 self.f_lo = self.usrp_center - (self.slider_range/2) self.f_hi = self.usrp_center + (self.slider_range/2) self.af_sample_rate = 32000 fir_decim = long (input_rate / self.af_sample_rate) # data point arrays for antenna tuner self.xdata = [] self.ydata = [] self.tb = gr.top_block() # radio variables, initial conditions self.frequency = self.usrp_center # these map the frequency slider (0-6000) to the actual range self.f_slider_offset = self.f_lo self.f_slider_scale = 10000 self.spin_ctrl_1.SetRange(self.f_lo,self.f_hi) self.text_ctrl_1.SetValue(str(int(self.usrp_center))) self.slider_5.SetValue(0) self.AM_mode = False self.slider_3.SetValue((self.frequency-self.f_slider_offset)/self.f_slider_scale) self.spin_ctrl_1.SetValue(int(self.frequency)) POWERMATE = True try: self.pm = powermate.powermate(self) except: sys.stderr.write("Unable to find PowerMate or Contour Shuttle\n") POWERMATE = False if POWERMATE: powermate.EVT_POWERMATE_ROTATE(self, self.on_rotate) powermate.EVT_POWERMATE_BUTTON(self, self.on_pmButton) self.active_button = 7 # command line options if options.audio_file == "": SAVE_AUDIO_TO_FILE = False else: SAVE_AUDIO_TO_FILE = True if options.radio_file == "": SAVE_RADIO_TO_FILE = False else: SAVE_RADIO_TO_FILE = True if options.input_file == "": self.PLAY_FROM_USRP = True else: self.PLAY_FROM_USRP = False if self.PLAY_FROM_USRP: self.src = uhd.usrp_source(device_addr=options.address, io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=1) self.src.set_samp_rate(input_rate) input_rate = self.src.get_samp_rate() self.src.set_center_freq(self.usrp_center, 0) self.tune_offset = 0 else: self.src = blocks.file_source (gr.sizeof_short,options.input_file) self.tune_offset = 2200 # 2200 works for 3.5-4Mhz band # convert rf data in interleaved short int form to complex s2ss = blocks.stream_to_streams(gr.sizeof_short,2) s2f1 = blocks.short_to_float() s2f2 = blocks.short_to_float() src_f2c = blocks.float_to_complex() self.tb.connect(self.src,s2ss) self.tb.connect((s2ss,0),s2f1) self.tb.connect((s2ss,1),s2f2) self.tb.connect(s2f1,(src_f2c,0)) self.tb.connect(s2f2,(src_f2c,1)) # save radio data to a file if SAVE_RADIO_TO_FILE: radio_file = blocks.file_sink(gr.sizeof_short, options.radio_file) self.tb.connect (self.src, radio_file) # 2nd DDC xlate_taps = filter.firdes.low_pass ( \ 1.0, input_rate, 16e3, 4e3, filter.firdes.WIN_HAMMING ) self.xlate = filter.freq_xlating_fir_filter_ccf ( \ fir_decim, xlate_taps, self.tune_offset, input_rate ) # Complex Audio filter audio_coeffs = filter.firdes.complex_band_pass ( 1.0, # gain self.af_sample_rate, # sample rate -3000, # low cutoff 0, # high cutoff 100, # transition filter.firdes.WIN_HAMMING) # window self.slider_fcutoff_hi.SetValue(0) self.slider_fcutoff_lo.SetValue(-3000) self.audio_filter = filter.fir_filter_ccc(1, audio_coeffs) # Main +/- 16Khz spectrum display self.fft = fftsink2.fft_sink_c(self.panel_2, fft_size=512, sample_rate=self.af_sample_rate, average=True, size=(640,240)) # AM Sync carrier if AM_SYNC_DISPLAY: self.fft2 = fftsink.fft_sink_c(self.tb, self.panel_9, y_per_div=20, fft_size=512, sample_rate=self.af_sample_rate, average=True, size=(640,240)) c2f = blocks.complex_to_float() # AM branch self.sel_am = blocks.multiply_const_cc(0) # the following frequencies turn out to be in radians/sample # analog.pll_refout_cc(alpha,beta,min_freq,max_freq) # suggested alpha = X, beta = .25 * X * X pll = analog.pll_refout_cc(.5,.0625,(2.*math.pi*7.5e3/self.af_sample_rate), (2.*math.pi*6.5e3/self.af_sample_rate)) self.pll_carrier_scale = blocks.multiply_const_cc(complex(10,0)) am_det = blocks.multiply_cc() # these are for converting +7.5kHz to -7.5kHz # for some reason blocks.conjugate_cc() adds noise ?? c2f2 = blocks.complex_to_float() c2f3 = blocks.complex_to_float() f2c = blocks.float_to_complex() phaser1 = blocks.multiply_const_ff(1) phaser2 = blocks.multiply_const_ff(-1) # filter for pll generated carrier pll_carrier_coeffs = filter.firdes.complex_band_pass ( 2.0, # gain self.af_sample_rate, # sample rate 7400, # low cutoff 7600, # high cutoff 100, # transition filter.firdes.WIN_HAMMING) # window self.pll_carrier_filter = filter.fir_filter_ccc (1, pll_carrier_coeffs) self.sel_sb = blocks.multiply_const_ff(1) combine = blocks.add_ff() #AGC sqr1 = blocks.multiply_ff() intr = filter.iir_filter_ffd( [.004, 0], [0, .999] ) offset = blocks.add_const_ff(1) agc = blocks.divide_ff() self.scale = blocks.multiply_const_ff(0.00001) dst = audio.sink(long(self.af_sample_rate), options.audio_output) if self.PLAY_FROM_USRP: self.tb.connect(self.src, self.xlate, self.fft) else: self.tb.connect(src_f2c, self.xlate, self.fft) self.tb.connect(self.xlate,self.audio_filter,self.sel_am,(am_det,0)) self.tb.connect(self.sel_am,pll,self.pll_carrier_scale, self.pll_carrier_filter,c2f3) self.tb.connect((c2f3,0),phaser1,(f2c,0)) self.tb.connect((c2f3,1),phaser2,(f2c,1)) self.tb.connect(f2c,(am_det,1)) self.tb.connect(am_det,c2f2,(combine,0)) self.tb.connect(self.audio_filter,c2f, self.sel_sb,(combine,1)) if AM_SYNC_DISPLAY: self.tb.connect(self.pll_carrier_filter,self.fft2) self.tb.connect(combine,self.scale) self.tb.connect(self.scale,(sqr1,0)) self.tb.connect(self.scale,(sqr1,1)) self.tb.connect(sqr1, intr, offset, (agc, 1)) self.tb.connect(self.scale,(agc, 0)) self.tb.connect(agc,dst) if SAVE_AUDIO_TO_FILE: f_out = blocks.file_sink(gr.sizeof_short,options.audio_file) sc1 = blocks.multiply_const_ff(64000) f2s1 = blocks.float_to_short() self.tb.connect(agc,sc1,f2s1,f_out) self.tb.start() # for mouse position reporting on fft display self.fft.win.Bind(wx.EVT_LEFT_UP, self.Mouse) # and left click to re-tune self.fft.win.Bind(wx.EVT_LEFT_DOWN, self.Click) # start a timer to check for web commands if WEB_CONTROL: self.timer = UpdateTimer(self, 1000) # every 1000 mSec, 1 Sec wx.EVT_BUTTON(self,ID_BUTTON_1,self.set_lsb) wx.EVT_BUTTON(self,ID_BUTTON_2,self.set_usb) wx.EVT_BUTTON(self,ID_BUTTON_3,self.set_am) wx.EVT_BUTTON(self,ID_BUTTON_4,self.set_cw) wx.EVT_BUTTON(self,ID_BUTTON_10,self.fwd) wx.EVT_BUTTON(self,ID_BUTTON_11,self.rew) wx.EVT_BUTTON(self, ID_BUTTON_13, self.AT_calibrate) wx.EVT_BUTTON(self, ID_BUTTON_14, self.AT_reset) wx.EVT_TOGGLEBUTTON(self,ID_BUTTON_5,self.on_button) wx.EVT_TOGGLEBUTTON(self,ID_BUTTON_6,self.on_button) wx.EVT_TOGGLEBUTTON(self,ID_BUTTON_7,self.on_button) wx.EVT_TOGGLEBUTTON(self,ID_BUTTON_8,self.on_button) wx.EVT_TOGGLEBUTTON(self,ID_BUTTON_9,self.on_button) wx.EVT_SLIDER(self,ID_SLIDER_1,self.set_filter) wx.EVT_SLIDER(self,ID_SLIDER_2,self.set_filter) wx.EVT_SLIDER(self,ID_SLIDER_3,self.slide_tune) wx.EVT_SLIDER(self,ID_SLIDER_4,self.set_volume) wx.EVT_SLIDER(self,ID_SLIDER_5,self.set_pga) wx.EVT_SLIDER(self,ID_SLIDER_6,self.am_carrier) wx.EVT_SLIDER(self,ID_SLIDER_7,self.antenna_tune) wx.EVT_SPINCTRL(self,ID_SPIN_1,self.spin_tune) wx.EVT_MENU(self, ID_EXIT, self.TimeToQuit) def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("HF Explorer") self.slider_fcutoff_hi.SetMinSize((450, 38)) self.slider_fcutoff_lo.SetMinSize((450, 38)) self.panel_2.SetMinSize((640, 240)) self.button_7.SetValue(1) self.slider_3.SetMinSize((450, 19)) self.slider_4.SetMinSize((275, 19)) self.slider_5.SetMinSize((275, 19)) if AM_SYNC_DISPLAY: self.panel_9.SetMinSize((640, 240)) self.slider_6.SetMinSize((300, 38)) self.slider_7.SetMinSize((400, 38)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) grid_sizer_1 = wx.FlexGridSizer(11, 2, 0, 0) sizer_7 = wx.BoxSizer(wx.HORIZONTAL) sizer_5 = wx.BoxSizer(wx.HORIZONTAL) sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_3 = wx.BoxSizer(wx.HORIZONTAL) sizer_6 = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) grid_sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0) sizer_2.Add(self.button_1, 0, wx.ADJUST_MINSIZE, 0) sizer_2.Add(self.button_2, 0, wx.ADJUST_MINSIZE, 0) sizer_2.Add(self.button_3, 0, wx.ADJUST_MINSIZE, 0) sizer_2.Add(self.button_4, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.button_5, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.slider_fcutoff_hi, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.button_6, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.slider_fcutoff_lo, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 0) sizer_6.Add(self.panel_5, 1, wx.EXPAND, 0) sizer_6.Add(self.label_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 0) sizer_6.Add(self.text_ctrl_1, 0, wx.ADJUST_MINSIZE, 0) sizer_6.Add(self.panel_6, 1, wx.EXPAND, 0) sizer_6.Add(self.panel_7, 1, wx.EXPAND, 0) grid_sizer_1.Add(sizer_6, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_2, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.button_7, 0, wx.ADJUST_MINSIZE, 0) sizer_3.Add(self.slider_3, 0, wx.ADJUST_MINSIZE, 0) sizer_3.Add(self.spin_ctrl_1, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(sizer_3, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.button_8, 0, wx.ADJUST_MINSIZE, 0) sizer_4.Add(self.slider_4, 0, wx.ADJUST_MINSIZE, 0) sizer_4.Add(self.slider_5, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(sizer_4, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.button_9, 0, wx.ADJUST_MINSIZE, 0) sizer_5.Add(self.button_11, 0, wx.ADJUST_MINSIZE, 0) sizer_5.Add(self.button_10, 0, wx.ADJUST_MINSIZE, 0) sizer_5.Add(self.panel_3, 1, wx.EXPAND, 0) sizer_5.Add(self.label_2, 0, wx.ADJUST_MINSIZE, 0) sizer_5.Add(self.panel_4, 1, wx.EXPAND, 0) grid_sizer_1.Add(sizer_5, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_8, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_9, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.label_3, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.slider_6, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.label_4, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.slider_7, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.panel_10, 1, wx.EXPAND, 0) sizer_7.Add(self.button_12, 0, wx.ADJUST_MINSIZE, 0) sizer_7.Add(self.button_13, 0, wx.ADJUST_MINSIZE, 0) sizer_7.Add(self.button_14, 0, wx.ADJUST_MINSIZE, 0) sizer_7.Add(self.panel_11, 1, wx.EXPAND, 0) sizer_7.Add(self.panel_12, 1, wx.EXPAND, 0) grid_sizer_1.Add(sizer_7, 1, wx.EXPAND, 0) sizer_1.Add(grid_sizer_1, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) sizer_1.Fit(self) sizer_1.SetSizeHints(self) self.Layout() # end wxGlade # Menu exit def TimeToQuit(self, event): self.tb.stop() self.Close(True) # Powermate being turned def on_rotate(self, event): if self.active_button == 5: self.slider_fcutoff_hi.SetValue(self.slider_fcutoff_hi.GetValue()+event.delta) if self.slider_fcutoff_lo.GetValue() > (self.slider_fcutoff_hi.GetValue() - 200) : self.slider_fcutoff_lo.SetValue(self.slider_fcutoff_hi.GetValue() - 200) self.filter() if self.active_button == 6: self.slider_fcutoff_lo.SetValue(self.slider_fcutoff_lo.GetValue()+event.delta) if self.slider_fcutoff_hi.GetValue() < (self.slider_fcutoff_lo.GetValue() + 200) : self.slider_fcutoff_hi.SetValue(self.slider_fcutoff_lo.GetValue() + 200) self.filter() if self.active_button == 7: new = max(0, min(6000, self.slider_3.GetValue() + event.delta)) self.slider_3.SetValue(new) self.frequency = (self.f_slider_scale * new) + self.f_slider_offset self.spin_ctrl_1.SetValue(self.frequency) if self.AM_mode == False: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset)) else: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset - 7.5e3)) if self.button_12.GetValue(): self.auto_antenna_tune() if self.active_button == 8: new = max(0, min(500, self.slider_4.GetValue() + event.delta)) self.slider_4.SetValue(new) self.scale.set_k(math.pow(10.,((self.slider_4.GetValue()-500.)/100.))) if self.active_button == 9: if self.PLAY_FROM_USRP == False: if event.delta == -1: self.src.seek(-1000000,gr.SEEK_CUR) elif event.delta == 1: self.src.seek(1000000,gr.SEEK_CUR) # Powermate pressed to switch controlled function def on_pmButton(self, event): if event.value == 0: if self.active_button == 5: self.active_button = 6 self.button_5.SetValue(False) self.button_6.SetValue(True) elif self.active_button == 6: self.active_button = 7 self.button_6.SetValue(False) self.button_7.SetValue(True) elif self.active_button == 7: self.active_button = 8 self.button_7.SetValue(False) self.button_8.SetValue(True) elif self.active_button == 8: self.active_button = 9 self.button_8.SetValue(False) self.button_9.SetValue(True) elif self.active_button == 9: self.active_button = 5 self.button_9.SetValue(False) self.button_5.SetValue(True) # Clicking one PM control button turns the rest off def on_button(self, event): id = event.GetId() if id == ID_BUTTON_5: self.active_button = 5 self.button_6.SetValue(False) self.button_7.SetValue(False) self.button_8.SetValue(False) self.button_9.SetValue(False) if id == ID_BUTTON_6: self.active_button = 6 self.button_5.SetValue(False) self.button_7.SetValue(False) self.button_8.SetValue(False) self.button_9.SetValue(False) if id == ID_BUTTON_7: self.active_button = 7 self.button_5.SetValue(False) self.button_6.SetValue(False) self.button_8.SetValue(False) self.button_9.SetValue(False) if id == ID_BUTTON_8: self.active_button = 8 self.button_5.SetValue(False) self.button_6.SetValue(False) self.button_7.SetValue(False) self.button_9.SetValue(False) if id == ID_BUTTON_9: self.active_button = 9 self.button_5.SetValue(False) self.button_6.SetValue(False) self.button_7.SetValue(False) self.button_8.SetValue(False) # Make sure filter settings are legal def set_filter(self, event): slider = event.GetId() slider1 = self.slider_fcutoff_hi.GetValue() slider2 = self.slider_fcutoff_lo.GetValue() if slider == ID_SLIDER_1: if slider2 > (self.slider_fcutoff_hi.GetValue() - 200) : self.slider_fcutoff_lo.SetValue(slider1 - 200) elif slider == ID_SLIDER_2: if slider1 < (self.slider_fcutoff_lo.GetValue() + 200) : self.slider_fcutoff_hi.SetValue(slider2 + 200) self.filter() # Calculate taps and apply def filter(self): audio_coeffs = filter.firdes.complex_band_pass ( 1.0, # gain self.af_sample_rate, # sample rate self.slider_fcutoff_lo.GetValue(), # low cutoff self.slider_fcutoff_hi.GetValue(), # high cutoff 100, # transition filter.firdes.WIN_HAMMING) # window self.audio_filter.set_taps(audio_coeffs) def set_lsb(self, event): self.AM_mode = False self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset)) self.sel_sb.set_k(1) self.sel_am.set_k(0) self.slider_fcutoff_hi.SetValue(0) self.slider_fcutoff_lo.SetValue(-3000) self.filter() def set_usb(self, event): self.AM_mode = False self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset)) self.sel_sb.set_k(1) self.sel_am.set_k(0) self.slider_fcutoff_hi.SetValue(3000) self.slider_fcutoff_lo.SetValue(0) self.filter() def set_am(self, event): self.AM_mode = True self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset - 7.5e3)) self.sel_sb.set_k(0) self.sel_am.set_k(1) self.slider_fcutoff_hi.SetValue(12500) self.slider_fcutoff_lo.SetValue(2500) self.filter() def set_cw(self, event): self.AM_mode = False self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset)) self.AM_mode = False self.sel_sb.set_k(1) self.sel_am.set_k(0) self.slider_fcutoff_hi.SetValue(-400) self.slider_fcutoff_lo.SetValue(-800) self.filter() def set_volume(self, event): self.scale.set_k(math.pow(10.,((self.slider_4.GetValue()-500.)/100.))) def set_pga(self,event): if self.PLAY_FROM_USRP: self.src.set_gain(self.slider_5.GetValue()) def slide_tune(self, event): self.frequency = (self.f_slider_scale * self.slider_3.GetValue()) + self.f_slider_offset if self.AM_mode == False: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset)) else: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset - 7.5e3)) self.spin_ctrl_1.SetValue(self.frequency) if self.button_12.GetValue(): self.auto_antenna_tune() def spin_tune(self, event): self.frequency = self.spin_ctrl_1.GetValue() if self.AM_mode == False: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset)) else: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset - 7.5e3)) self.slider_3.SetValue(int((self.frequency-self.f_slider_offset)/self.f_slider_scale)) if self.button_12.GetValue(): self.auto_antenna_tune() # Seek forwards in file def fwd(self, event): if self.PLAY_FROM_USRP == False: self.src.seek(10000000,gr.SEEK_CUR) # Seek backwards in file def rew(self, event): if self.PLAY_FROM_USRP == False: self.src.seek(-10000000,gr.SEEK_CUR) # Mouse over fft display - show frequency in tooltip def Mouse(self,event): if self.AM_mode: fRel = ( event.GetX() - 330. ) / 14.266666 - 7.5 else: fRel = ( event.GetX() - 330. ) / 14.266666 self.fft.win.SetToolTip(wx.ToolTip(eng_notation.num_to_str(self.frequency + (fRel*1e3)))) # Mouse clicked on fft display - change frequency def Click(self,event): fRel = ( event.GetX() - 330. ) / 14.266666 if self.AM_mode == False: self.frequency = self.frequency + (fRel*1e3) else: self.frequency = self.frequency + (fRel*1e3) - 7.5e3 self.spin_ctrl_1.SetValue(int(self.frequency)) self.slider_3.SetValue(int((self.frequency-self.f_slider_offset)/self.f_slider_scale)) if self.AM_mode == False: self.xlate.set_center_freq ( self.usrp_center - ( self.frequency - self.tune_offset )) else: self.xlate.set_center_freq( self.usrp_center - (self.frequency - self.tune_offset - 7.5e3)) # Set power of AM sync carrier def am_carrier(self,event): scale = math.pow(10,(self.slider_6.GetValue())/50.) self.pll_carrier_scale.set_k(complex(scale,0)) # Reset AT data and start calibrate over def AT_reset(self, event): self.xdata = [] self.ydata = [] # Save AT setting for a particular frequency def AT_calibrate(self, event): self.xdata.append(float(self.frequency)) self.ydata.append(self.slider_7.GetValue()) if len(self.xdata) > 1: self.m = [] self.b = [] for i in range(0,len(self.xdata)-1): self.m.append( (self.ydata[i+1] - self.ydata[i]) / (self.xdata[i+1] - self.xdata[i]) ) self.b.append( self.ydata[i] - self.m[i] * self.xdata[i] ) # Lookup calibrated points and calculate interpolated antenna tune voltage. # This is to automatically tune a narrowband loop antenna when the freq # is changed, to keep signals peaked. def auto_antenna_tune(self): for i in range(0,len(self.xdata)-1): if (self.frequency > self.xdata[i]) & (self.frequency < self.xdata[i+1]): self.slider_7.SetValue(self.m[i]*self.frequency + self.b[i]) self.antenna_tune(0) # Slider to set loop antenna capacitance def antenna_tune(self, evt): if self.PLAY_FROM_USRP: dev = self.src.get_dboard_iface() dev.write_aux_dac(uhd.dboard_iface.UNIT_RX, uhd.dboard_iface.AUX_DAC_C, float(self.slider_7.GetValue())) # Timer events - check for web commands def OnUpdate(self): cmds = os.listdir("/var/www/cgi-bin/commands/") if cmds!=[]: if cmds[0]=='chfreq': fd=open("/var/www/cgi-bin/commands/chfreq","r") new=fd.readline() fd.close() if new!='': os.unlink("/var/www/cgi-bin/commands/chfreq") if ( int(new) >= self.f_lo ) & ( int(new) <= self.f_hi ): self.frequency = int(new) self.slider_3.SetValue(( self.frequency - self.f_slider_offset) / self.f_slider_scale ) self.spin_ctrl_1.SetValue(self.frequency) if self.button_12.GetValue(): self.auto_antenna_tune() if self.AM_mode: self.xlate.set_center_freq ( self.usrp_center - ( self.frequency - self.tune_offset - 7.5e3 )) else: self.xlate.set_center_freq ( self.usrp_center - ( self.frequency - self.tune_offset )) if cmds[0]=='chvolume': fd=open("/var/www/cgi-bin/commands/chvolume","r") new=fd.readline() fd.close() if new!='': os.unlink("/var/www/cgi-bin/commands/chvolume") if ( int(new) >= 0 ) & ( int(new) <= 500 ): self.volume = int(new) self.slider_4.SetValue(self.volume) self.scale.set_k(math.pow(10.,((self.slider_4.GetValue()-500.)/100.))) else: # no new web commands, update state fh = open("/var/www/cgi-bin/state/freq","w") fh.write(str(int(self.frequency))+'\n') fh.close() fh = open("/var/www/cgi-bin/state/volume","w") fh.write(str(self.slider_4.GetValue())+'\n') fh.close() # end of class MyFrame # wx.Timer to check for web updates class UpdateTimer(wx.Timer): def __init__(self, target, dur=1000): wx.Timer.__init__(self) self.target = target self.Start(dur) def Notify(self): """Called every timer interval""" if self.target: self.target.OnUpdate() class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, "HF Explorer") frame.Show(True) self.SetTopWindow(frame) return True if __name__ == "__main__": app = MyApp(0) app.MainLoop() gnuradio-3.7.2.1/gr-uhd/apps/hf_explorer/README0000644000175000017500000000375011700377701020660 0ustar jcorganjcorganhfx.py is meant to be a full-featured Long Wave / Medium Wave and Short Wave (250kHz to 30Mhz) AM and Single Sideband receiver. It uses the USRP with a Basic RX board, and will need an antenna and some preamps, about 30db gain will work. See the 'Help' menu or hfx_help for more info. ---------------------------------------------------------- Powermate knob supported but not required, tooltip frequency display, single click tuning, AGC, record to disk, play from disk and record audio. Ability to tailor the audio passband with two sliders over the spectrum display. The sliders almost align with the actual frequency. Preset filter settings for LSB (-3000 to 0kHz), USB (0 to +3000kHz), CW (-400 to -800Hz) and AM (-5kHz from carrier to +5kHz). AM now switches in a synchronous PLL detector with the carriers at 7.5kHz. The PLL carrier is displayed in the bottom display and helps show where on the upper spectrum the demodulated signal lies. Everything gets shifted up 7.5kHz in AM, center frequency, tooltips, etc. The target AM carrier needs to be closely tuned in, it will have a hollow sound untill it is locked, and then the PLL carrier in the bottom display will jump up and remain relatively constant. There is a slider "AM sync carrier" to play with different levels to mix with the signal for demodulation. The filter in AM is preset to 2500/12500 (7.5kHz +/- 5kHz) and is handy for removing adjacent channel interference. Change AM_SYNC_DISPLAY in script for whether to show AM Sync carrier or not. Run with "-h" for command line help with setting USRP ddc center frequency, decimation, rf data record, playback and audio data recording. There are some controls for controlling a varactor and tuning an antenna - just ignore them unless you want to build a voltage tuned antenna to track frequency. There is also code for Web based control of frequency and volume - so I can tune the radio with an Ipaq from bed. Disabled by default - it takes a web server, some directories and scripts to use. gnuradio-3.7.2.1/gr-uhd/apps/hf_explorer/hfx_help0000644000175000017500000001375611744612271021531 0ustar jcorganjcorgan HF Explorer Help ----------------------------------------------------------------------- Command Line Switches: -c DDC center frequency, set band. -c 7.2e6 or -c 7.2M for 40 meter ham band. Default is 3.9e6 80 meter ham band. Example: hfx.py -c 9500k starts up in the 31 meter band. -a Audio output file. Output file for 32kHz two channel signed word audio. Two channels are used for independent sideband. This file can be converted to a wav file with sox. Example: sox -c 2 -r 3200 file.sw file.wav sox needs the .sw extension to indicate file type. If not specified no audio file is created. -r Radio output file. File to write RF data to for later demodulation. Records the entire band to disk, width determined by sample rate/decimation. Be sure to note the decimation and center freq for later use! Example: hfx.py -c 900e3 -d 80 -r rf_data_AM-c900e3-d80 writes a pre-demod rf file centered on 900kHz with a bandwidth of 800kHz (That's 80 AM stations!). The center and decimation could be put in the filename for proper use later. If not specified no rf data file is created. At default 250 decimation disk usage is about 8Gb / hour. -i Radio input file. Use to play back a previously recorded rf data file. Example: hfx.py -c 900e3 -d 80 -i rf_data_AM-c900e3-d80 plays back the previously recorded band, no usrp hardware needed. Tune about the 800kHz wide band. When playing a recorded file, time controls fast-forward and rewind are available. -d Decimation. Sets sample rate and bandwidth. This is the factor that the usrp sample rate, 64e6, is divided by. Default is 250 for 256kHz bandwidth which is enough to record a ham band without eating up disk space too fast. The 64e6 sample rate limits the upper practical frequency to 32MHz. The Basic RX transformer limits the lower frequency to about 200kHz. Powermate Knob: A Powermate knob is recommended but not necessary. If a knob is used, it is in one of 3 or 4 modes controlling frequency, volume, filter and (if playing a recorded file) time. Pushing the knob switches mode and the buttons on the HFX panel change to show which mode is in effect. Then just turn the knob to set frequency, volume, filter or go fast forward or rewind. Bandswitch: Across the top are a set of predefined bands and buttons to rapidly switch to the center of that band. To change a band, type the frequency in Hz into the box under "Center Frequency", then press "Set" on the left, then the button you want to program. From then on (untill the program is exited) pushing that button takes you to that band. To make a band button permenant edit the hfx.py script with whatever frequency you want assigned to what button. Frequency: There are 6 ways to set the frequency. 1) Move the slider with the mouse 2) Use the Spin Control up/down arrows (very fine 1Hz control) 3) Type the frequency in Hz into the Spin Control 4) Turn the Powermate knob 5) Web control. 6) Clicking on the FFT display to set demod center. This is very convenient for tuning +-15kHz when you see a signal on the display. If in Lower Sideband, clicking just to the right of a signal will tune to it immediately. Clicking several times on the far right right or left of the display will rapidly tune up or down the band. Volume: Move the volume slider with the mouse, or push the Powermate knob untill the volume button is active, or click on the volume button, then turn the knob. Volume can also be set by web control if web control is setup and enabled. Filter: Similar to volume, switches in any of 30 audio filters from 600 to 3600Hz in Sideband or up to 5kHz in AM. Mode: Demodulation modes are chosen by clicking on the buttons for Lower Sideband, Upper Sideband, or AM. PGA: PGA slider sets the rf gain in the Analog-to-Digital converter before digitizing. 0 to 20db gain easily shows up on the FFT display. Time: When playing back a recorded RF data file, you can enjoy the freedom of rewinding or fast-forwarding. Replay a weak signal or skip through annoying AM commercials. Antennas and Preamps: The USRP Basic RX board is not sensitive enough for anything but the strongest signals. In my experience about 40 db of small signal gain is required to make the HFX as sensitive as other receivers. Some working amplifiers are the Ramsey PR-2 with 20db gain, fairly low noise and more bandwidth than we can use here. Also the amp modules from Advanced Receiver Research are nice. I use an ARR 7-7.4MHz GaAsFET 29db amp with .5db noise at the apex of a 40 meter dipole with excellent results. Another amp I like is a Minicircuits ZHL-32A 29db amp but they are expensive and hard to find. Also it may help to use some filters to keep strong local signals from the ADC, or limit rf input to the band of interest, etc. Resonant outdoor antennas, like a dipole, in a low-noise (away from consumer electronics) environment are nice. Long random wires with a tuner work. I like a small indoor tuned loop made from 10ft of 1/4" copper tube, a 365pf tuning cap and a pickup loop connected to rg-58. Web Control: To control your radio remotely, ensure you have a web server (Apache, etc) working and a compatible directory structure in place. Directories /var/www/cgi-bin/commands and /var/www/cgi-bin/state must already exist. You will need a home page with forms and a set of scripts to put commands in and put the current state on the home page. email me for further help. Setting WEB_CONTROL to True in hfx.py turns on the timers that check for commands and update the state. IF Output: There is a provision for outputting un-demodulated complex through the audio out in stereo for use with Digital Radio Mondial (DRM) or using a seperate demodulation program like SDRadio (by I2PHD). Set IF_OUTPUT to True in weaver_isb_am1_usrp4.py. --Good luck and happy LW/MW/SW Exploring. Chuck chuckek@musicriver.homeunix.com gnuradio-3.7.2.1/gr-uhd/apps/uhd_rx_cfile0000775000175000017500000001773012237515112020045 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Read samples from a UHD device and write to file formatted as binary outputs single precision complex float values or complex short values (interleaved 16 bit signed short integers). """ from gnuradio import gr, gru, eng_notation from gnuradio import blocks from gnuradio import uhd from gnuradio.eng_option import eng_option from optparse import OptionParser import sys n2s = eng_notation.num_to_str class rx_cfile_block(gr.top_block): def __init__(self, options, filename): gr.top_block.__init__(self) # Create a UHD device source if options.output_shorts: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('sc16', options.wire_format, args=options.stream_args)) self._sink = blocks.file_sink(gr.sizeof_short*2, filename) else: self._u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32', options.wire_format, args=options.stream_args)) self._sink = blocks.file_sink(gr.sizeof_gr_complex, filename) # Set the subdevice spec if(options.spec): self._u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self._u.set_antenna(options.antenna, 0) # Set receiver sample rate self._u.set_samp_rate(options.samp_rate) # Set receive daughterboard gain if options.gain is None: g = self._u.get_gain_range() options.gain = float(g.start()+g.stop())/2 print "Using mid-point gain of", options.gain, "(", g.start(), "-", g.stop(), ")" self._u.set_gain(options.gain) # Set frequency (tune request takes lo_offset) if(options.lo_offset is not None): treq = uhd.tune_request(options.freq, options.lo_offset) else: treq = uhd.tune_request(options.freq) tr = self._u.set_center_freq(treq) if tr == None: sys.stderr.write('Failed to set center frequency\n') raise SystemExit, 1 # Create head block if needed and wire it up if options.nsamples is None: self.connect(self._u, self._sink) else: if options.output_shorts: self._head = blocks.head(gr.sizeof_short*2, int(options.nsamples)) else: self._head = blocks.head(gr.sizeof_gr_complex, int(options.nsamples)) self.connect(self._u, self._head, self._sink) input_rate = self._u.get_samp_rate() if options.verbose: try: info = self._u.get_usrp_info() mboard_id = info["mboard_id"].split(" ")[0] if info["mboard_serial"] == "": mboard_serial = "no serial" else: mboard_serial = info["mboard_serial"] rx_id = info["rx_id"].split(" ")[0] if info["rx_serial"] == "": rx_serial = "no serial" else: rx_serial = info["rx_serial"] rx_antenna = info["rx_antenna"] rx_subdev_spec = info["rx_subdev_spec"] print "Motherboard: %s (%s)" % (mboard_id, mboard_serial) if "B200" in mboard_id or "B210" in mboard_id: print "Daughterboard: %s (%s, %s)" % (mboard_id, rx_antenna, rx_subdev_spec) else: print "Daughterboard: %s (%s, %s, %s)" % (rx_id, rx_serial, rx_antenna, rx_subdev_spec) except: print "Args: ", options.args print "Rx gain:", options.gain print "Rx baseband frequency:", n2s(tr.actual_rf_freq) print "Rx DDC frequency:", n2s(tr.actual_dsp_freq) print "Rx Sample Rate:", n2s(input_rate) if options.nsamples is None: print "Receiving samples until Ctrl-C" else: print "Receving", n2s(options.nsamples), "samples" if options.output_shorts: print "Writing 16-bit complex shorts" else: print "Writing 32-bit complex floats" print "Output filename:", filename # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) def async_callback(self, msg): md = self.async_src.msg_to_async_metadata_t(msg) print "Channel: %i Time: %f Event: %i" % (md.channel, md.time_spec.get_real_secs(), md.event_code) def get_options(): usage="%prog: [options] output_filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option( "-s","--output-shorts", action="store_true", default=False, help="output interleaved shorts instead of complex floats") parser.add_option("-N", "--nsamples", type="eng_float", default=None, help="number of samples to collect [default=+inf]") parser.add_option("-v", "--verbose", action="store_true", default=False, help="verbose output") parser.add_option("", "--lo-offset", type="eng_float", default=None, help="set daughterboard LO offset to OFFSET [default=hw default]") parser.add_option("", "--wire-format", type="string", default="sc16", help="set wire format from USRP [default=%default") parser.add_option("", "--stream-args", type="string", default="", help="set stream arguments [default=%default]") parser.add_option("", "--show-async-msg", action="store_true", default=False, help="Show asynchronous message notifications from UHD [default=%default]") (options, args) = parser.parse_args () if len(args) != 1: parser.print_help() raise SystemExit, 1 if options.freq is None: parser.print_help() sys.stderr.write('You must specify the frequency with -f FREQ\n'); raise SystemExit, 1 return (options, args[0]) if __name__ == '__main__': (options, filename) = get_options() tb = rx_cfile_block(options, filename) try: tb.run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-uhd/apps/uhd_siggen0000755000175000017500000000324211744612271017523 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio.uhd import uhd_siggen_base as uhd_siggen import sys def main(): if gr.enable_realtime_scheduling() != gr.RT_OK: print "Note: failed to enable realtime scheduling, continuing" # Grab command line options and create top block try: (options, args) = uhd_siggen.get_options() tb = uhd_siggen.top_block(options, args) except RuntimeError, e: print e sys.exit(1) tb.start() raw_input('Press Enter to quit: ') tb.stop() tb.wait() # Make sure to create the top block (tb) within a function: # That code in main will allow tb to go out of scope on return, # which will call the decontructor on usrp and stop transmit. # Whats odd is that grc works fine with tb in the __main__, # perhaps its because the try/except clauses around tb. if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-uhd/apps/uhd_siggen_base.py0000664000175000017500000004140412237515112021137 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2008,2009,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # DESC_KEY = 'desc' SAMP_RATE_KEY = 'samp_rate' LINK_RATE_KEY = 'link_rate' GAIN_KEY = 'gain' TX_FREQ_KEY = 'tx_freq' DSP_FREQ_KEY = 'dsp_freq' RF_FREQ_KEY = 'rf_freq' AMPLITUDE_KEY = 'amplitude' AMPL_RANGE_KEY = 'ampl_range' WAVEFORM_FREQ_KEY = 'waveform_freq' WAVEFORM_OFFSET_KEY = 'waveform_offset' WAVEFORM2_FREQ_KEY = 'waveform2_freq' FREQ_RANGE_KEY = 'freq_range' GAIN_RANGE_KEY = 'gain_range' TYPE_KEY = 'type' def setter(ps, key, val): ps[key] = val from gnuradio import gr, gru, uhd, eng_notation from gnuradio import analog from gnuradio import blocks from gnuradio.gr.pubsub import pubsub from gnuradio.eng_option import eng_option from optparse import OptionParser import sys import math n2s = eng_notation.num_to_str waveforms = { analog.GR_SIN_WAVE : "Complex Sinusoid", analog.GR_CONST_WAVE : "Constant", analog.GR_GAUSSIAN : "Gaussian Noise", analog.GR_UNIFORM : "Uniform Noise", "2tone" : "Two Tone", "sweep" : "Sweep" } # # GUI-unaware GNU Radio flowgraph. This may be used either with command # line applications or GUI applications. # class top_block(gr.top_block, pubsub): def __init__(self, options, args): gr.top_block.__init__(self) pubsub.__init__(self) self._verbose = options.verbose #initialize values from options self._setup_usrpx(options) self[SAMP_RATE_KEY] = options.samp_rate self[TX_FREQ_KEY] = options.tx_freq self[AMPLITUDE_KEY] = options.amplitude self[WAVEFORM_FREQ_KEY] = options.waveform_freq self[WAVEFORM_OFFSET_KEY] = options.offset self[WAVEFORM2_FREQ_KEY] = options.waveform2_freq self[DSP_FREQ_KEY] = 0 self[RF_FREQ_KEY] = 0 #subscribe set methods self.subscribe(SAMP_RATE_KEY, self.set_samp_rate) self.subscribe(GAIN_KEY, self.set_gain) self.subscribe(TX_FREQ_KEY, self.set_freq) self.subscribe(AMPLITUDE_KEY, self.set_amplitude) self.subscribe(WAVEFORM_FREQ_KEY, self.set_waveform_freq) self.subscribe(WAVEFORM2_FREQ_KEY, self.set_waveform2_freq) self.subscribe(TYPE_KEY, self.set_waveform) #force update on pubsub keys for key in (SAMP_RATE_KEY, GAIN_KEY, TX_FREQ_KEY, AMPLITUDE_KEY, WAVEFORM_FREQ_KEY, WAVEFORM_OFFSET_KEY, WAVEFORM2_FREQ_KEY): self[key] = self[key] self[TYPE_KEY] = options.type #set type last def _setup_usrpx(self, options): self._u = uhd.usrp_sink(device_addr=options.args, stream_args=uhd.stream_args('fc32')) self._u.set_samp_rate(options.samp_rate) # Set the subdevice spec if(options.spec): self._u.set_subdev_spec(options.spec, 0) # Set the gain on the usrp from options if(options.gain): self._u.set_gain(options.gain) # Set the antenna if(options.antenna): self._u.set_antenna(options.antenna, 0) # Setup USRP Configuration value try: usrp_info = self._u.get_usrp_info() mboard_id = usrp_info["mboard_id"] mboard_serial = usrp_info["mboard_serial"] if mboard_serial == "": mboard_serial = "no serial" dboard_subdev_name = usrp_info["tx_subdev_name"] dboard_serial = usrp_info["tx_serial"] if dboard_serial == "": dboard_serial = "no serial" subdev = self._u.get_subdev_spec() antenna = self._u.get_antenna() desc_key_str = "Motherboard: %s [%s]\n" % (mboard_id, mboard_serial) if "B200" in mboard_id or "B210" in mboard_id: desc_key_str += "Daughterboard: %s\n" % dboard_subdev_name else: desc_key_str += "Daughterboard: %s [%s]\n" % (dboard_subdev_name, dboard_serial) desc_key_str += "Subdev: %s\n" % subdev desc_key_str += "Antenna: %s" % antenna except: desc_key_str = "USRP configuration output not implemented in this version" self.publish(DESC_KEY, lambda: desc_key_str) self.publish(FREQ_RANGE_KEY, self._u.get_freq_range) self.publish(GAIN_RANGE_KEY, self._u.get_gain_range) self.publish(GAIN_KEY, self._u.get_gain) print "UHD Signal Generator" print "Version: %s" % uhd.get_version_string() print "\nUsing USRP configuration:" print desc_key_str + "\n" # Direct asynchronous notifications to callback function if options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) def async_callback(self, msg): md = self.async_src.msg_to_async_metadata_t(msg) print "Channel: %i Time: %f Event: %i" % (md.channel, md.time_spec.get_real_secs(), md.event_code) def _set_tx_amplitude(self, ampl): """ Sets the transmit amplitude sent to the USRP Args: ampl: the amplitude or None for automatic """ ampl_range = self[AMPL_RANGE_KEY] if ampl is None: ampl = (ampl_range[1] - ampl_range[0])*0.15 + ampl_range[0] self[AMPLITUDE_KEY] = max(ampl_range[0], min(ampl, ampl_range[1])) def set_samp_rate(self, sr): self._u.set_samp_rate(sr) sr = self._u.get_samp_rate() if self[TYPE_KEY] in (analog.GR_SIN_WAVE, analog.GR_CONST_WAVE): self._src.set_sampling_freq(self[SAMP_RATE_KEY]) elif self[TYPE_KEY] == "2tone": self._src1.set_sampling_freq(self[SAMP_RATE_KEY]) self._src2.set_sampling_freq(self[SAMP_RATE_KEY]) elif self[TYPE_KEY] == "sweep": self._src1.set_sampling_freq(self[SAMP_RATE_KEY]) self._src2.set_sampling_freq(self[WAVEFORM_FREQ_KEY]*2*math.pi/self[SAMP_RATE_KEY]) else: return True # Waveform not yet set if self._verbose: print "Set sample rate to:", sr return True def set_gain(self, gain): if gain is None: g = self[GAIN_RANGE_KEY] gain = float(g.start()+g.stop())/2 if self._verbose: print "Using auto-calculated mid-point TX gain" self[GAIN_KEY] = gain return self._u.set_gain(gain) if self._verbose: print "Set TX gain to:", gain def set_freq(self, target_freq): if target_freq is None: f = self[FREQ_RANGE_KEY] target_freq = float(f.start()+f.stop())/2.0 if self._verbose: print "Using auto-calculated mid-point frequency" self[TX_FREQ_KEY] = target_freq return tr = self._u.set_center_freq(target_freq) fs = "%sHz" % (n2s(target_freq),) if tr is not None: self._freq = target_freq self[DSP_FREQ_KEY] = tr.actual_dsp_freq self[RF_FREQ_KEY] = tr.actual_rf_freq if self._verbose: print "Set center frequency to", self._u.get_center_freq() print "Tx RF frequency: %sHz" % (n2s(tr.actual_rf_freq),) print "Tx DSP frequency: %sHz" % (n2s(tr.actual_dsp_freq),) elif self._verbose: print "Failed to set freq." return tr def set_waveform_freq(self, freq): if self[TYPE_KEY] == analog.GR_SIN_WAVE: self._src.set_frequency(freq) elif self[TYPE_KEY] == "2tone": self._src1.set_frequency(freq) elif self[TYPE_KEY] == 'sweep': #there is no set sensitivity, redo fg self[TYPE_KEY] = self[TYPE_KEY] return True def set_waveform2_freq(self, freq): if freq is None: self[WAVEFORM2_FREQ_KEY] = -self[WAVEFORM_FREQ_KEY] return if self[TYPE_KEY] == "2tone": self._src2.set_frequency(freq) elif self[TYPE_KEY] == "sweep": self._src1.set_frequency(freq) return True def set_waveform(self, type): self.lock() self.disconnect_all() if type == analog.GR_SIN_WAVE or type == analog.GR_CONST_WAVE: self._src = analog.sig_source_c(self[SAMP_RATE_KEY], # Sample rate type, # Waveform type self[WAVEFORM_FREQ_KEY], # Waveform frequency self[AMPLITUDE_KEY], # Waveform amplitude self[WAVEFORM_OFFSET_KEY]) # Waveform offset elif type == analog.GR_GAUSSIAN or type == analog.GR_UNIFORM: self._src = analog.noise_source_c(type, self[AMPLITUDE_KEY]) elif type == "2tone": self._src1 = analog.sig_source_c(self[SAMP_RATE_KEY], analog.GR_SIN_WAVE, self[WAVEFORM_FREQ_KEY], self[AMPLITUDE_KEY]/2.0, 0) if(self[WAVEFORM2_FREQ_KEY] is None): self[WAVEFORM2_FREQ_KEY] = -self[WAVEFORM_FREQ_KEY] self._src2 = analog.sig_source_c(self[SAMP_RATE_KEY], analog.GR_SIN_WAVE, self[WAVEFORM2_FREQ_KEY], self[AMPLITUDE_KEY]/2.0, 0) self._src = blocks.add_cc() self.connect(self._src1,(self._src,0)) self.connect(self._src2,(self._src,1)) elif type == "sweep": # rf freq is center frequency # waveform_freq is total swept width # waveform2_freq is sweep rate # will sweep from (rf_freq-waveform_freq/2) to (rf_freq+waveform_freq/2) if self[WAVEFORM2_FREQ_KEY] is None: self[WAVEFORM2_FREQ_KEY] = 0.1 self._src1 = analog.sig_source_f(self[SAMP_RATE_KEY], analog.GR_TRI_WAVE, self[WAVEFORM2_FREQ_KEY], 1.0, -0.5) self._src2 = analog.frequency_modulator_fc(self[WAVEFORM_FREQ_KEY]*2*math.pi/self[SAMP_RATE_KEY]) self._src = blocks.multiply_const_cc(self[AMPLITUDE_KEY]) self.connect(self._src1,self._src2,self._src) else: raise RuntimeError("Unknown waveform type") self.connect(self._src, self._u) self.unlock() if self._verbose: print "Set baseband modulation to:", waveforms[type] if type == analog.GR_SIN_WAVE: print "Modulation frequency: %sHz" % (n2s(self[WAVEFORM_FREQ_KEY]),) print "Initial phase:", self[WAVEFORM_OFFSET_KEY] elif type == "2tone": print "Tone 1: %sHz" % (n2s(self[WAVEFORM_FREQ_KEY]),) print "Tone 2: %sHz" % (n2s(self[WAVEFORM2_FREQ_KEY]),) elif type == "sweep": print "Sweeping across %sHz to %sHz" % (n2s(-self[WAVEFORM_FREQ_KEY]/2.0),n2s(self[WAVEFORM_FREQ_KEY]/2.0)) print "Sweep rate: %sHz" % (n2s(self[WAVEFORM2_FREQ_KEY]),) print "TX amplitude:", self[AMPLITUDE_KEY] def set_amplitude(self, amplitude): if amplitude < 0.0 or amplitude > 1.0: if self._verbose: print "Amplitude out of range:", amplitude return False if self[TYPE_KEY] in (analog.GR_SIN_WAVE, analog.GR_CONST_WAVE, analog.GR_GAUSSIAN, analog.GR_UNIFORM): self._src.set_amplitude(amplitude) elif self[TYPE_KEY] == "2tone": self._src1.set_amplitude(amplitude/2.0) self._src2.set_amplitude(amplitude/2.0) elif self[TYPE_KEY] == "sweep": self._src.set_k(amplitude) else: return True # Waveform not yet set if self._verbose: print "Set amplitude to:", amplitude return True def get_options(): usage="%prog: [options]" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-f", "--tx-freq", type="eng_float", default=None, help="Set carrier frequency to FREQ [default=mid-point]", metavar="FREQ") parser.add_option("-x", "--waveform-freq", type="eng_float", default=0, help="Set baseband waveform frequency to FREQ [default=%default]") parser.add_option("-y", "--waveform2-freq", type="eng_float", default=None, help="Set 2nd waveform frequency to FREQ [default=%default]") parser.add_option("--sine", dest="type", action="store_const", const=analog.GR_SIN_WAVE, help="Generate a carrier modulated by a complex sine wave", default=analog.GR_SIN_WAVE) parser.add_option("--const", dest="type", action="store_const", const=analog.GR_CONST_WAVE, help="Generate a constant carrier") parser.add_option("--offset", type="eng_float", default=0, help="Set waveform phase offset to OFFSET [default=%default]") parser.add_option("--gaussian", dest="type", action="store_const", const=analog.GR_GAUSSIAN, help="Generate Gaussian random output") parser.add_option("--uniform", dest="type", action="store_const", const=analog.GR_UNIFORM, help="Generate Uniform random output") parser.add_option("--2tone", dest="type", action="store_const", const="2tone", help="Generate Two Tone signal for IMD testing") parser.add_option("--sweep", dest="type", action="store_const", const="sweep", help="Generate a swept sine wave") parser.add_option("", "--amplitude", type="eng_float", default=0.15, help="Set output amplitude to AMPL (0.0-1.0) [default=%default]", metavar="AMPL") parser.add_option("-v", "--verbose", action="store_true", default=False, help="Use verbose console output [default=%default]") parser.add_option("", "--show-async-msg", action="store_true", default=False, help="Show asynchronous message notifications from UHD [default=%default]") (options, args) = parser.parse_args() return (options, args) # If this script is executed, the following runs. If it is imported, # the below does not run. def test_main(): if gr.enable_realtime_scheduling() != gr.RT_OK: print "Note: failed to enable realtime scheduling, continuing" # Grab command line options and create top block try: (options, args) = get_options() tb = top_block(options, args) except RuntimeError, e: print e sys.exit(1) tb.start() raw_input('Press Enter to quit: ') tb.stop() tb.wait() # Make sure to create the top block (tb) within a function: # That code in main will allow tb to go out of scope on return, # which will call the decontructor on usrp and stop transmit. # Whats odd is that grc works fine with tb in the __main__, # perhaps its because the try/except clauses around tb. if __name__ == "__main__": test_main() gnuradio-3.7.2.1/gr-uhd/apps/uhd_siggen_gui0000775000175000017500000002774512207440367020407 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2009,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import wx from gnuradio import gr, uhd from gnuradio import analog from gnuradio.gr.pubsub import pubsub from gnuradio.wxgui import gui, forms from gnuradio.uhd import uhd_siggen_base as uhd_siggen import sys, math class app_gui(pubsub): def __init__(self, frame, panel, vbox, top_block, options, args): pubsub.__init__(self) self.frame = frame # Use for top-level application window frame self.panel = panel # Use as parent class for created windows self.vbox = vbox # Use as sizer for created windows self.tb = top_block # GUI-unaware flowgraph class self.options = options # Supplied command-line options self.args = args # Supplied command-line arguments self.build_gui() # Event response handlers def evt_set_status_msg(self, msg): self.frame.SetStatusText(msg, 0) # GUI construction def build_gui(self): self.vbox.AddSpacer(5) self.vbox.AddStretchSpacer() ################################################## # Baseband controls ################################################## bb_vbox = forms.static_box_sizer(parent=self.panel, label="Baseband Modulation", orient=wx.VERTICAL, bold=True) self.vbox.Add(bb_vbox, 0, wx.EXPAND) sine_bb_hbox = wx.BoxSizer(wx.HORIZONTAL) sweep_bb_hbox = wx.BoxSizer(wx.HORIZONTAL) tone_bb_hbox = wx.BoxSizer(wx.HORIZONTAL) self.vbox.AddSpacer(10) self.vbox.AddStretchSpacer() #callback to show/hide forms def set_type(type): sine_bb_hbox.ShowItems(type == analog.GR_SIN_WAVE) sweep_bb_hbox.ShowItems(type == 'sweep') tone_bb_hbox.ShowItems(type == '2tone') self.vbox.Layout() self.tb.subscribe(uhd_siggen.TYPE_KEY, set_type) #create sine forms sine_bb_hbox.AddSpacer(10) forms.text_box( parent=self.panel, sizer=sine_bb_hbox, label='Frequency (Hz)', ps=self.tb, key=uhd_siggen.WAVEFORM_FREQ_KEY, converter=forms.float_converter(), ) sine_bb_hbox.AddStretchSpacer() #create sweep forms sweep_bb_hbox.AddSpacer(10) forms.text_box( parent=self.panel, sizer=sweep_bb_hbox, label='Sweep Width (Hz)', ps=self.tb, key=uhd_siggen.WAVEFORM_FREQ_KEY, converter=forms.float_converter(), ) sweep_bb_hbox.AddStretchSpacer() forms.text_box( parent=self.panel, sizer=sweep_bb_hbox, label='Sweep Rate (Hz)', ps=self.tb, key=uhd_siggen.WAVEFORM2_FREQ_KEY, converter=forms.float_converter(), ) sweep_bb_hbox.AddStretchSpacer() #create 2tone forms tone_bb_hbox.AddSpacer(10) forms.text_box( parent=self.panel, sizer=tone_bb_hbox, label='Tone 1 (Hz)', ps=self.tb, key=uhd_siggen.WAVEFORM_FREQ_KEY, converter=forms.float_converter(), ) tone_bb_hbox.AddStretchSpacer() forms.text_box( parent=self.panel, sizer=tone_bb_hbox, label='Tone 2 (Hz)', ps=self.tb, key=uhd_siggen.WAVEFORM2_FREQ_KEY, converter=forms.float_converter(), ) tone_bb_hbox.AddStretchSpacer() forms.radio_buttons( parent=self.panel, sizer=bb_vbox, choices=uhd_siggen.waveforms.keys(), labels=uhd_siggen.waveforms.values(), ps=self.tb, key=uhd_siggen.TYPE_KEY, style=wx.NO_BORDER | wx.RA_HORIZONTAL, ) bb_vbox.AddSpacer(10) bb_vbox.Add(sine_bb_hbox, 0, wx.EXPAND) bb_vbox.Add(sweep_bb_hbox, 0, wx.EXPAND) bb_vbox.Add(tone_bb_hbox, 0, wx.EXPAND) set_type(self.tb[uhd_siggen.TYPE_KEY]) ################################################## # Frequency controls ################################################## fc_vbox = forms.static_box_sizer(parent=self.panel, label="Center Frequency", orient=wx.VERTICAL, bold=True) fc_vbox.AddSpacer(5) # First row of frequency controls (center frequency) freq_hbox = wx.BoxSizer(wx.HORIZONTAL) fc_vbox.Add(freq_hbox, 0, wx.EXPAND) fc_vbox.AddSpacer(10) # Second row of frequency controls (results) tr_hbox = wx.BoxSizer(wx.HORIZONTAL) fc_vbox.Add(tr_hbox, 0, wx.EXPAND) fc_vbox.AddSpacer(5) # Add frequency controls to top window sizer self.vbox.Add(fc_vbox, 0, wx.EXPAND) self.vbox.AddSpacer(10) self.vbox.AddStretchSpacer() freq_hbox.AddSpacer(5) forms.text_box( parent=self.panel, sizer=freq_hbox, proportion=1, converter=forms.float_converter(), ps=self.tb, key=uhd_siggen.TX_FREQ_KEY, ) freq_hbox.AddSpacer(10) forms.slider( parent=self.panel, sizer=freq_hbox, proportion=2, ps=self.tb, key=uhd_siggen.TX_FREQ_KEY, minimum=self.tb[uhd_siggen.FREQ_RANGE_KEY].start(), maximum=self.tb[uhd_siggen.FREQ_RANGE_KEY].stop(), num_steps=100, ) freq_hbox.AddSpacer(5) tr_hbox.AddSpacer(5) forms.static_text( parent=self.panel, sizer=tr_hbox, label='RF Frequency', ps=self.tb, key=uhd_siggen.RF_FREQ_KEY, converter=forms.float_converter(), proportion=1, ) tr_hbox.AddSpacer(10) forms.static_text( parent=self.panel, sizer=tr_hbox, label='DSP Frequency', ps=self.tb, key=uhd_siggen.DSP_FREQ_KEY, converter=forms.float_converter(), proportion=1, ) tr_hbox.AddSpacer(5) ################################################## # Amplitude controls ################################################## amp_hbox = forms.static_box_sizer(parent=self.panel, label="Amplitude", orient=wx.VERTICAL, bold=True) amp_hbox.AddSpacer(5) # First row of amp controls (ampl) lvl_hbox = wx.BoxSizer(wx.HORIZONTAL) amp_hbox.Add(lvl_hbox, 0, wx.EXPAND) amp_hbox.AddSpacer(10) # Second row of amp controls (tx gain) gain_hbox = wx.BoxSizer(wx.HORIZONTAL) amp_hbox.Add(gain_hbox, 0, wx.EXPAND) amp_hbox.AddSpacer(5) self.vbox.Add(amp_hbox, 0, wx.EXPAND) self.vbox.AddSpacer(10) self.vbox.AddStretchSpacer() lvl_hbox.AddSpacer(5) forms.text_box( parent=self.panel, sizer=lvl_hbox, proportion=1, converter=forms.float_converter(), ps=self.tb, key=uhd_siggen.AMPLITUDE_KEY, label="Level (0.0-1.0)", ) lvl_hbox.AddSpacer(10) forms.log_slider( parent=self.panel, sizer=lvl_hbox, proportion=2, ps=self.tb, key=uhd_siggen.AMPLITUDE_KEY, min_exp=-6, max_exp=0, base=10, num_steps=100, ) lvl_hbox.AddSpacer(5) if self.tb[uhd_siggen.GAIN_RANGE_KEY].start() < self.tb[uhd_siggen.GAIN_RANGE_KEY].stop(): gain_hbox.AddSpacer(5) forms.text_box( parent=self.panel, sizer=gain_hbox, proportion=1, converter=forms.float_converter(), ps=self.tb, key=uhd_siggen.GAIN_KEY, label="TX Gain (dB)", ) gain_hbox.AddSpacer(10) forms.slider( parent=self.panel, sizer=gain_hbox, proportion=2, ps=self.tb, key=uhd_siggen.GAIN_KEY, minimum=self.tb[uhd_siggen.GAIN_RANGE_KEY].start(), maximum=self.tb[uhd_siggen.GAIN_RANGE_KEY].stop(), step_size=self.tb[uhd_siggen.GAIN_RANGE_KEY].step(), ) gain_hbox.AddSpacer(5) ################################################## # Sample Rate controls ################################################## sam_hbox = forms.static_box_sizer(parent=self.panel, label="Sample Rate", orient=wx.HORIZONTAL, bold=True) self.vbox.Add(sam_hbox, 0, wx.EXPAND) self.vbox.AddSpacer(10) self.vbox.AddStretchSpacer() sam_hbox.AddStretchSpacer(20) forms.static_text( parent=self.panel, sizer=sam_hbox, label='Sample Rate (sps)', ps=self.tb, key=uhd_siggen.SAMP_RATE_KEY, converter=forms.float_converter(), ) sam_hbox.AddStretchSpacer(20) ################################################## # UHD status ################################################## u2_hbox = forms.static_box_sizer(parent=self.panel, label="UHD (%s)" % (uhd.get_version_string()), orient=wx.HORIZONTAL, bold=True) self.vbox.Add(u2_hbox, 0, wx.EXPAND) self.vbox.AddSpacer(10) self.vbox.AddStretchSpacer() u2_hbox.AddSpacer(10) forms.static_text( parent=self.panel, sizer=u2_hbox, ps=self.tb, key=uhd_siggen.DESC_KEY, converter=forms.str_converter(), ) self.vbox.AddSpacer(5) self.vbox.AddStretchSpacer() def main(): try: # Get command line parameters (options, args) = uhd_siggen.get_options() # Create the top block using these tb = uhd_siggen.top_block(options, args) # Create the GUI application app = gui.app(top_block=tb, # Constructed top block gui=app_gui, # User interface class options=options, # Command line options args=args, # Command line args title="UHD Signal Generator", # Top window title nstatus=1, # Number of status lines start=True, # Whether to start flowgraph realtime=True) # Whether to set realtime priority # And run it app.MainLoop() except RuntimeError, e: print e sys.exit(1) # Make sure to create the top block (tb) within a function: That code # in main will allow tb to go out of scope on return, which will call # the decontructor on uhd device and stop transmit. Whats odd is that # grc works fine with tb in the __main__, perhaps its because the # try/except clauses around tb. if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-uhd/apps/uhd_rx_nogui0000775000175000017500000002472512207440367020114 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, uhd, audio from gnuradio import filter from gnuradio import analog from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys """ This example application demonstrates receiving and demodulating different types of signals using the USRP. A receive chain is built up of the following signal processing blocks: USRP - Daughter board source generating complex baseband signal. CHAN - Low pass filter to select channel bandwidth RFSQL - RF squelch zeroing output when input power below threshold AGC - Automatic gain control leveling signal at [-1.0, +1.0] DEMOD - Demodulation block appropriate to selected signal type. This converts the complex baseband to real audio frequencies, and applies an appropriate low pass decimating filter. CTCSS - Optional tone squelch zeroing output when tone is not present. RSAMP - Resampler block to convert audio sample rate to user specified sound card output rate. AUDIO - Audio sink for playing final output to speakers. The following are required command line parameters: -f FREQ USRP receive frequency -m MOD Modulation type, select from AM, FM, or WFM The following are optional command line parameters: -R SUBDEV Daughter board specification, defaults to first found -c FREQ Calibration offset. Gets added to receive frequency. Defaults to 0.0 Hz. -g GAIN Daughterboard gain setting. Defaults to mid-range. -o RATE Sound card output rate. Defaults to 32000. Useful if your sound card only accepts particular sample rates. -r RFSQL RF squelch in db. Defaults to -50.0. -p FREQ CTCSS frequency. Opens squelch when tone is present. Once the program is running, ctrl-break (Ctrl-C) stops operation. Please see fm_demod.py and am_demod.py for details of the demodulation blocks. """ # (device_rate, channel_rate, audio_rate, channel_pass, channel_stop, demod) demod_params = { 'AM' : (256e3, 16e3, 16e3, 5000, 8000, analog.demod_10k0a3e_cf), 'FM' : (256e3, 32e3, 8e3, 8000, 9000, analog.demod_20k0f3e_cf), 'WFM' : (320e3, 320e3, 32e3, 80000, 115000, analog.demod_200kf3e_cf) } class uhd_src(gr.hier_block2): """ Create a UHD source object supplying complex floats. Selects user supplied subdevice or chooses first available one. Calibration value is the offset from the tuned frequency to the actual frequency. """ def __init__(self, args, spec, antenna, samp_rate, gain=None, calibration=0.0): gr.hier_block2.__init__(self, "uhd_src", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature self._src = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(spec): self._src.set_subdev_spec(spec, 0) # Set the antenna if(antenna): self._src.set_antenna(antenna, 0) self._src.set_samp_rate(samp_rate) dev_rate = self._src.get_samp_rate() self._samp_rate = samp_rate # Resampler to get to exactly samp_rate no matter what dev_rate is self._rrate = samp_rate / dev_rate self._resamp = filter.pfb.arb_resampler_ccf(self._rrate) # If no gain specified, set to midrange gain_range = self._src.get_gain_range() if gain is None: gain = (gain_range.start()+gain_range.stop())/2.0 print "Using gain: ", gain self._src.set_gain(gain) self._cal = calibration self.connect(self._src, self._resamp, self) def tune(self, freq): r = self._src.set_center_freq(freq+self._cal, 0) def rate(self): return self._samp_rate class app_top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) self.options = options (dev_rate, channel_rate, audio_rate, channel_pass, channel_stop, demod) = demod_params[options.modulation] DEV = uhd_src(options.args, # UHD device address options.spec, # device subdev spec options.antenna, # device antenna dev_rate, # device sample rate options.gain, # Receiver gain options.calibration) # Frequency offset DEV.tune(options.frequency) if_rate = DEV.rate() channel_decim = int(if_rate // channel_rate) audio_decim = int(channel_rate // audio_rate) CHAN_taps = filter.optfir.low_pass(1.0, # Filter gain if_rate, # Sample rate channel_pass, # One sided modulation bandwidth channel_stop, # One sided channel bandwidth 0.1, # Passband ripple 60) # Stopband attenuation CHAN = filter.freq_xlating_fir_filter_ccf(channel_decim, # Decimation rate CHAN_taps, # Filter taps 0.0, # Offset frequency if_rate) # Sample rate RFSQL = analog.pwr_squelch_cc(options.rf_squelch, # Power threshold 125.0/channel_rate, # Time constant int(channel_rate/20), # 50ms rise/fall False) # Zero, not gate output AGC = analog.agc_cc(1.0/channel_rate, # Time constant 1.0, # Reference power 1.0, # Initial gain 1.0) # Maximum gain DEMOD = demod(channel_rate, audio_decim) # From RF to audio #self.connect(DEV, CHAN, RFSQL, AGC, DEMOD) self.connect(DEV, CHAN, DEMOD) # Optionally add CTCSS and RSAMP if needed tail = DEMOD if options.ctcss != None and options.ctcss > 60.0: CTCSS = analog.ctcss_squelch_ff(audio_rate, # Sample rate options.ctcss) # Squelch tone self.connect(DEMOD, CTCSS) tail = CTCSS if options.output_rate != audio_rate: out_lcm = gru.lcm(audio_rate, options.output_rate) out_interp = int(out_lcm // audio_rate) out_decim = int(out_lcm // options.output_rate) RSAMP = filter.rational_resampler_fff(out_interp, out_decim) self.connect(tail, RSAMP) tail = RSAMP # Send to audio output device AUDIO = audio.sink(int(options.output_rate), options.audio_output) self.connect(tail, AUDIO) # Direct asynchronous notifications to callback function if self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) def async_callback(self, msg): md = self.async_src.msg_to_async_metadata_t(msg) print "Channel: %i Time: %f Event: %i" % (md.channel, md.time_spec.get_real_secs(), md.event_code) def main(): parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate [default=%default]") parser.add_option("-f", "--frequency", type="eng_float", default=None, metavar="Hz", help="set receive frequency to Hz [default=%default]") parser.add_option("-c", "--calibration", type="eng_float", default=0.0, metavar="Hz", help="set frequency offset to Hz [default=%default]") parser.add_option("-g", "--gain", type="eng_float", metavar="dB", default=None, help="set RF gain [default is midpoint]") parser.add_option("-m", "--modulation", type="choice", choices=('AM','FM','WFM'), metavar="TYPE", default=None, help="set modulation type (AM,FM,WFM) [default=%default]") parser.add_option("-o", "--output-rate", type="eng_float", default=32000, metavar="RATE", help="set audio output rate to RATE [default=%default]") parser.add_option("-r", "--rf-squelch", type="eng_float", default=-50.0, metavar="dB", help="set RF squelch to dB [default=%default]") parser.add_option("-p", "--ctcss", type="float", default=None, metavar="FREQ", help="set CTCSS squelch to FREQ [default=%default]") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--show-async-msg", action="store_true", default=False, help="Show asynchronous message notifications from UHD [default=%default]") (options, args) = parser.parse_args() if options.frequency is None: sys.stderr.write("Must supply receive frequency with -f.\n") sys.exit(1) if options.modulation is None: sys.stderr.write("Must supply a modulation type (AM, FM, WFM).\n") sys.exit(1) tb = app_top_block(options) try: tb.run() except KeyboardInterrupt: pass if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/0000755000175000017500000000000012207440367017233 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/apps/hf_radio/radio.py0000775000175000017500000002276012207440367020717 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # GUI interactions and high level connections handled here. # # Interacts with classes defined by wxGlade in ui.py. # # M. Revnell 2006-Jan from threading import * import wx import wx.lib.evtmgr as em import time from gnuradio import gr, gru, eng_notation, optfir from gnuradio import audio from gnuradio import blocks from gnuradio import uhd from gnuradio import blks2 from gnuradio.wxgui import fftsink2 from gnuradio.wxgui import waterfallsink2 from gnuradio.wxgui import scopesink2 from input import * from output import * from ssbdemod import * from ssbagc import * from ui import * from math import log10 class radio_top_block( gr.top_block ): def __init__( self ): gr.top_block.__init__(self, "radio_top_block") self.address = "addr=192.168.11.2" self.samp_rate = 256e3 self.freq = -2.5e6 self.gain = 0 self.src = uhd_input( self.address, self.samp_rate) self.src.set_freq(self.freq) self.src.set_gain(self.gain) self.fe_rate = self.src.usrp_rate self.filter_decim = 1 self.audio_decim = 16 self.demod_rate = self.fe_rate / self.filter_decim self.audio_rate = self.demod_rate / self.audio_decim self.audio_dev = "pulse" self.demod = ssb_demod( self.demod_rate, self.audio_rate ) self.agc = agc() self.out = output( self.audio_rate, self.audio_dev ) self.connect( self.src, self.demod, self.agc, self.out ) def tune( self, freq ): fe_target = -freq self.src.set_freq( fe_target ) demod_cf = fe_target - self.src.get_freq() self.demod.tune( demod_cf ) class radio_frame( ui_frame ): def __init__( self, block, *args, **kwds ): ui_frame.__init__( self, *args, **kwds ) self.block = block self.freq_disp.SetRange(0, 30e6) f = self.block.src.freq self.freq_disp.SetValue( -f ) self.volume.SetRange( 0, 20 ) self.pga.SetRange( 0, 20 ) self.rssi_range = 1 self.rssi.SetRange( self.rssi_range ) self.agc_max.SetValue( str( self.rssi_range ) ) self.spin_e0.SetValue( 50 ) self.spin_e1.SetValue( 50 ) self.spin_e2.SetValue( 50 ) self.spin_e3.SetValue( 50 ) self.spin_e4.SetValue( 50 ) self.spin_e5.SetValue( 50 ) self.spin_e6.SetValue( 50 ) bw = 3.3e3 self.bandwidth.SetValue( str( bw ) ) self.block.demod.set_bw( bw ) self.bw_spin.SetValue( 5 ) agc_gain = self.block.agc.gain.k() self.agc_gain_s.SetValue( 5 ) self.agc_gain.SetValue( str( agc_gain ) ) agc_ref = self.block.agc.offs.k() self.agc_ref.SetValue( str( agc_ref ) ) self.agc_ref_s.SetValue( 5 ) self.fespectrum = fftsink2.fft_sink_c( self.fe_panel, fft_size=512, sample_rate = block.fe_rate, ref_scale = 1.0, ref_level = 20.0, y_divs = 12, avg_alpha = 0.1) self.ifspectrum = fftsink2.fft_sink_c( self.if_panel, fft_size=512, sample_rate = block.audio_rate, ref_scale = 1.0, ref_level = 20.0, y_divs = 12, avg_alpha = 0.1) self.fespectrum.win.Bind( wx.EVT_MOTION, self.fe_mouse) self.fespectrum.win.Bind( wx.EVT_LEFT_DOWN, self.fe_click) block.connect( block.src.src, self.fespectrum ) block.connect( block.demod.xlate, self.ifspectrum ) def agc_ref_up( self, event ): self.agc_ref_s.SetValue( 5 ) r = float( self.agc_ref.GetValue() ) r = r + 5 self.agc_ref.SetValue( str( r ) ) self.block.agc.offs.set_k( r ) def agc_ref_down( self, event ): self.agc_ref_s.SetValue( 5 ) r = float( self.agc_ref.GetValue() ) r = r - 5 self.agc_ref.SetValue( str( r ) ) self.block.agc.offs.set_k( r ) def agc_gain_up( self, event ): self.agc_gain_s.SetValue( 5 ) g = float(self.agc_gain.GetValue()) g = g + 10 self.agc_gain.SetValue( str( g ) ) self.block.agc.gain.set_k( g ) def agc_gain_down( self, event ): self.agc_gain_s.SetValue( 5 ) g = float(self.agc_gain.GetValue()) g = g - 10 self.agc_gain.SetValue( str( g ) ) self.block.agc.gain.set_k( g ) def fe_mouse( self, event ): f = int(self.freq_disp.GetValue()) f = f+((event.GetX()-346.)*(400./610.))*1000 self.fespectrum.win.SetToolTip( wx.ToolTip( eng_notation.num_to_str(f))) def fe_click( self, event ): f = int(self.freq_disp.GetValue()) f = f+((event.GetX()-346.)*(400./610.))*1000 self.tune( f ) def setrssi( self, level ): if level < 0: level = 0 if level > self.rssi_range: self.rssi_range = level self.rssi.SetRange( level ) self.agc_max.SetValue( str( level )) self.rssi.SetValue( level ) self.agc_level.SetValue( str( level )) def tune_evt( self, event ): f = self.freq_disp.GetValue() self.tune( f ) def tune( self, frequency ): self.freq_disp.SetValue( frequency ) self.block.tune( frequency ) def up_e0( self, event ): self.spin_e0.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e0 ) def down_e0( self, event ): self.spin_e0.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e0 ) def up_e1( self, event ): self.spin_e1.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e1 ) def down_e1( self, event ): self.spin_e1.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e1 ) def up_e2( self, event ): self.spin_e2.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e2 ) def down_e2( self, event ): self.spin_e2.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e2 ) def up_e3( self, event ): self.spin_e3.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e3 ) def down_e3( self, event ): self.spin_e3.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e3 ) def up_e4( self, event ): self.spin_e4.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e4 ) def down_e4( self, event ): self.spin_e4.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e4 ) def up_e5( self, event ): self.spin_e5.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e5 ) def down_e5( self, event ): self.spin_e5.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e5 ) def up_e6( self, event ): self.spin_e6.SetValue( 50 ) self.tune( self.freq_disp.GetValue() + 1e6 ) def down_e6( self, event ): self.spin_e6.SetValue( 50 ) self.tune( self.freq_disp.GetValue() - 1e6 ) def event_pga( self, event ): self.block.src.set_gain(self.pga.GetValue()) def event_vol( self, event ): self.block.out.set( self.volume.GetValue()/20.0 ) def set_usb( self, event ): self.block.demod.upper_sb() def set_lsb( self, event ): self.block.demod.lower_sb() def set_am( self, event ): self.block.demod.set_am() def bw_up( self, event ): self.bw_spin.SetValue( 5 ) bw = float(self.bandwidth.GetValue()) bw = bw + 20.0 if bw > 10e3: bw = 10e3 self.bandwidth.SetValue( str( bw ) ) self.block.demod.set_bw( bw ) def bw_down( self, event ): self.bw_spin.SetValue( 5 ) bw = float(self.bandwidth.GetValue()) bw = bw - 20.0 if bw < 50: bw = 50 self.bandwidth.SetValue( str( bw ) ) self.block.demod.set_bw( bw ) class radio( wx.App ): def OnInit( self ): self.block = radio_top_block() self.frame = radio_frame( self.block, None, -1, "HF Receiver" ) self.frame.Show( True ) self.SetTopWindow( self.frame ) self.block.start() return True def rssi_function(): global radio_obj global sig_probe go = True while go: try: level = sig_probe.level() wx.CallAfter( radio_obj.frame.setrssi, level ) time.sleep( .1 ) except: go = False def main(): global radio_obj, sig_probe radio_obj = radio( 0 ) sig_probe = blocks.probe_signal_f() radio_obj.block.connect(radio_obj.block.agc.offs, sig_probe) thread2 = Thread( target = rssi_function ) thread2.start() radio_obj.MainLoop() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/ssbdemod.py0000664000175000017500000000776212207440367021423 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # This tries to push the hilbert transform for ssb demod back into the # freq. xlating filter. # # The starting point for this was weaver_isb_am1_usrp3.py. # # The tap coefficients for freq_xlating_fir_filter_ccf were generated # externally and are read from a file because I didn't want to learn how # to make fir filters with arbitrary phase response using python numeric # facilities. # # They were generated using Scilab which I am already familiar with. # M. Revnell Jan 06 from gnuradio import gr from gnuradio import blocks from gnuradio import filter class ssb_demod( gr.hier_block2 ): def __init__( self, if_rate, af_rate ): gr.hier_block2.__init__(self, "ssb_demod", gr.io_signature(1,1,gr.sizeof_gr_complex), gr.io_signature(1,1,gr.sizeof_float)) self.if_rate = int(if_rate) self.af_rate = int(af_rate) self.if_decim = int(if_rate / af_rate) self.sideband = 1 self.xlate_taps = ([complex(v) for v in file('ssb_taps').readlines()]) self.audio_taps = filter.firdes.low_pass( 1.0, self.af_rate, 3e3, 600, filter.firdes.WIN_HAMMING ) self.xlate = filter.freq_xlating_fir_filter_ccc( self.if_decim, self.xlate_taps, 0, self.if_rate ) self.split = blocks.complex_to_float() self.lpf = filter.fir_filter_fff( 1, self.audio_taps ) self.sum = blocks.add_ff( ) self.am_sel = blocks.multiply_const_ff( 0 ) self.sb_sel = blocks.multiply_const_ff( 1 ) self.mixer = blocks.add_ff() self.am_det = blocks.complex_to_mag() self.connect(self, self.xlate) self.connect(self.xlate, self.split) self.connect((self.split, 0), (self.sum, 0)) self.connect((self.split, 1), (self.sum, 1)) self.connect(self.sum, self.sb_sel) self.connect(self.xlate, self.am_det) self.connect(self.sb_sel, (self.mixer, 0)) self.connect(self.am_det, self.am_sel) self.connect(self.am_sel, (self.mixer, 1)) self.connect(self.mixer, self.lpf) self.connect(self.lpf, self) def upper_sb( self ): self.xlate.set_taps([v.conjugate() for v in self.xlate_taps]) self.sb_sel.set_k( 1.0 ) self.am_sel.set_k( 0.0 ) def lower_sb( self ): self.xlate.set_taps(self.xlate_taps) self.sb_sel.set_k( 1.0 ) self.am_sel.set_k( 0.0 ) def set_am( self ): taps = filter.firdes.low_pass( 1.0, self.if_rate, 5e3, 2e3, filter.firdes.WIN_HAMMING ) self.xlate.set_taps( taps ) self.sb_sel.set_k( 0.0 ) self.am_sel.set_k( 1.0 ) def set_bw( self, bw ): self.audio_taps = filter.firdes.low_pass( 1.0, self.af_rate, bw, 600, filter.firdes.WIN_HAMMING ) self.lpf.set_taps( self.audio_taps ) def tune( self, freq ): self.xlate.set_center_freq( freq ) gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/startup.py0000644000175000017500000000002411700377701021301 0ustar jcorganjcorganfrom radio import * gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/hfir.sci0000644000175000017500000000357411744612271020674 0ustar jcorganjcorgan// designs a complex tap fir filter akin to the hilbert transformer. // // The hilbert transformer is classified as a linear phase fir // with allpass magnitude response and 90 degree phase response for // positive frequencies and -90 degrees phase for negative frequencies. // Or, if you prefer, normalized frequencies between .5 and 1 since // negative frequencies don't really have much meaning outside the complex // domain. // // Normally one would use the hilbert transformer in one leg of a complex // processing block and a compensating delay in the other. // // This one differs in the following respects: // It is low pass with a cutoff of .078125 // The filter is a lowpass kaiser windowed filter with parameter 3 // The phase response is 45 degrees for positive frequencies and -45 // for negative frequencies. // The coefficent set is used in one path and the same coefficients // are used time reversed in the other. This results in the net effect // of +/- 90 degrees as in the usual hilbert application. // // The coefficient set can be used in the gnuradio frequency translating // fir filter for ssb demodulation. // // This isn't as computationally efficient as using the hilbert transformer // and compensating delay but fascinating none the less. // // This program is for the scilab language a very powerful free math // package similar to Matlab with infinitely better price/performace. // // compute the prototype lowpass fir // length is 255 (odd) for the same symmetry reasons as the hilbert transformer len = 1023; l2 = floor(len/2); md = l2 + 1; l3 = md + 1; h = wfir( 'lp', len, [10.0/256 0], 'kr', [3 0] ); H = fft(h); H(1:l2)=H(1:l2)*exp(%i*%pi/4); H(md)=0+%i*0; H(l3:len)=H(l3:len)*exp(-%i*%pi/4); j=real(ifft(H)); k(1:len)=j(len:-1:1); x=j+%i.*k; X=fft(x); plot(abs(X)) f = file('open','taps') for i=(1:len) fprintf( f, '%f%+fj', j(i), k(i) ) end file('close',f) gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/input.py0000664000175000017500000000527112207440367020753 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # Basic USRP setup and control. # It's only ever been tried with a basic rx daughter card. # # Imagine that the gnuradio boilerplate is here. # # M. Revnell 2005-Dec from gnuradio import gr from gnuradio import uhd class uhd_input(gr.hier_block2): def __init__( self, address, samp_rate): gr.hier_block2.__init__(self, "uhd_input", gr.io_signature(0,0,0), gr.io_signature(1,1,gr.sizeof_gr_complex)) self.src = uhd.usrp_source(device_addr=address, io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=1) self.src.set_samp_rate(samp_rate) self.usrp_rate = self.src.get_samp_rate() self.connect(self.src, self) def set_freq(self, target_freq): """ Set the center frequency. Args: target_freq: frequency in Hz """ r = self.src.set_center_freq(target_freq, 0) if r: self.freq = target_freq return True else: return False def get_freq(self): return self.src.get_center_freq(0) def set_gain(self, gain): self.gain = gain self.src.set_gain(gain, 0) def add_options(parser): parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") add_options = staticmethod(add_options) gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/ssbagc.py0000664000175000017500000000503712207440367021056 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # post detection agc processing # # This agc strategy is copied more or less verbatim from # weaver_isb_am1_usrp3.py by cswiger. # # Thanks. # # Then modified in a variety of ways. # # There doesn't appear to be a way to hook multiple blocks to the # input port when building a hier block like this. Thus the # split below. # # Basic operation. # Power is estimated by squaring the input. # Low pass filter using a 1 pole iir. # The time constant can be tweaked by changing the taps. # Currently there is no implementation to change this while operating # a potentially useful addition. # The log block turns this into dB # gain adjusts the agc authority. # # M. Revnell 2006-Jan from gnuradio import gr from gnuradio import blocks from gnuradio import filter class agc( gr.hier_block2 ): def __init__( self ): gr.hier_block2.__init__(self, "agc", gr.io_signature(1,1,gr.sizeof_float), gr.io_signature(1,1,gr.sizeof_float)) self.split = blocks.multiply_const_ff( 1 ) self.sqr = blocks.multiply_ff( ) self.int0 = filter.iir_filter_ffd( [.004, 0], [0, .999] ) self.offs = blocks.add_const_ff( -30 ) self.gain = blocks.multiply_const_ff( 70 ) self.log = blocks.nlog10_ff( 10, 1 ) self.agc = blocks.divide_ff( ) self.connect(self, self.split) self.connect(self.split, (self.agc, 0)) self.connect(self.split, (self.sqr, 0)) self.connect(self.split, (self.sqr, 1)) self.connect(self.sqr, self.int0) self.connect(self.int0, self.log) self.connect(self.log, self.offs) self.connect(self.offs, self.gain) self.connect(self.gain, (self.agc, 1)) self.connect(self.agc, self) gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/ssb_taps0000644000175000017500000004675511700377701021013 0ustar jcorganjcorgan-0.000035-0.000009j -0.000066-0.000020j -0.000080-0.000044j -0.000084-0.000071j -0.000077-0.000100j -0.000063-0.000127j -0.000041-0.000150j -0.000013-0.000167j 0.000020-0.000177j 0.000054-0.000180j 0.000089-0.000174j 0.000121-0.000161j 0.000150-0.000140j 0.000173-0.000113j 0.000188-0.000081j 0.000196-0.000046j 0.000194-0.000011j 0.000184+0.000022j 0.000165+0.000052j 0.000139+0.000077j 0.000107+0.000093j 0.000071+0.000102j 0.000034+0.000101j -0.000002+0.000090j -0.000036+0.000070j -0.000064+0.000042j -0.000086+0.000006j -0.000098-0.000034j -0.000101-0.000077j -0.000093-0.000120j -0.000076-0.000161j -0.000049-0.000197j -0.000014-0.000227j 0.000026-0.000248j 0.000071-0.000259j 0.000117-0.000259j 0.000162-0.000249j 0.000203-0.000228j 0.000237-0.000199j 0.000263-0.000162j 0.000279-0.000120j 0.000284-0.000075j 0.000278-0.000031j 0.000260+0.000010j 0.000232+0.000045j 0.000196+0.000073j 0.000153+0.000090j 0.000106+0.000095j 0.000059+0.000089j 0.000014+0.000071j -0.000027+0.000041j -0.000059+0.000002j -0.000082-0.000046j -0.000093-0.000098j -0.000091-0.000152j -0.000077-0.000206j -0.000050-0.000255j -0.000012-0.000298j 0.000034-0.000330j 0.000088-0.000351j 0.000145-0.000359j 0.000202-0.000354j 0.000256-0.000335j 0.000304-0.000304j 0.000343-0.000262j 0.000370-0.000213j 0.000384-0.000158j 0.000384-0.000102j 0.000369-0.000048j 0.000341+0.000002j 0.000302+0.000042j 0.000252+0.000072j 0.000196+0.000088j 0.000137+0.000089j 0.000078+0.000075j 0.000024+0.000047j -0.000023+0.000005j -0.000059-0.000048j -0.000082-0.000109j -0.000090-0.000175j -0.000081-0.000242j -0.000058-0.000306j -0.000019-0.000364j 0.000032-0.000411j 0.000093-0.000445j 0.000161-0.000465j 0.000232-0.000467j 0.000301-0.000453j 0.000365-0.000423j 0.000419-0.000379j 0.000461-0.000323j 0.000487-0.000259j 0.000497-0.000190j 0.000489-0.000121j 0.000464-0.000056j 0.000423+0.000001j 0.000369+0.000046j 0.000304+0.000076j 0.000233+0.000089j 0.000160+0.000083j 0.000089+0.000060j 0.000025+0.000018j -0.000027-0.000038j -0.000065-0.000107j -0.000086-0.000185j -0.000088-0.000266j -0.000071-0.000347j -0.000035-0.000422j 0.000019-0.000487j 0.000086-0.000538j 0.000164-0.000573j 0.000248-0.000588j 0.000334-0.000582j 0.000415-0.000557j 0.000488-0.000513j 0.000548-0.000452j 0.000592-0.000379j 0.000616-0.000297j 0.000619-0.000213j 0.000600-0.000130j 0.000561-0.000054j 0.000504+0.000010j 0.000432+0.000058j 0.000350+0.000086j 0.000261+0.000093j 0.000173+0.000078j 0.000090+0.000040j 0.000017-0.000017j -0.000040-0.000092j -0.000078-0.000180j -0.000095-0.000275j -0.000088-0.000374j -0.000058-0.000469j -0.000006-0.000555j 0.000065-0.000627j 0.000152-0.000681j 0.000250-0.000712j 0.000352-0.000720j 0.000454-0.000703j 0.000548-0.000663j 0.000630-0.000601j 0.000694-0.000521j 0.000737-0.000428j 0.000755-0.000327j 0.000748-0.000225j 0.000715-0.000128j 0.000659-0.000042j 0.000582+0.000028j 0.000490+0.000077j 0.000387+0.000101j 0.000280+0.000099j 0.000175+0.000070j 0.000080+0.000015j -0.000001-0.000063j -0.000061-0.000159j -0.000097-0.000268j -0.000106-0.000385j -0.000087-0.000501j -0.000040-0.000611j 0.000032-0.000708j 0.000125-0.000786j 0.000235-0.000839j 0.000354-0.000866j 0.000477-0.000863j 0.000595-0.000831j 0.000702-0.000772j 0.000792-0.000688j 0.000859-0.000585j 0.000898-0.000469j 0.000907-0.000347j 0.000886-0.000227j 0.000835-0.000115j 0.000757-0.000019j 0.000657+0.000055j 0.000540+0.000102j 0.000415+0.000119j 0.000287+0.000103j 0.000165+0.000056j 0.000058-0.000020j -0.000029-0.000122j -0.000090-0.000243j -0.000121-0.000378j -0.000118-0.000517j -0.000082-0.000653j -0.000014-0.000778j 0.000082-0.000885j 0.000201-0.000966j 0.000337-0.001017j 0.000481-0.001034j 0.000626-0.001016j 0.000762-0.000965j 0.000882-0.000882j 0.000978-0.000772j 0.001044-0.000643j 0.001076-0.000501j 0.001072-0.000355j 0.001032-0.000215j 0.000958-0.000089j 0.000854+0.000016j 0.000726+0.000091j 0.000582+0.000133j 0.000431+0.000138j 0.000281+0.000105j 0.000143+0.000035j 0.000024-0.000068j -0.000068-0.000199j -0.000126-0.000350j -0.000147-0.000513j -0.000128-0.000677j -0.000070-0.000834j 0.000024-0.000974j 0.000150-0.001089j 0.000300-0.001171j 0.000465-0.001216j 0.000637-0.001219j 0.000805-0.001182j 0.000960-0.001105j 0.001091-0.000993j 0.001191-0.000853j 0.001253-0.000692j 0.001274-0.000521j 0.001252-0.000350j 0.001188-0.000189j 0.001085-0.000049j 0.000950+0.000062j 0.000790+0.000136j 0.000614+0.000168j 0.000435+0.000156j 0.000261+0.000099j 0.000105+0.000000j -0.000024-0.000136j -0.000117-0.000301j -0.000169-0.000486j -0.000175-0.000680j -0.000134-0.000872j -0.000048-0.001051j 0.000079-0.001206j 0.000240-0.001326j 0.000426-0.001406j 0.000626-0.001439j 0.000829-0.001424j 0.001022-0.001361j 0.001195-0.001252j 0.001336-0.001106j 0.001437-0.000929j 0.001491-0.000733j 0.001496-0.000529j 0.001449-0.000330j 0.001354-0.000148j 0.001217+0.000005j 0.001044+0.000120j 0.000846+0.000188j 0.000635+0.000206j 0.000424+0.000170j 0.000226+0.000083j 0.000053-0.000053j -0.000084-0.000228j -0.000176-0.000434j -0.000216-0.000659j -0.000201-0.000889j -0.000131-0.001111j -0.000009-0.001312j 0.000158-0.001480j 0.000362-0.001604j 0.000590-0.001677j 0.000829-0.001694j 0.001066-0.001653j 0.001286-0.001556j 0.001477-0.001408j 0.001626-0.001219j 0.001724-0.001000j 0.001765-0.000762j 0.001746-0.000522j 0.001668-0.000293j 0.001534-0.000090j 0.001353+0.000075j 0.001135+0.000190j 0.000893+0.000247j 0.000642+0.000243j 0.000396+0.000176j 0.000172+0.000049j -0.000017-0.000131j -0.000159-0.000355j -0.000244-0.000609j -0.000266-0.000880j -0.000222-0.001151j -0.000114-0.001406j 0.000053-0.001630j 0.000270-0.001810j 0.000524-0.001934j 0.000802-0.001994j 0.001087-0.001987j 0.001362-0.001911j 0.001611-0.001772j 0.001819-0.001576j 0.001973-0.001336j 0.002063-0.001065j 0.002084-0.000779j 0.002033-0.000497j 0.001914-0.000236j 0.001732-0.000011j 0.001498+0.000162j 0.001225+0.000272j 0.000931+0.000312j 0.000633+0.000277j 0.000349+0.000168j 0.000097-0.000009j -0.000107-0.000246j -0.000250-0.000528j -0.000322-0.000841j -0.000316-0.001166j -0.000233-0.001484j -0.000076-0.001775j 0.000148-0.002024j 0.000426-0.002213j 0.000743-0.002332j 0.001080-0.002373j 0.001418-0.002332j 0.001736-0.002211j 0.002017-0.002017j 0.002241-0.001760j 0.002397-0.001457j 0.002473-0.001124j 0.002464-0.000783j 0.002371-0.000453j 0.002198-0.000156j 0.001954+0.000091j 0.001654+0.000269j 0.001316+0.000369j 0.000959+0.000381j 0.000606+0.000303j 0.000279+0.000139j -0.000003-0.000103j -0.000220-0.000411j -0.000359-0.000768j -0.000408-0.001152j -0.000365-0.001542j -0.000229-0.001915j -0.000006-0.002248j 0.000292-0.002522j 0.000648-0.002719j 0.001042-0.002826j 0.001452-0.002837j 0.001853-0.002750j 0.002223-0.002569j 0.002537-0.002304j 0.002778-0.001971j 0.002930-0.001588j 0.002984-0.001179j 0.002933-0.000770j 0.002782-0.000384j 0.002538-0.000046j 0.002215+0.000222j 0.001831+0.000402j 0.001410+0.000481j 0.000976+0.000452j 0.000557+0.000316j 0.000179+0.000077j -0.000134-0.000252j -0.000362-0.000654j -0.000490-0.001105j -0.000506-0.001580j -0.000407-0.002052j -0.000197-0.002492j 0.000113-0.002875j 0.000508-0.003176j 0.000966-0.003377j 0.001460-0.003464j 0.001963-0.003432j 0.002444-0.003281j 0.002876-0.003019j 0.003231-0.002659j 0.003488-0.002224j 0.003631-0.001739j 0.003649-0.001233j 0.003540-0.000737j 0.003309-0.000282j 0.002969+0.000103j 0.002539+0.000393j 0.002044+0.000568j 0.001515+0.000614j 0.000982+0.000525j 0.000480+0.000304j 0.000039-0.000039j -0.000311-0.000487j -0.000547-0.001016j -0.000652-0.001595j -0.000615-0.002193j -0.000436-0.002773j -0.000122-0.003301j 0.000311-0.003746j 0.000842-0.004081j 0.001440-0.004282j 0.002071-0.004338j 0.002700-0.004243j 0.003289-0.004000j 0.003803-0.003622j 0.004210-0.003132j 0.004485-0.002556j 0.004610-0.001930j 0.004574-0.001291j 0.004379-0.000679j 0.004034-0.000133j 0.003558+0.000313j 0.002977+0.000627j 0.002327+0.000787j 0.001647+0.000779j 0.000977+0.000598j 0.000360+0.000250j -0.000163-0.000249j -0.000559-0.000872j -0.000799-0.001587j -0.000864-0.002354j -0.000744-0.003129j -0.000442-0.003866j 0.000031-0.004522j 0.000651-0.005057j 0.001385-0.005437j 0.002193-0.005637j 0.003030-0.005643j 0.003848-0.005451j 0.004597-0.005069j 0.005234-0.004519j 0.005718-0.003830j 0.006019-0.003044j 0.006114-0.002206j 0.005997-0.001368j 0.005669-0.000583j 0.005147+0.000099j 0.004460+0.000631j 0.003647+0.000975j 0.002757+0.001105j 0.001842+0.001003j 0.000961+0.000668j 0.000168+0.000111j -0.000482-0.000643j -0.000944-0.001555j -0.001183-0.002578j -0.001176-0.003656j -0.000912-0.004727j -0.000397-0.005728j 0.000346-0.006601j 0.001284-0.007292j 0.002368-0.007755j 0.003540-0.007959j 0.004735-0.007886j 0.005885-0.007535j 0.006922-0.006922j 0.007782-0.006078j 0.008412-0.005050j 0.008769-0.003898j 0.008825-0.002691j 0.008572-0.001504j 0.008016-0.000412j 0.007185+0.000510j 0.006123+0.001196j 0.004891+0.001591j 0.003560+0.001657j 0.002212+0.001372j 0.000933+0.000734j -0.000192-0.000236j -0.001083-0.001500j -0.001672-0.002998j -0.001905-0.004655j -0.001747-0.006384j -0.001182-0.008090j -0.000222-0.009676j 0.001101-0.011045j 0.002732-0.012114j 0.004593-0.012810j 0.006591-0.013081j 0.008621-0.012896j 0.010571-0.012253j 0.012328-0.011175j 0.013785-0.009712j 0.014847-0.007941j 0.015438-0.005962j 0.015507-0.003893j 0.015029-0.001863j 0.014011-0.000011j 0.012494+0.001529j 0.010549+0.002630j 0.008277+0.003179j 0.005809+0.003090j 0.003294+0.002304j 0.000896+0.000795j -0.001212-0.001423j -0.002859-0.004299j -0.003886-0.007744j -0.004151-0.011630j -0.003539-0.015799j -0.001969-0.020066j 0.000601-0.024225j 0.004168-0.028064j 0.008684-0.031367j 0.014056-0.033927j 0.020145-0.035558j 0.026775-0.036101j 0.033735-0.035433j 0.040789-0.033475j 0.047684-0.030197j 0.054164-0.025619j 0.059974-0.019815j 0.064878-0.012907j 0.068665-0.005067j 0.071159+0.003494j 0.072228+0.012531j 0.071791+0.021776j 0.069818+0.030947j 0.066339+0.039761j 0.061435+0.047944j 0.055243+0.055243j 0.047944+0.061435j 0.039761+0.066339j 0.030947+0.069818j 0.021776+0.071791j 0.012531+0.072228j 0.003494+0.071159j -0.005067+0.068665j -0.012907+0.064878j -0.019815+0.059974j -0.025619+0.054164j -0.030197+0.047684j -0.033475+0.040789j -0.035433+0.033735j -0.036101+0.026775j -0.035558+0.020145j -0.033927+0.014056j -0.031367+0.008684j -0.028064+0.004168j -0.024225+0.000601j -0.020066-0.001969j -0.015799-0.003539j -0.011630-0.004151j -0.007744-0.003886j -0.004299-0.002859j -0.001423-0.001212j 0.000795+0.000896j 0.002304+0.003294j 0.003090+0.005809j 0.003179+0.008277j 0.002630+0.010549j 0.001529+0.012494j -0.000011+0.014011j -0.001863+0.015029j -0.003893+0.015507j -0.005962+0.015438j -0.007941+0.014847j -0.009712+0.013785j -0.011175+0.012328j -0.012253+0.010571j -0.012896+0.008621j -0.013081+0.006591j -0.012810+0.004593j -0.012114+0.002732j -0.011045+0.001101j -0.009676-0.000222j -0.008090-0.001182j -0.006384-0.001747j -0.004655-0.001905j -0.002998-0.001672j -0.001500-0.001083j -0.000236-0.000192j 0.000734+0.000933j 0.001372+0.002212j 0.001657+0.003560j 0.001591+0.004891j 0.001196+0.006123j 0.000510+0.007185j -0.000412+0.008016j -0.001504+0.008572j -0.002691+0.008825j -0.003898+0.008769j -0.005050+0.008412j -0.006078+0.007782j -0.006922+0.006922j -0.007535+0.005885j -0.007886+0.004735j -0.007959+0.003540j -0.007755+0.002368j -0.007292+0.001284j -0.006601+0.000346j -0.005728-0.000397j -0.004727-0.000912j -0.003656-0.001176j -0.002578-0.001183j -0.001555-0.000944j -0.000643-0.000482j 0.000111+0.000168j 0.000668+0.000961j 0.001003+0.001842j 0.001105+0.002757j 0.000975+0.003647j 0.000631+0.004460j 0.000099+0.005147j -0.000583+0.005669j -0.001368+0.005997j -0.002206+0.006114j -0.003044+0.006019j -0.003830+0.005718j -0.004519+0.005234j -0.005069+0.004597j -0.005451+0.003848j -0.005643+0.003030j -0.005637+0.002193j -0.005437+0.001385j -0.005057+0.000651j -0.004522+0.000031j -0.003866-0.000442j -0.003129-0.000744j -0.002354-0.000864j -0.001587-0.000799j -0.000872-0.000559j -0.000249-0.000163j 0.000250+0.000360j 0.000598+0.000977j 0.000779+0.001647j 0.000787+0.002327j 0.000627+0.002977j 0.000313+0.003558j -0.000133+0.004034j -0.000679+0.004379j -0.001291+0.004574j -0.001930+0.004610j -0.002556+0.004485j -0.003132+0.004210j -0.003622+0.003803j -0.004000+0.003289j -0.004243+0.002700j -0.004338+0.002071j -0.004282+0.001440j -0.004081+0.000842j -0.003746+0.000311j -0.003301-0.000122j -0.002773-0.000436j -0.002193-0.000615j -0.001595-0.000652j -0.001016-0.000547j -0.000487-0.000311j -0.000039+0.000039j 0.000304+0.000480j 0.000525+0.000982j 0.000614+0.001515j 0.000568+0.002044j 0.000393+0.002539j 0.000103+0.002969j -0.000282+0.003309j -0.000737+0.003540j -0.001233+0.003649j -0.001739+0.003631j -0.002224+0.003488j -0.002659+0.003231j -0.003019+0.002876j -0.003281+0.002444j -0.003432+0.001963j -0.003464+0.001460j -0.003377+0.000966j -0.003176+0.000508j -0.002875+0.000113j -0.002492-0.000197j -0.002052-0.000407j -0.001580-0.000506j -0.001105-0.000490j -0.000654-0.000362j -0.000252-0.000134j 0.000077+0.000179j 0.000316+0.000557j 0.000452+0.000976j 0.000481+0.001410j 0.000402+0.001831j 0.000222+0.002215j -0.000046+0.002538j -0.000384+0.002782j -0.000770+0.002933j -0.001179+0.002984j -0.001588+0.002930j -0.001971+0.002778j -0.002304+0.002537j -0.002569+0.002223j -0.002750+0.001853j -0.002837+0.001452j -0.002826+0.001042j -0.002719+0.000648j -0.002522+0.000292j -0.002248-0.000006j -0.001915-0.000229j -0.001542-0.000365j -0.001152-0.000408j -0.000768-0.000359j -0.000411-0.000220j -0.000103-0.000003j 0.000139+0.000279j 0.000303+0.000606j 0.000381+0.000959j 0.000369+0.001316j 0.000269+0.001654j 0.000091+0.001954j -0.000156+0.002198j -0.000453+0.002371j -0.000783+0.002464j -0.001124+0.002473j -0.001457+0.002397j -0.001760+0.002241j -0.002017+0.002017j -0.002211+0.001736j -0.002332+0.001418j -0.002373+0.001080j -0.002332+0.000743j -0.002213+0.000426j -0.002024+0.000148j -0.001775-0.000076j -0.001484-0.000233j -0.001166-0.000316j -0.000841-0.000322j -0.000528-0.000250j -0.000246-0.000107j -0.000009+0.000097j 0.000168+0.000349j 0.000277+0.000633j 0.000312+0.000931j 0.000272+0.001225j 0.000162+0.001498j -0.000011+0.001732j -0.000236+0.001914j -0.000497+0.002033j -0.000779+0.002084j -0.001065+0.002063j -0.001336+0.001973j -0.001576+0.001819j -0.001772+0.001611j -0.001911+0.001362j -0.001987+0.001087j -0.001994+0.000802j -0.001934+0.000524j -0.001810+0.000270j -0.001630+0.000053j -0.001406-0.000114j -0.001151-0.000222j -0.000880-0.000266j -0.000609-0.000244j -0.000355-0.000159j -0.000131-0.000017j 0.000049+0.000172j 0.000176+0.000396j 0.000243+0.000642j 0.000247+0.000893j 0.000190+0.001135j 0.000075+0.001353j -0.000090+0.001534j -0.000293+0.001668j -0.000522+0.001746j -0.000762+0.001765j -0.001000+0.001724j -0.001219+0.001626j -0.001408+0.001477j -0.001556+0.001286j -0.001653+0.001066j -0.001694+0.000829j -0.001677+0.000590j -0.001604+0.000362j -0.001480+0.000158j -0.001312-0.000009j -0.001111-0.000131j -0.000889-0.000201j -0.000659-0.000216j -0.000434-0.000176j -0.000228-0.000084j -0.000053+0.000053j 0.000083+0.000226j 0.000170+0.000424j 0.000206+0.000635j 0.000188+0.000846j 0.000120+0.001044j 0.000005+0.001217j -0.000148+0.001354j -0.000330+0.001449j -0.000529+0.001496j -0.000733+0.001491j -0.000929+0.001437j -0.001106+0.001336j -0.001252+0.001195j -0.001361+0.001022j -0.001424+0.000829j -0.001439+0.000626j -0.001406+0.000426j -0.001326+0.000240j -0.001206+0.000079j -0.001051-0.000048j -0.000872-0.000134j -0.000680-0.000175j -0.000486-0.000169j -0.000301-0.000117j -0.000136-0.000024j 0.000000+0.000105j 0.000099+0.000261j 0.000156+0.000435j 0.000168+0.000614j 0.000136+0.000790j 0.000062+0.000950j -0.000049+0.001085j -0.000189+0.001188j -0.000350+0.001252j -0.000521+0.001274j -0.000692+0.001253j -0.000853+0.001191j -0.000993+0.001091j -0.001105+0.000960j -0.001182+0.000805j -0.001219+0.000637j -0.001216+0.000465j -0.001171+0.000300j -0.001089+0.000150j -0.000974+0.000024j -0.000834-0.000070j -0.000677-0.000128j -0.000513-0.000147j -0.000350-0.000126j -0.000199-0.000068j -0.000068+0.000024j 0.000035+0.000143j 0.000105+0.000281j 0.000138+0.000431j 0.000133+0.000582j 0.000091+0.000726j 0.000016+0.000854j -0.000089+0.000958j -0.000215+0.001032j -0.000355+0.001072j -0.000501+0.001076j -0.000643+0.001044j -0.000772+0.000978j -0.000882+0.000882j -0.000965+0.000762j -0.001016+0.000626j -0.001034+0.000481j -0.001017+0.000337j -0.000966+0.000201j -0.000885+0.000082j -0.000778-0.000014j -0.000653-0.000082j -0.000517-0.000118j -0.000378-0.000121j -0.000243-0.000090j -0.000122-0.000029j -0.000020+0.000058j 0.000056+0.000165j 0.000103+0.000287j 0.000119+0.000415j 0.000102+0.000540j 0.000055+0.000657j -0.000019+0.000757j -0.000115+0.000835j -0.000227+0.000886j -0.000347+0.000907j -0.000469+0.000898j -0.000585+0.000859j -0.000688+0.000792j -0.000772+0.000702j -0.000831+0.000595j -0.000863+0.000477j -0.000866+0.000354j -0.000839+0.000235j -0.000786+0.000125j -0.000708+0.000032j -0.000611-0.000040j -0.000501-0.000087j -0.000385-0.000106j -0.000268-0.000097j -0.000159-0.000061j -0.000063-0.000001j 0.000015+0.000080j 0.000070+0.000175j 0.000099+0.000280j 0.000101+0.000387j 0.000077+0.000490j 0.000028+0.000582j -0.000042+0.000659j -0.000128+0.000715j -0.000225+0.000748j -0.000327+0.000755j -0.000428+0.000737j -0.000521+0.000694j -0.000601+0.000630j -0.000663+0.000548j -0.000703+0.000454j -0.000720+0.000352j -0.000712+0.000250j -0.000681+0.000152j -0.000627+0.000065j -0.000555-0.000006j -0.000469-0.000058j -0.000374-0.000088j -0.000275-0.000095j -0.000180-0.000078j -0.000092-0.000040j -0.000017+0.000017j 0.000040+0.000090j 0.000078+0.000173j 0.000093+0.000261j 0.000086+0.000350j 0.000058+0.000432j 0.000010+0.000504j -0.000054+0.000561j -0.000130+0.000600j -0.000213+0.000619j -0.000297+0.000616j -0.000379+0.000592j -0.000452+0.000548j -0.000513+0.000488j -0.000557+0.000415j -0.000582+0.000334j -0.000588+0.000248j -0.000573+0.000164j -0.000538+0.000086j -0.000487+0.000019j -0.000422-0.000035j -0.000347-0.000071j -0.000266-0.000088j -0.000185-0.000086j -0.000107-0.000065j -0.000038-0.000027j 0.000018+0.000025j 0.000060+0.000089j 0.000083+0.000160j 0.000089+0.000233j 0.000076+0.000304j 0.000046+0.000369j 0.000001+0.000423j -0.000056+0.000464j -0.000121+0.000489j -0.000190+0.000497j -0.000259+0.000487j -0.000323+0.000461j -0.000379+0.000419j -0.000423+0.000365j -0.000453+0.000301j -0.000467+0.000232j -0.000465+0.000161j -0.000445+0.000093j -0.000411+0.000032j -0.000364-0.000019j -0.000306-0.000058j -0.000242-0.000081j -0.000175-0.000090j -0.000109-0.000082j -0.000048-0.000059j 0.000005-0.000023j 0.000047+0.000024j 0.000075+0.000078j 0.000089+0.000137j 0.000088+0.000196j 0.000072+0.000252j 0.000042+0.000302j 0.000002+0.000341j -0.000048+0.000369j -0.000102+0.000384j -0.000158+0.000384j -0.000213+0.000370j -0.000262+0.000343j -0.000304+0.000304j -0.000335+0.000256j -0.000354+0.000202j -0.000359+0.000145j -0.000351+0.000088j -0.000330+0.000034j -0.000298-0.000012j -0.000255-0.000050j -0.000206-0.000077j -0.000152-0.000091j -0.000098-0.000093j -0.000046-0.000082j 0.000002-0.000059j 0.000041-0.000027j 0.000071+0.000014j 0.000089+0.000059j 0.000095+0.000106j 0.000090+0.000153j 0.000073+0.000196j 0.000045+0.000232j 0.000010+0.000260j -0.000031+0.000278j -0.000075+0.000284j -0.000120+0.000279j -0.000162+0.000263j -0.000199+0.000237j -0.000228+0.000203j -0.000249+0.000162j -0.000259+0.000117j -0.000259+0.000071j -0.000248+0.000026j -0.000227-0.000014j -0.000197-0.000049j -0.000161-0.000076j -0.000120-0.000093j -0.000077-0.000101j -0.000034-0.000098j 0.000006-0.000086j 0.000042-0.000064j 0.000070-0.000036j 0.000090-0.000002j 0.000101+0.000034j 0.000102+0.000071j 0.000093+0.000107j 0.000077+0.000139j 0.000052+0.000165j 0.000022+0.000184j -0.000011+0.000194j -0.000046+0.000196j -0.000081+0.000188j -0.000113+0.000173j -0.000140+0.000150j -0.000161+0.000121j -0.000174+0.000089j -0.000180+0.000054j -0.000177+0.000020j -0.000167-0.000013j -0.000150-0.000041j -0.000127-0.000063j -0.000100-0.000077j -0.000071-0.000084j -0.000044-0.000080j -0.000020-0.000066j -0.000009-0.000035j gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/README.TXT0000644000175000017500000000502611744612271020574 0ustar jcorganjcorgan# 2008-02-07 # # These files have not yet been update to use the new top_block/hier_block2 # interfaces. Until someone does that, this files will no longer run. # The files in this directory implement a fairly simple HF radio that works with the basic rx daughter board on the USRP. Many thanks to the Gnu Radio folks for a great new way to waste large blocks of time in infinitely tweaking a huge number of free parameters. Start the receiver by running the radio.py in this directory. Or from the Python prompt type "from radio import *" and you'll get the prompt back with the receiver running. You can then poke around to see what's going on. There are two spectrum displays. One is the output of the USRP and displays about 300KHz of bandwidth centered at the current tuning freq. The other displays the output spectrum of the demodulator. The demodulator does AM demod using the complex modulus block from gr. It does SSB demod using the frequency translating fir filter as a complex hilbert transformer. The taps for this filter were generated using a program called Scilab and the Scilab program in the file hfir.sci. More details in the associated files. Tune the receiver using the spin buttons under the big frequency display. The agc block is a roll your own. The standard agc in the newer CVS updates seems to work but doesn't seem to have adjustable time constants or provide access to internal signal nodes which are used for the RSSI. The AGC authority (a sort of gain parameter) and the reference level used in the power to dB computagion can be adjusted using the spin buttons. The audio bandwidth can be similarly adjusted from about 50Hz to 10KHz. The GUI layout was produced using wxGlade. The file radio.xml is the GUI specification. It will produce a file called ui.py which is subclassed by classes defined in radio.py. The ui.py is purely generated by wxGlade all app specific code for the GUI is in radio.py. Most of the actual signal processing code is built up in the other included files using the hierarchical block facilities. This organization should make it easier to tweak to your heart's content. Known bugs weakness and other wxPython and wxGlade seem to conspire to insure that the layout can never be exactly what you have in mind. Some of the controls don't behave as one might like. wx spin controls and spin boxes only support integers so it is rather a nuisance to make units come out nice. In the process of development I came up with a reasonable kluge so there is a mixture of approaches. Enjoy. M. Revnell 2006-Jan-06 gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/radio.xml0000644000175000017500000006740311700377701021063 0ustar jcorganjcorgan frame_1 wxVERTICAL wxEXPAND 0 wxHORIZONTAL wxEXPAND 0 wxVERTICAL wxEXPAND|wxADJUST_MINSIZE 0 32 default normal 0 tune_evt wxEXPAND 0 0 2 3 0 wxEXPAND 0 0 1 7 0 wxADJUST_MINSIZE 0 up_e6 down_e6 wxADJUST_MINSIZE 0 up_e5 down_e5 wxADJUST_MINSIZE 0 up_e4 down_e4 wxADJUST_MINSIZE 0 up_e3 down_e3 wxADJUST_MINSIZE 0 up_e2 down_e2 wxADJUST_MINSIZE 0 up_e1 down_e1 wxADJUST_MINSIZE 0 up_e0 down_e0 wxEXPAND 0 wxEXPAND 0 wxADJUST_MINSIZE 0 set_lsb wxADJUST_MINSIZE 0 set_usb wxADJUST_MINSIZE 0 set_am wxEXPAND 0 wxVERTICAL wxEXPAND 0 0 2 4 0 wxADJUST_MINSIZE 0 1 wxADJUST_MINSIZE 0 1 wxADJUST_MINSIZE 0 wxADJUST_MINSIZE 0 1 wxADJUST_MINSIZE 0 event_vol wxADJUST_MINSIZE 0 event_pga wxADJUST_MINSIZE 0 wxADJUST_MINSIZE 0 1 wxEXPAND 0 0 2 4 0 wxADJUST_MINSIZE 0 1 wxADJUST_MINSIZE 0 1 wxADJUST_MINSIZE 0 1 wxADJUST_MINSIZE 0 1 wxEXPAND 0 wxHORIZONTAL wxADJUST_MINSIZE 0 wxADJUST_MINSIZE 0 agc_gain_up agc_gain_down wxEXPAND 0 wxHORIZONTAL wxADJUST_MINSIZE 0 wxADJUST_MINSIZE 0 agc_ref_up agc_ref_down wxEXPAND 0 wxHORIZONTAL wxADJUST_MINSIZE 0 wxADJUST_MINSIZE 0 bw_up bw_down wxADJUST_MINSIZE 0 1 wxEXPAND|wxADJUST_MINSIZE 0 #ff0000 10 315, 10 wxEXPAND 0 wxEXPAND 0 gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/ui.py0000755000175000017500000003171111744612271020230 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # -*- coding: UTF-8 -*- # generated by wxGlade 0.4 on Mon Jan 2 19:02:03 2006 import wx class ui_frame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: ui_frame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.sizer_1_staticbox = wx.StaticBox(self, -1, "sizer_1") self.freq_disp = wx.SpinCtrl(self, -1, "", min=0, max=100) self.spin_e6 = wx.SpinButton(self, -1 ) self.spin_e5 = wx.SpinButton(self, -1 ) self.spin_e4 = wx.SpinButton(self, -1 ) self.spin_e3 = wx.SpinButton(self, -1 ) self.spin_e2 = wx.SpinButton(self, -1 ) self.spin_e1 = wx.SpinButton(self, -1 ) self.spin_e0 = wx.SpinButton(self, -1 ) self.panel_1 = wx.Panel(self, -1) self.panel_2 = wx.Panel(self, -1) self.button_lsb = wx.Button(self, -1, "LSB") self.button_usb = wx.Button(self, -1, "USB") self.button_am = wx.Button(self, -1, "AM") self.label_1 = wx.StaticText(self, -1, "VOLUME") self.label_2 = wx.StaticText(self, -1, "PGA") self.agc_level = wx.TextCtrl(self, -1, "") self.label_6 = wx.StaticText(self, -1, "") self.volume = wx.SpinCtrl(self, -1, "", min=0, max=100) self.pga = wx.SpinCtrl(self, -1, "", min=0, max=100) self.agc_max = wx.TextCtrl(self, -1, "") self.label_7 = wx.StaticText(self, -1, "") self.label_4 = wx.StaticText(self, -1, "AGC AUTHORITY") self.label_5 = wx.StaticText(self, -1, "AGC REF LVL") self.label_3 = wx.StaticText(self, -1, "BANDWIDTH") self.label_8 = wx.StaticText(self, -1, "") self.agc_gain = wx.TextCtrl(self, -1, "") self.agc_gain_s = wx.SpinButton(self, -1 ) self.agc_ref = wx.TextCtrl(self, -1, "") self.agc_ref_s = wx.SpinButton(self, -1 ) self.bandwidth = wx.TextCtrl(self, -1, "") self.bw_spin = wx.SpinButton(self, -1 ) self.label_9 = wx.StaticText(self, -1, "") self.rssi = wx.Gauge(self, -1, 10, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH) self.fe_panel = wx.Panel(self, -1) self.if_panel = wx.Panel(self, -1) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_SPINCTRL, self.tune_evt, self.freq_disp) self.Bind(wx.EVT_SPIN_DOWN, self.down_e6, self.spin_e6) self.Bind(wx.EVT_SPIN_UP, self.up_e6, self.spin_e6) self.Bind(wx.EVT_SPIN_DOWN, self.down_e5, self.spin_e5) self.Bind(wx.EVT_SPIN_UP, self.up_e5, self.spin_e5) self.Bind(wx.EVT_SPIN_DOWN, self.down_e4, self.spin_e4) self.Bind(wx.EVT_SPIN_UP, self.up_e4, self.spin_e4) self.Bind(wx.EVT_SPIN_DOWN, self.down_e3, self.spin_e3) self.Bind(wx.EVT_SPIN_UP, self.up_e3, self.spin_e3) self.Bind(wx.EVT_SPIN_DOWN, self.down_e2, self.spin_e2) self.Bind(wx.EVT_SPIN_UP, self.up_e2, self.spin_e2) self.Bind(wx.EVT_SPIN_DOWN, self.down_e1, self.spin_e1) self.Bind(wx.EVT_SPIN_UP, self.up_e1, self.spin_e1) self.Bind(wx.EVT_SPIN_DOWN, self.down_e0, self.spin_e0) self.Bind(wx.EVT_SPIN_UP, self.up_e0, self.spin_e0) self.Bind(wx.EVT_BUTTON, self.set_lsb, self.button_lsb) self.Bind(wx.EVT_BUTTON, self.set_usb, self.button_usb) self.Bind(wx.EVT_BUTTON, self.set_am, self.button_am) self.Bind(wx.EVT_SPINCTRL, self.event_vol, self.volume) self.Bind(wx.EVT_SPINCTRL, self.event_pga, self.pga) self.Bind(wx.EVT_SPIN_DOWN, self.agc_gain_down, self.agc_gain_s) self.Bind(wx.EVT_SPIN_UP, self.agc_gain_up, self.agc_gain_s) self.Bind(wx.EVT_SPIN_DOWN, self.agc_ref_down, self.agc_ref_s) self.Bind(wx.EVT_SPIN_UP, self.agc_ref_up, self.agc_ref_s) self.Bind(wx.EVT_SPIN_DOWN, self.bw_down, self.bw_spin) self.Bind(wx.EVT_SPIN_UP, self.bw_up, self.bw_spin) # end wxGlade def __set_properties(self): # begin wxGlade: ui_frame.__set_properties self.SetTitle("frame_1") self.freq_disp.SetFont(wx.Font(32, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "")) self.rssi.SetMinSize((315, 10)) self.rssi.SetForegroundColour(wx.Colour(255, 0, 0)) # end wxGlade def __do_layout(self): # begin wxGlade: ui_frame.__do_layout sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_4 = wx.BoxSizer(wx.VERTICAL) grid_sizer_4 = wx.GridSizer(2, 4, 0, 0) sizer_5 = wx.BoxSizer(wx.HORIZONTAL) sizer_7 = wx.BoxSizer(wx.HORIZONTAL) sizer_6 = wx.BoxSizer(wx.HORIZONTAL) grid_sizer_3 = wx.GridSizer(2, 4, 0, 0) sizer_3 = wx.BoxSizer(wx.VERTICAL) grid_sizer_1 = wx.GridSizer(2, 3, 0, 0) grid_sizer_2 = wx.GridSizer(1, 7, 0, 0) sizer_3.Add(self.freq_disp, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e6, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e5, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e4, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e3, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e2, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e1, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_2.Add(self.spin_e0, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(grid_sizer_2, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.panel_2, 1, wx.EXPAND, 0) grid_sizer_1.Add(self.button_lsb, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.button_usb, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_1.Add(self.button_am, 0, wx.ADJUST_MINSIZE, 0) sizer_3.Add(grid_sizer_1, 1, wx.EXPAND, 0) sizer_2.Add(sizer_3, 1, wx.EXPAND, 0) grid_sizer_3.Add(self.label_1, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.label_2, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.agc_level, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.label_6, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.volume, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.pga, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.agc_max, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_3.Add(self.label_7, 0, wx.ADJUST_MINSIZE, 0) sizer_4.Add(grid_sizer_3, 1, wx.EXPAND, 0) grid_sizer_4.Add(self.label_4, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_4.Add(self.label_5, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_4.Add(self.label_3, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_4.Add(self.label_8, 0, wx.ADJUST_MINSIZE, 0) sizer_6.Add(self.agc_gain, 0, wx.ADJUST_MINSIZE, 0) sizer_6.Add(self.agc_gain_s, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_4.Add(sizer_6, 1, wx.EXPAND, 0) sizer_7.Add(self.agc_ref, 0, wx.ADJUST_MINSIZE, 0) sizer_7.Add(self.agc_ref_s, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_4.Add(sizer_7, 1, wx.EXPAND, 0) sizer_5.Add(self.bandwidth, 0, wx.ADJUST_MINSIZE, 0) sizer_5.Add(self.bw_spin, 0, wx.ADJUST_MINSIZE, 0) grid_sizer_4.Add(sizer_5, 1, wx.EXPAND, 0) grid_sizer_4.Add(self.label_9, 0, wx.ADJUST_MINSIZE, 0) sizer_4.Add(grid_sizer_4, 1, wx.EXPAND, 0) sizer_4.Add(self.rssi, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_2.Add(sizer_4, 1, wx.EXPAND, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) sizer_1.Add(self.fe_panel, 1, wx.EXPAND, 0) sizer_1.Add(self.if_panel, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) sizer_1.Fit(self) sizer_1.SetSizeHints(self) self.Layout() # end wxGlade def down_e6(self, event): # wxGlade: ui_frame. print "Event handler `down_e6' not implemented" event.Skip() def up_e6(self, event): # wxGlade: ui_frame. print "Event handler `up_e6' not implemented" event.Skip() def down_e5(self, event): # wxGlade: ui_frame. print "Event handler `down_e5' not implemented" event.Skip() def up_e5(self, event): # wxGlade: ui_frame. print "Event handler `up_e5' not implemented" event.Skip() def down_e4(self, event): # wxGlade: ui_frame. print "Event handler `down_e4' not implemented" event.Skip() def up_e4(self, event): # wxGlade: ui_frame. print "Event handler `up_e4' not implemented" event.Skip() def down_e3(self, event): # wxGlade: ui_frame. print "Event handler `down_e3' not implemented" event.Skip() def up_e3(self, event): # wxGlade: ui_frame. print "Event handler `up_e3' not implemented" event.Skip() def down_e2(self, event): # wxGlade: ui_frame. print "Event handler `down_e2' not implemented" event.Skip() def up_e2(self, event): # wxGlade: ui_frame. print "Event handler `up_e2' not implemented" event.Skip() def down_e1(self, event): # wxGlade: ui_frame. print "Event handler `down_e1' not implemented" event.Skip() def up_e1(self, event): # wxGlade: ui_frame. print "Event handler `up_e1' not implemented" event.Skip() def down_e0(self, event): # wxGlade: ui_frame. print "Event handler `down_e0' not implemented" event.Skip() def up_e0(self, event): # wxGlade: ui_frame. print "Event handler `up_e0' not implemented" event.Skip() def event_vol(self, event): # wxGlade: ui_frame. print "Event handler `event_vol' not implemented" event.Skip() def event_pga(self, event): # wxGlade: ui_frame. print "Event handler `event_pga' not implemented" event.Skip() def set_lsb(self, event): # wxGlade: ui_frame. print "Event handler `set_lsb' not implemented" event.Skip() def set_usb(self, event): # wxGlade: ui_frame. print "Event handler `set_usb' not implemented" event.Skip() def set_am(self, event): # wxGlade: ui_frame. print "Event handler `set_am' not implemented" event.Skip() def set_bw(self, event): # wxGlade: ui_frame. print "Event handler `set_bw' not implemented" event.Skip() def tune_evt(self, event): # wxGlade: ui_frame. print "Event handler `tune_evt' not implemented" event.Skip() def bw_down(self, event): # wxGlade: ui_frame. print "Event handler `bw_down' not implemented" event.Skip() def bw_up(self, event): # wxGlade: ui_frame. print "Event handler `bw_up' not implemented" event.Skip() def agc_gain_down(self, event): # wxGlade: ui_frame. print "Event handler `agc_gain_down' not implemented" event.Skip() def agc_gain_up(self, event): # wxGlade: ui_frame. print "Event handler `agc_gain_up' not implemented" event.Skip() def agc_ref_down(self, event): # wxGlade: ui_frame. print "Event handler `agc_ref_down' not implemented" event.Skip() def agc_ref_up(self, event): # wxGlade: ui_frame. print "Event handler `agc_ref_up' not implemented" event.Skip() # end of class ui_frame class RadioFrame(wx.Frame): def __init__(self, *args, **kwds): # content of this block not found: did you rename this class? pass def __set_properties(self): # content of this block not found: did you rename this class? pass def __do_layout(self): # content of this block not found: did you rename this class? pass # end of class RadioFrame class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # content of this block not found: did you rename this class? pass def __set_properties(self): # content of this block not found: did you rename this class? pass def __do_layout(self): # content of this block not found: did you rename this class? pass # end of class MyFrame gnuradio-3.7.2.1/gr-uhd/apps/hf_radio/output.py0000664000175000017500000000255312207440367021154 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # Audio output with a volume control. # # M. Revnell 2005-Dec from gnuradio import gr, gru from gnuradio import blocks from gnuradio import audio class output( gr.hier_block2 ): def __init__( self, rate, device ): gr.hier_block2.__init__(self, "output", gr.io_signature(1,1,gr.sizeof_float), gr.io_signature(0,0,0)) self.vol = blocks.multiply_const_ff( 0.1 ) self.out = audio.sink( int(rate), device ) self.connect( self, self.vol, self.out ) def set( self, val ): self.vol.set_k( val ) gnuradio-3.7.2.1/gr-uhd/apps/uhd_fft0000775000175000017500000003264212237515112017030 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru from gnuradio import uhd from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys import numpy try: from gnuradio.wxgui import stdgui2, form, slider from gnuradio.wxgui import forms from gnuradio.wxgui import fftsink2, waterfallsink2, scopesink2 import wx except ImportError: sys.stderr.write("Error importing GNU Radio's wxgui. Please make sure gr-wxgui is installed.\n") sys.exit(1) class app_top_block(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv) self.frame = frame self.panel = panel parser = OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args , [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-W", "--waterfall", action="store_true", default=False, help="Enable waterfall display") parser.add_option("-S", "--oscilloscope", action="store_true", default=False, help="Enable oscilloscope display") parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1, help="Set fftsink averaging factor, default=[%default]") parser.add_option ("", "--averaging", action="store_true", default=False, help="Enable fftsink averaging, default=[%default]") parser.add_option("", "--ref-scale", type="eng_float", default=1.0, help="Set dBFS=0dB input value, default=[%default]") parser.add_option("", "--fft-size", type="int", default=1024, help="Set number of FFT bins [default=%default]") parser.add_option("", "--fft-rate", type="int", default=30, help="Set FFT update rate, [default=%default]") parser.add_option("", "--wire-format", type="string", default="sc16", help="Set wire format from USRP [default=%default]") parser.add_option("", "--stream-args", type="string", default="", help="Set additional stream args [default=%default]") parser.add_option("", "--show-async-msg", action="store_true", default=False, help="Show asynchronous message notifications from UHD [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.options = options self.show_debug_info = True self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args(cpu_format='fc32', otw_format=options.wire_format, args=options.stream_args)) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.u.set_samp_rate(options.samp_rate) input_rate = self.u.get_samp_rate() if options.waterfall: self.scope = \ waterfallsink2.waterfall_sink_c (panel, fft_size=1024, sample_rate=input_rate) self.frame.SetMinSize((800, 420)) elif options.oscilloscope: self.scope = scopesink2.scope_sink_c(panel, sample_rate=input_rate) self.frame.SetMinSize((800, 600)) else: self.scope = fftsink2.fft_sink_c (panel, fft_size=options.fft_size, sample_rate=input_rate, ref_scale=options.ref_scale, ref_level=20.0, y_divs = 12, average=options.averaging, avg_alpha=options.avg_alpha, fft_rate=options.fft_rate) def fftsink_callback(x, y): self.set_freq(x) self.scope.set_callback(fftsink_callback) self.frame.SetMinSize((800, 420)) self.connect(self.u, self.scope) self._build_gui(vbox) self._setup_events() # set initial values if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 if options.freq is None: # if no freq was specified, use the mid-point r = self.u.get_freq_range() options.freq = float(r.start()+r.stop())/2 self.set_gain(options.gain) if self.show_debug_info: self.myform['samprate'].set_value(self.u.get_samp_rate()) self.myform['rffreq'].set_value(0) self.myform['dspfreq'].set_value(0) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") # Direct asynchronous notifications to callback function if self.options.show_async_msg: self.async_msgq = gr.msg_queue(0) self.async_src = uhd.amsg_source("", self.async_msgq) self.async_rcv = gru.msgq_runner(self.async_msgq, self.async_callback) def async_callback(self, msg): md = self.async_src.msg_to_async_metadata_t(msg) print "Channel: %i Time: %f Event: %i" % (md.channel, md.time_spec.get_real_secs(), md.event_code) def _set_status_msg(self, msg): self.frame.GetStatusBar().SetStatusText(msg, 0) def _build_gui(self, vbox): def _form_set_freq(kv): return self.set_freq(kv['freq']) vbox.Add(self.scope.win, 10, wx.EXPAND) # add control area at the bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0, 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Center freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0, 0) g = self.u.get_gain_range() # some configurations don't have gain control if g.stop() <= g.start(): glow = 0.0 ghigh = 1.0 else: glow = g.start() ghigh = g.stop() myform['gain'] = form.slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, min=int(glow), max=int(ghigh), callback=self.set_gain) try: mboard_id = self.u.get_usrp_info()["mboard_id"] mboard_serial = self.u.get_usrp_info()["mboard_serial"] if mboard_serial == "": mboard_serial = "no serial" dboard_subdev_name = self.u.get_usrp_info()["rx_subdev_name"] dboard_serial = self.u.get_usrp_info()["rx_serial"] if dboard_serial == "": dboard_serial = "no serial" subdev = self.u.get_subdev_spec() antenna = self.u.get_antenna() if "B200" in mboard_id or "B210" in mboard_id: usrp_config_val = "%s (%s), %s (%s, %s)" % (mboard_id, mboard_serial, dboard_subdev_name, subdev, antenna) else: usrp_config_val = "%s (%s), %s (%s, %s, %s)" % (mboard_id, mboard_serial, dboard_subdev_name, dboard_serial, subdev, antenna) except: usrp_config_val = "Not implemented in this version." uhd_box = forms.static_box_sizer(parent=self.panel, label="UHD (%s)" % (uhd.get_version_string()), orient=wx.HORIZONTAL) usrp_config_form = forms.static_text( parent=self.panel, sizer=uhd_box, value=usrp_config_val, label="USRP", converter=forms.str_converter(), ) vbox.Add(uhd_box, 0, wx.EXPAND) vbox.AddSpacer(5) hbox.Add((5,0), 0, 0) vbox.Add(hbox, 0, wx.EXPAND) self._build_subpanel(vbox) def _build_subpanel(self, vbox_arg): # build a secondary information panel (sometimes hidden) # FIXME figure out how to have this be a subpanel that is always # created, but has its visibility controlled by foo.Show(True/False) def _form_set_samp_rate(kv): return self.set_samp_rate(kv['samprate']) if not(self.show_debug_info): return panel = self.panel vbox = vbox_arg myform = self.myform hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['samprate'] = form.float_field( parent=panel, sizer=hbox, label="Sample Rate", callback=myform.check_input_and_call(_form_set_samp_rate, self._set_status_msg)) hbox.Add((5,0), 1) myform['rffreq'] = form.static_float_field( parent=panel, sizer=hbox, label="RF Freq.") hbox.Add((5,0), 1) myform['dspfreq'] = form.static_float_field( parent=panel, sizer=hbox, label="DSP Freq.") vbox.AddSpacer(5) vbox.Add(hbox, 0, wx.EXPAND) vbox.AddSpacer(5) def set_freq(self, target_freq): """ Set the center frequency we're interested in. @param target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq, 0) if r: self.myform['freq'].set_value(self.u.get_center_freq()) self.myform['rffreq'].set_value(r.actual_rf_freq) self.myform['dspfreq'].set_value(r.actual_dsp_freq) if not self.options.oscilloscope: self.scope.set_baseband_freq(target_freq) return True return False def set_gain(self, gain): if self.myform.has_key('gain'): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain, 0) def set_samp_rate(self, samp_rate): ok = self.u.set_samp_rate(samp_rate) input_rate = self.u.get_samp_rate() self.scope.set_sample_rate(input_rate) if self.show_debug_info: # update displayed values self.myform['samprate'].set_value(self.u.get_samp_rate()) # uhd set_samp_rate never fails; always falls back to closest requested. return True def _setup_events(self): if not self.options.waterfall and not self.options.oscilloscope: self.scope.win.Bind(wx.EVT_LEFT_DCLICK, self.evt_left_dclick) def evt_left_dclick(self, event): (ux, uy) = self.scope.win.GetXY(event) if event.CmdDown(): # Re-center on maximum power points = self.scope.win._points if self.scope.win.peak_hold: if self.scope.win.peak_vals is not None: ind = numpy.argmax(self.scope.win.peak_vals) else: ind = int(points.shape()[0]/2) else: ind = numpy.argmax(points[:,1]) (freq, pwr) = points[ind] target_freq = freq/self.scope.win._scale_factor print ind, freq, pwr self.set_freq(target_freq) else: # Re-center on clicked frequency target_freq = ux/self.scope.win._scale_factor self.set_freq(target_freq) def main (): try: app = stdgui2.stdapp(app_top_block, "UHD FFT", nstatus=1) app.MainLoop() except RuntimeError, e: print e sys.exit(1) if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-uhd/examples/0000755000175000017500000000000011744612271016333 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/examples/grc/0000755000175000017500000000000012207440367017106 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_tx_dpsk.grc0000664000175000017500000005765412207440367022142 0ustar jcorganjcorgan Mon Mar 18 11:11:06 2013 options id uhd_tx_dpsk _enabled True title UHD TX DPSK author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samps_per_sym _enabled True value 4 _coordinate (10, 100) _rotation 0 variable_slider id ampl _enabled True label Amplitude value .1 min 0 max 1 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (7, 299) _rotation 0 parameter id samp_rate _enabled True label Sample Rate value 1e6 type eng_float short_id s _coordinate (334, 15) _rotation 0 parameter id freq _enabled True label Default Frequency value 2.45e9 type eng_float short_id f _coordinate (463, 17) _rotation 0 variable_slider id tun_gain _enabled True label UHD Gain value gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (151, 441) _rotation 0 variable_slider id tun_freq _enabled True label Freq (Hz) value freq min 2.4e9 max 2.5e9 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (7, 441) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 2**8 num_samps 1000 repeat True _coordinate (177, 162) _rotation 0 digital_dxpsk_mod id digital_dxpsk_mod_0 _enabled True type dqpsk samples_per_symbol samps_per_sym excess_bw 0.35 mod_code "gray" verbose False log False _coordinate (366, 162) _rotation 0 parameter id gain _enabled True label Default Gain value 0 type eng_float short_id g _coordinate (619, 15) _rotation 0 parameter id address _enabled True label IP Address value addr=192.168.10.2 type string short_id a _coordinate (177, 14) _rotation 0 uhd_usrp_sink id uhd_usrp_sink_0 _enabled True type fc32 otw stream_args dev_addr address sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq gain0 tun_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (783, 162) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const ampl vlen 1 _coordinate (566, 186) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title Transmit Spectrum samp_rate samp_rate baseband_freq tun_freq y_per_div 10 y_divs 10 ref_level 0 ref_scale 2 fft_size 1024 fft_rate 20 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook freqvar None _coordinate (827, 299) _rotation 0 analog_random_source_x_0 digital_dxpsk_mod_0 0 0 blocks_multiply_const_vxx_0 wxgui_fftsink2_0 0 0 blocks_multiply_const_vxx_0 uhd_usrp_sink_0 0 0 digital_dxpsk_mod_0 blocks_multiply_const_vxx_0 0 0 gnuradio-3.7.2.1/gr-uhd/examples/grc/CMakeLists.txt0000644000175000017500000000200111744612271021637 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES uhd_const_wave.grc uhd_dpsk_mod.grc uhd_fft.grc uhd_rx_dpsk.grc uhd_two_tone_loopback.grc uhd_tx_dpsk.grc uhd_wbfm_receive.grc DESTINATION ${GR_PKG_UHD_EXAMPLES_DIR} COMPONENT "uhd_python" ) gnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_rx_dpsk.grc0000664000175000017500000006731012207440367022126 0ustar jcorganjcorgan Mon Mar 18 11:10:25 2013 options id uhd_rx_dpsk _enabled True title UHD RX DPSK author description window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (12, 9) _rotation 0 variable id samps_per_sym _enabled True value 4 _coordinate (12, 88) _rotation 0 parameter id samp_rate _enabled True label Sample Rate value 1e6 type eng_float short_id s _coordinate (339, 11) _rotation 0 parameter id freq _enabled True label Default Frequency value 2.45e9 type eng_float short_id f _coordinate (466, 11) _rotation 0 parameter id gain _enabled True label Default Gain value 0 type eng_float short_id g _coordinate (624, 14) _rotation 0 parameter id address _enabled True label IP Address value addr=192.168.10.2 type string short_id a _coordinate (186, 10) _rotation 0 parameter id freq_offset _enabled True label Rx Frequency Offset value 0 type eng_float short_id o _coordinate (748, 15) _rotation 0 variable_slider id tun_freq _enabled True label Freq (Hz) value freq min 2.4e9 max 2.5e9 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (12, 436) _rotation 0 blocks_null_sink id blocks_null_sink_0 _enabled True type byte vlen 1 _coordinate (615, 144) _rotation 0 variable_slider id timing_bw _enabled True label Timing Loop BW value 6.28/100.0 min 0 max 1 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (604, 436) _rotation 0 variable_slider id phase_bw _enabled True label Phase Loop BW value 6.28/100.0 min 0 max 1.0 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (461, 436) _rotation 0 wxgui_constellationsink2 id wxgui_constellationsink2_0 _enabled True title Constellation Plot samp_rate samp_rate frame_rate 5 const_size 2048 M 4 theta 0 loop_bw 6.28/100.0 fmax 0.06 mu 0.5 gain_mu 0.005 symbol_rate samp_rate/samps_per_sym omega_limit 0.005 win_size grid_pos notebook _coordinate (931, 313) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq tun_freq y_per_div 10 y_divs 10 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook freqvar None _coordinate (710, 236) _rotation 0 digital_dxpsk_demod id digital_dxpsk_demod_0 _enabled True type dqpsk samples_per_symbol samps_per_sym excess_bw 0.35 freq_bw 6.28/100.0 phase_bw 6.28/100.0 timing_bw 6.28/100.0 mod_code "gray" verbose False log False sync_out False _coordinate (303, 154) _rotation 0 variable_slider id rx_freq_off _enabled True label RX Freq Offset (Hz) value freq_offset min -100e3 max +100e3 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (149, 437) _rotation 0 variable_slider id tun_gain _enabled True label UHD Gain value gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (306, 438) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled True type fc32 otw stream_args dev_addr address sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq+rx_freq_off gain0 tun_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (18, 276) _rotation 0 digital_dxpsk_demod_0 blocks_null_sink_0 0 0 uhd_usrp_source_0 digital_dxpsk_demod_0 0 0 uhd_usrp_source_0 wxgui_constellationsink2_0 0 0 uhd_usrp_source_0 wxgui_fftsink2_0 0 0 gnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_const_wave.grc0000664000175000017500000004707012207440367022625 0ustar jcorganjcorgan Mon Mar 18 11:04:05 2013 options id uhd_const_wave _enabled True title UHD Constant Wave author Example description Tune UHD Device window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 variable_slider id ampl _enabled True label Amplitude value .1 min 0 max 1 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (174, 313) _rotation 0 variable_slider id tun_gain _enabled True label UHD Gain value gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (318, 314) _rotation 0 variable_slider id tun_freq _enabled True label UHD Freq (Hz) value freq min 2.4e9 max 2.5e9 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (24, 315) _rotation 0 parameter id address _enabled True label IP Address value addr=192.168.11.2 type string short_id a _coordinate (188, 12) _rotation 0 parameter id samp_rate _enabled True label Sample Rate value 1e6 type eng_float short_id s _coordinate (342, 14) _rotation 0 parameter id freq _enabled True label Default Frequency value 2.45e9 type eng_float short_id f _coordinate (468, 14) _rotation 0 parameter id gain _enabled True label Default Gain value 0 type eng_float short_id g _coordinate (616, 13) _rotation 0 uhd_usrp_sink id uhd_usrp_sink_0 _enabled True type fc32 otw stream_args dev_addr address sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq gain0 tun_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (308, 169) _rotation 0 analog_const_source_x id analog_const_source_x_0 _enabled True type complex const ampl _coordinate (74, 193) _rotation 0 analog_const_source_x_0 uhd_usrp_sink_0 0 0 gnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_dpsk_mod.grc0000664000175000017500000012316012207440367022250 0ustar jcorganjcorgan Sat Oct 8 14:44:48 2011 options id uhd_dpsk_mod _enabled True title UHD DPSK Modulation author Example description Generate a DPSK signal window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True realtime_scheduling _coordinate (10, 10) _rotation 0 variable id samps_per_sym _enabled True value 8 _coordinate (33, 280) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq tun_freq y_per_div 10 y_divs 10 ref_level 10 ref_scale 2.0 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos notebook _coordinate (697, 248) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type complex title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale 1e-6 ac_couple False xy_mode True num_inputs 1 win_size grid_pos notebook trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (469, 355) _rotation 0 analog_random_source_x id analog_random_source_x_0 _enabled True type byte min 0 max 256 num_samps 1000 repeat True _coordinate (245, 139) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx_0 _enabled True type complex const ampl vlen 1 _coordinate (647, 163) _rotation 0 variable_slider id tun_rx_gain _enabled True label UHD RX Gain value rx_gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (477, 509) _rotation 0 variable_slider id rx_freq_off _enabled True label RX Freq Offset (Hz) value freq_offset min -50e3 max +50e3 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (190, 507) _rotation 0 parameter id rx_gain _enabled True label Default RX Gain value 0 type eng_float short_id _coordinate (1137, 8) _rotation 0 parameter id freq_offset _enabled True label Rx Frequency Offset value 0 type eng_float short_id o _coordinate (824, 8) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled True type complex dev_addr address1 sync clock_rate 0.0 num_mboards 1 ref_source0 sd_spec0 ref_source1 sd_spec1 ref_source2 sd_spec2 ref_source3 sd_spec3 ref_source4 sd_spec4 ref_source5 sd_spec5 ref_source6 sd_spec6 ref_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq+rx_freq_off gain0 tun_rx_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (216, 288) _rotation 0 wxgui_constellationsink2 id wxgui_constellationsink2_0 _enabled True title Constellation Plot samp_rate samp_rate frame_rate 5 const_size 2048 M 4 theta 0 loop_bw 6.28/100.0 fmax 0.06 mu 0.5 gain_mu 0.005 symbol_rate samp_rate/samps_per_sym omega_limit 0.005 win_size grid_pos notebook _coordinate (862, 336) _rotation 0 digital_dxpsk_mod id digital_dxpsk_mod_0 _enabled True type dqpsk samples_per_symbol samps_per_sym excess_bw 0.35 gray_coded True verbose False log False _coordinate (426, 139) _rotation 0 variable_slider id ampl _enabled True label Amplitude value .1 min 0 max 1 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (33, 353) _rotation 0 uhd_usrp_sink id uhd_usrp_sink_0 _enabled True type complex dev_addr address0 sync clock_rate 0.0 num_mboards 1 ref_source0 sd_spec0 ref_source1 sd_spec1 ref_source2 sd_spec2 ref_source3 sd_spec3 ref_source4 sd_spec4 ref_source5 sd_spec5 ref_source6 sd_spec6 ref_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq gain0 tun_rx_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (838, 139) _rotation 0 variable_slider id tun_tx_gain _enabled True label UHD TX Gain value tx_gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (351, 508) _rotation 0 parameter id address0 _enabled True label IP Address, Dev 0 value addr=192.168.10.2 type string short_id _coordinate (197, 11) _rotation 0 parameter id address1 _enabled True label IP Address, Dev 1 value addr=192.168.11.2 type string short_id _coordinate (357, 11) _rotation 0 parameter id samp_rate _enabled True label Sample Rate value 1e6 type eng_float short_id s _coordinate (543, 8) _rotation 0 parameter id freq _enabled True label Default Frequency value 2.45e9 type eng_float short_id f _coordinate (669, 8) _rotation 0 parameter id tx_gain _enabled True label Default TX Gain value 0 type eng_float short_id _coordinate (1003, 8) _rotation 0 variable_slider id tun_freq _enabled True label Freq (Hz) value freq min 2.4e9 max 2.5e9 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (35, 506) _rotation 0 uhd_usrp_source_0 wxgui_fftsink2_0 0 0 uhd_usrp_source_0 wxgui_constellationsink2_0 0 0 uhd_usrp_source_0 wxgui_scopesink2_0 0 0 blocks_multiply_const_vxx_0 uhd_usrp_sink_0 0 0 analog_random_source_x_0 digital_dxpsk_mod_0 0 0 digital_dxpsk_mod_0 blocks_multiply_const_vxx_0 0 0 gnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_two_tone_loopback.grc0000664000175000017500000012504512207440367024164 0ustar jcorganjcorgan Sat Nov 10 14:55:26 2012 options id uhd_two_tone_loopback _enabled True title UHD Loopback - 2 Tone author Example description Loopback test window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 parameter id tx_gain _enabled True label Default TX Gain value 0 type eng_float short_id _coordinate (999, 11) _rotation 0 parameter id freq _enabled True label Default Frequency value 2.45e9 type eng_float short_id f _coordinate (665, 11) _rotation 0 parameter id freq_offset _enabled True label Rx Frequency Offset value 0 type eng_float short_id o _coordinate (820, 11) _rotation 0 parameter id address1 _enabled True label IP Address, Dev 1 value addr=192.168.11.2 type string short_id _coordinate (353, 14) _rotation 0 parameter id address0 _enabled True label IP Address, Dev 0 value addr=192.168.10.2 type string short_id _coordinate (193, 14) _rotation 0 uhd_usrp_sink id uhd_usrp_sink_0 _enabled True type fc32 otw stream_args dev_addr address0 sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq gain0 tun_rx_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (669, 178) _rotation 0 parameter id rx_gain _enabled True label Default RX Gain value 0 type eng_float short_id _coordinate (1139, 12) _rotation 0 variable_slider id tone1 _enabled True label Tone 1 value 50e3 min -samp_rate/2 max samp_rate/2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 0, 0, 1, 4 notebook _coordinate (161, 484) _rotation 0 variable_slider id tone2 _enabled True label Tone 2 value 75e3 min -samp_rate/2 max samp_rate/2 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 0, 4, 1, 4 notebook _coordinate (308, 483) _rotation 0 variable_slider id tun_tx_gain _enabled True label UHD TX Gain value tx_gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (655, 486) _rotation 0 variable_slider id tun_freq _enabled True label Freq (Hz) value freq min 2.4e9 max 2.5e9 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (514, 487) _rotation 0 variable_slider id tun_rx_gain _enabled True label UHD RX Gain value rx_gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (781, 487) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled True type fc32 otw stream_args dev_addr address1 sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq gain0 tun_rx_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (672, 320) _rotation 0 variable_slider id tone_ampl _enabled True label Tone Ampl value 0.15 min 0 max 1 num_steps 100 style wx.SL_VERTICAL converver float_converter grid_pos 1, 0, 2, 1 notebook _coordinate (14, 485) _rotation 0 variable_slider id noise_ampl _enabled True label Noise Ampl value 0.1 min 0 max 1 num_steps 100 style wx.SL_VERTICAL converver float_converter grid_pos 1, 1, 2, 1 notebook _coordinate (15, 335) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq 0 y_per_div 10 y_divs 10 ref_level 0 ref_scale 2.0 fft_size 512*2 fft_rate 15 peak_hold False average False avg_alpha 0 win window.blackmanharris win_size grid_pos 1, 2, 2, 4 notebook freqvar None _coordinate (1114, 264) _rotation 0 parameter id samp_rate _enabled True label Sample Rate value 500e3 type eng_float short_id s _coordinate (539, 11) _rotation 0 analog_sig_source_x id analog_sig_source_x_0 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq tone1 amp tone_ampl offset 0 _coordinate (264, 136) _rotation 0 analog_sig_source_x id analog_sig_source_x_1 _enabled True type complex samp_rate samp_rate waveform analog.GR_COS_WAVE freq tone2 amp tone_ampl offset 0 _coordinate (265, 247) _rotation 0 blocks_add_xx id blocks_add_xx _enabled True type complex num_inputs 3 vlen 1 _coordinate (529, 172) _rotation 0 analog_noise_source_x id analog_noise_source_x_0 _enabled True type complex noise_type analog.GR_GAUSSIAN amp noise_ampl seed -42 _coordinate (288, 359) _rotation 0 blocks_add_xx uhd_usrp_sink_0 0 0 uhd_usrp_source_0 wxgui_fftsink2 0 0 analog_sig_source_x_0 blocks_add_xx 0 0 analog_sig_source_x_1 blocks_add_xx 0 1 analog_noise_source_x_0 blocks_add_xx 0 2 gnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_wbfm_receive.grc0000664000175000017500000006501512207440367023111 0ustar jcorganjcorgan Mon Mar 18 11:13:02 2013 options id uhd_wbfm_receive _enabled True title UHD WBFM Receive author Example description WBFM Receive window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (10, 10) _rotation 0 parameter id gain _enabled True label Default Gain value 0 type eng_float short_id g _coordinate (631, 15) _rotation 0 parameter id freq _enabled True label Default Frequency value 93.3e6 type eng_float short_id f _coordinate (479, 15) _rotation 0 variable_slider id tun_freq _enabled True label Freq (Hz) value freq min 87.9e6 max 108.1e6 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (15, 441) _rotation 0 variable_slider id fine _enabled True label Fine Freq (MHz) value 0 min -.1 max .1 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 0, 2, 1, 2 notebook _coordinate (277, 444) _rotation 0 variable_slider id tun_gain _enabled True label UHD Gain value gain min 0 max 20 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos notebook _coordinate (158, 440) _rotation 0 variable_slider id volume _enabled True label Volume value 1 min 0 max 10 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 1, 0, 1, 4 notebook _coordinate (436, 446) _rotation 0 blocks_multiply_const_vxx id blocks_multiply_const_vxx _enabled True type float const volume vlen 1 _coordinate (836, 161) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled True type fc32 otw stream_args dev_addr address sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 tun_freq+fine gain0 tun_gain ant0 bw0 0 center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (14, 165) _rotation 0 parameter id samp_rate _enabled True label Sample Rate value 400e3 type eng_float short_id s _coordinate (352, 15) _rotation 0 parameter id audio_output _enabled True label Audio Output Device value type string short_id O _coordinate (769, 13) _rotation 0 audio_sink id audio_sink _enabled True samp_rate int(samp_rate/audio_decim) device_name audio_output ok_to_block True num_inputs 1 _coordinate (1023, 161) _rotation 0 low_pass_filter id low_pass_filter_0 _enabled True type fir_filter_ccf decim 1 interp 1 gain 1 samp_rate samp_rate cutoff_freq 115e3 width 30e3 win firdes.WIN_HANN beta 6.76 _coordinate (326, 141) _rotation 0 variable id audio_decim _enabled True value 10 _coordinate (19, 351) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2 _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq (freq+fine) y_per_div 10 y_divs 10 ref_level 0 ref_scale 2.0 fft_size 512 fft_rate 15 peak_hold False average False avg_alpha 0 win None win_size grid_pos 2, 0, 2, 4 notebook freqvar None _coordinate (624, 278) _rotation 0 analog_wfm_rcv id analog_wfm_rcv _enabled True quad_rate samp_rate audio_decimation audio_decim _coordinate (625, 153) _rotation 0 parameter id address _enabled True label IP Address value addr=192.168.10.2 type string short_id a _coordinate (199, 14) _rotation 0 blocks_multiply_const_vxx audio_sink 0 0 analog_wfm_rcv blocks_multiply_const_vxx 0 0 low_pass_filter_0 analog_wfm_rcv 0 0 uhd_usrp_source_0 low_pass_filter_0 0 0 low_pass_filter_0 wxgui_fftsink2 0 0 gnuradio-3.7.2.1/gr-uhd/examples/grc/uhd_fft.grc0000664000175000017500000007135712207440367021241 0ustar jcorganjcorgan Mon Mar 18 15:42:27 2013 options id uhd_fft _enabled True title UHD FFT author Example description UHD FFT Waveform Plotter window_size 1280, 1024 generate_options wx_gui category Custom run_options prompt run True max_nouts 0 realtime_scheduling _coordinate (15, 15) _rotation 0 import id import_0 _enabled True import import numpy _coordinate (15, 121) _rotation 0 parameter id param_samp_rate _enabled True label Sample Rate value 1e6 type eng_float short_id s _coordinate (358, 14) _rotation 0 parameter id param_freq _enabled True label Default Frequency value 2.45e9 type eng_float short_id f _coordinate (508, 14) _rotation 0 parameter id param_gain _enabled True label Default Gain value 0 type eng_float short_id g _coordinate (672, 13) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled True type complex title Scope Plot samp_rate samp_rate v_scale 0 v_offset 0 t_scale 0 ac_couple False xy_mode False num_inputs 1 win_size grid_pos notebook nb0, 2 trig_mode wxgui.TRIG_MODE_AUTO y_axis_label Counts _coordinate (314, 250) _rotation 0 uhd_usrp_source id uhd_usrp_source_0 _enabled True type fc32 otw stream_args dev_addr address sync clock_rate 0.0 num_mboards 1 clock_source0 time_source0 sd_spec0 clock_source1 time_source1 sd_spec1 clock_source2 time_source2 sd_spec2 clock_source3 time_source3 sd_spec3 clock_source4 time_source4 sd_spec4 clock_source5 time_source5 sd_spec5 clock_source6 time_source6 sd_spec6 clock_source7 time_source7 sd_spec7 nchan 1 samp_rate samp_rate center_freq0 freq gain0 gain ant0 ant bw0 samp_rate center_freq1 0 gain1 0 ant1 bw1 0 center_freq2 0 gain2 0 ant2 bw2 0 center_freq3 0 gain3 0 ant3 bw3 0 center_freq4 0 gain4 0 ant4 bw4 0 center_freq5 0 gain5 0 ant5 bw5 0 center_freq6 0 gain6 0 ant6 bw6 0 center_freq7 0 gain7 0 ant7 bw7 0 center_freq8 0 gain8 0 ant8 bw8 0 center_freq9 0 gain9 0 ant9 bw9 0 center_freq10 0 gain10 0 ant10 bw10 0 center_freq11 0 gain11 0 ant11 bw11 0 center_freq12 0 gain12 0 ant12 bw12 0 center_freq13 0 gain13 0 ant13 bw13 0 center_freq14 0 gain14 0 ant14 bw14 0 center_freq15 0 gain15 0 ant15 bw15 0 center_freq16 0 gain16 0 ant16 bw16 0 center_freq17 0 gain17 0 ant17 bw17 0 center_freq18 0 gain18 0 ant18 bw18 0 center_freq19 0 gain19 0 ant19 bw19 0 center_freq20 0 gain20 0 ant20 bw20 0 center_freq21 0 gain21 0 ant21 bw21 0 center_freq22 0 gain22 0 ant22 bw22 0 center_freq23 0 gain23 0 ant23 bw23 0 center_freq24 0 gain24 0 ant24 bw24 0 center_freq25 0 gain25 0 ant25 bw25 0 center_freq26 0 gain26 0 ant26 bw26 0 center_freq27 0 gain27 0 ant27 bw27 0 center_freq28 0 gain28 0 ant28 bw28 0 center_freq29 0 gain29 0 ant29 bw29 0 center_freq30 0 gain30 0 ant30 bw30 0 center_freq31 0 gain31 0 ant31 bw31 0 _coordinate (37, 394) _rotation 0 variable_function_probe id chan0_lo_locked _enabled True value uhd.sensor_value("", False, "") block_id uhd_usrp_source_0 function_name get_sensor function_args "'lo_locked'" poll_rate 10 _coordinate (583, 432) _rotation 0 notebook id nb0 _enabled True style wx.NB_TOP labels ['FFT', 'Waterfall', 'Scope'] grid_pos 0, 0, 1, 8 notebook _coordinate (15, 172) _rotation 0 variable_chooser id ant_xcvr _enabled False label Antenna value "J2" choices ["J2","J1"] labels ["J2","J1"] type radio_buttons style wx.RA_HORIZONTAL grid_pos notebook _coordinate (830, 278) _rotation 0 variable_static_text id lo_locked_probe _enabled True label LO Locked value chan0_lo_locked.to_bool() converver str_converter formatter lambda x: x and "True" or "False" grid_pos 1, 7, 1, 1 notebook _coordinate (583, 314) _rotation 0 variable_chooser id ant _enabled True label Antenna value "RX2" choices ["RX2","TX/RX"] labels ["RX2","TX/RX"] type radio_buttons style wx.RA_HORIZONTAL grid_pos 1, 4, 1, 2 notebook _coordinate (830, 130) _rotation 0 wxgui_fftsink2 id fft _enabled True type complex title FFT Plot samp_rate samp_rate baseband_freq freq y_per_div 10 y_divs 15 ref_level 0 ref_scale 2.0 fft_size 1024 fft_rate 15 peak_hold False average False avg_alpha 0 win None win_size (-1, 400) grid_pos notebook nb0, 0 freqvar None _coordinate (314, 359) _rotation 0 wxgui_waterfallsink2 id wxgui_waterfallsink2_0 _enabled True type complex title Waterfall Plot samp_rate samp_rate baseband_freq 0 dynamic_range 100 ref_level 0 ref_scale 2.0 fft_size 512 fft_rate 15 average False avg_alpha 0 win None win_size (-1, 400) grid_pos notebook nb0, 1 freqvar None _coordinate (313, 573) _rotation 0 variable_text_box id samp_rate _enabled True label Sample Rate value param_samp_rate converver float_converter formatter None grid_pos 1, 0, 1, 3 notebook _coordinate (358, 129) _rotation 0 variable_slider id freq _enabled True label RX Tune Frequency value param_freq min 50e6 max 6e9 num_steps 1000 style wx.SL_HORIZONTAL converver float_converter grid_pos 3, 0, 1, 8 notebook _coordinate (510, 128) _rotation 0 variable_slider id gain _enabled True label RX Gain value param_gain min 0 max 31.5 num_steps 63 style wx.SL_HORIZONTAL converver float_converter grid_pos 2, 0, 1, 8 notebook _coordinate (679, 130) _rotation 0 parameter id address _enabled True label IP Address value addr=192.168.11.2 type string short_id a _coordinate (190, 15) _rotation 0 uhd_usrp_source_0 wxgui_scopesink2_0 0 0 uhd_usrp_source_0 wxgui_waterfallsink2_0 0 0 uhd_usrp_source_0 fft 0 0 gnuradio-3.7.2.1/gr-uhd/examples/python/0000755000175000017500000000000012207440367017654 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/examples/python/CMakeLists.txt0000644000175000017500000000236311744612271022420 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL( PROGRAMS fm_tx4.py fm_tx_2_daughterboards.py max_power.py usrp_am_mw_rcv.py usrp_nbfm_ptt.py usrp_nbfm_rcv.py usrp_spectrum_sense.py usrp_tv_rcv_nogui.py usrp_tv_rcv.py usrp_wfm_rcv2_nogui.py usrp_wfm_rcv_fmdet.py usrp_wfm_rcv_nogui.py usrp_wfm_rcv_pll.py usrp_wfm_rcv.py usrp_wfm_rcv_sca.py usrp_wxapt_rcv.py DESTINATION ${GR_PKG_UHD_EXAMPLES_DIR} COMPONENT "uhd_python" ) gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_tv_rcv.py0000775000175000017500000004256312207440367022621 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Realtime capture and display of analog Tv stations. Can also use a file as source or sink When you use an output file you can show the results frame-by-frame using ImageMagick When you want to use the realtime sdl display window you must first install gr-video-sdl. When you use a file source, instead of the usrp, make sure you capture interleaved shorts. (Use usrp_rx_file.py, or use usrp_rx_cfile.py --output-shorts if you have a recent enough usrp_rx_cfile.py) There is no synchronisation yet. The sync blocks are in development but not yet in cvs. """ from gnuradio import gr try: from gnuradio import video_sdl except: print "FYI: gr-video-sdl is not installed" print "realtime SDL video output window will not be available" from gnuradio import uhd from gnuradio import analog from gnuradio import blocks from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form from optparse import OptionParser import sys import wx class tv_rx_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) usage="%prog: [options] [input_filename]. \n If you don't specify an input filename the usrp will be used as source\n " \ "Make sure your input capture file containes interleaved shorts not complex floats" parser=OptionParser(option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate") parser.add_option("-f", "--freq", type="eng_float", default=519.25e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-c", "--contrast", type="eng_float", default=1.0, help="set contrast (default is 1.0)") parser.add_option("-b", "--brightness", type="eng_float", default=0.0, help="set brightness (default is 0)") parser.add_option("-p", "--pal", action="store_true", default=False, help="PAL video format (this is the default)") parser.add_option("-n", "--ntsc", action="store_true", default=False, help="NTSC video format") parser.add_option("-o", "--out-filename", type="string", default="sdl", help="For example out_raw_uchar.gray. If you don't specify an output filename you will get a video_sink_sdl realtime output window. You then need to have gr-video-sdl installed)") parser.add_option("-r", "--repeat", action="store_false", default=True, help="repeat file in a loop") parser.add_option("", "--freq-min", type="eng_float", default=50.25e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=900.25e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if not ((len(args) == 1) or (len(args) == 0)): parser.print_help() sys.exit(1) if len(args) == 1: filename = args[0] else: filename = None self.frame = frame self.panel = panel self.contrast = options.contrast self.brightness = options.brightness self.state = "FREQ" self.freq = 0 self.tv_freq_min = options.freq_min self.tv_freq_max = options.freq_max # build graph self.u=None if not (options.out_filename=="sdl"): options.repeat=False usrp_rate = options.samp_rate if not ((filename is None) or (filename=="usrp")): # file is data source self.filesource = blocks.file_source(gr.sizeof_short,filename,options.repeat) self.istoc = blocks.interleaved_short_to_complex() self.connect(self.filesource,self.istoc) self.src=self.istoc options.gain=0.0 self.gain=0.0 else: # use a UHD device self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 self.src=self.u self.gain = options.gain f2uc = blocks.float_to_uchar() # sdl window as final sink if not (options.pal or options.ntsc): options.pal=True #set default to PAL if options.pal: lines_per_frame=625.0 frames_per_sec=25.0 show_width=768 elif options.ntsc: lines_per_frame=525.0 frames_per_sec=29.97002997 show_width=640 width=int(usrp_rate/(lines_per_frame*frames_per_sec)) height=int(lines_per_frame) if (options.out_filename=="sdl"): #Here comes the tv screen, you have to build and install #gr-video-sdl for this (subproject of gnuradio, only in cvs #for now) try: video_sink = video_sdl.sink_uc ( frames_per_sec, width, height, 0, show_width, height) except: print "gr-video-sdl is not installed" print "realtime \"sdl\" video output window is not available" raise SystemExit, 1 self.dst=video_sink else: print "You can use the imagemagick display tool to show the resulting imagesequence" print "use the following line to show the demodulated TV-signal:" print "display -depth 8 -size " +str(width)+ "x" + str(height) \ + " gray:" + options.out_filename print "(Use the spacebar to advance to next frames)" options.repeat=False file_sink = blocks.file_sink(gr.sizeof_char, options.out_filename) self.dst =file_sink self.agc = analog.agc_cc(1e-7,1.0,1.0) #1e-7 self.am_demod = blocks.complex_to_mag () self.set_blacklevel = blocks.add_const_ff(0.0) self.invert_and_scale = blocks.multiply_const_ff (0.0) #-self.contrast *128.0*255.0/(200.0) # now wire it all together #sample_rate=options.width*options.height*options.framerate process_type='do_no_sync' if process_type=='do_no_sync': self.connect (self.src, self.agc,self.am_demod, self.invert_and_scale, self.set_blacklevel, f2uc,self.dst) elif process_type=='do_tv_sync_adv': #defaults: gr.tv_sync_adv (double sampling_freq, unsigned #int tv_format,bool output_active_video_only=false, bool #do_invert=false, double wanted_black_level=0.0, double #wanted_white_level=255.0, double avg_alpha=0.1, double #initial_gain=1.0, double initial_offset=0.0,bool #debug=false) #note, this block is not yet in cvs self.tv_sync_adv=gr.tv_sync_adv(usrp_rate, 0, False, False, 0.0, 255.0, 0.01, 1.0, 0.0, False) self.connect (self.src, self.am_demod, self.invert_and_scale, self.tv_sync_adv, s2f, f2uc, self.dst) elif process_type=='do_nullsink': #self.connect (self.src, self.am_demod,self.invert_and_scale,f2uc,video_sink) c2r=blocks.complex_to_real() nullsink=blocks.null_sink(gr.sizeof_float) self.connect (self.src, c2r,nullsink) #video_sink) elif process_type=='do_tv_sync_corr': frame_size=width*height #int(usrp_rate/25.0) nframes=10# 32 search_window=20*nframes debug=False video_alpha=0.3 #0.1 corr_alpha=0.3 #Note: this block is not yet in cvs tv_corr=gr.tv_correlator_ff(frame_size,nframes, search_window, video_alpha, corr_alpha,debug) shift = blocks.add_const_ff(-0.7) self.connect (self.src, self.agc, self.am_demod, tv_corr, self.invert_and_scale, self.set_blacklevel, f2uc, self.dst) else: # process_type=='do_test_image': src_vertical_bars = analog.sig_source_f(usrp_rate, analog.GR_SIN_WAVE, 10.0 *usrp_rate/320, 255,128) self.connect(src_vertical_bars, f2uc, self.dst) self._build_gui(vbox, usrp_rate, usrp_rate, usrp_rate) frange = self.u.get_freq_range() if(frange.start() > self.tv_freq_max or frange.stop() < self.tv_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.tv_freq_min or options.freq > self.tv_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_contrast(self.contrast) self.set_brightness(options.brightness) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) if 0: self.src_fft = fftsink.fft_sink_c (self, self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate) self.connect (self.src, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 0: post_demod_fft = fftsink.fft_sink_f (self, self.panel, title="Post Demod", fft_size=512, sample_rate=demod_rate, y_per_div=10, ref_level=-40) self.connect (self.am_demod, post_demod_fft) vbox.Add (post_demod_fft.win, 4, wx.EXPAND) if 0: post_filt_fft = fftsink.fft_sink_f (self, self.panel, title="Post Filter", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-40) self.connect (self.set_blacklevel, post_filt) vbox.Add (fft_win4, 4, wx.EXPAND) # control area form at bottom self.myform = myform = form.form() if not (self.u is None): hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(self.tv_freq_min, self.tv_freq_max, 0.25e6), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['contrast'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Contrast", weight=3, range=(-2.0, 2.0, 0.1), callback=self.set_contrast) hbox.Add((5,0), 1) myform['brightness'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Brightness", weight=3, range=(-255.0, 255.0, 1.0), callback=self.set_brightness) hbox.Add((5,0), 0) if not (self.u is None): g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 elif (self.state == "CONTRAST"): step = 0.1 if self.rot >= 3: self.set_contrast(self.contrast + step) self.rot -= 3 elif self.rot <=-3: self.set_contrast(self.contrast - step) self.rot += 3 else: step = 1 if self.rot >= 3: self.set_brightness(self.brightness + step) self.rot -= 3 elif self.rot <=-3: self.set_brightness(self.brightness - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "CONTRAST" elif self.state == "CONTRAST": self.state = "BRIGHTNESS" else: self.state = "FREQ" self.update_status_bar () def set_contrast (self, contrast): self.contrast = contrast self.invert_and_scale.set_k(-self.contrast *128.0*255.0/(200.0)) self.myform['contrast'].set_value(self.contrast) self.update_status_bar () def set_brightness (self, brightness): self.brightness = brightness self.set_blacklevel.set_k(self.brightness +255.0) self.myform['brightness'].set_value(self.brightness) self.update_status_bar () def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool Tuning is a two step process. First we ask the front-end to tune as close to the desired frequency as it can. Then we use the result of that operation and our target_frequency to determine the value for the digital down converter. """ if not (self.u is None): r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): if not (self.u is None): self.gain=gain self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) self.update_status_bar() def update_status_bar (self): msg = "Setting:%s Contrast:%r Brightness:%r Gain: %r" % \ (self.state, self.contrast,self.brightness,self.gain) self._set_status_msg(msg, 1) #self.src_fft.set_baseband_freq(self.freq) if __name__ == '__main__': app = stdgui2.stdapp (tv_rx_block, "USRP TV RX black-and-white") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wfm_rcv2_nogui.py0000775000175000017500000001412312207440367024233 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio.eng_option import eng_option from optparse import OptionParser import sys import math class wfm_rx_block (gr.top_block): def __init__(self): gr.top_block.__init__(self) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default="A:0 A:0", help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--f1", type="eng_float", default=100.7e6, help="set 1st station frequency to FREQ", metavar="FREQ") parser.add_option("", "--f2", type="eng_float", default=102.5e6, help="set 2nd station freq to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) if abs(options.f1 - options.f2) > 5.5e6: print "Sorry, two stations must be within 5.5MHz of each other" raise SystemExit f = (options.f1, options.f2) self.vol = .1 self.state = "FREQ" self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph stream_args = uhd.stream_args('fc32', channels=range(2)) self.u = uhd.usrp_source(device_addr=options.args, stream_args=stream_args) # Set front end channel mapping self.u.set_subdev_spec(options.spec) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 32e3 audio_decim = int(demod_rate / audio_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() # Make sure dboard can suppor the required frequencies frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) # sound card as final sink self.audio_sink = audio.sink(int(audio_rate), options.audio_output) # taps for channel filter nfilts = 32 chan_coeffs = filter.optfir.low_pass(nfilts, # gain nfilts*usrp_rate, # sampling rate 80e3, # passband cutoff 115e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation rrate = usrp_rate / dev_rate # set front end PLL to middle frequency mid_freq = (f[0] + f[1]) / 2.0 if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 for n in range(2): chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) guts = analog.wfm_rcv(demod_rate, audio_decim) volume_control = blocks.multiply_const_ff(self.vol) #self.connect((self.di, n), chan_filt) self.connect((self.u, n), chan_filt) self.connect(chan_filt, guts, volume_control) self.connect(volume_control, (self.audio_sink, n)) # Test the the requested frequencies are in range if(f[n] < self.fm_freq_min or f[n] > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # Tune each channel by setting the RF freq to mid_freq and the # DDC freq to f[n]. tr = uhd.tune_request(f[n], rf_freq=mid_freq, rf_freq_policy=uhd.tune_request.POLICY_MANUAL) self.u.set_center_freq(tr, n) # Set gain for each channel self.set_gain(options.gain, n) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, n) def set_vol (self, vol): self.vol = vol self.volume_control.set_k(self.vol) def set_gain(self, gain, n): self.u.set_gain(gain, n) if __name__ == '__main__': tb = wfm_rx_block() try: tb.run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_am_mw_rcv.py0000775000175000017500000003002612207440367023257 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, eng_notation from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio import audio from gnuradio import uhd from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form from optparse import OptionParser import sys import math import wx class wfm_rx_block (stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=1008.0e3, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-I", "--use-if-freq", action="store_true", default=False, help="use intermediate freq (compensates DC problems in quadrature boards)" ) parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is maximum)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.frame = frame self.panel = panel self.use_IF=options.use_if_freq if self.use_IF: self.IF_freq=64000.0 else: self.IF_freq=0.0 self.vol = 0 self.state = "FREQ" self.freq = 0 # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 256e3 demod_rate = 64e3 audio_rate = 32e3 chanfilt_decim = int(usrp_rate // demod_rate) audio_decim = int(demod_rate // audio_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() # Resample signal to exactly self.usrp_rate # FIXME: make one of the follow-on filters an arb resampler rrate = usrp_rate / dev_rate self.resamp = filter.pfb.arb_resampler_ccf(rrate) chan_filt_coeffs = filter.firdes.low_pass_2(1, # gain usrp_rate, # sampling rate 8e3, # passband cutoff 4e3, # transition bw 60) # stopband attenuation if self.use_IF: # Turn If to baseband and filter. self.chan_filt = filter.freq_xlating_fir_filter_ccf(chanfilt_decim, chan_filt_coeffs, self.IF_freq, usrp_rate) else: self.chan_filt = filter.fir_filter_ccf(chanfilt_decim, chan_filt_coeffs) self.agc = analog.agc_cc(0.1, 1, 1, 100000) self.am_demod = blocks.complex_to_mag() self.volume_control = blocks.multiply_const_ff(self.vol) audio_filt_coeffs = filter.firdes.low_pass_2(1, # gain demod_rate, # sampling rate 8e3, # passband cutoff 2e3, # transition bw 60) # stopband attenuation self.audio_filt = filter.fir_filter_fff(audio_decim, audio_filt_coeffs) # sound card as final sink self.audio_sink = audio.sink(int (audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect (self.u, self.resamp, self.chan_filt, self.agc, self.am_demod, self.audio_filt, self.volume_control, self.audio_sink) self._build_gui(vbox, usrp_rate, demod_rate, audio_rate) if options.gain is None: g = self.u.get_gain_range() # if no gain was specified, use the mid gain options.gain = (g.start() + g.stop())/2.0 if options.volume is None: v = self.volume_range() options.volume = float(v[0]*3+v[1])/4.0 if abs(options.freq) < 1e3: options.freq *= 1e3 # set initial values self.set_gain(options.gain) self.set_vol(options.volume) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) if 0: self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate, ref_scale=32768.0, ref_level=0.0, y_divs=12) self.connect (self.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 0: self.post_filt_fft = fftsink2.fft_sink_c(self.panel, title="Post Channel filter", fft_size=512, sample_rate=demod_rate) self.connect (self.chan_filt, self.post_filt_fft) vbox.Add (self.post_filt_fft.win, 4, wx.EXPAND) if 0: post_demod_fft = fftsink2.fft_sink_f(self.panel, title="Post Demod", fft_size=1024, sample_rate=demod_rate, y_per_div=10, ref_level=0) self.connect (self.am_demod, post_demod_fft) vbox.Add (post_demod_fft.win, 4, wx.EXPAND) if 1: audio_fft = fftsink2.fft_sink_f(self.panel, title="Audio", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=20) self.connect (self.audio_filt, audio_fft) vbox.Add (audio_fft.win, 4, wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(520.0e3, 1611.0e3, 1.0e3), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_vol) hbox.Add((5,0), 1) g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_vol(self.vol + step) self.rot -= 3 elif self.rot <=-3: self.set_vol(self.vol - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control.set_k(10**(self.vol/10)) self.myform['volume'].set_value(self.vol) self.update_status_bar () def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq + self.IF_freq, 0) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.vol, self.state) self._set_status_msg(msg, 1) try: self.src_fft.set_baseband_freq(self.freq) except: None def volume_range(self): return (-40.0, 0.0, 0.5) if __name__ == '__main__': app = stdgui2.stdapp (wfm_rx_block, "USRP Broadcast AM MW RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wfm_rcv_fmdet.py0000775000175000017500000003365512207440367024142 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form, scopesink2 from optparse import OptionParser import sys import wx class wfm_rx_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=100.1e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-s", "--squelch", type="eng_float", default=0, help="set squelch level (default is 0)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.frame = frame self.panel = panel self.vol = 0 self.state = "FREQ" self.freq = 0 self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 48e3 audio_decim = 10 self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = filter.firdes.low_pass_2(10*nfilts, # gain nfilts*usrp_rate, # sampling rate 90e3, # passband cutoff 30e3, # transition bw 70) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) self.guts = analog.wfm_rcv_fmdet (demod_rate, audio_decim) chan_rate = audio_rate / (demod_rate/audio_decim) self.rchan_filt = filter.pfb.arb_resampler_fff(chan_rate) self.lchan_filt = filter.pfb.arb_resampler_fff(chan_rate) # FIXME rework {add,multiply}_const_* to handle multiple streams self.volume_control_l = blocks.multiply_const_ff(self.vol) self.volume_control_r = blocks.multiply_const_ff(self.vol) # sound card as final sink self.audio_sink = audio.sink(int (audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect(self.u, self.chan_filt, self.guts) self.connect((self.guts, 0), self.lchan_filt, self.volume_control_l, (self.audio_sink,0)) self.connect((self.guts, 1), self.rchan_filt, self.volume_control_r, (self.audio_sink,1)) try: self.guts.stereo_carrier_pll_recovery.squelch_enable(True) except: print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" self._build_gui(vbox, usrp_rate, demod_rate, audio_rate) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 if abs(options.freq) < 1e6: options.freq *= 1e6 frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.fm_freq_min or options.freq > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_vol(options.volume) try: self.guts.stereo_carrier_pll_recovery.set_lock_threshold(options.squelch) except: print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) if 1: self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate, ref_scale=32768.0, ref_level=0, y_divs=12) self.connect (self.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 1: post_fm_demod_fft = fftsink2.fft_sink_f(self.panel, title="Post FM Demod", fft_size=512, sample_rate=demod_rate, y_per_div=10, ref_level=0) self.connect (self.guts.fm_demod, post_fm_demod_fft) vbox.Add (post_fm_demod_fft.win, 4, wx.EXPAND) if 0: post_stereo_carrier_generator_fft = fftsink2.fft_sink_c (self.panel, title="Post Stereo_carrier_generator", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=0) self.connect (self.guts.stereo_carrier_generator, post_stereo_carrier_generator_fft) vbox.Add (post_stereo_carrier_generator_fft.win, 4, wx.EXPAND) if 0: post_deemphasis_left = fftsink2.fft_sink_f (self.panel, title="Post_Deemphasis_Left", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=0) self.connect (self.guts.deemph_Left, post_deemphasis_left) vbox.Add (post_deemphasis_left.win, 4, wx.EXPAND) if 0: post_deemphasis_right = fftsink2.fft_sink_f(self.panel, title="Post_Deemphasis_Right", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-20) self.connect (self.guts.deemph_Left, post_deemphasis_right) vbox.Add (post_deemphasis_right.win, 4, wx.EXPAND) if 0: LmR_fft = fftsink2.fft_sink_f(self.panel, title="LmR", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-20) self.connect (self.guts.LmR_real,LmR_fft) vbox.Add (LmR_fft.win, 4, wx.EXPAND) if 0: self.scope = scopesink2.scope_sink_f(self.panel, sample_rate=demod_rate) self.connect (self.guts.fm_demod,self.scope) vbox.Add (self.scope.win,4,wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(self.fm_freq_min, self.fm_freq_max, 0.1e6), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_vol) hbox.Add((5,0), 1) g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) myform['sqlch_thrsh'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Stereo Squelch Threshold", weight=3, range=(0.0,1.0,0.01), callback=self.set_squelch) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_vol(self.vol + step) self.rot -= 3 elif self.rot <=-3: self.set_vol(self.vol - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control_l.set_k(10**(self.vol/10)) self.volume_control_r.set_k(10**(self.vol/10)) self.myform['volume'].set_value(self.vol) self.update_status_bar () def set_squelch(self,squelch_threshold): try: self.guts.stereo_carrier_pll_recovery.set_lock_threshold(squelch_threshold); except: print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.vol, self.state) self._set_status_msg(msg, 1) self.src_fft.set_baseband_freq(self.freq) def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': app = stdgui2.stdapp (wfm_rx_block, "USRP WFM RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wfm_rcv.py0000775000175000017500000002545512207440367022762 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2009,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form from optparse import OptionParser import sys import wx class wfm_rx_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=100.1e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.frame = frame self.panel = panel self.vol = 0 self.state = "FREQ" self.freq = 0 self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 32e3 audio_decim = int(demod_rate / audio_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = filter.optfir.low_pass(nfilts, # gain nfilts*usrp_rate, # sampling rate 80e3, # passband cutoff 115e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) self.guts = analog.wfm_rcv(demod_rate, audio_decim) self.volume_control = blocks.multiply_const_ff(self.vol) # sound card as final sink self.audio_sink = audio.sink(int (audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect(self.u, self.chan_filt, self.guts, self.volume_control, self.audio_sink) self._build_gui(vbox, usrp_rate, demod_rate, audio_rate) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.fm_freq_min or options.freq > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_vol(options.volume) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) if 1: self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate, ref_scale=32768.0, ref_level=0, y_divs=12) self.connect (self.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 1: post_filt_fft = fftsink2.fft_sink_f(self.panel, title="Post Demod", fft_size=1024, sample_rate=usrp_rate, y_per_div=10, ref_level=0) self.connect (self.guts.fm_demod, post_filt_fft) vbox.Add (post_filt_fft.win, 4, wx.EXPAND) if 0: post_deemph_fft = fftsink2.fft_sink_f(self.panel, title="Post Deemph", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-20) self.connect (self.guts.deemph, post_deemph_fft) vbox.Add (post_deemph_fft.win, 4, wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(self.fm_freq_min, self.fm_freq_max, 0.1e6), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_vol) hbox.Add((5,0), 1) g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_vol(self.vol + step) self.rot -= 3 elif self.rot <=-3: self.set_vol(self.vol - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control.set_k(10**(self.vol/10)) self.myform['volume'].set_value(self.vol) self.update_status_bar () def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.vol, self.state) self._set_status_msg(msg, 1) self.src_fft.set_baseband_freq(self.freq) def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': app = stdgui2.stdapp (wfm_rx_block, "USRP WFM RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wfm_rcv_pll.py0000775000175000017500000003361112207440367023622 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio import eng_notation from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form, scopesink2 from optparse import OptionParser import sys import wx class wfm_rx_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=100.1e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-s", "--squelch", type="eng_float", default=0, help="set squelch level (default is 0)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.frame = frame self.panel = panel self.vol = 0 self.state = "FREQ" self.freq = 0 self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 48e3 audio_decim = 10 self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = filter.firdes.low_pass_2(nfilts, # gain nfilts*usrp_rate, # sampling rate 90e3, # passband cutoff 30e3, # stopband cutoff 70) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) self.guts = analog.wfm_rcv_pll(demod_rate, audio_decim) chan_rate = audio_rate / (demod_rate/audio_decim) self.rchan_filt = filter.pfb.arb_resampler_fff(chan_rate) self.lchan_filt = filter.pfb.arb_resampler_fff(chan_rate) # FIXME rework {add,multiply}_const_* to handle multiple streams self.volume_control_l = blocks.multiply_const_ff(self.vol) self.volume_control_r = blocks.multiply_const_ff(self.vol) # sound card as final sink self.audio_sink = audio.sink (int (audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect (self.u, self.chan_filt, self.guts) self.connect((self.guts, 0), self.lchan_filt, self.volume_control_l, (self.audio_sink,0)) self.connect((self.guts, 1), self.rchan_filt, self.volume_control_r, (self.audio_sink,1)) try: self.guts.stereo_carrier_pll_recovery.squelch_enable(True) except: print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" self._build_gui(vbox, usrp_rate, demod_rate, audio_rate) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.fm_freq_min or options.freq > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_vol(options.volume) try: self.guts.stereo_carrier_pll_recovery.set_lock_threshold(options.squelch) except: print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) if 1: self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate, ref_scale=32768.0, ref_level=0, y_divs=12) self.connect (self.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 1: post_fm_demod_fft = fftsink2.fft_sink_f(self.panel, title="Post FM Demod", fft_size=512, sample_rate=demod_rate, y_per_div=10, ref_level=0) self.connect (self.guts.fm_demod, post_fm_demod_fft) vbox.Add (post_fm_demod_fft.win, 4, wx.EXPAND) if 0: post_stereo_carrier_generator_fft = fftsink2.fft_sink_c (self.panel, title="Post Stereo_carrier_generator", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=0) self.connect (self.guts.stereo_carrier_generator, post_stereo_carrier_generator_fft) vbox.Add (post_stereo_carrier_generator_fft.win, 4, wx.EXPAND) if 0: post_deemphasis_left = fftsink2.fft_sink_f (self.panel, title="Post_Deemphasis_Left", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=0) self.connect (self.guts.deemph_Left, post_deemphasis_left) vbox.Add (post_deemphasis_left.win, 4, wx.EXPAND) if 0: post_deemphasis_right = fftsink2.fft_sink_f(self.panel, title="Post_Deemphasis_Right", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-20) self.connect (self.guts.deemph_Left, post_deemphasis_right) vbox.Add (post_deemphasis_right.win, 4, wx.EXPAND) if 0: LmR_fft = fftsink2.fft_sink_f(self.panel, title="LmR", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-20) self.connect (self.guts.LmR_real,LmR_fft) vbox.Add (LmR_fft.win, 4, wx.EXPAND) if 0: self.scope = scopesink2.scope_sink_f(self.panel, sample_rate=demod_rate) self.connect (self.guts.fm_demod,self.scope) vbox.Add (self.scope.win,4,wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(self.fm_freq_min, self.fm_freq_max, 0.1e6), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_vol) hbox.Add((5,0), 1) g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) myform['sqlch_thrsh'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Stereo Squelch Threshold", weight=3, range=(0.0,1.0,0.01), callback=self.set_squelch) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_vol(self.vol + step) self.rot -= 3 elif self.rot <=-3: self.set_vol(self.vol - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control_l.set_k(10**(self.vol/10)) self.volume_control_r.set_k(10**(self.vol/10)) self.myform['volume'].set_value(self.vol) self.update_status_bar () def set_squelch(self,squelch_threshold): try: self.guts.stereo_carrier_pll_recovery.set_lock_threshold(squelch_threshold); except: print "FYI: This implementation of the stereo_carrier_pll_recovery has no squelch implementation yet" def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.vol, self.state) self._set_status_msg(msg, 1) self.src_fft.set_baseband_freq(self.freq) def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': app = stdgui2.stdapp (wfm_rx_block, "USRP WFM RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/fm_tx_2_daughterboards.py0000775000175000017500000001703212207440367024652 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Transmit 2 signals, one out each daughterboard. Outputs SSB (USB) signals on side A and side B at frequencies specified on command line. Side A is 600 Hz tone. Side B is 350 + 440 Hz tones. """ from gnuradio import gr, uhd from gnuradio import filter from gnuradio import analog from gnuradio import blocks from gnuradio.eng_notation import num_to_str, str_to_num from gnuradio.eng_option import eng_option from optparse import OptionParser import math import sys class example_signal_0(gr.hier_block2): """ Sinusoid at 600 Hz. """ def __init__(self, sample_rate): gr.hier_block2.__init__(self, "example_signal_0", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature src = analog.sig_source_c(sample_rate, # sample rate analog.GR_SIN_WAVE, # waveform type 600, # frequency 1.0, # amplitude 0) # DC Offset self.connect(src, self) class example_signal_1(gr.hier_block2): """ North American dial tone (350 + 440 Hz). """ def __init__(self, sample_rate): gr.hier_block2.__init__(self, "example_signal_1", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature src0 = analog.sig_source_c(sample_rate, # sample rate analog.GR_SIN_WAVE, # waveform type 350, # frequency 1.0, # amplitude 0) # DC Offset src1 = analog.sig_source_c(sample_rate, # sample rate analog.GR_SIN_WAVE, # waveform type 440, # frequency 1.0, # amplitude 0) # DC Offset sum = blocks.add_cc() self.connect(src0, (sum, 0)) self.connect(src1, (sum, 1)) self.connect(sum, self) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) usage = "%prog: [options] tx-freq0 tx-freq1" parser = OptionParser (option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=320e3, help="set sample rate [default=%default]") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") (options, args) = parser.parse_args () if len(args) != 2: parser.print_help() raise SystemExit else: freq0 = str_to_num(args[0]) freq1 = str_to_num(args[1]) # ---------------------------------------------------------------- # Set up USRP to transmit on both daughterboards d = uhd.find_devices(uhd.device_addr(options.args)) uhd_type = d[0].get('type') stream_args = uhd.stream_args('fc32', channels=range(2)) self.u = uhd.usrp_sink(device_addr=options.args, stream_args=stream_args) # Set up USRP system based on type if(uhd_type == "usrp"): self.u.set_subdev_spec("A:0 B:0") tr0 = uhd.tune_request(freq0) tr1 = uhd.tune_request(freq1) else: if abs(freq0 - freq1) > 5.5e6: sys.stderr.write("\nError: When not using two separate d'boards, frequencies must bewithin 5.5MHz of each other.\n") raise SystemExit self.u.set_subdev_spec("A:0 A:0") mid_freq = (freq0 + freq1)/2.0 tr0 = uhd.tune_request(freq0, rf_freq=mid_freq, rf_freq_policy=uhd.tune_request.POLICY_MANUAL) tr1 = uhd.tune_request(freq1, rf_freq=mid_freq, rf_freq_policy=uhd.tune_request.POLICY_MANUAL) # Use the tune requests to tune each channel self.set_freq(tr0, 0) self.set_freq(tr1, 1) self.usrp_rate = options.samp_rate self.u.set_samp_rate(self.usrp_rate) dev_rate = self.u.get_samp_rate() # ---------------------------------------------------------------- # build two signal sources, interleave them, amplify and # connect them to usrp sig0 = example_signal_0(self.usrp_rate) sig1 = example_signal_1(self.usrp_rate) intl = blocks.interleave(gr.sizeof_gr_complex) self.connect(sig0, (intl, 0)) self.connect(sig1, (intl, 1)) # Correct for any difference in requested and actual rates rrate = self.usrp_rate / dev_rate resamp = filter.pfb.arb_resampler_ccf(rrate) # and wire them up self.connect(intl, resamp, self.u) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 self.set_gain(options.gain, 0) self.set_gain(options.gain, 1) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.u.set_antenna(options.antenna, 1) def set_freq(self, target_freq, chan): """ Set the center frequency we're interested in. Args: side: 0 = side A, 1 = side B target_freq: frequency in Hz @rtype: bool """ print "Tuning channel %s to %sHz" % \ (chan, num_to_str(target_freq)) r = self.u.set_center_freq(target_freq, chan) if r: return True else: print " Set Frequency Failed!" return False def set_gain(self, gain, chan): self.u.set_gain(gain, chan) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_spectrum_sense.py0000775000175000017500000002650112207440367024347 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, eng_notation from gnuradio import blocks from gnuradio import audio from gnuradio import filter from gnuradio import fft from gnuradio import uhd from gnuradio.eng_option import eng_option from optparse import OptionParser import sys import math import struct import threading from datetime import datetime sys.stderr.write("Warning: this may have issues on some machines+Python version combinations to seg fault due to the callback in bin_statitics.\n\n") class ThreadClass(threading.Thread): def run(self): return class tune(gr.feval_dd): """ This class allows C++ code to callback into python. """ def __init__(self, tb): gr.feval_dd.__init__(self) self.tb = tb def eval(self, ignore): """ This method is called from blocks.bin_statistics_f when it wants to change the center frequency. This method tunes the front end to the new center frequency, and returns the new frequency as its result. """ try: # We use this try block so that if something goes wrong # from here down, at least we'll have a prayer of knowing # what went wrong. Without this, you get a very # mysterious: # # terminate called after throwing an instance of # 'Swig::DirectorMethodException' Aborted # # message on stderr. Not exactly helpful ;) new_freq = self.tb.set_next_freq() # wait until msgq is empty before continuing while(self.tb.msgq.full_p()): #print "msgq full, holding.." time.sleep(0.1) return new_freq except Exception, e: print "tune: Exception: ", e class parse_msg(object): def __init__(self, msg): self.center_freq = msg.arg1() self.vlen = int(msg.arg2()) assert(msg.length() == self.vlen * gr.sizeof_float) # FIXME consider using NumPy array t = msg.to_string() self.raw_data = t self.data = struct.unpack('%df' % (self.vlen,), t) class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) usage = "usage: %prog [options] min_freq max_freq" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate [default=%default]") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("", "--tune-delay", type="eng_float", default=0.25, metavar="SECS", help="time to delay (in seconds) after changing frequency [default=%default]") parser.add_option("", "--dwell-delay", type="eng_float", default=0.25, metavar="SECS", help="time to dwell (in seconds) at a given frequency [default=%default]") parser.add_option("-b", "--channel-bandwidth", type="eng_float", default=6.25e3, metavar="Hz", help="channel bandwidth of fft bins in Hz [default=%default]") parser.add_option("-l", "--lo-offset", type="eng_float", default=0, metavar="Hz", help="lo_offset in Hz [default=%default]") parser.add_option("-q", "--squelch-threshold", type="eng_float", default=None, metavar="dB", help="squelch threshold in dB [default=%default]") parser.add_option("-F", "--fft-size", type="int", default=None, help="specify number of FFT bins [default=samp_rate/channel_bw]") parser.add_option("", "--real-time", action="store_true", default=False, help="Attempt to enable real-time scheduling") (options, args) = parser.parse_args() if len(args) != 2: parser.print_help() sys.exit(1) self.channel_bandwidth = options.channel_bandwidth self.min_freq = eng_notation.str_to_num(args[0]) self.max_freq = eng_notation.str_to_num(args[1]) if self.min_freq > self.max_freq: # swap them self.min_freq, self.max_freq = self.max_freq, self.min_freq if not options.real_time: realtime = False else: # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.u.set_samp_rate(options.samp_rate) self.usrp_rate = usrp_rate = self.u.get_samp_rate() self.lo_offset = options.lo_offset if options.fft_size is None: self.fft_size = int(self.usrp_rate/self.channel_bandwidth) else: self.fft_size = options.fft_size self.squelch_threshold = options.squelch_threshold s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, self.fft_size) mywindow = filter.window.blackmanharris(self.fft_size) ffter = fft.fft_vcc(self.fft_size, True, mywindow, True) power = 0 for tap in mywindow: power += tap*tap c2mag = blocks.complex_to_mag_squared(self.fft_size) # FIXME the log10 primitive is dog slow #log = blocks.nlog10_ff(10, self.fft_size, # -20*math.log10(self.fft_size)-10*math.log10(power/self.fft_size)) # Set the freq_step to 75% of the actual data throughput. # This allows us to discard the bins on both ends of the spectrum. self.freq_step = self.nearest_freq((0.75 * self.usrp_rate), self.channel_bandwidth) self.min_center_freq = self.min_freq + (self.freq_step/2) nsteps = math.ceil((self.max_freq - self.min_freq) / self.freq_step) self.max_center_freq = self.min_center_freq + (nsteps * self.freq_step) self.next_freq = self.min_center_freq tune_delay = max(0, int(round(options.tune_delay * usrp_rate / self.fft_size))) # in fft_frames dwell_delay = max(1, int(round(options.dwell_delay * usrp_rate / self.fft_size))) # in fft_frames self.msgq = gr.msg_queue(1) self._tune_callback = tune(self) # hang on to this to keep it from being GC'd stats = blocks.bin_statistics_f(self.fft_size, self.msgq, self._tune_callback, tune_delay, dwell_delay) # FIXME leave out the log10 until we speed it up #self.connect(self.u, s2v, ffter, c2mag, log, stats) self.connect(self.u, s2v, ffter, c2mag, stats) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 self.set_gain(options.gain) print "gain =", options.gain def set_next_freq(self): target_freq = self.next_freq self.next_freq = self.next_freq + self.freq_step if self.next_freq >= self.max_center_freq: self.next_freq = self.min_center_freq if not self.set_freq(target_freq): print "Failed to set frequency to", target_freq sys.exit(1) return target_freq def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(uhd.tune_request(target_freq, rf_freq=(target_freq + self.lo_offset),rf_freq_policy=uhd.tune_request.POLICY_MANUAL)) if r: return True return False def set_gain(self, gain): self.u.set_gain(gain) def nearest_freq(self, freq, channel_bandwidth): freq = round(freq / channel_bandwidth, 0) * channel_bandwidth return freq def main_loop(tb): def bin_freq(i_bin, center_freq): #hz_per_bin = tb.usrp_rate / tb.fft_size freq = center_freq - (tb.usrp_rate / 2) + (tb.channel_bandwidth * i_bin) #print "freq original:",freq #freq = nearest_freq(freq, tb.channel_bandwidth) #print "freq rounded:",freq return freq bin_start = int(tb.fft_size * ((1 - 0.75) / 2)) bin_stop = int(tb.fft_size - bin_start) while 1: # Get the next message sent from the C++ code (blocking call). # It contains the center frequency and the mag squared of the fft m = parse_msg(tb.msgq.delete_head()) # m.center_freq is the center frequency at the time of capture # m.data are the mag_squared of the fft output # m.raw_data is a string that contains the binary floats. # You could write this as binary to a file. for i_bin in range(bin_start, bin_stop): center_freq = m.center_freq freq = bin_freq(i_bin, center_freq) #noise_floor_db = -174 + 10*math.log10(tb.channel_bandwidth) noise_floor_db = 10*math.log10(min(m.data)/tb.usrp_rate) power_db = 10*math.log10(m.data[i_bin]/tb.usrp_rate) - noise_floor_db if (power_db > tb.squelch_threshold) and (freq >= tb.min_freq) and (freq <= tb.max_freq): print datetime.now(), "center_freq", center_freq, "freq", freq, "power_db", power_db, "noise_floor_db", noise_floor_db if __name__ == '__main__': t = ThreadClass() t.start() tb = my_top_block() try: tb.start() main_loop(tb) except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_nbfm_rcv.py0000775000175000017500000003411112207440367023100 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form from optparse import OptionParser import sys import math import wx #//////////////////////////////////////////////////////////////////////// # Control Stuff #//////////////////////////////////////////////////////////////////////// class my_top_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=146.585e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("-N", "--no-gui", action="store_true", default=False) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) if options.freq < 1e6: options.freq *= 1e6 self.frame = frame self.panel = panel self.state = "FREQ" self.freq = 0 self.freq_step = 25e3 self.rxpath = receive_path(options.args, options.spec, options.antenna, options.gain, options.audio_output) self.connect(self.rxpath) self._build_gui(vbox, options.no_gui) # set initial values if options.volume is not None: self.set_volume(options.volume) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") self.set_gain(self.rxpath.gain) # update gui self.set_volume(self.rxpath.volume) # update gui self.set_squelch(self.rxpath.threshold()) # update gui def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, no_gui): def _form_set_freq(kv): return self.set_freq(kv['freq']) self.src_fft = None if 0 and not(no_gui): self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP", fft_size=512, sample_rate=self.rxpath.if_rate, ref_scale=32768.0, ref_level=0, y_per_div=10, y_divs=12) self.connect (self.rxpath.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 1 and not(no_gui): rx_fft = fftsink2.fft_sink_c(self.panel, title="Post s/w Resampling", fft_size=512, sample_rate=self.rxpath.quad_rate, ref_level=80, y_per_div=20) self.connect (self.rxpath.resamp, rx_fft) vbox.Add (rx_fft.win, 4, wx.EXPAND) if 1 and not(no_gui): post_deemph_fft = fftsink2.fft_sink_f(self.panel, title="Post Deemph", fft_size=512, sample_rate=self.rxpath.audio_rate, y_per_div=10, ref_level=-40) self.connect (self.rxpath.fmrx.deemph, post_deemph_fft) vbox.Add (post_deemph_fft.win, 4, wx.EXPAND) if 0: post_filt_fft = fftsink2.fft_sink_f(self.panel, title="Post Filter", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-40) self.connect (self.guts.audio_filter, post_filt) vbox.Add (fft_win4, 4, wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) #hbox.Add((5,0), 0) #myform['freq_slider'] = \ # form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, # range=(87.9e6, 108.1e6, 0.1e6), # callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_volume) hbox.Add((5,0), 0) myform['squelch'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Squelch", weight=3, range=self.rxpath.squelch_range(), callback=self.set_squelch) g = self.rxpath.u.get_gain_range() hbox.Add((5,0), 0) myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + self.freq_step) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - self.freq_step) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_volume(self.rxpath.volume + step) self.rot -= 3 elif self.rot <=-3: self.set_volume(self.rxpath.volume - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_squelch(self, threshold_in_db): self.rxpath.set_squelch(threshold_in_db) self.myform['squelch'].set_value(self.rxpath.threshold()) def set_volume (self, vol): self.rxpath.set_volume(vol) self.myform['volume'].set_value(self.rxpath.volume) self.update_status_bar () def set_freq(self, target_freq): r = self.rxpath.set_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value #self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.rxpath.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.rxpath.volume, self.state) self._set_status_msg(msg, 1) if self.src_fft: self.src_fft.set_baseband_freq(self.freq) def volume_range(self): return (-20.0, 0.0, 0.5) #//////////////////////////////////////////////////////////////////////// # Receive Path #//////////////////////////////////////////////////////////////////////// USE_SIMPLE_SQUELCH = False class receive_path(gr.hier_block2): def __init__(self, args, spec, antenna, gain, audio_output): gr.hier_block2.__init__(self, "receive_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(spec): self.u.set_subdev_spec(spec, 0) # Set the antenna if(antenna): self.u.set_antenna(antenna, 0) self.if_rate = 256e3 self.quad_rate = 64e3 self.audio_rate = 32e3 self.u.set_samp_rate(self.if_rate) dev_rate = self.u.get_samp_rate() # Create filter to get actual channel we want nfilts = 32 chan_coeffs = filter.firdes.low_pass(nfilts, # gain nfilts*dev_rate, # sampling rate 8e3, # low pass cutoff freq 2e3, # width of trans. band filter.firdes.WIN_HANN) # filter type rrate = self.quad_rate / dev_rate self.resamp = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) if USE_SIMPLE_SQUELCH: self.squelch = analog.simple_squelch_cc(20) else: self.squelch = analog.standard_squelch(self.audio_rate) # instantiate the guts of the single channel receiver self.fmrx = analog.nbfm_rx(self.audio_rate, self.quad_rate) # audio gain / mute block self._audio_gain = blocks.multiply_const_ff(1.0) # sound card as final sink audio_sink = audio.sink (int(self.audio_rate), audio_output) # now wire it all together if USE_SIMPLE_SQUELCH: self.connect (self.u, self.resamp, self.squelch, self.fmrx, self._audio_gain, audio_sink) else: self.connect (self.u, self.resamp, self.fmrx, self.squelch, self._audio_gain, audio_sink) if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() gain = float(g.start()+g.stop())/2 self.set_gain(gain) v = self.volume_range() self.set_volume((v[0]+v[1])/2) s = self.squelch_range() self.set_squelch((s[0]+s[1])/2) def volume_range(self): return (-20.0, 0.0, 0.5) def set_volume (self, vol): g = self.volume_range() self.volume = max(g[0], min(g[1], vol)) self._update_audio_gain() def _update_audio_gain(self): self._audio_gain.set_k(10**(self.volume/10)) def squelch_range(self): r = self.squelch.squelch_range() #print "squelch_range: ", r return r def set_squelch(self, threshold): #print "SQL =", threshold self.squelch.set_threshold(threshold) def threshold(self): t = self.squelch.threshold() #print "t =", t return t def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: return True return False def set_gain(self, gain): self.gain = gain self.u.set_gain(gain) # //////////////////////////////////////////////////////////////////////// # Main # //////////////////////////////////////////////////////////////////////// if __name__ == '__main__': app = stdgui2.stdapp (my_top_block, "USRP NBFM RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wfm_rcv_sca.py0000775000175000017500000004044412207440367023603 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Here is a bit of code that will receive SCA analog subcarriers of FM Broadcast Stations using the USRP. It is a modified version of usrp_wfm_rcv.py. Common SCA frequencies are 67 kHz and 92 kHz. SCA is used for Reading Services for the Blind, Background Music, Foreign Language Services, and other services. Remember you may hear static when tuned to a FM station because this code only outputs SCA audio. The USRP gain is critical for good decoding. Adjust for minimum noise. I use the Post FM Demod FFT to check for SCA subcarriers and to adjust the USRP gain for the lowest noise floor. The stereo pilot at 19 KHz, the stereo difference signal around 38 KHz, and RDS at 57 KHz are also displayed on the Post FM Demod FFT if present. The range below 67 kHz is used for SCA only when Stereo is not used. The SCA recieve range is not as far as the main FM carrier receive range so tune in strong local stations first. I tried to comment the code with the various parameters. There seems to be several choices for a couple of them. I coded the common ones I see here. In the local area there are a couple of stations using digital SCA. These look similar to narrow DRM signals and I wonder if they are using OFDM. """ from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form from optparse import OptionParser import sys import math import wx class wfm_rx_sca_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=100.1e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.frame = frame self.panel = panel self.vol = 0 self.state = "FREQ" self.freq = 0 self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 32e3 sca_demod_rate = 64e3 audio_decim = int(demod_rate / audio_rate) sca_chanfilt_decim = int(demod_rate / sca_demod_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = filter.optfir.low_pass(nfilts, # gain nfilts*usrp_rate, # sampling rate 100e3, # passband cutoff 140e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) #Create demodulator block for Main FM Channel max_dev = 75e3 fm_demod_gain = demod_rate/(2*math.pi*max_dev) self.fm_demod = analog.quadrature_demod_cf(fm_demod_gain) # Note - deemphasis is not applied to the Main FM Channel as # main audio is not decoded # SCA Devation is 10% of carrier but some references say 20% # if mono with one SCA (6 KHz seems typical) max_sca_dev = 6e3 # Create filter to get SCA channel we want sca_chan_coeffs = filter.firdes.low_pass(1.0, # gain demod_rate, # sampling rate max_sca_dev, # cutoff freq max_sca_dev/3, # trans. band filter.firdes.WIN_HANN) # filter type self.ddc = filter.freq_xlating_fir_filter_fcf(sca_chanfilt_decim, # decim rate sca_chan_coeffs, # taps 0, # freq translation amount (Gets set by the UI) demod_rate) # input sample rate #Create demodulator block for SCA Channel sca_demod_gain = sca_demod_rate/(2*math.pi*max_sca_dev) self.fm_demod_sca = analog.quadrature_demod_cf(sca_demod_gain) # SCA analog audio is bandwidth limited to 5 KHz max_sca_audio_freq = 5.0e3 # SCA analog deephasis is 150 uS (75 uS may be used) sca_tau = 150e-6 # compute FIR filter taps for SCA audio filter audio_coeffs = filter.firdes.low_pass(1.0, # gain sca_demod_rate, # sampling rate max_sca_audio_freq, # cutoff freq max_sca_audio_freq/2.5, # trans. band filter.firdes.WIN_HAMMING) # input: float; output: float self.audio_filter = filter.fir_filter_fff(audio_decim, audio_coeffs) # Create deemphasis block that is applied after SCA demodulation self.deemph = analog.fm_deemph(audio_rate, sca_tau) self.volume_control = blocks.multiply_const_ff(self.vol) # sound card as final sink self.audio_sink = audio.sink(int (audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect(self.u, self.chan_filt, self.fm_demod, self.ddc, self.fm_demod_sca) self.connect(self.fm_demod_sca, self.audio_filter, self.deemph, self.volume_control, self.audio_sink) self._build_gui(vbox, usrp_rate, demod_rate, sca_demod_rate, audio_rate) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.fm_freq_min or options.freq > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_vol(options.volume) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") self.set_sca_freq(67000) # A common SCA Frequency def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, sca_demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) def _form_set_sca_freq(kv): return self.set_sca_freq(kv['sca_freq']) if 1: self.src_fft = fftsink2.fft_sink_c(self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate, ref_scale=32768.0, ref_level=0, y_divs=12) self.connect (self.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 1: post_demod_fft = fftsink2.fft_sink_f(self.panel, title="Post FM Demod", fft_size=2048, sample_rate=demod_rate, y_per_div=10, ref_level=0) self.connect (self.fm_demod, post_demod_fft) vbox.Add (post_demod_fft.win, 4, wx.EXPAND) if 0: post_demod_sca_fft = fftsink2.fft_sink_f(self.panel, title="Post SCA Demod", fft_size=1024, sample_rate=sca_demod_rate, y_per_div=10, ref_level=0) self.connect (self.fm_demod_sca, post_demod_sca_fft) vbox.Add (post_demod_sca_fft.win, 4, wx.EXPAND) if 0: post_deemph_fft = fftsink2.fft_sink_f (self.panel, title="Post SCA Deemph", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=-20) self.connect (self.deemph, post_deemph_fft) vbox.Add (post_deemph_fft.win, 4, wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(self.fm_freq_min, self.fm_freq_max, 0.1e6), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['sca_freq'] = form.float_field( parent=self.panel, sizer=hbox, label="SCA", weight=1, callback=myform.check_input_and_call(_form_set_sca_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['sca_freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(38e3, 100e3, 1.0e3), callback=self.set_sca_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_vol) hbox.Add((5,0), 1) g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_vol(self.vol + step) self.rot -= 3 elif self.rot <=-3: self.set_vol(self.vol - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control.set_k(10**(self.vol/10)) self.myform['volume'].set_value(self.vol) self.update_status_bar () def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool Tuning is a two step process. First we ask the front-end to tune as close to the desired frequency as it can. Then we use the result of that operation and our target_frequency to determine the value for the digital down converter. """ r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_sca_freq(self, target_sca_freq): self.ddc.set_center_freq(-target_sca_freq) self.myform['sca_freq'].set_value(target_sca_freq) # update displayed value self.myform['sca_freq_slider'].set_value(target_sca_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.vol, self.state) self._set_status_msg(msg, 1) self.src_fft.set_baseband_freq(self.freq) def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': app = stdgui2.stdapp (wfm_rx_sca_block, "USRP WFM SCA RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wxapt_rcv.py0000775000175000017500000002517012207440367023326 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio.eng_option import eng_option from gnuradio.wxgui import slider, powermate from gnuradio.wxgui import stdgui2, fftsink2, form from optparse import OptionParser import sys import wx class wxapt_rx_block (stdgui2.std_top_block): def __init__(self,frame,panel,vbox,argv): stdgui2.std_top_block.__init__ (self,frame,panel,vbox,argv) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args, [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=137.5e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=137e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=138e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.frame = frame self.panel = panel self.vol = 0 self.state = "FREQ" self.freq = 0 self.freq_min = options.freq_min self.freq_max = options.freq_max # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 32e3 audio_decim = int(demod_rate / audio_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = filter.firdes.low_pass_2(nfilts, # gain nfilts*usrp_rate, # sampling rate 40e3, # passband cutoff 20e3, # transition bw 60) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) self.guts = analog.wfm_rcv(demod_rate, audio_decim) self.volume_control = blocks.multiply_const_ff(self.vol) # sound card as final sink self.audio_sink = audio.sink(int (audio_rate), options.audio_output) # now wire it all together self.connect(self.u, self.chan_filt, self.guts, self.volume_control, self.audio_sink) self._build_gui(vbox, usrp_rate, demod_rate, audio_rate) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 frange = self.u.get_freq_range() if(frange.start() > self.freq_max or frange.stop() < self.freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.freq_min or options.freq > self.freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_vol(options.volume) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _build_gui(self, vbox, usrp_rate, demod_rate, audio_rate): def _form_set_freq(kv): return self.set_freq(kv['freq']) if 1: self.src_fft = fftsink2.fft_sink_c (self.panel, title="Data from USRP", fft_size=512, sample_rate=usrp_rate, ref_scale=32768.0, ref_level=0, y_divs=12) self.connect (self.u, self.src_fft) vbox.Add (self.src_fft.win, 4, wx.EXPAND) if 1: post_deemph_fft = fftsink2.fft_sink_f (self.panel, title="Post Deemph", fft_size=512, sample_rate=demod_rate, y_per_div=10, ref_level=-20) self.connect (self.guts.deemph, post_deemph_fft) vbox.Add (post_deemph_fft.win, 4, wx.EXPAND) if 1: post_filt_fft = fftsink2.fft_sink_f (self.panel, title="Post Filter", fft_size=512, sample_rate=audio_rate, y_per_div=10, ref_level=0) self.connect (self.guts.audio_filter, post_filt_fft) vbox.Add (post_filt_fft.win, 4, wx.EXPAND) # control area form at bottom self.myform = myform = form.form() hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['freq'] = form.float_field( parent=self.panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0) myform['freq_slider'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, weight=3, range=(self.freq_min, self.freq_max, 0.0005e6), callback=self.set_freq) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.volume_range(), callback=self.set_vol) hbox.Add((5,0), 1) g = self.u.get_gain_range() myform['gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Gain", weight=3, range=(g.start(), g.start(), g.step()), callback=self.set_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) try: self.knob = powermate.powermate(self.frame) self.rot = 0 powermate.EVT_POWERMATE_ROTATE (self.frame, self.on_rotate) powermate.EVT_POWERMATE_BUTTON (self.frame, self.on_button) except: print "FYI: No Powermate or Contour Knob found" def on_rotate (self, event): self.rot += event.delta if (self.state == "FREQ"): if self.rot >= 3: self.set_freq(self.freq + .1e6) self.rot -= 3 elif self.rot <=-3: self.set_freq(self.freq - .1e6) self.rot += 3 else: step = self.volume_range()[2] if self.rot >= 3: self.set_vol(self.vol + step) self.rot -= 3 elif self.rot <=-3: self.set_vol(self.vol - step) self.rot += 3 def on_button (self, event): if event.value == 0: # button up return self.rot = 0 if self.state == "FREQ": self.state = "VOL" else: self.state = "FREQ" self.update_status_bar () def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control.set_k(10**(self.vol/10)) self.myform['volume'].set_value(self.vol) self.update_status_bar () def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.myform['freq'].set_value(target_freq) # update displayed value self.myform['freq_slider'].set_value(target_freq) # update displayed value self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.myform['gain'].set_value(gain) # update displayed value self.u.set_gain(gain) def update_status_bar (self): msg = "Volume:%r Setting:%s" % (self.vol, self.state) self._set_status_msg(msg, 1) self.src_fft.set_baseband_freq(self.freq) def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': app = stdgui2.stdapp (wxapt_rx_block, "USRP WXAPT RX") app.MainLoop () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_tv_rcv_nogui.py0000775000175000017500000002216612207440367024017 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Reads from a file and generates PAL TV pictures in black and white which can be displayed using ImageMagick or realtime using gr-video-sdl (To capture the input file Use usrp_rx_file.py, or use usrp_rx_cfile.py --output-shorts if you have a recent enough usrp_rx_cfile.py) Can also use usrp directly as capture source, but then you need a higher decimation factor (64) and thus get a lower horizontal resulution. There is no synchronisation yet. The sync blocks are in development but not yet in cvs. """ from gnuradio import gr, eng_notation from gnuradio import analog from gnuradio import blocks from gnuradio import audio from gnuradio import uhd from gnuradio.eng_option import eng_option from optparse import OptionParser import sys try: from gnuradio import video_sdl except: print "FYI: gr-video-sdl is not installed" print "realtime \"sdl\" video output window will not be available" class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) usage=("%prog: [options] output_filename.\nSpecial output_filename" + \ "\"sdl\" will use video_sink_sdl as realtime output window. " + \ "You then need to have gr-video-sdl installed.\n" +\ "Make sure your input capture file containes interleaved " + \ "shorts not complex floats") parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=1e6, help="set sample rate") parser.add_option("-c", "--contrast", type="eng_float", default=1.0, help="set contrast (default is 1.0)") parser.add_option("-b", "--brightness", type="eng_float", default=0.0, help="set brightness (default is 0)") parser.add_option("-i", "--in-filename", type="string", default=None, help="Use input file as source. samples must be " + \ "interleaved shorts \n Use usrp_rx_file.py or " + \ "usrp_rx_cfile.py --output-shorts.\n Special " + \ "name \"usrp\" results in realtime capturing " + \ "and processing using usrp.\n" + \ "You then probably need a decimation factor of 64 or higher.") parser.add_option("-f", "--freq", type="eng_float", default=519.25e6, help="set frequency to FREQ.\nNote that the frequency of the video carrier is not at the middle of the TV channel", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-p", "--pal", action="store_true", default=False, help="PAL video format (this is the default)") parser.add_option("-n", "--ntsc", action="store_true", default=False, help="NTSC video format") parser.add_option("-r", "--repeat", action="store_false", default=True, help="repeat in_file in a loop") parser.add_option("-N", "--nframes", type="eng_float", default=None, help="number of frames to collect [default=+inf]") parser.add_option("", "--freq-min", type="eng_float", default=50.25e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=900.25e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args () if not (len(args) == 1): parser.print_help() sys.stderr.write('You must specify the output. FILENAME or sdl \n'); sys.exit(1) filename = args[0] self.tv_freq_min = options.freq_min self.tv_freq_max = options.freq_max if options.in_filename is None: parser.print_help() sys.stderr.write('You must specify the input -i FILENAME or -i usrp\n'); raise SystemExit, 1 if not (filename=="sdl"): options.repeat=False input_rate = options.samp_rate print "video sample rate %s" % (eng_notation.num_to_str(input_rate)) if not (options.in_filename=="usrp"): # file is data source, capture with usr_rx_csfile.py self.filesource = blocks.file_source(gr.sizeof_short, options.in_filename, options.repeat) self.istoc = blocks.interleaved_short_to_complex() self.connect(self.filesource,self.istoc) self.src=self.istoc else: if options.freq is None: parser.print_help() sys.stderr.write('You must specify the frequency with -f FREQ\n'); raise SystemExit, 1 # build the graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.u.set_samp_rate(input_rate) dev_rate = self.u.get_samp_rate() self.src=self.u if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 self.u.set_gain(options.gain) r = self.u.set_center_freq(options.freq) if not r: sys.stderr.write('Failed to set frequency\n') raise SystemExit, 1 self.agc = analog.agc_cc(1e-7,1.0,1.0) #1e-7 self.am_demod = blocks.complex_to_mag () self.set_blacklevel = blocks.add_const_ff(options.brightness +255.0) self.invert_and_scale = blocks.multiply_const_ff(-options.contrast *128.0*255.0/(200.0)) self.f2uc = blocks.float_to_uchar() # sdl window as final sink if not (options.pal or options.ntsc): options.pal=True #set default to PAL if options.pal: lines_per_frame=625.0 frames_per_sec=25.0 show_width=768 elif options.ntsc: lines_per_frame=525.0 frames_per_sec=29.97002997 show_width=640 width=int(input_rate/(lines_per_frame*frames_per_sec)) height=int(lines_per_frame) if filename=="sdl": #Here comes the tv screen, you have to build and install #gr-video-sdl for this (subproject of gnuradio) try: video_sink = video_sdl.sink_uc(frames_per_sec, width, height, 0, show_width,height) except: print "gr-video-sdl is not installed" print "realtime \"sdl\" video output window is not available" raise SystemExit, 1 self.dst=video_sink else: print "You can use the imagemagick display tool to show the resulting imagesequence" print "use the following line to show the demodulated TV-signal:" print "display -depth 8 -size " +str(width)+ "x" + str(height) + " gray:" +filename print "(Use the spacebar to advance to next frames)" file_sink = blocks.file_sink(gr.sizeof_char, filename) self.dst =file_sink if options.nframes is None: self.connect(self.src, self.agc) else: self.head = blocks.head(gr.sizeof_gr_complex, int(options.nframes*width*height)) self.connect(self.src, self.head, self.agc) self.connect (self.agc, self.am_demod, self.invert_and_scale, self.set_blacklevel, self.f2uc, self.dst) if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-uhd/examples/python/fm_tx4.py0000775000175000017500000001705712207440367021446 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Transmit N simultaneous narrow band FM signals. They will be centered at the frequency specified on the command line, and will spaced at 25kHz steps from there. The program opens N files with names audio-N.dat where N is in [0,7]. These files should contain floating point audio samples in the range [-1,1] sampled at 32kS/sec. You can create files like this using audio_to_file.py """ from gnuradio import gr, eng_notation from gnuradio import uhd from gnuradio import analog from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import math import sys from gnuradio.wxgui import stdgui2, fftsink2 import wx ######################################################## # instantiate one transmit chain for each call class pipeline(gr.hier_block2): def __init__(self, filename, lo_freq, audio_rate, if_rate): gr.hier_block2.__init__(self, "pipeline", gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_gr_complex)) try: src = blocks.file_source (gr.sizeof_float, filename, True) except RuntimeError: sys.stderr.write(("\nError: Could not open file '%s'\n\n" % \ filename)) sys.exit(1) print audio_rate, if_rate fmtx = analog.nbfm_tx(audio_rate, if_rate, max_dev=5e3, tau=75e-6) # Local oscillator lo = analog.sig_source_c(if_rate, # sample rate analog.GR_SIN_WAVE, # waveform type lo_freq, # frequency 1.0, # amplitude 0) # DC Offset mixer = blocks.multiply_cc() self.connect(src, fmtx, (mixer, 0)) self.connect(lo, (mixer, 1)) self.connect(mixer, self) class fm_tx_block(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): MAX_CHANNELS = 7 stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) parser = OptionParser (option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-s", "--samp-rate", type="eng_float", default=400e3, help="set sample rate (bandwidth) [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-n", "--nchannels", type="int", default=4, help="number of Tx channels [1,4]") #parser.add_option("","--debug", action="store_true", default=False, # help="Launch Tx debugger") (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.nchannels < 1 or options.nchannels > MAX_CHANNELS: sys.stderr.write ("fm_tx4: nchannels out of range. Must be in [1,%d]\n" % MAX_CHANNELS) sys.exit(1) if options.freq is None: sys.stderr.write("fm_tx4: must specify frequency with -f FREQ\n") parser.print_help() sys.exit(1) # ---------------------------------------------------------------- # Set up constants and parameters self.u = uhd.usrp_sink(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) self.usrp_rate = options.samp_rate self.u.set_samp_rate(self.usrp_rate) self.usrp_rate = self.u.get_samp_rate() self.sw_interp = 10 self.audio_rate = self.usrp_rate / self.sw_interp # 32 kS/s if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2 self.set_gain(options.gain) self.set_freq(options.freq) self.sum = blocks.add_cc () # Instantiate N NBFM channels step = 25e3 offset = (0 * step, 1 * step, -1 * step, 2 * step, -2 * step, 3 * step, -3 * step) for i in range (options.nchannels): t = pipeline("audio-%d.dat" % (i % 4), offset[i], self.audio_rate, self.usrp_rate) self.connect(t, (self.sum, i)) self.gain = blocks.multiply_const_cc (1.0 / options.nchannels) # connect it all self.connect (self.sum, self.gain) self.connect (self.gain, self.u) # plot an FFT to verify we are sending what we want if 1: post_mod = fftsink2.fft_sink_c(panel, title="Post Modulation", fft_size=512, sample_rate=self.usrp_rate, y_per_div=20, ref_level=40) self.connect (self.gain, post_mod) vbox.Add (post_mod.win, 1, wx.EXPAND) #if options.debug: # self.debugger = tx_debug_gui.tx_debug_gui(self.subdev) # self.debugger.Show(True) def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool Tuning is a two step process. First we ask the front-end to tune as close to the desired frequency as it can. Then we use the result of that operation and our target_frequency to determine the value for the digital up converter. Finally, we feed any residual_freq to the s/w freq translater. """ r = self.u.set_center_freq(target_freq, 0) if r: print "Frequency =", eng_notation.num_to_str(self.u.get_center_freq()) return True return False def set_gain(self, gain): self.u.set_gain(gain, 0) def main (): app = stdgui2.stdapp(fm_tx_block, "Multichannel FM Tx", nstatus=1) app.MainLoop () if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_nbfm_ptt.py0000775000175000017500000004266312207440367023130 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math import sys import wx from optparse import OptionParser from gnuradio import gr, audio, uhd from gnuradio import analog from gnuradio import blocks from gnuradio import filter from gnuradio.eng_option import eng_option from gnuradio.wxgui import stdgui2, fftsink2, scopesink2, slider, form from numpy import convolve, array #import os #print "pid =", os.getpid() #raw_input('Press Enter to continue: ') # //////////////////////////////////////////////////////////////////////// # Control Stuff # //////////////////////////////////////////////////////////////////////// class ptt_block(stdgui2.std_top_block): def __init__(self, frame, panel, vbox, argv): stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv) self.frame = frame self.space_bar_pressed = False parser = OptionParser (option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option ("-f", "--freq", type="eng_float", default=442.1e6, help="set Tx and Rx frequency to FREQ", metavar="FREQ") parser.add_option ("-g", "--rx-gain", type="eng_float", default=None, help="set rx gain [default=midpoint in dB]") parser.add_option ("", "--tx-gain", type="eng_float", default=None, help="set tx gain [default=midpoint in dB]") parser.add_option("-I", "--audio-input", type="string", default="default", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm output device name. E.g., hw:0,0 or /dev/dsp") parser.add_option ("-N", "--no-gui", action="store_true", default=False) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.freq < 1e6: options.freq *= 1e6 self.txpath = transmit_path(options.args, options.spec, options.antenna, options.tx_gain, options.audio_input) self.rxpath = receive_path(options.args, options.spec, options.antenna, options.rx_gain, options.audio_output) self.connect(self.txpath) self.connect(self.rxpath) self._build_gui(frame, panel, vbox, argv, options.no_gui) self.set_transmit(False) self.set_freq(options.freq) self.set_rx_gain(self.rxpath.gain) # update gui self.set_volume(self.rxpath.volume) # update gui self.set_squelch(self.rxpath.threshold()) # update gui def set_transmit(self, enabled): self.txpath.set_enable(enabled) self.rxpath.set_enable(not(enabled)) if enabled: self.frame.SetStatusText ("Transmitter ON", 1) else: self.frame.SetStatusText ("Receiver ON", 1) def set_rx_gain(self, gain): self.myform['rx_gain'].set_value(gain) # update displayed value self.rxpath.set_gain(gain) def set_tx_gain(self, gain): self.txpath.set_gain(gain) def set_squelch(self, threshold): self.rxpath.set_squelch(threshold) self.myform['squelch'].set_value(self.rxpath.threshold()) def set_volume (self, vol): self.rxpath.set_volume(vol) self.myform['volume'].set_value(self.rxpath.volume) #self.update_status_bar () def set_freq(self, freq): r1 = self.txpath.set_freq(freq) r2 = self.rxpath.set_freq(freq) #print "txpath.set_freq =", r1 #print "rxpath.set_freq =", r2 if r1 and r2: self.myform['freq'].set_value(freq) # update displayed value return r1 and r2 def _build_gui(self, frame, panel, vbox, argv, no_gui): def _form_set_freq(kv): return self.set_freq(kv['freq']) self.panel = panel # FIXME This REALLY needs to be replaced with a hand-crafted button # that sends both button down and button up events hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((10,0), 1) self.status_msg = wx.StaticText(panel, -1, "Press Space Bar to Transmit") of = self.status_msg.GetFont() self.status_msg.SetFont(wx.Font(15, of.GetFamily(), of.GetStyle(), of.GetWeight())) hbox.Add(self.status_msg, 0, wx.ALIGN_CENTER) hbox.Add((10,0), 1) vbox.Add(hbox, 0, wx.EXPAND | wx.ALIGN_CENTER) panel.Bind(wx.EVT_KEY_DOWN, self._on_key_down) panel.Bind(wx.EVT_KEY_UP, self._on_key_up) panel.Bind(wx.EVT_KILL_FOCUS, self._on_kill_focus) panel.SetFocus() if 1 and not(no_gui): rx_fft = fftsink2.fft_sink_c(panel, title="Rx Input", fft_size=512, sample_rate=self.rxpath.if_rate, ref_level=80, y_per_div=20) self.connect (self.rxpath.u, rx_fft) vbox.Add (rx_fft.win, 1, wx.EXPAND) if 1 and not(no_gui): rx_fft = fftsink2.fft_sink_c(panel, title="Post s/w Resampler", fft_size=512, sample_rate=self.rxpath.quad_rate, ref_level=80, y_per_div=20) self.connect (self.rxpath.resamp, rx_fft) vbox.Add (rx_fft.win, 1, wx.EXPAND) if 0 and not(no_gui): foo = scopesink2.scope_sink_f(panel, title="Squelch", sample_rate=32000) self.connect (self.rxpath.fmrx.div, (foo,0)) self.connect (self.rxpath.fmrx.gate, (foo,1)) self.connect (self.rxpath.fmrx.squelch_lpf, (foo,2)) vbox.Add (foo.win, 1, wx.EXPAND) if 0 and not(no_gui): tx_fft = fftsink2.fft_sink_c(panel, title="Tx Output", fft_size=512, sample_rate=self.txpath.usrp_rate) self.connect (self.txpath.amp, tx_fft) vbox.Add (tx_fft.win, 1, wx.EXPAND) # add control area at the bottom self.myform = myform = form.form() # first row hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0, 0) myform['freq'] = form.float_field( parent=panel, sizer=hbox, label="Freq", weight=1, callback=myform.check_input_and_call(_form_set_freq, self._set_status_msg)) hbox.Add((5,0), 0, 0) vbox.Add(hbox, 0, wx.EXPAND) # second row hbox = wx.BoxSizer(wx.HORIZONTAL) myform['volume'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Volume", weight=3, range=self.rxpath.volume_range(), callback=self.set_volume) hbox.Add((5,0), 0) myform['squelch'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Squelch", weight=3, range=self.rxpath.squelch_range(), callback=self.set_squelch) g = self.rxpath.u.get_gain_range() hbox.Add((5,0), 0) myform['rx_gain'] = \ form.quantized_slider_field(parent=self.panel, sizer=hbox, label="Rx Gain", weight=3, range=(g.start(), g.stop(), g.step()), callback=self.set_rx_gain) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) self._build_subpanel(vbox) def _build_subpanel(self, vbox_arg): # build a secondary information panel (sometimes hidden) # FIXME figure out how to have this be a subpanel that is always # created, but has its visibility controlled by foo.Show(True/False) #if not(self.show_debug_info): # return panel = self.panel vbox = vbox_arg myform = self.myform #panel = wx.Panel(self.panel, -1) #vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add((5,0), 0) #myform['decim'] = form.static_float_field( # parent=panel, sizer=hbox, label="Decim") #hbox.Add((5,0), 1) #myform['fs@usb'] = form.static_float_field( # parent=panel, sizer=hbox, label="Fs@USB") #hbox.Add((5,0), 1) #myform['dbname'] = form.static_text_field( # parent=panel, sizer=hbox) hbox.Add((5,0), 0) vbox.Add(hbox, 0, wx.EXPAND) def _set_status_msg(self, msg, which=0): self.frame.GetStatusBar().SetStatusText(msg, which) def _on_key_down(self, evt): # print "key_down:", evt.m_keyCode if evt.m_keyCode == wx.WXK_SPACE and not(self.space_bar_pressed): self.space_bar_pressed = True self.set_transmit(True) def _on_key_up(self, evt): # print "key_up", evt.m_keyCode if evt.m_keyCode == wx.WXK_SPACE: self.space_bar_pressed = False self.set_transmit(False) def _on_kill_focus(self, evt): # if we lose the keyboard focus, turn off the transmitter self.space_bar_pressed = False self.set_transmit(False) # //////////////////////////////////////////////////////////////////////// # Transmit Path # //////////////////////////////////////////////////////////////////////// class transmit_path(gr.hier_block2): def __init__(self, args, spec, antenna, gain, audio_input): gr.hier_block2.__init__(self, "transmit_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(spec): self.u.set_subdev_spec(spec, 0) # Set the antenna if(antenna): self.u.set_antenna(antenna, 0) self.if_rate = 320e3 self.audio_rate = 32e3 self.u.set_samp_rate(self.if_rate) dev_rate = self.u.get_samp_rate() self.audio_gain = 10 self.normal_gain = 32000 self.audio = audio.source(int(self.audio_rate), audio_input) self.audio_amp = blocks.multiply_const_ff(self.audio_gain) lpf = filter.firdes.low_pass(1, # gain self.audio_rate, # sampling rate 3800, # low pass cutoff freq 300, # width of trans. band filter.firdes.WIN_HANN) # filter type hpf = filter.firdes.high_pass(1, # gain self.audio_rate, # sampling rate 325, # low pass cutoff freq 50, # width of trans. band filter.firdes.WIN_HANN) # filter type audio_taps = convolve(array(lpf),array(hpf)) self.audio_filt = filter.fir_filter_fff(1,audio_taps) self.pl = analog.ctcss_gen_f(self.audio_rate,123.0) self.add_pl = blocks.add_ff() self.connect(self.pl,(self.add_pl,1)) self.fmtx = analog.nbfm_tx(self.audio_rate, self.if_rate) self.amp = blocks.multiply_const_cc (self.normal_gain) rrate = dev_rate / self.if_rate self.resamp = filter.pfb.arb_resampler_ccf(rrate) self.connect(self.audio, self.audio_amp, self.audio_filt, (self.add_pl,0), self.fmtx, self.amp, self.resamp, self.u) if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() gain = float(g.start() + g.stop())/2.0 self.set_gain(gain) self.set_enable(False) def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: return True return False def set_gain(self, gain): self.gain = gain self.u.set_gain(gain) def set_enable(self, enable): if enable: self.amp.set_k (self.normal_gain) else: self.amp.set_k (0) # //////////////////////////////////////////////////////////////////////// # Receive Path # //////////////////////////////////////////////////////////////////////// class receive_path(gr.hier_block2): def __init__(self, args, spec, antenna, gain, audio_output): gr.hier_block2.__init__(self, "receive_path", gr.io_signature(0, 0, 0), # Input signature gr.io_signature(0, 0, 0)) # Output signature self.u = uhd.usrp_source(device_addr=args, io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=1) self.if_rate = 256e3 self.quad_rate = 64e3 self.audio_rate = 32e3 self.u.set_samp_rate(self.if_rate) dev_rate = self.u.get_samp_rate() # Create filter to get actual channel we want nfilts = 32 chan_coeffs = filter.firdes.low_pass(nfilts, # gain nfilts*dev_rate, # sampling rate 13e3, # low pass cutoff freq 4e3, # width of trans. band filter.firdes.WIN_HANN) # filter type rrate = self.quad_rate / dev_rate self.resamp = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) # instantiate the guts of the single channel receiver self.fmrx = analog.nbfm_rx(self.audio_rate, self.quad_rate) # standard squelch block self.squelch = analog.standard_squelch(self.audio_rate) # audio gain / mute block self._audio_gain = blocks.multiply_const_ff(1.0) # sound card as final sink audio_sink = audio.sink(int(self.audio_rate), audio_output) # now wire it all together self.connect(self.u, self.resamp, self.fmrx, self.squelch, self._audio_gain, audio_sink) if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() gain = float(g.start() + g.stop())/2.0 self.enabled = True self.set_gain(gain) v = self.volume_range() self.set_volume((v[0]+v[1])/2) s = self.squelch_range() self.set_squelch((s[0]+s[1])/2) # Set the subdevice spec if(spec): self.u.set_subdev_spec(spec, 0) # Set the antenna if(antenna): self.u.set_antenna(antenna, 0) def volume_range(self): return (-20.0, 0.0, 0.5) def set_volume (self, vol): g = self.volume_range() self.volume = max(g[0], min(g[1], vol)) self._update_audio_gain() def set_enable(self, enable): self.enabled = enable self._update_audio_gain() def _update_audio_gain(self): if self.enabled: self._audio_gain.set_k(10**(self.volume/10)) else: self._audio_gain.set_k(0) def squelch_range(self): return self.squelch.squelch_range() def set_squelch(self, threshold): print "SQL =", threshold self.squelch.set_threshold(threshold) def threshold(self): return self.squelch.threshold() def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: return True return False def set_gain(self, gain): self.gain = gain self.u.set_gain(gain) # //////////////////////////////////////////////////////////////////////// # Main # //////////////////////////////////////////////////////////////////////// def main(): app = stdgui2.stdapp(ptt_block, "NBFM Push to Talk") app.MainLoop() if __name__ == '__main__': main() gnuradio-3.7.2.1/gr-uhd/examples/python/max_power.py0000775000175000017500000001176212207440367022243 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Setup USRP for maximum power consumption. """ from gnuradio import gr from gnuradio import analog from gnuradio import blocks from gnuradio import uhd from gnuradio.eng_option import eng_option from optparse import OptionParser from gnuradio import eng_notation n2s = eng_notation.num_to_str # Set this to a huge number; UHD will adjust to the # maximum the USRP xxxx device can handle MAX_RATE = 1000e6 class build_block(gr.top_block): def __init__(self, args, tx_enable, rx_enable): gr.top_block.__init__(self) d = uhd.find_devices(uhd.device_addr(args)) uhd_type = d[0].get('type') print "\nFound '%s' at args '%s'" % \ (uhd_type, args) # Test the type of USRP; if it's a USRP (v1), it has # 2 channels; otherwise, it has 1 channel if uhd_type == "usrp": tx_nchan = 2 rx_nchan = 2 else: tx_nchan = 1 rx_nchan = 1 if tx_enable: print "\nTRANSMIT CHAIN" stream_args = uhd.stream_args('fc32', channels=range(tx_nchan)) self.u_tx = uhd.usrp_sink(device_addr=args, stream_args=stream_args) self.u_tx.set_samp_rate(MAX_RATE) self.tx_src0 = analog.sig_source_c(self.u_tx.get_samp_rate(), analog.GR_CONST_WAVE, 0, 1.0, 0) # Get dboard gain range and select maximum tx_gain_range = self.u_tx.get_gain_range() tx_gain = tx_gain_range.stop() # Get dboard freq range and select midpoint tx_freq_range = self.u_tx.get_freq_range() tx_freq_mid = (tx_freq_range.start() + tx_freq_range.stop())/2.0 for i in xrange(tx_nchan): self.u_tx.set_center_freq (tx_freq_mid + i*1e6, i) self.u_tx.set_gain(tx_gain, i) print "\nTx Sample Rate: %ssps" % (n2s(self.u_tx.get_samp_rate())) for i in xrange(tx_nchan): print "Tx Channel %d: " % (i) print "\tFrequency = %sHz" % \ (n2s(self.u_tx.get_center_freq(i))) print "\tGain = %f dB" % (self.u_tx.get_gain(i)) print "" self.connect (self.tx_src0, self.u_tx) if rx_enable: print "\nRECEIVE CHAIN" self.u_rx = uhd.usrp_source(device_addr=args, io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=rx_nchan) self.rx_dst0 = blocks.null_sink(gr.sizeof_gr_complex) self.u_rx.set_samp_rate(MAX_RATE) # Get dboard gain range and select maximum rx_gain_range = self.u_rx.get_gain_range() rx_gain = rx_gain_range.stop() # Get dboard freq range and select midpoint rx_freq_range = self.u_rx.get_freq_range() rx_freq_mid = (rx_freq_range.start() + rx_freq_range.stop())/2.0 for i in xrange(tx_nchan): self.u_rx.set_center_freq (rx_freq_mid + i*1e6, i) self.u_rx.set_gain(rx_gain, i) print "\nRx Sample Rate: %ssps" % (n2s(self.u_rx.get_samp_rate())) for i in xrange(rx_nchan): print "Rx Channel %d: " % (i) print "\tFrequency = %sHz" % \ (n2s(self.u_rx.get_center_freq(i))) print "\tGain = %f dB" % (self.u_rx.get_gain(i)) print "" self.connect (self.u_rx, self.rx_dst0) def main (): parser = OptionParser (option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("-t", action="store_true", dest="tx_enable", default=False, help="enable Tx path") parser.add_option("-r", action="store_true", dest="rx_enable", default=False, help="enable Rx path") (options, args) = parser.parse_args () tb = build_block (options.args, options.tx_enable, options.rx_enable) tb.start () raw_input ('Press Enter to quit: ') tb.stop () if __name__ == '__main__': main () gnuradio-3.7.2.1/gr-uhd/examples/python/usrp_wfm_rcv_nogui.py0000775000175000017500000001471312207440367024156 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005-2007,2011,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, audio, uhd from gnuradio import blocks from gnuradio import filter from gnuradio import analog from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser import sys class wfm_rx_block (gr.top_block): def __init__(self): gr.top_block.__init__(self) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default=None, help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("-f", "--freq", type="eng_float", default=100.1e6, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-V", "--volume", type="eng_float", default=None, help="set volume (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="default", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) self.state = "FREQ" self.freq = 0 self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph self.u = uhd.usrp_source(device_addr=options.args, stream_args=uhd.stream_args('fc32')) # Set the subdevice spec if(options.spec): self.u.set_subdev_spec(options.spec, 0) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, 0) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 32e3 audio_decim = int(demod_rate / audio_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() nfilts = 32 chan_coeffs = filter.optfir.low_pass(nfilts, # gain nfilts*usrp_rate, # sampling rate 80e3, # passband cutoff 115e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation rrate = usrp_rate / dev_rate self.chan_filt = filter.pfb.arb_resampler_ccf(rrate, chan_coeffs, nfilts) self.guts = analog.wfm_rcv(demod_rate, audio_decim) self.volume_control = blocks.multiply_const_ff(1) # sound card as final sink self.audio_sink = audio.sink(int(audio_rate), options.audio_output, False) # ok_to_block # now wire it all together self.connect(self.u, self.chan_filt, self.guts, self.volume_control, self.audio_sink) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 if options.volume is None: g = self.volume_range() options.volume = float(g[0]+g[1])/2 frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) if(options.freq < self.fm_freq_min or options.freq > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # set initial values self.set_gain(options.gain) self.set_vol(options.volume) if not(self.set_freq(options.freq)): self._set_status_msg("Failed to set initial frequency") def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) self.volume_control.set_k(10**(self.vol/10)) self.update_status_bar () def set_freq(self, target_freq): """ Set the center frequency we're interested in. Args: target_freq: frequency in Hz @rypte: bool """ r = self.u.set_center_freq(target_freq) if r: self.freq = target_freq self.update_status_bar() self._set_status_msg("OK", 0) return True self._set_status_msg("Failed", 0) return False def set_gain(self, gain): self.u.set_gain(gain) def update_status_bar (self): msg = "Freq: %s Volume:%f Setting:%s" % ( eng_notation.num_to_str(self.freq), self.vol, self.state) self._set_status_msg(msg, 1) def _set_status_msg(self, msg, which=0): print msg def volume_range(self): return (-20.0, 0.0, 0.5) if __name__ == '__main__': tb = wfm_rx_block() try: tb.run() except KeyboardInterrupt: pass gnuradio-3.7.2.1/gr-uhd/examples/c++/0000755000175000017500000000000012207440367016703 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-uhd/examples/c++/CMakeLists.txt0000664000175000017500000000303612207440367021447 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${CMAKE_CURRENT_SOURCE_DIR} ${GR_UHD_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${UHD_INCLUDE_DIRS} ) link_directories(${UHD_LIBRARY_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) ######################################################################## # Build executable ######################################################################## add_executable(tags_demo tags_demo.cc) target_link_libraries(tags_demo gnuradio-uhd) INSTALL(TARGETS tags_demo DESTINATION ${GR_PKG_UHD_EXAMPLES_DIR} COMPONENT "uhd_examples" ) gnuradio-3.7.2.1/gr-uhd/examples/c++/tag_source_demo.h0000664000175000017500000001050312207440367022214 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include class tag_source_demo : public gr::sync_block { public: tag_source_demo( const uint64_t start_secs, const double start_fracs, const double samp_rate, const double idle_duration, const double burst_duration ): sync_block( "uhd tag source demo", gr::io_signature::make(0, 0, 0), gr::io_signature::make(1, 1, sizeof(std::complex)) ), _time_secs(start_secs), _time_fracs(start_fracs), _samp_rate(samp_rate), _samps_per_burst(samp_rate*burst_duration), _cycle_duration(idle_duration + burst_duration), _samps_left_in_burst(1), //immediate EOB _do_new_burst(false) { //NOP } void make_time_tag(const uint64_t tag_count) { const pmt::pmt_t key = pmt::string_to_symbol("tx_time"); const pmt::pmt_t value = pmt::make_tuple( pmt::from_uint64(_time_secs), pmt::from_double(_time_fracs) ); const pmt::pmt_t srcid = pmt::string_to_symbol(this->name()); this->add_item_tag(0/*chan0*/, tag_count, key, value, srcid); } void make_sob_tag(const uint64_t tag_count) { const pmt::pmt_t key = pmt::string_to_symbol("tx_sob"); const pmt::pmt_t value = pmt::PMT_T; const pmt::pmt_t srcid = pmt::string_to_symbol(this->name()); this->add_item_tag(0/*chan0*/, tag_count, key, value, srcid); } void make_eob_tag(const uint64_t tag_count) { const pmt::pmt_t key = pmt::string_to_symbol("tx_eob"); const pmt::pmt_t value = pmt::PMT_T; const pmt::pmt_t srcid = pmt::string_to_symbol(this->name()); this->add_item_tag(0/*chan0*/, tag_count, key, value, srcid); } int work( int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { //load the output with a constant std::complex *output = reinterpret_cast *>(output_items[0]); for (size_t i = 0; i < size_t(noutput_items); i++){ output[i] = std::complex(0.7, 0.7); } //Handle the start of burst condition. //Tag a start of burst and timestamp. //Increment the time for the next burst. if (_do_new_burst){ _do_new_burst = false; _samps_left_in_burst = _samps_per_burst; this->make_sob_tag(this->nitems_written(0)); this->make_time_tag(this->nitems_written(0)); _time_fracs += _cycle_duration; double intpart; //normalize _time_fracs = std::modf(_time_fracs, &intpart); _time_secs += uint64_t(intpart); } //Handle the end of burst condition. //Tag an end of burst and return early. //the next work call will be a start of burst. if (_samps_left_in_burst < size_t(noutput_items)){ this->make_eob_tag(this->nitems_written(0) + _samps_left_in_burst - 1); _do_new_burst = true; noutput_items = _samps_left_in_burst; } _samps_left_in_burst -= noutput_items; return noutput_items; } private: uint64_t _time_secs; double _time_fracs; const double _samp_rate; const uint64_t _samps_per_burst; const double _cycle_duration; uint64_t _samps_left_in_burst; bool _do_new_burst; }; gnuradio-3.7.2.1/gr-uhd/examples/c++/tag_sink_demo.h0000664000175000017500000000421412207440367021662 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include class tag_sink_demo : public gr::sync_block { public: tag_sink_demo(void): sync_block( "uhd tag sink demo", gr::io_signature::make(1, 1, sizeof(std::complex)), gr::io_signature::make(0, 0, 0) ) { //NOP } int work( int ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items ){ //grab all "rx time" tags in this work call const uint64_t samp0_count = this->nitems_read(0); std::vector rx_time_tags; get_tags_in_range(rx_time_tags, 0, samp0_count, samp0_count + ninput_items, pmt::string_to_symbol("rx_time")); //print all tags BOOST_FOREACH(const gr::tag_t &rx_time_tag, rx_time_tags){ const uint64_t offset = rx_time_tag.offset; const pmt::pmt_t &value = rx_time_tag.value; std::cout << boost::format("Full seconds %u, Frac seconds %f, abs sample offset %u") % pmt::to_uint64(pmt::tuple_ref(value, 0)) % pmt::to_double(pmt::tuple_ref(value, 1)) % offset << std::endl; } return ninput_items; } }; gnuradio-3.7.2.1/gr-uhd/examples/c++/tags_demo.cc0000664000175000017500000001330112207440367021154 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include //sleep #include #include #include namespace po = boost::program_options; /*********************************************************************** * Signal handlers **********************************************************************/ static bool stop_signal_called = false; void sig_int_handler(int){stop_signal_called = true;} /*********************************************************************** * Main w/ program options **********************************************************************/ int main(int argc, char *argv[]){ std::string device_addr; double center_freq, samp_rate, burst_dur, idle_dur; //setup the program options po::options_description desc("Allowed options"); desc.add_options() ("help", "help message") ("addr", po::value(&device_addr)->default_value(""), "the device address in string format") ("rate", po::value(&samp_rate)->default_value(1e6), "the sample rate in samples per second") ("freq", po::value(¢er_freq)->default_value(10e6), "the center frequency in Hz") ("burst", po::value(&burst_dur)->default_value(0.1), "the duration of each burst in seconds") ("idle", po::value(&idle_dur)->default_value(0.05), "idle time between bursts in seconds") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //print the help message if (vm.count("help")){ std::cout << boost::format("UHD Tags Demo %s") % desc << std::endl << "The tags sink demo block will print USRP source time stamps." << std::endl << "The tags source demo block will send bursts to the USRP sink." << std::endl << "Look at the USRP output on a scope to see the timed bursts." << std::endl << std::endl; return ~0; } //------------------------------------------------------------------ //-- make a top block //------------------------------------------------------------------ gr::top_block_sptr tb = gr::make_top_block("tags_demo"); //------------------------------------------------------------------ //-- make the usrp source test blocks //------------------------------------------------------------------ gr::uhd::usrp_source::sptr usrp_source = gr::uhd::usrp_source::make (device_addr, uhd::stream_args_t("fc32")); usrp_source->set_samp_rate(samp_rate); usrp_source->set_center_freq(center_freq); boost::shared_ptr tag_sink = boost::make_shared(); //------------------------------------------------------------------ //-- connect the usrp source test blocks //------------------------------------------------------------------ tb->connect(usrp_source, 0, tag_sink, 0); //------------------------------------------------------------------ //-- make the usrp sink test blocks //------------------------------------------------------------------ gr::uhd::usrp_sink::sptr usrp_sink = gr::uhd::usrp_sink::make (device_addr, uhd::stream_args_t("fc32")); usrp_sink->set_samp_rate(samp_rate); usrp_sink->set_center_freq(center_freq); const uhd::time_spec_t time_now = usrp_sink->get_time_now(); boost::shared_ptr tag_source = boost::make_shared( time_now.get_full_secs() + 1, time_now.get_frac_secs(), //time now + 1 second samp_rate, idle_dur, burst_dur ); //------------------------------------------------------------------ //-- connect the usrp sink test blocks //------------------------------------------------------------------ tb->connect(tag_source, 0, usrp_sink, 0); //------------------------------------------------------------------ //-- start flow graph execution //------------------------------------------------------------------ std::cout << "starting flow graph" << std::endl; tb->start(); //------------------------------------------------------------------ //-- poll the exit signal while running //------------------------------------------------------------------ std::signal(SIGINT, &sig_int_handler); std::cout << "press ctrl + c to exit" << std::endl; while (not stop_signal_called){ boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } //------------------------------------------------------------------ //-- stop flow graph execution //------------------------------------------------------------------ std::cout << "stopping flow graph" << std::endl; tb->stop(); tb->wait(); std::cout << "done!" << std::endl; return 0; } gnuradio-3.7.2.1/gr-vocoder/0000755000175000017500000000000012207440367015376 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/CMakeLists.txt0000664000175000017500000000732112207440367020143 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-vocoder" ENABLE_GR_VOCODER Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_FFT ENABLE_GR_BLOCKS ENABLE_GR_FILTER ENABLE_GR_ANALOG ) GR_SET_GLOBAL(GR_VOCODER_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) SET(GR_PKG_VOCODER_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/vocoder) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_VOCODER) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_VOCODER_DESCRIPTION "GNU Radio Vocoder Blocks") CPACK_COMPONENT("vocoder_runtime" GROUP "Vocoder" DISPLAY_NAME "Runtime" DESCRIPTION "Dynamic link libraries" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("vocoder_devel" GROUP "Vocoder" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("vocoder_python" GROUP "Vocoder" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime" DEPENDS "runtime_python;vocoder_runtime" ) CPACK_COMPONENT("vocoder_examples" GROUP "Vocoder" DISPLAY_NAME "Examples" DESCRIPTION "Python examples for vocoder" DEPENDS "vocoder_python" ) CPACK_COMPONENT("vocoder_swig" GROUP "Vocoder" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;vocoder_python;vocoder_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/vocoder) add_subdirectory(lib) add_subdirectory(doc) if(ENABLE_PYTHON) add_subdirectory(swig) add_subdirectory(python/vocoder) add_subdirectory(grc) add_subdirectory(examples) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-vocoder.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-vocoder.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-vocoder.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "vocoder_devel" ) endif(ENABLE_GR_VOCODER) gnuradio-3.7.2.1/gr-vocoder/include/0000775000175000017500000000000012207440367017023 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/include/gnuradio/0000775000175000017500000000000012207440367020633 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/0000775000175000017500000000000012207440367022274 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/CMakeLists.txt0000664000175000017500000000261012207440367025033 0ustar jcorganjcorgan# Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h alaw_decode_bs.h alaw_encode_sb.h codec2_decode_ps.h codec2_encode_sp.h cvsd_decode_bs.h cvsd_encode_sb.h g721_decode_bs.h g721_encode_sb.h g723_24_decode_bs.h g723_24_encode_sb.h g723_40_decode_bs.h g723_40_encode_sb.h gsm_fr_decode_ps.h gsm_fr_encode_sp.h ulaw_decode_bs.h ulaw_encode_sb.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/vocoder COMPONENT "vocoder_devel" ) gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/alaw_decode_bs.h0000664000175000017500000000272612207440367025367 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ALAW_DECODE_BS_H #define INCLUDED_VOCODER_ALAW_DECODE_BS_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs alaw audio decoding. * \ingroup audio_blk */ class VOCODER_API alaw_decode_bs : virtual public sync_block { public: // gr::vocoder::alaw_decode_bs::sptr typedef boost::shared_ptr sptr; /*! * \brief Make alaw decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ALAW_DECODE_BS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/g721_decode_bs.h0000664000175000017500000000272612207440367025123 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G721_DECODE_BS_H #define INCLUDED_VOCODER_G721_DECODE_BS_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g721 audio decoding. * \ingroup audio_blk */ class VOCODER_API g721_decode_bs : virtual public sync_block { public: // gr::vocoder::g721_decode_bs::sptr typedef boost::shared_ptr sptr; /*! * \brief Make G721 decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G721_DECODE_BS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/g721_encode_sb.h0000664000175000017500000000272612207440367025135 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G721_ENCODE_SB_H #define INCLUDED_VOCODER_G721_ENCODE_SB_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g721 audio encoding. * \ingroup audio_blk */ class VOCODER_API g721_encode_sb : virtual public sync_block { public: // gr::vocoder::g721_encode_sb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make G721 encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G721_ENCODE_SB_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/cvsd_encode_sb.h0000664000175000017500000001403212207440367025405 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CVSD_ENCODER_SB_H #define INCLUDED_VOCODER_CVSD_ENCODER_SB_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs CVSD audio encoding. Its design and * implementation is modeled after the CVSD encoder/decoder * specifications defined in the Bluetooth standard. * \ingroup audio_blk * * \details * CVSD is a method for encoding speech that seeks to reduce the * bandwidth required for digital voice transmission. CVSD takes * advantage of strong correlation between samples, quantizing the * difference in amplitude between two consecutive samples. This * difference requires fewer quantization levels as compared to * other methods that quantize the actual amplitude level, * reducing the bandwidth. CVSD employs a two level quantizer * (one bit) and an adaptive algorithm that allows for continuous * step size adjustment. * * The coder can represent low amplitude signals with accuracy * without sacrificing performance on large amplitude signals, a * trade off that occurs in some non-adaptive modulations. * * The CVSD encoder effectively provides 8-to-1 compression. More * specifically, each incoming audio sample is compared to an * internal reference value. If the input is greater or equal to * the reference, the encoder outputs a "1" bit. If the input is * less than the reference, the encoder outputs a "0" bit. The * reference value is then updated accordingly based on the * frequency of outputted "1" or "0" bits. By grouping 8 outputs * bits together, the encoder essentially produce one output byte * for every 8 input audio samples. * * This encoder requires that input audio samples are 2-byte short * signed integers. The result bandwidth conversion, therefore, * is 16 input bytes of raw audio data to 1 output byte of encoded * audio data. * * The CVSD encoder module must be prefixed by an up-converter to * over-sample the audio data prior to encoding. The Bluetooth * standard specifically calls for a 1-to-8 interpolating * up-converter. While this reduces the overall compression of * the codec, this is required so that the encoder can accurately * compute the slope between adjacent audio samples and correctly * update its internal reference value. * * References: * * 1. Continuously Variable Slope Delta Modulation (CVSD) A Tutorial, * Available: http://www.eetkorea.com/ARTICLES/2003AUG/A/2003AUG29_NTEK_RFD_AN02.PDF. * * 2. Specification of The Bluetooth System * Available: http://grouper.ieee.org/groups/802/15/Bluetooth/core_10_b.pdf. * * 3. McGarrity, S., Bluetooth Full Duplex Voice and Data Transmission. 2002. * Bluetooth Voice Simulink Model, Available: * http://www.mathworks.com/company/newsletters/digest/nov01/bluetooth.html */ class VOCODER_API cvsd_encode_sb : virtual public sync_decimator { public: // gr::vocoder::cvsd_encode_sb::sptr typedef boost::shared_ptr sptr; /*! * \brief Constructor parameters to initialize the CVSD encoder. * The default values are modeled after the Bluetooth standard and * should not be changed except by an advanced user * * \param min_step Minimum step size used to update the internal reference. Default: "10" * \param max_step Maximum step size used to update the internal reference. Default: "1280" * \param step_decay Decay factor applied to step size when there is not a run of J output 1s or 0s. * Default: "0.9990234375" (i.e. 1-1/1024) * \param accum_decay Decay factor applied to the internal reference during every interation of the codec. * Default: "0.96875" (i.e. 1-1/32) * \param K; Size of shift register; the number of output bits remembered by codec (must be <= to 32). * Default: "32" * \param J; Number of bits in the shift register that are equal; i.e. the size of a run of 1s, 0s. * Default: "4" * \param pos_accum_max Maximum integer value allowed for the internal reference. * Default: "32767" (2^15 - 1 or MAXSHORT) * \param neg_accum_max Minimum integer value allowed for the internal reference. * Default: "-32767" (-2^15 + 1 or MINSHORT+1) */ static sptr make(short min_step=10, short max_step=1280, double step_decay=0.9990234375, double accum_decay= 0.96875, int K=32, int J=4, short pos_accum_max=32767, short neg_accum_max=-32767); virtual short min_step() = 0; virtual short max_step() = 0; virtual double step_decay() = 0; virtual double accum_decay() = 0; virtual int K() = 0; virtual int J() = 0; virtual short pos_accum_max() = 0; virtual short neg_accum_max() = 0; }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CVSD_ENCODE_SB_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/gsm_fr_encode_sp.h0000664000175000017500000000303512207440367025742 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_GSM_FR_ENCODE_SP_H #define INCLUDED_VOCODER_GSM_FR_ENCODE_SP_H #include #include namespace gr { namespace vocoder { /*! * \brief GSM 06.10 Full Rate Vocoder Encoder * \ingroup audio_blk * * shorts in; 33 byte packets out */ class VOCODER_API gsm_fr_encode_sp : virtual public sync_decimator { public: // gr::vocoder::gsm_fr_encode_sp::sptr typedef boost::shared_ptr sptr; /*! * \brief Make GSM encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_GSM_FR_ENCODE_SP_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/gsm_fr_decode_ps.h0000664000175000017500000000275712207440367025742 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_GSM_FR_DECODE_PS_H #define INCLUDED_VOCODER_GSM_FR_DECODE_PS_H #include #include namespace gr { namespace vocoder { /*! * \brief GSM 06.10 Full Rate Vocoder Decoder * \ingroup audio_blk */ class VOCODER_API gsm_fr_decode_ps : virtual public sync_interpolator { public: // gr::vocoder::gsm_fr_decode_ps::sptr typedef boost::shared_ptr sptr; /*! * \brief Make GSM decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_GSM_FR_DECODE_PS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/cvsd_decode_bs.h0000664000175000017500000001421512207440367025376 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CVSD_DECODE_BS_H #define INCLUDED_VOCODER_CVSD_DECODE_BS_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs CVSD audio decoding. Its design and * implementation is modeled after the CVSD encoder/decoder * specifications defined in the Bluetooth standard. * \ingroup audio_blk * * \details * CVSD is a method for encoding speech that seeks to reduce the * bandwidth required for digital voice transmission. CVSD takes * advantage of strong correlation between samples, quantizing the * difference in amplitude between two consecutive samples. This * difference requires fewer quantization levels as compared to * other methods that quantize the actual amplitude level, * reducing the bandwidth. CVSD employs a two level quantizer * (one bit) and an adaptive algorithm that allows for continuous * step size adjustment. * * The coder can represent low amplitude signals with accuracy * without sacrificing performance on large amplitude signals, a * trade off that occurs in some non-adaptive modulations. * * The CVSD decoder effectively provides 1-to-8 decompression. * More specifically, for each incoming input bit, the decoder * outputs one audio sample. If the input is a "1" bit, the * internal reference is increased appropriately and then * outputted as the next estimated audio sample. If the input is * a "0" bit, the internal reference is decreased appropriately * and then likewise outputted as the next estimated audio sample. * Grouping 8 input bits together, the encoder essentially * produces 8 output audio samples for everyone one input byte. * * This decoder requires that output audio samples are 2-byte * short signed integers. The result bandwidth conversion, * therefore, is 1 byte of encoded audio data to 16 output bytes * of raw audio data. * * The CVSD decoder module must be post-fixed by a down-converter * to under-sample the audio data after decoding. The Bluetooth * standard specifically calls for a 8-to-1 decimating * down-converter. This is required so that so that output * sampling rate equals the original input sampling rate present * before the encoder. In all cases, the output down-converter * rate must be the inverse of the input up-converter rate before * the CVSD encoder. * * References: * 1. Continuously Variable Slope Delta Modulation (CVSD) A Tutorial, * Available: http://www.eetkorea.com/ARTICLES/2003AUG/A/2003AUG29_NTEK_RFD_AN02.PDF. * 2. Specification of The Bluetooth System * Available: http://grouper.ieee.org/groups/802/15/Bluetooth/core_10_b.pdf. * 3. McGarrity, S., Bluetooth Full Duplex Voice and Data Transmission. 2002. * Bluetooth Voice Simulink Model, Available: * http://www.mathworks.com/company/newsletters/digest/nov01/bluetooth.html */ class VOCODER_API cvsd_decode_bs : virtual public sync_interpolator { public: // gr::vocoder::cvsd_decode_bs::sptr typedef boost::shared_ptr sptr; /*! * \brief Constructor parameters to initialize the CVSD decoder. * The default values are modeled after the Bluetooth standard * and should not be changed, except by an advanced user * * \param min_step Minimum step size used to update the internal reference. * Default: "10" * \param max_step Maximum step size used to update the internal reference. * Default: "1280" * \param step_decay Decay factor applied to step size when there is not a run of J output 1s or 0s. * Default: "0.9990234375" (i.e. 1-1/1024) * \param accum_decay Decay factor applied to the internal reference during every interation of the codec. * Default: "0.96875" (i.e. 1-1/32) * \param K; Size of shift register; the number of output bits remembered by codec (must be <= to 32). * Default: "32" * \param J; Number of bits in the shift register that are equal; i.e. the size of a run of 1s, 0s. * Default: "4" * \param pos_accum_max Maximum integer value allowed for the internal reference. * Default: "32767" (2^15 - 1 or MAXSHORT) * \param neg_accum_max Minimum integer value allowed for the internal reference. * Default: "-32767" (-2^15 + 1 or MINSHORT+1) */ static sptr make(short min_step=10, short max_step=1280, double step_decay=0.9990234375, double accum_decay= 0.96875, int K=32, int J=4, short pos_accum_max=32767, short neg_accum_max=-32767); virtual short min_step() = 0; virtual short max_step() = 0; virtual double step_decay() = 0; virtual double accum_decay() = 0; virtual int K() = 0; virtual int J() = 0; virtual short pos_accum_max() = 0; virtual short neg_accum_max() = 0; }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CVSD_DECODE_BS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/g723_40_encode_sb.h0000664000175000017500000000275612207440367025445 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_40_ENCODE_SB_H #define INCLUDED_VOCODER_G723_40_ENCODE_SB_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g723_40 audio encoding. * \ingroup audio_blk */ class VOCODER_API g723_40_encode_sb : virtual public sync_block { public: // gr::vocoder::g723_40_encode_sb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make G722_40 encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_40_ENCODE_SB_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/ulaw_decode_bs.h0000664000175000017500000000272612207440367025413 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ULAW_DECODE_BS_H #define INCLUDED_VOCODER_ULAW_DECODE_BS_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs ulaw audio decoding. * \ingroup audio_blk */ class VOCODER_API ulaw_decode_bs : virtual public sync_block { public: // gr::vocoder::ulaw_decode_bs::sptr typedef boost::shared_ptr sptr; /*! * \brief Make ulaw decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ULAW_DECODE_BS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/g723_40_decode_bs.h0000664000175000017500000000275612207440367025433 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_40_DECODE_BS_H #define INCLUDED_VOCODER_G723_40_DECODE_BS_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g723_40 audio decoding. * \ingroup audio_blk */ class VOCODER_API g723_40_decode_bs : virtual public sync_block { public: // gr::vocoder::g723_40_decode_bs::sptr typedef boost::shared_ptr sptr; /*! * \brief Make G722_40 decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_40_DECODE_BS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/codec2_encode_sp.h0000664000175000017500000000273212207440367025627 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CODEC2_ENCODE_SP_H #define INCLUDED_VOCODER_CODEC2_ENCODE_SP_H #include #include namespace gr { namespace vocoder { /*! * \brief CODEC2 Vocoder Encoder * \ingroup audio_blk */ class VOCODER_API codec2_encode_sp : virtual public sync_decimator { public: // gr::vocoder::codec2_encode_sp::sptr typedef boost::shared_ptr sptr; /*! * \brief Make Codec2 encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CODEC2_ENCODE_SP_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/g723_24_decode_bs.h0000664000175000017500000000275612207440367025435 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_24_DECODE_BS_H #define INCLUDED_VOCODER_G723_24_DECODE_BS_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g723_24 audio decoding. * \ingroup audio_blk */ class VOCODER_API g723_24_decode_bs : virtual public sync_block { public: // gr::vocoder::g723_24_decode_bs::sptr typedef boost::shared_ptr sptr; /*! * \brief Make G722_24 decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_24_DECODE_BS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/g723_24_encode_sb.h0000664000175000017500000000275612207440367025447 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_24_ENCODE_SB_H #define INCLUDED_VOCODER_G723_24_ENCODE_SB_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g723_24 audio encoding. * \ingroup audio_blk */ class VOCODER_API g723_24_encode_sb : virtual public sync_block { public: // gr::vocoder::g723_24_encode_sb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make G722_24 encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_24_ENCODE_SB_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/alaw_encode_sb.h0000664000175000017500000000273612207440367025402 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011.2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ALAW_ENCODER_SB_H #define INCLUDED_VOCODER_ALAW_ENCODER_SB_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g.711 alaw audio encoding. * \ingroup audio_blk */ class VOCODER_API alaw_encode_sb : virtual public sync_block { public: // gr::vocoder::alaw_encode_sb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make alaw encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ALAW_ENCODE_SB_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/codec2_decode_ps.h0000664000175000017500000000274012207440367025614 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CODEC2_DECODE_PS_H #define INCLUDED_VOCODER_CODEC2_DECODE_PS_H #include #include namespace gr { namespace vocoder { /*! * \brief CODEC2 Vocoder Decoder * \ingroup audio_blk */ class VOCODER_API codec2_decode_ps : virtual public sync_interpolator { public: // gr::vocoder::codec2_decode_ps::sptr typedef boost::shared_ptr sptr; /*! * \brief Make Codec2 decoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CODEC2_DECODE_PS_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/ulaw_encode_sb.h0000664000175000017500000000273612207440367025426 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ULAW_ENCODER_SB_H #define INCLUDED_VOCODER_ULAW_ENCODER_SB_H #include #include namespace gr { namespace vocoder { /*! * \brief This block performs g.711 ulaw audio encoding. * \ingroup audio_blk */ class VOCODER_API ulaw_encode_sb : virtual public sync_block { public: // gr::vocoder::ulaw_encode_sb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make ulaw encoder block. */ static sptr make(); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ULAW_ENCODE_SB_H */ gnuradio-3.7.2.1/gr-vocoder/include/gnuradio/vocoder/api.h0000664000175000017500000000204512207440367023217 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_API_H #define INCLUDED_VOCODER_API_H #include #ifdef gnuradio_vocoder_EXPORTS # define VOCODER_API __GR_ATTR_EXPORT #else # define VOCODER_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_VOCODER_API_H */ gnuradio-3.7.2.1/gr-vocoder/grc/0000755000175000017500000000000012207440367016151 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/grc/vocoder_ulaw_encode_sb.xml0000644000175000017500000000067711716531255023400 0ustar jcorganjcorgan ulaw Audio Encoder vocoder_ulaw_encode_sb from gnuradio import vocoder vocoder.ulaw_encode_sb() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_codec2_decode_ps.xml0000644000175000017500000000070511716531255023563 0ustar jcorganjcorgan CODEC2 Audio Decoder vocoder_codec2_decode_ps from gnuradio import vocoder vocoder.codec2_decode_ps() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_codec2_encode_sp.xml0000644000175000017500000000070711716531255023577 0ustar jcorganjcorgan CODEC2 Audio Encoder vocoder_codec2_encode_sp from gnuradio import vocoder vocoder.codec2_encode_sp() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/CMakeLists.txt0000644000175000017500000000266311716531255020721 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install(FILES vocoder_alaw_decode_bs.xml vocoder_alaw_encode_sb.xml vocoder_block_tree.xml vocoder_codec2_decode_ps.xml vocoder_codec2_encode_sp.xml vocoder_cvsd_decode_bs.xml vocoder_cvsd_decode.xml vocoder_cvsd_encode_sb.xml vocoder_cvsd_encode.xml vocoder_g721_decode_bs.xml vocoder_g721_encode_sb.xml vocoder_g723_24_decode_bs.xml vocoder_g723_24_encode_sb.xml vocoder_g723_40_decode_bs.xml vocoder_g723_40_encode_sb.xml vocoder_gsm_fr_decode_ps.xml vocoder_gsm_fr_encode_sp.xml vocoder_ulaw_decode_bs.xml vocoder_ulaw_encode_sb.xml DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "vocoder_python" ) gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_gsm_fr_encode_sp.xml0000644000175000017500000000072511717535431023716 0ustar jcorganjcorgan GSM full-rate Audio Encoder vocoder_gsm_fr_encode_sp from gnuradio import vocoder vocoder.gsm_fr_encode_sp() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_g723_40_encode_sb.xml0000644000175000017500000000071311716531255023404 0ustar jcorganjcorgan g723_40 Audio Encoder vocoder_g723_40_encode_sb from gnuradio import vocoder vocoder.g723_40_encode_sb() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_alaw_encode_sb.xml0000664000175000017500000000070412207440367023344 0ustar jcorganjcorgan g711 Alaw Audio Encoder vocoder_alaw_encode_sb from gnuradio import vocoder vocoder.alaw_encode_sb() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_cvsd_decode_bs.xml0000644000175000017500000000071611716531255023347 0ustar jcorganjcorgan CVSD Audio Decoder (Raw Bit-Level) vocoder_cvsd_decode_bs from gnuradio import vocoder vocoder.cvsd_decode_bs() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_ulaw_decode_bs.xml0000664000175000017500000000067512207440367023365 0ustar jcorganjcorgan ulaw Audio Decoder vocoder_ulaw_decode_bs from gnuradio import vocoder vocoder.ulaw_decode_bs() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_gsm_fr_decode_ps.xml0000644000175000017500000000072311717535444023706 0ustar jcorganjcorgan GSM full-rate Audio Decoder vocoder_gsm_fr_decode_ps from gnuradio import vocoder vocoder.gsm_fr_decode_ps() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_cvsd_encode.xml0000644000175000017500000000123011716531255022665 0ustar jcorganjcorgan CVSD Encoder vocoder_cvsd_encode_fb from gnuradio import vocoder vocoder.cvsd_encode_fb($resample,$bw) Resample resample 8 int Frac. Bandwidth bw 0.5 real in float out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_cvsd_encode_sb.xml0000644000175000017500000000071711716531255023362 0ustar jcorganjcorgan CVSD Audio Encoder (Raw Bit-Level) vocoder_cvsd_encode_sb from gnuradio import vocoder vocoder.cvsd_encode_sb() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_block_tree.xml0000664000175000017500000000336012207440367022531 0ustar jcorganjcorgan Audio vocoder_alaw_decode_bs vocoder_alaw_encode_sb vocoder_codec2_decode_ps vocoder_codec2_encode_sp vocoder_cvsd_decode_bs vocoder_cvsd_encode_sb vocoder_cvsd_decode_bf vocoder_cvsd_encode_fb vocoder_g721_decode_bs vocoder_g721_encode_sb vocoder_g723_24_decode_bs vocoder_g723_24_encode_sb vocoder_g723_40_decode_bs vocoder_g723_40_encode_sb vocoder_gsm_fr_decode_ps vocoder_gsm_fr_encode_sp vocoder_ulaw_decode_bs vocoder_ulaw_encode_sb gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_g721_encode_sb.xml0000644000175000017500000000067711716531255023110 0ustar jcorganjcorgan g721 Audio Encoder vocoder_g721_encode_sb from gnuradio import vocoder vocoder.g721_encode_sb() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_g723_40_decode_bs.xml0000644000175000017500000000071111717513013023361 0ustar jcorganjcorgan g723_40 Audio Decoder vocoder_g723_40_decode_bs from gnuradio import vocoder vocoder.g723_40_decode_bs() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_g723_24_encode_sb.xml0000644000175000017500000000071311716531255023406 0ustar jcorganjcorgan g723_24 Audio Encoder vocoder_g723_24_encode_sb from gnuradio import vocoder vocoder.g723_24_encode_sb() in short out byte gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_cvsd_decode.xml0000644000175000017500000000123011716531255022653 0ustar jcorganjcorgan CVSD Decoder vocoder_cvsd_decode_bf from gnuradio import vocoder vocoder.cvsd_decode_bf($resample,$bw) Resample resample 8 int Frac. Bandwidth bw 0.5 real in byte out float gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_alaw_decode_bs.xml0000644000175000017500000000067511716531255023340 0ustar jcorganjcorgan Alaw Audio Decoder vocoder_alaw_decode_bs from gnuradio import vocoder vocoder.alaw_decode_bs() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_g723_24_decode_bs.xml0000644000175000017500000000071111717512767023402 0ustar jcorganjcorgan g723_24 Audio Decoder vocoder_g723_24_decode_bs from gnuradio import vocoder vocoder.g723_24_decode_bs() in byte out short gnuradio-3.7.2.1/gr-vocoder/grc/vocoder_g721_decode_bs.xml0000644000175000017500000000067511717512717023077 0ustar jcorganjcorgan g721 Audio Decoder vocoder_g721_decode_bs from gnuradio import vocoder vocoder.g721_decode_bs() in byte out short gnuradio-3.7.2.1/gr-vocoder/doc/0000755000175000017500000000000012207440367016143 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/doc/README.vocoder0000644000175000017500000000065111744612271020465 0ustar jcorganjcorganThis is the gr-vocoder package. This package includes the various vocoder blocks in GNU Radio. To use the vocoder blocks, the Python namespaces is in gnuradio.vocoder, which would be normally imported as: from gnuradio import vocoder See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: help(vocoder) gnuradio-3.7.2.1/gr-vocoder/doc/CMakeLists.txt0000644000175000017500000000152111744612271020702 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install( FILES README.vocoder DESTINATION ${GR_PKG_DOC_DIR} ) gnuradio-3.7.2.1/gr-vocoder/doc/vocoder.dox0000664000175000017500000000076712207440367020334 0ustar jcorganjcorgan/*! \page page_vocoder Voice Coders and Decoders (Vocoders) \section Introduction This is the gr-vocoder package. It contains all available vocoders in GNU Radio. The Python namespaces is in gnuradio.vocoder, which would be normally imported as: \code from gnuradio import vocoder \endcode See the Doxygen documentation for details about the blocks available in this package. A quick listing of the details can be found in Python after importing by using: \code help(vocoder) \endcode */ gnuradio-3.7.2.1/gr-vocoder/python/0000775000175000017500000000000012207440367016721 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/python/vocoder/0000775000175000017500000000000012207440367020362 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/python/vocoder/CMakeLists.txt0000664000175000017500000000334112207440367023123 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup python install ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py cvsd.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/vocoder COMPONENT "vocoder_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-vocoder/python/vocoder/cvsd.py0000664000175000017500000000674512207440367021707 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, filter, blocks import vocoder_swig class cvsd_encode_fb(gr.hier_block2): ''' This is a wrapper for the CVSD encoder that performs interpolation and filtering necessary to work with the vocoding. It converts an incoming float (+-1) to a short, scales it (to 32000; slightly below the maximum value), interpolates it, and then vocodes it. The incoming sampling rate can be anything, though, of course, the higher the sampling rate and the higher the interpolation rate are, the better the sound quality. ''' def __init__(self, resample=8, bw=0.5): ''' When using the CVSD vocoder, appropriate sampling rates are from 8k to 64k with resampling rates from 1 to 8. A rate of 8k with a resampling rate of 8 provides a good quality signal. ''' gr.hier_block2.__init__(self, "cvsd_encode", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_char)) # Output signature scale_factor = 32000.0 self.interp = resample src_scale = blocks.multiply_const_ff(scale_factor) taps = filter.firdes.low_pass(self.interp, self.interp, bw, 2*bw) interp = filter.interp_fir_filter_fff(self.interp, taps) f2s = blocks.float_to_short() enc = vocoder_swig.cvsd_encode_sb() self.connect(self, src_scale, interp, f2s, enc, self) class cvsd_decode_bf(gr.hier_block2): ''' This is a wrapper for the CVSD decoder that performs decimation and filtering necessary to work with the vocoding. It converts an incoming CVSD-encoded short to a float, decodes it to a float, decimates it, and scales it (by 32000; slightly below the maximum value to avoid clipping). The sampling rate can be anything, though, of course, the higher the sampling rate and the higher the interpolation rate are, the better the sound quality. ''' def __init__(self, resample=8, bw=0.5): ''' When using the CVSD vocoder, appropriate sampling rates are from 8k to 64k with resampling rates from 1 to 8. A rate of 8k with a resampling rate of 8 provides a good quality signal. ''' gr.hier_block2.__init__(self, "cvsd_decode", gr.io_signature(1, 1, gr.sizeof_char), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature scale_factor = 32000.0 self.decim = resample dec = vocoder_swig.cvsd_decode_bs() s2f = blocks.short_to_float() taps = filter.firdes.low_pass(1, 1, bw, 2*bw) decim = filter.fir_filter_fff(self.decim, taps) sink_scale = blocks.multiply_const_ff(1.0/scale_factor) self.connect(self, dec, s2f, decim, sink_scale, self) gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_ulaw_vocoder.py0000775000175000017500000000303712207440367024114 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_ulaw_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): data = (8,24,40,56,72,88,104,120,132,148,164,180, 196,212,228,244,260,276,292,308,324,340) src = blocks.vector_source_s(data) enc = vocoder.ulaw_encode_sb() dec = vocoder.ulaw_decode_bs() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(data, actual_result) if __name__ == '__main__': gr_unittest.run(test_ulaw_vocoder, "test_ulaw_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_cvsd_vocoder.py0000775000175000017500000001340712207440367024105 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2010,2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks, filter from gnuradio.vocoder import cvsd class test_cvsd_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): raw_enc = vocoder.cvsd_encode_sb() raw_dec = vocoder.cvsd_decode_bs() hb_enc = cvsd.cvsd_encode_fb() hb_dec = cvsd.cvsd_decode_bf() """ Disable for now def test01(self): sample_rate = 8000 scale_factor = 32000 expected_data = (6.9670547250243192e-21, -2.4088578356895596e-05, -5.1261918997624889e-05, 7.2410854045301676e-05, 8.444241393590346e-05, -1.2537107068055775e-05, 0.00024186755763366818, -0.00060463894624263048, 0.00064864184241741896, 0.010409165173768997, 0.0087582804262638092, 0.017965050414204597, 0.010722399689257145, 0.006602009292691946, 0.02213001623749733, 0.0079685859382152557, 0.033707316964864731, 0.027021972462534904, 0.0086071854457259178, 0.0081678871065378189, 0.039343506097793579, 0.030671956017613411, 0.029626710340380669, 0.020126519724726677, 0.023636780679225922, 0.0064640454947948456, -0.0038861562497913837, 0.0021134600974619389, -0.0088051930069923401, -0.00023228264763019979, -0.033737499266862869, -0.033141419291496277, -0.037145044654607773, -0.0080892946571111679, -0.077117636799812317, -0.078382067382335663, -0.055503919720649719, -0.019355267286300659, -0.022441385313868523, -0.073706060647964478, -0.054677654057741165, -0.047119375318288803, -0.044418536126613617, -0.036084383726119995, -0.0206278245896101, -0.031200021505355835, -0.0004070434661116451, 0.0006594572332687676, -0.016584658995270729, 0.07387717068195343, -0.0063191778026521206, 0.051200628280639648, -0.029480356723070145, 0.05176771804690361, 0.038578659296035767, 0.026550088077783585, 0.067103870213031769, 0.001888439292088151, 0.28141644597053528, 0.49543789029121399, 0.6626054048538208, 0.79180729389190674, 0.89210402965545654, 0.96999943256378174, 1.0261462926864624, 1.0267977714538574, 1.0251555442810059, 1.0265737771987915, 1.0278496742248535, 1.0208886861801147, 1.0325057506561279, 0.91415292024612427, 0.83941859006881714, 0.67373806238174438, 0.51683622598648071, 0.38949671387672424, 0.16016888618469238, 0.049505095928907394, -0.16699212789535522, -0.26886492967605591, -0.49256673455238342, -0.59178370237350464, -0.73317724466323853, -0.78922677040100098, -0.88782668113708496, -0.96708977222442627, -0.96490746736526489, -0.94962418079376221, -0.94716215133666992, -0.93755108118057251, -0.84852480888366699, -0.80485564470291138, -0.69762390851974487, -0.58398681879043579, -0.45891636610031128, -0.29681697487831116, -0.16035343706607819, 0.014823081903159618, 0.16282452642917633, 0.33802291750907898) # WARNING: not importing analog in this QA code. # If we enable this, we can probably just create a sin with numpy. src = analog.sig_source_f(sample_rate, analog.GR_SIN_WAVE, 200, 1, 0) head = blocks.head(gr.sizeof_float, 100) src_scale = blocks.multiply_const_ff(scale_factor) interp = filter.rational_resampler_fff(8, 1) f2s = blocks.float_to_short() enc = vocoder.cvsd_vocoder.encode_sb() dec = vocoder.cvsd_vocoder.decode_bs() s2f = blocks.short_to_float() decim = filter.rational_resampler_fff(1, 8) sink_scale = blocks.multiply_const_ff(1.0/scale_factor) sink = blocks.vector_sink_f() self.tb.connect(src, src_scale, interp, f2s, enc) self.tb.connect(enc, dec, s2f, decim, sink_scale, head, sink) self.tb.run() print sink.data() self.assertFloatTuplesAlmostEqual (expected_data, sink.data(), 5) """ if __name__ == '__main__': gr_unittest.run(test_cvsd_vocoder, "test_cvsd_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_gsm_full_rate.py0000775000175000017500000000472512207440367024253 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2007,2010,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_gsm_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test001_module_load (self): data = 20*(100,200,300,400,500,600,700,800) expected_data = (0,0,360,304,256,720,600,504,200,144,128,464, 376,384,680,576,440,264,176,176,640,520,480, 464,384,288,432,296,328,760,624,504,176,96,96, 416,312,360,808,672,216,104,136,504,376,448, 720,608,296,304,176,336,576,456,560,512,320, 216,344,264,456,672,576,488,192,80,152,424, 368,552,688,560,280,200,104,256,520,464,608, 488,184,104,16,472,456,360,696,568,208,136,88, 376,480,456,616,472,232,224,264,320,512,624, 632,520,176,80,192,304,400,592,664,552,248,152, 144,336,440,520,616,664,304,176,80,536,448,376, 680,600,240,168,112,408,488,472,608,480,240,232, 208,288,480,600,616,520,176,88,184,296,392,584, 656,552,248,160,144,336,432,512,608,664) src = blocks.vector_source_s(data) enc = vocoder.gsm_fr_encode_sp() dec = vocoder.gsm_fr_decode_ps() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(expected_data, actual_result) if __name__ == '__main__': gr_unittest.run(test_gsm_vocoder, "test_gsm_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_alaw_vocoder.py0000775000175000017500000000305012207440367024063 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_alaw_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): data = (8,24,40,56,72,88,104,120,136,152,168,184, 200,216,232,248,264,280,296,312,328,344) src = blocks.vector_source_s(data) enc = vocoder.alaw_encode_sb() dec = vocoder.alaw_decode_bs() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(data, actual_result) if __name__ == '__main__': gr_unittest.run(test_alaw_vocoder, "test_alaw_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_g723_24_vocoder.py0000775000175000017500000000275612207440367024142 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_g723_24_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): data = (0,16,36,40,68,104,148,220,320,512) src = blocks.vector_source_s(data) enc = vocoder.g723_24_encode_sb() dec = vocoder.g723_24_decode_bs() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(data, actual_result) if __name__ == '__main__': gr_unittest.run(test_g723_24_vocoder, "test_g723_24_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/__init__.py0000664000175000017500000000215412207440367022475 0ustar jcorganjcorgan# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' This is the gr-vocoder package. This package includes the various vocoder blocks in GNU Radio. ''' import os try: from vocoder_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from vocoder_swig import * from cvsd import * gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_codec2_vocoder.py0000775000175000017500000000456412207440367024311 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_codec2_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): data = 20*(100,200,300,400,500,600,700,800) expected_data = (0,0,0,3,2,0,1,5,6,7,1,-1,0,-5,-11,-10,-20,-22, -20,-20,-27,-26,-36,-48,-59,-24,5,-7,-12,-27,-22, -22,-16,13,20,39,23,25,8,-6,15,44,97,135,145,125, 94,102,126,129,165,192,180,132,99,79,73,83,72,47, 40,0,-32,-46,-67,-99,-123,-114,-87,-108,-131,-152, -181,-245,-348,-294,-101,-71,-85,-26,99,123,15,2,77, 13,-117,-145,-105,-39,-50,-89,-59,-77,-134,-95,-51, -22,17,-19,-59,-74,-103,-78,4,77,113,60,18,13,-67, -49,24,88,179,190,89,18,-90,-102,-50,-5,123,135,57, 31,-82,-98,-51,6,93,104,44,-5,-84,-107,-44,45,102,104, 15,-47,-107,-126,-87,-11,89,93,13,-95,-136,-187,-70, -167,216,-70,-103,175,-284,-486) src = blocks.vector_source_s(data) enc = vocoder.codec2_encode_sp() dec = vocoder.codec2_decode_ps() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(expected_data, actual_result) if __name__ == '__main__': gr_unittest.run(test_codec2_vocoder, "test_codec2_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_g721_vocoder.py0000775000175000017500000000304512207440367023623 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_g721_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): data = (8,24,36,52,56,64,76,88,104,124,132,148,172, 196,220,244,280,320,372,416,468,524,580,648) src = blocks.vector_source_s(data) enc = vocoder.g721_encode_sb() dec = vocoder.g721_decode_bs() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(data, actual_result) if __name__ == '__main__': gr_unittest.run(test_g721_vocoder, "test_g721_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/python/vocoder/qa_g723_40_vocoder.py0000775000175000017500000000275612207440367024140 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, vocoder, blocks class test_g723_40_vocoder (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def test001_module_load (self): data = (0,8,36,72,100,152,228,316,404,528) src = blocks.vector_source_s(data) enc = vocoder.g723_40_encode_sb() dec = vocoder.g723_40_decode_bs() snk = blocks.vector_sink_s() self.tb.connect(src, enc, dec, snk) self.tb.run() actual_result = snk.data() self.assertEqual(data, actual_result) if __name__ == '__main__': gr_unittest.run(test_g723_40_vocoder, "test_g723_40_vocoder.xml") gnuradio-3.7.2.1/gr-vocoder/lib/0000755000175000017500000000000012207440367016144 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/lib/CMakeLists.txt0000664000175000017500000000573612207440367020721 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_VOCODER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${LOG4CXX_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) link_directories(${LOG4CXX_LIBRARY_DIRS}) link_directories(${Boost_LIBRARY_DIRS}) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) include_directories(${LOG4CPP_INCLUDE_DIRS}) link_directories(${LOG4CPP_LIBRARY_DIRS}) ######################################################################## # Setup library ######################################################################## list(APPEND gr_vocoder_sources alaw_decode_bs_impl.cc alaw_encode_sb_impl.cc codec2_decode_ps_impl.cc codec2_encode_sp_impl.cc cvsd_decode_bs_impl.cc cvsd_encode_sb_impl.cc g721_decode_bs_impl.cc g721_encode_sb_impl.cc g723_24_decode_bs_impl.cc g723_24_encode_sb_impl.cc g723_40_decode_bs_impl.cc g723_40_encode_sb_impl.cc gsm_fr_decode_ps_impl.cc gsm_fr_encode_sp_impl.cc ulaw_decode_bs_impl.cc ulaw_encode_sb_impl.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-vocoder.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-vocoder.rc @ONLY) list(APPEND gr_uhd_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-vocoder.rc ) endif(MSVC) ######################################################################## # Include subdirs rather to populate to the sources lists. ######################################################################## GR_INCLUDE_SUBDIRECTORY(codec2) GR_INCLUDE_SUBDIRECTORY(g7xx) GR_INCLUDE_SUBDIRECTORY(gsm) list(APPEND vocoder_libs gnuradio-runtime ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_library(gnuradio-vocoder SHARED ${gr_vocoder_sources}) target_link_libraries(gnuradio-vocoder ${vocoder_libs}) GR_LIBRARY_FOO(gnuradio-vocoder RUNTIME_COMPONENT "vocoder_runtime" DEVEL_COMPONENT "vocoder_devel") gnuradio-3.7.2.1/gr-vocoder/lib/alaw_encode_sb_impl.cc0000664000175000017500000000354212207440367022427 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "alaw_encode_sb_impl.h" #include #include namespace gr { namespace vocoder { extern "C" { #include "g7xx/g72x.h" } alaw_encode_sb::sptr alaw_encode_sb::make() { return gnuradio::get_initial_sptr (new alaw_encode_sb_impl()); } alaw_encode_sb_impl::alaw_encode_sb_impl() : sync_block("avocoder_law_encode_sb", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(unsigned char))) { } alaw_encode_sb_impl::~alaw_encode_sb_impl() { } int alaw_encode_sb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = linear2alaw(in[i]); } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/0000755000175000017500000000000012207440367017041 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/lib/g7xx/CMakeLists.txt0000664000175000017500000000234012207440367021602 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Append all sources in this dir ######################################################################## include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}) list(APPEND gr_vocoder_sources ${CMAKE_CURRENT_SOURCE_DIR}/g711.c ${CMAKE_CURRENT_SOURCE_DIR}/g72x.c ${CMAKE_CURRENT_SOURCE_DIR}/g721.c ${CMAKE_CURRENT_SOURCE_DIR}/g723_24.c ${CMAKE_CURRENT_SOURCE_DIR}/g723_40.c ) gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/g72x.c0000644000175000017500000003405711700377701020003 0ustar jcorganjcorgan/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ #include /* * g72x.c * * Common routines for G.721 and G.723 conversions. */ #include "g72x.h" static short power2[15] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000}; /* * quan() * * quantizes the input val against the table of size short integers. * It returns i if table[i - 1] <= val < table[i]. * * Using linear search for simple coding. */ static int quan( int val, short *table, int size) { int i; for (i = 0; i < size; i++) if (val < *table++) break; return (i); } /* * fmult() * * returns the integer product of the 14-bit integer "an" and * "floating point" representation (4-bit exponent, 6-bit mantessa) "srn". */ static int fmult( int an, int srn) { short anmag, anexp, anmant; short wanexp, wanmant; short retval; anmag = (an > 0) ? an : ((-an) & 0x1FFF); anexp = quan(anmag, power2, 15) - 6; anmant = (anmag == 0) ? 32 : (anexp >= 0) ? anmag >> anexp : anmag << -anexp; wanexp = anexp + ((srn >> 6) & 0xF) - 13; wanmant = (anmant * (srn & 077) + 0x30) >> 4; retval = (wanexp >= 0) ? ((wanmant << wanexp) & 0x7FFF) : (wanmant >> -wanexp); return (((an ^ srn) < 0) ? -retval : retval); } /* * g72x_init_state() * * This routine initializes and/or resets the g72x_state structure * pointed to by 'state_ptr'. * All the initial state values are specified in the CCITT G.721 document. */ void g72x_init_state( struct g72x_state *state_ptr) { int cnta; state_ptr->yl = 34816; state_ptr->yu = 544; state_ptr->dms = 0; state_ptr->dml = 0; state_ptr->ap = 0; for (cnta = 0; cnta < 2; cnta++) { state_ptr->a[cnta] = 0; state_ptr->pk[cnta] = 0; state_ptr->sr[cnta] = 32; } for (cnta = 0; cnta < 6; cnta++) { state_ptr->b[cnta] = 0; state_ptr->dq[cnta] = 32; } state_ptr->td = 0; } /* * predictor_zero() * * computes the estimated signal from 6-zero predictor. * */ int predictor_zero( struct g72x_state *state_ptr) { int i; int sezi; sezi = fmult(state_ptr->b[0] >> 2, state_ptr->dq[0]); for (i = 1; i < 6; i++) /* ACCUM */ sezi += fmult(state_ptr->b[i] >> 2, state_ptr->dq[i]); return (sezi); } /* * predictor_pole() * * computes the estimated signal from 2-pole predictor. * */ int predictor_pole( struct g72x_state *state_ptr) { return (fmult(state_ptr->a[1] >> 2, state_ptr->sr[1]) + fmult(state_ptr->a[0] >> 2, state_ptr->sr[0])); } /* * step_size() * * computes the quantization step size of the adaptive quantizer. * */ int step_size( struct g72x_state *state_ptr) { int y; int dif; int al; if (state_ptr->ap >= 256) return (state_ptr->yu); else { y = state_ptr->yl >> 6; dif = state_ptr->yu - y; al = state_ptr->ap >> 2; if (dif > 0) y += (dif * al) >> 6; else if (dif < 0) y += (dif * al + 0x3F) >> 6; return (y); } } /* * quantize() * * Given a raw sample, 'd', of the difference signal and a * quantization step size scale factor, 'y', this routine returns the * ADPCM codeword to which that sample gets quantized. The step * size scale factor division operation is done in the log base 2 domain * as a subtraction. */ int quantize( int d, /* Raw difference signal sample */ int y, /* Step size multiplier */ short *table, /* quantization table */ int size) /* table size of short integers */ { short dqm; /* Magnitude of 'd' */ short exp; /* Integer part of base 2 log of 'd' */ short mant; /* Fractional part of base 2 log */ short dl; /* Log of magnitude of 'd' */ short dln; /* Step size scale factor normalized log */ int i; /* * LOG * * Compute base 2 log of 'd', and store in 'dl'. */ dqm = abs(d); exp = quan(dqm >> 1, power2, 15); mant = ((dqm << 7) >> exp) & 0x7F; /* Fractional portion. */ dl = (exp << 7) + mant; /* * SUBTB * * "Divide" by step size multiplier. */ dln = dl - (y >> 2); /* * QUAN * * Obtain codword i for 'd'. */ i = quan(dln, table, size); if (d < 0) /* take 1's complement of i */ return ((size << 1) + 1 - i); else if (i == 0) /* take 1's complement of 0 */ return ((size << 1) + 1); /* new in 1988 */ else return (i); } /* * reconstruct() * * Returns reconstructed difference signal 'dq' obtained from * codeword 'i' and quantization step size scale factor 'y'. * Multiplication is performed in log base 2 domain as addition. */ int reconstruct( int sign, /* 0 for non-negative value */ int dqln, /* G.72x codeword */ int y) /* Step size multiplier */ { short dql; /* Log of 'dq' magnitude */ short dex; /* Integer part of log */ short dqt; short dq; /* Reconstructed difference signal sample */ dql = dqln + (y >> 2); /* ADDA */ if (dql < 0) { return ((sign) ? -0x8000 : 0); } else { /* ANTILOG */ dex = (dql >> 7) & 15; dqt = 128 + (dql & 127); dq = (dqt << 7) >> (14 - dex); return ((sign) ? (dq - 0x8000) : dq); } } /* * update() * * updates the state variables for each output code */ void update( int code_size, /* distinguish 723_40 with others */ int y, /* quantizer step size */ int wi, /* scale factor multiplier */ int fi, /* for long/short term energies */ int dq, /* quantized prediction difference */ int sr, /* reconstructed signal */ int dqsez, /* difference from 2-pole predictor */ struct g72x_state *state_ptr) /* coder state pointer */ { int cnt; short mag, exp; /* Adaptive predictor, FLOAT A */ short a2p = 0; /* LIMC */ short a1ul; /* UPA1 */ short pks1; /* UPA2 */ short fa1; char tr; /* tone/transition detector */ short ylint, thr2, dqthr; short ylfrac, thr1; short pk0; pk0 = (dqsez < 0) ? 1 : 0; /* needed in updating predictor poles */ mag = dq & 0x7FFF; /* prediction difference magnitude */ /* TRANS */ ylint = state_ptr->yl >> 15; /* exponent part of yl */ ylfrac = (state_ptr->yl >> 10) & 0x1F; /* fractional part of yl */ thr1 = (32 + ylfrac) << ylint; /* threshold */ thr2 = (ylint > 9) ? 31 << 10 : thr1; /* limit thr2 to 31 << 10 */ dqthr = (thr2 + (thr2 >> 1)) >> 1; /* dqthr = 0.75 * thr2 */ if (state_ptr->td == 0) /* signal supposed voice */ tr = 0; else if (mag <= dqthr) /* supposed data, but small mag */ tr = 0; /* treated as voice */ else /* signal is data (modem) */ tr = 1; /* * Quantizer scale factor adaptation. */ /* FUNCTW & FILTD & DELAY */ /* update non-steady state step size multiplier */ state_ptr->yu = y + ((wi - y) >> 5); /* LIMB */ if (state_ptr->yu < 544) /* 544 <= yu <= 5120 */ state_ptr->yu = 544; else if (state_ptr->yu > 5120) state_ptr->yu = 5120; /* FILTE & DELAY */ /* update steady state step size multiplier */ state_ptr->yl += state_ptr->yu + ((-state_ptr->yl) >> 6); /* * Adaptive predictor coefficients. */ if (tr == 1) { /* reset a's and b's for modem signal */ state_ptr->a[0] = 0; state_ptr->a[1] = 0; state_ptr->b[0] = 0; state_ptr->b[1] = 0; state_ptr->b[2] = 0; state_ptr->b[3] = 0; state_ptr->b[4] = 0; state_ptr->b[5] = 0; } else { /* update a's and b's */ pks1 = pk0 ^ state_ptr->pk[0]; /* UPA2 */ /* update predictor pole a[1] */ a2p = state_ptr->a[1] - (state_ptr->a[1] >> 7); if (dqsez != 0) { fa1 = (pks1) ? state_ptr->a[0] : -state_ptr->a[0]; if (fa1 < -8191) /* a2p = function of fa1 */ a2p -= 0x100; else if (fa1 > 8191) a2p += 0xFF; else a2p += fa1 >> 5; if (pk0 ^ state_ptr->pk[1]) /* LIMC */ if (a2p <= -12160) a2p = -12288; else if (a2p >= 12416) a2p = 12288; else a2p -= 0x80; else if (a2p <= -12416) a2p = -12288; else if (a2p >= 12160) a2p = 12288; else a2p += 0x80; } /* TRIGB & DELAY */ state_ptr->a[1] = a2p; /* UPA1 */ /* update predictor pole a[0] */ state_ptr->a[0] -= state_ptr->a[0] >> 8; if (dqsez != 0){ if (pks1 == 0) state_ptr->a[0] += 192; else state_ptr->a[0] -= 192; } /* LIMD */ a1ul = 15360 - a2p; if (state_ptr->a[0] < -a1ul) state_ptr->a[0] = -a1ul; else if (state_ptr->a[0] > a1ul) state_ptr->a[0] = a1ul; /* UPB : update predictor zeros b[6] */ for (cnt = 0; cnt < 6; cnt++) { if (code_size == 5) /* for 40Kbps G.723 */ state_ptr->b[cnt] -= state_ptr->b[cnt] >> 9; else /* for G.721 and 24Kbps G.723 */ state_ptr->b[cnt] -= state_ptr->b[cnt] >> 8; if (dq & 0x7FFF) { /* XOR */ if ((dq ^ state_ptr->dq[cnt]) >= 0) state_ptr->b[cnt] += 128; else state_ptr->b[cnt] -= 128; } } } for (cnt = 5; cnt > 0; cnt--) state_ptr->dq[cnt] = state_ptr->dq[cnt-1]; /* FLOAT A : convert dq[0] to 4-bit exp, 6-bit mantissa f.p. */ if (mag == 0) { state_ptr->dq[0] = (dq >= 0) ? 0x20 : 0xFC20; } else { exp = quan(mag, power2, 15); state_ptr->dq[0] = (dq >= 0) ? (exp << 6) + ((mag << 6) >> exp) : (exp << 6) + ((mag << 6) >> exp) - 0x400; } state_ptr->sr[1] = state_ptr->sr[0]; /* FLOAT B : convert sr to 4-bit exp., 6-bit mantissa f.p. */ if (sr == 0) { state_ptr->sr[0] = 0x20; } else if (sr > 0) { exp = quan(sr, power2, 15); state_ptr->sr[0] = (exp << 6) + ((sr << 6) >> exp); } else if (sr > -32768) { mag = -sr; exp = quan(mag, power2, 15); state_ptr->sr[0] = (exp << 6) + ((mag << 6) >> exp) - 0x400; } else state_ptr->sr[0] = 0xFC20; /* DELAY A */ state_ptr->pk[1] = state_ptr->pk[0]; state_ptr->pk[0] = pk0; /* TONE */ if (tr == 1) /* this sample has been treated as data */ state_ptr->td = 0; /* next one will be treated as voice */ else if (a2p < -11776) /* small sample-to-sample correlation */ state_ptr->td = 1; /* signal may be data */ else /* signal is voice */ state_ptr->td = 0; /* * Adaptation speed control. */ state_ptr->dms += (fi - state_ptr->dms) >> 5; /* FILTA */ state_ptr->dml += (((fi << 2) - state_ptr->dml) >> 7); /* FILTB */ if (tr == 1) state_ptr->ap = 256; else if (y < 1536) /* SUBTC */ state_ptr->ap += (0x200 - state_ptr->ap) >> 4; else if (state_ptr->td == 1) state_ptr->ap += (0x200 - state_ptr->ap) >> 4; else if (abs((state_ptr->dms << 2) - state_ptr->dml) >= (state_ptr->dml >> 3)) state_ptr->ap += (0x200 - state_ptr->ap) >> 4; else state_ptr->ap += (-state_ptr->ap) >> 4; } /* * tandem_adjust(sr, se, y, i, sign) * * At the end of ADPCM decoding, it simulates an encoder which may be receiving * the output of this decoder as a tandem process. If the output of the * simulated encoder differs from the input to this decoder, the decoder output * is adjusted by one level of A-law or u-law codes. * * Input: * sr decoder output linear PCM sample, * se predictor estimate sample, * y quantizer step size, * i decoder input code, * sign sign bit of code i * * Return: * adjusted A-law or u-law compressed sample. */ int tandem_adjust_alaw( int sr, /* decoder output linear PCM sample */ int se, /* predictor estimate sample */ int y, /* quantizer step size */ int i, /* decoder input code */ int sign, short *qtab) { unsigned char sp; /* A-law compressed 8-bit code */ short dx; /* prediction error */ char id; /* quantized prediction error */ int sd; /* adjusted A-law decoded sample value */ int im; /* biased magnitude of i */ int imx; /* biased magnitude of id */ if (sr <= -32768) sr = -1; sp = linear2alaw((sr >> 1) << 3); /* short to A-law compression */ dx = (alaw2linear(sp) >> 2) - se; /* 16-bit prediction error */ id = quantize(dx, y, qtab, sign - 1); if (id == i) { /* no adjustment on sp */ return (sp); } else { /* sp adjustment needed */ /* ADPCM codes : 8, 9, ... F, 0, 1, ... , 6, 7 */ im = i ^ sign; /* 2's complement to biased unsigned */ imx = id ^ sign; if (imx > im) { /* sp adjusted to next lower value */ if (sp & 0x80) { sd = (sp == 0xD5) ? 0x55 : ((sp ^ 0x55) - 1) ^ 0x55; } else { sd = (sp == 0x2A) ? 0x2A : ((sp ^ 0x55) + 1) ^ 0x55; } } else { /* sp adjusted to next higher value */ if (sp & 0x80) sd = (sp == 0xAA) ? 0xAA : ((sp ^ 0x55) + 1) ^ 0x55; else sd = (sp == 0x55) ? 0xD5 : ((sp ^ 0x55) - 1) ^ 0x55; } return (sd); } } int tandem_adjust_ulaw( int sr, /* decoder output linear PCM sample */ int se, /* predictor estimate sample */ int y, /* quantizer step size */ int i, /* decoder input code */ int sign, short *qtab) { unsigned char sp; /* u-law compressed 8-bit code */ short dx; /* prediction error */ char id; /* quantized prediction error */ int sd; /* adjusted u-law decoded sample value */ int im; /* biased magnitude of i */ int imx; /* biased magnitude of id */ if (sr <= -32768) sr = 0; sp = linear2ulaw(sr << 2); /* short to u-law compression */ dx = (ulaw2linear(sp) >> 2) - se; /* 16-bit prediction error */ id = quantize(dx, y, qtab, sign - 1); if (id == i) { return (sp); } else { /* ADPCM codes : 8, 9, ... F, 0, 1, ... , 6, 7 */ im = i ^ sign; /* 2's complement to biased unsigned */ imx = id ^ sign; if (imx > im) { /* sp adjusted to next lower value */ if (sp & 0x80) sd = (sp == 0xFF) ? 0x7E : sp + 1; else sd = (sp == 0) ? 0 : sp - 1; } else { /* sp adjusted to next higher value */ if (sp & 0x80) sd = (sp == 0x80) ? 0x80 : sp - 1; else sd = (sp == 0x7F) ? 0xFE : sp + 1; } return (sd); } } gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/g723_24.c0000644000175000017500000001103511700377701020172 0ustar jcorganjcorgan/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * g723_24.c * * Description: * * g723_24_encoder(), g723_24_decoder() * * These routines comprise an implementation of the CCITT G.723 24 Kbps * ADPCM coding algorithm. Essentially, this implementation is identical to * the bit level description except for a few deviations which take advantage * of workstation attributes, such as hardware 2's complement arithmetic. * */ #include "g72x.h" /* * Maps G.723_24 code word to reconstructed scale factor normalized log * magnitude values. */ static short _dqlntab[8] = {-2048, 135, 273, 373, 373, 273, 135, -2048}; /* Maps G.723_24 code word to log of scale factor multiplier. */ static short _witab[8] = {-128, 960, 4384, 18624, 18624, 4384, 960, -128}; /* * Maps G.723_24 code words to a set of values whose long and short * term averages are computed and then compared to give an indication * how stationary (steady state) the signal is. */ static short _fitab[8] = {0, 0x200, 0x400, 0xE00, 0xE00, 0x400, 0x200, 0}; static short qtab_723_24[3] = {8, 218, 331}; /* * g723_24_encoder() * * Encodes a linear PCM, A-law or u-law input sample and returns its 3-bit code. * Returns -1 if invalid input coding value. */ int g723_24_encoder( int sl, int in_coding, struct g72x_state *state_ptr) { short sei, sezi, se, sez; /* ACCUM */ short d; /* SUBTA */ short y; /* MIX */ short sr; /* ADDB */ short dqsez; /* ADDC */ short dq, i; switch (in_coding) { /* linearize input sample to 14-bit PCM */ case AUDIO_ENCODING_ALAW: sl = alaw2linear(sl) >> 2; break; case AUDIO_ENCODING_ULAW: sl = ulaw2linear(sl) >> 2; break; case AUDIO_ENCODING_LINEAR: sl >>= 2; /* sl of 14-bit dynamic range */ break; default: return (-1); } sezi = predictor_zero(state_ptr); sez = sezi >> 1; sei = sezi + predictor_pole(state_ptr); se = sei >> 1; /* se = estimated signal */ d = sl - se; /* d = estimation diff. */ /* quantize prediction difference d */ y = step_size(state_ptr); /* quantizer step size */ i = quantize(d, y, qtab_723_24, 3); /* i = ADPCM code */ dq = reconstruct(i & 4, _dqlntab[i], y); /* quantized diff. */ sr = (dq < 0) ? se - (dq & 0x3FFF) : se + dq; /* reconstructed signal */ dqsez = sr + sez - se; /* pole prediction diff. */ update(3, y, _witab[i], _fitab[i], dq, sr, dqsez, state_ptr); return (i); } /* * g723_24_decoder() * * Decodes a 3-bit CCITT G.723_24 ADPCM code and returns * the resulting 16-bit linear PCM, A-law or u-law sample value. * -1 is returned if the output coding is unknown. */ int g723_24_decoder( int i, int out_coding, struct g72x_state *state_ptr) { short sezi, sei, sez, se; /* ACCUM */ short y; /* MIX */ short sr; /* ADDB */ short dq; short dqsez; i &= 0x07; /* mask to get proper bits */ sezi = predictor_zero(state_ptr); sez = sezi >> 1; sei = sezi + predictor_pole(state_ptr); se = sei >> 1; /* se = estimated signal */ y = step_size(state_ptr); /* adaptive quantizer step size */ dq = reconstruct(i & 0x04, _dqlntab[i], y); /* unquantize pred diff */ sr = (dq < 0) ? (se - (dq & 0x3FFF)) : (se + dq); /* reconst. signal */ dqsez = sr - se + sez; /* pole prediction diff. */ update(3, y, _witab[i], _fitab[i], dq, sr, dqsez, state_ptr); switch (out_coding) { case AUDIO_ENCODING_ALAW: return (tandem_adjust_alaw(sr, se, y, i, 4, qtab_723_24)); case AUDIO_ENCODING_ULAW: return (tandem_adjust_ulaw(sr, se, y, i, 4, qtab_723_24)); case AUDIO_ENCODING_LINEAR: return (sr << 2); /* sr was of 14-bit dynamic range */ default: return (-1); } } gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/g723_40.c0000644000175000017500000001262411700377701020175 0ustar jcorganjcorgan/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * g723_40.c * * Description: * * g723_40_encoder(), g723_40_decoder() * * These routines comprise an implementation of the CCITT G.723 40Kbps * ADPCM coding algorithm. Essentially, this implementation is identical to * the bit level description except for a few deviations which * take advantage of workstation attributes, such as hardware 2's * complement arithmetic. * * The deviation from the bit level specification (lookup tables), * preserves the bit level performance specifications. * * As outlined in the G.723 Recommendation, the algorithm is broken * down into modules. Each section of code below is preceded by * the name of the module which it is implementing. * */ #include "g72x.h" /* * Maps G.723_40 code word to ructeconstructed scale factor normalized log * magnitude values. */ static short _dqlntab[32] = {-2048, -66, 28, 104, 169, 224, 274, 318, 358, 395, 429, 459, 488, 514, 539, 566, 566, 539, 514, 488, 459, 429, 395, 358, 318, 274, 224, 169, 104, 28, -66, -2048}; /* Maps G.723_40 code word to log of scale factor multiplier. */ static short _witab[32] = {448, 448, 768, 1248, 1280, 1312, 1856, 3200, 4512, 5728, 7008, 8960, 11456, 14080, 16928, 22272, 22272, 16928, 14080, 11456, 8960, 7008, 5728, 4512, 3200, 1856, 1312, 1280, 1248, 768, 448, 448}; /* * Maps G.723_40 code words to a set of values whose long and short * term averages are computed and then compared to give an indication * how stationary (steady state) the signal is. */ static short _fitab[32] = {0, 0, 0, 0, 0, 0x200, 0x200, 0x200, 0x200, 0x200, 0x400, 0x600, 0x800, 0xA00, 0xC00, 0xC00, 0xC00, 0xC00, 0xA00, 0x800, 0x600, 0x400, 0x200, 0x200, 0x200, 0x200, 0x200, 0, 0, 0, 0, 0}; static short qtab_723_40[15] = {-122, -16, 68, 139, 198, 250, 298, 339, 378, 413, 445, 475, 502, 528, 553}; /* * g723_40_encoder() * * Encodes a 16-bit linear PCM, A-law or u-law input sample and retuens * the resulting 5-bit CCITT G.723 40Kbps code. * Returns -1 if the input coding value is invalid. */ int g723_40_encoder( int sl, int in_coding, struct g72x_state *state_ptr) { short sei, sezi, se, sez; /* ACCUM */ short d; /* SUBTA */ short y; /* MIX */ short sr; /* ADDB */ short dqsez; /* ADDC */ short dq, i; switch (in_coding) { /* linearize input sample to 14-bit PCM */ case AUDIO_ENCODING_ALAW: sl = alaw2linear(sl) >> 2; break; case AUDIO_ENCODING_ULAW: sl = ulaw2linear(sl) >> 2; break; case AUDIO_ENCODING_LINEAR: sl >>= 2; /* sl of 14-bit dynamic range */ break; default: return (-1); } sezi = predictor_zero(state_ptr); sez = sezi >> 1; sei = sezi + predictor_pole(state_ptr); se = sei >> 1; /* se = estimated signal */ d = sl - se; /* d = estimation difference */ /* quantize prediction difference */ y = step_size(state_ptr); /* adaptive quantizer step size */ i = quantize(d, y, qtab_723_40, 15); /* i = ADPCM code */ dq = reconstruct(i & 0x10, _dqlntab[i], y); /* quantized diff */ sr = (dq < 0) ? se - (dq & 0x7FFF) : se + dq; /* reconstructed signal */ dqsez = sr + sez - se; /* dqsez = pole prediction diff. */ update(5, y, _witab[i], _fitab[i], dq, sr, dqsez, state_ptr); return (i); } /* * g723_40_decoder() * * Decodes a 5-bit CCITT G.723 40Kbps code and returns * the resulting 16-bit linear PCM, A-law or u-law sample value. * -1 is returned if the output coding is unknown. */ int g723_40_decoder( int i, int out_coding, struct g72x_state *state_ptr) { short sezi, sei, sez, se; /* ACCUM */ short y; /* MIX */ short sr; /* ADDB */ short dq; short dqsez; i &= 0x1f; /* mask to get proper bits */ sezi = predictor_zero(state_ptr); sez = sezi >> 1; sei = sezi + predictor_pole(state_ptr); se = sei >> 1; /* se = estimated signal */ y = step_size(state_ptr); /* adaptive quantizer step size */ dq = reconstruct(i & 0x10, _dqlntab[i], y); /* estimation diff. */ sr = (dq < 0) ? (se - (dq & 0x7FFF)) : (se + dq); /* reconst. signal */ dqsez = sr - se + sez; /* pole prediction diff. */ update(5, y, _witab[i], _fitab[i], dq, sr, dqsez, state_ptr); switch (out_coding) { case AUDIO_ENCODING_ALAW: return (tandem_adjust_alaw(sr, se, y, i, 0x10, qtab_723_40)); case AUDIO_ENCODING_ULAW: return (tandem_adjust_ulaw(sr, se, y, i, 0x10, qtab_723_40)); case AUDIO_ENCODING_LINEAR: return (sr << 2); /* sr was of 14-bit dynamic range */ default: return (-1); } } gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/encode.c0000644000175000017500000000527411700377701020450 0ustar jcorganjcorgan/* * encode.c * * CCITT ADPCM encoder * * Usage : encode [-3|4|5] [-a|u|l] < infile > outfile */ #include #include "g72x.h" /* * Pack output codes into bytes and write them to stdout. * Returns 1 if there is residual output, else returns 0. */ int pack_output( unsigned code, int bits) { static unsigned int out_buffer = 0; static int out_bits = 0; unsigned char out_byte; out_buffer |= (code << out_bits); out_bits += bits; if (out_bits >= 8) { out_byte = out_buffer & 0xff; out_bits -= 8; out_buffer >>= 8; fwrite(&out_byte, sizeof (char), 1, stdout); } return (out_bits > 0); } main( int argc, char **argv) { struct g72x_state state; unsigned char sample_char; short sample_short; unsigned char code; int resid; int in_coding; int in_size; unsigned *in_buf; int (*enc_routine)(); int enc_bits; g72x_init_state(&state); /* Set defaults to u-law input, G.721 output */ in_coding = AUDIO_ENCODING_ULAW; in_size = sizeof (char); in_buf = (unsigned *)&sample_char; enc_routine = g721_encoder; enc_bits = 4; /* Process encoding argument, if any */ while ((argc > 1) && (argv[1][0] == '-')) { switch (argv[1][1]) { case '3': enc_routine = g723_24_encoder; enc_bits = 3; break; case '4': enc_routine = g721_encoder; enc_bits = 4; break; case '5': enc_routine = g723_40_encoder; enc_bits = 5; break; case 'u': in_coding = AUDIO_ENCODING_ULAW; in_size = sizeof (char); in_buf = (unsigned *)&sample_char; break; case 'a': in_coding = AUDIO_ENCODING_ALAW; in_size = sizeof (char); in_buf = (unsigned *)&sample_char; break; case 'l': in_coding = AUDIO_ENCODING_LINEAR; in_size = sizeof (short); in_buf = (unsigned *)&sample_short; break; default: fprintf(stderr, "CCITT ADPCM Encoder -- usage:\n"); fprintf(stderr, "\tencode [-3|4|5] [-a|u|l] < infile > outfile\n"); fprintf(stderr, "where:\n"); fprintf(stderr, "\t-3\tGenerate G.723 24kbps (3-bit) data\n"); fprintf(stderr, "\t-4\tGenerate G.721 32kbps (4-bit) data [default]\n"); fprintf(stderr, "\t-5\tGenerate G.723 40kbps (5-bit) data\n"); fprintf(stderr, "\t-a\tProcess 8-bit A-law input data\n"); fprintf(stderr, "\t-u\tProcess 8-bit u-law input data [default]\n"); fprintf(stderr, "\t-l\tProcess 16-bit linear PCM input data\n"); exit(1); } argc--; argv++; } /* Read input file and process */ while (fread(in_buf, in_size, 1, stdin) == 1) { code = (*enc_routine)(in_size == 2 ? sample_short : sample_char, in_coding, &state); resid = pack_output(code, enc_bits); } /* Write zero codes until all residual codes are written out */ while (resid) { resid = pack_output(0, enc_bits); } fclose(stdout); } gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/g72x.h0000644000175000017500000001004711744612271020003 0ustar jcorganjcorgan/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * g72x.h * * Header file for CCITT conversion routines. * */ #ifndef _G72X_H #define _G72X_H #define AUDIO_ENCODING_ULAW (1) /* ISDN u-law */ #define AUDIO_ENCODING_ALAW (2) /* ISDN A-law */ #define AUDIO_ENCODING_LINEAR (3) /* PCM 2's-complement (0-center) */ /* * The following is the definition of the state structure * used by the G.721/G.723 encoder and decoder to preserve their internal * state between successive calls. The meanings of the majority * of the state structure fields are explained in detail in the * CCITT Recommendation G.721. The field names are essentially indentical * to variable names in the bit level description of the coding algorithm * included in this Recommendation. */ struct g72x_state { long yl; /* Locked or steady state step size multiplier. */ short yu; /* Unlocked or non-steady state step size multiplier. */ short dms; /* Short term energy estimate. */ short dml; /* Long term energy estimate. */ short ap; /* Linear weighting coefficient of 'yl' and 'yu'. */ short a[2]; /* Coefficients of pole portion of prediction filter. */ short b[6]; /* Coefficients of zero portion of prediction filter. */ short pk[2]; /* * Signs of previous two samples of a partially * reconstructed signal. */ short dq[6]; /* * Previous 6 samples of the quantized difference * signal represented in an internal floating point * format. */ short sr[2]; /* * Previous 2 samples of the quantized difference * signal represented in an internal floating point * format. */ char td; /* delayed tone detect, new in 1988 version */ }; /* External function definitions. */ extern void g72x_init_state(struct g72x_state *); extern int g721_encoder( int sample, int in_coding, struct g72x_state *state_ptr); extern int g721_decoder( int code, int out_coding, struct g72x_state *state_ptr); extern int g723_24_encoder( int sample, int in_coding, struct g72x_state *state_ptr); extern int g723_24_decoder( int code, int out_coding, struct g72x_state *state_ptr); extern int g723_40_encoder( int sample, int in_coding, struct g72x_state *state_ptr); extern int g723_40_decoder( int code, int out_coding, struct g72x_state *state_ptr); extern int quantize( int d, int y, short *table, int size); extern int reconstruct(int,int,int);void extern update( int code_size, int y, int wi, int fi, int dq, int sr, int dqsez, struct g72x_state *state_ptr); extern int tandem_adjust_alaw( int sr, int se, int y, int i, int sign, short *qtab); extern int tandem_adjust_ulaw( int sr, int se, int y, int i, int sign, short *qtab); extern unsigned char linear2alaw( int pcm_val); extern int alaw2linear( unsigned char a_val); extern unsigned char linear2ulaw(int pcm_val); extern int ulaw2linear( unsigned char u_val); extern int predictor_zero(struct g72x_state *state_ptr); extern int predictor_pole( struct g72x_state *state_ptr); extern int step_size( struct g72x_state *state_ptr); #endif /* !_G72X_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/g711.c0000644000175000017500000001654111700377701017671 0ustar jcorganjcorgan/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * g711.c * * u-law, A-law and linear PCM conversions. */ #define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */ #define QUANT_MASK (0xf) /* Quantization field mask. */ #define NSEGS (8) /* Number of A-law segments. */ #define SEG_SHIFT (4) /* Left shift for segment number. */ #define SEG_MASK (0x70) /* Segment field mask. */ static short seg_end[8] = {0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF}; /* copy from CCITT G.711 specifications */ unsigned char _u2a[128] = { /* u- to A-law conversions */ 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128}; unsigned char _a2u[128] = { /* A- to u-law conversions */ 1, 3, 5, 7, 9, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 48, 49, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127}; static int search( int val, short *table, int size) { int i; for (i = 0; i < size; i++) { if (val <= *table++) return (i); } return (size); } /* * linear2alaw() - Convert a 16-bit linear PCM value to 8-bit A-law * * linear2alaw() accepts an 16-bit integer and encodes it as A-law data. * * Linear Input Code Compressed Code * ------------------------ --------------- * 0000000wxyza 000wxyz * 0000001wxyza 001wxyz * 000001wxyzab 010wxyz * 00001wxyzabc 011wxyz * 0001wxyzabcd 100wxyz * 001wxyzabcde 101wxyz * 01wxyzabcdef 110wxyz * 1wxyzabcdefg 111wxyz * * For further information see John C. Bellamy's Digital Telephony, 1982, * John Wiley & Sons, pps 98-111 and 472-476. */ unsigned char linear2alaw( int pcm_val) /* 2's complement (16-bit range) */ { int mask; int seg; unsigned char aval; if (pcm_val >= 0) { mask = 0xD5; /* sign (7th) bit = 1 */ } else { mask = 0x55; /* sign bit = 0 */ pcm_val = -pcm_val - 8; } /* Convert the scaled magnitude to segment number. */ seg = search(pcm_val, seg_end, 8); /* Combine the sign, segment, and quantization bits. */ if (seg >= 8) /* out of range, return maximum value. */ return (0x7F ^ mask); else { aval = seg << SEG_SHIFT; if (seg < 2) aval |= (pcm_val >> 4) & QUANT_MASK; else aval |= (pcm_val >> (seg + 3)) & QUANT_MASK; return (aval ^ mask); } } /* * alaw2linear() - Convert an A-law value to 16-bit linear PCM * */ int alaw2linear( unsigned char a_val) { int t; int seg; a_val ^= 0x55; t = (a_val & QUANT_MASK) << 4; seg = ((unsigned)a_val & SEG_MASK) >> SEG_SHIFT; switch (seg) { case 0: t += 8; break; case 1: t += 0x108; break; default: t += 0x108; t <<= seg - 1; } return ((a_val & SIGN_BIT) ? t : -t); } #define BIAS (0x84) /* Bias for linear code. */ /* * linear2ulaw() - Convert a linear PCM value to u-law * * In order to simplify the encoding process, the original linear magnitude * is biased by adding 33 which shifts the encoding range from (0 - 8158) to * (33 - 8191). The result can be seen in the following encoding table: * * Biased Linear Input Code Compressed Code * ------------------------ --------------- * 00000001wxyza 000wxyz * 0000001wxyzab 001wxyz * 000001wxyzabc 010wxyz * 00001wxyzabcd 011wxyz * 0001wxyzabcde 100wxyz * 001wxyzabcdef 101wxyz * 01wxyzabcdefg 110wxyz * 1wxyzabcdefgh 111wxyz * * Each biased linear code has a leading 1 which identifies the segment * number. The value of the segment number is equal to 7 minus the number * of leading 0's. The quantization interval is directly available as the * four bits wxyz. * The trailing bits (a - h) are ignored. * * Ordinarily the complement of the resulting code word is used for * transmission, and so the code word is complemented before it is returned. * * For further information see John C. Bellamy's Digital Telephony, 1982, * John Wiley & Sons, pps 98-111 and 472-476. */ unsigned char linear2ulaw( int pcm_val) /* 2's complement (16-bit range) */ { int mask; int seg; unsigned char uval; /* Get the sign and the magnitude of the value. */ if (pcm_val < 0) { pcm_val = BIAS - pcm_val; mask = 0x7F; } else { pcm_val += BIAS; mask = 0xFF; } /* Convert the scaled magnitude to segment number. */ seg = search(pcm_val, seg_end, 8); /* * Combine the sign, segment, quantization bits; * and complement the code word. */ if (seg >= 8) /* out of range, return maximum value. */ return (0x7F ^ mask); else { uval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0xF); return (uval ^ mask); } } /* * ulaw2linear() - Convert a u-law value to 16-bit linear PCM * * First, a biased linear code is derived from the code word. An unbiased * output can then be obtained by subtracting 33 from the biased code. * * Note that this function expects to be passed the complement of the * original code word. This is in keeping with ISDN conventions. */ int ulaw2linear( unsigned char u_val) { int t; /* Complement to obtain normal u-law value. */ u_val = ~u_val; /* * Extract and bias the quantization bits. Then * shift up by the segment number and subtract out the bias. */ t = ((u_val & QUANT_MASK) << 3) + BIAS; t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT; return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS)); } /* A-law to u-law conversion */ unsigned char alaw2ulaw( unsigned char aval) { aval &= 0xff; return ((aval & 0x80) ? (0xFF ^ _a2u[aval ^ 0xD5]) : (0x7F ^ _a2u[aval ^ 0x55])); } /* u-law to A-law conversion */ unsigned char ulaw2alaw( unsigned char uval) { uval &= 0xff; return ((uval & 0x80) ? (0xD5 ^ (_u2a[0xFF ^ uval] - 1)) : (0x55 ^ (_u2a[0x7F ^ uval] - 1))); } gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/decode.c0000644000175000017500000000473711700377701020441 0ustar jcorganjcorgan/* * decode.c * * CCITT ADPCM decoder * * Usage : decode [-3|4|5] [-a|u|l] < infile > outfile */ #include #include "g72x.h" /* * Unpack input codes and pass them back as bytes. * Returns 1 if there is residual input, returns -1 if eof, else returns 0. */ int unpack_input( unsigned char *code, int bits) { static unsigned int in_buffer = 0; static int in_bits = 0; unsigned char in_byte; if (in_bits < bits) { if (fread(&in_byte, sizeof (char), 1, stdin) != 1) { *code = 0; return (-1); } in_buffer |= (in_byte << in_bits); in_bits += 8; } *code = in_buffer & ((1 << bits) - 1); in_buffer >>= bits; in_bits -= bits; return (in_bits > 0); } main( int argc, char **argv) { short sample; unsigned char code; int n; struct g72x_state state; int out_coding; int out_size; int (*dec_routine)(); int dec_bits; g72x_init_state(&state); out_coding = AUDIO_ENCODING_ULAW; out_size = sizeof (char); dec_routine = g721_decoder; dec_bits = 4; /* Process encoding argument, if any */ while ((argc > 1) && (argv[1][0] == '-')) { switch (argv[1][1]) { case '3': dec_routine = g723_24_decoder; dec_bits = 3; break; case '4': dec_routine = g721_decoder; dec_bits = 4; break; case '5': dec_routine = g723_40_decoder; dec_bits = 5; break; case 'u': out_coding = AUDIO_ENCODING_ULAW; out_size = sizeof (char); break; case 'a': out_coding = AUDIO_ENCODING_ALAW; out_size = sizeof (char); break; case 'l': out_coding = AUDIO_ENCODING_LINEAR; out_size = sizeof (short); break; default: fprintf(stderr, "CCITT ADPCM Decoder -- usage:\n"); fprintf(stderr, "\tdecode [-3|4|5] [-a|u|l] < infile > outfile\n"); fprintf(stderr, "where:\n"); fprintf(stderr, "\t-3\tProcess G.723 24kbps (3-bit) input data\n"); fprintf(stderr, "\t-4\tProcess G.721 32kbps (4-bit) input data [default]\n"); fprintf(stderr, "\t-5\tProcess G.723 40kbps (5-bit) input data\n"); fprintf(stderr, "\t-a\tGenerate 8-bit A-law data\n"); fprintf(stderr, "\t-u\tGenerate 8-bit u-law data [default]\n"); fprintf(stderr, "\t-l\tGenerate 16-bit linear PCM data\n"); exit(1); } argc--; argv++; } /* Read and unpack input codes and process them */ while (unpack_input(&code, dec_bits) >= 0) { sample = (*dec_routine)(code, out_coding, &state); if (out_size == 2) { fwrite(&sample, out_size, 1, stdout); } else { code = (unsigned char)sample; fwrite(&code, out_size, 1, stdout); } } fclose(stdout); } gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/README0000644000175000017500000000622111700377701017720 0ustar jcorganjcorganThe files in this directory comprise ANSI-C language reference implementations of the CCITT (International Telegraph and Telephone Consultative Committee) G.711, G.721 and G.723 voice compressions. They have been tested on Sun SPARCstations and passed 82 out of 84 test vectors published by CCITT (Dec. 20, 1988) for G.721 and G.723. [The two remaining test vectors, which the G.721 decoder implementation for u-law samples did not pass, may be in error because they are identical to two other vectors for G.723_40.] This source code is released by Sun Microsystems, Inc. to the public domain. Please give your acknowledgement in product literature if this code is used in your product implementation. Sun Microsystems supports some CCITT audio formats in Solaris 2.0 system software. However, Sun's implementations have been optimized for higher performance on SPARCstations. The source files for CCITT conversion routines in this directory are: g72x.h header file for g721.c, g723_24.c and g723_40.c g711.c CCITT G.711 u-law and A-law compression g72x.c common denominator of G.721 and G.723 ADPCM codes g721.c CCITT G.721 32Kbps ADPCM coder (with g72x.c) g723_24.c CCITT G.723 24Kbps ADPCM coder (with g72x.c) g723_40.c CCITT G.723 40Kbps ADPCM coder (with g72x.c) Simple conversions between u-law, A-law, and 16-bit linear PCM are invoked as follows: unsigned char ucode, acode; short pcm_val; ucode = linear2ulaw(pcm_val); ucode = alaw2ulaw(acode); acode = linear2alaw(pcm_val); acode = ulaw2alaw(ucode); pcm_val = ulaw2linear(ucode); pcm_val = alaw2linear(acode); The other CCITT compression routines are invoked as follows: #include "g72x.h" struct g72x_state state; int sample, code; g72x_init_state(&state); code = {g721,g723_24,g723_40}_encoder(sample, coding, &state); sample = {g721,g723_24,g723_40}_decoder(code, coding, &state); where coding = AUDIO_ENCODING_ULAW for 8-bit u-law samples AUDIO_ENCODING_ALAW for 8-bit A-law samples AUDIO_ENCODING_LINEAR for 16-bit linear PCM samples This directory also includes the following sample programs: encode.c CCITT ADPCM encoder decode.c CCITT ADPCM decoder Makefile makefile for the sample programs The sample programs contain examples of how to call the various compression routines and pack/unpack the bits. The sample programs read byte streams from stdin and write to stdout. The input/output data is raw data (no file header or other identifying information is embedded). The sample programs are invoked as follows: encode [-3|4|5] [-a|u|l] outfile decode [-3|4|5] [-a|u|l] outfile where: -3 encode to (decode from) G.723 24kbps (3-bit) data -4 encode to (decode from) G.721 32kbps (4-bit) data [the default] -5 encode to (decode from) G.723 40kbps (5-bit) data -a encode from (decode to) A-law data -u encode from (decode to) u-law data [the default] -l encode from (decode to) 16-bit linear data Examples: # Read 16-bit linear and output G.721 encode -4 -l g721file # Read 40Kbps G.723 and output A-law decode -5 -a alawfile # Compress and then decompress u-law data using 24Kbps G.723 encode -3 ulawout gnuradio-3.7.2.1/gr-vocoder/lib/g7xx/g721.c0000644000175000017500000001221111700377701017660 0ustar jcorganjcorgan/* * This source code is a product of Sun Microsystems, Inc. and is provided * for unrestricted use. Users may copy or modify this source code without * charge. * * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun source code is provided with no support and without any obligation on * the part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * g721.c * * Description: * * g721_encoder(), g721_decoder() * * These routines comprise an implementation of the CCITT G.721 ADPCM * coding algorithm. Essentially, this implementation is identical to * the bit level description except for a few deviations which * take advantage of work station attributes, such as hardware 2's * complement arithmetic and large memory. Specifically, certain time * consuming operations such as multiplications are replaced * with lookup tables and software 2's complement operations are * replaced with hardware 2's complement. * * The deviation from the bit level specification (lookup tables) * preserves the bit level performance specifications. * * As outlined in the G.721 Recommendation, the algorithm is broken * down into modules. Each section of code below is preceded by * the name of the module which it is implementing. * */ #include "g72x.h" static short qtab_721[7] = {-124, 80, 178, 246, 300, 349, 400}; /* * Maps G.721 code word to reconstructed scale factor normalized log * magnitude values. */ static short _dqlntab[16] = {-2048, 4, 135, 213, 273, 323, 373, 425, 425, 373, 323, 273, 213, 135, 4, -2048}; /* Maps G.721 code word to log of scale factor multiplier. */ static short _witab[16] = {-12, 18, 41, 64, 112, 198, 355, 1122, 1122, 355, 198, 112, 64, 41, 18, -12}; /* * Maps G.721 code words to a set of values whose long and short * term averages are computed and then compared to give an indication * how stationary (steady state) the signal is. */ static short _fitab[16] = {0, 0, 0, 0x200, 0x200, 0x200, 0x600, 0xE00, 0xE00, 0x600, 0x200, 0x200, 0x200, 0, 0, 0}; /* * g721_encoder() * * Encodes the input vale of linear PCM, A-law or u-law data sl and returns * the resulting code. -1 is returned for unknown input coding value. */ int g721_encoder( int sl, int in_coding, struct g72x_state *state_ptr) { short sezi, se, sez; /* ACCUM */ short d; /* SUBTA */ short sr; /* ADDB */ short y; /* MIX */ short dqsez; /* ADDC */ short dq, i; switch (in_coding) { /* linearize input sample to 14-bit PCM */ case AUDIO_ENCODING_ALAW: sl = alaw2linear(sl) >> 2; break; case AUDIO_ENCODING_ULAW: sl = ulaw2linear(sl) >> 2; break; case AUDIO_ENCODING_LINEAR: sl >>= 2; /* 14-bit dynamic range */ break; default: return (-1); } sezi = predictor_zero(state_ptr); sez = sezi >> 1; se = (sezi + predictor_pole(state_ptr)) >> 1; /* estimated signal */ d = sl - se; /* estimation difference */ /* quantize the prediction difference */ y = step_size(state_ptr); /* quantizer step size */ i = quantize(d, y, qtab_721, 7); /* i = ADPCM code */ dq = reconstruct(i & 8, _dqlntab[i], y); /* quantized est diff */ sr = (dq < 0) ? se - (dq & 0x3FFF) : se + dq; /* reconst. signal */ dqsez = sr + sez - se; /* pole prediction diff. */ update(4, y, _witab[i] << 5, _fitab[i], dq, sr, dqsez, state_ptr); return (i); } /* * g721_decoder() * * Description: * * Decodes a 4-bit code of G.721 encoded data of i and * returns the resulting linear PCM, A-law or u-law value. * return -1 for unknown out_coding value. */ int g721_decoder( int i, int out_coding, struct g72x_state *state_ptr) { short sezi, sei, sez, se; /* ACCUM */ short y; /* MIX */ short sr; /* ADDB */ short dq; short dqsez; i &= 0x0f; /* mask to get proper bits */ sezi = predictor_zero(state_ptr); sez = sezi >> 1; sei = sezi + predictor_pole(state_ptr); se = sei >> 1; /* se = estimated signal */ y = step_size(state_ptr); /* dynamic quantizer step size */ dq = reconstruct(i & 0x08, _dqlntab[i], y); /* quantized diff. */ sr = (dq < 0) ? (se - (dq & 0x3FFF)) : se + dq; /* reconst. signal */ dqsez = sr - se + sez; /* pole prediction diff. */ update(4, y, _witab[i] << 5, _fitab[i], dq, sr, dqsez, state_ptr); switch (out_coding) { case AUDIO_ENCODING_ALAW: return (tandem_adjust_alaw(sr, se, y, i, 8, qtab_721)); case AUDIO_ENCODING_ULAW: return (tandem_adjust_ulaw(sr, se, y, i, 8, qtab_721)); case AUDIO_ENCODING_LINEAR: return (sr << 2); /* sr was 14-bit dynamic range */ default: return (-1); } } gnuradio-3.7.2.1/gr-vocoder/lib/cvsd_encode_sb_impl.cc0000664000175000017500000001252112207440367022437 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cvsd_encode_sb_impl.h" #include #include namespace gr { namespace vocoder { cvsd_encode_sb::sptr cvsd_encode_sb::make(short min_step, short max_step, double step_decay, double accum_decay, int K, int J, short pos_accum_max, short neg_accum_max) { return gnuradio::get_initial_sptr (new cvsd_encode_sb_impl(min_step, max_step, step_decay, accum_decay, K, J, pos_accum_max, neg_accum_max)); } cvsd_encode_sb_impl::cvsd_encode_sb_impl(short min_step, short max_step, double step_decay, double accum_decay, int K, int J, short pos_accum_max, short neg_accum_max) : sync_decimator("vocoder_cvsd_encode_sb", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(unsigned char)), 8), d_min_step (min_step), d_max_step(max_step), d_step_decay(step_decay), d_accum_decay(accum_decay), d_K(K), d_J(J), d_pos_accum_max(pos_accum_max), d_neg_accum_max(neg_accum_max), d_accum(0), d_loop_counter(1), d_runner(0), d_stepsize(min_step) { if(d_K > 32) throw std::runtime_error("cvsd_decode_bs_impl: K must be <= 32\n"); if(d_J > d_K) throw std::runtime_error("cvsd_decode_bs_impl: J must be <= K\n"); } cvsd_encode_sb_impl::~cvsd_encode_sb_impl() { // nothing else required in this example } unsigned char cvsd_encode_sb_impl::cvsd_bitwise_sum(unsigned int input) { unsigned int temp = input; unsigned char bits = 0; while(temp) { temp=temp&(temp-1); bits++; } return bits; } int cvsd_encode_sb_impl::cvsd_round(double input) { double temp; temp=input+0.5; temp=floor(temp); return (int)temp; } unsigned int cvsd_encode_sb_impl::cvsd_pow(short radix, short power) { double d_radix = (double)radix; int i_power = (int)power; double output; output = pow(d_radix,i_power); return ((unsigned int)cvsd_round(output)); } int cvsd_encode_sb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; unsigned short i=0; // 2 bytes, 0 .. 65,535 unsigned char output_bit=0; // 1 byte, 0 .. 255 unsigned char output_byte=0; // 1 bytes 0.255 unsigned char bit_count=0; // 1 byte, 0 .. 255 unsigned int mask=0; // 4 bytes, 0 .. 4,294,967,295 // Loop through each input data point for(i = 0; i < noutput_items*8; i++) { if((int)in[i] >= d_accum) { // Note: sign((data(n)-accum)) output_bit=1; } else { output_bit=0; } // Update Accum (i.e. the reference value) if(output_bit) { d_accum=d_accum+d_stepsize; //printf("Addding %d to the accum; the result is: %d.\n", d_stepsize, d_accum); } else { d_accum=d_accum-d_stepsize; //printf("Subtracting %d to the accum; the result is: %d.\n", d_stepsize, d_accum); } // Multiply by Accum_Decay d_accum = (cvsd_round(d_accum*d_accum_decay)); // Check for overflow if(d_accum >= ((int)d_pos_accum_max)) { d_accum = (int)d_pos_accum_max; } else if(d_accum <= ((int) d_neg_accum_max)) { d_accum = (int) d_neg_accum_max; } // Update runner with the last output bit // Update Step Size if(d_loop_counter >= d_J) { // Run this only if you have >= J bits in your shift register mask = (cvsd_pow(2, d_J) - 1); if((cvsd_bitwise_sum(d_runner & mask) >= d_J) || (cvsd_bitwise_sum((~d_runner) & mask) >= d_J)) { // Runs of 1s and 0s d_stepsize = std::min((short)(d_stepsize + d_min_step), d_max_step); } else { // No runs of 1s and 0s d_stepsize = std::max((short)cvsd_round(d_stepsize*d_step_decay), d_min_step); } } // Runner is a shift-register; shift left, add on newest output bit d_runner = (d_runner<<1) | ((unsigned int) output_bit); // Update the ouput type; shift left, add on newest output bit // If you have put in 8 bits, output it as a byte output_byte = (output_byte<<1) | output_bit; bit_count++; if(d_loop_counter <= d_K) { d_loop_counter++; } // If you have put 8 bits, output and clear. if(bit_count==8) { // Read in short from the file *(out++) = output_byte; // Reset the bit_count bit_count=0; output_byte=0; } } // While return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/ulaw_decode_bs_impl.h0000664000175000017500000000254512207440367022305 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ULAW_DECODE_BS_IMPL_H #define INCLUDED_VOCODER_ULAW_DECODE_BS_IMPL_H #include namespace gr { namespace vocoder { class ulaw_decode_bs_impl : public ulaw_decode_bs { public: ulaw_decode_bs_impl(); ~ulaw_decode_bs_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ULAW_DECODE_BS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_24_encode_sb_impl.cc0000664000175000017500000000361512207440367022473 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "g723_24_encode_sb_impl.h" #include #include namespace gr { namespace vocoder { g723_24_encode_sb::sptr g723_24_encode_sb::make() { return gnuradio::get_initial_sptr (new g723_24_encode_sb_impl()); } g723_24_encode_sb_impl::g723_24_encode_sb_impl() : sync_block("vocoder_g723_24_encode_sb", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(unsigned char))) { g72x_init_state(&d_state); } g723_24_encode_sb_impl::~g723_24_encode_sb_impl() { } int g723_24_encode_sb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = g723_24_encoder(in[i], AUDIO_ENCODING_LINEAR, &d_state); return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/cvsd_decode_bs_impl.h0000664000175000017500000000645312207440367022276 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CVSD_DECODE_BS_IMPL_H #define INCLUDED_VOCODER_CVSD_DECODE_BS_IMPL_H #include namespace gr { namespace vocoder { class cvsd_decode_bs_impl : public cvsd_decode_bs { private: //! Member functions required by the encoder/decoder //! \brief Rounding function specific to CVSD //! \return the input value rounded to the nearest integer int cvsd_round(double input); //! \brief A power function specific to CVSD data formats //! \return (radix)^power, where radix and power are short integers unsigned int cvsd_pow(short radix, short power); //! \brief Sums number of 1's in the input //! \return the number of 1s in the four bytes of an input unsigned integer unsigned char cvsd_bitwise_sum(unsigned int input); short d_min_step; short d_max_step; double d_step_decay; double d_accum_decay; int d_K; //!< \brief Size of shift register; the number of output bits remembered in shift register int d_J; //!< \brief Number of bits in the shift register that are equal; size of run of 1s, 0s short d_pos_accum_max; short d_neg_accum_max; int d_accum; //!< \brief Current value of internal reference int d_loop_counter; //!< \brief Current value of the loop counter unsigned int d_runner; //!< \brief Current value of the shift register unsigned int d_runner_mask; //!< \brief Value of the mask to access the last J bits of the shift register short d_stepsize; //!< \brief Current value of the step sizer public: cvsd_decode_bs_impl(short min_step=10, short max_step=1280, double step_decay=0.9990234375, double accum_decay= 0.96875, int K=32, int J=4, short pos_accum_max=32767, short neg_accum_max=-32767); ~cvsd_decode_bs_impl(); short min_step() { return d_min_step; } short max_step() { return d_max_step; } double step_decay() { return d_step_decay; } double accum_decay() { return d_accum_decay; } int K() { return d_K; } int J() { return d_J; } short pos_accum_max() { return d_pos_accum_max; } short neg_accum_max() { return d_neg_accum_max; } int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CVSD_DECODE_BS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/alaw_decode_bs_impl.h0000664000175000017500000000254512207440367022261 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011.2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ALAW_DECODE_BS_IMPL_H #define INCLUDED_VOCODER_ALAW_DECODE_BS_IMPL_H #include namespace gr { namespace vocoder { class alaw_decode_bs_impl : public alaw_decode_bs { public: alaw_decode_bs_impl(); ~alaw_decode_bs_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ALAW_DECODE_BS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/codec2_encode_sp_impl.h0000664000175000017500000000263112207440367022520 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CODEC2_ENCODE_SP_IMPL_H #define INCLUDED_VOCODER_CODEC2_ENCODE_SP_IMPL_H #include namespace gr { namespace vocoder { class codec2_encode_sp_impl : public codec2_encode_sp { private: void *d_codec2; public: codec2_encode_sp_impl(); ~codec2_encode_sp_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CODEC2_ENCODE_SP_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/cvsd_decode_bs_impl.cc0000664000175000017500000001235212207440367022427 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2010,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "cvsd_decode_bs_impl.h" #include #include namespace gr { namespace vocoder { cvsd_decode_bs::sptr cvsd_decode_bs::make(short min_step, short max_step, double step_decay, double accum_decay, int K, int J, short pos_accum_max, short neg_accum_max) { return gnuradio::get_initial_sptr (new cvsd_decode_bs_impl(min_step, max_step, step_decay, accum_decay, K, J, pos_accum_max, neg_accum_max)); } cvsd_decode_bs_impl::cvsd_decode_bs_impl(short min_step, short max_step, double step_decay, double accum_decay, int K, int J, short pos_accum_max, short neg_accum_max) : sync_interpolator("vocoder_cvsd_decode_bs", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(short)), 8), d_min_step(min_step), d_max_step(max_step), d_step_decay(step_decay), d_accum_decay(accum_decay), d_K(K), d_J(J), d_pos_accum_max(pos_accum_max), d_neg_accum_max(neg_accum_max), d_accum(0), d_loop_counter(1), d_runner(0), d_runner_mask(0), d_stepsize(min_step) { if(d_K > 32) throw std::runtime_error("cvsd_decode_bs_impl: K must be <= 32\n"); if(d_J > d_K) throw std::runtime_error("cvsd_decode_bs_impl: J must be <= K\n"); } cvsd_decode_bs_impl::~cvsd_decode_bs_impl() { // nothing else required in this example } unsigned char cvsd_decode_bs_impl::cvsd_bitwise_sum(unsigned int input) { unsigned int temp = input; unsigned char bits = 0; while(temp) { temp=temp&(temp-1); bits++; } return bits; } int cvsd_decode_bs_impl::cvsd_round(double input) { double temp; temp=input+0.5; temp=floor(temp); return (int)temp; } unsigned int cvsd_decode_bs_impl::cvsd_pow(short radix, short power) { double d_radix = (double) radix; int i_power = (int) power; double output; output = pow(d_radix,i_power); return ( (unsigned int)cvsd_round(output)); } int cvsd_decode_bs_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short *) output_items[0]; int i=0; short output_short=0; // 2 bytes 0 .. 65,535 unsigned char bit_count=0; // 1 byte, 0 .. 255 unsigned int mask=0; // 4 bytes, 0 .. 4,294,967,295 unsigned char input_byte=0; // 1 bytes unsigned char input_bit=0; // 1 byte, 0 .. 255 // Loop through each input data point for(i = 0; i < noutput_items/8.0; i++) { input_byte = in[i]; // Initiliaze bit counter bit_count=0; while(bit_count<8) { // Compute the Appropriate Mask mask=cvsd_pow(2,7-bit_count); // Pull off the corresponding bit input_bit = input_byte & mask; // Update the bit counter bit_count++; // Update runner with the next input bit // Runner is a shift-register; shift left, add on newest output bit d_runner = (d_runner<<1) | ((unsigned int) input_bit); // Run this only if you have >= J bits in your shift register if(d_loop_counter>=d_J) { // Update Step Size d_runner_mask=(cvsd_pow(2,d_J)-1); if((cvsd_bitwise_sum(d_runner & d_runner_mask)>=d_J) || (cvsd_bitwise_sum((~d_runner) & d_runner_mask)>=d_J)) { // Runs of 1s and 0s d_stepsize = std::min( (short) (d_stepsize + d_min_step), d_max_step); } else { // No runs of 1s and 0s d_stepsize = std::max( (short) cvsd_round(d_stepsize*d_step_decay), d_min_step); } } // Update Accum (i.e. the reference value) if(input_bit) { d_accum = d_accum+d_stepsize; } else { d_accum = d_accum-d_stepsize; } // Multiply by Accum_Decay d_accum = (cvsd_round(d_accum*d_accum_decay)); // Check for overflow if(d_accum >=((int) d_pos_accum_max)) { d_accum = (int)d_pos_accum_max; } else if(d_accum <=((int) d_neg_accum_max)) { d_accum = (int)d_neg_accum_max; } // Find the output short to write to the file output_short = ((short)d_accum); if(d_loop_counter <= d_K) { d_loop_counter++; } *(out++) = output_short; } // while () } // for() return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_24_decode_bs_impl.cc0000664000175000017500000000361512207440367022461 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "g723_24_decode_bs_impl.h" #include #include namespace gr { namespace vocoder { g723_24_decode_bs::sptr g723_24_decode_bs::make() { return gnuradio::get_initial_sptr (new g723_24_decode_bs_impl()); } g723_24_decode_bs_impl::g723_24_decode_bs_impl() : sync_block("vocoder_g723_24_decode_bs", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(short))) { g72x_init_state(&d_state); } g723_24_decode_bs_impl::~g723_24_decode_bs_impl() { } int g723_24_decode_bs_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = g723_24_decoder(in[i], AUDIO_ENCODING_LINEAR, &d_state); return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_40_encode_sb_impl.h0000664000175000017500000000271412207440367022332 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_40_ENCODE_SB_IMPL_H #define INCLUDED_VOCODER_G723_40_ENCODE_SB_IMPL_H #include extern "C" { #include "g7xx/g72x.h" } namespace gr { namespace vocoder { class g723_40_encode_sb_impl : public g723_40_encode_sb { private: g72x_state d_state; public: g723_40_encode_sb_impl(); ~g723_40_encode_sb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_40_ENCODE_SB_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm_fr_decode_ps_impl.cc0000664000175000017500000000426712207440367022771 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsm_fr_decode_ps_impl.h" #include #include #include namespace gr { namespace vocoder { gsm_fr_decode_ps::sptr gsm_fr_decode_ps::make() { return gnuradio::get_initial_sptr (new gsm_fr_decode_ps_impl()); } gsm_fr_decode_ps_impl::gsm_fr_decode_ps_impl() : sync_interpolator("vocoder_gsm_fr_decode_ps", io_signature::make(1, 1, sizeof(gsm_frame)), io_signature::make(1, 1, sizeof(short)), GSM_SAMPLES_PER_FRAME) { if((d_gsm = gsm_create()) == 0) throw std::runtime_error("gsm_fr_decode_ps_impl: gsm_create failed"); } gsm_fr_decode_ps_impl::~gsm_fr_decode_ps_impl() { gsm_destroy(d_gsm); } int gsm_fr_decode_ps_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short*)output_items[0]; assert((noutput_items % GSM_SAMPLES_PER_FRAME) == 0); for(int i = 0; i < noutput_items; i += GSM_SAMPLES_PER_FRAME) { gsm_decode(d_gsm, const_cast(in), out); in += sizeof(gsm_frame); out += GSM_SAMPLES_PER_FRAME; } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/ulaw_encode_sb_impl.h0000664000175000017500000000254712207440367022321 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ULAW_ENCODER_SB_IMPL_H #define INCLUDED_VOCODER_ULAW_ENCODER_SB_IMPL_H #include namespace gr { namespace vocoder { class ulaw_encode_sb_impl : public ulaw_encode_sb { public: ulaw_encode_sb_impl(); ~ulaw_encode_sb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ULAW_ENCODE_SB_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gnuradio-vocoder.rc.in0000664000175000017500000000164412207440367022355 0ustar jcorganjcorgan#include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-vocoder" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-vocoder.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-vocoder.dll" VALUE "ProductName", "gnuradio-vocoder" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-vocoder/lib/codec2_decode_ps_impl.h0000664000175000017500000000263112207440367022506 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CODEC2_DECODE_PS_IMPL_H #define INCLUDED_VOCODER_CODEC2_DECODE_PS_IMPL_H #include namespace gr { namespace vocoder { class codec2_decode_ps_impl : public codec2_decode_ps { private: void *d_codec2; public: codec2_decode_ps_impl(); ~codec2_decode_ps_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CODEC2_DECODE_PS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_40_encode_sb_impl.cc0000664000175000017500000000361012207440367022464 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "g723_40_encode_sb_impl.h" #include #include namespace gr { namespace vocoder { g723_40_encode_sb::sptr g723_40_encode_sb::make() { return gnuradio::get_initial_sptr (new g723_40_encode_sb_impl()); } g723_40_encode_sb_impl::g723_40_encode_sb_impl() : sync_block("vocoder_g723_40_encode_sb", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(unsigned char))) { g72x_init_state(&d_state); } g723_40_encode_sb_impl::~g723_40_encode_sb_impl() { } int g723_40_encode_sb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = g723_40_encoder(in[i], AUDIO_ENCODING_LINEAR, &d_state); return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm/0000755000175000017500000000000012207440367016732 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/lib/gsm/README.gsm0000644000175000017500000000320611744612271020400 0ustar jcorganjcorgan GSM 06.10 13 kbit/s RPE/LTP speech compression available -------------------------------------------------------- The Communications and Operating Systems Research Group (KBS) at the Technische Universitaet Berlin is currently working on a set of UNIX-based tools for computer-mediated telecooperation that will be made freely available. As part of this effort we are publishing an implementation of the European GSM 06.10 provisional standard for full-rate speech transcoding, prI-ETS 300 036, which uses RPE/LTP (residual pulse excitation/long term prediction) coding at 13 kbit/s. GSM 06.10 compresses frames of 160 13-bit samples (8 kHz sampling rate, i.e. a frame rate of 50 Hz) into 260 bits; for compatibility with typical UNIX applications, our implementation turns frames of 160 16-bit linear samples into 33-byte frames (1650 Bytes/s). The quality of the algorithm is good enough for reliable speaker recognition; even music often survives transcoding in recognizable form (given the bandwidth limitations of 8 kHz sampling rate). The interfaces offered are a front end modelled after compress(1), and a library API. Compression and decompression run faster than realtime on most SPARCstations. The implementation has been verified against the ETSI standard test patterns. Jutta Degener (jutta@cs.tu-berlin.de) Carsten Bormann (cabo@cs.tu-berlin.de) Communications and Operating Systems Research Group, TU Berlin Fax: +49.30.31425156, Phone: +49.30.31424315 -- Copyright 1992 by Jutta Degener and Carsten Bormann, Technische Universitaet Berlin. See the accompanying file "COPYRIGHT" for details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. gnuradio-3.7.2.1/gr-vocoder/lib/gsm/CMakeLists.txt0000664000175000017500000000364512207440367021504 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Append all sources in this dir ######################################################################## include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}) set(gsm_sources ${CMAKE_CURRENT_SOURCE_DIR}/add.c ${CMAKE_CURRENT_SOURCE_DIR}/code.c ${CMAKE_CURRENT_SOURCE_DIR}/debug.c ${CMAKE_CURRENT_SOURCE_DIR}/decode.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_create.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_decode.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_destroy.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_encode.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_explode.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_implode.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_option.c ${CMAKE_CURRENT_SOURCE_DIR}/gsm_print.c ${CMAKE_CURRENT_SOURCE_DIR}/long_term.c ${CMAKE_CURRENT_SOURCE_DIR}/lpc.c ${CMAKE_CURRENT_SOURCE_DIR}/preprocess.c ${CMAKE_CURRENT_SOURCE_DIR}/rpe.c ${CMAKE_CURRENT_SOURCE_DIR}/short_term.c ${CMAKE_CURRENT_SOURCE_DIR}/table.c ) set_source_files_properties(${gsm_sources} PROPERTIES COMPILE_DEFINITION "NeedFunctionPrototypes=1" ) list(APPEND gr_vocoder_sources ${gsm_sources}) gnuradio-3.7.2.1/gr-vocoder/lib/gsm/rpe.c0000644000175000017500000002531511744612271017672 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include #include "private.h" #include "gsm.h" #include "proto.h" /* 4.2.13 .. 4.2.17 RPE ENCODING SECTION */ /* 4.2.13 */ static void Weighting_filter P2((e, x), register word * e, /* signal [-5..0.39.44] IN */ word * x /* signal [0..39] OUT */ ) /* * The coefficients of the weighting filter are stored in a table * (see table 4.4). The following scaling is used: * * H[0..10] = integer( real_H[ 0..10] * 8192 ); */ { /* word wt[ 50 ]; */ register longword L_result; register int k /* , i */ ; /* Initialization of a temporary working array wt[0...49] */ /* for (k = 0; k <= 4; k++) wt[k] = 0; * for (k = 5; k <= 44; k++) wt[k] = *e++; * for (k = 45; k <= 49; k++) wt[k] = 0; * * (e[-5..-1] and e[40..44] are allocated by the caller, * are initially zero and are not written anywhere.) */ e -= 5; /* Compute the signal x[0..39] */ for (k = 0; k <= 39; k++) { L_result = 8192 >> 1; /* for (i = 0; i <= 10; i++) { * L_temp = GSM_L_MULT( wt[k+i], gsm_H[i] ); * L_result = GSM_L_ADD( L_result, L_temp ); * } */ #undef STEP #define STEP( i, H ) (e[ k + i ] * (longword)H) /* Every one of these multiplications is done twice -- * but I don't see an elegant way to optimize this. * Do you? */ #ifdef STUPID_COMPILER L_result += STEP( 0, -134 ) ; L_result += STEP( 1, -374 ) ; /* + STEP( 2, 0 ) */ L_result += STEP( 3, 2054 ) ; L_result += STEP( 4, 5741 ) ; L_result += STEP( 5, 8192 ) ; L_result += STEP( 6, 5741 ) ; L_result += STEP( 7, 2054 ) ; /* + STEP( 8, 0 ) */ L_result += STEP( 9, -374 ) ; L_result += STEP( 10, -134 ) ; #else L_result += STEP( 0, -134 ) + STEP( 1, -374 ) /* + STEP( 2, 0 ) */ + STEP( 3, 2054 ) + STEP( 4, 5741 ) + STEP( 5, 8192 ) + STEP( 6, 5741 ) + STEP( 7, 2054 ) /* + STEP( 8, 0 ) */ + STEP( 9, -374 ) + STEP(10, -134 ) ; #endif /* L_result = GSM_L_ADD( L_result, L_result ); (* scaling(x2) *) * L_result = GSM_L_ADD( L_result, L_result ); (* scaling(x4) *) * * x[k] = SASR( L_result, 16 ); */ /* 2 adds vs. >>16 => 14, minus one shift to compensate for * those we lost when replacing L_MULT by '*'. */ L_result = SASR( L_result, 13 ); x[k] = ( L_result < MIN_WORD ? MIN_WORD : (L_result > MAX_WORD ? MAX_WORD : L_result )); } } /* 4.2.14 */ static void RPE_grid_selection P3((x,xM,Mc_out), word * x, /* [0..39] IN */ word * xM, /* [0..12] OUT */ word * Mc_out /* OUT */ ) /* * The signal x[0..39] is used to select the RPE grid which is * represented by Mc. */ { /* register word temp1; */ register int /* m, */ i; register longword L_result, L_temp; longword EM; /* xxx should be L_EM? */ word Mc; longword L_common_0_3; EM = 0; Mc = 0; /* for (m = 0; m <= 3; m++) { * L_result = 0; * * * for (i = 0; i <= 12; i++) { * * temp1 = SASR( x[m + 3*i], 2 ); * * assert(temp1 != MIN_WORD); * * L_temp = GSM_L_MULT( temp1, temp1 ); * L_result = GSM_L_ADD( L_temp, L_result ); * } * * if (L_result > EM) { * Mc = m; * EM = L_result; * } * } */ #undef STEP #define STEP( m, i ) L_temp = SASR( x[m + 3 * i], 2 ); \ L_result += L_temp * L_temp; /* common part of 0 and 3 */ L_result = 0; STEP( 0, 1 ); STEP( 0, 2 ); STEP( 0, 3 ); STEP( 0, 4 ); STEP( 0, 5 ); STEP( 0, 6 ); STEP( 0, 7 ); STEP( 0, 8 ); STEP( 0, 9 ); STEP( 0, 10); STEP( 0, 11); STEP( 0, 12); L_common_0_3 = L_result; /* i = 0 */ STEP( 0, 0 ); L_result <<= 1; /* implicit in L_MULT */ EM = L_result; /* i = 1 */ L_result = 0; STEP( 1, 0 ); STEP( 1, 1 ); STEP( 1, 2 ); STEP( 1, 3 ); STEP( 1, 4 ); STEP( 1, 5 ); STEP( 1, 6 ); STEP( 1, 7 ); STEP( 1, 8 ); STEP( 1, 9 ); STEP( 1, 10); STEP( 1, 11); STEP( 1, 12); L_result <<= 1; if (L_result > EM) { Mc = 1; EM = L_result; } /* i = 2 */ L_result = 0; STEP( 2, 0 ); STEP( 2, 1 ); STEP( 2, 2 ); STEP( 2, 3 ); STEP( 2, 4 ); STEP( 2, 5 ); STEP( 2, 6 ); STEP( 2, 7 ); STEP( 2, 8 ); STEP( 2, 9 ); STEP( 2, 10); STEP( 2, 11); STEP( 2, 12); L_result <<= 1; if (L_result > EM) { Mc = 2; EM = L_result; } /* i = 3 */ L_result = L_common_0_3; STEP( 3, 12 ); L_result <<= 1; if (L_result > EM) { Mc = 3; EM = L_result; } /**/ /* Down-sampling by a factor 3 to get the selected xM[0..12] * RPE sequence. */ for (i = 0; i <= 12; i ++) xM[i] = x[Mc + 3*i]; *Mc_out = Mc; } /* 4.12.15 */ static void APCM_quantization_xmaxc_to_exp_mant P3((xmaxc,exp_out,mant_out), word xmaxc, /* IN */ word * exp_out, /* OUT */ word * mant_out ) /* OUT */ { word exp, mant; /* Compute exponent and mantissa of the decoded version of xmaxc */ exp = 0; if (xmaxc > 15) exp = SASR(xmaxc, 3) - 1; mant = xmaxc - (exp << 3); if (mant == 0) { exp = -4; mant = 7; } else { while (mant <= 7) { mant = mant << 1 | 1; exp--; } mant -= 8; } assert( exp >= -4 && exp <= 6 ); assert( mant >= 0 && mant <= 7 ); *exp_out = exp; *mant_out = mant; } static void APCM_quantization P5((xM,xMc,mant_out,exp_out,xmaxc_out), word * xM, /* [0..12] IN */ word * xMc, /* [0..12] OUT */ word * mant_out, /* OUT */ word * exp_out, /* OUT */ word * xmaxc_out /* OUT */ ) { int i, itest; word xmax, xmaxc, temp, temp1, temp2; word exp, mant; /* Find the maximum absolute value xmax of xM[0..12]. */ xmax = 0; for (i = 0; i <= 12; i++) { temp = xM[i]; temp = GSM_ABS(temp); if (temp > xmax) xmax = temp; } /* Qantizing and coding of xmax to get xmaxc. */ exp = 0; temp = SASR( xmax, 9 ); itest = 0; for (i = 0; i <= 5; i++) { itest |= (temp <= 0); temp = SASR( temp, 1 ); assert(exp <= 5); if (itest == 0) exp++; /* exp = add (exp, 1) */ } assert(exp <= 6 && exp >= 0); temp = exp + 5; assert(temp <= 11 && temp >= 0); xmaxc = gsm_add( SASR(xmax, temp), exp << 3 ); /* Quantizing and coding of the xM[0..12] RPE sequence * to get the xMc[0..12] */ APCM_quantization_xmaxc_to_exp_mant( xmaxc, &exp, &mant ); /* This computation uses the fact that the decoded version of xmaxc * can be calculated by using the exponent and the mantissa part of * xmaxc (logarithmic table). * So, this method avoids any division and uses only a scaling * of the RPE samples by a function of the exponent. A direct * multiplication by the inverse of the mantissa (NRFAC[0..7] * found in table 4.5) gives the 3 bit coded version xMc[0..12] * of the RPE samples. */ /* Direct computation of xMc[0..12] using table 4.5 */ assert( exp <= 4096 && exp >= -4096); assert( mant >= 0 && mant <= 7 ); temp1 = 6 - exp; /* normalization by the exponent */ temp2 = gsm_NRFAC[ mant ]; /* inverse mantissa */ for (i = 0; i <= 12; i++) { assert(temp1 >= 0 && temp1 < 16); temp = xM[i] << temp1; temp = GSM_MULT( temp, temp2 ); temp = SASR(temp, 12); xMc[i] = temp + 4; /* see note below */ } /* NOTE: This equation is used to make all the xMc[i] positive. */ *mant_out = mant; *exp_out = exp; *xmaxc_out = xmaxc; } /* 4.2.16 */ static void APCM_inverse_quantization P4((xMc,mant,exp,xMp), register word * xMc, /* [0..12] IN */ word mant, word exp, register word * xMp) /* [0..12] OUT */ /* * This part is for decoding the RPE sequence of coded xMc[0..12] * samples to obtain the xMp[0..12] array. Table 4.6 is used to get * the mantissa of xmaxc (FAC[0..7]). */ { int i; word temp, temp1, temp2, temp3; longword ltmp; assert( mant >= 0 && mant <= 7 ); temp1 = gsm_FAC[ mant ]; /* see 4.2-15 for mant */ temp2 = gsm_sub( 6, exp ); /* see 4.2-15 for exp */ temp3 = gsm_asl( 1, gsm_sub( temp2, 1 )); for (i = 13; i--;) { assert( *xMc <= 7 && *xMc >= 0 ); /* 3 bit unsigned */ /* temp = gsm_sub( *xMc++ << 1, 7 ); */ temp = (*xMc++ << 1) - 7; /* restore sign */ assert( temp <= 7 && temp >= -7 ); /* 4 bit signed */ temp <<= 12; /* 16 bit signed */ temp = GSM_MULT_R( temp1, temp ); temp = GSM_ADD( temp, temp3 ); *xMp++ = gsm_asr( temp, temp2 ); } } /* 4.2.17 */ static void RPE_grid_positioning P3((Mc,xMp,ep), word Mc, /* grid position IN */ register word * xMp, /* [0..12] IN */ register word * ep /* [0..39] OUT */ ) /* * This procedure computes the reconstructed long term residual signal * ep[0..39] for the LTP analysis filter. The inputs are the Mc * which is the grid position selection and the xMp[0..12] decoded * RPE samples which are upsampled by a factor of 3 by inserting zero * values. */ { int i = 13; assert(0 <= Mc && Mc <= 3); switch (Mc) { case 3: *ep++ = 0; case 2: do { *ep++ = 0; case 1: *ep++ = 0; case 0: *ep++ = *xMp++; } while (--i); } while (++Mc < 4) *ep++ = 0; /* int i, k; for (k = 0; k <= 39; k++) ep[k] = 0; for (i = 0; i <= 12; i++) { ep[ Mc + (3*i) ] = xMp[i]; } */ } /* 4.2.18 */ /* This procedure adds the reconstructed long term residual signal * ep[0..39] to the estimated signal dpp[0..39] from the long term * analysis filter to compute the reconstructed short term residual * signal dp[-40..-1]; also the reconstructed short term residual * array dp[-120..-41] is updated. */ #if 0 /* Has been inlined in code.c */ void Gsm_Update_of_reconstructed_short_time_residual_signal P3((dpp, ep, dp), word * dpp, /* [0...39] IN */ word * ep, /* [0...39] IN */ word * dp) /* [-120...-1] IN/OUT */ { int k; for (k = 0; k <= 79; k++) dp[ -120 + k ] = dp[ -80 + k ]; for (k = 0; k <= 39; k++) dp[ -40 + k ] = gsm_add( ep[k], dpp[k] ); } #endif /* Has been inlined in code.c */ void Gsm_RPE_Encoding P5((S,e,xmaxc,Mc,xMc), struct gsm_state * S, word * e, /* -5..-1][0..39][40..44 IN/OUT */ word * xmaxc, /* OUT */ word * Mc, /* OUT */ word * xMc) /* [0..12] OUT */ { word x[40]; word xM[13], xMp[13]; word mant, exp; Weighting_filter(e, x); RPE_grid_selection(x, xM, Mc); APCM_quantization( xM, xMc, &mant, &exp, xmaxc); APCM_inverse_quantization( xMc, mant, exp, xMp); RPE_grid_positioning( *Mc, xMp, e ); } void Gsm_RPE_Decoding P5((S, xmaxcr, Mcr, xMcr, erp), struct gsm_state * S, word xmaxcr, word Mcr, word * xMcr, /* [0..12], 3 bits IN */ word * erp /* [0..39] OUT */ ) { word exp, mant; word xMp[ 13 ]; APCM_quantization_xmaxc_to_exp_mant( xmaxcr, &exp, &mant ); APCM_inverse_quantization( xMcr, mant, exp, xMp ); RPE_grid_positioning( Mcr, xMp, erp ); } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_option.c0000644000175000017500000000213011744612271021250 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "private.h" #include "gsm.h" #include "proto.h" int gsm_option P3((r, opt, val), gsm r, int opt, int * val) { int result = -1; switch (opt) { case GSM_OPT_LTP_CUT: #ifdef LTP_CUT result = r->ltp_cut; if (val) r->ltp_cut = *val; #endif break; case GSM_OPT_VERBOSE: #ifndef NDEBUG result = r->verbose; if (val) r->verbose = *val; #endif break; case GSM_OPT_FAST: #if defined(FAST) && defined(USE_FLOAT_MUL) result = r->fast; if (val) r->fast = !!*val; #endif break; case GSM_OPT_FRAME_CHAIN: #ifdef WAV49 result = r->frame_chain; if (val) r->frame_chain = *val; #endif break; case GSM_OPT_FRAME_INDEX: #ifdef WAV49 result = r->frame_index; if (val) r->frame_index = *val; #endif break; case GSM_OPT_WAV49: #ifdef WAV49 result = r->wav_fmt; if (val) r->wav_fmt = !!*val; #endif break; default: break; } return result; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_create.c0000644000175000017500000000137411700377701021212 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ static char const ident[] = "$Header$"; #include "config.h" #ifdef HAS_STRING_H #include #else # include "proto.h" extern char * memset P((char *, int, int)); #endif #ifdef HAS_STDLIB_H # include #else # ifdef HAS_MALLOC_H # include # else extern char * malloc(); # endif #endif #include #include "gsm.h" #include "private.h" #include "proto.h" gsm gsm_create P0() { gsm r; r = (gsm)malloc(sizeof(struct gsm_state)); if (!r) return r; memset((char *)r, 0, sizeof(*r)); r->nrp = 40; return r; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_explode.c0000644000175000017500000002547311744612271021417 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "private.h" #include "gsm.h" #include "proto.h" int gsm_explode P3((s, c, target), gsm s, gsm_byte * c, gsm_signal * target) { # define LARc target # define Nc *((gsm_signal (*) [17])(target + 8)) # define bc *((gsm_signal (*) [17])(target + 9)) # define Mc *((gsm_signal (*) [17])(target + 10)) # define xmaxc *((gsm_signal (*) [17])(target + 11)) #ifdef WAV49 if (s->wav_fmt) { uword sr = 0; if (s->frame_index == 1) { sr = *c++; LARc[0] = sr & 0x3f; sr >>= 6; sr |= (uword)*c++ << 2; LARc[1] = sr & 0x3f; sr >>= 6; sr |= (uword)*c++ << 4; LARc[2] = sr & 0x1f; sr >>= 5; LARc[3] = sr & 0x1f; sr >>= 5; sr |= (uword)*c++ << 2; LARc[4] = sr & 0xf; sr >>= 4; LARc[5] = sr & 0xf; sr >>= 4; sr |= (uword)*c++ << 2; /* 5 */ LARc[6] = sr & 0x7; sr >>= 3; LARc[7] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[0] = sr & 0x7f; sr >>= 7; bc[0] = sr & 0x3; sr >>= 2; Mc[0] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[0] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 12) xmc[0] = sr & 0x7; sr >>= 3; sr = *c++; xmc[1] = sr & 0x7; sr >>= 3; xmc[2] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[3] = sr & 0x7; sr >>= 3; xmc[4] = sr & 0x7; sr >>= 3; xmc[5] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 10 */ xmc[6] = sr & 0x7; sr >>= 3; xmc[7] = sr & 0x7; sr >>= 3; xmc[8] = sr & 0x7; sr >>= 3; sr = *c++; xmc[9] = sr & 0x7; sr >>= 3; xmc[10] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[11] = sr & 0x7; sr >>= 3; xmc[12] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[1] = sr & 0x7f; sr >>= 7; bc[1] = sr & 0x3; sr >>= 2; Mc[1] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[1] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 29 - 13) xmc[13] = sr & 0x7; sr >>= 3; sr = *c++; /* 15 */ xmc[14] = sr & 0x7; sr >>= 3; xmc[15] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[16] = sr & 0x7; sr >>= 3; xmc[17] = sr & 0x7; sr >>= 3; xmc[18] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[19] = sr & 0x7; sr >>= 3; xmc[20] = sr & 0x7; sr >>= 3; xmc[21] = sr & 0x7; sr >>= 3; sr = *c++; xmc[22] = sr & 0x7; sr >>= 3; xmc[23] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[24] = sr & 0x7; sr >>= 3; xmc[25] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; /* 20 */ Nc[2] = sr & 0x7f; sr >>= 7; bc[2] = sr & 0x3; sr >>= 2; Mc[2] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[2] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 46 - 26) xmc[26] = sr & 0x7; sr >>= 3; sr = *c++; xmc[27] = sr & 0x7; sr >>= 3; xmc[28] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[29] = sr & 0x7; sr >>= 3; xmc[30] = sr & 0x7; sr >>= 3; xmc[31] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[32] = sr & 0x7; sr >>= 3; xmc[33] = sr & 0x7; sr >>= 3; xmc[34] = sr & 0x7; sr >>= 3; sr = *c++; /* 25 */ xmc[35] = sr & 0x7; sr >>= 3; xmc[36] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[37] = sr & 0x7; sr >>= 3; xmc[38] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[3] = sr & 0x7f; sr >>= 7; bc[3] = sr & 0x3; sr >>= 2; Mc[3] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[3] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 63 - 39) xmc[39] = sr & 0x7; sr >>= 3; sr = *c++; xmc[40] = sr & 0x7; sr >>= 3; xmc[41] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; /* 30 */ xmc[42] = sr & 0x7; sr >>= 3; xmc[43] = sr & 0x7; sr >>= 3; xmc[44] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[45] = sr & 0x7; sr >>= 3; xmc[46] = sr & 0x7; sr >>= 3; xmc[47] = sr & 0x7; sr >>= 3; sr = *c++; xmc[48] = sr & 0x7; sr >>= 3; xmc[49] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[50] = sr & 0x7; sr >>= 3; xmc[51] = sr & 0x7; sr >>= 3; s->frame_chain = sr & 0xf; } else { sr = s->frame_chain; sr |= (uword)*c++ << 4; /* 1 */ LARc[0] = sr & 0x3f; sr >>= 6; LARc[1] = sr & 0x3f; sr >>= 6; sr = *c++; LARc[2] = sr & 0x1f; sr >>= 5; sr |= (uword)*c++ << 3; LARc[3] = sr & 0x1f; sr >>= 5; LARc[4] = sr & 0xf; sr >>= 4; sr |= (uword)*c++ << 2; LARc[5] = sr & 0xf; sr >>= 4; LARc[6] = sr & 0x7; sr >>= 3; LARc[7] = sr & 0x7; sr >>= 3; sr = *c++; /* 5 */ Nc[0] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[0] = sr & 0x3; sr >>= 2; Mc[0] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[0] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 12) xmc[0] = sr & 0x7; sr >>= 3; xmc[1] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[2] = sr & 0x7; sr >>= 3; xmc[3] = sr & 0x7; sr >>= 3; xmc[4] = sr & 0x7; sr >>= 3; sr = *c++; xmc[5] = sr & 0x7; sr >>= 3; xmc[6] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; /* 10 */ xmc[7] = sr & 0x7; sr >>= 3; xmc[8] = sr & 0x7; sr >>= 3; xmc[9] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[10] = sr & 0x7; sr >>= 3; xmc[11] = sr & 0x7; sr >>= 3; xmc[12] = sr & 0x7; sr >>= 3; sr = *c++; Nc[1] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[1] = sr & 0x3; sr >>= 2; Mc[1] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[1] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 29 - 13) xmc[13] = sr & 0x7; sr >>= 3; xmc[14] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 15 */ xmc[15] = sr & 0x7; sr >>= 3; xmc[16] = sr & 0x7; sr >>= 3; xmc[17] = sr & 0x7; sr >>= 3; sr = *c++; xmc[18] = sr & 0x7; sr >>= 3; xmc[19] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[20] = sr & 0x7; sr >>= 3; xmc[21] = sr & 0x7; sr >>= 3; xmc[22] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[23] = sr & 0x7; sr >>= 3; xmc[24] = sr & 0x7; sr >>= 3; xmc[25] = sr & 0x7; sr >>= 3; sr = *c++; Nc[2] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; /* 20 */ bc[2] = sr & 0x3; sr >>= 2; Mc[2] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[2] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 46 - 26) xmc[26] = sr & 0x7; sr >>= 3; xmc[27] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[28] = sr & 0x7; sr >>= 3; xmc[29] = sr & 0x7; sr >>= 3; xmc[30] = sr & 0x7; sr >>= 3; sr = *c++; xmc[31] = sr & 0x7; sr >>= 3; xmc[32] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[33] = sr & 0x7; sr >>= 3; xmc[34] = sr & 0x7; sr >>= 3; xmc[35] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 25 */ xmc[36] = sr & 0x7; sr >>= 3; xmc[37] = sr & 0x7; sr >>= 3; xmc[38] = sr & 0x7; sr >>= 3; sr = *c++; Nc[3] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[3] = sr & 0x3; sr >>= 2; Mc[3] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[3] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (target + 63 - 39) xmc[39] = sr & 0x7; sr >>= 3; xmc[40] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[41] = sr & 0x7; sr >>= 3; xmc[42] = sr & 0x7; sr >>= 3; xmc[43] = sr & 0x7; sr >>= 3; sr = *c++; /* 30 */ xmc[44] = sr & 0x7; sr >>= 3; xmc[45] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[46] = sr & 0x7; sr >>= 3; xmc[47] = sr & 0x7; sr >>= 3; xmc[48] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[49] = sr & 0x7; sr >>= 3; xmc[50] = sr & 0x7; sr >>= 3; xmc[51] = sr & 0x7; sr >>= 3; } } else #endif { /* GSM_MAGIC = (*c >> 4) & 0xF; */ if (((*c >> 4) & 0x0F) != GSM_MAGIC) return -1; LARc[0] = (*c++ & 0xF) << 2; /* 1 */ LARc[0] |= (*c >> 6) & 0x3; LARc[1] = *c++ & 0x3F; LARc[2] = (*c >> 3) & 0x1F; LARc[3] = (*c++ & 0x7) << 2; LARc[3] |= (*c >> 6) & 0x3; LARc[4] = (*c >> 2) & 0xF; LARc[5] = (*c++ & 0x3) << 2; LARc[5] |= (*c >> 6) & 0x3; LARc[6] = (*c >> 3) & 0x7; LARc[7] = *c++ & 0x7; Nc[0] = (*c >> 1) & 0x7F; bc[0] = (*c++ & 0x1) << 1; bc[0] |= (*c >> 7) & 0x1; Mc[0] = (*c >> 5) & 0x3; xmaxc[0] = (*c++ & 0x1F) << 1; xmaxc[0] |= (*c >> 7) & 0x1; #undef xmc #define xmc (target + 12) xmc[0] = (*c >> 4) & 0x7; xmc[1] = (*c >> 1) & 0x7; xmc[2] = (*c++ & 0x1) << 2; xmc[2] |= (*c >> 6) & 0x3; xmc[3] = (*c >> 3) & 0x7; xmc[4] = *c++ & 0x7; xmc[5] = (*c >> 5) & 0x7; xmc[6] = (*c >> 2) & 0x7; xmc[7] = (*c++ & 0x3) << 1; /* 10 */ xmc[7] |= (*c >> 7) & 0x1; xmc[8] = (*c >> 4) & 0x7; xmc[9] = (*c >> 1) & 0x7; xmc[10] = (*c++ & 0x1) << 2; xmc[10] |= (*c >> 6) & 0x3; xmc[11] = (*c >> 3) & 0x7; xmc[12] = *c++ & 0x7; Nc[1] = (*c >> 1) & 0x7F; bc[1] = (*c++ & 0x1) << 1; bc[1] |= (*c >> 7) & 0x1; Mc[1] = (*c >> 5) & 0x3; xmaxc[1] = (*c++ & 0x1F) << 1; xmaxc[1] |= (*c >> 7) & 0x1; #undef xmc #define xmc (target + 29 - 13) xmc[13] = (*c >> 4) & 0x7; xmc[14] = (*c >> 1) & 0x7; xmc[15] = (*c++ & 0x1) << 2; xmc[15] |= (*c >> 6) & 0x3; xmc[16] = (*c >> 3) & 0x7; xmc[17] = *c++ & 0x7; xmc[18] = (*c >> 5) & 0x7; xmc[19] = (*c >> 2) & 0x7; xmc[20] = (*c++ & 0x3) << 1; xmc[20] |= (*c >> 7) & 0x1; xmc[21] = (*c >> 4) & 0x7; xmc[22] = (*c >> 1) & 0x7; xmc[23] = (*c++ & 0x1) << 2; xmc[23] |= (*c >> 6) & 0x3; xmc[24] = (*c >> 3) & 0x7; xmc[25] = *c++ & 0x7; Nc[2] = (*c >> 1) & 0x7F; bc[2] = (*c++ & 0x1) << 1; /* 20 */ bc[2] |= (*c >> 7) & 0x1; Mc[2] = (*c >> 5) & 0x3; xmaxc[2] = (*c++ & 0x1F) << 1; xmaxc[2] |= (*c >> 7) & 0x1; #undef xmc #define xmc (target + 46 - 26) xmc[26] = (*c >> 4) & 0x7; xmc[27] = (*c >> 1) & 0x7; xmc[28] = (*c++ & 0x1) << 2; xmc[28] |= (*c >> 6) & 0x3; xmc[29] = (*c >> 3) & 0x7; xmc[30] = *c++ & 0x7; xmc[31] = (*c >> 5) & 0x7; xmc[32] = (*c >> 2) & 0x7; xmc[33] = (*c++ & 0x3) << 1; xmc[33] |= (*c >> 7) & 0x1; xmc[34] = (*c >> 4) & 0x7; xmc[35] = (*c >> 1) & 0x7; xmc[36] = (*c++ & 0x1) << 2; xmc[36] |= (*c >> 6) & 0x3; xmc[37] = (*c >> 3) & 0x7; xmc[38] = *c++ & 0x7; Nc[3] = (*c >> 1) & 0x7F; bc[3] = (*c++ & 0x1) << 1; bc[3] |= (*c >> 7) & 0x1; Mc[3] = (*c >> 5) & 0x3; xmaxc[3] = (*c++ & 0x1F) << 1; xmaxc[3] |= (*c >> 7) & 0x1; #undef xmc #define xmc (target + 63 - 39) xmc[39] = (*c >> 4) & 0x7; xmc[40] = (*c >> 1) & 0x7; xmc[41] = (*c++ & 0x1) << 2; xmc[41] |= (*c >> 6) & 0x3; xmc[42] = (*c >> 3) & 0x7; xmc[43] = *c++ & 0x7; /* 30 */ xmc[44] = (*c >> 5) & 0x7; xmc[45] = (*c >> 2) & 0x7; xmc[46] = (*c++ & 0x3) << 1; xmc[46] |= (*c >> 7) & 0x1; xmc[47] = (*c >> 4) & 0x7; xmc[48] = (*c >> 1) & 0x7; xmc[49] = (*c++ & 0x1) << 2; xmc[49] |= (*c >> 6) & 0x3; xmc[50] = (*c >> 3) & 0x7; xmc[51] = *c & 0x7; /* 33 */ } return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/config.h0000644000175000017500000000240611700377701020350 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /*$Header$*/ #ifndef CONFIG_H #define CONFIG_H #undef SIGHANDLER_T /* signal handlers are void */ #undef HAS_SYSV_SIGNAL /* sigs not blocked/reset? */ #define HAS_STDLIB_H 1 /* /usr/include/stdlib.h */ #undef HAS_LIMITS_H /* /usr/include/limits.h */ #define HAS_FCNTL_H 1 /* /usr/include/fcntl.h */ #undef HAS_ERRNO_DECL /* errno.h declares errno */ #define HAS_FSTAT 1 /* fstat syscall */ #define HAS_FCHMOD 1 /* fchmod syscall */ #define HAS_CHMOD 1 /* chmod syscall */ #define HAS_FCHOWN 1 /* fchown syscall */ #define HAS_CHOWN 1 /* chown syscall */ #undef HAS__FSETMODE /* _fsetmode -- set file mode */ #define HAS_STRING_H 1 /* /usr/include/string.h */ #undef HAS_STRINGS_H /* /usr/include/strings.h */ #define HAS_UNISTD_H 1 /* /usr/include/unistd.h */ #define HAS_UTIME 1 /* POSIX utime(path, times) */ #undef HAS_UTIMES /* use utimes() syscall instead */ #define HAS_UTIME_H 1 /* UTIME header file */ #undef HAS_UTIMBUF /* struct utimbuf */ #undef HAS_UTIMEUSEC /* microseconds in utimbuf? */ #endif /* CONFIG_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm/proto.h0000644000175000017500000000275711744612271020261 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /*$Header$*/ #ifndef PROTO_H #define PROTO_H #if __cplusplus # define NeedFunctionPrototypes 1 #endif #if __STDC__ # define NeedFunctionPrototypes 1 #endif #ifdef _NO_PROTO # undef NeedFunctionPrototypes #endif #undef P /* gnu stdio.h actually defines this... */ #undef P0 #undef P1 #undef P2 #undef P3 #undef P4 #undef P5 #undef P6 #undef P7 #undef P8 #if NeedFunctionPrototypes # define P( protos ) protos # define P0() (void) # define P1(x, a) (a) # define P2(x, a, b) (a, b) # define P3(x, a, b, c) (a, b, c) # define P4(x, a, b, c, d) (a, b, c, d) # define P5(x, a, b, c, d, e) (a, b, c, d, e) # define P6(x, a, b, c, d, e, f) (a, b, c, d, e, f) # define P7(x, a, b, c, d, e, f, g) (a, b, c, d, e, f, g) # define P8(x, a, b, c, d, e, f, g, h) (a, b, c, d, e, f, g, h) #else /* !NeedFunctionPrototypes */ # define P( protos ) ( /* protos */ ) # define P0() () # define P1(x, a) x a; # define P2(x, a, b) x a; b; # define P3(x, a, b, c) x a; b; c; # define P4(x, a, b, c, d) x a; b; c; d; # define P5(x, a, b, c, d, e) x a; b; c; d; e; # define P6(x, a, b, c, d, e, f) x a; b; c; d; e; f; # define P7(x, a, b, c, d, e, f, g) x a; b; c; d; e; f; g; # define P8(x, a, b, c, d, e, f, g, h) x a; b; c; d; e; f; g; h; #endif /* !NeedFunctionPrototypes */ #endif /* PROTO_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm/private.h0000644000175000017500000001701111744612271020555 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /*$Header$*/ #ifndef PRIVATE_H #define PRIVATE_H typedef short word; /* 16 bit signed int */ typedef long longword; /* 32 bit signed int */ typedef unsigned short uword; /* unsigned word */ typedef unsigned long ulongword; /* unsigned longword */ struct gsm_state { word dp0[ 280 ]; word z1; /* preprocessing.c, Offset_com. */ longword L_z2; /* Offset_com. */ int mp; /* Preemphasis */ word u[8]; /* short_term_aly_filter.c */ word LARpp[2][8]; /* */ word j; /* */ word ltp_cut; /* long_term.c, LTP crosscorr. */ word nrp; /* 40 */ /* long_term.c, synthesis */ word v[9]; /* short_term.c, synthesis */ word msr; /* decoder.c, Postprocessing */ char verbose; /* only used if !NDEBUG */ char fast; /* only used if FAST */ char wav_fmt; /* only used if WAV49 defined */ unsigned char frame_index; /* odd/even chaining */ unsigned char frame_chain; /* half-byte to carry forward */ }; #define MIN_WORD (-32767 - 1) #define MAX_WORD 32767 #define MIN_LONGWORD (-2147483647 - 1) #define MAX_LONGWORD 2147483647 #ifdef SASR /* flag: >> is a signed arithmetic shift right */ #undef SASR #define SASR(x, by) ((x) >> (by)) #else #define SASR(x, by) ((x) >= 0 ? (x) >> (by) : (~(-((x) + 1) >> (by)))) #endif /* SASR */ #include "proto.h" /* * Prototypes from add.c */ extern word gsm_mult P((word a, word b)); extern longword gsm_L_mult P((word a, word b)); extern word gsm_mult_r P((word a, word b)); extern word gsm_div P((word num, word denum)); extern word gsm_add P(( word a, word b )); extern longword gsm_L_add P(( longword a, longword b )); extern word gsm_sub P((word a, word b)); extern longword gsm_L_sub P((longword a, longword b)); extern word gsm_abs P((word a)); extern word gsm_norm P(( longword a )); extern longword gsm_L_asl P((longword a, int n)); extern word gsm_asl P((word a, int n)); extern longword gsm_L_asr P((longword a, int n)); extern word gsm_asr P((word a, int n)); /* * Inlined functions from add.h */ /* * #define GSM_MULT_R(a, b) (* word a, word b, !(a == b == MIN_WORD) *) \ * (0x0FFFF & SASR(((longword)(a) * (longword)(b) + 16384), 15)) */ #define GSM_MULT_R(a, b) /* word a, word b, !(a == b == MIN_WORD) */ \ (SASR( ((longword)(a) * (longword)(b) + 16384), 15 )) # define GSM_MULT(a,b) /* word a, word b, !(a == b == MIN_WORD) */ \ (SASR( ((longword)(a) * (longword)(b)), 15 )) # define GSM_L_MULT(a, b) /* word a, word b */ \ (((longword)(a) * (longword)(b)) << 1) # define GSM_L_ADD(a, b) \ ( (a) < 0 ? ( (b) >= 0 ? (a) + (b) \ : (utmp = (ulongword)-((a) + 1) + (ulongword)-((b) + 1)) \ >= MAX_LONGWORD ? MIN_LONGWORD : -(longword)utmp-2 ) \ : ((b) <= 0 ? (a) + (b) \ : (utmp = (ulongword)(a) + (ulongword)(b)) >= MAX_LONGWORD \ ? MAX_LONGWORD : utmp)) /* * # define GSM_ADD(a, b) \ * ((ltmp = (longword)(a) + (longword)(b)) >= MAX_WORD \ * ? MAX_WORD : ltmp <= MIN_WORD ? MIN_WORD : ltmp) */ /* Nonportable, but faster: */ #define GSM_ADD(a, b) \ ((ulongword)((ltmp = (longword)(a) + (longword)(b)) - MIN_WORD) > \ MAX_WORD - MIN_WORD ? (ltmp > 0 ? MAX_WORD : MIN_WORD) : ltmp) # define GSM_SUB(a, b) \ ((ltmp = (longword)(a) - (longword)(b)) >= MAX_WORD \ ? MAX_WORD : ltmp <= MIN_WORD ? MIN_WORD : ltmp) # define GSM_ABS(a) ((a) < 0 ? ((a) == MIN_WORD ? MAX_WORD : -(a)) : (a)) /* Use these if necessary: # define GSM_MULT_R(a, b) gsm_mult_r(a, b) # define GSM_MULT(a, b) gsm_mult(a, b) # define GSM_L_MULT(a, b) gsm_L_mult(a, b) # define GSM_L_ADD(a, b) gsm_L_add(a, b) # define GSM_ADD(a, b) gsm_add(a, b) # define GSM_SUB(a, b) gsm_sub(a, b) # define GSM_ABS(a) gsm_abs(a) */ /* * More prototypes from implementations.. */ extern void Gsm_Coder P(( struct gsm_state * S, word * s, /* [0..159] samples IN */ word * LARc, /* [0..7] LAR coefficients OUT */ word * Nc, /* [0..3] LTP lag OUT */ word * bc, /* [0..3] coded LTP gain OUT */ word * Mc, /* [0..3] RPE grid selection OUT */ word * xmaxc,/* [0..3] Coded maximum amplitude OUT */ word * xMc /* [13*4] normalized RPE samples OUT */)); extern void Gsm_Long_Term_Predictor P(( /* 4x for 160 samples */ struct gsm_state * S, word * d, /* [0..39] residual signal IN */ word * dp, /* [-120..-1] d' IN */ word * e, /* [0..40] OUT */ word * dpp, /* [0..40] OUT */ word * Nc, /* correlation lag OUT */ word * bc /* gain factor OUT */)); extern void Gsm_LPC_Analysis P(( struct gsm_state * S, word * s, /* 0..159 signals IN/OUT */ word * LARc)); /* 0..7 LARc's OUT */ extern void Gsm_Preprocess P(( struct gsm_state * S, word * s, word * so)); extern void Gsm_Encoding P(( struct gsm_state * S, word * e, word * ep, word * xmaxc, word * Mc, word * xMc)); extern void Gsm_Short_Term_Analysis_Filter P(( struct gsm_state * S, word * LARc, /* coded log area ratio [0..7] IN */ word * d /* st res. signal [0..159] IN/OUT */)); extern void Gsm_Decoder P(( struct gsm_state * S, word * LARcr, /* [0..7] IN */ word * Ncr, /* [0..3] IN */ word * bcr, /* [0..3] IN */ word * Mcr, /* [0..3] IN */ word * xmaxcr, /* [0..3] IN */ word * xMcr, /* [0..13*4] IN */ word * s)); /* [0..159] OUT */ extern void Gsm_Decoding P(( struct gsm_state * S, word xmaxcr, word Mcr, word * xMcr, /* [0..12] IN */ word * erp)); /* [0..39] OUT */ extern void Gsm_Long_Term_Synthesis_Filtering P(( struct gsm_state* S, word Ncr, word bcr, word * erp, /* [0..39] IN */ word * drp)); /* [-120..-1] IN, [0..40] OUT */ void Gsm_RPE_Decoding P(( struct gsm_state *S, word xmaxcr, word Mcr, word * xMcr, /* [0..12], 3 bits IN */ word * erp)); /* [0..39] OUT */ void Gsm_RPE_Encoding P(( struct gsm_state * S, word * e, /* -5..-1][0..39][40..44 IN/OUT */ word * xmaxc, /* OUT */ word * Mc, /* OUT */ word * xMc)); /* [0..12] OUT */ extern void Gsm_Short_Term_Synthesis_Filter P(( struct gsm_state * S, word * LARcr, /* log area ratios [0..7] IN */ word * drp, /* received d [0...39] IN */ word * s)); /* signal s [0..159] OUT */ extern void Gsm_Update_of_reconstructed_short_time_residual_signal P(( word * dpp, /* [0...39] IN */ word * ep, /* [0...39] IN */ word * dp)); /* [-120...-1] IN/OUT */ /* * Tables from table.c */ #ifndef GSM_TABLE_C extern word gsm_A[8], gsm_B[8], gsm_MIC[8], gsm_MAC[8]; extern word gsm_INVA[8]; extern word gsm_DLB[4], gsm_QLB[4]; extern word gsm_H[11]; extern word gsm_NRFAC[8]; extern word gsm_FAC[8]; #endif /* GSM_TABLE_C */ /* * Debugging */ #ifdef NDEBUG # define gsm_debug_words(a, b, c, d) /* nil */ # define gsm_debug_longwords(a, b, c, d) /* nil */ # define gsm_debug_word(a, b) /* nil */ # define gsm_debug_longword(a, b) /* nil */ #else /* !NDEBUG => DEBUG */ extern void gsm_debug_words P((char * name, int, int, word *)); extern void gsm_debug_longwords P((char * name, int, int, longword *)); extern void gsm_debug_longword P((char * name, longword)); extern void gsm_debug_word P((char * name, word)); #endif /* !NDEBUG */ #include "unproto.h" #endif /* PRIVATE_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm/code.c0000644000175000017500000000465711744612271020024 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "config.h" #ifdef HAS_STDLIB_H #include #else # include "proto.h" extern char * memcpy P((char *, char *, int)); #endif #include "private.h" #include "gsm.h" #include "proto.h" #include /* * 4.2 FIXED POINT IMPLEMENTATION OF THE RPE-LTP CODER */ void Gsm_Coder P8((S,s,LARc,Nc,bc,Mc,xmaxc,xMc), struct gsm_state * S, word * s, /* [0..159] samples IN */ /* * The RPE-LTD coder works on a frame by frame basis. The length of * the frame is equal to 160 samples. Some computations are done * once per frame to produce at the output of the coder the * LARc[1..8] parameters which are the coded LAR coefficients and * also to realize the inverse filtering operation for the entire * frame (160 samples of signal d[0..159]). These parts produce at * the output of the coder: */ word * LARc, /* [0..7] LAR coefficients OUT */ /* * Procedure 4.2.11 to 4.2.18 are to be executed four times per * frame. That means once for each sub-segment RPE-LTP analysis of * 40 samples. These parts produce at the output of the coder: */ word * Nc, /* [0..3] LTP lag OUT */ word * bc, /* [0..3] coded LTP gain OUT */ word * Mc, /* [0..3] RPE grid selection OUT */ word * xmaxc,/* [0..3] Coded maximum amplitude OUT */ word * xMc /* [13*4] normalized RPE samples OUT */ ) { int k; word * dp = S->dp0 + 120; /* [ -120...-1 ] */ word * dpp = dp; /* [ 0...39 ] */ static word e[50]; word so[160]; Gsm_Preprocess (S, s, so); Gsm_LPC_Analysis (S, so, LARc); Gsm_Short_Term_Analysis_Filter (S, LARc, so); for (k = 0; k <= 3; k++, xMc += 13) { Gsm_Long_Term_Predictor ( S, so+k*40, /* d [0..39] IN */ dp, /* dp [-120..-1] IN */ e + 5, /* e [0..39] OUT */ dpp, /* dpp [0..39] OUT */ Nc++, bc++); Gsm_RPE_Encoding ( S, e + 5, /* e ][0..39][ IN/OUT */ xmaxc++, Mc++, xMc ); /* * Gsm_Update_of_reconstructed_short_time_residual_signal * ( dpp, e + 5, dp ); */ { register int i; register longword ltmp; for (i = 0; i <= 39; i++) dp[ i ] = GSM_ADD( e[5 + i], dpp[i] ); } dp += 40; dpp += 40; } (void)memcpy( (char *)S->dp0, (char *)(S->dp0 + 160), 120 * sizeof(*S->dp0) ); } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm.h0000644000175000017500000000313611744612271017674 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /*$Header$*/ #ifndef GSM_H #define GSM_H #ifdef __cplusplus # define NeedFunctionPrototypes 1 #endif #if __STDC__ # define NeedFunctionPrototypes 1 #endif #ifdef _NO_PROTO # undef NeedFunctionPrototypes #endif #ifdef NeedFunctionPrototypes # include /* for FILE * */ #endif #undef GSM_P #if NeedFunctionPrototypes # define GSM_P( protos ) protos #else # define GSM_P( protos ) ( /* protos */ ) #endif /* * Interface */ typedef struct gsm_state * gsm; typedef short gsm_signal; /* signed 16 bit */ typedef unsigned char gsm_byte; typedef gsm_byte gsm_frame[33]; /* 33 * 8 bits */ #define GSM_MAGIC 0xD /* 13 kbit/s RPE-LTP */ #define GSM_PATCHLEVEL 10 #define GSM_MINOR 0 #define GSM_MAJOR 1 #define GSM_OPT_VERBOSE 1 #define GSM_OPT_FAST 2 #define GSM_OPT_LTP_CUT 3 #define GSM_OPT_WAV49 4 #define GSM_OPT_FRAME_INDEX 5 #define GSM_OPT_FRAME_CHAIN 6 #define GSM_SAMPLES_PER_FRAME 160 extern gsm gsm_create GSM_P((void)); extern void gsm_destroy GSM_P((gsm)); extern int gsm_print GSM_P((FILE *, gsm, gsm_byte *)); extern int gsm_option GSM_P((gsm, int, int *)); extern void gsm_encode GSM_P((gsm, gsm_signal *, gsm_byte *)); extern int gsm_decode GSM_P((gsm, gsm_byte *, gsm_signal *)); extern int gsm_explode GSM_P((gsm, gsm_byte *, gsm_signal *)); extern void gsm_implode GSM_P((gsm, gsm_signal *, gsm_byte *)); #undef GSM_P #endif /* GSM_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm/preprocess.c0000644000175000017500000000462211744612271021267 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include #include "private.h" #include "gsm.h" #include "proto.h" /* 4.2.0 .. 4.2.3 PREPROCESSING SECTION * * After A-law to linear conversion (or directly from the * Ato D converter) the following scaling is assumed for * input to the RPE-LTP algorithm: * * in: 0.1.....................12 * S.v.v.v.v.v.v.v.v.v.v.v.v.*.*.* * * Where S is the sign bit, v a valid bit, and * a "don't care" bit. * The original signal is called sop[..] * * out: 0.1................... 12 * S.S.v.v.v.v.v.v.v.v.v.v.v.v.0.0 */ void Gsm_Preprocess P3((S, s, so), struct gsm_state * S, word * s, word * so ) /* [0..159] IN/OUT */ { word z1 = S->z1; longword L_z2 = S->L_z2; word mp = S->mp; word s1; longword L_s2; longword L_temp; word msp, lsp; word SO; longword ltmp; /* for ADD */ ulongword utmp; /* for L_ADD */ register int k = 160; while (k--) { /* 4.2.1 Downscaling of the input signal */ SO = SASR( *s, 3 ) << 2; s++; assert (SO >= -0x4000); /* downscaled by */ assert (SO <= 0x3FFC); /* previous routine. */ /* 4.2.2 Offset compensation * * This part implements a high-pass filter and requires extended * arithmetic precision for the recursive part of this filter. * The input of this procedure is the array so[0...159] and the * output the array sof[ 0...159 ]. */ /* Compute the non-recursive part */ s1 = SO - z1; /* s1 = gsm_sub( *so, z1 ); */ z1 = SO; assert(s1 != MIN_WORD); /* Compute the recursive part */ L_s2 = s1; L_s2 <<= 15; /* Execution of a 31 bv 16 bits multiplication */ msp = SASR( L_z2, 15 ); lsp = L_z2-((longword)msp<<15); /* gsm_L_sub(L_z2,(msp<<15)); */ L_s2 += GSM_MULT_R( lsp, 32735 ); L_temp = (longword)msp * 32735; /* GSM_L_MULT(msp,32735) >> 1;*/ L_z2 = GSM_L_ADD( (ulongword)L_temp, (ulongword)L_s2 ); /* Compute sof[k] with rounding */ L_temp = GSM_L_ADD( (ulongword)L_z2, 16384 ); /* 4.2.3 Preemphasis */ msp = GSM_MULT_R( mp, -28180 ); mp = SASR( L_temp, 15 ); *so++ = GSM_ADD( mp, msp ); } S->z1 = z1; S->L_z2 = L_z2; S->mp = mp; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/table.c0000644000175000017500000000401311744612271020163 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ /* Most of these tables are inlined at their point of use. */ /* 4.4 TABLES USED IN THE FIXED POINT IMPLEMENTATION OF THE RPE-LTP * CODER AND DECODER * * (Most of them inlined, so watch out.) */ #define GSM_TABLE_C #include "private.h" #include "gsm.h" /* Table 4.1 Quantization of the Log.-Area Ratios */ /* i 1 2 3 4 5 6 7 8 */ word gsm_A[8] = {20480, 20480, 20480, 20480, 13964, 15360, 8534, 9036}; word gsm_B[8] = { 0, 0, 2048, -2560, 94, -1792, -341, -1144}; word gsm_MIC[8] = { -32, -32, -16, -16, -8, -8, -4, -4 }; word gsm_MAC[8] = { 31, 31, 15, 15, 7, 7, 3, 3 }; /* Table 4.2 Tabulation of 1/A[1..8] */ word gsm_INVA[8]={ 13107, 13107, 13107, 13107, 19223, 17476, 31454, 29708 }; /* Table 4.3a Decision level of the LTP gain quantizer */ /* bc 0 1 2 3 */ word gsm_DLB[4] = { 6554, 16384, 26214, 32767 }; /* Table 4.3b Quantization levels of the LTP gain quantizer */ /* bc 0 1 2 3 */ word gsm_QLB[4] = { 3277, 11469, 21299, 32767 }; /* Table 4.4 Coefficients of the weighting filter */ /* i 0 1 2 3 4 5 6 7 8 9 10 */ word gsm_H[11] = {-134, -374, 0, 2054, 5741, 8192, 5741, 2054, 0, -374, -134 }; /* Table 4.5 Normalized inverse mantissa used to compute xM/xmax */ /* i 0 1 2 3 4 5 6 7 */ word gsm_NRFAC[8] = { 29128, 26215, 23832, 21846, 20165, 18725, 17476, 16384 }; /* Table 4.6 Normalized direct mantissa used to compute xM/xmax */ /* i 0 1 2 3 4 5 6 7 */ word gsm_FAC[8] = { 18431, 20479, 22527, 24575, 26623, 28671, 30719, 32767 }; gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_destroy.c0000644000175000017500000000073411700377701021437 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "gsm.h" #include "config.h" #include "proto.h" #ifdef HAS_STDLIB_H # include #else # ifdef HAS_MALLOC_H # include # else extern void free(); # endif #endif void gsm_destroy P1((S), gsm S) { if (S) free((char *)S); } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_encode.c0000644000175000017500000002610611700377701021204 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "private.h" #include "gsm.h" #include "proto.h" void gsm_encode P3((s, source, c), gsm s, gsm_signal * source, gsm_byte * c) { word LARc[8], Nc[4], Mc[4], bc[4], xmaxc[4], xmc[13*4]; Gsm_Coder(s, source, LARc, Nc, bc, Mc, xmaxc, xmc); /* variable size GSM_MAGIC 4 LARc[0] 6 LARc[1] 6 LARc[2] 5 LARc[3] 5 LARc[4] 4 LARc[5] 4 LARc[6] 3 LARc[7] 3 Nc[0] 7 bc[0] 2 Mc[0] 2 xmaxc[0] 6 xmc[0] 3 xmc[1] 3 xmc[2] 3 xmc[3] 3 xmc[4] 3 xmc[5] 3 xmc[6] 3 xmc[7] 3 xmc[8] 3 xmc[9] 3 xmc[10] 3 xmc[11] 3 xmc[12] 3 Nc[1] 7 bc[1] 2 Mc[1] 2 xmaxc[1] 6 xmc[13] 3 xmc[14] 3 xmc[15] 3 xmc[16] 3 xmc[17] 3 xmc[18] 3 xmc[19] 3 xmc[20] 3 xmc[21] 3 xmc[22] 3 xmc[23] 3 xmc[24] 3 xmc[25] 3 Nc[2] 7 bc[2] 2 Mc[2] 2 xmaxc[2] 6 xmc[26] 3 xmc[27] 3 xmc[28] 3 xmc[29] 3 xmc[30] 3 xmc[31] 3 xmc[32] 3 xmc[33] 3 xmc[34] 3 xmc[35] 3 xmc[36] 3 xmc[37] 3 xmc[38] 3 Nc[3] 7 bc[3] 2 Mc[3] 2 xmaxc[3] 6 xmc[39] 3 xmc[40] 3 xmc[41] 3 xmc[42] 3 xmc[43] 3 xmc[44] 3 xmc[45] 3 xmc[46] 3 xmc[47] 3 xmc[48] 3 xmc[49] 3 xmc[50] 3 xmc[51] 3 */ #ifdef WAV49 if (s->wav_fmt) { s->frame_index = !s->frame_index; if (s->frame_index) { uword sr; sr = 0; sr = sr >> 6 | LARc[0] << 10; sr = sr >> 6 | LARc[1] << 10; *c++ = sr >> 4; sr = sr >> 5 | LARc[2] << 11; *c++ = sr >> 7; sr = sr >> 5 | LARc[3] << 11; sr = sr >> 4 | LARc[4] << 12; *c++ = sr >> 6; sr = sr >> 4 | LARc[5] << 12; sr = sr >> 3 | LARc[6] << 13; *c++ = sr >> 7; sr = sr >> 3 | LARc[7] << 13; sr = sr >> 7 | Nc[0] << 9; *c++ = sr >> 5; sr = sr >> 2 | bc[0] << 14; sr = sr >> 2 | Mc[0] << 14; sr = sr >> 6 | xmaxc[0] << 10; *c++ = sr >> 3; sr = sr >> 3 | xmc[0] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[1] << 13; sr = sr >> 3 | xmc[2] << 13; sr = sr >> 3 | xmc[3] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[4] << 13; sr = sr >> 3 | xmc[5] << 13; sr = sr >> 3 | xmc[6] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[7] << 13; sr = sr >> 3 | xmc[8] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[9] << 13; sr = sr >> 3 | xmc[10] << 13; sr = sr >> 3 | xmc[11] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[12] << 13; sr = sr >> 7 | Nc[1] << 9; *c++ = sr >> 5; sr = sr >> 2 | bc[1] << 14; sr = sr >> 2 | Mc[1] << 14; sr = sr >> 6 | xmaxc[1] << 10; *c++ = sr >> 3; sr = sr >> 3 | xmc[13] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[14] << 13; sr = sr >> 3 | xmc[15] << 13; sr = sr >> 3 | xmc[16] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[17] << 13; sr = sr >> 3 | xmc[18] << 13; sr = sr >> 3 | xmc[19] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[20] << 13; sr = sr >> 3 | xmc[21] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[22] << 13; sr = sr >> 3 | xmc[23] << 13; sr = sr >> 3 | xmc[24] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[25] << 13; sr = sr >> 7 | Nc[2] << 9; *c++ = sr >> 5; sr = sr >> 2 | bc[2] << 14; sr = sr >> 2 | Mc[2] << 14; sr = sr >> 6 | xmaxc[2] << 10; *c++ = sr >> 3; sr = sr >> 3 | xmc[26] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[27] << 13; sr = sr >> 3 | xmc[28] << 13; sr = sr >> 3 | xmc[29] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[30] << 13; sr = sr >> 3 | xmc[31] << 13; sr = sr >> 3 | xmc[32] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[33] << 13; sr = sr >> 3 | xmc[34] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[35] << 13; sr = sr >> 3 | xmc[36] << 13; sr = sr >> 3 | xmc[37] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[38] << 13; sr = sr >> 7 | Nc[3] << 9; *c++ = sr >> 5; sr = sr >> 2 | bc[3] << 14; sr = sr >> 2 | Mc[3] << 14; sr = sr >> 6 | xmaxc[3] << 10; *c++ = sr >> 3; sr = sr >> 3 | xmc[39] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[40] << 13; sr = sr >> 3 | xmc[41] << 13; sr = sr >> 3 | xmc[42] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[43] << 13; sr = sr >> 3 | xmc[44] << 13; sr = sr >> 3 | xmc[45] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[46] << 13; sr = sr >> 3 | xmc[47] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[48] << 13; sr = sr >> 3 | xmc[49] << 13; sr = sr >> 3 | xmc[50] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[51] << 13; sr = sr >> 4; *c = sr >> 8; s->frame_chain = *c; } else { uword sr; sr = 0; sr = sr >> 4 | s->frame_chain << 12; sr = sr >> 6 | LARc[0] << 10; *c++ = sr >> 6; sr = sr >> 6 | LARc[1] << 10; *c++ = sr >> 8; sr = sr >> 5 | LARc[2] << 11; sr = sr >> 5 | LARc[3] << 11; *c++ = sr >> 6; sr = sr >> 4 | LARc[4] << 12; sr = sr >> 4 | LARc[5] << 12; *c++ = sr >> 6; sr = sr >> 3 | LARc[6] << 13; sr = sr >> 3 | LARc[7] << 13; *c++ = sr >> 8; sr = sr >> 7 | Nc[0] << 9; sr = sr >> 2 | bc[0] << 14; *c++ = sr >> 7; sr = sr >> 2 | Mc[0] << 14; sr = sr >> 6 | xmaxc[0] << 10; *c++ = sr >> 7; sr = sr >> 3 | xmc[0] << 13; sr = sr >> 3 | xmc[1] << 13; sr = sr >> 3 | xmc[2] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[3] << 13; sr = sr >> 3 | xmc[4] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[5] << 13; sr = sr >> 3 | xmc[6] << 13; sr = sr >> 3 | xmc[7] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[8] << 13; sr = sr >> 3 | xmc[9] << 13; sr = sr >> 3 | xmc[10] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[11] << 13; sr = sr >> 3 | xmc[12] << 13; *c++ = sr >> 8; sr = sr >> 7 | Nc[1] << 9; sr = sr >> 2 | bc[1] << 14; *c++ = sr >> 7; sr = sr >> 2 | Mc[1] << 14; sr = sr >> 6 | xmaxc[1] << 10; *c++ = sr >> 7; sr = sr >> 3 | xmc[13] << 13; sr = sr >> 3 | xmc[14] << 13; sr = sr >> 3 | xmc[15] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[16] << 13; sr = sr >> 3 | xmc[17] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[18] << 13; sr = sr >> 3 | xmc[19] << 13; sr = sr >> 3 | xmc[20] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[21] << 13; sr = sr >> 3 | xmc[22] << 13; sr = sr >> 3 | xmc[23] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[24] << 13; sr = sr >> 3 | xmc[25] << 13; *c++ = sr >> 8; sr = sr >> 7 | Nc[2] << 9; sr = sr >> 2 | bc[2] << 14; *c++ = sr >> 7; sr = sr >> 2 | Mc[2] << 14; sr = sr >> 6 | xmaxc[2] << 10; *c++ = sr >> 7; sr = sr >> 3 | xmc[26] << 13; sr = sr >> 3 | xmc[27] << 13; sr = sr >> 3 | xmc[28] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[29] << 13; sr = sr >> 3 | xmc[30] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[31] << 13; sr = sr >> 3 | xmc[32] << 13; sr = sr >> 3 | xmc[33] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[34] << 13; sr = sr >> 3 | xmc[35] << 13; sr = sr >> 3 | xmc[36] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[37] << 13; sr = sr >> 3 | xmc[38] << 13; *c++ = sr >> 8; sr = sr >> 7 | Nc[3] << 9; sr = sr >> 2 | bc[3] << 14; *c++ = sr >> 7; sr = sr >> 2 | Mc[3] << 14; sr = sr >> 6 | xmaxc[3] << 10; *c++ = sr >> 7; sr = sr >> 3 | xmc[39] << 13; sr = sr >> 3 | xmc[40] << 13; sr = sr >> 3 | xmc[41] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[42] << 13; sr = sr >> 3 | xmc[43] << 13; *c++ = sr >> 8; sr = sr >> 3 | xmc[44] << 13; sr = sr >> 3 | xmc[45] << 13; sr = sr >> 3 | xmc[46] << 13; *c++ = sr >> 7; sr = sr >> 3 | xmc[47] << 13; sr = sr >> 3 | xmc[48] << 13; sr = sr >> 3 | xmc[49] << 13; *c++ = sr >> 6; sr = sr >> 3 | xmc[50] << 13; sr = sr >> 3 | xmc[51] << 13; *c++ = sr >> 8; } } else #endif /* WAV49 */ { *c++ = ((GSM_MAGIC & 0xF) << 4) /* 1 */ | ((LARc[0] >> 2) & 0xF); *c++ = ((LARc[0] & 0x3) << 6) | (LARc[1] & 0x3F); *c++ = ((LARc[2] & 0x1F) << 3) | ((LARc[3] >> 2) & 0x7); *c++ = ((LARc[3] & 0x3) << 6) | ((LARc[4] & 0xF) << 2) | ((LARc[5] >> 2) & 0x3); *c++ = ((LARc[5] & 0x3) << 6) | ((LARc[6] & 0x7) << 3) | (LARc[7] & 0x7); *c++ = ((Nc[0] & 0x7F) << 1) | ((bc[0] >> 1) & 0x1); *c++ = ((bc[0] & 0x1) << 7) | ((Mc[0] & 0x3) << 5) | ((xmaxc[0] >> 1) & 0x1F); *c++ = ((xmaxc[0] & 0x1) << 7) | ((xmc[0] & 0x7) << 4) | ((xmc[1] & 0x7) << 1) | ((xmc[2] >> 2) & 0x1); *c++ = ((xmc[2] & 0x3) << 6) | ((xmc[3] & 0x7) << 3) | (xmc[4] & 0x7); *c++ = ((xmc[5] & 0x7) << 5) /* 10 */ | ((xmc[6] & 0x7) << 2) | ((xmc[7] >> 1) & 0x3); *c++ = ((xmc[7] & 0x1) << 7) | ((xmc[8] & 0x7) << 4) | ((xmc[9] & 0x7) << 1) | ((xmc[10] >> 2) & 0x1); *c++ = ((xmc[10] & 0x3) << 6) | ((xmc[11] & 0x7) << 3) | (xmc[12] & 0x7); *c++ = ((Nc[1] & 0x7F) << 1) | ((bc[1] >> 1) & 0x1); *c++ = ((bc[1] & 0x1) << 7) | ((Mc[1] & 0x3) << 5) | ((xmaxc[1] >> 1) & 0x1F); *c++ = ((xmaxc[1] & 0x1) << 7) | ((xmc[13] & 0x7) << 4) | ((xmc[14] & 0x7) << 1) | ((xmc[15] >> 2) & 0x1); *c++ = ((xmc[15] & 0x3) << 6) | ((xmc[16] & 0x7) << 3) | (xmc[17] & 0x7); *c++ = ((xmc[18] & 0x7) << 5) | ((xmc[19] & 0x7) << 2) | ((xmc[20] >> 1) & 0x3); *c++ = ((xmc[20] & 0x1) << 7) | ((xmc[21] & 0x7) << 4) | ((xmc[22] & 0x7) << 1) | ((xmc[23] >> 2) & 0x1); *c++ = ((xmc[23] & 0x3) << 6) | ((xmc[24] & 0x7) << 3) | (xmc[25] & 0x7); *c++ = ((Nc[2] & 0x7F) << 1) /* 20 */ | ((bc[2] >> 1) & 0x1); *c++ = ((bc[2] & 0x1) << 7) | ((Mc[2] & 0x3) << 5) | ((xmaxc[2] >> 1) & 0x1F); *c++ = ((xmaxc[2] & 0x1) << 7) | ((xmc[26] & 0x7) << 4) | ((xmc[27] & 0x7) << 1) | ((xmc[28] >> 2) & 0x1); *c++ = ((xmc[28] & 0x3) << 6) | ((xmc[29] & 0x7) << 3) | (xmc[30] & 0x7); *c++ = ((xmc[31] & 0x7) << 5) | ((xmc[32] & 0x7) << 2) | ((xmc[33] >> 1) & 0x3); *c++ = ((xmc[33] & 0x1) << 7) | ((xmc[34] & 0x7) << 4) | ((xmc[35] & 0x7) << 1) | ((xmc[36] >> 2) & 0x1); *c++ = ((xmc[36] & 0x3) << 6) | ((xmc[37] & 0x7) << 3) | (xmc[38] & 0x7); *c++ = ((Nc[3] & 0x7F) << 1) | ((bc[3] >> 1) & 0x1); *c++ = ((bc[3] & 0x1) << 7) | ((Mc[3] & 0x3) << 5) | ((xmaxc[3] >> 1) & 0x1F); *c++ = ((xmaxc[3] & 0x1) << 7) | ((xmc[39] & 0x7) << 4) | ((xmc[40] & 0x7) << 1) | ((xmc[41] >> 2) & 0x1); *c++ = ((xmc[41] & 0x3) << 6) /* 30 */ | ((xmc[42] & 0x7) << 3) | (xmc[43] & 0x7); *c++ = ((xmc[44] & 0x7) << 5) | ((xmc[45] & 0x7) << 2) | ((xmc[46] >> 1) & 0x3); *c++ = ((xmc[46] & 0x1) << 7) | ((xmc[47] & 0x7) << 4) | ((xmc[48] & 0x7) << 1) | ((xmc[49] >> 2) & 0x1); *c++ = ((xmc[49] & 0x3) << 6) | ((xmc[50] & 0x7) << 3) | (xmc[51] & 0x7); } } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/debug.c0000644000175000017500000000266311744612271020173 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "private.h" #ifndef NDEBUG /* If NDEBUG _is_ defined and no debugging should be performed, * calls to functions in this module are #defined to nothing * in private.h. */ #include #include "proto.h" void gsm_debug_words P4( (name, from, to, ptr), char * name, int from, int to, word * ptr) { int nprinted = 0; fprintf( stderr, "%s [%d .. %d]: ", name, from, to ); while (from <= to) { fprintf(stderr, "%d ", ptr[ from ] ); from++; if (nprinted++ >= 7) { nprinted = 0; if (from < to) putc('\n', stderr); } } putc('\n', stderr); } void gsm_debug_longwords P4( (name, from, to, ptr), char * name, int from, int to, longword * ptr) { int nprinted = 0; fprintf( stderr, "%s [%d .. %d]: ", name, from, to ); while (from <= to) { fprintf(stderr, "%ld ", ptr[ from ] ); from++; if (nprinted++ >= 7) { nprinted = 0; if (from < to) putc('\n', stderr); } } putc('\n', stderr); } void gsm_debug_longword P2( (name, value), char * name, longword value ) { fprintf(stderr, "%s: %ld\n", name, (long)value ); } void gsm_debug_word P2( (name, value), char * name, word value ) { fprintf(stderr, "%s: %ld\n", name, (long)value); } #endif gnuradio-3.7.2.1/gr-vocoder/lib/gsm/unproto.h0000644000175000017500000000057711700377701020620 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /*$Header$*/ #ifdef PROTO_H /* sic */ #undef PROTO_H #undef P #undef P0 #undef P1 #undef P2 #undef P3 #undef P4 #undef P5 #undef P6 #undef P7 #undef P8 #endif /* PROTO_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm/long_term.c0000644000175000017500000005570011744612271021073 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include #include "private.h" #include "gsm.h" #include "proto.h" /* * 4.2.11 .. 4.2.12 LONG TERM PREDICTOR (LTP) SECTION */ /* * This module computes the LTP gain (bc) and the LTP lag (Nc) * for the long term analysis filter. This is done by calculating a * maximum of the cross-correlation function between the current * sub-segment short term residual signal d[0..39] (output of * the short term analysis filter; for simplification the index * of this array begins at 0 and ends at 39 for each sub-segment of the * RPE-LTP analysis) and the previous reconstructed short term * residual signal dp[ -120 .. -1 ]. A dynamic scaling must be * performed to avoid overflow. */ /* The next procedure exists in six versions. First two integer * version (if USE_FLOAT_MUL is not defined); then four floating * point versions, twice with proper scaling (USE_FLOAT_MUL defined), * once without (USE_FLOAT_MUL and FAST defined, and fast run-time * option used). Every pair has first a Cut version (see the -C * option to toast or the LTP_CUT option to gsm_option()), then the * uncut one. (For a detailed explanation of why this is altogether * a bad idea, see Henry Spencer and Geoff Collyer, ``#ifdef Considered * Harmful''.) */ #ifndef USE_FLOAT_MUL #ifdef LTP_CUT static void Cut_Calculation_of_the_LTP_parameters P5((st, d,dp,bc_out,Nc_out), struct gsm_state * st, register word * d, /* [0..39] IN */ register word * dp, /* [-120..-1] IN */ word * bc_out, /* OUT */ word * Nc_out /* OUT */ ) { register int k, lambda; word Nc, bc; word wt[40]; longword L_result; longword L_max, L_power; word R, S, dmax, scal, best_k; word ltp_cut; register word temp, wt_k; /* Search of the optimum scaling of d[0..39]. */ dmax = 0; for (k = 0; k <= 39; k++) { temp = d[k]; temp = GSM_ABS( temp ); if (temp > dmax) { dmax = temp; best_k = k; } } temp = 0; if (dmax == 0) scal = 0; else { assert(dmax > 0); temp = gsm_norm( (longword)dmax << 16 ); } if (temp > 6) scal = 0; else scal = 6 - temp; assert(scal >= 0); /* Search for the maximum cross-correlation and coding of the LTP lag */ L_max = 0; Nc = 40; /* index for the maximum cross-correlation */ wt_k = SASR(d[best_k], scal); for (lambda = 40; lambda <= 120; lambda++) { L_result = (longword)wt_k * dp[best_k - lambda]; if (L_result > L_max) { Nc = lambda; L_max = L_result; } } *Nc_out = Nc; L_max <<= 1; /* Rescaling of L_max */ assert(scal <= 100 && scal >= -100); L_max = L_max >> (6 - scal); /* sub(6, scal) */ assert( Nc <= 120 && Nc >= 40); /* Compute the power of the reconstructed short term residual * signal dp[..] */ L_power = 0; for (k = 0; k <= 39; k++) { register longword L_temp; L_temp = SASR( dp[k - Nc], 3 ); L_power += L_temp * L_temp; } L_power <<= 1; /* from L_MULT */ /* Normalization of L_max and L_power */ if (L_max <= 0) { *bc_out = 0; return; } if (L_max >= L_power) { *bc_out = 3; return; } temp = gsm_norm( L_power ); R = SASR( L_max << temp, 16 ); S = SASR( L_power << temp, 16 ); /* Coding of the LTP gain */ /* Table 4.3a must be used to obtain the level DLB[i] for the * quantization of the LTP gain b to get the coded version bc. */ for (bc = 0; bc <= 2; bc++) if (R <= gsm_mult(S, gsm_DLB[bc])) break; *bc_out = bc; } #endif /* LTP_CUT */ static void Calculation_of_the_LTP_parameters P4((d,dp,bc_out,Nc_out), register word * d, /* [0..39] IN */ register word * dp, /* [-120..-1] IN */ word * bc_out, /* OUT */ word * Nc_out /* OUT */ ) { register int k, lambda; word Nc, bc; word wt[40]; longword L_max, L_power; word R, S, dmax, scal; register word temp; /* Search of the optimum scaling of d[0..39]. */ dmax = 0; for (k = 0; k <= 39; k++) { temp = d[k]; temp = GSM_ABS( temp ); if (temp > dmax) dmax = temp; } temp = 0; if (dmax == 0) scal = 0; else { assert(dmax > 0); temp = gsm_norm( (longword)dmax << 16 ); } if (temp > 6) scal = 0; else scal = 6 - temp; assert(scal >= 0); /* Initialization of a working array wt */ for (k = 0; k <= 39; k++) wt[k] = SASR( d[k], scal ); /* Search for the maximum cross-correlation and coding of the LTP lag */ L_max = 0; Nc = 40; /* index for the maximum cross-correlation */ for (lambda = 40; lambda <= 120; lambda++) { # undef STEP # define STEP(k) (longword)wt[k] * dp[k - lambda] register longword L_result; L_result = STEP(0) ; L_result += STEP(1) ; L_result += STEP(2) ; L_result += STEP(3) ; L_result += STEP(4) ; L_result += STEP(5) ; L_result += STEP(6) ; L_result += STEP(7) ; L_result += STEP(8) ; L_result += STEP(9) ; L_result += STEP(10) ; L_result += STEP(11) ; L_result += STEP(12) ; L_result += STEP(13) ; L_result += STEP(14) ; L_result += STEP(15) ; L_result += STEP(16) ; L_result += STEP(17) ; L_result += STEP(18) ; L_result += STEP(19) ; L_result += STEP(20) ; L_result += STEP(21) ; L_result += STEP(22) ; L_result += STEP(23) ; L_result += STEP(24) ; L_result += STEP(25) ; L_result += STEP(26) ; L_result += STEP(27) ; L_result += STEP(28) ; L_result += STEP(29) ; L_result += STEP(30) ; L_result += STEP(31) ; L_result += STEP(32) ; L_result += STEP(33) ; L_result += STEP(34) ; L_result += STEP(35) ; L_result += STEP(36) ; L_result += STEP(37) ; L_result += STEP(38) ; L_result += STEP(39) ; if (L_result > L_max) { Nc = lambda; L_max = L_result; } } *Nc_out = Nc; L_max <<= 1; /* Rescaling of L_max */ assert(scal <= 100 && scal >= -100); L_max = L_max >> (6 - scal); /* sub(6, scal) */ assert( Nc <= 120 && Nc >= 40); /* Compute the power of the reconstructed short term residual * signal dp[..] */ L_power = 0; for (k = 0; k <= 39; k++) { register longword L_temp; L_temp = SASR( dp[k - Nc], 3 ); L_power += L_temp * L_temp; } L_power <<= 1; /* from L_MULT */ /* Normalization of L_max and L_power */ if (L_max <= 0) { *bc_out = 0; return; } if (L_max >= L_power) { *bc_out = 3; return; } temp = gsm_norm( L_power ); R = SASR( L_max << temp, 16 ); S = SASR( L_power << temp, 16 ); /* Coding of the LTP gain */ /* Table 4.3a must be used to obtain the level DLB[i] for the * quantization of the LTP gain b to get the coded version bc. */ for (bc = 0; bc <= 2; bc++) if (R <= gsm_mult(S, gsm_DLB[bc])) break; *bc_out = bc; } #else /* USE_FLOAT_MUL */ #ifdef LTP_CUT static void Cut_Calculation_of_the_LTP_parameters P5((st, d,dp,bc_out,Nc_out), struct gsm_state * st, /* IN */ register word * d, /* [0..39] IN */ register word * dp, /* [-120..-1] IN */ word * bc_out, /* OUT */ word * Nc_out /* OUT */ ) { register int k, lambda; word Nc, bc; word ltp_cut; float wt_float[40]; float dp_float_base[120], * dp_float = dp_float_base + 120; longword L_max, L_power; word R, S, dmax, scal; register word temp; /* Search of the optimum scaling of d[0..39]. */ dmax = 0; for (k = 0; k <= 39; k++) { temp = d[k]; temp = GSM_ABS( temp ); if (temp > dmax) dmax = temp; } temp = 0; if (dmax == 0) scal = 0; else { assert(dmax > 0); temp = gsm_norm( (longword)dmax << 16 ); } if (temp > 6) scal = 0; else scal = 6 - temp; assert(scal >= 0); ltp_cut = (longword)SASR(dmax, scal) * st->ltp_cut / 100; /* Initialization of a working array wt */ for (k = 0; k < 40; k++) { register word w = SASR( d[k], scal ); if (w < 0 ? w > -ltp_cut : w < ltp_cut) { wt_float[k] = 0.0; } else { wt_float[k] = w; } } for (k = -120; k < 0; k++) dp_float[k] = dp[k]; /* Search for the maximum cross-correlation and coding of the LTP lag */ L_max = 0; Nc = 40; /* index for the maximum cross-correlation */ for (lambda = 40; lambda <= 120; lambda += 9) { /* Calculate L_result for l = lambda .. lambda + 9. */ register float *lp = dp_float - lambda; register float W; register float a = lp[-8], b = lp[-7], c = lp[-6], d = lp[-5], e = lp[-4], f = lp[-3], g = lp[-2], h = lp[-1]; register float E; register float S0 = 0, S1 = 0, S2 = 0, S3 = 0, S4 = 0, S5 = 0, S6 = 0, S7 = 0, S8 = 0; # undef STEP # define STEP(K, a, b, c, d, e, f, g, h) \ if ((W = wt_float[K]) != 0.0) { \ E = W * a; S8 += E; \ E = W * b; S7 += E; \ E = W * c; S6 += E; \ E = W * d; S5 += E; \ E = W * e; S4 += E; \ E = W * f; S3 += E; \ E = W * g; S2 += E; \ E = W * h; S1 += E; \ a = lp[K]; \ E = W * a; S0 += E; } else (a = lp[K]) # define STEP_A(K) STEP(K, a, b, c, d, e, f, g, h) # define STEP_B(K) STEP(K, b, c, d, e, f, g, h, a) # define STEP_C(K) STEP(K, c, d, e, f, g, h, a, b) # define STEP_D(K) STEP(K, d, e, f, g, h, a, b, c) # define STEP_E(K) STEP(K, e, f, g, h, a, b, c, d) # define STEP_F(K) STEP(K, f, g, h, a, b, c, d, e) # define STEP_G(K) STEP(K, g, h, a, b, c, d, e, f) # define STEP_H(K) STEP(K, h, a, b, c, d, e, f, g) STEP_A( 0); STEP_B( 1); STEP_C( 2); STEP_D( 3); STEP_E( 4); STEP_F( 5); STEP_G( 6); STEP_H( 7); STEP_A( 8); STEP_B( 9); STEP_C(10); STEP_D(11); STEP_E(12); STEP_F(13); STEP_G(14); STEP_H(15); STEP_A(16); STEP_B(17); STEP_C(18); STEP_D(19); STEP_E(20); STEP_F(21); STEP_G(22); STEP_H(23); STEP_A(24); STEP_B(25); STEP_C(26); STEP_D(27); STEP_E(28); STEP_F(29); STEP_G(30); STEP_H(31); STEP_A(32); STEP_B(33); STEP_C(34); STEP_D(35); STEP_E(36); STEP_F(37); STEP_G(38); STEP_H(39); if (S0 > L_max) { L_max = S0; Nc = lambda; } if (S1 > L_max) { L_max = S1; Nc = lambda + 1; } if (S2 > L_max) { L_max = S2; Nc = lambda + 2; } if (S3 > L_max) { L_max = S3; Nc = lambda + 3; } if (S4 > L_max) { L_max = S4; Nc = lambda + 4; } if (S5 > L_max) { L_max = S5; Nc = lambda + 5; } if (S6 > L_max) { L_max = S6; Nc = lambda + 6; } if (S7 > L_max) { L_max = S7; Nc = lambda + 7; } if (S8 > L_max) { L_max = S8; Nc = lambda + 8; } } *Nc_out = Nc; L_max <<= 1; /* Rescaling of L_max */ assert(scal <= 100 && scal >= -100); L_max = L_max >> (6 - scal); /* sub(6, scal) */ assert( Nc <= 120 && Nc >= 40); /* Compute the power of the reconstructed short term residual * signal dp[..] */ L_power = 0; for (k = 0; k <= 39; k++) { register longword L_temp; L_temp = SASR( dp[k - Nc], 3 ); L_power += L_temp * L_temp; } L_power <<= 1; /* from L_MULT */ /* Normalization of L_max and L_power */ if (L_max <= 0) { *bc_out = 0; return; } if (L_max >= L_power) { *bc_out = 3; return; } temp = gsm_norm( L_power ); R = SASR( L_max << temp, 16 ); S = SASR( L_power << temp, 16 ); /* Coding of the LTP gain */ /* Table 4.3a must be used to obtain the level DLB[i] for the * quantization of the LTP gain b to get the coded version bc. */ for (bc = 0; bc <= 2; bc++) if (R <= gsm_mult(S, gsm_DLB[bc])) break; *bc_out = bc; } #endif /* LTP_CUT */ static void Calculation_of_the_LTP_parameters P4((d,dp,bc_out,Nc_out), register word * d, /* [0..39] IN */ register word * dp, /* [-120..-1] IN */ word * bc_out, /* OUT */ word * Nc_out /* OUT */ ) { register int k, lambda; word Nc, bc; float wt_float[40]; float dp_float_base[120], * dp_float = dp_float_base + 120; longword L_max, L_power; word R, S, dmax, scal; register word temp; /* Search of the optimum scaling of d[0..39]. */ dmax = 0; for (k = 0; k <= 39; k++) { temp = d[k]; temp = GSM_ABS( temp ); if (temp > dmax) dmax = temp; } temp = 0; if (dmax == 0) scal = 0; else { assert(dmax > 0); temp = gsm_norm( (longword)dmax << 16 ); } if (temp > 6) scal = 0; else scal = 6 - temp; assert(scal >= 0); /* Initialization of a working array wt */ for (k = 0; k < 40; k++) wt_float[k] = SASR( d[k], scal ); for (k = -120; k < 0; k++) dp_float[k] = dp[k]; /* Search for the maximum cross-correlation and coding of the LTP lag */ L_max = 0; Nc = 40; /* index for the maximum cross-correlation */ for (lambda = 40; lambda <= 120; lambda += 9) { /* Calculate L_result for l = lambda .. lambda + 9. */ register float *lp = dp_float - lambda; register float W; register float a = lp[-8], b = lp[-7], c = lp[-6], d = lp[-5], e = lp[-4], f = lp[-3], g = lp[-2], h = lp[-1]; register float E; register float S0 = 0, S1 = 0, S2 = 0, S3 = 0, S4 = 0, S5 = 0, S6 = 0, S7 = 0, S8 = 0; # undef STEP # define STEP(K, a, b, c, d, e, f, g, h) \ W = wt_float[K]; \ E = W * a; S8 += E; \ E = W * b; S7 += E; \ E = W * c; S6 += E; \ E = W * d; S5 += E; \ E = W * e; S4 += E; \ E = W * f; S3 += E; \ E = W * g; S2 += E; \ E = W * h; S1 += E; \ a = lp[K]; \ E = W * a; S0 += E # define STEP_A(K) STEP(K, a, b, c, d, e, f, g, h) # define STEP_B(K) STEP(K, b, c, d, e, f, g, h, a) # define STEP_C(K) STEP(K, c, d, e, f, g, h, a, b) # define STEP_D(K) STEP(K, d, e, f, g, h, a, b, c) # define STEP_E(K) STEP(K, e, f, g, h, a, b, c, d) # define STEP_F(K) STEP(K, f, g, h, a, b, c, d, e) # define STEP_G(K) STEP(K, g, h, a, b, c, d, e, f) # define STEP_H(K) STEP(K, h, a, b, c, d, e, f, g) STEP_A( 0); STEP_B( 1); STEP_C( 2); STEP_D( 3); STEP_E( 4); STEP_F( 5); STEP_G( 6); STEP_H( 7); STEP_A( 8); STEP_B( 9); STEP_C(10); STEP_D(11); STEP_E(12); STEP_F(13); STEP_G(14); STEP_H(15); STEP_A(16); STEP_B(17); STEP_C(18); STEP_D(19); STEP_E(20); STEP_F(21); STEP_G(22); STEP_H(23); STEP_A(24); STEP_B(25); STEP_C(26); STEP_D(27); STEP_E(28); STEP_F(29); STEP_G(30); STEP_H(31); STEP_A(32); STEP_B(33); STEP_C(34); STEP_D(35); STEP_E(36); STEP_F(37); STEP_G(38); STEP_H(39); if (S0 > L_max) { L_max = S0; Nc = lambda; } if (S1 > L_max) { L_max = S1; Nc = lambda + 1; } if (S2 > L_max) { L_max = S2; Nc = lambda + 2; } if (S3 > L_max) { L_max = S3; Nc = lambda + 3; } if (S4 > L_max) { L_max = S4; Nc = lambda + 4; } if (S5 > L_max) { L_max = S5; Nc = lambda + 5; } if (S6 > L_max) { L_max = S6; Nc = lambda + 6; } if (S7 > L_max) { L_max = S7; Nc = lambda + 7; } if (S8 > L_max) { L_max = S8; Nc = lambda + 8; } } *Nc_out = Nc; L_max <<= 1; /* Rescaling of L_max */ assert(scal <= 100 && scal >= -100); L_max = L_max >> (6 - scal); /* sub(6, scal) */ assert( Nc <= 120 && Nc >= 40); /* Compute the power of the reconstructed short term residual * signal dp[..] */ L_power = 0; for (k = 0; k <= 39; k++) { register longword L_temp; L_temp = SASR( dp[k - Nc], 3 ); L_power += L_temp * L_temp; } L_power <<= 1; /* from L_MULT */ /* Normalization of L_max and L_power */ if (L_max <= 0) { *bc_out = 0; return; } if (L_max >= L_power) { *bc_out = 3; return; } temp = gsm_norm( L_power ); R = SASR( L_max << temp, 16 ); S = SASR( L_power << temp, 16 ); /* Coding of the LTP gain */ /* Table 4.3a must be used to obtain the level DLB[i] for the * quantization of the LTP gain b to get the coded version bc. */ for (bc = 0; bc <= 2; bc++) if (R <= gsm_mult(S, gsm_DLB[bc])) break; *bc_out = bc; } #ifdef FAST #ifdef LTP_CUT static void Cut_Fast_Calculation_of_the_LTP_parameters P5((st, d,dp,bc_out,Nc_out), struct gsm_state * st, /* IN */ register word * d, /* [0..39] IN */ register word * dp, /* [-120..-1] IN */ word * bc_out, /* OUT */ word * Nc_out /* OUT */ ) { register int k, lambda; register float wt_float; word Nc, bc; word wt_max, best_k, ltp_cut; float dp_float_base[120], * dp_float = dp_float_base + 120; register float L_result, L_max, L_power; wt_max = 0; for (k = 0; k < 40; ++k) { if ( d[k] > wt_max) wt_max = d[best_k = k]; else if (-d[k] > wt_max) wt_max = -d[best_k = k]; } assert(wt_max >= 0); wt_float = (float)wt_max; for (k = -120; k < 0; ++k) dp_float[k] = (float)dp[k]; /* Search for the maximum cross-correlation and coding of the LTP lag */ L_max = 0; Nc = 40; /* index for the maximum cross-correlation */ for (lambda = 40; lambda <= 120; lambda++) { L_result = wt_float * dp_float[best_k - lambda]; if (L_result > L_max) { Nc = lambda; L_max = L_result; } } *Nc_out = Nc; if (L_max <= 0.) { *bc_out = 0; return; } /* Compute the power of the reconstructed short term residual * signal dp[..] */ dp_float -= Nc; L_power = 0; for (k = 0; k < 40; ++k) { register float f = dp_float[k]; L_power += f * f; } if (L_max >= L_power) { *bc_out = 3; return; } /* Coding of the LTP gain * Table 4.3a must be used to obtain the level DLB[i] for the * quantization of the LTP gain b to get the coded version bc. */ lambda = L_max / L_power * 32768.; for (bc = 0; bc <= 2; ++bc) if (lambda <= gsm_DLB[bc]) break; *bc_out = bc; } #endif /* LTP_CUT */ static void Fast_Calculation_of_the_LTP_parameters P4((d,dp,bc_out,Nc_out), register word * d, /* [0..39] IN */ register word * dp, /* [-120..-1] IN */ word * bc_out, /* OUT */ word * Nc_out /* OUT */ ) { register int k, lambda; word Nc, bc; float wt_float[40]; float dp_float_base[120], * dp_float = dp_float_base + 120; register float L_max, L_power; for (k = 0; k < 40; ++k) wt_float[k] = (float)d[k]; for (k = -120; k < 0; ++k) dp_float[k] = (float)dp[k]; /* Search for the maximum cross-correlation and coding of the LTP lag */ L_max = 0; Nc = 40; /* index for the maximum cross-correlation */ for (lambda = 40; lambda <= 120; lambda += 9) { /* Calculate L_result for l = lambda .. lambda + 9. */ register float *lp = dp_float - lambda; register float W; register float a = lp[-8], b = lp[-7], c = lp[-6], d = lp[-5], e = lp[-4], f = lp[-3], g = lp[-2], h = lp[-1]; register float E; register float S0 = 0, S1 = 0, S2 = 0, S3 = 0, S4 = 0, S5 = 0, S6 = 0, S7 = 0, S8 = 0; # undef STEP # define STEP(K, a, b, c, d, e, f, g, h) \ W = wt_float[K]; \ E = W * a; S8 += E; \ E = W * b; S7 += E; \ E = W * c; S6 += E; \ E = W * d; S5 += E; \ E = W * e; S4 += E; \ E = W * f; S3 += E; \ E = W * g; S2 += E; \ E = W * h; S1 += E; \ a = lp[K]; \ E = W * a; S0 += E # define STEP_A(K) STEP(K, a, b, c, d, e, f, g, h) # define STEP_B(K) STEP(K, b, c, d, e, f, g, h, a) # define STEP_C(K) STEP(K, c, d, e, f, g, h, a, b) # define STEP_D(K) STEP(K, d, e, f, g, h, a, b, c) # define STEP_E(K) STEP(K, e, f, g, h, a, b, c, d) # define STEP_F(K) STEP(K, f, g, h, a, b, c, d, e) # define STEP_G(K) STEP(K, g, h, a, b, c, d, e, f) # define STEP_H(K) STEP(K, h, a, b, c, d, e, f, g) STEP_A( 0); STEP_B( 1); STEP_C( 2); STEP_D( 3); STEP_E( 4); STEP_F( 5); STEP_G( 6); STEP_H( 7); STEP_A( 8); STEP_B( 9); STEP_C(10); STEP_D(11); STEP_E(12); STEP_F(13); STEP_G(14); STEP_H(15); STEP_A(16); STEP_B(17); STEP_C(18); STEP_D(19); STEP_E(20); STEP_F(21); STEP_G(22); STEP_H(23); STEP_A(24); STEP_B(25); STEP_C(26); STEP_D(27); STEP_E(28); STEP_F(29); STEP_G(30); STEP_H(31); STEP_A(32); STEP_B(33); STEP_C(34); STEP_D(35); STEP_E(36); STEP_F(37); STEP_G(38); STEP_H(39); if (S0 > L_max) { L_max = S0; Nc = lambda; } if (S1 > L_max) { L_max = S1; Nc = lambda + 1; } if (S2 > L_max) { L_max = S2; Nc = lambda + 2; } if (S3 > L_max) { L_max = S3; Nc = lambda + 3; } if (S4 > L_max) { L_max = S4; Nc = lambda + 4; } if (S5 > L_max) { L_max = S5; Nc = lambda + 5; } if (S6 > L_max) { L_max = S6; Nc = lambda + 6; } if (S7 > L_max) { L_max = S7; Nc = lambda + 7; } if (S8 > L_max) { L_max = S8; Nc = lambda + 8; } } *Nc_out = Nc; if (L_max <= 0.) { *bc_out = 0; return; } /* Compute the power of the reconstructed short term residual * signal dp[..] */ dp_float -= Nc; L_power = 0; for (k = 0; k < 40; ++k) { register float f = dp_float[k]; L_power += f * f; } if (L_max >= L_power) { *bc_out = 3; return; } /* Coding of the LTP gain * Table 4.3a must be used to obtain the level DLB[i] for the * quantization of the LTP gain b to get the coded version bc. */ lambda = L_max / L_power * 32768.; for (bc = 0; bc <= 2; ++bc) if (lambda <= gsm_DLB[bc]) break; *bc_out = bc; } #endif /* FAST */ #endif /* USE_FLOAT_MUL */ /* 4.2.12 */ static void Long_term_analysis_filtering P6((bc,Nc,dp,d,dpp,e), word bc, /* IN */ word Nc, /* IN */ register word * dp, /* previous d [-120..-1] IN */ register word * d, /* d [0..39] IN */ register word * dpp, /* estimate [0..39] OUT */ register word * e /* long term res. signal [0..39] OUT */ ) /* * In this part, we have to decode the bc parameter to compute * the samples of the estimate dpp[0..39]. The decoding of bc needs the * use of table 4.3b. The long term residual signal e[0..39] * is then calculated to be fed to the RPE encoding section. */ { register int k; register longword ltmp; # undef STEP # define STEP(BP) \ for (k = 0; k <= 39; k++) { \ dpp[k] = GSM_MULT_R( BP, dp[k - Nc]); \ e[k] = GSM_SUB( d[k], dpp[k] ); \ } switch (bc) { case 0: STEP( 3277 ); break; case 1: STEP( 11469 ); break; case 2: STEP( 21299 ); break; case 3: STEP( 32767 ); break; } } void Gsm_Long_Term_Predictor P7((S,d,dp,e,dpp,Nc,bc), /* 4x for 160 samples */ struct gsm_state * S, word * d, /* [0..39] residual signal IN */ word * dp, /* [-120..-1] d' IN */ word * e, /* [0..39] OUT */ word * dpp, /* [0..39] OUT */ word * Nc, /* correlation lag OUT */ word * bc /* gain factor OUT */ ) { assert( d ); assert( dp ); assert( e ); assert( dpp); assert( Nc ); assert( bc ); #if defined(FAST) && defined(USE_FLOAT_MUL) if (S->fast) #if defined (LTP_CUT) if (S->ltp_cut) Cut_Fast_Calculation_of_the_LTP_parameters(S, d, dp, bc, Nc); else #endif /* LTP_CUT */ Fast_Calculation_of_the_LTP_parameters(d, dp, bc, Nc ); else #endif /* FAST & USE_FLOAT_MUL */ #ifdef LTP_CUT if (S->ltp_cut) Cut_Calculation_of_the_LTP_parameters(S, d, dp, bc, Nc); else #endif Calculation_of_the_LTP_parameters(d, dp, bc, Nc); Long_term_analysis_filtering( *bc, *Nc, dp, d, dpp, e ); } /* 4.3.2 */ void Gsm_Long_Term_Synthesis_Filtering P5((S,Ncr,bcr,erp,drp), struct gsm_state * S, word Ncr, word bcr, register word * erp, /* [0..39] IN */ register word * drp /* [-120..-1] IN, [-120..40] OUT */ ) /* * This procedure uses the bcr and Ncr parameter to realize the * long term synthesis filtering. The decoding of bcr needs * table 4.3b. */ { register longword ltmp; /* for ADD */ register int k; word brp, drpp, Nr; /* Check the limits of Nr. */ Nr = Ncr < 40 || Ncr > 120 ? S->nrp : Ncr; S->nrp = Nr; assert(Nr >= 40 && Nr <= 120); /* Decoding of the LTP gain bcr */ brp = gsm_QLB[ bcr ]; /* Computation of the reconstructed short term residual * signal drp[0..39] */ assert(brp != MIN_WORD); for (k = 0; k <= 39; k++) { drpp = GSM_MULT_R( brp, drp[ k - Nr ] ); drp[k] = GSM_ADD( erp[k], drpp ); } /* * Update of the reconstructed short term residual signal * drp[ -1..-120 ] */ for (k = 0; k <= 119; k++) drp[ -120 + k ] = drp[ -80 + k ]; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_decode.c0000644000175000017500000002451311744612271021174 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "private.h" #include "gsm.h" #include "proto.h" int gsm_decode P3((s, c, target), gsm s, gsm_byte * c, gsm_signal * target) { word LARc[8], Nc[4], Mc[4], bc[4], xmaxc[4], xmc[13*4]; #ifdef WAV49 if (s->wav_fmt) { uword sr = 0; s->frame_index = !s->frame_index; if (s->frame_index) { sr = *c++; LARc[0] = sr & 0x3f; sr >>= 6; sr |= (uword)*c++ << 2; LARc[1] = sr & 0x3f; sr >>= 6; sr |= (uword)*c++ << 4; LARc[2] = sr & 0x1f; sr >>= 5; LARc[3] = sr & 0x1f; sr >>= 5; sr |= (uword)*c++ << 2; LARc[4] = sr & 0xf; sr >>= 4; LARc[5] = sr & 0xf; sr >>= 4; sr |= (uword)*c++ << 2; /* 5 */ LARc[6] = sr & 0x7; sr >>= 3; LARc[7] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[0] = sr & 0x7f; sr >>= 7; bc[0] = sr & 0x3; sr >>= 2; Mc[0] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[0] = sr & 0x3f; sr >>= 6; xmc[0] = sr & 0x7; sr >>= 3; sr = *c++; xmc[1] = sr & 0x7; sr >>= 3; xmc[2] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[3] = sr & 0x7; sr >>= 3; xmc[4] = sr & 0x7; sr >>= 3; xmc[5] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 10 */ xmc[6] = sr & 0x7; sr >>= 3; xmc[7] = sr & 0x7; sr >>= 3; xmc[8] = sr & 0x7; sr >>= 3; sr = *c++; xmc[9] = sr & 0x7; sr >>= 3; xmc[10] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[11] = sr & 0x7; sr >>= 3; xmc[12] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[1] = sr & 0x7f; sr >>= 7; bc[1] = sr & 0x3; sr >>= 2; Mc[1] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[1] = sr & 0x3f; sr >>= 6; xmc[13] = sr & 0x7; sr >>= 3; sr = *c++; /* 15 */ xmc[14] = sr & 0x7; sr >>= 3; xmc[15] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[16] = sr & 0x7; sr >>= 3; xmc[17] = sr & 0x7; sr >>= 3; xmc[18] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[19] = sr & 0x7; sr >>= 3; xmc[20] = sr & 0x7; sr >>= 3; xmc[21] = sr & 0x7; sr >>= 3; sr = *c++; xmc[22] = sr & 0x7; sr >>= 3; xmc[23] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[24] = sr & 0x7; sr >>= 3; xmc[25] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; /* 20 */ Nc[2] = sr & 0x7f; sr >>= 7; bc[2] = sr & 0x3; sr >>= 2; Mc[2] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[2] = sr & 0x3f; sr >>= 6; xmc[26] = sr & 0x7; sr >>= 3; sr = *c++; xmc[27] = sr & 0x7; sr >>= 3; xmc[28] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[29] = sr & 0x7; sr >>= 3; xmc[30] = sr & 0x7; sr >>= 3; xmc[31] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[32] = sr & 0x7; sr >>= 3; xmc[33] = sr & 0x7; sr >>= 3; xmc[34] = sr & 0x7; sr >>= 3; sr = *c++; /* 25 */ xmc[35] = sr & 0x7; sr >>= 3; xmc[36] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[37] = sr & 0x7; sr >>= 3; xmc[38] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[3] = sr & 0x7f; sr >>= 7; bc[3] = sr & 0x3; sr >>= 2; Mc[3] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[3] = sr & 0x3f; sr >>= 6; xmc[39] = sr & 0x7; sr >>= 3; sr = *c++; xmc[40] = sr & 0x7; sr >>= 3; xmc[41] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; /* 30 */ xmc[42] = sr & 0x7; sr >>= 3; xmc[43] = sr & 0x7; sr >>= 3; xmc[44] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[45] = sr & 0x7; sr >>= 3; xmc[46] = sr & 0x7; sr >>= 3; xmc[47] = sr & 0x7; sr >>= 3; sr = *c++; xmc[48] = sr & 0x7; sr >>= 3; xmc[49] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[50] = sr & 0x7; sr >>= 3; xmc[51] = sr & 0x7; sr >>= 3; s->frame_chain = sr & 0xf; } else { sr = s->frame_chain; sr |= (uword)*c++ << 4; /* 1 */ LARc[0] = sr & 0x3f; sr >>= 6; LARc[1] = sr & 0x3f; sr >>= 6; sr = *c++; LARc[2] = sr & 0x1f; sr >>= 5; sr |= (uword)*c++ << 3; LARc[3] = sr & 0x1f; sr >>= 5; LARc[4] = sr & 0xf; sr >>= 4; sr |= (uword)*c++ << 2; LARc[5] = sr & 0xf; sr >>= 4; LARc[6] = sr & 0x7; sr >>= 3; LARc[7] = sr & 0x7; sr >>= 3; sr = *c++; /* 5 */ Nc[0] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[0] = sr & 0x3; sr >>= 2; Mc[0] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[0] = sr & 0x3f; sr >>= 6; xmc[0] = sr & 0x7; sr >>= 3; xmc[1] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[2] = sr & 0x7; sr >>= 3; xmc[3] = sr & 0x7; sr >>= 3; xmc[4] = sr & 0x7; sr >>= 3; sr = *c++; xmc[5] = sr & 0x7; sr >>= 3; xmc[6] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; /* 10 */ xmc[7] = sr & 0x7; sr >>= 3; xmc[8] = sr & 0x7; sr >>= 3; xmc[9] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[10] = sr & 0x7; sr >>= 3; xmc[11] = sr & 0x7; sr >>= 3; xmc[12] = sr & 0x7; sr >>= 3; sr = *c++; Nc[1] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[1] = sr & 0x3; sr >>= 2; Mc[1] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[1] = sr & 0x3f; sr >>= 6; xmc[13] = sr & 0x7; sr >>= 3; xmc[14] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 15 */ xmc[15] = sr & 0x7; sr >>= 3; xmc[16] = sr & 0x7; sr >>= 3; xmc[17] = sr & 0x7; sr >>= 3; sr = *c++; xmc[18] = sr & 0x7; sr >>= 3; xmc[19] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[20] = sr & 0x7; sr >>= 3; xmc[21] = sr & 0x7; sr >>= 3; xmc[22] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[23] = sr & 0x7; sr >>= 3; xmc[24] = sr & 0x7; sr >>= 3; xmc[25] = sr & 0x7; sr >>= 3; sr = *c++; Nc[2] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; /* 20 */ bc[2] = sr & 0x3; sr >>= 2; Mc[2] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[2] = sr & 0x3f; sr >>= 6; xmc[26] = sr & 0x7; sr >>= 3; xmc[27] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[28] = sr & 0x7; sr >>= 3; xmc[29] = sr & 0x7; sr >>= 3; xmc[30] = sr & 0x7; sr >>= 3; sr = *c++; xmc[31] = sr & 0x7; sr >>= 3; xmc[32] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[33] = sr & 0x7; sr >>= 3; xmc[34] = sr & 0x7; sr >>= 3; xmc[35] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 25 */ xmc[36] = sr & 0x7; sr >>= 3; xmc[37] = sr & 0x7; sr >>= 3; xmc[38] = sr & 0x7; sr >>= 3; sr = *c++; Nc[3] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[3] = sr & 0x3; sr >>= 2; Mc[3] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[3] = sr & 0x3f; sr >>= 6; xmc[39] = sr & 0x7; sr >>= 3; xmc[40] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[41] = sr & 0x7; sr >>= 3; xmc[42] = sr & 0x7; sr >>= 3; xmc[43] = sr & 0x7; sr >>= 3; sr = *c++; /* 30 */ xmc[44] = sr & 0x7; sr >>= 3; xmc[45] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[46] = sr & 0x7; sr >>= 3; xmc[47] = sr & 0x7; sr >>= 3; xmc[48] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[49] = sr & 0x7; sr >>= 3; xmc[50] = sr & 0x7; sr >>= 3; xmc[51] = sr & 0x7; sr >>= 3; } } else #endif { /* GSM_MAGIC = (*c >> 4) & 0xF; */ if (((*c >> 4) & 0x0F) != GSM_MAGIC) return -1; LARc[0] = (*c++ & 0xF) << 2; /* 1 */ LARc[0] |= (*c >> 6) & 0x3; LARc[1] = *c++ & 0x3F; LARc[2] = (*c >> 3) & 0x1F; LARc[3] = (*c++ & 0x7) << 2; LARc[3] |= (*c >> 6) & 0x3; LARc[4] = (*c >> 2) & 0xF; LARc[5] = (*c++ & 0x3) << 2; LARc[5] |= (*c >> 6) & 0x3; LARc[6] = (*c >> 3) & 0x7; LARc[7] = *c++ & 0x7; Nc[0] = (*c >> 1) & 0x7F; bc[0] = (*c++ & 0x1) << 1; bc[0] |= (*c >> 7) & 0x1; Mc[0] = (*c >> 5) & 0x3; xmaxc[0] = (*c++ & 0x1F) << 1; xmaxc[0] |= (*c >> 7) & 0x1; xmc[0] = (*c >> 4) & 0x7; xmc[1] = (*c >> 1) & 0x7; xmc[2] = (*c++ & 0x1) << 2; xmc[2] |= (*c >> 6) & 0x3; xmc[3] = (*c >> 3) & 0x7; xmc[4] = *c++ & 0x7; xmc[5] = (*c >> 5) & 0x7; xmc[6] = (*c >> 2) & 0x7; xmc[7] = (*c++ & 0x3) << 1; /* 10 */ xmc[7] |= (*c >> 7) & 0x1; xmc[8] = (*c >> 4) & 0x7; xmc[9] = (*c >> 1) & 0x7; xmc[10] = (*c++ & 0x1) << 2; xmc[10] |= (*c >> 6) & 0x3; xmc[11] = (*c >> 3) & 0x7; xmc[12] = *c++ & 0x7; Nc[1] = (*c >> 1) & 0x7F; bc[1] = (*c++ & 0x1) << 1; bc[1] |= (*c >> 7) & 0x1; Mc[1] = (*c >> 5) & 0x3; xmaxc[1] = (*c++ & 0x1F) << 1; xmaxc[1] |= (*c >> 7) & 0x1; xmc[13] = (*c >> 4) & 0x7; xmc[14] = (*c >> 1) & 0x7; xmc[15] = (*c++ & 0x1) << 2; xmc[15] |= (*c >> 6) & 0x3; xmc[16] = (*c >> 3) & 0x7; xmc[17] = *c++ & 0x7; xmc[18] = (*c >> 5) & 0x7; xmc[19] = (*c >> 2) & 0x7; xmc[20] = (*c++ & 0x3) << 1; xmc[20] |= (*c >> 7) & 0x1; xmc[21] = (*c >> 4) & 0x7; xmc[22] = (*c >> 1) & 0x7; xmc[23] = (*c++ & 0x1) << 2; xmc[23] |= (*c >> 6) & 0x3; xmc[24] = (*c >> 3) & 0x7; xmc[25] = *c++ & 0x7; Nc[2] = (*c >> 1) & 0x7F; bc[2] = (*c++ & 0x1) << 1; /* 20 */ bc[2] |= (*c >> 7) & 0x1; Mc[2] = (*c >> 5) & 0x3; xmaxc[2] = (*c++ & 0x1F) << 1; xmaxc[2] |= (*c >> 7) & 0x1; xmc[26] = (*c >> 4) & 0x7; xmc[27] = (*c >> 1) & 0x7; xmc[28] = (*c++ & 0x1) << 2; xmc[28] |= (*c >> 6) & 0x3; xmc[29] = (*c >> 3) & 0x7; xmc[30] = *c++ & 0x7; xmc[31] = (*c >> 5) & 0x7; xmc[32] = (*c >> 2) & 0x7; xmc[33] = (*c++ & 0x3) << 1; xmc[33] |= (*c >> 7) & 0x1; xmc[34] = (*c >> 4) & 0x7; xmc[35] = (*c >> 1) & 0x7; xmc[36] = (*c++ & 0x1) << 2; xmc[36] |= (*c >> 6) & 0x3; xmc[37] = (*c >> 3) & 0x7; xmc[38] = *c++ & 0x7; Nc[3] = (*c >> 1) & 0x7F; bc[3] = (*c++ & 0x1) << 1; bc[3] |= (*c >> 7) & 0x1; Mc[3] = (*c >> 5) & 0x3; xmaxc[3] = (*c++ & 0x1F) << 1; xmaxc[3] |= (*c >> 7) & 0x1; xmc[39] = (*c >> 4) & 0x7; xmc[40] = (*c >> 1) & 0x7; xmc[41] = (*c++ & 0x1) << 2; xmc[41] |= (*c >> 6) & 0x3; xmc[42] = (*c >> 3) & 0x7; xmc[43] = *c++ & 0x7; /* 30 */ xmc[44] = (*c >> 5) & 0x7; xmc[45] = (*c >> 2) & 0x7; xmc[46] = (*c++ & 0x3) << 1; xmc[46] |= (*c >> 7) & 0x1; xmc[47] = (*c >> 4) & 0x7; xmc[48] = (*c >> 1) & 0x7; xmc[49] = (*c++ & 0x1) << 2; xmc[49] |= (*c >> 6) & 0x3; xmc[50] = (*c >> 3) & 0x7; xmc[51] = *c & 0x7; /* 33 */ } Gsm_Decoder(s, LARc, Nc, bc, Mc, xmaxc, xmc, target); return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/decode.c0000644000175000017500000000271211700377701020321 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include "private.h" #include "gsm.h" #include "proto.h" /* * 4.3 FIXED POINT IMPLEMENTATION OF THE RPE-LTP DECODER */ static void Postprocessing P2((S,s), struct gsm_state * S, register word * s) { register int k; register word msr = S->msr; register longword ltmp; /* for GSM_ADD */ register word tmp; for (k = 160; k--; s++) { tmp = GSM_MULT_R( msr, 28180 ); msr = GSM_ADD(*s, tmp); /* Deemphasis */ *s = GSM_ADD(msr, msr) & 0xFFF8; /* Truncation & Upscaling */ } S->msr = msr; } void Gsm_Decoder P8((S,LARcr, Ncr,bcr,Mcr,xmaxcr,xMcr,s), struct gsm_state * S, word * LARcr, /* [0..7] IN */ word * Ncr, /* [0..3] IN */ word * bcr, /* [0..3] IN */ word * Mcr, /* [0..3] IN */ word * xmaxcr, /* [0..3] IN */ word * xMcr, /* [0..13*4] IN */ word * s) /* [0..159] OUT */ { int j, k; word erp[40], wt[160]; word * drp = S->dp0 + 120; for (j=0; j <= 3; j++, xmaxcr++, bcr++, Ncr++, Mcr++, xMcr += 13) { Gsm_RPE_Decoding( S, *xmaxcr, *Mcr, xMcr, erp ); Gsm_Long_Term_Synthesis_Filtering( S, *Ncr, *bcr, erp, drp ); for (k = 0; k <= 39; k++) wt[ j * 40 + k ] = drp[ k ]; } Gsm_Short_Term_Synthesis_Filter( S, LARcr, wt, s ); Postprocessing(S, s); } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/COPYRIGHT0000644000175000017500000000126211700377701020224 0ustar jcorganjcorganCopyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann, Technische Universitaet Berlin Any use of this software is permitted provided that this notice is not removed and that neither the authors nor the Technische Universitaet Berlin are deemed to have made any representations as to the suitability of this software for any purpose nor are held responsible for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. As a matter of courtesy, the authors request to be informed about uses this software has found, about bugs in this software, and about any improvements that may be of general interest. Berlin, 28.11.1994 Jutta Degener Carsten Bormann gnuradio-3.7.2.1/gr-vocoder/lib/gsm/lpc.c0000644000175000017500000001552611744612271017665 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include #include "private.h" #include "gsm.h" #include "proto.h" #undef P /* * 4.2.4 .. 4.2.7 LPC ANALYSIS SECTION */ /* 4.2.4 */ static void Autocorrelation P2((s, L_ACF), word * s, /* [0..159] IN/OUT */ longword * L_ACF) /* [0..8] OUT */ /* * The goal is to compute the array L_ACF[k]. The signal s[i] must * be scaled in order to avoid an overflow situation. */ { register int k, i; word temp, smax, scalauto; #ifdef USE_FLOAT_MUL float float_s[160]; #endif /* Dynamic scaling of the array s[0..159] */ /* Search for the maximum. */ smax = 0; for (k = 0; k <= 159; k++) { temp = GSM_ABS( s[k] ); if (temp > smax) smax = temp; } /* Computation of the scaling factor. */ if (smax == 0) scalauto = 0; else { assert(smax > 0); scalauto = 4 - gsm_norm( (longword)smax << 16 );/* sub(4,..) */ } /* Scaling of the array s[0...159] */ if (scalauto > 0) { # ifdef USE_FLOAT_MUL # define SCALE(n) \ case n: for (k = 0; k <= 159; k++) \ float_s[k] = (float) \ (s[k] = GSM_MULT_R(s[k], 16384 >> (n-1)));\ break; # else # define SCALE(n) \ case n: for (k = 0; k <= 159; k++) \ s[k] = GSM_MULT_R( s[k], 16384 >> (n-1) );\ break; # endif /* USE_FLOAT_MUL */ switch (scalauto) { SCALE(1) SCALE(2) SCALE(3) SCALE(4) } # undef SCALE } # ifdef USE_FLOAT_MUL else for (k = 0; k <= 159; k++) float_s[k] = (float) s[k]; # endif /* Compute the L_ACF[..]. */ { # ifdef USE_FLOAT_MUL register float * sp = float_s; register float sl = *sp; # define STEP(k) L_ACF[k] += (longword)(sl * sp[ -(k) ]); # else word * sp = s; word sl = *sp; # define STEP(k) L_ACF[k] += ((longword)sl * sp[ -(k) ]); # endif # define NEXTI sl = *++sp for (k = 9; k--; L_ACF[k] = 0) ; STEP (0); NEXTI; STEP(0); STEP(1); NEXTI; STEP(0); STEP(1); STEP(2); NEXTI; STEP(0); STEP(1); STEP(2); STEP(3); NEXTI; STEP(0); STEP(1); STEP(2); STEP(3); STEP(4); NEXTI; STEP(0); STEP(1); STEP(2); STEP(3); STEP(4); STEP(5); NEXTI; STEP(0); STEP(1); STEP(2); STEP(3); STEP(4); STEP(5); STEP(6); NEXTI; STEP(0); STEP(1); STEP(2); STEP(3); STEP(4); STEP(5); STEP(6); STEP(7); for (i = 8; i <= 159; i++) { NEXTI; STEP(0); STEP(1); STEP(2); STEP(3); STEP(4); STEP(5); STEP(6); STEP(7); STEP(8); } for (k = 9; k--; L_ACF[k] <<= 1) ; } /* Rescaling of the array s[0..159] */ if (scalauto > 0) { assert(scalauto <= 4); for (k = 160; k--; *s++ <<= scalauto) ; } } #if defined(USE_FLOAT_MUL) && defined(FAST) static void Fast_Autocorrelation P2((s, L_ACF), word * s, /* [0..159] IN/OUT */ longword * L_ACF) /* [0..8] OUT */ { register int k, i; float f_L_ACF[9]; float scale; float s_f[160]; register float *sf = s_f; for (i = 0; i < 160; ++i) sf[i] = s[i]; for (k = 0; k <= 8; k++) { register float L_temp2 = 0; register float *sfl = sf - k; for (i = k; i < 160; ++i) L_temp2 += sf[i] * sfl[i]; f_L_ACF[k] = L_temp2; } scale = MAX_LONGWORD / f_L_ACF[0]; for (k = 0; k <= 8; k++) { L_ACF[k] = f_L_ACF[k] * scale; } } #endif /* defined (USE_FLOAT_MUL) && defined (FAST) */ /* 4.2.5 */ static void Reflection_coefficients P2( (L_ACF, r), longword * L_ACF, /* 0...8 IN */ register word * r /* 0...7 OUT */ ) { register int i, m, n; register word temp; register longword ltmp; word ACF[9]; /* 0..8 */ word P[ 9]; /* 0..8 */ word K[ 9]; /* 2..8 */ /* Schur recursion with 16 bits arithmetic. */ if (L_ACF[0] == 0) { for (i = 8; i--; *r++ = 0) ; return; } assert( L_ACF[0] != 0 ); temp = gsm_norm( L_ACF[0] ); assert(temp >= 0 && temp < 32); /* ? overflow ? */ for (i = 0; i <= 8; i++) ACF[i] = SASR( L_ACF[i] << temp, 16 ); /* Initialize array P[..] and K[..] for the recursion. */ for (i = 1; i <= 7; i++) K[ i ] = ACF[ i ]; for (i = 0; i <= 8; i++) P[ i ] = ACF[ i ]; /* Compute reflection coefficients */ for (n = 1; n <= 8; n++, r++) { temp = P[1]; temp = GSM_ABS(temp); if (P[0] < temp) { for (i = n; i <= 8; i++) *r++ = 0; return; } *r = gsm_div( temp, P[0] ); assert(*r >= 0); if (P[1] > 0) *r = -*r; /* r[n] = sub(0, r[n]) */ assert (*r != MIN_WORD); if (n == 8) return; /* Schur recursion */ temp = GSM_MULT_R( P[1], *r ); P[0] = GSM_ADD( P[0], temp ); for (m = 1; m <= 8 - n; m++) { temp = GSM_MULT_R( K[ m ], *r ); P[m] = GSM_ADD( P[ m+1 ], temp ); temp = GSM_MULT_R( P[ m+1 ], *r ); K[m] = GSM_ADD( K[ m ], temp ); } } } /* 4.2.6 */ static void Transformation_to_Log_Area_Ratios P1((r), register word * r /* 0..7 IN/OUT */ ) /* * The following scaling for r[..] and LAR[..] has been used: * * r[..] = integer( real_r[..]*32768. ); -1 <= real_r < 1. * LAR[..] = integer( real_LAR[..] * 16384 ); * with -1.625 <= real_LAR <= 1.625 */ { register word temp; register int i; /* Computation of the LAR[0..7] from the r[0..7] */ for (i = 1; i <= 8; i++, r++) { temp = *r; temp = GSM_ABS(temp); assert(temp >= 0); if (temp < 22118) { temp >>= 1; } else if (temp < 31130) { assert( temp >= 11059 ); temp -= 11059; } else { assert( temp >= 26112 ); temp -= 26112; temp <<= 2; } *r = *r < 0 ? -temp : temp; assert( *r != MIN_WORD ); } } /* 4.2.7 */ static void Quantization_and_coding P1((LAR), register word * LAR /* [0..7] IN/OUT */ ) { register word temp; longword ltmp; /* This procedure needs four tables; the following equations * give the optimum scaling for the constants: * * A[0..7] = integer( real_A[0..7] * 1024 ) * B[0..7] = integer( real_B[0..7] * 512 ) * MAC[0..7] = maximum of the LARc[0..7] * MIC[0..7] = minimum of the LARc[0..7] */ # undef STEP # define STEP( A, B, MAC, MIC ) \ temp = GSM_MULT( A, *LAR ); \ temp = GSM_ADD( temp, B ); \ temp = GSM_ADD( temp, 256 ); \ temp = SASR( temp, 9 ); \ *LAR = temp>MAC ? MAC - MIC : (tempfast) Fast_Autocorrelation (s, L_ACF ); else #endif Autocorrelation (s, L_ACF ); Reflection_coefficients (L_ACF, LARc ); Transformation_to_Log_Area_Ratios (LARc); Quantization_and_coding (LARc); } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/README0000644000175000017500000000021611700377701017607 0ustar jcorganjcorganThis code was extracted from gsm-1.0-pl10.tar.gz See COPYRIGHT for the copyright. See http://kbs.cs.tu-berlin.de/~jutta/toast.html for docs. gnuradio-3.7.2.1/gr-vocoder/lib/gsm/short_term.c0000644000175000017500000002410511744612271021266 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include #include "private.h" #include "gsm.h" #include "proto.h" /* * SHORT TERM ANALYSIS FILTERING SECTION */ /* 4.2.8 */ static void Decoding_of_the_coded_Log_Area_Ratios P2((LARc,LARpp), word * LARc, /* coded log area ratio [0..7] IN */ word * LARpp) /* out: decoded .. */ { register word temp1 /* , temp2 */; register long ltmp; /* for GSM_ADD */ /* This procedure requires for efficient implementation * two tables. * * INVA[1..8] = integer( (32768 * 8) / real_A[1..8]) * MIC[1..8] = minimum value of the LARc[1..8] */ /* Compute the LARpp[1..8] */ /* for (i = 1; i <= 8; i++, B++, MIC++, INVA++, LARc++, LARpp++) { * * temp1 = GSM_ADD( *LARc, *MIC ) << 10; * temp2 = *B << 1; * temp1 = GSM_SUB( temp1, temp2 ); * * assert(*INVA != MIN_WORD); * * temp1 = GSM_MULT_R( *INVA, temp1 ); * *LARpp = GSM_ADD( temp1, temp1 ); * } */ #undef STEP #define STEP( B, MIC, INVA ) \ temp1 = GSM_ADD( *LARc++, MIC ) << 10; \ temp1 = GSM_SUB( temp1, B << 1 ); \ temp1 = GSM_MULT_R( INVA, temp1 ); \ *LARpp++ = GSM_ADD( temp1, temp1 ); STEP( 0, -32, 13107 ); STEP( 0, -32, 13107 ); STEP( 2048, -16, 13107 ); STEP( -2560, -16, 13107 ); STEP( 94, -8, 19223 ); STEP( -1792, -8, 17476 ); STEP( -341, -4, 31454 ); STEP( -1144, -4, 29708 ); /* NOTE: the addition of *MIC is used to restore * the sign of *LARc. */ } /* 4.2.9 */ /* Computation of the quantized reflection coefficients */ /* 4.2.9.1 Interpolation of the LARpp[1..8] to get the LARp[1..8] */ /* * Within each frame of 160 analyzed speech samples the short term * analysis and synthesis filters operate with four different sets of * coefficients, derived from the previous set of decoded LARs(LARpp(j-1)) * and the actual set of decoded LARs (LARpp(j)) * * (Initial value: LARpp(j-1)[1..8] = 0.) */ static void Coefficients_0_12 P3((LARpp_j_1, LARpp_j, LARp), register word * LARpp_j_1, register word * LARpp_j, register word * LARp) { register int i; register longword ltmp; for (i = 1; i <= 8; i++, LARp++, LARpp_j_1++, LARpp_j++) { *LARp = GSM_ADD( SASR( *LARpp_j_1, 2 ), SASR( *LARpp_j, 2 )); *LARp = GSM_ADD( *LARp, SASR( *LARpp_j_1, 1)); } } static void Coefficients_13_26 P3((LARpp_j_1, LARpp_j, LARp), register word * LARpp_j_1, register word * LARpp_j, register word * LARp) { register int i; register longword ltmp; for (i = 1; i <= 8; i++, LARpp_j_1++, LARpp_j++, LARp++) { *LARp = GSM_ADD( SASR( *LARpp_j_1, 1), SASR( *LARpp_j, 1 )); } } static void Coefficients_27_39 P3((LARpp_j_1, LARpp_j, LARp), register word * LARpp_j_1, register word * LARpp_j, register word * LARp) { register int i; register longword ltmp; for (i = 1; i <= 8; i++, LARpp_j_1++, LARpp_j++, LARp++) { *LARp = GSM_ADD( SASR( *LARpp_j_1, 2 ), SASR( *LARpp_j, 2 )); *LARp = GSM_ADD( *LARp, SASR( *LARpp_j, 1 )); } } static void Coefficients_40_159 P2((LARpp_j, LARp), register word * LARpp_j, register word * LARp) { register int i; for (i = 1; i <= 8; i++, LARp++, LARpp_j++) *LARp = *LARpp_j; } /* 4.2.9.2 */ static void LARp_to_rp P1((LARp), register word * LARp) /* [0..7] IN/OUT */ /* * The input of this procedure is the interpolated LARp[0..7] array. * The reflection coefficients, rp[i], are used in the analysis * filter and in the synthesis filter. */ { register int i; register word temp; register longword ltmp; for (i = 1; i <= 8; i++, LARp++) { /* temp = GSM_ABS( *LARp ); * * if (temp < 11059) temp <<= 1; * else if (temp < 20070) temp += 11059; * else temp = GSM_ADD( temp >> 2, 26112 ); * * *LARp = *LARp < 0 ? -temp : temp; */ if (*LARp < 0) { temp = *LARp == MIN_WORD ? MAX_WORD : -(*LARp); *LARp = - ((temp < 11059) ? temp << 1 : ((temp < 20070) ? temp + 11059 : GSM_ADD( temp >> 2, 26112 ))); } else { temp = *LARp; *LARp = (temp < 11059) ? temp << 1 : ((temp < 20070) ? temp + 11059 : GSM_ADD( temp >> 2, 26112 )); } } } /* 4.2.10 */ static void Short_term_analysis_filtering P4((S,rp,k_n,s), struct gsm_state * S, register word * rp, /* [0..7] IN */ register int k_n, /* k_end - k_start */ register word * s /* [0..n-1] IN/OUT */ ) /* * This procedure computes the short term residual signal d[..] to be fed * to the RPE-LTP loop from the s[..] signal and from the local rp[..] * array (quantized reflection coefficients). As the call of this * procedure can be done in many ways (see the interpolation of the LAR * coefficient), it is assumed that the computation begins with index * k_start (for arrays d[..] and s[..]) and stops with index k_end * (k_start and k_end are defined in 4.2.9.1). This procedure also * needs to keep the array u[0..7] in memory for each call. */ { register word * u = S->u; register int i; register word di, zzz, ui, sav, rpi; register longword ltmp; for (; k_n--; s++) { di = sav = *s; for (i = 0; i < 8; i++) { /* YYY */ ui = u[i]; rpi = rp[i]; u[i] = sav; zzz = GSM_MULT_R(rpi, di); sav = GSM_ADD( ui, zzz); zzz = GSM_MULT_R(rpi, ui); di = GSM_ADD( di, zzz ); } *s = di; } } #if defined(USE_FLOAT_MUL) && defined(FAST) static void Fast_Short_term_analysis_filtering P4((S,rp,k_n,s), struct gsm_state * S, register word * rp, /* [0..7] IN */ register int k_n, /* k_end - k_start */ register word * s /* [0..n-1] IN/OUT */ ) { register word * u = S->u; register int i; float uf[8], rpf[8]; register float scalef = 3.0517578125e-5; register float sav, di, temp; for (i = 0; i < 8; ++i) { uf[i] = u[i]; rpf[i] = rp[i] * scalef; } for (; k_n--; s++) { sav = di = *s; for (i = 0; i < 8; ++i) { register float rpfi = rpf[i]; register float ufi = uf[i]; uf[i] = sav; temp = rpfi * di + ufi; di += rpfi * ufi; sav = temp; } *s = di; } for (i = 0; i < 8; ++i) u[i] = uf[i]; } #endif /* ! (defined (USE_FLOAT_MUL) && defined (FAST)) */ static void Short_term_synthesis_filtering P5((S,rrp,k,wt,sr), struct gsm_state * S, register word * rrp, /* [0..7] IN */ register int k, /* k_end - k_start */ register word * wt, /* [0..k-1] IN */ register word * sr /* [0..k-1] OUT */ ) { register word * v = S->v; register int i; register word sri, tmp1, tmp2; register longword ltmp; /* for GSM_ADD & GSM_SUB */ while (k--) { sri = *wt++; for (i = 8; i--;) { /* sri = GSM_SUB( sri, gsm_mult_r( rrp[i], v[i] ) ); */ tmp1 = rrp[i]; tmp2 = v[i]; tmp2 = ( tmp1 == MIN_WORD && tmp2 == MIN_WORD ? MAX_WORD : 0x0FFFF & (( (longword)tmp1 * (longword)tmp2 + 16384) >> 15)) ; sri = GSM_SUB( sri, tmp2 ); /* v[i+1] = GSM_ADD( v[i], gsm_mult_r( rrp[i], sri ) ); */ tmp1 = ( tmp1 == MIN_WORD && sri == MIN_WORD ? MAX_WORD : 0x0FFFF & (( (longword)tmp1 * (longword)sri + 16384) >> 15)) ; v[i+1] = GSM_ADD( v[i], tmp1); } *sr++ = v[0] = sri; } } #if defined(FAST) && defined(USE_FLOAT_MUL) static void Fast_Short_term_synthesis_filtering P5((S,rrp,k,wt,sr), struct gsm_state * S, register word * rrp, /* [0..7] IN */ register int k, /* k_end - k_start */ register word * wt, /* [0..k-1] IN */ register word * sr /* [0..k-1] OUT */ ) { register word * v = S->v; register int i; float va[9], rrpa[8]; register float scalef = 3.0517578125e-5, temp; for (i = 0; i < 8; ++i) { va[i] = v[i]; rrpa[i] = (float)rrp[i] * scalef; } while (k--) { register float sri = *wt++; for (i = 8; i--;) { sri -= rrpa[i] * va[i]; if (sri < -32768.) sri = -32768.; else if (sri > 32767.) sri = 32767.; temp = va[i] + rrpa[i] * sri; if (temp < -32768.) temp = -32768.; else if (temp > 32767.) temp = 32767.; va[i+1] = temp; } *sr++ = va[0] = sri; } for (i = 0; i < 9; ++i) v[i] = va[i]; } #endif /* defined(FAST) && defined(USE_FLOAT_MUL) */ void Gsm_Short_Term_Analysis_Filter P3((S,LARc,s), struct gsm_state * S, word * LARc, /* coded log area ratio [0..7] IN */ word * s /* signal [0..159] IN/OUT */ ) { word * LARpp_j = S->LARpp[ S->j ]; word * LARpp_j_1 = S->LARpp[ S->j ^= 1 ]; word LARp[8]; #undef FILTER #if defined(FAST) && defined(USE_FLOAT_MUL) # define FILTER (* (S->fast \ ? Fast_Short_term_analysis_filtering \ : Short_term_analysis_filtering )) #else # define FILTER Short_term_analysis_filtering #endif Decoding_of_the_coded_Log_Area_Ratios( LARc, LARpp_j ); Coefficients_0_12( LARpp_j_1, LARpp_j, LARp ); LARp_to_rp( LARp ); FILTER( S, LARp, 13, s); Coefficients_13_26( LARpp_j_1, LARpp_j, LARp); LARp_to_rp( LARp ); FILTER( S, LARp, 14, s + 13); Coefficients_27_39( LARpp_j_1, LARpp_j, LARp); LARp_to_rp( LARp ); FILTER( S, LARp, 13, s + 27); Coefficients_40_159( LARpp_j, LARp); LARp_to_rp( LARp ); FILTER( S, LARp, 120, s + 40); } void Gsm_Short_Term_Synthesis_Filter P4((S, LARcr, wt, s), struct gsm_state * S, word * LARcr, /* received log area ratios [0..7] IN */ word * wt, /* received d [0..159] IN */ word * s /* signal s [0..159] OUT */ ) { word * LARpp_j = S->LARpp[ S->j ]; word * LARpp_j_1 = S->LARpp[ S->j ^=1 ]; word LARp[8]; #undef FILTER #if defined(FAST) && defined(USE_FLOAT_MUL) # define FILTER (* (S->fast \ ? Fast_Short_term_synthesis_filtering \ : Short_term_synthesis_filtering )) #else # define FILTER Short_term_synthesis_filtering #endif Decoding_of_the_coded_Log_Area_Ratios( LARcr, LARpp_j ); Coefficients_0_12( LARpp_j_1, LARpp_j, LARp ); LARp_to_rp( LARp ); FILTER( S, LARp, 13, wt, s ); Coefficients_13_26( LARpp_j_1, LARpp_j, LARp); LARp_to_rp( LARp ); FILTER( S, LARp, 14, wt + 13, s + 13 ); Coefficients_27_39( LARpp_j_1, LARpp_j, LARp); LARp_to_rp( LARp ); FILTER( S, LARp, 13, wt + 27, s + 27 ); Coefficients_40_159( LARpp_j, LARp ); LARp_to_rp( LARp ); FILTER(S, LARp, 120, wt + 40, s + 40); } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/add.c0000644000175000017500000001253211744612271017631 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ /* * See private.h for the more commonly used macro versions. */ #include #include #include "private.h" #include "gsm.h" #include "proto.h" #define saturate(x) \ ((x) < MIN_WORD ? MIN_WORD : (x) > MAX_WORD ? MAX_WORD: (x)) word gsm_add P2((a,b), word a, word b) { longword sum = (longword)a + (longword)b; return saturate(sum); } word gsm_sub P2((a,b), word a, word b) { longword diff = (longword)a - (longword)b; return saturate(diff); } word gsm_mult P2((a,b), word a, word b) { if (a == MIN_WORD && b == MIN_WORD) return MAX_WORD; else return SASR( (longword)a * (longword)b, 15 ); } word gsm_mult_r P2((a,b), word a, word b) { if (b == MIN_WORD && a == MIN_WORD) return MAX_WORD; else { longword prod = (longword)a * (longword)b + 16384; prod >>= 15; return prod & 0xFFFF; } } word gsm_abs P1((a), word a) { return a < 0 ? (a == MIN_WORD ? MAX_WORD : -a) : a; } longword gsm_L_mult P2((a,b),word a, word b) { assert( a != MIN_WORD || b != MIN_WORD ); return ((longword)a * (longword)b) << 1; } longword gsm_L_add P2((a,b), longword a, longword b) { if (a < 0) { if (b >= 0) return a + b; else { ulongword A = (ulongword)-(a + 1) + (ulongword)-(b + 1); return A >= MAX_LONGWORD ? MIN_LONGWORD :-(longword)A-2; } } else if (b <= 0) return a + b; else { ulongword A = (ulongword)a + (ulongword)b; return A > MAX_LONGWORD ? MAX_LONGWORD : A; } } longword gsm_L_sub P2((a,b), longword a, longword b) { if (a >= 0) { if (b >= 0) return a - b; else { /* a>=0, b<0 */ ulongword A = (ulongword)a + -(b + 1); return A >= MAX_LONGWORD ? MAX_LONGWORD : (A + 1); } } else if (b <= 0) return a - b; else { /* a<0, b>0 */ ulongword A = (ulongword)-(a + 1) + b; return A >= MAX_LONGWORD ? MIN_LONGWORD : -(longword)A - 1; } } static unsigned char const bitoff[ 256 ] = { 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; word gsm_norm P1((a), longword a ) /* * the number of left shifts needed to normalize the 32 bit * variable L_var1 for positive values on the interval * * with minimum of * minimum of 1073741824 (01000000000000000000000000000000) and * maximum of 2147483647 (01111111111111111111111111111111) * * * and for negative values on the interval with * minimum of -2147483648 (-10000000000000000000000000000000) and * maximum of -1073741824 ( -1000000000000000000000000000000). * * in order to normalize the result, the following * operation must be done: L_norm_var1 = L_var1 << norm( L_var1 ); * * (That's 'ffs', only from the left, not the right..) */ { assert(a != 0); if (a < 0) { if (a <= -1073741824) return 0; a = ~a; } return a & 0xffff0000 ? ( a & 0xff000000 ? -1 + bitoff[ 0xFF & (a >> 24) ] : 7 + bitoff[ 0xFF & (a >> 16) ] ) : ( a & 0xff00 ? 15 + bitoff[ 0xFF & (a >> 8) ] : 23 + bitoff[ 0xFF & a ] ); } longword gsm_L_asl P2((a,n), longword a, int n) { if (n >= 32) return 0; if (n <= -32) return -(a < 0); if (n < 0) return gsm_L_asr(a, -n); return a << n; } word gsm_asl P2((a,n), word a, int n) { if (n >= 16) return 0; if (n <= -16) return -(a < 0); if (n < 0) return gsm_asr(a, -n); return a << n; } longword gsm_L_asr P2((a,n), longword a, int n) { if (n >= 32) return -(a < 0); if (n <= -32) return 0; if (n < 0) return a << -n; # ifdef SASR return a >> n; # else if (a >= 0) return a >> n; else return -(longword)( -(ulongword)a >> n ); # endif } word gsm_asr P2((a,n), word a, int n) { if (n >= 16) return -(a < 0); if (n <= -16) return 0; if (n < 0) return a << -n; # ifdef SASR return a >> n; # else if (a >= 0) return a >> n; else return -(word)( -(uword)a >> n ); # endif } /* * (From p. 46, end of section 4.2.5) * * NOTE: The following lines gives [sic] one correct implementation * of the div(num, denum) arithmetic operation. Compute div * which is the integer division of num by denum: with denum * >= num > 0 */ word gsm_div P2((num,denum), word num, word denum) { longword L_num = num; longword L_denum = denum; word div = 0; int k = 15; /* The parameter num sometimes becomes zero. * Although this is explicitly guarded against in 4.2.5, * we assume that the result should then be zero as well. */ /* assert(num != 0); */ assert(num >= 0 && denum >= num); if (num == 0) return 0; while (k--) { div <<= 1; L_num <<= 1; if (L_num >= L_denum) { L_num -= L_denum; div++; } } return div; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_print.c0000644000175000017500000001135011700377701021076 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include #include "private.h" #include "gsm.h" #include "proto.h" int gsm_print P3((f, s, c), FILE * f, gsm s, gsm_byte * c) { word LARc[8], Nc[4], Mc[4], bc[4], xmaxc[4], xmc[13*4]; /* GSM_MAGIC = (*c >> 4) & 0xF; */ if (((*c >> 4) & 0x0F) != GSM_MAGIC) return -1; LARc[0] = (*c++ & 0xF) << 2; /* 1 */ LARc[0] |= (*c >> 6) & 0x3; LARc[1] = *c++ & 0x3F; LARc[2] = (*c >> 3) & 0x1F; LARc[3] = (*c++ & 0x7) << 2; LARc[3] |= (*c >> 6) & 0x3; LARc[4] = (*c >> 2) & 0xF; LARc[5] = (*c++ & 0x3) << 2; LARc[5] |= (*c >> 6) & 0x3; LARc[6] = (*c >> 3) & 0x7; LARc[7] = *c++ & 0x7; Nc[0] = (*c >> 1) & 0x7F; bc[0] = (*c++ & 0x1) << 1; bc[0] |= (*c >> 7) & 0x1; Mc[0] = (*c >> 5) & 0x3; xmaxc[0] = (*c++ & 0x1F) << 1; xmaxc[0] |= (*c >> 7) & 0x1; xmc[0] = (*c >> 4) & 0x7; xmc[1] = (*c >> 1) & 0x7; xmc[2] = (*c++ & 0x1) << 2; xmc[2] |= (*c >> 6) & 0x3; xmc[3] = (*c >> 3) & 0x7; xmc[4] = *c++ & 0x7; xmc[5] = (*c >> 5) & 0x7; xmc[6] = (*c >> 2) & 0x7; xmc[7] = (*c++ & 0x3) << 1; /* 10 */ xmc[7] |= (*c >> 7) & 0x1; xmc[8] = (*c >> 4) & 0x7; xmc[9] = (*c >> 1) & 0x7; xmc[10] = (*c++ & 0x1) << 2; xmc[10] |= (*c >> 6) & 0x3; xmc[11] = (*c >> 3) & 0x7; xmc[12] = *c++ & 0x7; Nc[1] = (*c >> 1) & 0x7F; bc[1] = (*c++ & 0x1) << 1; bc[1] |= (*c >> 7) & 0x1; Mc[1] = (*c >> 5) & 0x3; xmaxc[1] = (*c++ & 0x1F) << 1; xmaxc[1] |= (*c >> 7) & 0x1; xmc[13] = (*c >> 4) & 0x7; xmc[14] = (*c >> 1) & 0x7; xmc[15] = (*c++ & 0x1) << 2; xmc[15] |= (*c >> 6) & 0x3; xmc[16] = (*c >> 3) & 0x7; xmc[17] = *c++ & 0x7; xmc[18] = (*c >> 5) & 0x7; xmc[19] = (*c >> 2) & 0x7; xmc[20] = (*c++ & 0x3) << 1; xmc[20] |= (*c >> 7) & 0x1; xmc[21] = (*c >> 4) & 0x7; xmc[22] = (*c >> 1) & 0x7; xmc[23] = (*c++ & 0x1) << 2; xmc[23] |= (*c >> 6) & 0x3; xmc[24] = (*c >> 3) & 0x7; xmc[25] = *c++ & 0x7; Nc[2] = (*c >> 1) & 0x7F; bc[2] = (*c++ & 0x1) << 1; /* 20 */ bc[2] |= (*c >> 7) & 0x1; Mc[2] = (*c >> 5) & 0x3; xmaxc[2] = (*c++ & 0x1F) << 1; xmaxc[2] |= (*c >> 7) & 0x1; xmc[26] = (*c >> 4) & 0x7; xmc[27] = (*c >> 1) & 0x7; xmc[28] = (*c++ & 0x1) << 2; xmc[28] |= (*c >> 6) & 0x3; xmc[29] = (*c >> 3) & 0x7; xmc[30] = *c++ & 0x7; xmc[31] = (*c >> 5) & 0x7; xmc[32] = (*c >> 2) & 0x7; xmc[33] = (*c++ & 0x3) << 1; xmc[33] |= (*c >> 7) & 0x1; xmc[34] = (*c >> 4) & 0x7; xmc[35] = (*c >> 1) & 0x7; xmc[36] = (*c++ & 0x1) << 2; xmc[36] |= (*c >> 6) & 0x3; xmc[37] = (*c >> 3) & 0x7; xmc[38] = *c++ & 0x7; Nc[3] = (*c >> 1) & 0x7F; bc[3] = (*c++ & 0x1) << 1; bc[3] |= (*c >> 7) & 0x1; Mc[3] = (*c >> 5) & 0x3; xmaxc[3] = (*c++ & 0x1F) << 1; xmaxc[3] |= (*c >> 7) & 0x1; xmc[39] = (*c >> 4) & 0x7; xmc[40] = (*c >> 1) & 0x7; xmc[41] = (*c++ & 0x1) << 2; xmc[41] |= (*c >> 6) & 0x3; xmc[42] = (*c >> 3) & 0x7; xmc[43] = *c++ & 0x7; /* 30 */ xmc[44] = (*c >> 5) & 0x7; xmc[45] = (*c >> 2) & 0x7; xmc[46] = (*c++ & 0x3) << 1; xmc[46] |= (*c >> 7) & 0x1; xmc[47] = (*c >> 4) & 0x7; xmc[48] = (*c >> 1) & 0x7; xmc[49] = (*c++ & 0x1) << 2; xmc[49] |= (*c >> 6) & 0x3; xmc[50] = (*c >> 3) & 0x7; xmc[51] = *c & 0x7; /* 33 */ fprintf(f, "LARc:\t%2.2d %2.2d %2.2d %2.2d %2.2d %2.2d %2.2d %2.2d\n", LARc[0],LARc[1],LARc[2],LARc[3],LARc[4],LARc[5],LARc[6],LARc[7]); fprintf(f, "#1: Nc %4.4d bc %d Mc %d xmaxc %d\n", Nc[0], bc[0], Mc[0], xmaxc[0]); fprintf(f, "\t%.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d\n", xmc[0],xmc[1],xmc[2],xmc[3],xmc[4],xmc[5],xmc[6], xmc[7],xmc[8],xmc[9],xmc[10],xmc[11],xmc[12] ); fprintf(f, "#2: Nc %4.4d bc %d Mc %d xmaxc %d\n", Nc[1], bc[1], Mc[1], xmaxc[1]); fprintf(f, "\t%.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d\n", xmc[13+0],xmc[13+1],xmc[13+2],xmc[13+3],xmc[13+4],xmc[13+5], xmc[13+6], xmc[13+7],xmc[13+8],xmc[13+9],xmc[13+10],xmc[13+11], xmc[13+12] ); fprintf(f, "#3: Nc %4.4d bc %d Mc %d xmaxc %d\n", Nc[2], bc[2], Mc[2], xmaxc[2]); fprintf(f, "\t%.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d\n", xmc[26+0],xmc[26+1],xmc[26+2],xmc[26+3],xmc[26+4],xmc[26+5], xmc[26+6], xmc[26+7],xmc[26+8],xmc[26+9],xmc[26+10],xmc[26+11], xmc[26+12] ); fprintf(f, "#4: Nc %4.4d bc %d Mc %d xmaxc %d\n", Nc[3], bc[3], Mc[3], xmaxc[3]); fprintf(f, "\t%.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d %.2d\n", xmc[39+0],xmc[39+1],xmc[39+2],xmc[39+3],xmc[39+4],xmc[39+5], xmc[39+6], xmc[39+7],xmc[39+8],xmc[39+9],xmc[39+10],xmc[39+11], xmc[39+12] ); return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/gsm/gsm_implode.c0000644000175000017500000003114211744612271021376 0ustar jcorganjcorgan/* * Copyright 1992 by Jutta Degener and Carsten Bormann, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ /* $Header$ */ #include "private.h" #include "gsm.h" #include "proto.h" void gsm_implode P3((s, source, c), gsm s, gsm_signal * source, gsm_byte * c) { /* variable size index GSM_MAGIC 4 - LARc[0] 6 0 LARc[1] 6 1 LARc[2] 5 2 LARc[3] 5 3 LARc[4] 4 4 LARc[5] 4 5 LARc[6] 3 6 LARc[7] 3 7 Nc[0] 7 8 bc[0] 2 9 Mc[0] 2 10 xmaxc[0] 6 11 xmc[0] 3 12 xmc[1] 3 13 xmc[2] 3 14 xmc[3] 3 15 xmc[4] 3 16 xmc[5] 3 17 xmc[6] 3 18 xmc[7] 3 19 xmc[8] 3 20 xmc[9] 3 21 xmc[10] 3 22 xmc[11] 3 23 xmc[12] 3 24 Nc[1] 7 25 bc[1] 2 26 Mc[1] 2 27 xmaxc[1] 6 28 xmc[13] 3 29 xmc[14] 3 30 xmc[15] 3 31 xmc[16] 3 32 xmc[17] 3 33 xmc[18] 3 34 xmc[19] 3 35 xmc[20] 3 36 xmc[21] 3 37 xmc[22] 3 38 xmc[23] 3 39 xmc[24] 3 40 xmc[25] 3 41 Nc[2] 7 42 bc[2] 2 43 Mc[2] 2 44 xmaxc[2] 6 45 xmc[26] 3 46 xmc[27] 3 47 xmc[28] 3 48 xmc[29] 3 49 xmc[30] 3 50 xmc[31] 3 51 xmc[32] 3 52 xmc[33] 3 53 xmc[34] 3 54 xmc[35] 3 55 xmc[36] 3 56 xmc[37] 3 57 xmc[38] 3 58 Nc[3] 7 59 bc[3] 2 60 Mc[3] 2 61 xmaxc[3] 6 62 xmc[39] 3 63 xmc[40] 3 64 xmc[41] 3 65 xmc[42] 3 66 xmc[43] 3 67 xmc[44] 3 68 xmc[45] 3 69 xmc[46] 3 70 xmc[47] 3 71 xmc[48] 3 72 xmc[49] 3 73 xmc[50] 3 74 xmc[51] 3 75 */ /* There are 76 parameters per frame. The first eight are * unique. The remaining 68 are four identical subframes of * 17 parameters each. gsm_implode converts from a representation * of these parameters as values in one array of signed words * to the "packed" version of a GSM frame. */ # define LARc source # define Nc *((gsm_signal (*) [17])(source + 8)) # define bc *((gsm_signal (*) [17])(source + 9)) # define Mc *((gsm_signal (*) [17])(source + 10)) # define xmaxc *((gsm_signal (*) [17])(source + 11)) #ifdef WAV49 if (s->wav_fmt) { uword sr = 0; if (s->frame_index == 0) { sr = *c++; LARc[0] = sr & 0x3f; sr >>= 6; sr |= (uword)*c++ << 2; LARc[1] = sr & 0x3f; sr >>= 6; sr |= (uword)*c++ << 4; LARc[2] = sr & 0x1f; sr >>= 5; LARc[3] = sr & 0x1f; sr >>= 5; sr |= (uword)*c++ << 2; LARc[4] = sr & 0xf; sr >>= 4; LARc[5] = sr & 0xf; sr >>= 4; sr |= (uword)*c++ << 2; /* 5 */ LARc[6] = sr & 0x7; sr >>= 3; LARc[7] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[0] = sr & 0x7f; sr >>= 7; bc[0] = sr & 0x3; sr >>= 2; Mc[0] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[0] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 12) xmc[0] = sr & 0x7; sr >>= 3; sr = *c++; xmc[1] = sr & 0x7; sr >>= 3; xmc[2] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[3] = sr & 0x7; sr >>= 3; xmc[4] = sr & 0x7; sr >>= 3; xmc[5] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 10 */ xmc[6] = sr & 0x7; sr >>= 3; xmc[7] = sr & 0x7; sr >>= 3; xmc[8] = sr & 0x7; sr >>= 3; sr = *c++; xmc[9] = sr & 0x7; sr >>= 3; xmc[10] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[11] = sr & 0x7; sr >>= 3; xmc[12] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[1] = sr & 0x7f; sr >>= 7; bc[1] = sr & 0x3; sr >>= 2; Mc[1] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[1] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 29 - 13) xmc[13] = sr & 0x7; sr >>= 3; sr = *c++; /* 15 */ xmc[14] = sr & 0x7; sr >>= 3; xmc[15] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[16] = sr & 0x7; sr >>= 3; xmc[17] = sr & 0x7; sr >>= 3; xmc[18] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[19] = sr & 0x7; sr >>= 3; xmc[20] = sr & 0x7; sr >>= 3; xmc[21] = sr & 0x7; sr >>= 3; sr = *c++; xmc[22] = sr & 0x7; sr >>= 3; xmc[23] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[24] = sr & 0x7; sr >>= 3; xmc[25] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; /* 20 */ Nc[2] = sr & 0x7f; sr >>= 7; bc[2] = sr & 0x3; sr >>= 2; Mc[2] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[2] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 46 - 26) xmc[26] = sr & 0x7; sr >>= 3; sr = *c++; xmc[27] = sr & 0x7; sr >>= 3; xmc[28] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[29] = sr & 0x7; sr >>= 3; xmc[30] = sr & 0x7; sr >>= 3; xmc[31] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[32] = sr & 0x7; sr >>= 3; xmc[33] = sr & 0x7; sr >>= 3; xmc[34] = sr & 0x7; sr >>= 3; sr = *c++; /* 25 */ xmc[35] = sr & 0x7; sr >>= 3; xmc[36] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[37] = sr & 0x7; sr >>= 3; xmc[38] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 4; Nc[3] = sr & 0x7f; sr >>= 7; bc[3] = sr & 0x3; sr >>= 2; Mc[3] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 1; xmaxc[3] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 63 - 39) xmc[39] = sr & 0x7; sr >>= 3; sr = *c++; xmc[40] = sr & 0x7; sr >>= 3; xmc[41] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; /* 30 */ xmc[42] = sr & 0x7; sr >>= 3; xmc[43] = sr & 0x7; sr >>= 3; xmc[44] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[45] = sr & 0x7; sr >>= 3; xmc[46] = sr & 0x7; sr >>= 3; xmc[47] = sr & 0x7; sr >>= 3; sr = *c++; xmc[48] = sr & 0x7; sr >>= 3; xmc[49] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[50] = sr & 0x7; sr >>= 3; xmc[51] = sr & 0x7; sr >>= 3; s->frame_chain = sr & 0xf; } else { sr = s->frame_chain; sr |= (uword)*c++ << 4; /* 1 */ LARc[0] = sr & 0x3f; sr >>= 6; LARc[1] = sr & 0x3f; sr >>= 6; sr = *c++; LARc[2] = sr & 0x1f; sr >>= 5; sr |= (uword)*c++ << 3; LARc[3] = sr & 0x1f; sr >>= 5; LARc[4] = sr & 0xf; sr >>= 4; sr |= (uword)*c++ << 2; LARc[5] = sr & 0xf; sr >>= 4; LARc[6] = sr & 0x7; sr >>= 3; LARc[7] = sr & 0x7; sr >>= 3; sr = *c++; /* 5 */ Nc[0] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[0] = sr & 0x3; sr >>= 2; Mc[0] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[0] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 12) xmc[0] = sr & 0x7; sr >>= 3; xmc[1] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[2] = sr & 0x7; sr >>= 3; xmc[3] = sr & 0x7; sr >>= 3; xmc[4] = sr & 0x7; sr >>= 3; sr = *c++; xmc[5] = sr & 0x7; sr >>= 3; xmc[6] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; /* 10 */ xmc[7] = sr & 0x7; sr >>= 3; xmc[8] = sr & 0x7; sr >>= 3; xmc[9] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[10] = sr & 0x7; sr >>= 3; xmc[11] = sr & 0x7; sr >>= 3; xmc[12] = sr & 0x7; sr >>= 3; sr = *c++; Nc[1] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[1] = sr & 0x3; sr >>= 2; Mc[1] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[1] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 29 - 13) xmc[13] = sr & 0x7; sr >>= 3; xmc[14] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 15 */ xmc[15] = sr & 0x7; sr >>= 3; xmc[16] = sr & 0x7; sr >>= 3; xmc[17] = sr & 0x7; sr >>= 3; sr = *c++; xmc[18] = sr & 0x7; sr >>= 3; xmc[19] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[20] = sr & 0x7; sr >>= 3; xmc[21] = sr & 0x7; sr >>= 3; xmc[22] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[23] = sr & 0x7; sr >>= 3; xmc[24] = sr & 0x7; sr >>= 3; xmc[25] = sr & 0x7; sr >>= 3; sr = *c++; Nc[2] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; /* 20 */ bc[2] = sr & 0x3; sr >>= 2; Mc[2] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[2] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 46 - 26) xmc[26] = sr & 0x7; sr >>= 3; xmc[27] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[28] = sr & 0x7; sr >>= 3; xmc[29] = sr & 0x7; sr >>= 3; xmc[30] = sr & 0x7; sr >>= 3; sr = *c++; xmc[31] = sr & 0x7; sr >>= 3; xmc[32] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[33] = sr & 0x7; sr >>= 3; xmc[34] = sr & 0x7; sr >>= 3; xmc[35] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; /* 25 */ xmc[36] = sr & 0x7; sr >>= 3; xmc[37] = sr & 0x7; sr >>= 3; xmc[38] = sr & 0x7; sr >>= 3; sr = *c++; Nc[3] = sr & 0x7f; sr >>= 7; sr |= (uword)*c++ << 1; bc[3] = sr & 0x3; sr >>= 2; Mc[3] = sr & 0x3; sr >>= 2; sr |= (uword)*c++ << 5; xmaxc[3] = sr & 0x3f; sr >>= 6; #undef xmc #define xmc (source + 63 - 39) xmc[39] = sr & 0x7; sr >>= 3; xmc[40] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[41] = sr & 0x7; sr >>= 3; xmc[42] = sr & 0x7; sr >>= 3; xmc[43] = sr & 0x7; sr >>= 3; sr = *c++; /* 30 */ xmc[44] = sr & 0x7; sr >>= 3; xmc[45] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 2; xmc[46] = sr & 0x7; sr >>= 3; xmc[47] = sr & 0x7; sr >>= 3; xmc[48] = sr & 0x7; sr >>= 3; sr |= (uword)*c++ << 1; xmc[49] = sr & 0x7; sr >>= 3; xmc[50] = sr & 0x7; sr >>= 3; xmc[51] = sr & 0x7; sr >>= 3; } } else #endif { *c++ = ((GSM_MAGIC & 0xF) << 4) /* 1 */ | ((LARc[0] >> 2) & 0xF); *c++ = ((LARc[0] & 0x3) << 6) | (LARc[1] & 0x3F); *c++ = ((LARc[2] & 0x1F) << 3) | ((LARc[3] >> 2) & 0x7); *c++ = ((LARc[3] & 0x3) << 6) | ((LARc[4] & 0xF) << 2) | ((LARc[5] >> 2) & 0x3); *c++ = ((LARc[5] & 0x3) << 6) | ((LARc[6] & 0x7) << 3) | (LARc[7] & 0x7); *c++ = ((Nc[0] & 0x7F) << 1) | ((bc[0] >> 1) & 0x1); *c++ = ((bc[0] & 0x1) << 7) | ((Mc[0] & 0x3) << 5) | ((xmaxc[0] >> 1) & 0x1F); *c++ = ((xmaxc[0] & 0x1) << 7) #undef xmc #define xmc (source + 12) | ((xmc[0] & 0x7) << 4) | ((xmc[1] & 0x7) << 1) | ((xmc[2] >> 2) & 0x1); *c++ = ((xmc[2] & 0x3) << 6) | ((xmc[3] & 0x7) << 3) | (xmc[4] & 0x7); *c++ = ((xmc[5] & 0x7) << 5) /* 10 */ | ((xmc[6] & 0x7) << 2) | ((xmc[7] >> 1) & 0x3); *c++ = ((xmc[7] & 0x1) << 7) | ((xmc[8] & 0x7) << 4) | ((xmc[9] & 0x7) << 1) | ((xmc[10] >> 2) & 0x1); *c++ = ((xmc[10] & 0x3) << 6) | ((xmc[11] & 0x7) << 3) | (xmc[12] & 0x7); *c++ = ((Nc[1] & 0x7F) << 1) | ((bc[1] >> 1) & 0x1); *c++ = ((bc[1] & 0x1) << 7) | ((Mc[1] & 0x3) << 5) | ((xmaxc[1] >> 1) & 0x1F); *c++ = ((xmaxc[1] & 0x1) << 7) #undef xmc #define xmc (source + 29 - 13) | ((xmc[13] & 0x7) << 4) | ((xmc[14] & 0x7) << 1) | ((xmc[15] >> 2) & 0x1); *c++ = ((xmc[15] & 0x3) << 6) | ((xmc[16] & 0x7) << 3) | (xmc[17] & 0x7); *c++ = ((xmc[18] & 0x7) << 5) | ((xmc[19] & 0x7) << 2) | ((xmc[20] >> 1) & 0x3); *c++ = ((xmc[20] & 0x1) << 7) | ((xmc[21] & 0x7) << 4) | ((xmc[22] & 0x7) << 1) | ((xmc[23] >> 2) & 0x1); *c++ = ((xmc[23] & 0x3) << 6) | ((xmc[24] & 0x7) << 3) | (xmc[25] & 0x7); *c++ = ((Nc[2] & 0x7F) << 1) /* 20 */ | ((bc[2] >> 1) & 0x1); *c++ = ((bc[2] & 0x1) << 7) | ((Mc[2] & 0x3) << 5) | ((xmaxc[2] >> 1) & 0x1F); *c++ = ((xmaxc[2] & 0x1) << 7) #undef xmc #define xmc (source + 46 - 26) | ((xmc[26] & 0x7) << 4) | ((xmc[27] & 0x7) << 1) | ((xmc[28] >> 2) & 0x1); *c++ = ((xmc[28] & 0x3) << 6) | ((xmc[29] & 0x7) << 3) | (xmc[30] & 0x7); *c++ = ((xmc[31] & 0x7) << 5) | ((xmc[32] & 0x7) << 2) | ((xmc[33] >> 1) & 0x3); *c++ = ((xmc[33] & 0x1) << 7) | ((xmc[34] & 0x7) << 4) | ((xmc[35] & 0x7) << 1) | ((xmc[36] >> 2) & 0x1); *c++ = ((xmc[36] & 0x3) << 6) | ((xmc[37] & 0x7) << 3) | (xmc[38] & 0x7); *c++ = ((Nc[3] & 0x7F) << 1) | ((bc[3] >> 1) & 0x1); *c++ = ((bc[3] & 0x1) << 7) | ((Mc[3] & 0x3) << 5) | ((xmaxc[3] >> 1) & 0x1F); *c++ = ((xmaxc[3] & 0x1) << 7) #undef xmc #define xmc (source + 63 - 39) | ((xmc[39] & 0x7) << 4) | ((xmc[40] & 0x7) << 1) | ((xmc[41] >> 2) & 0x1); *c++ = ((xmc[41] & 0x3) << 6) /* 30 */ | ((xmc[42] & 0x7) << 3) | (xmc[43] & 0x7); *c++ = ((xmc[44] & 0x7) << 5) | ((xmc[45] & 0x7) << 2) | ((xmc[46] >> 1) & 0x3); *c++ = ((xmc[46] & 0x1) << 7) | ((xmc[47] & 0x7) << 4) | ((xmc[48] & 0x7) << 1) | ((xmc[49] >> 2) & 0x1); *c++ = ((xmc[49] & 0x3) << 6) | ((xmc[50] & 0x7) << 3) | (xmc[51] & 0x7); } } gnuradio-3.7.2.1/gr-vocoder/lib/ulaw_decode_bs_impl.cc0000664000175000017500000000354212207440367022441 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ulaw_decode_bs_impl.h" #include #include namespace gr { namespace vocoder { extern "C" { #include "g7xx/g72x.h" } ulaw_decode_bs::sptr ulaw_decode_bs::make() { return gnuradio::get_initial_sptr (new ulaw_decode_bs_impl()); } ulaw_decode_bs_impl::ulaw_decode_bs_impl() : sync_block("vocoder_ulaw_decode_bs", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(short))) { } ulaw_decode_bs_impl::~ulaw_decode_bs_impl() { } int ulaw_decode_bs_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = ulaw2linear(in[i]); } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/codec2/0000755000175000017500000000000012231726673017307 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/lib/codec2/c2demo.c0000644000175000017500000000445311744612271020626 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: c2demo.c AUTHOR......: David Rowe DATE CREATED: 15/11/2010 Encodes and decodes a file of raw speech samples using Codec 2. Demonstrates use of Codec 2 function API. Note to convert a wave file to raw and vice-versa: $ sox file.wav -r 8000 -s -2 file.raw $ sox -r 8000 -s -2 file.raw file.wav \*---------------------------------------------------------------------------*/ /* Copyright (C) 2010 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include "codec2.h" #include #include #include #include #define BITS_SIZE ((CODEC2_BITS_PER_FRAME + 7) / 8) int main(int argc, char *argv[]) { void *codec2; FILE *fin; FILE *fout; short buf[CODEC2_SAMPLES_PER_FRAME]; unsigned char bits[BITS_SIZE]; if (argc != 3) { printf("usage: %s InputRawSpeechFile OutputRawSpeechFile\n", argv[0]); exit(1); } if ( (fin = fopen(argv[1],"rb")) == NULL ) { fprintf(stderr, "Error opening input speech file: %s: %s.\n", argv[1], strerror(errno)); exit(1); } if ( (fout = fopen(argv[2],"wb")) == NULL ) { fprintf(stderr, "Error opening output speech file: %s: %s.\n", argv[2], strerror(errno)); exit(1); } /* Note only one set of Codec 2 states is required for an encoder and decoder pair. */ codec2 = codec2_create(); while(fread(buf, sizeof(short), CODEC2_SAMPLES_PER_FRAME, fin) == CODEC2_SAMPLES_PER_FRAME) { codec2_encode(codec2, bits, buf); codec2_decode(codec2, buf, bits); fwrite(buf, sizeof(short), CODEC2_SAMPLES_PER_FRAME, fout); } codec2_destroy(codec2); fclose(fin); fclose(fout); return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/CMakeLists.txt0000664000175000017500000001113412207440367022045 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Create executable to generate other sources # http://www.vtk.org/Wiki/CMake_Cross_Compiling#Using_executables_in_the_build_created_during_the_build ######################################################################## if(NOT CMAKE_CROSSCOMPILING) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}) add_executable(generate_codebook ${CMAKE_CURRENT_SOURCE_DIR}/generate_codebook.c) target_link_libraries(generate_codebook -lm) export(TARGETS generate_codebook APPEND FILE ${EXPORT_FILE}) endif() ######################################################################## # Create codebook ######################################################################## set(CODEBOOKS ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp1.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp2.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp3.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp4.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp5.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp6.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp7.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp8.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp9.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/lsp10.txt ) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/codebook.c DEPENDS generate_codebook ${CODEBOOKS} COMMAND generate_codebook lsp_cb ${CODEBOOKS} > ${CMAKE_CURRENT_BINARY_DIR}/codebook.c ) ######################################################################## # Create codebookd ######################################################################## set(CODEBOOKSD ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp1.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp2.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp3.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp4.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp5.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp6.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp7.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp8.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp9.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp10.txt ) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/codebookd.c DEPENDS generate_codebook ${CODEBOOKSD} COMMAND generate_codebook lsp_cbd ${CODEBOOKSD} > ${CMAKE_CURRENT_BINARY_DIR}/codebookd.c ) ######################################################################## # Create codebookdvq ######################################################################## set(CODEBOOKSDVQ ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp1.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp2.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp3.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp4.txt ${CMAKE_CURRENT_SOURCE_DIR}/codebook/dlsp5.txt ) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/codebookdvq.c DEPENDS generate_codebook ${CODEBOOKSDVQ} COMMAND generate_codebook lsp_cbdvq ${CODEBOOKSDVQ} > ${CMAKE_CURRENT_BINARY_DIR}/codebookdvq.c ) ######################################################################## # Append all sources in this dir ######################################################################## list(APPEND gr_vocoder_sources ${CMAKE_CURRENT_BINARY_DIR}/codebook.c ${CMAKE_CURRENT_BINARY_DIR}/codebookd.c ${CMAKE_CURRENT_BINARY_DIR}/codebookdvq.c ${CMAKE_CURRENT_SOURCE_DIR}/dump.c ${CMAKE_CURRENT_SOURCE_DIR}/lpc.c ${CMAKE_CURRENT_SOURCE_DIR}/nlp.c ${CMAKE_CURRENT_SOURCE_DIR}/postfilter.c ${CMAKE_CURRENT_SOURCE_DIR}/sine.c ${CMAKE_CURRENT_SOURCE_DIR}/codec2.c ${CMAKE_CURRENT_SOURCE_DIR}/fft.c ${CMAKE_CURRENT_SOURCE_DIR}/kiss_fft.c ${CMAKE_CURRENT_SOURCE_DIR}/interp.c ${CMAKE_CURRENT_SOURCE_DIR}/lsp.c ${CMAKE_CURRENT_SOURCE_DIR}/phase.c ${CMAKE_CURRENT_SOURCE_DIR}/quantise.c ${CMAKE_CURRENT_SOURCE_DIR}/pack.c ) gnuradio-3.7.2.1/gr-vocoder/lib/codec2/postfilter.c0000644000175000017500000001051011744612271021637 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: postfilter.c AUTHOR......: David Rowe DATE CREATED: 13/09/09 Postfilter to improve sound quality for speech with high levels of background noise. Unlike mixed-excitation models requires no bits to be transmitted to handle background noise. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include #include #include "defines.h" #include "comp.h" #include "dump.h" #include "postfilter.h" /*---------------------------------------------------------------------------*\ DEFINES \*---------------------------------------------------------------------------*/ #define BG_THRESH 40.0 /* only consider low levels signals for bg_est */ #define BG_BETA 0.1 /* averaging filter constant */ /*---------------------------------------------------------------------------*\ postfilter() The post filter is designed to help with speech corrupted by background noise. The zero phase model tends to make speech with background noise sound "clicky". With high levels of background noise the low level inter-formant parts of the spectrum will contain noise rather than speech harmonics, so modelling them as voiced (i.e. a continuous, non-random phase track) is inaccurate. Some codecs (like MBE) have a mixed voicing model that breaks the spectrum into voiced and unvoiced regions. Several bits/frame (5-12) are required to transmit the frequency selective voicing information. Mixed excitation also requires accurate voicing estimation (parameter estimators always break occasionally under exceptional condition). In our case we use a post filter approach which requires no additional bits to be transmitted. The decoder measures the average level of the background noise during unvoiced frames. If a harmonic is less than this level it is made unvoiced by randomising it's phases. This idea is rather experimental. Some potential problems that may happen: 1/ If someone says "aaaaaaaahhhhhhhhh" will background estimator track up to speech level? This would be a bad thing. 2/ If background noise suddenly dissapears from the source speech does estimate drop quickly? What is noise suddenly re-appears? 3/ Background noise with a non-flat sepctrum. Current algorithm just comsiders scpetrum as a whole, but this could be broken up into bands, each with their own estimator. 4/ Males and females with the same level of background noise. Check performance the same. Changing Wo affects width of each band, may affect bg energy estimates. 5/ Not sure what happens during long periods of voiced speech e.g. "sshhhhhhh" \*---------------------------------------------------------------------------*/ void postfilter( MODEL *model, float *bg_est ) { int m, uv; float e; /* determine average energy across spectrum */ e = 0.0; for(m=1; m<=model->L; m++) e += model->A[m]*model->A[m]; e = 10.0*log10(e/model->L); /* If beneath threhold, update bg estimate. The idea of the threshold is to prevent updating during high level speech. */ if ((e < BG_THRESH) && !model->voiced) *bg_est = *bg_est*(1.0 - BG_BETA) + e*BG_BETA; /* now mess with phases during voiced frames to make any harmonics less then our background estimate unvoiced. */ uv = 0; if (model->voiced) for(m=1; m<=model->L; m++) if (20.0*log10(model->A[m]) < *bg_est) { model->phi[m] = TWO_PI*(float)rand()/RAND_MAX; uv++; } #ifdef DUMP dump_bg(e, *bg_est, 100.0*uv/model->L); #endif } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/postfilter.h0000644000175000017500000000177411744612271021660 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: postfilter.h AUTHOR......: David Rowe DATE CREATED: 13/09/09 Postfilter header file. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __POSTFILTER__ #define __POSTFILTER__ void postfilter(MODEL *model, float *bg_est); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/dump.h0000644000175000017500000000331311744612271020421 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: dump.h AUTHOR......: David Rowe DATE CREATED: 25/8/09 Routines to dump data to text files for Octave analysis. \*---------------------------------------------------------------------------*/ /* All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __DUMP__ #define __DUMP__ #include "comp.h" void dump_on(char filename_prefix[]); void dump_off(); void dump_Sn(float Sn[]); void dump_Sw(COMP Sw[]); void dump_Sw_(COMP Sw_[]); void dump_Ew(COMP Ew[]); /* amplitude modelling */ void dump_model(MODEL *m); void dump_quantised_model(MODEL *m); void dump_Pw(COMP Pw[]); void dump_lsp(float lsp[]); void dump_ak(float ak[], int order); void dump_E(float E); void dump_resample(float w[], float A[], int n); /* phase modelling */ void dump_snr(float snr); void dump_phase(float phase[], int L); void dump_phase_(float phase[], int L); /* NLP states */ void dump_sq(float sq[]); void dump_dec(COMP Fw[]); void dump_Fw(COMP Fw[]); void dump_e(float e_hz[]); void dump_Rk(float Rk[]); /* post filter */ void dump_bg(float e, float bg_est, float percent_uv); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/interp.c0000664000175000017500000003240212231726673020757 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: interp.c AUTHOR......: David Rowe DATE CREATED: 9/10/09 Interpolation of 20ms frames to 10ms frames. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include #include #include #include #include "defines.h" #include "interp.h" #include "lsp.h" #include "quantise.h" #include "dump.h" float sample_log_amp(MODEL *model, float w); /*---------------------------------------------------------------------------*\ FUNCTION....: interp() AUTHOR......: David Rowe DATE CREATED: 22/8/10 Given two frames decribed by model parameters 20ms apart, determines the model parameters of the 10ms frame between them. Assumes voicing is available for middle (interpolated) frame. Outputs are amplitudes and Wo for the interpolated frame. This version can interpolate the amplitudes between two frames of different Wo and L. This version works by log linear interpolation, but listening tests showed it creates problems in background noise, e.g. hts2a and mmt1. When this function is used (--dec mode) bg noise appears to be amplitude modulated, and gets louder. The interp_lsp() function below seems to do a better job. \*---------------------------------------------------------------------------*/ void interpolate( MODEL *interp, /* interpolated model params */ MODEL *prev, /* previous frames model params */ MODEL *next /* next frames model params */ ) { int l; float w,log_amp; /* Wo depends on voicing of this and adjacent frames */ if (interp->voiced) { if (prev->voiced && next->voiced) interp->Wo = (prev->Wo + next->Wo)/2.0; if (!prev->voiced && next->voiced) interp->Wo = next->Wo; if (prev->voiced && !next->voiced) interp->Wo = prev->Wo; } else { interp->Wo = TWO_PI/P_MAX; } interp->L = PI/interp->Wo; /* Interpolate amplitudes using linear interpolation in log domain */ for(l=1; l<=interp->L; l++) { w = l*interp->Wo; log_amp = (sample_log_amp(prev, w) + sample_log_amp(next, w))/2.0; interp->A[l] = pow(10.0, log_amp); } } /*---------------------------------------------------------------------------*\ FUNCTION....: sample_log_amp() AUTHOR......: David Rowe DATE CREATED: 22/8/10 Samples the amplitude envelope at an arbitrary frequency w. Uses linear interpolation in the log domain to sample between harmonic amplitudes. \*---------------------------------------------------------------------------*/ float sample_log_amp(MODEL *model, float w) { int m; float f, log_amp; assert(w > 0.0); assert (w <= PI); m = 0; while ((m+1)*model->Wo < w) m++; f = (w - m*model->Wo)/model->Wo; assert(f <= 1.0); if (m < 1) { log_amp = f*log10(model->A[1] + 1E-6); } else if ((m+1) > model->L) { log_amp = (1.0-f)*log10(model->A[model->L] + 1E-6); } else { log_amp = (1.0-f)*log10(model->A[m] + 1E-6) + f*log10(model->A[m+1] + 1E-6); //printf("m=%d A[m] %f A[m+1] %f x %f %f %f\n", m, model->A[m], // model->A[m+1], pow(10.0, log_amp), // (1-f), f); } return log_amp; } /*---------------------------------------------------------------------------*\ FUNCTION....: sample_log_amp_quad() AUTHOR......: David Rowe DATE CREATED: 9 March 2011 Samples the amplitude envelope at an arbitrary frequency w. Uses quadratic interpolation in the log domain to sample between harmonic amplitudes. y(x) = ax*x + bx + c We assume three points are x=-1, x=0, x=1, which we map to m-1,m,m+1 c = y(0) b = (y(1) - y(-1))/2 a = y(-1) + b - y(0) \*---------------------------------------------------------------------------*/ float sample_log_amp_quad(MODEL *model, float w) { int m; float a,b,c,x, log_amp; assert(w > 0.0); assert (w <= PI); m = floor(w/model->Wo + 0.5); if (m < 2) m = 2; if (m > (model->L-1)) m = model->L-1; c = log10(model->A[m]+1E-6); b = (log10(model->A[m+1]+1E-6) - log10(model->A[m-1]+1E-6))/2.0; a = log10(model->A[m-1]+1E-6) + b - c; x = (w - m*model->Wo)/model->Wo; log_amp = a*x*x + b*x + c; //printf("m=%d A[m-1] %f A[m] %f A[m+1] %f w %f x %f log_amp %f\n", m, // model->A[m-1], // model->A[m], model->A[m+1], w, x, pow(10.0, log_amp)); return log_amp; } /*---------------------------------------------------------------------------*\ FUNCTION....: sample_log_amp_quad_nl() AUTHOR......: David Rowe DATE CREATED: 10 March 2011 Samples the amplitude envelope at an arbitrary frequency w. Uses quadratic interpolation in the log domain to sample between harmonic amplitudes. This version can handle non-linear steps along a freq axis defined by arbitrary steps. y(x) = ax*x + bx + c We assume three points are (x_1,y_1), (0,y0) and (x1,y1). \*---------------------------------------------------------------------------*/ float sample_log_amp_quad_nl( float w[], /* frequency points */ float A[], /* for these amplitude samples */ int np, /* number of frequency points */ float w_sample /* frequency of new samples */ ) { int m,i; float a,b,c,x, log_amp, best_dist; float x_1, x1; float y_1, y0, y1; //printf("w_sample %f\n", w_sample); assert(w_sample >= 0.0); assert (w_sample <= 1.1*PI); /* find closest point to centre quadratic interpolator */ best_dist = 1E32; m = 0; for (i=0; i (np-2)) m = np - 2; /* find polynomial coeffs */ x_1 = w[m-1]- w[m]; x1 = w[m+1] - w[m]; y_1 = log10(A[m-1]+1E-6); y0 = log10(A[m]+1E-6); y1 = log10(A[m+1]+1E-6); c = y0; a = (y_1*x1 - y1*x_1 + c*x_1 - c*x1)/(x_1*x_1*x1 - x1*x1*x_1); b = (y1 -a*x1*x1 - c)/x1; x = w_sample - w[m]; //printf("%f %f %f\n", w[0], w[1], w[2]); //printf("%f %f %f %f %f %f\n", x_1, y_1, 0.0, y0, x1, y1); log_amp = a*x*x + b*x + c; //printf("a %f b %f c %f\n", a, b, c); //printf("m=%d A[m-1] %f A[m] %f A[m+1] %f w_sample %f w[m] %f x %f log_amp %f\n", m, // A[m-1], // A[m], A[m+1], w_sample, w[m], x, log_amp); //exit(0); return log_amp; } #define M_MAX 40 float fres[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1850, 2100, 2350, 2600, 2900, 3400, 3800}; /*---------------------------------------------------------------------------*\ FUNCTION....: resample_amp_nl() AUTHOR......: David Rowe DATE CREATED: 7 March 2011 Converts the current model with L {Am} samples spaced Wo apart to RES_POINTS samples spaced Wo/RES_POINTS apart. Then subtracts from the previous frames samples to get the delta. \*---------------------------------------------------------------------------*/ void resample_amp_fixed(MODEL *model, float w[], float A[], float wres[], float Ares[], float AresdB_prev[], float AresdB[], float deltat[]) { int i; for(i=1; i<=model->L; i++) { w[i-1] = i*model->Wo; A[i-1] = model->A[i]; } for(i=0; iL, wres[i])); } /* work out delta T vector for this frame */ for(i=0; iL; i++) { new_A = pow(10.0,sample_log_amp_quad_nl(wres, Ares, RES_POINTS, model->Wo*i)); signal += pow(model->A[i], 2.0); noise += pow(model->A[i] - new_A, 2.0); //printf("%f %f\n", model->A[i], new_A); model->A[i] = new_A; } snr = 10.0*log10(signal/noise); printf("snr = %3.2f\n", snr); //exit(0); return snr; } /*---------------------------------------------------------------------------*\ FUNCTION....: resample_amp() AUTHOR......: David Rowe DATE CREATED: 10 March 2011 Converts the current model with L {Am} samples spaced Wo apart to M samples with a non-linear spacing. Then converts back to L {Am} samples. used to prototype constant rate Amplitude encoding ideas. Returns the SNR in dB. \*---------------------------------------------------------------------------*/ float resample_amp(MODEL *model, int m) { int i; MODEL model_m; float new_A, signal, noise, snr, log_amp_dB; float n_db = 0.0; model_m.Wo = PI/(float)m; model_m.L = PI/model_m.Wo; for(i=1; i<=model_m.L; i++) { log_amp_dB = 20.0*sample_log_amp_quad(model, i*model_m.Wo); log_amp_dB += n_db*(1.0 - 2.0*rand()/RAND_MAX); model_m.A[i] = pow(10,log_amp_dB/20.0); } //dump_resample(&model_m); signal = noise = 0.0; for(i=1; iL/4; i++) { new_A = pow(10,sample_log_amp_quad(&model_m, i*model->Wo)); signal += pow(model->A[i], 2.0); noise += pow(model->A[i] - new_A, 2.0); //printf("%f %f\n", model->A[i], new_A); model->A[i] = new_A; } snr = 10.0*log10(signal/noise); //printf("snr = %3.2f\n", snr); //exit(0); return snr; } /*---------------------------------------------------------------------------*\ FUNCTION....: interp_lsp() AUTHOR......: David Rowe DATE CREATED: 10 Nov 2010 Given two frames decribed by model parameters 20ms apart, determines the model parameters of the 10ms frame between them. Assumes voicing is available for middle (interpolated) frame. Outputs are amplitudes and Wo for the interpolated frame. This version uses interpolation of LSPs, seems to do a better job with bg noise. \*---------------------------------------------------------------------------*/ void interpolate_lsp( MODEL *interp, /* interpolated model params */ MODEL *prev, /* previous frames model params */ MODEL *next, /* next frames model params */ float *prev_lsps, /* previous frames LSPs */ float prev_e, /* previous frames LPC energy */ float *next_lsps, /* next frames LSPs */ float next_e, /* next frames LPC energy */ float *ak_interp /* interpolated aks for this frame */ ) { //int l,i; int i; float lsps[LPC_ORD],e; float snr; /* Wo depends on voicing of this and adjacent frames */ if (interp->voiced) { if (prev->voiced && next->voiced) interp->Wo = (prev->Wo + next->Wo)/2.0; if (!prev->voiced && next->voiced) interp->Wo = next->Wo; if (prev->voiced && !next->voiced) interp->Wo = prev->Wo; } else { interp->Wo = TWO_PI/P_MAX; } interp->L = PI/interp->Wo; /* interpolate LSPs */ for(i=0; i. */ #include "codec2.h" #include #include #include #include #define BITS_SIZE ((CODEC2_BITS_PER_FRAME + 7) / 8) int main(int argc, char *argv[]) { void *codec2; FILE *fin; FILE *fout; short buf[CODEC2_SAMPLES_PER_FRAME]; unsigned char bits[BITS_SIZE]; if (argc != 3) { printf("usage: %s InputBitFile OutputRawSpeechFile\n", argv[0]); exit(1); } if (strcmp(argv[1], "-") == 0) fin = stdin; else if ( (fin = fopen(argv[1],"rb")) == NULL ) { fprintf(stderr, "Error opening input bit file: %s: %s.\n", argv[1], strerror(errno)); exit(1); } if (strcmp(argv[2], "-") == 0) fout = stdout; else if ( (fout = fopen(argv[2],"wb")) == NULL ) { fprintf(stderr, "Error opening output speech file: %s: %s.\n", argv[2], strerror(errno)); exit(1); } codec2 = codec2_create(); while(fread(bits, sizeof(char), BITS_SIZE, fin) == BITS_SIZE) { codec2_decode(codec2, buf, bits); fwrite(buf, sizeof(short), CODEC2_SAMPLES_PER_FRAME, fout); //if this is in a pipeline, we probably don't want the usual //buffering to occur if (fout == stdout) fflush(stdout); if (fin == stdin) fflush(stdin); } codec2_destroy(codec2); fclose(fin); fclose(fout); return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/globals.c0000644000175000017500000000316111744612271021073 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: globals.c AUTHOR......: David Rowe DATE CREATED: 11/5/94 Globals for sinusoidal speech coder. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include "sine.h" /* global defines for coder */ /* Globals used in encoder and decoder */ int frames; /* number of frames processed so far */ float Sn[M]; /* float input speech samples */ MODEL model; /* model parameters for the current frame */ int Nw; /* number of samples in analysis window */ float sig; /* energy of current frame */ /* Globals used in encoder */ float w[M]; /* time domain hamming window */ COMP W[FFT_ENC]; /* DFT of w[] */ COMP Sw[FFT_ENC]; /* DFT of current frame */ /* Globals used in decoder */ COMP Sw_[FFT_ENC]; /* DFT of all voiced synthesised signal */ float Sn_[AW_DEC]; /* synthesised speech */ float Pn[AW_DEC]; /* time domain Parzen (trapezoidal) window */ gnuradio-3.7.2.1/gr-vocoder/lib/codec2/c2sim.c0000644000175000017500000002553311744612271020474 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: c2sim.c AUTHOR......: David Rowe DATE CREATED: 20/8/2010 Codec2 simulation. Combines encoder and decoder and allows switching in out various algorithms and quantisation steps. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include #include #include #include #include #include "defines.h" #include "sine.h" #include "nlp.h" #include "dump.h" #include "lpc.h" #include "lsp.h" #include "quantise.h" #include "phase.h" #include "postfilter.h" #include "interp.h" /*---------------------------------------------------------------------------*\ switch_present() Searches the command line arguments for a "switch". If the switch is found, returns the command line argument where it ws found, else returns NULL. \*---------------------------------------------------------------------------*/ int switch_present(sw,argc,argv) register char sw[]; /* switch in string form */ register int argc; /* number of command line arguments */ register char *argv[]; /* array of command line arguments in string form */ { register int i; /* loop variable */ for(i=1; i 20)) { fprintf(stderr, "Error in lpc order: %d\n", order); exit(1); } } dump = switch_present("--dump",argc,argv); #ifdef DUMP if (dump) dump_on(argv[dump+1]); #endif lsp = switch_present("--lsp",argc,argv); lsp_quantiser = 0; if (lsp) assert(order == LPC_ORD); lspd = switch_present("--lspd",argc,argv); if (lspd) assert(order == LPC_ORD); lspdvq = switch_present("--lspdvq",argc,argv); if (lspdvq) assert(order == LPC_ORD); phase0 = switch_present("--phase0",argc,argv); if (phase0) { ex_phase[0] = 0; } hand_voicing = switch_present("--hand_voicing",argc,argv); if (hand_voicing) { fvoicing = fopen(argv[hand_voicing+1],"rt"); assert(fvoicing != NULL); } bg_est = 0.0; postfilt = switch_present("--postfilter",argc,argv); decimate = switch_present("--dec",argc,argv); arg = switch_present("--resample",argc,argv); resample = atoi(argv[arg+1]); /* Initialise ------------------------------------------------------------*/ make_analysis_window(w,W); make_synthesis_window(Pn); quantise_init(); /* Main loop ------------------------------------------------------------*/ frames = 0; sum_snr = 0; while(fread(buf,sizeof(short),N,fin)) { frames++; //printf("frame: %d", frames); /* Read input speech */ for(i=0; i 32767.0) buf[i] = 32767; else if (Sn_[i] < -32767.0) buf[i] = -32767; else buf[i] = Sn_[i]; } } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/lsp.c0000644000175000017500000002220211744612271020243 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: lsp.c AUTHOR......: David Rowe DATE CREATED: 24/2/93 This file contains functions for LPC to LSP conversion and LSP to LPC conversion. Note that the LSP coefficients are not in radians format but in the x domain of the unit circle. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include "defines.h" #include "lsp.h" #include #include #include /* Only 10 gets used, so far. */ #define LSP_MAX_ORDER 20 /*---------------------------------------------------------------------------*\ Introduction to Line Spectrum Pairs (LSPs) ------------------------------------------ LSPs are used to encode the LPC filter coefficients {ak} for transmission over the channel. LSPs have several properties (like less sensitivity to quantisation noise) that make them superior to direct quantisation of {ak}. A(z) is a polynomial of order lpcrdr with {ak} as the coefficients. A(z) is transformed to P(z) and Q(z) (using a substitution and some algebra), to obtain something like: A(z) = 0.5[P(z)(z+z^-1) + Q(z)(z-z^-1)] (1) As you can imagine A(z) has complex zeros all over the z-plane. P(z) and Q(z) have the very neat property of only having zeros _on_ the unit circle. So to find them we take a test point z=exp(jw) and evaluate P (exp(jw)) and Q(exp(jw)) using a grid of points between 0 and pi. The zeros (roots) of P(z) also happen to alternate, which is why we swap coefficients as we find roots. So the process of finding the LSP frequencies is basically finding the roots of 5th order polynomials. The root so P(z) and Q(z) occur in symmetrical pairs at +/-w, hence the name Line Spectrum Pairs (LSPs). To convert back to ak we just evaluate (1), "clocking" an impulse thru it lpcrdr times gives us the impulse response of A(z) which is {ak}. \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ FUNCTION....: cheb_poly_eva() AUTHOR......: David Rowe DATE CREATED: 24/2/93 This function evalutes a series of chebyshev polynomials FIXME: performing memory allocation at run time is very inefficient, replace with stack variables of MAX_P size. \*---------------------------------------------------------------------------*/ static float cheb_poly_eva(float *coef,float x,int m) /* float coef[] coefficients of the polynomial to be evaluated */ /* float x the point where polynomial is to be evaluated */ /* int m order of the polynomial */ { int i; float *t,*u,*v,sum; float T[(LSP_MAX_ORDER / 2) + 1]; /* Initialise pointers */ t = T; /* T[i-2] */ *t++ = 1.0; u = t--; /* T[i-1] */ *u++ = x; v = u--; /* T[i] */ /* Evaluate chebyshev series formulation using iterative approach */ for(i=2;i<=m/2;i++) *v++ = (2*x)*(*u++) - *t++; /* T[i] = 2*x*T[i-1] - T[i-2] */ sum=0.0; /* initialise sum to zero */ t = T; /* reset pointer */ /* Evaluate polynomial and return value also free memory space */ for(i=0;i<=m/2;i++) sum+=coef[(m/2)-i]**t++; return sum; } /*---------------------------------------------------------------------------*\ FUNCTION....: lpc_to_lsp() AUTHOR......: David Rowe DATE CREATED: 24/2/93 This function converts LPC coefficients to LSP coefficients. \*---------------------------------------------------------------------------*/ int lpc_to_lsp (float *a, int lpcrdr, float *freq, int nb, float delta) /* float *a lpc coefficients */ /* int lpcrdr order of LPC coefficients (10) */ /* float *freq LSP frequencies in radians */ /* int nb number of sub-intervals (4) */ /* float delta grid spacing interval (0.02) */ { float psuml,psumr,psumm,temp_xr,xl,xr,xm = 0; float temp_psumr; int i,j,m,flag,k; float *px; /* ptrs of respective P'(z) & Q'(z) */ float *qx; float *p; float *q; float *pt; /* ptr used for cheb_poly_eval() whether P' or Q' */ int roots=0; /* number of roots found */ float Q[LSP_MAX_ORDER + 1]; float P[LSP_MAX_ORDER + 1]; flag = 1; m = lpcrdr/2; /* order of P'(z) & Q'(z) polynimials */ /* Allocate memory space for polynomials */ /* determine P'(z)'s and Q'(z)'s coefficients where P'(z) = P(z)/(1 + z^(-1)) and Q'(z) = Q(z)/(1-z^(-1)) */ px = P; /* initilaise ptrs */ qx = Q; p = px; q = qx; *px++ = 1.0; *qx++ = 1.0; for(i=1;i<=m;i++){ *px++ = a[i]+a[lpcrdr+1-i]-*p++; *qx++ = a[i]-a[lpcrdr+1-i]+*q++; } px = P; qx = Q; for(i=0;i= -1.0)){ xr = xl - delta ; /* interval spacing */ psumr = cheb_poly_eva(pt,xr,lpcrdr);/* poly(xl-delta_x) */ temp_psumr = psumr; temp_xr = xr; /* if no sign change increment xr and re-evaluate poly(xr). Repeat til sign change. if a sign change has occurred the interval is bisected and then checked again for a sign change which determines in which interval the zero lies in. If there is no sign change between poly(xm) and poly(xl) set interval between xm and xr else set interval between xl and xr and repeat till root is located within the specified limits */ if((psumr*psuml)<0.0){ roots++; psumm=psuml; for(k=0;k<=nb;k++){ xm = (xl+xr)/2; /* bisect the interval */ psumm=cheb_poly_eva(pt,xm,lpcrdr); if(psumm*psuml>0.){ psuml=psumm; xl=xm; } else{ psumr=psumm; xr=xm; } } /* once zero is found, reset initial interval to xr */ freq[j] = (xm); xl = xm; flag = 0; /* reset flag for next search */ } else{ psuml=temp_psumr; xl=temp_xr; } } } /* convert from x domain to radians */ for(i=0; i. */ #include "defines.h" #include "phase.h" #include "fft.h" #include "comp.h" #include "glottal.c" #include #include #include #include #define GLOTTAL_FFT_SIZE 512 /*---------------------------------------------------------------------------*\ aks_to_H() Samples the complex LPC synthesis filter spectrum at the harmonic frequencies. \*---------------------------------------------------------------------------*/ void aks_to_H( MODEL *model, /* model parameters */ float aks[], /* LPC's */ float G, /* energy term */ COMP H[], /* complex LPC spectral samples */ int order ) { COMP Pw[FFT_DEC]; /* power spectrum */ int i,m; /* loop variables */ int am,bm; /* limits of current band */ float r; /* no. rads/bin */ float Em; /* energy in band */ float Am; /* spectral amplitude sample */ int b; /* centre bin of harmonic */ float phi_; /* phase of LPC spectra */ r = TWO_PI/(FFT_DEC); /* Determine DFT of A(exp(jw)) ------------------------------------------*/ for(i=0; iL; m++) { am = floor((m - 0.5)*model->Wo/r + 0.5); bm = floor((m + 0.5)*model->Wo/r + 0.5); b = floor(m*model->Wo/r + 0.5); Em = 0.0; for(i=am; iWo)*N/2; */ ex_phase[0] += (model->Wo)*N; ex_phase[0] -= TWO_PI*floor(ex_phase[0]/TWO_PI + 0.5); r = TWO_PI/GLOTTAL_FFT_SIZE; for(m=1; m<=model->L; m++) { /* generate excitation */ if (model->voiced) { /* I think adding a little jitter helps improve low pitch males like hts1a. This moves the onset of each harmonic over at +/- 0.25 of a sample. */ jitter = 0.25*(1.0 - 2.0*rand()/RAND_MAX); b = floor(m*model->Wo/r + 0.5); if (b > ((GLOTTAL_FFT_SIZE/2)-1)) { b = (GLOTTAL_FFT_SIZE/2)-1; } Ex[m].real = cos(ex_phase[0]*m - jitter*model->Wo*m + glottal[b]); Ex[m].imag = sin(ex_phase[0]*m - jitter*model->Wo*m + glottal[b]); } else { /* When a few samples were tested I found that LPC filter phase is not needed in the unvoiced case, but no harm in keeping it. */ float phi = TWO_PI*(float)rand()/RAND_MAX; Ex[m].real = cos(phi); Ex[m].imag = sin(phi); } /* filter using LPC filter */ A_[m].real = H[m].real*Ex[m].real - H[m].imag*Ex[m].imag; A_[m].imag = H[m].imag*Ex[m].real + H[m].real*Ex[m].imag; /* modify sinusoidal phase */ new_phi = atan2(A_[m].imag, A_[m].real+1E-12); model->phi[m] = new_phi; } } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/kiss_fft.h0000644000175000017500000000632411744612271021271 0ustar jcorganjcorgan#ifndef KISS_FFT_H #define KISS_FFT_H #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* ATTENTION! If you would like a : -- a utility that will handle the caching of fft objects -- real-only (no imaginary time component ) FFT -- a multi-dimensional FFT -- a command-line utility to perform ffts -- a command-line utility to perform fast-convolution filtering Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c in the tools/ directory. */ #ifdef USE_SIMD # include # define kiss_fft_scalar __m128 #define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) #define KISS_FFT_FREE _mm_free #else #define KISS_FFT_MALLOC malloc #define KISS_FFT_FREE free #endif #ifdef FIXED_POINT #include # if (FIXED_POINT == 32) # define kiss_fft_scalar int32_t # else # define kiss_fft_scalar int16_t # endif #else # ifndef kiss_fft_scalar /* default is float */ # define kiss_fft_scalar float # endif #endif typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; typedef struct kiss_fft_state* kiss_fft_cfg; /* * kiss_fft_alloc * * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. * * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); * * The return value from fft_alloc is a cfg buffer used internally * by the fft routine or NULL. * * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. * The returned value should be free()d when done to avoid memory leaks. * * The state can be placed in a user supplied buffer 'mem': * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, * then the function places the cfg in mem and the size used in *lenmem * and returns mem. * * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), * then the function returns NULL and places the minimum cfg * buffer size in *lenmem. * */ kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); /* * kiss_fft(cfg,in_out_buf) * * Perform an FFT on a complex input buffer. * for a forward FFT, * fin should be f[0] , f[1] , ... ,f[nfft-1] * fout will be F[0] , F[1] , ... ,F[nfft-1] * Note that each element is complex and can be accessed like f[k].r and f[k].i * */ void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); /* A more generic version of the above function. It reads its input from every Nth sample. * */ void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); /* If kiss_fft_alloc allocated a buffer, it is one contiguous buffer and can be simply free()d when no longer needed*/ #define kiss_fft_free free /* Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up your compiler output to call this before you exit. */ void kiss_fft_cleanup(void); /* * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) */ int kiss_fft_next_fast_size(int n); /* for real ffts, we need an even size */ #define kiss_fftr_next_fast_size_real(n) \ (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) #ifdef __cplusplus } #endif #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/lsp.h0000644000175000017500000000232611700377701020253 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: lsp.c AUTHOR......: David Rowe DATE CREATED: 24/2/93 This file contains functions for LPC to LSP conversion and LSP to LPC conversion. Note that the LSP coefficients are not in radians format but in the x domain of the unit circle. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __LSP__ #define __LSP__ int lpc_to_lsp (float *a, int lpcrdr, float *freq, int nb, float delta); void lsp_to_lpc(float *freq, float *ak, int lpcrdr); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/defines.h0000644000175000017500000000633611744612271021101 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: defines.h AUTHOR......: David Rowe DATE CREATED: 23/4/93 Defines and structures used throughout the codec. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __DEFINES__ #define __DEFINES__ /*---------------------------------------------------------------------------*\ DEFINES \*---------------------------------------------------------------------------*/ /* General defines */ #define N 80 /* number of samples per frame */ #define MAX_AMP 80 /* maximum number of harmonics */ #define PI 3.141592654 /* mathematical constant */ #define TWO_PI 6.283185307 /* mathematical constant */ #define FS 8000 /* sample rate in Hz */ #define MAX_STR 256 /* maximum string size */ #define NW 279 /* analysis window size */ #define FFT_ENC 512 /* size of FFT used for encoder */ #define FFT_DEC 512 /* size of FFT used in decoder */ #define TW 40 /* Trapezoidal synthesis window overlap */ #define V_THRESH 6.0 /* voicing threshold in dB */ #define LPC_MAX 20 /* maximum LPC order */ #define LPC_ORD 10 /* phase modelling LPC order */ /* Pitch estimation defines */ #define M 320 /* pitch analysis frame size */ #define P_MIN 20 /* minimum pitch */ #define P_MAX 160 /* maximum pitch */ /*---------------------------------------------------------------------------*\ TYPEDEFS \*---------------------------------------------------------------------------*/ /* Structure to hold model parameters for one frame */ typedef struct { float Wo; /* fundamental frequency estimate in radians */ int L; /* number of harmonics */ float A[MAX_AMP]; /* amplitiude of each harmonic */ float phi[MAX_AMP]; /* phase of each harmonic */ int voiced; /* non-zero if this frame is voiced */ } MODEL; /* describes each codebook */ struct lsp_codebook { int k; /* dimension of vector */ int log2m; /* number of bits in m */ int m; /* elements in codebook */ const float * cb; /* The elements */ }; extern const struct lsp_codebook lsp_cb[]; extern const struct lsp_codebook lsp_cbd[]; extern const struct lsp_codebook lsp_cbdvq[]; #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/phase.h0000644000175000017500000000203711744612271020556 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: phase.h AUTHOR......: David Rowe DATE CREATED: 1/2/09 Functions for modelling phase. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __PHASE__ #define __PHASE__ void phase_synth_zero_order(MODEL *model, float aks[], float *ex_phase, int order); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/lpc.h0000644000175000017500000000301111744612271020225 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: lpc.h AUTHOR......: David Rowe DATE CREATED: 24/8/09 Linear Prediction functions written in C. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __LPC__ #define __LPC__ #define LPC_MAX_ORDER 20 void hanning_window(float Sn[], float Wn[], int Nsam); void autocorrelate(float Sn[], float Rn[], int Nsam, int order); void autocorrelate_freq(float Pw[], float w[], float R[], int Nsam, int order); void levinson_durbin(float R[], float lpcs[], int order); void inverse_filter(float Sn[], float a[], int Nsam, float res[], int order); void synthesis_filter(float res[], float a[], int Nsam, int order, float Sn_[]); void find_aks(float Sn[], float a[], int Nsam, int order, float *E); void weight(float ak[], float gamma, int order, float akw[]); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/glottal.c0000644000175000017500000000630311700377701021115 0ustar jcorganjcorganconst float glottal[]={ 0.000000, -0.057687, -0.115338, -0.172917, -0.230385, -0.287707, -0.344845, -0.401762, -0.458419, -0.514781, -0.570809, -0.626467, -0.681721, -0.736537, -0.790884, -0.844733, -0.898057, -0.950834, -1.003044, -1.054670, -1.105700, -1.156124, -1.205936, -1.255132, -1.303711, -1.351675, -1.399026, -1.445769, -1.491908, -1.537448, -1.582393, -1.626747, -1.670514, -1.713693, -1.756285, -1.798288, -1.839697, -1.880507, -1.920712, -1.960302, -1.999269, -2.037603, -2.075295, -2.112335, -2.148716, -2.184430, -2.219472, -2.253839, -2.287531, -2.320550, -2.352900, -2.384588, -2.415623, -2.446019, -2.475788, -2.504946, -2.533512, -2.561501, -2.588934, -2.615827, -2.642198, -2.668064, -2.693439, -2.718337, -2.742767, -2.766738, -2.790256, -2.813322, -2.835936, -2.858094, -2.879790, -2.901016, -2.921759, -2.942008, -2.961747, -2.980961, -2.999632, -3.017745, -3.035282, -3.052228, -3.068567, -3.084285, -3.099371, -3.113813, -3.127605, -3.140738, 3.129975, 3.118167, 3.107022, 3.096537, 3.086709, 3.077531, 3.068996, 3.061096, 3.053821, 3.047159, 3.041102, 3.035636, 3.030753, 3.026441, 3.022690, 3.019491, 3.016836, 3.014718, 3.013132, 3.012072, 3.011535, 3.011521, 3.012028, 3.013057, 3.014612, 3.016695, 3.019310, 3.022463, 3.026160, 3.030407, 3.035212, 3.040580, 3.046520, 3.053038, 3.060141, 3.067836, 3.076128, 3.085023, 3.094525, 3.104639, 3.115367, 3.126712, 3.138674, -3.131930, -3.118731, -3.104915, -3.090485, -3.075444, -3.059795, -3.043543, -3.026695, -3.009254, -2.991229, -2.972625, -2.953449, -2.933710, -2.913414, -2.892567, -2.871176, -2.849248, -2.826787, -2.803798, -2.780284, -2.756247, -2.731689, -2.706609, -2.681005, -2.654875, -2.628213, -2.601015, -2.573272, -2.544977, -2.516121, -2.486694, -2.456686, -2.426084, -2.394879, -2.363060, -2.330616, -2.297538, -2.263816, -2.229444, -2.194416, -2.158727, -2.122375, -2.085359, -2.047682, -2.009347, -1.970361, -1.930732, -1.890470, -1.849587, -1.808098, -1.766017, -1.723360, -1.680145, -1.636388, -1.592105, -1.547313, -1.502025, -1.456256, -1.410016, -1.363314, -1.316157, -1.268547, -1.220486, -1.171971, -1.122997, -1.073555, -1.023636, -0.973227, -0.922312, -0.870875, -0.818899, -0.766366, -0.713257, -0.659554, -0.605242, -0.550303, -0.494723, -0.438492, -0.381598, -0.324036, -0.265800, -0.206889, -0.147303, -0.087046, -0.026121, 0.035463, 0.097698, 0.160576, 0.224087, 0.288221, 0.352969, 0.418323, 0.484276, 0.550822, 0.617958, 0.685681, 0.753991, 0.822889, 0.892378, 0.962462, 1.033144, 1.104430, 1.176325, 1.248833, 1.321956, 1.395696, 1.470051, 1.545019, 1.620593, 1.696763, 1.773516, 1.850837, 1.928705, 2.007097, 2.085987, 2.165347, 2.245145, 2.325347, 2.405919, 2.486824, 2.568025, 2.649485, 2.731167, 2.813033, 2.895045, 2.977167, 3.059362}; gnuradio-3.7.2.1/gr-vocoder/lib/codec2/nlp.c0000644000175000017500000002337411744612271020251 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: nlp.c AUTHOR......: David Rowe DATE CREATED: 23/3/93 Non Linear Pitch (NLP) estimation functions. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include "defines.h" #include "nlp.h" #include "dump.h" #include "fft.h" #include #include #include /*---------------------------------------------------------------------------*\ DEFINES \*---------------------------------------------------------------------------*/ #define PMAX_M 600 /* maximum NLP analysis window size */ #define COEFF 0.95 /* notch filter parameter */ #define PE_FFT_SIZE 512 /* DFT size for pitch estimation */ #define DEC 5 /* decimation factor */ #define SAMPLE_RATE 8000 #define PI 3.141592654 /* mathematical constant */ #define T 0.1 /* threshold for local minima candidate */ #define F0_MAX 500 #define CNLP 0.3 /* post processor constant */ #define NLP_NTAP 48 /* Decimation LPF order */ /*---------------------------------------------------------------------------*\ GLOBALS \*---------------------------------------------------------------------------*/ /* 48 tap 600Hz low pass FIR filter coefficients */ const float nlp_fir[] = { -1.0818124e-03, -1.1008344e-03, -9.2768838e-04, -4.2289438e-04, 5.5034190e-04, 2.0029849e-03, 3.7058509e-03, 5.1449415e-03, 5.5924666e-03, 4.3036754e-03, 8.0284511e-04, -4.8204610e-03, -1.1705810e-02, -1.8199275e-02, -2.2065282e-02, -2.0920610e-02, -1.2808831e-02, 3.2204775e-03, 2.6683811e-02, 5.5520624e-02, 8.6305944e-02, 1.1480192e-01, 1.3674206e-01, 1.4867556e-01, 1.4867556e-01, 1.3674206e-01, 1.1480192e-01, 8.6305944e-02, 5.5520624e-02, 2.6683811e-02, 3.2204775e-03, -1.2808831e-02, -2.0920610e-02, -2.2065282e-02, -1.8199275e-02, -1.1705810e-02, -4.8204610e-03, 8.0284511e-04, 4.3036754e-03, 5.5924666e-03, 5.1449415e-03, 3.7058509e-03, 2.0029849e-03, 5.5034190e-04, -4.2289438e-04, -9.2768838e-04, -1.1008344e-03, -1.0818124e-03 }; typedef struct { float sq[PMAX_M]; /* squared speech samples */ float mem_x,mem_y; /* memory for notch filter */ float mem_fir[NLP_NTAP]; /* decimation FIR filter memory */ } NLP; float post_process_mbe(COMP Fw[], int pmin, int pmax, float gmax); float post_process_sub_multiples(COMP Fw[], int pmin, int pmax, float gmax, int gmax_bin, float *prev_Wo); /*---------------------------------------------------------------------------*\ nlp_create() Initialisation function for NLP pitch estimator. \*---------------------------------------------------------------------------*/ void *nlp_create() { NLP *nlp; int i; nlp = (NLP*)malloc(sizeof(NLP)); if (nlp == NULL) return NULL; for(i=0; isq[i] = 0.0; nlp->mem_x = 0.0; nlp->mem_y = 0.0; for(i=0; imem_fir[i] = 0.0; return (void*)nlp; } /*---------------------------------------------------------------------------*\ nlp_destory() Initialisation function for NLP pitch estimator. \*---------------------------------------------------------------------------*/ void nlp_destroy(void *nlp_state) { assert(nlp_state != NULL); free(nlp_state); } /*---------------------------------------------------------------------------*\ nlp() Determines the pitch in samples using the Non Linear Pitch (NLP) algorithm [1]. Returns the fundamental in Hz. Note that the actual pitch estimate is for the centre of the M sample Sn[] vector, not the current N sample input vector. This is (I think) a delay of 2.5 frames with N=80 samples. You should align further analysis using this pitch estimate to be centred on the middle of Sn[]. Two post processors have been tried, the MBE version (as discussed in [1]), and a post processor that checks sub-multiples. Both suffer occasional gross pitch errors (i.e. neither are perfect). In the presence of background noise the sub-multiple algorithm tends towards low F0 which leads to better sounding background noise than the MBE post processor. A good way to test and develop the NLP pitch estimator is using the tnlp (codec2/unittest) and the codec2/octave/plnlp.m Octave script. A pitch tracker searching a few frames forward and backward in time would be a useful addition. References: [1] http://www.itr.unisa.edu.au/~steven/thesis/dgr.pdf Chapter 4 \*---------------------------------------------------------------------------*/ float nlp( void *nlp_state, float Sn[], /* input speech vector */ int n, /* frames shift (no. new samples in Sn[]) */ int m, /* analysis window size */ int pmin, /* minimum pitch value */ int pmax, /* maximum pitch value */ float *pitch, /* estimated pitch period in samples */ COMP Sw[], /* Freq domain version of Sn[] */ float *prev_Wo ) { NLP *nlp; float notch; /* current notch filter output */ COMP Fw[PE_FFT_SIZE]; /* DFT of squared signal */ float gmax; int gmax_bin; int i,j; float best_f0; assert(nlp_state != NULL); nlp = (NLP*)nlp_state; /* Square, notch filter at DC, and LP filter vector */ for(i=m-n; isq[i] = Sn[i]*Sn[i]; for(i=m-n; isq[i] - nlp->mem_x; notch += COEFF*nlp->mem_y; nlp->mem_x = nlp->sq[i]; nlp->mem_y = notch; nlp->sq[i] = notch; } for(i=m-n; imem_fir[j] = nlp->mem_fir[j+1]; nlp->mem_fir[NLP_NTAP-1] = nlp->sq[i]; nlp->sq[i] = 0.0; for(j=0; jsq[i] += nlp->mem_fir[j]*nlp_fir[j]; } /* Decimate and DFT */ for(i=0; isq[i*DEC]*(0.5 - 0.5*cos(2*PI*i/(m/DEC-1))); } #ifdef DUMP dump_dec(Fw); #endif fft(&Fw[0].real,PE_FFT_SIZE,1); for(i=0; isq); dump_Fw(Fw); #endif /* find global peak */ gmax = 0.0; gmax_bin = PE_FFT_SIZE*DEC/pmax; for(i=PE_FFT_SIZE*DEC/pmax; i<=PE_FFT_SIZE*DEC/pmin; i++) { if (Fw[i].real > gmax) { gmax = Fw[i].real; gmax_bin = i; } } best_f0 = post_process_sub_multiples(Fw, pmin, pmax, gmax, gmax_bin, prev_Wo); /* Shift samples in buffer to make room for new samples */ for(i=0; isq[i] = nlp->sq[i+n]; /* return pitch and F0 estimate */ *pitch = (float)SAMPLE_RATE/best_f0; return(best_f0); } /*---------------------------------------------------------------------------*\ post_process_sub_multiples() Given the global maximma of Fw[] we search interger submultiples for local maxima. If local maxima exist and they are above an experimentally derived threshold (OK a magic number I pulled out of the air) we choose the submultiple as the F0 estimate. The rational for this is that the lowest frequency peak of Fw[] should be F0, as Fw[] can be considered the autocorrelation function of Sw[] (the speech spectrum). However sometimes due to phase effects the lowest frequency maxima may not be the global maxima. This works OK in practice and favours low F0 values in the presence of background noise which means the sinusoidal codec does an OK job of synthesising the background noise. High F0 in background noise tends to sound more periodic introducing annoying artifacts. \*---------------------------------------------------------------------------*/ float post_process_sub_multiples(COMP Fw[], int pmin, int pmax, float gmax, int gmax_bin, float *prev_Wo) { int min_bin, cmax_bin; int mult; float thresh, best_f0; int b, bmin, bmax, lmax_bin; float lmax, cmax; int prev_f0_bin; /* post process estimate by searching submultiples */ mult = 2; min_bin = PE_FFT_SIZE*DEC/pmax; cmax_bin = gmax_bin; prev_f0_bin = *prev_Wo*(4000.0/PI)*(PE_FFT_SIZE*DEC)/SAMPLE_RATE; while(gmax_bin/mult >= min_bin) { b = gmax_bin/mult; /* determine search interval */ bmin = 0.8*b; bmax = 1.2*b; if (bmin < min_bin) bmin = min_bin; /* lower threshold to favour previous frames pitch estimate, this is a form of pitch tracking */ if ((prev_f0_bin > bmin) && (prev_f0_bin < bmax)) thresh = CNLP*0.5*gmax; else thresh = CNLP*gmax; lmax = 0; lmax_bin = bmin; for (b=bmin; b<=bmax; b++) /* look for maximum in interval */ if (Fw[b].real > lmax) { lmax = Fw[b].real; lmax_bin = b; } if (lmax > thresh) if ((lmax > Fw[lmax_bin-1].real) && (lmax > Fw[lmax_bin+1].real)) { cmax = lmax; cmax_bin = lmax_bin; } mult++; } best_f0 = (float)cmax_bin*SAMPLE_RATE/(PE_FFT_SIZE*DEC); return best_f0; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/c2enc.c0000644000175000017500000000440111744612271020440 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: c2enc.c AUTHOR......: David Rowe DATE CREATED: 23/8/2010 Encodes a file of raw speech samples using codec2 and outputs a file of bits. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2010 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include "codec2.h" #include #include #include #include #define BITS_SIZE ((CODEC2_BITS_PER_FRAME + 7) / 8) int main(int argc, char *argv[]) { void *codec2; FILE *fin; FILE *fout; short buf[CODEC2_SAMPLES_PER_FRAME]; unsigned char bits[BITS_SIZE]; if (argc != 3) { printf("usage: %s InputRawspeechFile OutputBitFile\n", argv[0]); exit(1); } if (strcmp(argv[1], "-") == 0) fin = stdin; else if ( (fin = fopen(argv[1],"rb")) == NULL ) { fprintf(stderr, "Error opening input bit file: %s: %s.\n", argv[1], strerror(errno)); exit(1); } if (strcmp(argv[2], "-") == 0) fout = stdout; else if ( (fout = fopen(argv[2],"wb")) == NULL ) { fprintf(stderr, "Error opening output speech file: %s: %s.\n", argv[2], strerror(errno)); exit(1); } codec2 = codec2_create(); while(fread(buf, sizeof(short), CODEC2_SAMPLES_PER_FRAME, fin) == CODEC2_SAMPLES_PER_FRAME) { codec2_encode(codec2, bits, buf); fwrite(bits, sizeof(char), BITS_SIZE, fout); //if this is in a pipeline, we probably don't want the usual //buffering to occur if (fout == stdout) fflush(stdout); if (fin == stdin) fflush(stdin); } codec2_destroy(codec2); fclose(fin); fclose(fout); return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/quantise.h0000644000175000017500000000457211744612271021315 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: quantise.h AUTHOR......: David Rowe DATE CREATED: 31/5/92 Quantisation functions for the sinusoidal coder. \*---------------------------------------------------------------------------*/ /* All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __QUANTISE__ #define __QUANTISE__ #define WO_BITS 7 #define WO_LEVELS (1< This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "defines.h" #include "quantise.h" #include /* Compile-time constants */ /* Size of unsigned char in bits. Assumes 8 bits-per-char. */ static const unsigned int WordSize = 8; /* Mask to pick the bit component out of bitIndex. */ static const unsigned int IndexMask = 0x7; /* Used to pick the word component out of bitIndex. */ static const unsigned int ShiftRight = 3; /** Pack a bit field into a bit string, encoding the field in Gray code. * * The output is an array of unsigned char data. The fields are efficiently * packed into the bit string. The Gray coding is a naive attempt to reduce * the effect of single-bit errors, we expect to do a better job as the * codec develops. * * This code would be simpler if it just set one bit at a time in the string, * but would hit the same cache line more often. I'm not sure the complexity * gains us anything here. * * Although field is currently of int type rather than unsigned for * compatibility with the rest of the code, indices are always expected to * be >= 0. */ void pack( unsigned char * bitArray, /* The output bit string. */ unsigned int * bitIndex, /* Index into the string in BITS, not bytes.*/ int field, /* The bit field to be packed. */ unsigned int fieldWidth/* Width of the field in BITS, not bytes. */ ) { /* Convert the field to Gray code */ field = (field >> 1) ^ field; do { unsigned int bI = *bitIndex; unsigned int bitsLeft = WordSize - (bI & IndexMask); unsigned int sliceWidth = bitsLeft < fieldWidth ? bitsLeft : fieldWidth; unsigned int wordIndex = bI >> ShiftRight; bitArray[wordIndex] |= ((unsigned char)((field >> (fieldWidth - sliceWidth)) << (bitsLeft - sliceWidth))); *bitIndex = bI + sliceWidth; fieldWidth -= sliceWidth; } while ( fieldWidth != 0 ); } /** Unpack a field from a bit string, converting from Gray code to binary. * */ int unpack( const unsigned char * bitArray, /* The input bit string. */ unsigned int * bitIndex, /* Index into the string in BITS, not bytes.*/ unsigned int fieldWidth/* Width of the field in BITS, not bytes. */ ) { unsigned int field = 0; unsigned int t; do { unsigned int bI = *bitIndex; unsigned int bitsLeft = WordSize - (bI & IndexMask); unsigned int sliceWidth = bitsLeft < fieldWidth ? bitsLeft : fieldWidth; field |= (((bitArray[bI >> ShiftRight] >> (bitsLeft - sliceWidth)) & ((1 << sliceWidth) - 1)) << (fieldWidth - sliceWidth)); *bitIndex = bI + sliceWidth; fieldWidth -= sliceWidth; } while ( fieldWidth != 0 ); /* Convert from Gray code to binary. Works for maximum 8-bit fields. */ t = field ^ (field >> 8); t ^= (t >> 4); t ^= (t >> 2); t ^= (t >> 1); return t; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/nlp.h0000644000175000017500000000231011744612271020241 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: nlp.c AUTHOR......: David Rowe DATE CREATED: 23/3/93 Non Linear Pitch (NLP) estimation functions. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __NLP__ #define __NLP__ #include "comp.h" void *nlp_create(); void nlp_destroy(void *nlp_state); float nlp(void *nlp_state, float Sn[], int n, int m, int pmin, int pmax, float *pitch, COMP Sw[], float *prev_Wo); float test_candidate_mbe(COMP Sw[], float f0, COMP Sw_[]); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codec2.h0000644000175000017500000000254111744612271020615 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: codec2.h AUTHOR......: David Rowe DATE CREATED: 21/8/2010 Codec2 fully quantised encoder and decoder functions. If you want use codec2, these are the functions you need to call. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2010 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __CODEC2__ #define __CODEC2__ #define CODEC2_SAMPLES_PER_FRAME 160 #define CODEC2_BITS_PER_FRAME 50 void *codec2_create(); void codec2_destroy(void *codec2_state); void codec2_encode(void *codec2_state, unsigned char * bits, short speech_in[]); void codec2_decode(void *codec2_state, short speech_out[], const unsigned char * bits); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/globals.h0000644000175000017500000000317111744612271021101 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: globals.h AUTHOR......: David Rowe DATE CREATED: 1/11/94 Globals for sinusoidal speech coder. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ /* Globals used in encoder and decoder */ extern int frames; /* number of frames processed so far */ extern float Sn[]; /* float input speech samples */ extern MODEL model; /* model parameters for the current frame */ extern int Nw; /* number of samples in analysis window */ extern float sig; /* energy of current frame */ /* Globals used in encoder */ extern float w[]; /* time domain hamming window */ extern COMP W[]; /* frequency domain hamming window */ extern COMP Sw[]; /* DFT of current frame */ extern COMP Sw_[]; /* DFT of all voiced synthesised signal */ /* Globals used in decoder */ extern float Sn_[]; /* output synthesised speech samples */ extern float Pn[]; /* time domain Parzen (trapezoidal) window */ gnuradio-3.7.2.1/gr-vocoder/lib/codec2/kiss_fft.c0000644000175000017500000003055211744612271021264 0ustar jcorganjcorgan/* Copyright (c) 2003-2010, Mark Borgerding All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "_kiss_fft_guts.h" /* The guts header contains all the multiplication and addition macros that are defined for fixed or floating point complex numbers. It also delares the kf_ internal functions. */ static void kf_bfly2( kiss_fft_cpx * Fout, const size_t fstride, const kiss_fft_cfg st, int m ) { kiss_fft_cpx * Fout2; kiss_fft_cpx * tw1 = st->twiddles; kiss_fft_cpx t; Fout2 = Fout + m; do{ C_FIXDIV(*Fout,2); C_FIXDIV(*Fout2,2); C_MUL (t, *Fout2 , *tw1); tw1 += fstride; C_SUB( *Fout2 , *Fout , t ); C_ADDTO( *Fout , t ); ++Fout2; ++Fout; }while (--m); } static void kf_bfly4( kiss_fft_cpx * Fout, const size_t fstride, const kiss_fft_cfg st, const size_t m ) { kiss_fft_cpx *tw1,*tw2,*tw3; kiss_fft_cpx scratch[6]; size_t k=m; const size_t m2=2*m; const size_t m3=3*m; tw3 = tw2 = tw1 = st->twiddles; do { C_FIXDIV(*Fout,4); C_FIXDIV(Fout[m],4); C_FIXDIV(Fout[m2],4); C_FIXDIV(Fout[m3],4); C_MUL(scratch[0],Fout[m] , *tw1 ); C_MUL(scratch[1],Fout[m2] , *tw2 ); C_MUL(scratch[2],Fout[m3] , *tw3 ); C_SUB( scratch[5] , *Fout, scratch[1] ); C_ADDTO(*Fout, scratch[1]); C_ADD( scratch[3] , scratch[0] , scratch[2] ); C_SUB( scratch[4] , scratch[0] , scratch[2] ); C_SUB( Fout[m2], *Fout, scratch[3] ); tw1 += fstride; tw2 += fstride*2; tw3 += fstride*3; C_ADDTO( *Fout , scratch[3] ); if(st->inverse) { Fout[m].r = scratch[5].r - scratch[4].i; Fout[m].i = scratch[5].i + scratch[4].r; Fout[m3].r = scratch[5].r + scratch[4].i; Fout[m3].i = scratch[5].i - scratch[4].r; }else{ Fout[m].r = scratch[5].r + scratch[4].i; Fout[m].i = scratch[5].i - scratch[4].r; Fout[m3].r = scratch[5].r - scratch[4].i; Fout[m3].i = scratch[5].i + scratch[4].r; } ++Fout; }while(--k); } static void kf_bfly3( kiss_fft_cpx * Fout, const size_t fstride, const kiss_fft_cfg st, size_t m ) { size_t k=m; const size_t m2 = 2*m; kiss_fft_cpx *tw1,*tw2; kiss_fft_cpx scratch[5]; kiss_fft_cpx epi3; epi3 = st->twiddles[fstride*m]; tw1=tw2=st->twiddles; do{ C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3); C_MUL(scratch[1],Fout[m] , *tw1); C_MUL(scratch[2],Fout[m2] , *tw2); C_ADD(scratch[3],scratch[1],scratch[2]); C_SUB(scratch[0],scratch[1],scratch[2]); tw1 += fstride; tw2 += fstride*2; Fout[m].r = Fout->r - HALF_OF(scratch[3].r); Fout[m].i = Fout->i - HALF_OF(scratch[3].i); C_MULBYSCALAR( scratch[0] , epi3.i ); C_ADDTO(*Fout,scratch[3]); Fout[m2].r = Fout[m].r + scratch[0].i; Fout[m2].i = Fout[m].i - scratch[0].r; Fout[m].r -= scratch[0].i; Fout[m].i += scratch[0].r; ++Fout; }while(--k); } static void kf_bfly5( kiss_fft_cpx * Fout, const size_t fstride, const kiss_fft_cfg st, int m ) { kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; int u; kiss_fft_cpx scratch[13]; kiss_fft_cpx * twiddles = st->twiddles; kiss_fft_cpx *tw; kiss_fft_cpx ya,yb; ya = twiddles[fstride*m]; yb = twiddles[fstride*2*m]; Fout0=Fout; Fout1=Fout0+m; Fout2=Fout0+2*m; Fout3=Fout0+3*m; Fout4=Fout0+4*m; tw=st->twiddles; for ( u=0; ur += scratch[7].r + scratch[8].r; Fout0->i += scratch[7].i + scratch[8].i; scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r); scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r); scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i); scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i); C_SUB(*Fout1,scratch[5],scratch[6]); C_ADD(*Fout4,scratch[5],scratch[6]); scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r); scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r); scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i); scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i); C_ADD(*Fout2,scratch[11],scratch[12]); C_SUB(*Fout3,scratch[11],scratch[12]); ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; } } /* perform the butterfly for one stage of a mixed radix FFT */ static void kf_bfly_generic( kiss_fft_cpx * Fout, const size_t fstride, const kiss_fft_cfg st, int m, int p ) { int u,k,q1,q; kiss_fft_cpx * twiddles = st->twiddles; kiss_fft_cpx t; int Norig = st->nfft; kiss_fft_cpx * scratch = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC(sizeof(kiss_fft_cpx)*p); for ( u=0; u=Norig) twidx-=Norig; C_MUL(t,scratch[q] , twiddles[twidx] ); C_ADDTO( Fout[ k ] ,t); } k += m; } } KISS_FFT_TMP_FREE(scratch); } static void kf_work( kiss_fft_cpx * Fout, const kiss_fft_cpx * f, const size_t fstride, int in_stride, int * factors, const kiss_fft_cfg st ) { kiss_fft_cpx * Fout_beg=Fout; const int p=*factors++; /* the radix */ const int m=*factors++; /* stage's fft length/p */ const kiss_fft_cpx * Fout_end = Fout + p*m; #ifdef _OPENMP // use openmp extensions at the // top-level (not recursive) if (fstride==1 && p<=5) { int k; // execute the p different work units in different threads # pragma omp parallel for for (k=0;k floor_sqrt) p = n; /* no more factors, skip to end */ } n /= p; *facbuf++ = p; *facbuf++ = n; } while (n > 1); } /* * * User-callable function to allocate all necessary storage space for the fft. * * The return value is a contiguous block of memory, allocated with malloc. As such, * It can be freed with free(), rather than a kiss_fft-specific function. * */ kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem ) { kiss_fft_cfg st=NULL; size_t memneeded = sizeof(struct kiss_fft_state) + sizeof(kiss_fft_cpx)*(nfft-1); /* twiddle factors*/ if ( lenmem==NULL ) { st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded ); }else{ if (mem != NULL && *lenmem >= memneeded) st = (kiss_fft_cfg)mem; *lenmem = memneeded; } if (st) { int i; st->nfft=nfft; st->inverse = inverse_fft; for (i=0;iinverse) phase *= -1; kf_cexp(st->twiddles+i, phase ); } kf_factor(nfft,st->factors); } return st; } void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride) { if (fin == fout) { //NOTE: this is not really an in-place FFT algorithm. //It just performs an out-of-place FFT into a temp buffer kiss_fft_cpx * tmpbuf = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC( sizeof(kiss_fft_cpx)*st->nfft); kf_work(tmpbuf,fin,1,in_stride, st->factors,st); memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); KISS_FFT_TMP_FREE(tmpbuf); }else{ kf_work( fout, fin, 1,in_stride, st->factors,st ); } } void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout) { kiss_fft_stride(cfg,fin,fout,1); } void kiss_fft_cleanup(void) { // nothing needed any more } int kiss_fft_next_fast_size(int n) { while(1) { int m=n; while ( (m%2) == 0 ) m/=2; while ( (m%3) == 0 ) m/=3; while ( (m%5) == 0 ) m/=5; if (m<=1) break; /* n is completely factorable by twos, threes, and fives */ n++; } return n; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/quantise.c0000664000175000017500000005057512224351213021304 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: quantise.c AUTHOR......: David Rowe DATE CREATED: 31/5/92 Quantisation functions for the sinusoidal coder. \*---------------------------------------------------------------------------*/ /* All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include #include #include #include #include #include "defines.h" #include "dump.h" #include "quantise.h" #include "lpc.h" #include "lsp.h" #include "fft.h" #define LSP_DELTA1 0.01 /* grid spacing for LSP root searches */ /*---------------------------------------------------------------------------*\ FUNCTION HEADERS \*---------------------------------------------------------------------------*/ float speech_to_uq_lsps(float lsp[], float ak[], float Sn[], float w[], int order); /*---------------------------------------------------------------------------*\ FUNCTIONS \*---------------------------------------------------------------------------*/ int lsp_bits(int i) { return lsp_cb[i].log2m; } #if VECTOR_QUANTISATION /*---------------------------------------------------------------------------*\ quantise_uniform Simulates uniform quantising of a float. \*---------------------------------------------------------------------------*/ void quantise_uniform(float *val, float min, float max, int bits) { int levels = 1 << (bits-1); float norm; int index; /* hard limit to quantiser range */ printf("min: %f max: %f val: %f ", min, max, val[0]); if (val[0] < min) val[0] = min; if (val[0] > max) val[0] = max; norm = (*val - min)/(max-min); printf("%f norm: %f ", val[0], norm); index = fabs(levels*norm + 0.5); *val = min + index*(max-min)/levels; printf("index %d val_: %f\n", index, val[0]); } #endif /*---------------------------------------------------------------------------*\ quantise_init Loads the entire LSP quantiser comprised of several vector quantisers (codebooks). \*---------------------------------------------------------------------------*/ void quantise_init() { } /*---------------------------------------------------------------------------*\ quantise Quantises vec by choosing the nearest vector in codebook cb, and returns the vector index. The squared error of the quantised vector is added to se. \*---------------------------------------------------------------------------*/ long quantise(const float * cb, float vec[], float w[], int k, int m, float *se) /* float cb[][K]; current VQ codebook */ /* float vec[]; vector to quantise */ /* float w[]; weighting vector */ /* int k; dimension of vectors */ /* int m; size of codebook */ /* float *se; accumulated squared error */ { float e; /* current error */ long besti; /* best index so far */ float beste; /* best error so far */ long j; int i; besti = 0; beste = 1E32; for(j=0; j {Am} LPC decode */ return snr; } /*---------------------------------------------------------------------------*\ aks_to_M2() Transforms the linear prediction coefficients to spectral amplitude samples. This function determines A(m) from the average energy per band using an FFT. \*---------------------------------------------------------------------------*/ void aks_to_M2( float ak[], /* LPC's */ int order, MODEL *model, /* sinusoidal model parameters for this frame */ float E, /* energy term */ float *snr, /* signal to noise ratio for this frame in dB */ int dump /* true to dump sample to dump file */ ) { COMP Pw[FFT_DEC]; /* power spectrum */ int i,m; /* loop variables */ int am,bm; /* limits of current band */ float r; /* no. rads/bin */ float Em; /* energy in band */ float Am; /* spectral amplitude sample */ float signal, noise; r = TWO_PI/(FFT_DEC); /* Determine DFT of A(exp(jw)) --------------------------------------------*/ for(i=0; iL; m++) { am = floor((m - 0.5)*model->Wo/r + 0.5); bm = floor((m + 0.5)*model->Wo/r + 0.5); Em = 0.0; for(i=am; iA[m],2.0); noise += pow(model->A[m] - Am,2.0); model->A[m] = Am; } *snr = 10.0*log10(signal/noise); } /*---------------------------------------------------------------------------*\ FUNCTION....: encode_Wo() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Encodes Wo using a WO_LEVELS quantiser. \*---------------------------------------------------------------------------*/ int encode_Wo(float Wo) { int index; float Wo_min = TWO_PI/P_MAX; float Wo_max = TWO_PI/P_MIN; float norm; norm = (Wo - Wo_min)/(Wo_max - Wo_min); index = floor(WO_LEVELS * norm + 0.5); if (index < 0 ) index = 0; if (index > (WO_LEVELS-1)) index = WO_LEVELS-1; return index; } /*---------------------------------------------------------------------------*\ FUNCTION....: decode_Wo() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Decodes Wo using a WO_LEVELS quantiser. \*---------------------------------------------------------------------------*/ float decode_Wo(int index) { float Wo_min = TWO_PI/P_MAX; float Wo_max = TWO_PI/P_MIN; float step; float Wo; step = (Wo_max - Wo_min)/WO_LEVELS; Wo = Wo_min + step*(index); return Wo; } /*---------------------------------------------------------------------------*\ FUNCTION....: speech_to_uq_lsps() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Analyse a windowed frame of time domain speech to determine LPCs which are the converted to LSPs for quantisation and transmission over the channel. \*---------------------------------------------------------------------------*/ float speech_to_uq_lsps(float lsp[], float ak[], float Sn[], float w[], int order ) { int i, roots; float Wn[M]; float R[LPC_MAX+1]; float E; for(i=0; iWo < (PI*150.0/4000)) { model->A[1] *= 0.032; } } /*---------------------------------------------------------------------------*\ FUNCTION....: encode_energy() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Encodes LPC energy using an E_LEVELS quantiser. \*---------------------------------------------------------------------------*/ int encode_energy(float e) { int index; float e_min = E_MIN_DB; float e_max = E_MAX_DB; float norm; e = 10.0*log10(e); norm = (e - e_min)/(e_max - e_min); index = floor(E_LEVELS * norm + 0.5); if (index < 0 ) index = 0; if (index > (E_LEVELS-1)) index = E_LEVELS-1; return index; } /*---------------------------------------------------------------------------*\ FUNCTION....: decode_energy() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Decodes energy using a WO_BITS quantiser. \*---------------------------------------------------------------------------*/ float decode_energy(int index) { float e_min = E_MIN_DB; float e_max = E_MAX_DB; float step; float e; step = (e_max - e_min)/E_LEVELS; e = e_min + step*(index); e = pow(10.0,e/10.0); return e; } /*---------------------------------------------------------------------------*\ FUNCTION....: encode_amplitudes() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Time domain LPC is used model the amplitudes which are then converted to LSPs and quantised. So we don't actually encode the amplitudes directly, rather we derive an equivalent representation from the time domain speech. \*---------------------------------------------------------------------------*/ void encode_amplitudes(int lsp_indexes[], int *energy_index, MODEL *model, float Sn[], float w[]) { float lsps[LPC_ORD]; float ak[LPC_ORD+1]; float e; e = speech_to_uq_lsps(lsps, ak, Sn, w, LPC_ORD); encode_lsps(lsp_indexes, lsps, LPC_ORD); *energy_index = encode_energy(e); } /*---------------------------------------------------------------------------*\ FUNCTION....: decode_amplitudes() AUTHOR......: David Rowe DATE CREATED: 22/8/2010 Given the amplitude quantiser indexes recovers the harmonic amplitudes. \*---------------------------------------------------------------------------*/ float decode_amplitudes(MODEL *model, float ak[], int lsp_indexes[], int energy_index, float lsps[], float *e ) { float snr; decode_lsps(lsps, lsp_indexes, LPC_ORD); bw_expand_lsps(lsps, LPC_ORD); lsp_to_lpc(lsps, ak, LPC_ORD); *e = decode_energy(energy_index); aks_to_M2(ak, LPC_ORD, model, *e, &snr, 1); apply_lpc_correction(model); return snr; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/dump.c0000644000175000017500000002155411744612271020423 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: dump.c AUTHOR......: David Rowe DATE CREATED: 25/8/09 Routines to dump data to text files for Octave analysis. \*---------------------------------------------------------------------------*/ /* All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include "defines.h" #include "comp.h" #include "dump.h" #include #include #include #include #include #ifdef DUMP static int dumpon = 0; static FILE *fsn = NULL; static FILE *fsw = NULL; static FILE *few = NULL; static FILE *fsw_ = NULL; static FILE *fmodel = NULL; static FILE *fqmodel = NULL; static FILE *fpw = NULL; static FILE *flsp = NULL; static FILE *fphase = NULL; static FILE *fphase_ = NULL; static FILE *ffw = NULL; static FILE *fe = NULL; static FILE *fsq = NULL; static FILE *fdec = NULL; static FILE *fsnr = NULL; static FILE *fak = NULL; static FILE *fbg = NULL; static FILE *fE = NULL; static FILE *frk = NULL; static FILE *fres = NULL; static char prefix[MAX_STR]; void dump_on(char p[]) { dumpon = 1; strcpy(prefix, p); } void dump_off(){ if (fsn != NULL) fclose(fsn); if (fsw != NULL) fclose(fsw); if (fsw_ != NULL) fclose(fsw_); if (few != NULL) fclose(few); if (fmodel != NULL) fclose(fmodel); if (fqmodel != NULL) fclose(fqmodel); if (fpw != NULL) fclose(fpw); if (flsp != NULL) fclose(flsp); if (fphase != NULL) fclose(fphase); if (fphase_ != NULL) fclose(fphase_); if (ffw != NULL) fclose(ffw); if (fe != NULL) fclose(fe); if (fsq != NULL) fclose(fsq); if (fdec != NULL) fclose(fdec); if (fsnr != NULL) fclose(fsnr); if (fak != NULL) fclose(fak); if (fbg != NULL) fclose(fbg); if (fE != NULL) fclose(fE); if (frk != NULL) fclose(frk); if (fres != NULL) fclose(fres); } void dump_Sn(float Sn[]) { int i; char s[MAX_STR]; if (!dumpon) return; if (fsn == NULL) { sprintf(s,"%s_sn.txt", prefix); fsn = fopen(s, "wt"); assert(fsn != NULL); } /* split across two lines to avoid max line length problems */ /* reconstruct in Octave */ for(i=0; iWo, model->L); for(l=1; l<=model->L; l++) fprintf(fmodel,"%f\t",model->A[l]); for(l=model->L+1; lvoiced); fprintf(fmodel,"\n"); } void dump_quantised_model(MODEL *model) { int l; char s[MAX_STR]; if (!dumpon) return; if (fqmodel == NULL) { sprintf(s,"%s_qmodel.txt", prefix); fqmodel = fopen(s, "wt"); assert(fqmodel != NULL); } fprintf(fqmodel,"%f\t%d\t", model->Wo, model->L); for(l=1; l<=model->L; l++) fprintf(fqmodel,"%f\t",model->A[l]); for(l=model->L+1; l. */ #define LPC_MAX_N 512 /* maximum no. of samples in frame */ #define PI 3.141592654 /* mathematical constant */ #include #include #include "defines.h" #include "lpc.h" /*---------------------------------------------------------------------------*\ hanning_window() Hanning windows a frame of speech samples. \*---------------------------------------------------------------------------*/ void hanning_window( float Sn[], /* input frame of speech samples */ float Wn[], /* output frame of windowed samples */ int Nsam /* number of samples */ ) { int i; /* loop variable */ for(i=0; i 1.0) k[i] = 0.0; a[i][i] = k[i]; for(j=1; j<=i-1; j++) a[i][j] = a[i-1][j] + k[i]*a[i-1][i-j]; /* Equation 38c, Makhoul */ E[i] = (1-k[i]*k[i])*E[i-1]; /* Equation 38d, Makhoul */ } for(i=1; i<=order; i++) lpcs[i] = a[order][i]; lpcs[0] = 1.0; } /*---------------------------------------------------------------------------*\ inverse_filter() Inverse Filter, A(z). Produces an array of residual samples from an array of input samples and linear prediction coefficients. The filter memory is stored in the first order samples of the input array. \*---------------------------------------------------------------------------*/ void inverse_filter( float Sn[], /* Nsam input samples */ float a[], /* LPCs for this frame of samples */ int Nsam, /* number of samples */ float res[], /* Nsam residual samples */ int order /* order of LPC */ ) { int i,j; /* loop variables */ for(i=0; i #define MAXFACTORS 32 /* e.g. an fft of length 128 has 4 factors as far as kissfft is concerned 4*4*4*2 */ struct kiss_fft_state{ int nfft; int inverse; int factors[2*MAXFACTORS]; kiss_fft_cpx twiddles[1]; }; /* Explanation of macros dealing with complex math: C_MUL(m,a,b) : m = a*b C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise C_SUB( res, a,b) : res = a - b C_SUBFROM( res , a) : res -= a C_ADDTO( res , a) : res += a * */ #ifdef FIXED_POINT #if (FIXED_POINT==32) # define FRACBITS 31 # define SAMPPROD int64_t #define SAMP_MAX 2147483647 #else # define FRACBITS 15 # define SAMPPROD int32_t #define SAMP_MAX 32767 #endif #define SAMP_MIN -SAMP_MAX #if defined(CHECK_OVERFLOW) # define CHECK_OVERFLOW_OP(a,op,b) \ if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } #endif # define smul(a,b) ( (SAMPPROD)(a)*(b) ) # define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) # define S_MUL(a,b) sround( smul(a,b) ) # define C_MUL(m,a,b) \ do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) # define DIVSCALAR(x,k) \ (x) = sround( smul( x, SAMP_MAX/k ) ) # define C_FIXDIV(c,div) \ do { DIVSCALAR( (c).r , div); \ DIVSCALAR( (c).i , div); }while (0) # define C_MULBYSCALAR( c, s ) \ do{ (c).r = sround( smul( (c).r , s ) ) ;\ (c).i = sround( smul( (c).i , s ) ) ; }while(0) #else /* not FIXED_POINT*/ # define S_MUL(a,b) ( (a)*(b) ) #define C_MUL(m,a,b) \ do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) # define C_FIXDIV(c,div) /* NOOP */ # define C_MULBYSCALAR( c, s ) \ do{ (c).r *= (s);\ (c).i *= (s); }while(0) #endif #ifndef CHECK_OVERFLOW_OP # define CHECK_OVERFLOW_OP(a,op,b) /* noop */ #endif #define C_ADD( res, a,b)\ do { \ CHECK_OVERFLOW_OP((a).r,+,(b).r)\ CHECK_OVERFLOW_OP((a).i,+,(b).i)\ (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ }while(0) #define C_SUB( res, a,b)\ do { \ CHECK_OVERFLOW_OP((a).r,-,(b).r)\ CHECK_OVERFLOW_OP((a).i,-,(b).i)\ (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ }while(0) #define C_ADDTO( res , a)\ do { \ CHECK_OVERFLOW_OP((res).r,+,(a).r)\ CHECK_OVERFLOW_OP((res).i,+,(a).i)\ (res).r += (a).r; (res).i += (a).i;\ }while(0) #define C_SUBFROM( res , a)\ do {\ CHECK_OVERFLOW_OP((res).r,-,(a).r)\ CHECK_OVERFLOW_OP((res).i,-,(a).i)\ (res).r -= (a).r; (res).i -= (a).i; \ }while(0) #ifdef FIXED_POINT # define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) # define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) # define HALF_OF(x) ((x)>>1) #elif defined(USE_SIMD) # define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) # define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) # define HALF_OF(x) ((x)*_mm_set1_ps(.5)) #else # define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) # define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) # define HALF_OF(x) ((x)*.5) #endif #define kf_cexp(x,phase) \ do{ \ (x)->r = KISS_FFT_COS(phase);\ (x)->i = KISS_FFT_SIN(phase);\ }while(0) /* a debugging function */ #define pcpx(c)\ fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) #ifdef KISS_FFT_USE_ALLOCA // define this to allow use of alloca instead of malloc for temporary buffers // Temporary buffers are used in two case: // 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 // 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. #include #define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) #define KISS_FFT_TMP_FREE(ptr) #else #define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) #define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codec2.c0000644000175000017500000002214511744612271020612 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: codec2.c AUTHOR......: David Rowe DATE CREATED: 21/8/2010 Codec2 fully quantised encoder and decoder functions. If you want use codec2, the codec2_xxx functions are for you. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2010 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include #include #include #include #include "defines.h" #include "sine.h" #include "nlp.h" #include "dump.h" #include "lpc.h" #include "quantise.h" #include "phase.h" #include "interp.h" #include "postfilter.h" #include "codec2.h" #include "codec2_internal.h" /*---------------------------------------------------------------------------*\ FUNCTIONS \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ FUNCTION....: codec2_create AUTHOR......: David Rowe DATE CREATED: 21/8/2010 Create and initialise an instance of the codec. Returns a pointer to the codec states or NULL on failure. One set of states is sufficient for a full duuplex codec (i.e. an encoder and decoder). You don't need separate states for encoders and decoders. See c2enc.c and c2dec.c for examples. \*---------------------------------------------------------------------------*/ void *codec2_create() { CODEC2 *c2; int i,l; c2 = (CODEC2*)malloc(sizeof(CODEC2)); if (c2 == NULL) return NULL; for(i=0; iSn[i] = 1.0; c2->hpf_states[0] = c2->hpf_states[1] = 0.0; for(i=0; i<2*N; i++) c2->Sn_[i] = 0; make_analysis_window(c2->w,c2->W); make_synthesis_window(c2->Pn); quantise_init(); c2->prev_Wo = 0.0; c2->bg_est = 0.0; c2->ex_phase = 0.0; for(l=1; lprev_model.A[l] = 0.0; c2->prev_model.Wo = TWO_PI/P_MAX; c2->prev_model.L = PI/c2->prev_model.Wo; c2->prev_model.voiced = 0; for(i=0; iprev_lsps[i] = i*PI/(LPC_ORD+1); } c2->prev_energy = 1; c2->nlp = nlp_create(); if (c2->nlp == NULL) { free (c2); return NULL; } return (void*)c2; } /*---------------------------------------------------------------------------*\ FUNCTION....: codec2_create AUTHOR......: David Rowe DATE CREATED: 21/8/2010 Destroy an instance of the codec. \*---------------------------------------------------------------------------*/ void codec2_destroy(void *codec2_state) { CODEC2 *c2; assert(codec2_state != NULL); c2 = (CODEC2*)codec2_state; nlp_destroy(c2->nlp); free(codec2_state); } /*---------------------------------------------------------------------------*\ FUNCTION....: codec2_encode AUTHOR......: David Rowe DATE CREATED: 21/8/2010 Encodes 160 speech samples (20ms of speech) into 51 bits. The codec2 algorithm actually operates internally on 10ms (80 sample) frames, so we run the encoding algorithm twice. On the first frame we just send the voicing bit. One the second frame we send all model parameters. The bit allocation is: Parameter bits/frame -------------------------------------- Harmonic magnitudes (LSPs) 36 Low frequency LPC correction 1 Energy 5 Wo (fundamental frequnecy) 7 Voicing (10ms update) 2 TOTAL 51 \*---------------------------------------------------------------------------*/ void codec2_encode(void *codec2_state, unsigned char * bits, short speech[]) { CODEC2 *c2; MODEL model; int voiced1, voiced2; int lsp_indexes[LPC_ORD]; int energy_index; int Wo_index; int i; unsigned int nbit = 0; assert(codec2_state != NULL); c2 = (CODEC2*)codec2_state; /* first 10ms analysis frame - we just want voicing */ analyse_one_frame(c2, &model, speech); voiced1 = model.voiced; /* second 10ms analysis frame */ analyse_one_frame(c2, &model, &speech[N]); voiced2 = model.voiced; Wo_index = encode_Wo(model.Wo); encode_amplitudes(lsp_indexes, &energy_index, &model, c2->Sn, c2->w); memset(bits, '\0', ((CODEC2_BITS_PER_FRAME + 7) / 8)); pack(bits, &nbit, Wo_index, WO_BITS); for(i=0; iprev_model, &model, c2->prev_lsps, c2->prev_energy, lsps, energy, ak_interp); apply_lpc_correction(&model_interp); /* synthesis two 10ms frames */ synthesise_one_frame(c2, speech, &model_interp, ak_interp); synthesise_one_frame(c2, &speech[N], &model, ak); /* update memories (decode states) for next time */ memcpy(&c2->prev_model, &model, sizeof(MODEL)); memcpy(c2->prev_lsps, lsps, sizeof(lsps)); c2->prev_energy = energy; } /*---------------------------------------------------------------------------*\ FUNCTION....: synthesise_one_frame() AUTHOR......: David Rowe DATE CREATED: 23/8/2010 Synthesise 80 speech samples (10ms) from model parameters. \*---------------------------------------------------------------------------*/ void synthesise_one_frame(CODEC2 *c2, short speech[], MODEL *model, float ak[]) { int i; phase_synth_zero_order(model, ak, &c2->ex_phase, LPC_ORD); postfilter(model, &c2->bg_est); synthesise(c2->Sn_, model, c2->Pn, 1); for(i=0; iSn_[i] > 32767.0) speech[i] = 32767; else if (c2->Sn_[i] < -32767.0) speech[i] = -32767; else speech[i] = c2->Sn_[i]; } } /*---------------------------------------------------------------------------*\ FUNCTION....: analyse_one_frame() AUTHOR......: David Rowe DATE CREATED: 23/8/2010 Extract sinusoidal model parameters from 80 speech samples (10ms of speech). \*---------------------------------------------------------------------------*/ void analyse_one_frame(CODEC2 *c2, MODEL *model, short speech[]) { COMP Sw[FFT_ENC]; COMP Sw_[FFT_ENC]; COMP Ew[FFT_ENC]; float pitch; int i; /* Read input speech */ for(i=0; iSn[i] = c2->Sn[i+N]; for(i=0; iSn[i+M-N] = speech[i]; dft_speech(Sw, c2->Sn, c2->w); /* Estimate pitch */ nlp(c2->nlp,c2->Sn,N,M,P_MIN,P_MAX,&pitch,Sw,&c2->prev_Wo); model->Wo = TWO_PI/pitch; model->L = PI/model->Wo; /* estimate model parameters */ two_stage_pitch_refinement(model, Sw); estimate_amplitudes(model, Sw, c2->W); est_voicing_mbe(model, Sw, c2->W, Sw_, Ew, c2->prev_Wo); c2->prev_Wo = model->Wo; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/fft.c0000644000175000017500000000527011744612271020232 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: fft.c AUTHOR......: Bruce Robertson DATE CREATED: 20/11/2010 Bridging function to the kiss_fft package. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2010 Bruce Robertson All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include "kiss_fft.h" /*---------------------------------------------------------------------------*\ GLOBALS \*---------------------------------------------------------------------------*/ kiss_fft_cpx *fin; kiss_fft_cpx *fout; kiss_fft_cfg cfg_forward; kiss_fft_cfg cfg_reverse; /*---------------------------------------------------------------------------*\ initialize_fft(int n) Initialisation function for kiss_fft. This assumes that all calls to fft() use the same datatypes and are one arrays of the same size. \*---------------------------------------------------------------------------*/ void initialize_fft (int n) { fin = KISS_FFT_MALLOC (n * sizeof (kiss_fft_cpx)); assert(fin != NULL); fout = KISS_FFT_MALLOC (n * sizeof (kiss_fft_cpx)); assert(fout != NULL); cfg_forward = kiss_fft_alloc (n, 0, NULL, NULL); assert(cfg_forward != NULL); cfg_reverse = kiss_fft_alloc (n, 1, NULL, NULL); assert(cfg_reverse != NULL); } /*---------------------------------------------------------------------------*\ fft(float x[], int n, int isign) Function that calls kiss_fft with the signature of four1 from NRC. \*---------------------------------------------------------------------------*/ void fft (float x[], int n, int isign) { //int isReverse = 0; // never used int c; kiss_fft_cfg cfg; if (cfg_forward == NULL) { initialize_fft (n); } for (c = 0; c < n * 2; c += 2) { fin[c / 2].r = x[c]; fin[c / 2].i = -x[c + 1]; } if (isign == -1) { cfg = cfg_reverse; } else { cfg = cfg_forward; } kiss_fft (cfg, fin, fout); for (c = 0; c < n * 2; c += 2) { x[c] = fout[(c) / 2].r; x[c + 1] = -fout[(c) / 2].i; } } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/0000755000175000017500000000000011744612271021070 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp1.txt0000644000175000017500000000010511700377701022646 0ustar jcorganjcorgan1 16 225 250 275 300 325 350 375 400 425 450 475 500 525 550 575 600 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp8910.txt0000644000175000017500000000350511744612271022754 0ustar jcorganjcorgan3 64 2.048073 2.534502 2.645915 2.019670 2.269744 2.605462 1.961101 2.329646 2.562857 1.968573 2.532712 2.616918 2.183480 2.514381 2.629582 2.259379 2.516615 2.620410 2.172791 2.462460 2.567064 2.097666 2.303933 2.421685 2.052990 2.353242 2.546992 2.043642 2.232362 2.499262 2.106151 2.393131 2.488401 2.099167 2.437862 2.558655 2.013877 2.422875 2.530071 2.033848 2.483776 2.584598 2.114474 2.516856 2.602372 2.229214 2.584056 2.678855 2.131151 2.584299 2.674845 1.472721 2.477091 2.630241 2.010907 2.598415 2.682989 2.353653 2.524066 2.619773 2.419897 2.623938 2.699605 2.319080 2.602148 2.689044 1.860342 2.503881 2.616576 1.910517 2.386693 2.610126 1.748689 2.371809 2.496542 1.618495 2.403425 2.554956 1.844073 2.437026 2.533443 1.924810 2.388543 2.502698 1.937227 2.258363 2.501697 1.687554 2.209123 2.545239 1.851950 2.278628 2.565632 1.868154 2.330150 2.444883 1.874180 2.213118 2.351940 1.757311 2.030626 2.433836 1.650306 2.152371 2.243421 1.612794 1.884686 2.339313 1.745431 2.278895 2.389449 1.590923 2.304155 2.408510 1.475982 2.275548 2.509897 1.508695 2.045463 2.455520 1.872054 2.061777 2.246202 1.983947 2.159155 2.445535 1.745180 2.483765 2.593698 1.900116 2.079600 2.407479 1.841672 2.167042 2.486827 1.932912 2.148464 2.569850 2.134174 2.363673 2.584252 2.106094 2.450645 2.638417 1.954135 2.460313 2.666512 1.907634 2.573801 2.674025 1.625579 2.539569 2.656363 1.785866 2.572616 2.676082 1.798447 2.376454 2.624298 2.020033 2.397244 2.619868 1.946581 2.468791 2.564185 2.008920 2.342400 2.469132 1.983846 2.271044 2.395408 1.988039 2.154150 2.317920 2.077197 2.216622 2.389101 2.117255 2.283907 2.512242 2.177233 2.334622 2.458268 2.214655 2.425510 2.620013 2.199931 2.390272 2.520731 2.271755 2.448682 2.552649 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp7.txt0000644000175000017500000000004311700377701022655 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp3.txt0000644000175000017500000000004211700377701022650 0ustar jcorganjcorgan1 8 50 75 100 120 150 250 350 450 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp6.txt0000644000175000017500000000004311700377701022654 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp8.txt0000644000175000017500000000005611700377701022516 0ustar jcorganjcorgan1 8 2300 2400 2500 2600 2700 2800 2900 3000 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp6.txt0000644000175000017500000000012711700377701022513 0ustar jcorganjcorgan1 16 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000 2100 2200 2300 2400 2500 2600 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp5.txt0000644000175000017500000000004311700377701022653 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp2.txt0000644000175000017500000000010211700377701022644 0ustar jcorganjcorgan1 16 25 50 75 100 125 150 175 200 225 250 275 300 325 350 375 400 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp10.txt0000644000175000017500000000004311700377701022727 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp4.txt0000644000175000017500000000004311700377701022652 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp5.txt0000644000175000017500000000012711700377701022512 0ustar jcorganjcorgan1 16 950 1050 1150 1250 1350 1450 1550 1650 1750 1850 1950 2050 2150 2250 2350 2450 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp7.txt0000644000175000017500000000012711700377701022514 0ustar jcorganjcorgan1 16 1500 1600 1700 1800 1900 2000 2100 2200 2300 2400 2500 2600 2700 2800 2900 3000 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp8.txt0000644000175000017500000000004311700377701022656 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp9.txt0000644000175000017500000000005611700377701022517 0ustar jcorganjcorgan1 8 2500 2600 2700 2800 2900 3000 3100 3200 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp10.txt0000644000175000017500000000003111700377701022560 0ustar jcorganjcorgan1 4 2900 3100 3300 3500 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp4.txt0000644000175000017500000000012211700377701022504 0ustar jcorganjcorgan1 16 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000 2100 2200 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp2.txt0000644000175000017500000000010511700377701022503 0ustar jcorganjcorgan1 16 325 350 375 400 425 450 475 500 525 550 575 600 625 650 675 700 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/dlsp9.txt0000644000175000017500000000004311700377701022657 0ustar jcorganjcorgan1 8 50 100 200 300 425 550 675 800 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp3.txt0000644000175000017500000000011311700377701022503 0ustar jcorganjcorgan1 16 500 550 600 650 700 750 800 850 900 950 1000 1050 1100 1150 1200 1250 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codebook/lsp1.txt0000644000175000017500000000010511700377701022502 0ustar jcorganjcorgan1 16 225 250 275 300 325 350 375 400 425 450 475 500 525 550 575 600 gnuradio-3.7.2.1/gr-vocoder/lib/codec2/codec2_internal.h0000644000175000017500000000515311744612271022513 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: codec2_internal.h AUTHOR......: David Rowe DATE CREATED: 22 March 2011 Some internal structures and states broken out here as they are useful for testing and development. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2011 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __CODEC2_INTERNAL__ #define __CODEC2_INTERNAL__ /*---------------------------------------------------------------------------*\ STATES \*---------------------------------------------------------------------------*/ typedef struct { float w[M]; /* time domain hamming window */ COMP W[FFT_ENC]; /* DFT of w[] */ float Pn[2*N]; /* trapezoidal synthesis window */ float Sn[M]; /* input speech */ float hpf_states[2]; /* high pass filter states */ void *nlp; /* pitch predictor states */ float Sn_[2*N]; /* synthesised output speech */ float ex_phase; /* excitation model phase track */ float bg_est; /* background noise estimate for post filter */ float prev_Wo; /* previous frame's pitch estimate */ MODEL prev_model; /* previous frame's model parameters */ float prev_lsps[LPC_ORD]; /* previous frame's LSPs */ float prev_energy; /* previous frame's LPC energy */ } CODEC2; /*---------------------------------------------------------------------------*\ FUNCTION HEADERS \*---------------------------------------------------------------------------*/ void analyse_one_frame(CODEC2 *c2, MODEL *model, short speech[]); void synthesise_one_frame(CODEC2 *c2, short speech[], MODEL *model,float ak[]); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/comp.h0000644000175000017500000000201211744612271020405 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: comp.h AUTHOR......: David Rowe DATE CREATED: 24/08/09 Complex number definition. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __COMP__ #define __COMP__ /* Complex number */ typedef struct { float real; float imag; } COMP; #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/generate_codebook.c0000644000175000017500000001030011744612271023100 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: generate_codebook.c AUTHOR......: Bruce Perens DATE CREATED: 29 Sep 2010 Generate header files containing LSP quantisers, runs at compile time. \*---------------------------------------------------------------------------*/ /* All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #include #include #include #include static const char usage[] = "Usage: %s filename array_name [filename ...]\n" "\tCreate C code for codebook tables.\n"; static const char format[] = "The table format must be:\n" "\tTwo integers describing the dimensions of the codebook.\n" "\tThen, enough numbers to fill the specified dimensions.\n"; static const char header[] = "/* THIS IS A GENERATED FILE. Edit generate_codebook.c and its input */\n\n" "/*\n" " * This intermediary file and the files that used to create it are under \n" " * The LGPL. See the file COPYING.\n" " */\n\n" "#include \"defines.h\"\n\n"; struct codebook { unsigned int k; unsigned int log2m; unsigned int m; float * cb; }; static void dump_array(const struct codebook * b, int index) { int limit = b->k * b->m; int i; printf("static const float codes%d[] = {\n", index); for ( i = 0; i < limit; i++ ) { printf(" %g", b->cb[i]); if ( i < limit - 1 ) printf(","); /* organise VQs by rows, looks prettier */ if ( ((i+1) % b->k) == 0 ) printf("\n"); } printf("};\n"); } static void dump_structure(const struct codebook * b, int index) { printf(" {\n"); printf(" %d,\n", b->k); printf(" %g,\n", log(b->m) / log(2)); printf(" %d,\n", b->m); printf(" codes%d\n", index); printf(" }"); } float get_float(FILE * in, const char * name, char * * cursor, char * buffer, int size) { for ( ; ; ) { char * s = *cursor; char c; while ( (c = *s) != '\0' && !isdigit(c) && c != '-' && c != '.' ) s++; /* Comments start with "#" and continue to the end of the line. */ if ( c != '\0' && c != '#' ) { char * end = 0; float f = 0; f = strtod(s, &end); if ( end != s ) *cursor = end; return f; } if ( fgets(buffer, size, in) == NULL ) { fprintf(stderr, "%s: Format error. %s\n", name, format); exit(1); } *cursor = buffer; } } static struct codebook * load(FILE * file, const char * name) { char line[1024]; char * cursor = line; struct codebook * b = malloc(sizeof(struct codebook)); int i; int size; *cursor = '\0'; b->k = (int)get_float(file, name, &cursor, line, sizeof(line)); b->m = (int)get_float(file, name ,&cursor, line, sizeof(line)); size = b->k * b->m; b->cb = (float *)malloc(size * sizeof(float)); for ( i = 0; i < size; i++ ) b->cb[i] = get_float(file, name, &cursor, line, sizeof(line)); return b; } int main(int argc, char * * argv) { struct codebook * * cb = malloc(argc * sizeof(struct codebook *)); int i; if ( argc < 2 ) { fprintf(stderr, usage, argv[0]); fprintf(stderr, format); exit(1); } for ( i = 0; i < argc - 2; i++ ) { FILE * in = fopen(argv[i + 2], "r"); if ( in == NULL ) { perror(argv[i + 2]); exit(1); } cb[i] = load(in, argv[i + 2]); fclose(in); } printf(header); for ( i = 0; i < argc - 2; i++ ) { printf(" /* %s */\n", argv[i + 2]); dump_array(cb[i], i); } printf("\nconst struct lsp_codebook %s[] = {\n", argv[1]); for ( i = 0; i < argc - 2; i++ ) { printf(" /* %s */\n", argv[i + 2]); dump_structure(cb[i], i); printf(",\n"); } printf(" { 0, 0, 0, 0 }\n"); printf("};\n"); return 0; } gnuradio-3.7.2.1/gr-vocoder/lib/codec2/sine.c0000644000175000017500000004165311744612271020416 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: sine.c AUTHOR......: David Rowe DATE CREATED: 19/8/2010 Sinusoidal analysis and synthesis functions. \*---------------------------------------------------------------------------*/ /* Copyright (C) 1990-2010 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ /*---------------------------------------------------------------------------*\ INCLUDES \*---------------------------------------------------------------------------*/ #include #include #include #include "defines.h" #include "sine.h" #include "fft.h" #define HPF_BETA 0.125 /*---------------------------------------------------------------------------*\ HEADERS \*---------------------------------------------------------------------------*/ void hs_pitch_refinement(MODEL *model, COMP Sw[], float pmin, float pmax, float pstep); /*---------------------------------------------------------------------------*\ FUNCTIONS \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ FUNCTION....: make_analysis_window AUTHOR......: David Rowe DATE CREATED: 11/5/94 Init function that generates the time domain analysis window and it's DFT. \*---------------------------------------------------------------------------*/ void make_analysis_window(float w[],COMP W[]) { float m; COMP temp; int i,j; /* Generate Hamming window centered on M-sample pitch analysis window 0 M/2 M-1 |-------------|-------------| |-------|-------| NW samples All our analysis/synthsis is centred on the M/2 sample. */ m = 0.0; for(i=0; iWo + 5; pmin = TWO_PI/model->Wo - 5; pstep = 1.0; hs_pitch_refinement(model,Sw,pmin,pmax,pstep); /* Fine refinement */ pmax = TWO_PI/model->Wo + 1; pmin = TWO_PI/model->Wo - 1; pstep = 0.25; hs_pitch_refinement(model,Sw,pmin,pmax,pstep); /* Limit range */ if (model->Wo < TWO_PI/P_MAX) model->Wo = TWO_PI/P_MAX; if (model->Wo > TWO_PI/P_MIN) model->Wo = TWO_PI/P_MIN; model->L = floor(PI/model->Wo); } /*---------------------------------------------------------------------------*\ FUNCTION....: hs_pitch_refinement AUTHOR......: David Rowe DATE CREATED: 27/5/94 Harmonic sum pitch refinement function. pmin pitch search range minimum pmax pitch search range maximum step pitch search step size model current pitch estimate in model.Wo model refined pitch estimate in model.Wo \*---------------------------------------------------------------------------*/ void hs_pitch_refinement(MODEL *model, COMP Sw[], float pmin, float pmax, float pstep) { int m; /* loop variable */ int b; /* bin for current harmonic centre */ float E; /* energy for current pitch*/ float Wo; /* current "test" fundamental freq. */ float Wom; /* Wo that maximises E */ float Em; /* mamimum energy */ float r; /* number of rads/bin */ float p; /* current pitch */ /* Initialisation */ model->L = PI/model->Wo; /* use initial pitch est. for L */ Wom = model->Wo; Em = 0.0; r = TWO_PI/FFT_ENC; /* Determine harmonic sum for a range of Wo values */ for(p=pmin; p<=pmax; p+=pstep) { E = 0.0; Wo = TWO_PI/p; /* Sum harmonic magnitudes */ for(m=1; m<=model->L; m++) { b = floor(m*Wo/r + 0.5); E += Sw[b].real*Sw[b].real + Sw[b].imag*Sw[b].imag; } /* Compare to see if this is a maximum */ if (E > Em) { Em = E; Wom = Wo; } } model->Wo = Wom; } /*---------------------------------------------------------------------------*\ FUNCTION....: estimate_amplitudes AUTHOR......: David Rowe DATE CREATED: 27/5/94 Estimates the complex amplitudes of the harmonics. \*---------------------------------------------------------------------------*/ void estimate_amplitudes(MODEL *model, COMP Sw[], COMP W[]) { int i,m; /* loop variables */ int am,bm; /* bounds of current harmonic */ int b; /* DFT bin of centre of current harmonic */ float den; /* denominator of amplitude expression */ float r; /* number of rads/bin */ int offset; COMP Am; r = TWO_PI/FFT_ENC; for(m=1; m<=model->L; m++) { den = 0.0; am = floor((m - 0.5)*model->Wo/r + 0.5); bm = floor((m + 0.5)*model->Wo/r + 0.5); b = floor(m*model->Wo/r + 0.5); /* Estimate ampltude of harmonic */ den = 0.0; Am.real = Am.imag = 0.0; for(i=am; iWo/r + 0.5); Am.real += Sw[i].real*W[offset].real; Am.imag += Sw[i].imag*W[offset].real; } model->A[m] = sqrt(den); /* Estimate phase of harmonic */ model->phi[m] = atan2(Sw[b].imag,Sw[b].real); } } /*---------------------------------------------------------------------------*\ est_voicing_mbe() Returns the error of the MBE cost function for a fiven F0. Note: I think a lot of the operations below can be simplified as W[].imag = 0 and has been normalised such that den always equals 1. \*---------------------------------------------------------------------------*/ float est_voicing_mbe( MODEL *model, COMP Sw[], COMP W[], COMP Sw_[], /* DFT of all voiced synthesised signal */ /* useful for debugging/dump file */ COMP Ew[], /* DFT of error */ float prev_Wo) { int i,l,al,bl,m; /* loop variables */ COMP Am; /* amplitude sample for this band */ int offset; /* centers Hw[] about current harmonic */ float den; /* denominator of Am expression */ float error; /* accumulated error between original and synthesised */ float Wo; float sig, snr; float elow, ehigh, eratio; float dF0, sixty; sig = 0.0; for(l=1; l<=model->L/4; l++) { sig += model->A[l]*model->A[l]; } for(i=0; iWo; error = 0.0; /* Just test across the harmonics in the first 1000 Hz (L/4) */ for(l=1; l<=model->L/4; l++) { Am.real = 0.0; Am.imag = 0.0; den = 0.0; al = ceil((l - 0.5)*Wo*FFT_ENC/TWO_PI); bl = ceil((l + 0.5)*Wo*FFT_ENC/TWO_PI); /* Estimate amplitude of harmonic assuming harmonic is totally voiced */ for(m=al; m V_THRESH) model->voiced = 1; else model->voiced = 0; /* post processing, helps clean up some voicing errors ------------------*/ /* Determine the ratio of low freancy to high frequency energy, voiced speech tends to be dominated by low frequency energy, unvoiced by high frequency. This measure can be used to determine if we have made any gross errors. */ elow = ehigh = 0.0; for(l=1; l<=model->L/2; l++) { elow += model->A[l]*model->A[l]; } for(l=model->L/2; l<=model->L; l++) { ehigh += model->A[l]*model->A[l]; } eratio = 10.0*log10(elow/ehigh); dF0 = 0.0; /* Look for Type 1 errors, strongly V speech that has been accidentally declared UV */ if (model->voiced == 0) if (eratio > 10.0) model->voiced = 1; /* Look for Type 2 errors, strongly UV speech that has been accidentally declared V */ if (model->voiced == 1) { if (eratio < -10.0) model->voiced = 0; /* If pitch is jumping about it's likely this is UV */ dF0 = (model->Wo - prev_Wo)*FS/TWO_PI; if (fabs(dF0) > 15.0) model->voiced = 0; /* A common source of Type 2 errors is the pitch estimator gives a low (50Hz) estimate for UV speech, which gives a good match with noise due to the close harmoonic spacing. These errors are much more common than people with 50Hz pitch, so we have just a small eratio threshold. */ sixty = 60.0*TWO_PI/FS; if ((eratio < -4.0) && (model->Wo <= sixty)) model->voiced = 0; } //printf(" v: %d snr: %f eratio: %3.2f %f\n",model->voiced,snr,eratio,dF0); return snr; } /*---------------------------------------------------------------------------*\ FUNCTION....: make_synthesis_window AUTHOR......: David Rowe DATE CREATED: 11/5/94 Init function that generates the trapezoidal (Parzen) sythesis window. \*---------------------------------------------------------------------------*/ void make_synthesis_window(float Pn[]) { int i; float win; /* Generate Parzen window in time domain */ win = 0.0; for(i=0; i 10ms sound poor. The effect can also be seen when synthesising test signals like single sine waves, some sort of amplitude modulation at the frame rate. Another possibility is using a larger FFT size (1024 or 2048). */ #define FFT_SYNTHESIS #ifdef FFT_SYNTHESIS /* Now set up frequency domain synthesised speech */ for(l=1; l<=model->L; l++) { b = floor(l*model->Wo*FFT_DEC/TWO_PI + 0.5); if (b > ((FFT_DEC/2)-1)) { b = (FFT_DEC/2)-1; } Sw_[b].real = model->A[l]*cos(model->phi[l]); Sw_[b].imag = model->A[l]*sin(model->phi[l]); Sw_[FFT_DEC-b].real = Sw_[b].real; Sw_[FFT_DEC-b].imag = -Sw_[b].imag; } /* Perform inverse DFT */ fft(&Sw_[0].real,FFT_DEC,1); #else /* Direct time domain synthesis using the cos() function. Works well at 10ms and 20ms frames rates. Note synthesis window is still used to handle overlap-add between adjacent frames. This could be simplified as we don't need to synthesise where Pn[] is zero. */ for(l=1; l<=model->L; l++) { for(i=0,j=-N+1; iA[l]*cos(j*model->Wo*l + model->phi[l]); } for(i=N-1,j=0; i<2*N; i++,j++) Sw_[j].real += 2.0*model->A[l]*cos(j*model->Wo*l + model->phi[l]); } #endif /* Overlap add to previous samples */ for(i=0; i. */ #ifndef __SINE__ #define __SINE__ #include "defines.h" #include "comp.h" void make_analysis_window(float w[], COMP W[]); float hpf(float x, float states[]); void dft_speech(COMP Sw[], float Sn[], float w[]); void two_stage_pitch_refinement(MODEL *model, COMP Sw[]); void estimate_amplitudes(MODEL *model, COMP Sw[], COMP W[]); float est_voicing_mbe(MODEL *model, COMP Sw[], COMP W[], COMP Sw_[],COMP Ew[], float prev_Wo); void make_synthesis_window(float Pn[]); void synthesise(float Sn_[], MODEL *model, float Pn[], int shift); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/interp.h0000644000175000017500000000247011744612271020760 0ustar jcorganjcorgan/*---------------------------------------------------------------------------*\ FILE........: interp.h AUTHOR......: David Rowe DATE CREATED: 9/10/09 Interpolation of 20ms frames to 10ms frames. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2009 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see . */ #ifndef __INTERP__ #define __INTERP__ #define RES_POINTS 20 void interpolate(MODEL *interp, MODEL *prev, MODEL *next); void interpolate_lsp(MODEL *interp, MODEL *prev, MODEL *next, float *prev_lsps, float prev_e, float *next_lsps, float next_e, float *ak_interp); float resample_amp(MODEL *model, int m); float resample_amp_nl(MODEL *model, int m, float Ares_prev[]); #endif gnuradio-3.7.2.1/gr-vocoder/lib/codec2/fq20.sh0000755000175000017500000000033711744612271020415 0ustar jcorganjcorgan#!/bin/sh # fq20.shsh # David Rowe 27 July 2010 # # Decode a file with fully quantised codec at 20ms frame rate ../src/sinedec ../raw/$1.raw $1.mdl -o $1_phase0_lsp_20_EWo2.raw --phase 0 --lpc 10 --lsp --postfilter --dec gnuradio-3.7.2.1/gr-vocoder/lib/gsm_fr_encode_sp_impl.cc0000664000175000017500000000407512207440367023000 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2010,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gsm_fr_encode_sp_impl.h" #include #include namespace gr { namespace vocoder { gsm_fr_encode_sp::sptr gsm_fr_encode_sp::make() { return gnuradio::get_initial_sptr (new gsm_fr_encode_sp_impl()); } gsm_fr_encode_sp_impl::gsm_fr_encode_sp_impl() : sync_decimator("vocoder_gsm_fr_encode_sp", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(gsm_frame)), GSM_SAMPLES_PER_FRAME) { if((d_gsm = gsm_create ()) == 0) throw std::runtime_error("gsm_fr_encode_sp_impl: gsm_create failed"); } gsm_fr_encode_sp_impl::~gsm_fr_encode_sp_impl() { gsm_destroy (d_gsm); } int gsm_fr_encode_sp_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { gsm_encode(d_gsm, const_cast(in), out); in += GSM_SAMPLES_PER_FRAME; out += sizeof(gsm_frame); } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/ulaw_encode_sb_impl.cc0000664000175000017500000000354212207440367022453 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ulaw_encode_sb_impl.h" #include #include namespace gr { namespace vocoder { extern "C" { #include "g7xx/g72x.h" } ulaw_encode_sb::sptr ulaw_encode_sb::make() { return gnuradio::get_initial_sptr (new ulaw_encode_sb_impl()); } ulaw_encode_sb_impl::ulaw_encode_sb_impl() : sync_block("vocoder_ulaw_encode_sb", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(unsigned char))) { } ulaw_encode_sb_impl::~ulaw_encode_sb_impl() { } int ulaw_encode_sb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = linear2ulaw(in[i]); } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/alaw_encode_sb_impl.h0000664000175000017500000000254712207440367022275 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_ALAW_ENCODER_SB_IMPL_H #define INCLUDED_VOCODER_ALAW_ENCODER_SB_IMPL_H #include namespace gr { namespace vocoder { class alaw_encode_sb_impl : public alaw_encode_sb { public: alaw_encode_sb_impl(); ~alaw_encode_sb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_ALAW_ENCODE_SB_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/cvsd_encode_sb_impl.h0000664000175000017500000000640312207440367022303 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2007,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_CVSD_ENCODER_SB_IMPL_H #define INCLUDED_VOCODER_CVSD_ENCODER_SB_IMPL_H #include namespace gr { namespace vocoder { class cvsd_encode_sb_impl : public cvsd_encode_sb { private: //! Member functions required by the encoder/decoder //! \brief Rounding function specific to CVSD //! \return the input value rounded to the nearest integer int cvsd_round(double input); //! \brief A power function specific to CVSD data formats //! \return (radix)^power, where radix and power are short integers unsigned int cvsd_pow(short radix, short power); //! \brief Sums number of 1's in the input //! \return the number of 1s in the four bytes of an input unsigned integer unsigned char cvsd_bitwise_sum(unsigned int input); // Members variables related to the CVSD encoder use to update interal reference value short d_min_step; short d_max_step; double d_step_decay; double d_accum_decay; int d_K; //!< \brief Size of shift register; the number of output bits remembered in shift register int d_J; //!< \brief Number of bits in the shift register that are equal; size of run of 1s, 0s short d_pos_accum_max; short d_neg_accum_max; int d_accum; //!< \brief Current value of internal reference int d_loop_counter; //!< \brief Current value of the loop counter unsigned int d_runner; //!< \brief Current value of the shift register short d_stepsize; //!< \brief Current value of the step sizer public: cvsd_encode_sb_impl(short min_step=10, short max_step=1280, double step_decay=0.9990234375, double accum_decay= 0.96875, int K=32, int J=4, short pos_accum_max=32767, short neg_accum_max=-32767); ~cvsd_encode_sb_impl(); short min_step() { return d_min_step; } short max_step() { return d_max_step; } double step_decay() { return d_step_decay; } double accum_decay() { return d_accum_decay; } int K() { return d_K; } int J() { return d_J; } short pos_accum_max() { return d_pos_accum_max; } short neg_accum_max() { return d_neg_accum_max; } int work (int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_CVSD_ENCODE_SB_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g721_encode_sb_impl.h0000664000175000017500000000266412207440367022031 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G721_ENCODE_SB_IMPL_H #define INCLUDED_VOCODER_G721_ENCODE_SB_IMPL_H #include extern "C" { #include "g7xx/g72x.h" } namespace gr { namespace vocoder { class g721_encode_sb_impl : public g721_encode_sb { private: g72x_state d_state; public: g721_encode_sb_impl(); ~g721_encode_sb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G721_ENCODE_SB_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm_fr_decode_ps_impl.h0000664000175000017500000000271312207440367022625 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_GSM_FR_DECODE_PS_IMPL_H #define INCLUDED_VOCODER_GSM_FR_DECODE_PS_IMPL_H #include extern "C"{ #include "gsm/gsm.h" } namespace gr { namespace vocoder { class gsm_fr_decode_ps_impl : public gsm_fr_decode_ps { private: struct gsm_state *d_gsm; public: gsm_fr_decode_ps_impl(); ~gsm_fr_decode_ps_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_GSM_FR_DECODE_PS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g721_decode_bs_impl.cc0000664000175000017500000000357312207440367022155 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "g721_decode_bs_impl.h" #include #include namespace gr { namespace vocoder { g721_decode_bs::sptr g721_decode_bs::make() { return gnuradio::get_initial_sptr (new g721_decode_bs_impl()); } g721_decode_bs_impl::g721_decode_bs_impl() : sync_block("vocoder_g721_decode_bs", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(short))) { g72x_init_state(&d_state); } g721_decode_bs_impl::~g721_decode_bs_impl() { } int g721_decode_bs_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = g721_decoder(in[i], AUDIO_ENCODING_LINEAR, &d_state); return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_24_encode_sb_impl.h0000664000175000017500000000271412207440367022334 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_24_ENCODE_SB_IMPL_H #define INCLUDED_VOCODER_G723_24_ENCODE_SB_IMPL_H #include extern "C" { #include "g7xx/g72x.h" } namespace gr { namespace vocoder { class g723_24_encode_sb_impl : public g723_24_encode_sb { private: g72x_state d_state; public: g723_24_encode_sb_impl(); ~g723_24_encode_sb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_24_ENCODE_SB_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/gsm_fr_encode_sp_impl.h0000664000175000017500000000271312207440367022637 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_GSM_FR_ENCODE_SP_IMPL_H #define INCLUDED_VOCODER_GSM_FR_ENCODE_SP_IMPL_H #include extern "C"{ #include "gsm/gsm.h" } namespace gr { namespace vocoder { class gsm_fr_encode_sp_impl : public gsm_fr_encode_sp { private: struct gsm_state *d_gsm; public: gsm_fr_encode_sp_impl(); ~gsm_fr_encode_sp_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_GSM_FR_ENCODE_SP_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/codec2_encode_sp_impl.cc0000664000175000017500000000423412207440367022657 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "codec2_encode_sp_impl.h" extern "C" { #include "codec2/codec2.h" } #include #include namespace gr { namespace vocoder { codec2_encode_sp::sptr codec2_encode_sp::make() { return gnuradio::get_initial_sptr (new codec2_encode_sp_impl()); } codec2_encode_sp_impl::codec2_encode_sp_impl() : sync_decimator("vocoder_codec2_encode_sp", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, CODEC2_BITS_PER_FRAME * sizeof(char)), CODEC2_SAMPLES_PER_FRAME) { if((d_codec2 = codec2_create()) == 0) throw std::runtime_error("codec2_encode_sp_impl: codec2_create failed"); } codec2_encode_sp_impl::~codec2_encode_sp_impl() { codec2_destroy(d_codec2); } int codec2_encode_sp_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) { codec2_encode(d_codec2, out, const_cast(in)); in += CODEC2_SAMPLES_PER_FRAME; out += CODEC2_BITS_PER_FRAME * sizeof(char); } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g721_decode_bs_impl.h0000664000175000017500000000266412207440367022017 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G721_DECODE_BS_IMPL_H #define INCLUDED_VOCODER_G721_DECODE_BS_IMPL_H #include extern "C" { #include "g7xx/g72x.h" } namespace gr { namespace vocoder { class g721_decode_bs_impl : public g721_decode_bs { private: g72x_state d_state; public: g721_decode_bs_impl(); ~g721_decode_bs_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G721_DECODE_BS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g721_encode_sb_impl.cc0000664000175000017500000000356612207440367022171 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "g721_encode_sb_impl.h" #include #include namespace gr { namespace vocoder { g721_encode_sb::sptr g721_encode_sb::make() { return gnuradio::get_initial_sptr (new g721_encode_sb_impl()); } g721_encode_sb_impl::g721_encode_sb_impl() : sync_block("vocoder_g721_encode_sb", io_signature::make(1, 1, sizeof(short)), io_signature::make(1, 1, sizeof(unsigned char))) { g72x_init_state(&d_state); } g721_encode_sb_impl::~g721_encode_sb_impl() { } int g721_encode_sb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const short *in = (const short*)input_items[0]; unsigned char *out = (unsigned char*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = g721_encoder(in[i], AUDIO_ENCODING_LINEAR, &d_state); return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_40_decode_bs_impl.h0000664000175000017500000000271412207440367022320 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_40_DECODE_BS_IMPL_H #define INCLUDED_VOCODER_G723_40_DECODE_BS_IMPL_H #include extern "C" { #include "g7xx/g72x.h" } namespace gr { namespace vocoder { class g723_40_decode_bs_impl : public g723_40_decode_bs { private: g72x_state d_state; public: g723_40_decode_bs_impl(); ~g723_40_decode_bs_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_40_DECODE_BS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_24_decode_bs_impl.h0000664000175000017500000000270512207440367022322 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_VOCODER_G723_24_DECODE_BS_IMPL_H #define INCLUDED_VOCODER_G723_24_DECODE_BS_IMPL_H #include extern "C" { #include "g7xx/g72x.h" } namespace gr { namespace vocoder { class g723_24_decode_bs_impl : public g723_24_decode_bs { private: g72x_state d_state; public: g723_24_decode_bs_impl(); ~g723_24_decode_bs_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace vocoder */ } /* namespace gr */ #endif /* INCLUDED_VOCODER_G723_24_DECODE_BS_IMPL_H */ gnuradio-3.7.2.1/gr-vocoder/lib/alaw_decode_bs_impl.cc0000664000175000017500000000354212207440367022415 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "alaw_decode_bs_impl.h" #include #include namespace gr { namespace vocoder { extern "C" { #include "g7xx/g72x.h" } alaw_decode_bs::sptr alaw_decode_bs::make() { return gnuradio::get_initial_sptr (new alaw_decode_bs_impl()); } alaw_decode_bs_impl::alaw_decode_bs_impl() : sync_block("vocoder_alaw_decode_bs", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(short))) { } alaw_decode_bs_impl::~alaw_decode_bs_impl() { } int alaw_decode_bs_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short*)output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i] = alaw2linear(in[i]); } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/codec2_decode_ps_impl.cc0000664000175000017500000000445212207440367022647 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2005,2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "codec2_decode_ps_impl.h" extern "C" { #include "codec2/codec2.h" } #include #include #include namespace gr { namespace vocoder { codec2_decode_ps::sptr codec2_decode_ps::make() { return gnuradio::get_initial_sptr (new codec2_decode_ps_impl()); } codec2_decode_ps_impl::codec2_decode_ps_impl () : sync_interpolator("vocoder_codec2_decode_ps", io_signature::make(1, 1, CODEC2_BITS_PER_FRAME * sizeof(char)), io_signature::make (1, 1, sizeof(short)), CODEC2_SAMPLES_PER_FRAME) { if((d_codec2 = codec2_create()) == 0) throw std::runtime_error("codec2_decode_ps_impl: codec2_create failed"); } codec2_decode_ps_impl::~codec2_decode_ps_impl() { codec2_destroy(d_codec2); } int codec2_decode_ps_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short *) output_items[0]; assert((noutput_items % CODEC2_SAMPLES_PER_FRAME) == 0); for(int i = 0; i < noutput_items; i += CODEC2_SAMPLES_PER_FRAME) { codec2_decode (d_codec2, out, const_cast(in)); in += CODEC2_BITS_PER_FRAME * sizeof (char); out += CODEC2_SAMPLES_PER_FRAME; } return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/lib/g723_40_decode_bs_impl.cc0000664000175000017500000000362412207440367022457 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "g723_40_decode_bs_impl.h" #include #include namespace gr { namespace vocoder { g723_40_decode_bs::sptr g723_40_decode_bs::make() { return gnuradio::get_initial_sptr (new g723_40_decode_bs_impl()); } g723_40_decode_bs_impl::g723_40_decode_bs_impl() : sync_block("vocoder_g723_40_decode_bs", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(short))) { g72x_init_state(&d_state); } g723_40_decode_bs_impl::~g723_40_decode_bs_impl() { } int g723_40_decode_bs_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char*)input_items[0]; short *out = (short*)output_items[0]; for(int i = 0; i < noutput_items; i++) out[i] = g723_40_decoder(in[i], AUDIO_ENCODING_LINEAR, &d_state); return noutput_items; } } /* namespace vocoder */ } /* namespace gr */ gnuradio-3.7.2.1/gr-vocoder/swig/0000755000175000017500000000000012207440367016347 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/swig/CMakeLists.txt0000664000175000017500000000345712207440367021122 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_VOCODER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/vocoder_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/vocoder) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-vocoder) GR_SWIG_MAKE(vocoder_swig vocoder_swig.i) GR_SWIG_INSTALL( TARGETS vocoder_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/vocoder COMPONENT "vocoder_python" ) install( FILES vocoder_swig.i ${CMAKE_CURRENT_BINARY_DIR}/vocoder_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "vocoder_swig" ) gnuradio-3.7.2.1/gr-vocoder/swig/vocoder_swig.i0000664000175000017500000000617512207440367021226 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2011,2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define VOCODER_API %include "gnuradio.i" //load generated python docstrings %include "vocoder_swig_doc.i" %{ #include "gnuradio/vocoder/alaw_decode_bs.h" #include "gnuradio/vocoder/alaw_encode_sb.h" #include "gnuradio/vocoder/codec2_decode_ps.h" #include "gnuradio/vocoder/codec2_encode_sp.h" #include "gnuradio/vocoder/cvsd_decode_bs.h" #include "gnuradio/vocoder/cvsd_encode_sb.h" #include "gnuradio/vocoder/g721_decode_bs.h" #include "gnuradio/vocoder/g721_encode_sb.h" #include "gnuradio/vocoder/g723_24_decode_bs.h" #include "gnuradio/vocoder/g723_24_encode_sb.h" #include "gnuradio/vocoder/g723_40_decode_bs.h" #include "gnuradio/vocoder/g723_40_encode_sb.h" #include "gnuradio/vocoder/gsm_fr_decode_ps.h" #include "gnuradio/vocoder/gsm_fr_encode_sp.h" #include "gnuradio/vocoder/ulaw_decode_bs.h" #include "gnuradio/vocoder/ulaw_encode_sb.h" %} %include "gnuradio/vocoder/alaw_decode_bs.h" %include "gnuradio/vocoder/alaw_encode_sb.h" %include "gnuradio/vocoder/codec2_decode_ps.h" %include "gnuradio/vocoder/codec2_encode_sp.h" %include "gnuradio/vocoder/cvsd_decode_bs.h" %include "gnuradio/vocoder/cvsd_encode_sb.h" %include "gnuradio/vocoder/g721_decode_bs.h" %include "gnuradio/vocoder/g721_encode_sb.h" %include "gnuradio/vocoder/g723_24_decode_bs.h" %include "gnuradio/vocoder/g723_24_encode_sb.h" %include "gnuradio/vocoder/g723_40_decode_bs.h" %include "gnuradio/vocoder/g723_40_encode_sb.h" %include "gnuradio/vocoder/gsm_fr_decode_ps.h" %include "gnuradio/vocoder/gsm_fr_encode_sp.h" %include "gnuradio/vocoder/ulaw_decode_bs.h" %include "gnuradio/vocoder/ulaw_encode_sb.h" GR_SWIG_BLOCK_MAGIC2(vocoder, alaw_decode_bs); GR_SWIG_BLOCK_MAGIC2(vocoder, alaw_encode_sb); GR_SWIG_BLOCK_MAGIC2(vocoder, codec2_decode_ps); GR_SWIG_BLOCK_MAGIC2(vocoder, codec2_encode_sp); GR_SWIG_BLOCK_MAGIC2(vocoder, cvsd_decode_bs); GR_SWIG_BLOCK_MAGIC2(vocoder, cvsd_encode_sb); GR_SWIG_BLOCK_MAGIC2(vocoder, g721_decode_bs); GR_SWIG_BLOCK_MAGIC2(vocoder, g721_encode_sb); GR_SWIG_BLOCK_MAGIC2(vocoder, g723_24_decode_bs); GR_SWIG_BLOCK_MAGIC2(vocoder, g723_24_encode_sb); GR_SWIG_BLOCK_MAGIC2(vocoder, g723_40_decode_bs); GR_SWIG_BLOCK_MAGIC2(vocoder, g723_40_encode_sb); GR_SWIG_BLOCK_MAGIC2(vocoder, gsm_fr_decode_ps); GR_SWIG_BLOCK_MAGIC2(vocoder, gsm_fr_encode_sp); GR_SWIG_BLOCK_MAGIC2(vocoder, ulaw_decode_bs); GR_SWIG_BLOCK_MAGIC2(vocoder, ulaw_encode_sb); gnuradio-3.7.2.1/gr-vocoder/gnuradio-vocoder.pc.in0000664000175000017500000000041412207440367021577 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-vocoder Description: GNU Radio blocks implementing voice codecs Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-vocoder Cflags: -I${includedir} gnuradio-3.7.2.1/gr-vocoder/examples/0000755000175000017500000000000012207440367017214 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-vocoder/examples/ulaw_audio_loopback.py0000775000175000017500000000267712207440367023612 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.ulaw_encode_sb() dec = vocoder.ulaw_decode_bs() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/CMakeLists.txt0000644000175000017500000000242411744612271021756 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install Examples ######################################################################## include(GrPython) GR_PYTHON_INSTALL( PROGRAMS alaw_audio_loopback.py codec2_audio_loopback.py cvsd_audio_loopback.py g721_audio_loopback.py g723_24_audio_loopback.py g723_40_audio_loopback.py gsm_audio_loopback.py ulaw_audio_loopback.py DESTINATION ${GR_PKG_VOCODER_EXAMPLES_DIR} COMPONENT "vocoder_examples" ) gnuradio-3.7.2.1/gr-vocoder/examples/g723_24_audio_loopback.py0000775000175000017500000000270512207440367023621 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.g723_24_encode_sb() dec = vocoder.g723_24_decode_bs() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/alaw_audio_loopback.py0000775000175000017500000000267712207440367023566 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.alaw_encode_sb() dec = vocoder.alaw_decode_bs() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/cvsd_audio_loopback.py0000775000175000017500000000457112207440367023574 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import filter from gnuradio import vocoder def build_graph(): sample_rate = 8000 scale_factor = 32000 tb = gr.top_block() src = audio.source(sample_rate, "plughw:0,0") src_scale = blocks.multiply_const_ff(scale_factor) interp = filter.rational_resampler_fff(8, 1) f2s = blocks.float_to_short() enc = vocoder.cvsd_encode_sb() dec = vocoder.cvsd_decode_bs() s2f = blocks.short_to_float() decim = filter.rational_resampler_fff(1, 8) sink_scale = blocks.multiply_const_ff(1.0/scale_factor) sink = audio.sink(sample_rate, "plughw:0,0") tb.connect(src, src_scale, interp, f2s, enc) tb.connect(enc, dec, s2f, decim, sink_scale, sink) if 0: # debug tb.conect(src, blocks.file_sink(gr.sizeof_float, "source.dat")) tb.conect(src_scale, blocks.file_sink(gr.sizeof_float, "src_scale.dat")) tb.conect(interp, blocks.file_sink(gr.sizeof_float, "interp.dat")) tb.conect(f2s, blocks.file_sink(gr.sizeof_short, "f2s.dat")) tb.conect(enc, blocks.file_sink(gr.sizeof_char, "enc.dat")) tb.conect(dec, blocks.file_sink(gr.sizeof_short, "dec.dat")) tb.conect(s2f, blocks.file_sink(gr.sizeof_float, "s2f.dat")) tb.conect(decim, blocks.file_sink(gr.sizeof_float, "decim.dat")) tb.conect(sink_scale, blocks.file_sink(gr.sizeof_float, "sink_scale.dat")) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/gsm_audio_loopback.py0000775000175000017500000000271512207440367023421 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.gsm_fr_encode_sp() dec = vocoder.gsm_fr_decode_ps() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/codec2_audio_loopback.py0000775000175000017500000000271512207440367023772 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2005,2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.codec2_encode_sp() dec = vocoder.codec2_decode_ps() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/g721_audio_loopback.py0000775000175000017500000000267712207440367023322 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.g721_encode_sb() dec = vocoder.g721_decode_bs() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/gr-vocoder/examples/g723_40_audio_loopback.py0000775000175000017500000000270512207440367023617 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.g723_40_encode_sb() dec = vocoder.g723_40_decode_bs() s2f = blocks.short_to_float() sink_scale = blocks.multiply_const_ff(1.0/32767.) sink = audio.sink(8000) tb.connect(src, src_scale, f2s, enc, dec, s2f, sink_scale, sink) return tb if __name__ == '__main__': tb = build_graph() tb.start() raw_input ('Press Enter to exit: ') tb.stop() tb.wait() gnuradio-3.7.2.1/README0000664000175000017500000001070512207440367014214 0ustar jcorganjcorgan# # Copyright 2001-2007,2009,2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # Welcome to GNU Radio! Please see http://gnuradio.org for the wiki, bug tracking, and source code viewer. If you've got questions about GNU Radio, please subscribe to the discuss-gnuradio mailing list and post your questions there. http://gnuradio.org/redmine/projects/gnuradio/wiki/MailingLists There is also a "Build Guide" in the wiki that contains OS specific recommendations: http://gnuradio.org/redmine/projects/gnuradio/wiki/BuildGuide The bleeding edge code can be found in our git repository at http://gnuradio.org/git/gnuradio.git/. To checkout the latest, use this command: $ git clone git://git.gnuradio.org/gnuradio For information about using Git, please see: http://gnuradio.org/redmine/projects/gnuradio/wiki/DevelopingWithGit How to Build GNU Radio: For more complete instructions, see the "Building GNU Radio" page in the GNU Radio manual (can be built or found online at http://gnuradio.org/doc/doxygen/page_build.html). See these steps fow a quick build guide. (1) Ensure that you've satisfied the external dependencies. These dependencies are listed in the manual's build page and are not presented here to reduce duplication errors. See the wiki at http://gnuradio.org for details. (2) Building from cmake: $ mkdir $(builddir) $ cd $(builddir) $ cmake [OPTIONS] $(srcdir) $ make $ make test $ sudo make install That's it! Options: Useful options include setting the install prefix and the build type: -DCMAKE_INSTALL_PREFIX= -DCMAKE_BUILD_TYPE="" Currently, GNU Radio has a "Debug" type that builds with '-g -O2' useful for debugging the software and a "Release" type that builds with '-O3', which is the default. ------------------------------------------------------------------------------- KNOWN INCOMPATIBILITIES GNU Radio triggers bugs in g++ 3.3 for X86. DO NOT USE GCC 3.3 on the X86 platform. g++ 3.2, 3.4, and the 4.* series are known to work well. ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- NOTES ------------------------------------------------------------------------------- To run the examples you may need to set PYTHONPATH. Note that the prefix and python version number in the path needs to match your installed version of python. $ export PYTHONPATH=/usr/local/lib/python2.7/dist-packages You may want to add this to your shell init file (~/.bash_profile if you use bash). Another handy trick if for example your fftw includes and libs are installed in, say ~/local/include and ~/local/lib, instead of /usr/local is this: $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/local/lib $ make CPPFLAGS="-I$HOME/local/include" Sometimes the prerequisites are installed in a location which is not included in the default compiler and linker search paths. This happens with pkgsrc and NetBSD. To build, tell configure to use these locations: LDFLAGS="-L/usr/pkg/lib -R/usr/pkg/lib" CPPFLAGS="-I/usr/pkg/include" ./configure --prefix=/usr/gnuradio ------------------------------------------------------------------------------- Legal Matters ------------------------------------------------------------------------------- Some files have been changed many times throughout the years. Copyright notices at the tops of these files list which years changes have been made. For some files, changes have occurred in many consecutive years. These files may often have the format of a year range (e.g., "2006 - 2011"), which indicates that these files have had copyrightable changes made during each year in the range, inclusive. gnuradio-3.7.2.1/gr-pager/0000755000175000017500000000000012207440367015033 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/CMakeLists.txt0000664000175000017500000000677712207440367017616 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## include(GrBoost) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("gr-pager" ENABLE_GR_PAGER Boost_FOUND ENABLE_GNURADIO_RUNTIME ENABLE_GR_FILTER ENABLE_GR_ANALOG ) GR_SET_GLOBAL(GR_PAGER_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include ) GR_SET_GLOBAL(GR_PAGER_SWIG_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/swig ) SET(GR_PKG_PAGER_EXAMPLES_DIR ${GR_PKG_DATA_DIR}/examples/pager) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_GR_PAGER) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_SET(CPACK_COMPONENT_GROUP_PAGER_DESCRIPTION "GNU Radio Pager Blocks") CPACK_COMPONENT("pager_runtime" GROUP "Pager" DISPLAY_NAME "Runtime" DESCRIPTION "Runtime" DEPENDS "runtime_runtime" ) CPACK_COMPONENT("pager_devel" GROUP "Pager" DISPLAY_NAME "Development" DESCRIPTION "C++ headers, package config, import libraries" DEPENDS "runtime_devel" ) CPACK_COMPONENT("pager_python" GROUP "Pager" DISPLAY_NAME "Python" DESCRIPTION "Python modules for runtime; GRC xml files" DEPENDS "runtime_python;pager_runtime" ) CPACK_COMPONENT("pager_swig" GROUP "Pager" DISPLAY_NAME "SWIG" DESCRIPTION "SWIG development .i files" DEPENDS "runtime_swig;pager_python;pager_devel" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(include/gnuradio/pager) add_subdirectory(lib) if(ENABLE_PYTHON) add_subdirectory(python/pager) add_subdirectory(swig) add_subdirectory(grc) add_subdirectory(apps) endif(ENABLE_PYTHON) ######################################################################## # Create Pkg Config File ######################################################################## configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-pager.pc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-pager.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-pager.pc DESTINATION ${GR_LIBRARY_DIR}/pkgconfig COMPONENT "pager_devel" ) endif(ENABLE_GR_PAGER) gnuradio-3.7.2.1/gr-pager/include/0000775000175000017500000000000012207440367016460 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/include/gnuradio/0000775000175000017500000000000012207440367020270 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/0000775000175000017500000000000012207440367021366 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/flex_parse.h0000664000175000017500000000272712207440367023677 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_PARSE_H #define INCLUDED_PAGER_FLEX_PARSE_H #include #include #include #include namespace gr { namespace pager { #define FIELD_DELIM ((unsigned char)128) /*! * \brief flex parse description * \ingroup pager_blk */ class PAGER_API flex_parse : virtual public sync_block { public: // gr::pager::flex_parse::sptr typedef boost::shared_ptr sptr; static sptr make(msg_queue::sptr queue, float freq); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_PARSE_H */ gnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/CMakeLists.txt0000664000175000017500000000217212207440367024130 0ustar jcorganjcorgan# Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Install header files ######################################################################## install(FILES api.h flex_frame.h slicer_fb.h flex_deinterleave.h flex_parse.h flex_sync.h DESTINATION ${GR_INCLUDE_DIR}/gnuradio/pager COMPONENT "pager_devel" ) gnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/slicer_fb.h0000664000175000017500000000270712207440367023475 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_SLICER_FB_H #define INCLUDED_PAGER_SLICER_FB_H #include #include namespace gr { namespace pager { /*! * \brief slicer description * \ingroup pager_blk */ class PAGER_API slicer_fb : virtual public sync_block { public: // gr::pager::slicer_fb::sptr typedef boost::shared_ptr sptr; /*! * \brief Make a pager slicer */ static sptr make(float alpha); virtual float dc_offset() const = 0; }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_SLICER_FB_H */ gnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/flex_sync.h0000664000175000017500000000250412207440367023532 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_SYNC_H #define INCLUDED_PAGER_FLEX_SYNC_H #include #include namespace gr { namespace pager { /*! * \brief flex sync description * \ingroup pager_blk */ class PAGER_API flex_sync : virtual public block { public: // gr::pager::flex_sync::sptr typedef boost::shared_ptr sptr; static sptr make(); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_SYNC_H */ gnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/flex_frame.h0000664000175000017500000000246512207440367023656 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_FRAME_H #define INCLUDED_PAGER_FLEX_FRAME_H #include #include namespace gr { namespace pager { /*! * \brief flex_frame. * \ingroup pager_blk */ class PAGER_API flex_frame { public: // gr::pager::flex_frame::sptr typedef boost::shared_ptr sptr; static sptr make(); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_FRAME_H */ gnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/flex_deinterleave.h0000664000175000017500000000272212207440367025227 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_DEINTERLEAVE_H #define INCLUDED_PAGER_FLEX_DEINTERLEAVE_H #include #include namespace gr { namespace pager { /*! * \brief flex deinterleave description * \ingroup pager_blk */ class PAGER_API flex_deinterleave : virtual public sync_decimator { public: // gr::pager::flex_deinterleave::sptr typedef boost::shared_ptr sptr; /*! * \brief Make flex deinterleaver */ static sptr make(); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_DEINTERLEAVE_H */ gnuradio-3.7.2.1/gr-pager/include/gnuradio/pager/api.h0000664000175000017500000000203112207440367022304 0ustar jcorganjcorgan/* * Copyright 2011 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_API_H #define INCLUDED_PAGER_API_H #include #ifdef gnuradio_pager_EXPORTS # define PAGER_API __GR_ATTR_EXPORT #else # define PAGER_API __GR_ATTR_IMPORT #endif #endif /* INCLUDED_PAGER_API_H */ gnuradio-3.7.2.1/gr-pager/grc/0000755000175000017500000000000011744612271015606 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/grc/CMakeLists.txt0000644000175000017500000000165211744612271020352 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. install(FILES pager_slicer_fb.xml pager_flex_sync.xml pager_flex_deinterleave.xml DESTINATION ${GRC_BLOCKS_DIR} COMPONENT "pager_python" ) gnuradio-3.7.2.1/gr-pager/grc/pager_flex_sync.xml0000644000175000017500000000117711700377701021504 0ustar jcorganjcorgan FLEX Synchronizer pager_flex_sync Pager from gnuradio import pager pager.flex_sync() dibits byte A byte B byte C byte D byte gnuradio-3.7.2.1/gr-pager/grc/pager_slicer_fb.xml0000644000175000017500000000111611700377701021433 0ustar jcorganjcorgan 4-Level Slicer/DCR pager_slicer_fb Pager from gnuradio import pager pager.slicer_fb($alpha) Alpha alpha 1e-6 real bb float dibits byte gnuradio-3.7.2.1/gr-pager/grc/pager_flex_deinterleave.xml0000644000175000017500000000074211700377701023174 0ustar jcorganjcorgan FLEX Deinterleave pager_flex_deinterleave Pager from gnuradio import pager pager.flex_deinterleave() bits byte codes int gnuradio-3.7.2.1/gr-pager/python/0000775000175000017500000000000012207440367016356 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/python/pager/0000775000175000017500000000000012207440367017454 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/python/pager/CMakeLists.txt0000664000175000017500000000323312207440367022215 0ustar jcorganjcorgan# Copyright 2011-2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## include(GrPython) GR_PYTHON_INSTALL( FILES __init__.py pager_utils.py flex_demod.py DESTINATION ${GR_PYTHON_DIR}/gnuradio/pager COMPONENT "pager_python" ) ######################################################################## # Handle the unit tests ######################################################################## if(ENABLE_TESTING) set(GR_TEST_TARGET_DEPS "") set(GR_TEST_LIBRARY_DIRS "") set(GR_TEST_PYTHON_DIRS ${CMAKE_BINARY_DIR}/gnuradio-runtime/python ) include(GrTest) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) GR_ADD_TEST(${py_qa_test_name} ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) gnuradio-3.7.2.1/gr-pager/python/pager/pager_utils.py0000664000175000017500000000332212207440367022344 0ustar jcorganjcorgan# # Copyright 2008,2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from gnuradio import gr import gnuradio.gr.gr_threading as _threading from string import split, join, printable import time def make_trans_table(): table = 256 * ['.'] for i in range(256): if (i < 32): table[i] = '.' else: table[i] = chr(i) return ''.join(table) _trans_table = make_trans_table() def make_printable(s): return s.translate(_trans_table) class queue_runner(_threading.Thread): def __init__(self, msgq): _threading.Thread.__init__(self) self.msgq = msgq self.done = False self.start() def run(self): while 1: msg = self.msgq.delete_head() # Blocking read if msg.type() != 0: break page = join(split(msg.to_string(), chr(128)), '|') s = make_printable(page) print msg.type(), s def end(self): self.msgq.insert_tail(gr.message(1)) self.done = True gnuradio-3.7.2.1/gr-pager/python/pager/flex_demod.py0000664000175000017500000000433212207440367022136 0ustar jcorganjcorgan# # Copyright 2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import analog from gnuradio import blocks from gnuradio import filter from math import pi import pager_swig class flex_demod(gr.hier_block2): """ FLEX pager protocol demodulation block. This block demodulates a band-limited, complex down-converted baseband channel into FLEX protocol frames. """ def __init__(self, queue, freq=0.0, verbose=False, log=False): gr.hier_block2.__init__(self, "flex_demod", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0,0,0)) k = 25000/(2*pi*1600) # 4800 Hz max deviation quad = analog.quadrature_demod_cf(k) self.connect(self, quad) rsamp = filter.rational_resampler_fff(16, 25) self.slicer = pager_swig.slicer_fb(5e-6) # DC removal averaging filter constant self.sync = pager_swig.flex_sync() self.connect(quad, rsamp, self.slicer, self.sync) for i in range(4): self.connect((self.sync, i), pager_swig.flex_deinterleave(), pager_swig.flex_parse(queue, freq)) if log: suffix = '_'+ "%3.3f" % (freq/1e6,) + '.dat' quad_sink = blocks.file_sink(gr.sizeof_float, 'quad'+suffix) rsamp_sink = blocks.file_sink(gr.sizeof_float, 'rsamp'+suffix) slicer_sink = blocks.file_sink(gr.sizeof_char, 'slicer'+suffix) self.connect(rsamp, rsamp_sink) self.connect(quad, quad_sink) self.connect(self.slicer, slicer_sink) def dc_offset(self): return self.slicer.dc_offset() gnuradio-3.7.2.1/gr-pager/python/pager/__init__.py0000664000175000017500000000223312207440367021565 0ustar jcorganjcorgan# # Copyright 2006 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # The presence of this file turns this directory into a Python package ''' The GNU Radio pager application. ''' import os try: from pager_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from pager_swig import * from flex_demod import flex_demod from pager_utils import * gnuradio-3.7.2.1/gr-pager/python/pager/qa_pager.py0000775000175000017500000000207412207440367021613 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2004,2006,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, pager class test_pager(gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None if __name__ == '__main__': gr_unittest.run(test_pager, "test_pager.xml") gnuradio-3.7.2.1/gr-pager/lib/0000755000175000017500000000000012207440367015601 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/lib/CMakeLists.txt0000664000175000017500000000454412207440367020352 0ustar jcorganjcorgan# Copyright 2011,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup the include and linker paths ######################################################################## include_directories( ${GR_PAGER_INCLUDE_DIRS} ${GR_BLOCKS_INCLUDE_DIRS} ${GNURADIO_RUNTIME_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) ADD_DEFINITIONS(-DGR_CTRLPORT) include_directories(${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) link_directories(${Boost_LIBRARY_DIRS}) include_directories(${LOG4CPP_INCLUDE_DIRS}) link_directories(${LOG4CPP_LIBRARY_DIRS}) ######################################################################## # Setup library ######################################################################## list(APPEND pager_sources flex_deinterleave_impl.cc flex_frame_impl.cc flex_parse_impl.cc flex_sync_impl.cc slicer_fb_impl.cc bch3221.cc flex_modes.cc util.cc ) #Add Windows DLL resource file if using MSVC if(MSVC) include(${CMAKE_SOURCE_DIR}/cmake/Modules/GrVersion.cmake) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/gnuradio-pager.rc.in ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-pager.rc @ONLY) list(APPEND gr_pager_sources ${CMAKE_CURRENT_BINARY_DIR}/gnuradio-pager.rc ) endif(MSVC) list(APPEND pager_libs gnuradio-runtime gnuradio-blocks ${Boost_LIBRARIES} ${LOG4CPP_LIBRARIES} ) add_library(gnuradio-pager SHARED ${pager_sources}) target_link_libraries(gnuradio-pager ${pager_libs}) GR_LIBRARY_FOO(gnuradio-pager RUNTIME_COMPONENT "pager_runtime" DEVEL_COMPONENT "pager_devel") gnuradio-3.7.2.1/gr-pager/lib/flex_frame_impl.h0000664000175000017500000000226312207440367021110 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_FRAME_IMPL_H #define INCLUDED_PAGER_FLEX_FRAME_IMPL_H #include namespace gr { namespace pager { class flex_frame_impl : public flex_frame { public: flex_frame_impl(); ~flex_frame_impl(); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_FRAME_IMPL_H */ gnuradio-3.7.2.1/gr-pager/lib/util.h0000664000175000017500000000214212207440367016730 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_UTIL_H #define INCLUDED_PAGER_UTIL_H #include namespace gr { namespace pager { unsigned char reverse_bits8(unsigned char val); int32_t reverse_bits32(int32_t val); } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_UTIL_H */ gnuradio-3.7.2.1/gr-pager/lib/flex_modes.cc0000664000175000017500000000304012207440367020234 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "flex_modes.h" namespace gr { namespace pager { const flex_mode_t flex_modes[] = { { 0x870C78F3, 1600, 2 }, { 0xB0684F97, 1600, 4 }, // { 0xUNKNOWN, 3200, 2 }, { 0xDEA0215F, 3200, 4 }, { 0x4C7CB383, 3200, 4 } }; const int num_flex_modes = sizeof(flex_modes)/sizeof(flex_modes[0]); unsigned char flex_bcd[17] = "0123456789 U -]["; const char *flex_page_desc[] = { "ENC", "UNK", "TON", "NUM", "SPN", "ALN", "BIN", "NNM" }; int find_flex_mode(int32_t sync_code) { for(int i = 0; i < num_flex_modes; i++) if(flex_modes[i].sync == sync_code) return i; // Not found return -1; } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/flex_parse_impl.cc0000664000175000017500000001443412207440367021271 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "flex_parse_impl.h" #include "bch3221.h" #include #include #include #include namespace gr { namespace pager { flex_parse::sptr flex_parse::make(msg_queue::sptr queue, float freq) { return gnuradio::get_initial_sptr (new flex_parse_impl(queue, freq)); } flex_parse_impl::flex_parse_impl(msg_queue::sptr queue, float freq) : sync_block("flex_parse", io_signature::make(1, 1, sizeof(gr_int32)), io_signature::make(0, 0, 0)), d_queue(queue), d_freq(freq) { d_count = 0; } flex_parse_impl::~flex_parse_impl() { } int flex_parse_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const gr_int32 *in = (const gr_int32 *)input_items[0]; int i = 0; while(i < noutput_items) { // Accumulate one whole frame's worth of data words (88 of them) d_datawords[d_count] = *in++; i++; if(++d_count == 88) { parse_data(); d_count = 0; } } return i; } /* FLEX data frames (that is, 88 data words per phase recovered after sync, symbol decoding, dephasing, deinterleaving, error correction, and conversion from codewords to data words) start with a block information word containing indices of the page address field and page vector fields. */ void flex_parse_impl::parse_capcode(int aw1, int aw2) { d_laddr = (aw1 < 0x008001L) || (aw1 > 0x1E0000L) || (aw1 > 0x1E7FFEL); if(d_laddr) d_capcode = aw1+((aw2^0x001FFFFF)<<15)+0x1F9000; // Don't ask else d_capcode = aw1-0x8000; } void flex_parse_impl::parse_data() { // Block information word is the first data word in frame int biw = d_datawords[0]; // Nothing to see here, please move along if(biw == 0 || biw == 0x001FFFFF) return; // Vector start index is bits 15-10 // Address start address is bits 9-8, plus one for offset int voffset = (biw >> 10) & 0x3f; int aoffset = ((biw >> 8) & 0x03) + 1; //printf("BIW:%08X AW:%02i-%02i\n", biw, aoffset, voffset); // Iterate through pages and dispatch to appropriate handler for(int i = aoffset; i < voffset; i++) { int j = voffset+i-aoffset; // Start of vector field for address @ i if(d_datawords[i] == 0x00000000 || d_datawords[i] == 0x001FFFFF) continue; // Idle codewords, invalid address parse_capcode(d_datawords[i], d_datawords[i+1]); if(d_laddr) i++; if(d_capcode < 0) // Invalid address, skip continue; // Parse vector information word for address @ offset 'i' int viw = d_datawords[j]; d_type = (page_type_t)((viw >> 4) & 0x00000007); int mw1 = (viw >> 7) & 0x00000007F; int len = (viw >> 14) & 0x0000007F; if(is_numeric_page(d_type)) len &= 0x07; int mw2 = mw1+len; if(mw1 == 0 && mw2 == 0) continue; // Invalid VIW if(is_tone_page(d_type)) mw1 = mw2 = 0; if(mw1 > 87 || mw2 > 87) continue; // Invalid offsets d_payload.str(""); d_payload.setf(std::ios::showpoint); d_payload << std::setprecision(6) << std::setw(7) << d_freq/1e6 << FIELD_DELIM << std::setw(10) << d_capcode << FIELD_DELIM << flex_page_desc[d_type] << FIELD_DELIM; if(is_alphanumeric_page(d_type)) parse_alphanumeric(mw1, mw2-1, j); else if(is_numeric_page(d_type)) parse_numeric(mw1, mw2, j); else if(is_tone_page(d_type)) parse_tone_only(); else parse_unknown(mw1, mw2); message::sptr msg = message::make_from_string(std::string(d_payload.str())); d_queue->handle(msg); } } void flex_parse_impl::parse_alphanumeric(int mw1, int mw2, int j) { int frag; //bool cont; if(!d_laddr) { frag = (d_datawords[mw1] >> 11) & 0x03; //cont = (d_datawords[mw1] >> 10) & 0x01; mw1++; } else { frag = (d_datawords[j+1] >> 11) & 0x03; //cont = (d_datawords[j+1] >> 10) & 0x01; mw2--; } //d_payload << frag << FIELD_DELIM; //d_payload << cont << FIELD_DELIM; for(int i = mw1; i <= mw2; i++) { int dw = d_datawords[i]; unsigned char ch; if(i > mw1 || frag != 0x03) { ch = dw & 0x7F; if(ch != 0x03) d_payload << ch; } ch = (dw >> 7) & 0x7F; if(ch != 0x03) // Fill d_payload << ch; ch = (dw >> 14) & 0x7F; if(ch != 0x03) // Fill d_payload << ch; } } void flex_parse_impl::parse_numeric(int mw1, int mw2, int j) { // Get first dataword from message field or from second // vector word if long address int dw; if(!d_laddr) { dw = d_datawords[mw1]; mw1++; mw2++; } else { dw = d_datawords[j+1]; } unsigned char digit = 0; int count = 4; if(d_type == FLEX_NUMBERED_NUMERIC) count += 10; // Skip 10 header bits for numbered numeric pages else count += 2; // Otherwise skip 2 for(int i = mw1; i <= mw2; i++) { for(int k = 0; k < 21; k++) { // Shift LSB from data word into digit digit = (digit >> 1) & 0x0F; if(dw & 0x01) digit ^= 0x08; dw >>= 1; if(--count == 0) { if(digit != 0x0C) // Fill d_payload << flex_bcd[digit]; count = 4; } } dw = d_datawords[i]; } } void flex_parse_impl::parse_tone_only() { } void flex_parse_impl::parse_unknown(int mw1, int mw2) { } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/gnuradio-pager.rc.in0000664000175000017500000000332212207440367021442 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ PRODUCTVERSION @MAJOR_VERSION@,@API_COMPAT@,@RC_MINOR_VERSION@,@RC_MAINT_VERSION@ FILEFLAGSMASK 0x3fL #ifndef NDEBUG FILEFLAGS 0x0L #else FILEFLAGS 0x1L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_INSTALLABLE BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "gnuradio-pager" VALUE "FileVersion", "@VERSION@" VALUE "InternalName", "gnuradio-pager.dll" VALUE "LegalCopyright", "Licensed under GPLv3 or any later version" VALUE "OriginalFilename", "gnuradio-pager.dll" VALUE "ProductName", "gnuradio-pager" VALUE "ProductVersion", "@VERSION@" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END gnuradio-3.7.2.1/gr-pager/lib/flex_deinterleave_impl.h0000664000175000017500000000307312207440367022465 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_DEINTERLEAVE_IMPL_H #define INCLUDED_PAGER_FLEX_DEINTERLEAVE_IMPL_H #include #include namespace gr { namespace pager { /*! * \brief flex deinterleave description * \ingroup pager_blk */ class flex_deinterleave_impl : public flex_deinterleave { private: // One FLEX block of deinterleaved data int d_codewords[8]; public: flex_deinterleave_impl(); ~flex_deinterleave_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_DEINTERLEAVE_IMPL_H */ gnuradio-3.7.2.1/gr-pager/lib/flex_modes.h0000664000175000017500000000424312207440367020104 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_MODES_H #define INCLUDED_PAGER_FLEX_MODES_H #include namespace gr { namespace pager { #define FLEX_SYNC_MARKER 0xA6C6AAAA typedef struct flex_mode { int32_t sync; // Outer synchronization code unsigned int baud; // Baudrate of SYNC2 and DATA unsigned int levels; // FSK encoding of SYNC2 and DATA } flex_mode_t; extern const flex_mode_t flex_modes[]; extern const char *flex_page_desc[]; extern const int num_flex_modes; int find_flex_mode(int32_t sync_code); extern unsigned char flex_bcd[]; typedef enum { FLEX_SECURE, FLEX_UNKNOWN, FLEX_TONE, FLEX_STANDARD_NUMERIC, FLEX_SPECIAL_NUMERIC, FLEX_ALPHANUMERIC, FLEX_BINARY, FLEX_NUMBERED_NUMERIC, NUM_FLEX_PAGE_TYPES } page_type_t; inline bool is_alphanumeric_page(page_type_t type) { return (type == FLEX_ALPHANUMERIC || type == FLEX_SECURE); } inline bool is_numeric_page(page_type_t type) { return (type == FLEX_STANDARD_NUMERIC || type == FLEX_SPECIAL_NUMERIC || type == FLEX_NUMBERED_NUMERIC); } inline bool is_tone_page(page_type_t type) { return (type == FLEX_TONE); } } /* namespace pager */ } /* namespace gr */ #endif // INCLUDED_PAGER_FLEX_MODES_H gnuradio-3.7.2.1/gr-pager/lib/bch3221.h0000664000175000017500000000221612207440367017021 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_BCH3221_H #define INCLUDED_PAGER_BCH3221_H namespace gr { namespace pager { // Perform BCH (32,21) error correction on supplied data // Return number of errors found/corrected (0, 1, or 2) int bch3221(int &data); } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_BCH3221_H */ gnuradio-3.7.2.1/gr-pager/lib/slicer_fb_impl.h0000664000175000017500000000307512207440367020732 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2007,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_SLICER_FB_IMPL_H #define INCLUDED_PAGER_SLICER_FB_IMPL_H #include namespace gr { namespace pager { class slicer_fb_impl : public slicer_fb { private: unsigned char slice(float sample); float d_alpha; // DC removal time constant float d_beta; // 1.0-d_alpha float d_avg; // Average value for DC offset subtraction public: slicer_fb_impl(float alpha); ~slicer_fb_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); float dc_offset() const { return d_avg; } }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_SLICER_FB_IMPL_H */ gnuradio-3.7.2.1/gr-pager/lib/slicer_fb_impl.cc0000664000175000017500000000454412207440367021072 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2007,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "slicer_fb_impl.h" #include namespace gr { namespace pager { slicer_fb::sptr slicer_fb::make(float alpha) { return gnuradio::get_initial_sptr (new slicer_fb_impl(alpha)); } slicer_fb_impl::slicer_fb_impl(float alpha) : sync_block("slicer_fb", io_signature::make(1, 1, sizeof(float)), io_signature::make(1, 1, sizeof(unsigned char))) { d_alpha = alpha; d_beta = 1.0-alpha; d_avg = 0.0; } slicer_fb_impl::~slicer_fb_impl() { } // Tracks average, minimum, and peak, then converts input into one of: // // [0, 1, 2, 3] unsigned char slicer_fb_impl::slice(float sample) { unsigned char decision; // Update DC level and remove d_avg = d_avg*d_beta+sample*d_alpha; sample -= d_avg; if(sample > 0) { if(sample > 2.0) decision = 3; else decision = 2; } else { if(sample < -2.0) decision = 0; else decision = 1; } return decision; } int slicer_fb_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { float *iptr = (float *)input_items[0]; unsigned char *optr = (unsigned char *)output_items[0]; int size = noutput_items; for(int i = 0; i < size; i++) *optr++ = slice(*iptr++); return noutput_items; } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/flex_deinterleave_impl.cc0000664000175000017500000000627112207440367022626 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "flex_deinterleave_impl.h" #include "bch3221.h" #include "util.h" #include namespace gr { namespace pager { flex_deinterleave::sptr flex_deinterleave::make() { return gnuradio::get_initial_sptr (new flex_deinterleave_impl()); } flex_deinterleave_impl::flex_deinterleave_impl() : sync_decimator("flex_deinterleave", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(1, 1, sizeof(int)), 32) { set_output_multiple(8); // One FLEX block at a time } flex_deinterleave_impl::~flex_deinterleave_impl() { } int flex_deinterleave_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *)input_items[0]; int *out = (int *)output_items[0]; // FLEX codewords are interleaved in blocks of 256 bits or 8, 32 // bit codes. To deinterleave we parcel each incoming bit into // the MSB of each codeword, then switch to MSB-1, etc. This is // done by shifting in the bits from the right on each codeword // as the bits come in. When we are done we have a FLEX block of // eight codewords, ready for conversion to data words. // // FLEX data words are recovered by reversing the bit order of // the code word, masking off the (reversed) ECC, and inverting // the remainder of the bits (!). // // The data portion of a FLEX frame consists of 11 of these // deinterleaved and converted blocks. // // set_output_multiple garauntees we have output space for at // least eight data words, and 256 bits are supplied on input int i, j; for(i = 0; i < 32; i++) { for(j = 0; j < 8; j++) { d_codewords[j] <<= 1; d_codewords[j] |= *in++; } } // Now convert code words into data words for(j = 0; j < 8; j++) { int codeword = d_codewords[j]; // Apply BCH 32,21 error correction // TODO: mark dataword when codeword fails ECC bch3221(codeword); // Reverse bit order codeword = reverse_bits32(codeword); // Mask off ECC then invert lower 21 bits codeword = (codeword & 0x001FFFFF)^0x001FFFFF; *out++ = codeword; } return j; } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/flex_parse_impl.h0000664000175000017500000000441412207440367021130 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_PARSE_IMPL_H #define INCLUDED_PAGER_FLEX_PARSE_IMPL_H #include #include #include #include "flex_modes.h" #include namespace gr { namespace pager { #define FIELD_DELIM ((unsigned char)128) class flex_parse_impl : public flex_parse { private: std::ostringstream d_payload; msg_queue::sptr d_queue; // Destination for decoded pages int d_count; // Count of received codewords int d_datawords[88]; // 11 blocks of 8 32-bit words page_type_t d_type; // Current page type int d_capcode; // Current page destination address bool d_laddr; // Current page has long address float d_freq; // Channel frequency void parse_data(); // Handle a frame's worth of data void parse_capcode(int32_t aw1, int32_t aw2); void parse_alphanumeric(int mw1, int mw2, int j); void parse_numeric(int mw1, int mw2, int j); void parse_tone_only(); void parse_unknown(int mw1, int mw2); public: flex_parse_impl(msg_queue::sptr queue, float freq); ~flex_parse_impl(); int work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_PARSE_IMPL_H */ gnuradio-3.7.2.1/gr-pager/lib/bch3221.cc0000664000175000017500000000225512207440367017162 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "bch3221.h" namespace gr { namespace pager { // Corrects supplied data word according to BCH3221 encoding and // returns the number of errors detected/corrected. // // Not implemented yet int bch3221(int &data) { return 0; } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/flex_sync_impl.h0000664000175000017500000000545312207440367020776 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PAGER_FLEX_SYNC_IMPL_H #define INCLUDED_PAGER_FLEX_SYNC_IMPL_H #include namespace gr { namespace pager { class flex_sync_impl : public flex_sync { private: // State machine transitions void enter_idle(); void enter_syncing(); void enter_sync1(); void enter_sync2(); void enter_data(); int index_avg(int start, int end); bool test_sync(unsigned char sym); void parse_fiw(); int output_symbol(unsigned char sym); // Simple state machine enum state_t { ST_IDLE, ST_SYNCING, ST_SYNC1, ST_SYNC2, ST_DATA }; state_t d_state; int d_index; // Index into current baud int d_start; // Start of good sync int d_center; // Center of bit int d_end; // End of good sync int d_count; // Bit counter int d_mode; // Current packet mode int d_baudrate; // Current decoding baud rate int d_levels; // Current decoding levels int d_spb; // Current samples per baud bool d_hibit; // Alternating bit indicator for 3200 bps int d_fiw; // Frame information word int d_frame; // Current FLEX frame int d_cycle; // Current FLEX cycle int d_unknown1; int d_unknown2; unsigned char d_bit_a; unsigned char d_bit_b; unsigned char d_bit_c; unsigned char d_bit_d; unsigned char *d_phase_a; unsigned char *d_phase_b; unsigned char *d_phase_c; unsigned char *d_phase_d; std::vector d_sync; // Trial synchronizers public: flex_sync_impl(); ~flex_sync_impl(); void forecast(int noutput_items, gr_vector_int &inputs_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } /* namespace pager */ } /* namespace gr */ #endif /* INCLUDED_PAGER_FLEX_SYNC_IMPL_H */ gnuradio-3.7.2.1/gr-pager/lib/flex_sync_impl.cc0000664000175000017500000002374212207440367021135 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2004,2006,2010,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "flex_sync_impl.h" #include "flex_modes.h" #include "bch3221.h" #include "util.h" #include #include #include namespace gr { namespace pager { flex_sync::sptr flex_sync::make() { return gnuradio::get_initial_sptr (new flex_sync_impl()); } // FLEX sync block takes input from sliced baseband stream [0-3] // at specified channel rate. Symbol timing is established based // on receiving one of the defined FLEX protocol synchronization // words. The block outputs one FLEX frame worth of bits on each // output phase for the data portion of the frame. Unused phases // get all zeros, which are considered idle code words. flex_sync_impl::flex_sync_impl() : block("flex_sync", io_signature::make(1, 1, sizeof(unsigned char)), io_signature::make(4, 4, sizeof(unsigned char))), d_sync(10) // Fixed at 10 samples per baud (@ 1600 baud) { enter_idle(); } flex_sync_impl::~flex_sync_impl() { } void flex_sync_impl::forecast(int noutput_items, gr_vector_int &inputs_required) { // samples per bit X number of outputs needed int items = noutput_items*d_spb; for(unsigned int i = 0; i < inputs_required.size(); i++) inputs_required[i] = items; } int flex_sync_impl::index_avg(int start, int end) { // modulo average if(start < end) return (end + start)/2; else return ((end + start)/2 + d_spb/2) % d_spb; } bool flex_sync_impl::test_sync(unsigned char sym) { // 64-bit FLEX sync code: // AAAA:BBBBBBBB:CCCC // // Where BBBBBBBB is always 0xA6C6AAAA // and AAAA^CCCC is 0xFFFF // // Specific values of AAAA determine what bps and encoding the // packet is beyond the frame information word // // First we match on the marker field with a hamming distance < 4 // Then we match on the outer code with a hamming distance < 4 d_sync[d_index] = (d_sync[d_index] << 1) | (sym < 2); int64_t val = d_sync[d_index]; int32_t marker = ((val & 0x0000FFFFFFFF0000ULL)) >> 16; if(gr::blocks::count_bits32(marker^FLEX_SYNC_MARKER) < 4) { int32_t code = ((val & 0xFFFF000000000000ULL) >> 32) | (val & 0x000000000000FFFFULL); for(int i = 0; i < num_flex_modes; i++) { if(gr::blocks::count_bits32(code^flex_modes[i].sync) < 4) { d_mode = i; return true; } } // Marker received but doesn't match known codes // All codes have high word inverted to low word unsigned short high = (code & 0xFFFF0000) >> 16; unsigned short low = code & 0x0000FFFF; unsigned short syn = high^low; if(syn == 0xFFFF) fprintf(stderr, "Unknown sync code detected: %08X\n", code); } return false; } void flex_sync_impl::enter_idle() { d_state = ST_IDLE; d_index = 0; d_start = 0; d_center = 0; d_end = 0; d_count = 0; d_mode = 0; d_baudrate = 1600; d_levels = 2; d_spb = 16000/d_baudrate; d_bit_a = 0; d_bit_b = 0; d_bit_c = 0; d_bit_d = 0; d_hibit = false; fflush(stdout); } void flex_sync_impl::enter_syncing() { d_start = d_index; d_state = ST_SYNCING; } void flex_sync_impl::enter_sync1() { d_state = ST_SYNC1; d_end = d_index; d_center = index_avg(d_start, d_end); // Center of goodness d_count = 0; } void flex_sync_impl::enter_sync2() { d_state = ST_SYNC2; d_count = 0; d_baudrate = flex_modes[d_mode].baud; d_levels = flex_modes[d_mode].levels; d_spb = 16000/d_baudrate; if(d_baudrate == 3200) { // Oversampling buffer just got halved d_center = d_center/2; // We're here at the center of a 1600 baud bit // So this hack puts the index and bit counter // in the right place for 3200 bps. d_index = d_index/2-d_spb/2; d_count = -1; } } void flex_sync_impl::enter_data() { d_state = ST_DATA; d_count = 0; } void flex_sync_impl::parse_fiw() { // Nothing is done with these now, but these will end up getting // passed as metadata when mblocks are available // Bits 31-28 are frame number related, but unknown function // This might be a checksum d_unknown2 = reverse_bits8((d_fiw >> 24) & 0xF0); // Cycle is bits 27-24, reversed d_cycle = reverse_bits8((d_fiw >> 20) & 0xF0); // Frame is bits 23-17, reversed d_frame = reverse_bits8((d_fiw >> 16) & 0xFE); // Bits 16-11 are some sort of marker, usually identical across // many frames but sometimes changes between frames or modes d_unknown1 = (d_fiw >> 11) & 0x3F; //printf("CYC:%02i FRM:%03i\n", d_cycle, d_frame); } int flex_sync_impl::output_symbol(unsigned char sym) { // Here is where we output a 1 or 0 on each phase according // to current FLEX mode and symbol value. Unassigned phases // are zero from the enter_idle() initialization. // // FLEX can transmit the data portion of the frame at either // 1600 bps or 3200 bps, and can use either two- or four-level // FSK encoding. // // At 1600 bps, 2-level, a single "phase" is transmitted with bit // value '0' using level '3' and bit value '1' using level '0'. // // At 1600 bps, 4-level, a second "phase" is transmitted, and the // di-bits are encoded with a gray code: // // Symbol Phase 1 Phase 2 // ------ ------- ------- // 0 1 1 // 1 1 0 // 2 0 0 // 3 0 1 // // At 1600 bps, 4-level, these are called PHASE A and PHASE B. // // At 3200 bps, the same 1 or 2 bit encoding occurs, except that // additionally two streams are interleaved on alternating symbols. // Thus, PHASE A (and PHASE B if 4-level) are decoded on one symbol, // then PHASE C (and PHASE D if 4-level) are decoded on the next. int bits = 0; if(d_baudrate == 1600) { d_bit_a = (sym < 2); if(d_levels == 4) d_bit_b = (sym == 0) || (sym == 3); *d_phase_a++ = d_bit_a; *d_phase_b++ = d_bit_b; *d_phase_c++ = d_bit_c; *d_phase_d++ = d_bit_d; bits++; } else { if(!d_hibit) { d_bit_a = (sym < 2); if(d_levels == 4) d_bit_b = (sym == 0) || (sym == 3); d_hibit = true; } else { d_bit_c = (sym < 2); if(d_levels == 4) d_bit_d = (sym == 0) || (sym == 3); d_hibit = false; *d_phase_a++ = d_bit_a; *d_phase_b++ = d_bit_b; *d_phase_c++ = d_bit_c; *d_phase_d++ = d_bit_d; bits++; } } return bits; } int flex_sync_impl::general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *)input_items[0]; d_phase_a = (unsigned char *)output_items[0]; d_phase_b = (unsigned char *)output_items[1]; d_phase_c = (unsigned char *)output_items[2]; d_phase_d = (unsigned char *)output_items[3]; int i = 0, j = 0; int ninputs = ninput_items[0]; while(i < ninputs && j < noutput_items) { unsigned char sym = *in++; i++; d_index = (d_index+1) % d_spb; switch(d_state) { case ST_IDLE: // Continually compare the received symbol stream // against the known FLEX sync words. if(test_sync(sym)) enter_syncing(); break; case ST_SYNCING: // Wait until we stop seeing sync, then calculate // the center of the bit period (d_center) if(!test_sync(sym)) enter_sync1(); break; case ST_SYNC1: // Skip 16 bits of dotting, then accumulate 32 bits // of Frame Information Word. if(d_index == d_center) { d_fiw = (d_fiw << 1) | (sym > 1); if(++d_count == 48) { // FIW is accumulated, call BCH to error correct it bch3221(d_fiw); parse_fiw(); enter_sync2(); } } break; case ST_SYNC2: // This part and the remainder of the frame are transmitted // at either 1600 bps or 3200 bps based on the received // FLEX sync word. The second SYNC header is 25ms of idle bits // at either speed. if(d_index == d_center) { // Skip 25 ms = 40 bits @ 1600 bps, 80 @ 3200 bps if(++d_count == d_baudrate/40) enter_data(); } break; case ST_DATA: // The data portion of the frame is 1760 ms long at either // baudrate. This is 2816 bits @ 1600 bps and 5632 bits @ 3200 bps. // The output_symbol() routine decodes and doles out the bits // to each of the four transmitted phases of FLEX interleaved codes. if(d_index == d_center) { j += output_symbol(sym); if(++d_count == d_baudrate*1760/1000) enter_idle(); } break; default: assert(0); // memory corruption of d_state if ever gets here break; } } consume_each(i); return j; } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/flex_frame_impl.cc0000664000175000017500000000226712207440367021252 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "flex_frame_impl.h" namespace gr { namespace pager { flex_frame::sptr flex_frame::make() { return flex_frame::sptr (new flex_frame_impl()); } flex_frame_impl::flex_frame_impl() { } flex_frame_impl::~flex_frame_impl() { } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/lib/util.cc0000664000175000017500000000331012207440367017064 0ustar jcorganjcorgan/* -*- c++ -*- */ /* * Copyright 2006,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "util.h" namespace gr { namespace pager { unsigned char reverse_bits8(unsigned char val) { // This method was attributed to Rich Schroeppel in the Programming // Hacks section of Beeler, M., Gosper, R. W., and Schroeppel, R. // HAKMEM. MIT AI Memo 239, Feb. 29, 1972. // // Reverses 8 bits in 5 machine operations with 64 bit arch return (val * 0x0202020202ULL & 0x010884422010ULL) % 1023; } int32_t reverse_bits32(int32_t val) { int32_t out = 0x00000000; out |= (reverse_bits8((val >> 24) & 0x000000FF) ); out |= (reverse_bits8((val >> 16) & 0x000000FF) << 8); out |= (reverse_bits8((val >> 8) & 0x000000FF) << 16); out |= (reverse_bits8((val ) & 0x000000FF) << 24); return out; } } /* namespace pager */ } /* namespace gr */ gnuradio-3.7.2.1/gr-pager/swig/0000755000175000017500000000000012207440367016004 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/swig/CMakeLists.txt0000664000175000017500000000342712207440367020554 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup swig generation ######################################################################## include(GrPython) include(GrSwig) set(GR_SWIG_INCLUDE_DIRS ${GR_PAGER_INCLUDE_DIRS} ${GNURADIO_RUNTIME_SWIG_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) if(ENABLE_GR_CTRLPORT) list(APPEND GR_SWIG_FLAGS "-DGR_CTRLPORT") list(APPEND GR_SWIG_INCLUDE_DIRS ${ICE_INCLUDE_DIR}) endif(ENABLE_GR_CTRLPORT) set(GR_SWIG_DOC_FILE ${CMAKE_CURRENT_BINARY_DIR}/pager_swig_doc.i) set(GR_SWIG_DOC_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/../include/gnuradio/pager) set(GR_SWIG_DOCS_TARGET_DEPS runtime_swig_swig_doc) set(GR_SWIG_LIBRARIES gnuradio-pager) GR_SWIG_MAKE(pager_swig pager_swig.i) GR_SWIG_INSTALL( TARGETS pager_swig DESTINATION ${GR_PYTHON_DIR}/gnuradio/pager COMPONENT "pager_python" ) install( FILES pager_swig.i ${CMAKE_CURRENT_BINARY_DIR}/pager_swig_doc.i DESTINATION ${GR_INCLUDE_DIR}/gnuradio/swig COMPONENT "pager_swig" ) gnuradio-3.7.2.1/gr-pager/swig/pager_swig.i0000664000175000017500000000300712207440367020307 0ustar jcorganjcorgan/* * Copyright 2005,2006,2009,2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #define PAGER_API %include "gnuradio.i" //load generated python docstrings %include "pager_swig_doc.i" %{ #include "gnuradio/pager/flex_frame.h" #include "gnuradio/pager/slicer_fb.h" #include "gnuradio/pager/flex_sync.h" #include "gnuradio/pager/flex_deinterleave.h" #include "gnuradio/pager/flex_parse.h" %} %include "gnuradio/pager/flex_frame.h" %include "gnuradio/pager/slicer_fb.h" %include "gnuradio/pager/flex_sync.h" %include "gnuradio/pager/flex_deinterleave.h" %include "gnuradio/pager/flex_parse.h" GR_SWIG_BLOCK_MAGIC2(pager, flex_frame); GR_SWIG_BLOCK_MAGIC2(pager, slicer_fb); GR_SWIG_BLOCK_MAGIC2(pager, flex_sync); GR_SWIG_BLOCK_MAGIC2(pager, flex_deinterleave); GR_SWIG_BLOCK_MAGIC2(pager, flex_parse); gnuradio-3.7.2.1/gr-pager/README0000644000175000017500000000713511744612271015721 0ustar jcorganjcorganThis GNU Radio component implements a FLEX radiopager receiver/demodulator. FLEX pager towers are between 929 MHz and 932 MHz at 25 KHz centers. Current status (7/16/07): FLEX receiving is completed except for addition of BCH error correction. There are three scripts: usrp_flex.py - Receives and displays pages from a single paging channel. To work from recorded data, record from USRP with decimation 256 at center frequency. Usage: usrp_flex.py [options] Options: -h, --help show this help message and exit -f Hz, --frequency=Hz set receive frequency to Hz -R SUBDEV, --rx-subdev-spec=SUBDEV select USRP Rx side A or B -c Hz, --calibration=Hz set frequency offset to Hz -g dB, --gain=dB set RF gain -l, --log log flowgraph to files (LOTS of data) -v, --verbose display debug output -F FROM_FILE, --from-file=FROM_FILE read samples from file instead of USRP Example, to receive from 931.95M (a common nationwide channel) with DBSRX in side A of USRP: $ usrp_flex.py -f 931.95M -g 32 -R A usrp_flex_band.py - Receives and displays pages from a 1 MHz paging band (40 pager channels.) To work from recorded data, record from USRP with decimation 64 at center frequency. Usage: usrp_flex_band.py [options] Options: -h, --help show this help message and exit -f Hz, --frequency=Hz set receive center frequency to Hz -R SUBDEV, --rx-subdev-spec=SUBDEV select USRP Rx side A or B -c Hz, --calibration=Hz set frequency offset to Hz -g dB, --gain=dB set RF gain -F FROM_FILE, --from-file=FROM_FILE Read from file instead of USRP -l, --log log flowgraph to files (LOTS of data) -v, --verbose display debug output Example, to receive from the lower third of the pager band with DBSRX in side B of USRP: $ usrp_flex_band.py -f 929.5M -g 32 -R B usrp_flex_all.py - Receives and displays pages from entire pager band (3 MHz, 120 pager channels.) This does not work in real time due to CPU limitations, but can work from recorded USRP data. To work from recorded data, record from USRP with decimation 20 at center frequency of 930.5M. Usage: usrp_flex_all.py [options] Options: -h, --help show this help message and exit -R SUBDEV, --rx-subdev-spec=SUBDEVC select USRP Rx side A or B -c Hz, --calibration=Hz set frequency offset to Hz -g dB, --gain=dB set RF gain -F FROM_FILE, --from-file=FROM_FILE Read from file instead of USRP -l, --log log flowgraph to files (LOTS of data) -v, --verbose display debug output Example, to receive all pager channels with DBSRX in side A: $ usrp_flex_all.py -R A The demodulator is relatively sensitive to frequency offset and can capture a signal within 3k of the actual signal. All three scripts take a 'calibration' parameter, which specifies the frequency offset of the daughterboard. This causes the USRP to be tuned to the given center frequency plus the calibration offset. For example, if your DBSRX shows 930MHz as 930.001MHz in usrp_fft.py, then use '-c 1k' in the command line to automatically add this. Johnathan Corgan Corgan Enterprises LLC jcorgan@corganenterprises.com gnuradio-3.7.2.1/gr-pager/apps/0000755000175000017500000000000012207440367015776 5ustar jcorganjcorgangnuradio-3.7.2.1/gr-pager/apps/CMakeLists.txt0000644000175000017500000000166211744612271020543 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) GR_PYTHON_INSTALL( PROGRAMS usrp_flex usrp_flex_all usrp_flex_band DESTINATION ${GR_RUNTIME_DIR} COMPONENT "pager_python" ) gnuradio-3.7.2.1/gr-pager/apps/usrp_flex_all0000775000175000017500000001477012207440367020576 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2009,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, uhd, eng_notation, pager from gnuradio import blocks from gnuradio import filter from gnuradio.eng_option import eng_option from optparse import OptionParser from string import split, join, printable import sys class app_top_block(gr.top_block): def __init__(self, options, queue): gr.top_block.__init__(self, "usrp_flex_all") if options.from_file is not None: self.u = blocks.file_source(gr.sizeof_gr_complex, options.from_file) self.nchan = options.nchan if options.verbose: print "Reading samples from file", options.from_file print "User specified file contains", options.nchan, "25 KHz channels." else: # Set up USRP source self.u = uhd.usrp_source(device_addr=options.address, stream_args=uhd.stream_args('fc32')) # Tune daughterboard r = self.u.set_center_freq(options.freq+options.calibration, 0) if not r: frange = self.u.get_freq_range() sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ (freq, frange.start(), frange.stop())) sys.exit(1) if options.verbose: print "Tuned to center frequency", (options.freq+options.calibration)/1e6, "MHz" # if no gain was specified, use the mid-point in dB if options.rx_gain is None: grange = self.u.get_gain_range() options.rx_gain = float(grange.start()+grange.stop())/2.0 print "\nNo gain specified." print "Setting gain to %f (from [%f, %f])" % \ (options.rx_gain, grange.start(), grange.stop()) self.u.set_gain(options.rx_gain, 0) # Grab >=3 MHz of spectrum, evenly divisible by 25 KHz channels # (A UHD facility to get sample rate range and granularity would be useful) self.u.set_samp_rate(3.125e6) # Works if USRP is 100 Msps and can decimate by 32 rate = self.u.get_samp_rate() if rate != 3.125e6: self.u.set_samp_rate(3.2e6) # Works if USRP is 64 Msps and can decimate by 20 rate = self.u.get_samp_rate() if (rate != 3.2e6): print "Unable to set required sample rate for >= 3MHz of 25 KHz channels." sys.exit(1) self.nchan = int(rate/25e3) if options.verbose: print "\nReceiving", rate/1e6, "MHz of bandwidth containing", self.nchan, "baseband channels." taps = filter.firdes.low_pass(1.0, 1.0, 1.0/self.nchan*0.4, 1.0/self.nchan*0.1, filter.firdes.WIN_HANN) if options.verbose: print "Channel filter has", len(taps), "taps" self.bank = filter.analysis_filterbank(self.nchan, taps) self.connect(self.u, self.bank) if options.log and options.from_file == None: src_sink = blocks.file_sink(gr.sizeof_gr_complex, 'usrp.dat') self.connect(self.u, src_sink) mid_chan = int(self.nchan/2) for i in range(self.nchan): if i < mid_chan: freq = options.freq+i*25e3 else: freq = options.freq-(self.nchan-i)*25e3 if (freq < 929.0e6 or freq > 932.0e6): self.connect((self.bank, i), blocks.null_sink(gr.sizeof_gr_complex)) else: self.connect((self.bank, i), pager.flex_demod(queue, freq, options.verbose, options.log)) if options.log: self.connect((self.bank, i), blocks.file_sink(gr.sizeof_gr_complex, 'chan_'+'%3.3f'%(freq/1e6)+'.dat')) def get_options(): parser = OptionParser(option_class=eng_option) parser.add_option('-f', '--freq', type="eng_float", default=929.5125e6, help="Set receive frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--rx-gain", type="eng_float", default=None, help="set receive gain in dB (default is midpoint)") parser.add_option("-c", "--calibration", type="eng_float", default=0.0, help="set frequency offset to Hz", metavar="Hz") parser.add_option("-v", "--verbose", action="store_true", default=False) parser.add_option("-l", "--log", action="store_true", default=False, help="log flowgraph to files (LOTS of data)") parser.add_option("-F", "--from-file", default=None, help="read samples from file instead of USRP") parser.add_option("", "--nchan", type="int", default=None, help="set to number of channels in capture file", metavar="nchan") (options, args) = parser.parse_args() if len(args) > 0: print "Run 'usrp_flex_all.py -h' for options." sys.exit(1) if options.nchan is None and options.from_file is not None: print "You must specify the number of baseband channels with --nchan when reading from a file" sys.exit(1) return (options, args) def main(): (options, args) = get_options() queue = gr.msg_queue() tb = app_top_block(options, queue) runner = pager.queue_runner(queue) try: tb.run() except KeyboardInterrupt: pass runner.end() if __name__ == "__main__": main() gnuradio-3.7.2.1/gr-pager/apps/usrp_flex0000775000175000017500000001434212207440367017741 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2009,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gru, uhd, eng_notation, pager from gnuradio import filter from gnuradio.filter import optfir from gnuradio import blocks from gnuradio.eng_option import eng_option from optparse import OptionParser import time, os, sys class app_top_block(gr.top_block): def __init__(self, options, queue): gr.top_block.__init__(self, "usrp_flex") self.options = options self.offset = 0.0 self.adj_time = time.time() self.verbose = options.verbose if options.from_file is None: # Set up USRP source self.u = uhd.usrp_source(device_addr=options.address, stream_args=uhd.stream_args('fc32')) # Grab 250 KHz of spectrum # (A UHD facility to get sample rate range and granularity would be useful) self.u.set_samp_rate(250e3) rate = self.u.get_samp_rate() if rate != 250e3: print "Unable to set required sample rate of 250 Ksps (got %f)" % rate sys.exit(1) # Tune daughterboard r = self.u.set_center_freq(options.freq+options.calibration, 0) if not r: frange = self.u.get_freq_range() sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ (freq, frange.start(), frange.stop())) sys.exit(1) # if no gain was specified, use the mid-point in dB if options.rx_gain is None: grange = self.u.get_gain_range() options.rx_gain = float(grange.start()+grange.stop())/2.0 print "\nNo gain specified." print "Setting gain to %f (from [%f, %f])" % \ (options.rx_gain, grange.start(), grange.stop()) self.u.set_gain(options.rx_gain, 0) else: # Use supplied file as source of samples self.u = blocks.file_source(gr.sizeof_gr_complex, options.from_file) if options.verbose: print "Reading samples from", options.from_file if options.log and not options.from_file: usrp_sink = blocks.file_sink(gr.sizeof_gr_complex, 'usrp.dat') self.connect(self.u, usrp_sink) # Set up 22KHz-wide bandpass about center frequency. Decimate by 10 # to get channel rate of 25Ksps taps = optfir.low_pass(1.0, # Filter gain 250e3, # Sample rate 11000, # One-sided modulation bandwidth 12500, # One-sided channel bandwidth 0.1, # Passband ripple 60) # Stopband attenuation if options.verbose: print "Channel filter has", len(taps), "taps." self.chan = filter.freq_xlating_fir_filter_ccf(10, # Decimation rate taps, # Filter taps 0.0, # Offset frequency 250e3) # Sample rate if options.log: chan_sink = blocks.file_sink(gr.sizeof_gr_complex, 'chan.dat') self.connect(self.chan, chan_sink) # FLEX protocol demodulator self.flex = pager.flex_demod(queue, options.freq, options.verbose, options.log) self.connect(self.u, self.chan, self.flex) def freq_offset(self): return self.flex.dc_offset()*1600 def adjust_freq(self): if time.time() - self.adj_time > 1.6: # Only do it once per FLEX frame self.adj_time = time.time() self.offset -= self.freq_offset() self.chan.set_center_freq(self.offset) if self.verbose: print "Channel frequency offset (Hz):", int(self.offset) def get_options(): parser = OptionParser(option_class=eng_option) parser.add_option('-f', '--freq', type="eng_float", default=None, help="Set receive frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--rx-gain", type="eng_float", default=None, help="set receive gain in dB (default is midpoint)") parser.add_option("-c", "--calibration", type="eng_float", default=0.0, help="set frequency offset to Hz", metavar="Hz") parser.add_option("-v", "--verbose", action="store_true", default=False) parser.add_option("-l", "--log", action="store_true", default=False, help="log flowgraph to files (LOTS of data)") parser.add_option("-F", "--from-file", default=None, help="read samples from file instead of USRP") (options, args) = parser.parse_args() if len(args) > 0: print "Run 'usrp_flex.py -h' for options." sys.exit(1) if (options.freq is None): sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") sys.exit(1) return (options, args) if __name__ == "__main__": (options, args) = get_options() # Flow graph emits pages into message queue queue = gr.msg_queue() tb = app_top_block(options, queue) runner = pager.queue_runner(queue) try: tb.run() except KeyboardInterrupt: pass runner.end() gnuradio-3.7.2.1/gr-pager/apps/usrp_flex_band0000775000175000017500000001236012207440367020723 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006,2007,2009,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, uhd, eng_notation, pager from gnuradio import blocks from gnuradio import filter from gnuradio.eng_option import eng_option from optparse import OptionParser import sys class app_top_block(gr.top_block): def __init__(self, options, queue): gr.top_block.__init__(self, "usrp_flex_all") if options.from_file is not None: self.u = blocks.file_source(gr.sizeof_gr_complex, options.from_file) if options.verbose: print "Reading samples from file", options.from_file else: # Set up USRP source self.u = uhd.usrp_source(device_addr=options.address, stream_args=uhd.stream_args('fc32')) # Grab 1 MHz of spectrum # (A UHD facility to get sample rate range and granularity would be useful) self.u.set_samp_rate(1e6) rate = self.u.get_samp_rate() if rate != 1e6: print "Unable to set required sample rate of 1 Msps (got %f)" % rate sys.exit(1) # Tune daughterboard r = self.u.set_center_freq(options.freq+options.calibration, 0) if not r: frange = self.u.get_freq_range() sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ (freq, frange.start(), frange.stop())) sys.exit(1) # if no gain was specified, use the mid-point in dB if options.rx_gain is None: grange = self.u.get_gain_range() options.rx_gain = float(grange.start()+grange.stop())/2.0 print "\nNo gain specified." print "Setting gain to %f (from [%f, %f])" % \ (options.rx_gain, grange.start(), grange.stop()) self.u.set_gain(options.rx_gain, 0) taps = filter.firdes.low_pass(1.0, 1.0, 1.0/40.0*0.4, 1.0/40.0*0.1, filter.firdes.WIN_HANN) if options.verbose: print "Channel filter has", len(taps), "taps" bank = filter.analysis_filterbank(40, taps) self.connect(self.u, bank) if options.log and options.from_file == None: src_sink = blocks.file_sink(gr.sizeof_gr_complex, 'usrp.dat') self.connect(self.u, src_sink) for i in range(40): if i < 20: freq = options.freq+i*25e3 else: freq = options.freq-0.5e6+(i-20)*25e3 self.connect((bank, i), pager.flex_demod(queue, freq, options.verbose, options.log)) if options.log: self.connect((bank, i), blocks.file_sink(gr.sizeof_gr_complex, 'chan_'+'%3.3f'%(freq/1e6)+'.dat')) def get_options(): parser = OptionParser(option_class=eng_option) parser.add_option('-f', '--freq', type="eng_float", default=None, help="Set receive frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-a", "--address", type="string", default="addr=192.168.10.2", help="Address of UHD device, [default=%default]") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--rx-gain", type="eng_float", default=None, help="set receive gain in dB (default is midpoint)") parser.add_option("-c", "--calibration", type="eng_float", default=0.0, help="set frequency offset to Hz", metavar="Hz") parser.add_option("-v", "--verbose", action="store_true", default=False) parser.add_option("-l", "--log", action="store_true", default=False, help="log flowgraph to files (LOTS of data)") parser.add_option("-F", "--from-file", default=None, help="read samples from file instead of USRP") (options, args) = parser.parse_args() if len(args) > 0: print "Run 'usrp_flex_band.py -h' for options." sys.exit(1) if (options.freq is None): sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") sys.exit(1) return (options, args) if __name__ == "__main__": (options, args) = get_options() queue = gr.msg_queue() tb = app_top_block(options, queue) runner = pager.queue_runner(queue) try: tb.run() except KeyboardInterrupt: pass runner.end() gnuradio-3.7.2.1/gr-pager/apps/usrp_rx_flex.py0000775000175000017500000004131112207440367021075 0ustar jcorganjcorgan#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: USRP FLEX Pager Receiver (Single Channel) # Generated: Thu Oct 29 11:03:16 2009 ################################################## from gnuradio import eng_notation from gnuradio import gr from gnuradio import blocks from gnuradio import filter from gnuradio import pager from gnuradio.eng_option import eng_option from gnuradio.filter import window from gnuradio.filter import firdes from gnuradio.wxgui import fftsink2 from gnuradio.wxgui import forms from gnuradio.wxgui import scopesink2 from grc_gnuradio import usrp as grc_usrp from grc_gnuradio import wxgui as grc_wxgui from optparse import OptionParser import ConfigParser import os, math import wx class usrp_rx_flex(grc_wxgui.top_block_gui): def __init__(self): grc_wxgui.top_block_gui.__init__(self, title="USRP FLEX Pager Receiver (Single Channel)") ################################################## # Variables ################################################## self.config_filename = config_filename = os.environ["HOME"]+"/.gnuradio/config.conf" self.symbol_rate = symbol_rate = 3200 self._saved_channel_config = ConfigParser.ConfigParser() self._saved_channel_config.read(config_filename) try: saved_channel = self._saved_channel_config.getint("gr-pager", "channel") except: saved_channel = 25 self.saved_channel = saved_channel self._saved_band_freq_config = ConfigParser.ConfigParser() self._saved_band_freq_config.read(config_filename) try: saved_band_freq = self._saved_band_freq_config.getfloat("gr-pager", "band_center") except: saved_band_freq = 930.5125e6 self.saved_band_freq = saved_band_freq self.deviation = deviation = 4800 self.decim = decim = 20 self.adc_rate = adc_rate = 64e6 self.sample_rate = sample_rate = adc_rate/decim self.passband = passband = 2*(deviation+symbol_rate) self.channel_rate = channel_rate = 8*3200 self.channel = channel = saved_channel self.band_freq = band_freq = saved_band_freq self._saved_rx_gain_config = ConfigParser.ConfigParser() self._saved_rx_gain_config.read(config_filename) try: saved_rx_gain = self._saved_rx_gain_config.getint("gr-pager", "rx_gain") except: saved_rx_gain = 40 self.saved_rx_gain = saved_rx_gain self._saved_offset_config = ConfigParser.ConfigParser() self._saved_offset_config.read(config_filename) try: saved_offset = self._saved_offset_config.getfloat("gr-pager", "freq_offset") except: saved_offset = 0 self.saved_offset = saved_offset self.freq = freq = band_freq+(channel-61)*25e3 self.channel_taps = channel_taps = firdes.low_pass(10, sample_rate, passband/2.0, (channel_rate-passband)/2.0) self.rx_gain = rx_gain = saved_rx_gain self.offset = offset = saved_offset self.nchan_taps = nchan_taps = len(channel_taps) self.ma_ntaps = ma_ntaps = int(channel_rate/symbol_rate) self.freq_text = freq_text = freq self.demod_k = demod_k = 3*channel_rate/(2*math.pi*deviation) self.channel_decim = channel_decim = int(sample_rate/channel_rate) self.bb_interp = bb_interp = 5 self.bb_decim = bb_decim = 8 self.baseband_rate = baseband_rate = 16000 ################################################## # Notebooks ################################################## self.displays = wx.Notebook(self.GetWin(), style=wx.NB_TOP) self.displays.AddPage(grc_wxgui.Panel(self.displays), "RX Spectrum") self.displays.AddPage(grc_wxgui.Panel(self.displays), "Baseband") self.GridAdd(self.displays, 1, 0, 1, 5) ################################################## # Controls ################################################## _channel_sizer = wx.BoxSizer(wx.VERTICAL) self._channel_text_box = forms.text_box( parent=self.GetWin(), sizer=_channel_sizer, value=self.channel, callback=self.set_channel, label="Channel", converter=forms.int_converter(), proportion=0, ) self._channel_slider = forms.slider( parent=self.GetWin(), sizer=_channel_sizer, value=self.channel, callback=self.set_channel, minimum=1, maximum=120, num_steps=119, style=wx.SL_HORIZONTAL, cast=int, proportion=1, ) self.GridAdd(_channel_sizer, 0, 1, 1, 1) self._band_freq_text_box = forms.text_box( parent=self.GetWin(), value=self.band_freq, callback=self.set_band_freq, label="Band Freq.", converter=forms.float_converter(), ) self.GridAdd(self._band_freq_text_box, 0, 0, 1, 1) _rx_gain_sizer = wx.BoxSizer(wx.VERTICAL) self._rx_gain_text_box = forms.text_box( parent=self.GetWin(), sizer=_rx_gain_sizer, value=self.rx_gain, callback=self.set_rx_gain, label="Analog Gain", converter=forms.int_converter(), proportion=0, ) self._rx_gain_slider = forms.slider( parent=self.GetWin(), sizer=_rx_gain_sizer, value=self.rx_gain, callback=self.set_rx_gain, minimum=0, maximum=100, num_steps=100, style=wx.SL_HORIZONTAL, cast=int, proportion=1, ) self.GridAdd(_rx_gain_sizer, 0, 4, 1, 1) _offset_sizer = wx.BoxSizer(wx.VERTICAL) self._offset_text_box = forms.text_box( parent=self.GetWin(), sizer=_offset_sizer, value=self.offset, callback=self.set_offset, label="Freq. Offset", converter=forms.float_converter(), proportion=0, ) self._offset_slider = forms.slider( parent=self.GetWin(), sizer=_offset_sizer, value=self.offset, callback=self.set_offset, minimum=-12.5e3, maximum=12.5e3, num_steps=100, style=wx.SL_HORIZONTAL, cast=float, proportion=1, ) self.GridAdd(_offset_sizer, 0, 3, 1, 1) self._freq_text_static_text = forms.static_text( parent=self.GetWin(), value=self.freq_text, callback=self.set_freq_text, label="Ch. Freq", converter=forms.float_converter(), ) self.GridAdd(self._freq_text_static_text, 0, 2, 1, 1) ################################################## # Blocks ################################################## self.fm_demod = gr.quadrature_demod_cf(demod_k) self.gr_freq_xlating_fir_filter_xxx_0 = gr.freq_xlating_fir_filter_ccc(channel_decim, (channel_taps), band_freq-freq+offset, sample_rate) self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_int*1) self.blocks_null_sink_0_0 = blocks.null_sink(gr.sizeof_int*1) self.blocks_null_sink_0_1 = blocks.null_sink(gr.sizeof_int*1) self.blocks_null_sink_0_2 = blocks.null_sink(gr.sizeof_int*1) self.pager_flex_deinterleave_0 = pager.flex_deinterleave() self.pager_flex_deinterleave_0_0 = pager.flex_deinterleave() self.pager_flex_deinterleave_0_1 = pager.flex_deinterleave() self.pager_flex_deinterleave_0_1_0 = pager.flex_deinterleave() self.pager_flex_sync_0 = pager.flex_sync() self.pager_slicer_fb_0 = pager.slicer_fb(1e-6) self.resampler = filter.rational_resampler_fff( interpolation=bb_interp, decimation=bb_decim, taps=([1.0/ma_ntaps,]*ma_ntaps*bb_interp), fractional_bw=None, ) self.usrp_source = grc_usrp.simple_source_c(which=0, side="A", rx_ant="RXA") self.usrp_source.set_decim_rate(decim) self.usrp_source.set_frequency(band_freq, verbose=True) self.usrp_source.set_gain(rx_gain) self.wxgui_fftsink2_0 = fftsink2.fft_sink_c( self.displays.GetPage(0).GetWin(), baseband_freq=band_freq, y_per_div=10, y_divs=10, ref_level=0, ref_scale=65536, sample_rate=sample_rate, fft_size=1024, fft_rate=30, average=False, avg_alpha=None, title="FLEX Spectrum", peak_hold=False, ) self.displays.GetPage(0).GridAdd(self.wxgui_fftsink2_0.win, 0, 0, 1, 1) self.wxgui_fftsink2_1 = fftsink2.fft_sink_c( self.displays.GetPage(0).GetWin(), baseband_freq=freq, y_per_div=10, y_divs=10, ref_level=0, ref_scale=65536, sample_rate=channel_rate, fft_size=1024, fft_rate=30, average=False, avg_alpha=None, title="Channel Spectrum", peak_hold=False, ) self.displays.GetPage(0).GridAdd(self.wxgui_fftsink2_1.win, 1, 0, 1, 1) self.wxgui_scopesink2_0_0 = scopesink2.scope_sink_f( self.displays.GetPage(1).GetWin(), title="Baseband", sample_rate=16e3, v_scale=1, v_offset=0, t_scale=40.0/16e3, ac_couple=False, xy_mode=False, num_inputs=1, ) self.displays.GetPage(1).GridAdd(self.wxgui_scopesink2_0_0.win, 0, 0, 1, 1) ################################################## # Connections ################################################## self.connect((self.gr_freq_xlating_fir_filter_xxx_0, 0), (self.wxgui_fftsink2_1, 0)) self.connect((self.usrp_source, 0), (self.gr_freq_xlating_fir_filter_xxx_0, 0)) self.connect((self.usrp_source, 0), (self.wxgui_fftsink2_0, 0)) self.connect((self.gr_freq_xlating_fir_filter_xxx_0, 0), (self.fm_demod, 0)) self.connect((self.resampler, 0), (self.wxgui_scopesink2_0_0, 0)) self.connect((self.fm_demod, 0), (self.resampler, 0)) self.connect((self.pager_slicer_fb_0, 0), (self.pager_flex_sync_0, 0)) self.connect((self.resampler, 0), (self.pager_slicer_fb_0, 0)) self.connect((self.pager_flex_sync_0, 1), (self.pager_flex_deinterleave_0_1_0, 0)) self.connect((self.pager_flex_sync_0, 2), (self.pager_flex_deinterleave_0_1, 0)) self.connect((self.pager_flex_sync_0, 0), (self.pager_flex_deinterleave_0, 0)) self.connect((self.pager_flex_sync_0, 3), (self.pager_flex_deinterleave_0_0, 0)) self.connect((self.pager_flex_deinterleave_0, 0), (self.blocks_null_sink_0, 0)) self.connect((self.pager_flex_deinterleave_0_1_0, 0), (self.blocks_null_sink_0_0, 0)) self.connect((self.pager_flex_deinterleave_0_1, 0), (self.blocks_null_sink_0_1, 0)) self.connect((self.pager_flex_deinterleave_0_0, 0), (self.blocks_null_sink_0_2, 0)) def set_config_filename(self, config_filename): self.config_filename = config_filename self._saved_band_freq_config = ConfigParser.ConfigParser() self._saved_band_freq_config.read(self.config_filename) if not self._saved_band_freq_config.has_section("gr-pager"): self._saved_band_freq_config.add_section("gr-pager") self._saved_band_freq_config.set("gr-pager", "band_center", str(self.band_freq)) self._saved_band_freq_config.write(open(self.config_filename, 'w')) self._saved_channel_config = ConfigParser.ConfigParser() self._saved_channel_config.read(self.config_filename) if not self._saved_channel_config.has_section("gr-pager"): self._saved_channel_config.add_section("gr-pager") self._saved_channel_config.set("gr-pager", "channel", str(self.channel)) self._saved_channel_config.write(open(self.config_filename, 'w')) self._saved_offset_config = ConfigParser.ConfigParser() self._saved_offset_config.read(self.config_filename) if not self._saved_offset_config.has_section("gr-pager"): self._saved_offset_config.add_section("gr-pager") self._saved_offset_config.set("gr-pager", "freq_offset", str(self.offset)) self._saved_offset_config.write(open(self.config_filename, 'w')) self._saved_rx_gain_config = ConfigParser.ConfigParser() self._saved_rx_gain_config.read(self.config_filename) if not self._saved_rx_gain_config.has_section("gr-pager"): self._saved_rx_gain_config.add_section("gr-pager") self._saved_rx_gain_config.set("gr-pager", "rx_gain", str(self.rx_gain)) self._saved_rx_gain_config.write(open(self.config_filename, 'w')) def set_symbol_rate(self, symbol_rate): self.symbol_rate = symbol_rate self.set_passband(2*(self.deviation+self.symbol_rate)) self.set_ma_ntaps(int(self.channel_rate/self.symbol_rate)) def set_saved_channel(self, saved_channel): self.saved_channel = saved_channel self.set_channel(self.saved_channel) def set_saved_band_freq(self, saved_band_freq): self.saved_band_freq = saved_band_freq self.set_band_freq(self.saved_band_freq) def set_deviation(self, deviation): self.deviation = deviation self.set_demod_k(3*self.channel_rate/(2*math.pi*self.deviation)) self.set_passband(2*(self.deviation+self.symbol_rate)) def set_decim(self, decim): self.decim = decim self.set_sample_rate(self.adc_rate/self.decim) self.usrp_source.set_decim_rate(self.decim) def set_adc_rate(self, adc_rate): self.adc_rate = adc_rate self.set_sample_rate(self.adc_rate/self.decim) def set_sample_rate(self, sample_rate): self.sample_rate = sample_rate self.wxgui_fftsink2_0.set_sample_rate(self.sample_rate) self.set_channel_decim(int(self.sample_rate/self.channel_rate)) self.set_channel_taps(firdes.low_pass(10, self.sample_rate, self.passband/2.0, (self.channel_rate-self.passband)/2.0)) def set_passband(self, passband): self.passband = passband self.set_channel_taps(firdes.low_pass(10, self.sample_rate, self.passband/2.0, (self.channel_rate-self.passband)/2.0)) def set_channel_rate(self, channel_rate): self.channel_rate = channel_rate self.wxgui_fftsink2_1.set_sample_rate(self.channel_rate) self.set_channel_decim(int(self.sample_rate/self.channel_rate)) self.set_demod_k(3*self.channel_rate/(2*math.pi*self.deviation)) self.set_channel_taps(firdes.low_pass(10, self.sample_rate, self.passband/2.0, (self.channel_rate-self.passband)/2.0)) self.set_ma_ntaps(int(self.channel_rate/self.symbol_rate)) def set_channel(self, channel): self.channel = channel self.set_freq(self.band_freq+(self.channel-61)*25e3) self._saved_channel_config = ConfigParser.ConfigParser() self._saved_channel_config.read(self.config_filename) if not self._saved_channel_config.has_section("gr-pager"): self._saved_channel_config.add_section("gr-pager") self._saved_channel_config.set("gr-pager", "channel", str(self.channel)) self._saved_channel_config.write(open(self.config_filename, 'w')) self._channel_slider.set_value(self.channel) self._channel_text_box.set_value(self.channel) def set_band_freq(self, band_freq): self.band_freq = band_freq self.set_freq(self.band_freq+(self.channel-61)*25e3) self.wxgui_fftsink2_0.set_baseband_freq(self.band_freq) self.usrp_source.set_frequency(self.band_freq) self.gr_freq_xlating_fir_filter_xxx_0.set_center_freq(self.band_freq-self.freq+self.offset) self._saved_band_freq_config = ConfigParser.ConfigParser() self._saved_band_freq_config.read(self.config_filename) if not self._saved_band_freq_config.has_section("gr-pager"): self._saved_band_freq_config.add_section("gr-pager") self._saved_band_freq_config.set("gr-pager", "band_center", str(self.band_freq)) self._saved_band_freq_config.write(open(self.config_filename, 'w')) self._band_freq_text_box.set_value(self.band_freq) def set_saved_rx_gain(self, saved_rx_gain): self.saved_rx_gain = saved_rx_gain self.set_rx_gain(self.saved_rx_gain) def set_saved_offset(self, saved_offset): self.saved_offset = saved_offset self.set_offset(self.saved_offset) def set_freq(self, freq): self.freq = freq self.gr_freq_xlating_fir_filter_xxx_0.set_center_freq(self.band_freq-self.freq+self.offset) self.wxgui_fftsink2_1.set_baseband_freq(self.freq) self.set_freq_text(self.freq) def set_channel_taps(self, channel_taps): self.channel_taps = channel_taps self.gr_freq_xlating_fir_filter_xxx_0.set_taps((self.channel_taps)) self.set_nchan_taps(len(self.channel_taps)) def set_rx_gain(self, rx_gain): self.rx_gain = rx_gain self.usrp_source.set_gain(self.rx_gain) self._saved_rx_gain_config = ConfigParser.ConfigParser() self._saved_rx_gain_config.read(self.config_filename) if not self._saved_rx_gain_config.has_section("gr-pager"): self._saved_rx_gain_config.add_section("gr-pager") self._saved_rx_gain_config.set("gr-pager", "rx_gain", str(self.rx_gain)) self._saved_rx_gain_config.write(open(self.config_filename, 'w')) self._rx_gain_slider.set_value(self.rx_gain) self._rx_gain_text_box.set_value(self.rx_gain) def set_offset(self, offset): self.offset = offset self.gr_freq_xlating_fir_filter_xxx_0.set_center_freq(self.band_freq-self.freq+self.offset) self._saved_offset_config = ConfigParser.ConfigParser() self._saved_offset_config.read(self.config_filename) if not self._saved_offset_config.has_section("gr-pager"): self._saved_offset_config.add_section("gr-pager") self._saved_offset_config.set("gr-pager", "freq_offset", str(self.offset)) self._saved_offset_config.write(open(self.config_filename, 'w')) self._offset_slider.set_value(self.offset) self._offset_text_box.set_value(self.offset) def set_nchan_taps(self, nchan_taps): self.nchan_taps = nchan_taps def set_ma_ntaps(self, ma_ntaps): self.ma_ntaps = ma_ntaps def set_freq_text(self, freq_text): self.freq_text = freq_text self._freq_text_static_text.set_value(self.freq_text) def set_demod_k(self, demod_k): self.demod_k = demod_k def set_channel_decim(self, channel_decim): self.channel_decim = channel_decim def set_bb_interp(self, bb_interp): self.bb_interp = bb_interp def set_bb_decim(self, bb_decim): self.bb_decim = bb_decim def set_baseband_rate(self, baseband_rate): self.baseband_rate = baseband_rate if __name__ == '__main__': parser = OptionParser(option_class=eng_option, usage="%prog: [options]") (options, args) = parser.parse_args() tb = usrp_rx_flex() tb.Run(True) gnuradio-3.7.2.1/gr-pager/apps/usrp_rx_flex.grc0000664000175000017500000011051212207440367021215 0ustar jcorganjcorgan Thu Oct 29 11:01:22 2009 options id usrp_rx_flex _enabled True title USRP FLEX Pager Receiver (Single Channel) author description window_size 4095,4095 generate_options wx_gui category Custom run_options prompt run True realtime_scheduling _coordinate (10, 10) _rotation 0 variable id adc_rate _enabled True value 64e6 _coordinate (225, 12) _rotation 0 variable id sample_rate _enabled True value adc_rate/decim _coordinate (382, 12) _rotation 0 variable id freq _enabled True value band_freq+(channel-61)*25e3 _coordinate (480, 11) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_0 _enabled True type complex title FLEX Spectrum samp_rate sample_rate baseband_freq band_freq y_per_div 10 y_divs 10 ref_level 0 ref_scale 65536 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos 0,0,1,1 notebook displays,0 _coordinate (34, 508) _rotation 180 notebook id displays _enabled True style wx.NB_TOP labels ['RX Spectrum','Baseband'] grid_pos 1, 0, 1, 5 notebook _coordinate (9, 209) _rotation 0 import id import_0 _enabled True import import os, math _coordinate (10, 76) _rotation 0 usrp_simple_source_x id usrp_source _enabled True type complex format which 0 decimation decim frequency band_freq lo_offset float('inf') gain rx_gain side A rx_ant RXA hb_filters _coordinate (32, 734) _rotation 0 filter_freq_xlating_fir_filter_xxx id filter_freq_xlating_fir_filter_xxx_0 _enabled True type ccc decim channel_decim taps channel_taps center_freq band_freq-freq+offset samp_rate sample_rate _coordinate (321, 750) _rotation 0 wxgui_fftsink2 id wxgui_fftsink2_1 _enabled True type complex title Channel Spectrum samp_rate channel_rate baseband_freq freq y_per_div 10 y_divs 10 ref_level 0 ref_scale 65536 fft_size 1024 fft_rate 30 peak_hold False average False avg_alpha 0 win None win_size grid_pos 1, 0, 1, 1 notebook displays, 0 _coordinate (344, 511) _rotation 180 variable id decim _enabled True value 20 _coordinate (310, 11) _rotation 0 variable id symbol_rate _enabled True value 3200 _coordinate (590, 12) _rotation 0 variable id channel_decim _enabled True value int(sample_rate/channel_rate) _coordinate (906, 12) _rotation 0 variable id deviation _enabled True value 4800 _coordinate (688, 14) _rotation 0 variable id demod_k _enabled True value 3*channel_rate/(2*math.pi*deviation) _coordinate (598, 857) _rotation 0 variable id channel_taps _enabled True value firdes.low_pass(10, sample_rate, passband/2.0, (channel_rate-passband)/2.0) _coordinate (325, 857) _rotation 0 variable id config_filename _enabled True value os.environ["HOME"]+"/.gnuradio/config.conf" _coordinate (9, 133) _rotation 0 variable_config id saved_band_freq _enabled True value 930.5125e6 type real config_file config_filename section gr-pager option band_center writeback band_freq _coordinate (228, 311) _rotation 0 variable_config id saved_channel _enabled True value 25 type int config_file config_filename section gr-pager option channel writeback channel _coordinate (387, 312) _rotation 0 variable_config id saved_offset _enabled True value 0 type real config_file config_filename section gr-pager option freq_offset writeback offset _coordinate (547, 312) _rotation 0 variable_config id saved_rx_gain _enabled True value 40 type int config_file config_filename section gr-pager option rx_gain writeback rx_gain _coordinate (706, 312) _rotation 0 variable_text_box id band_freq _enabled True label Band Freq. value saved_band_freq converver float_converter formatter None grid_pos 0, 0, 1, 1 notebook _coordinate (225, 121) _rotation 0 variable_static_text id freq_text _enabled True label Ch. Freq value freq converver float_converter formatter None grid_pos 0, 2, 1, 1 notebook _coordinate (801, 124) _rotation 0 variable id passband _enabled True value 2*(deviation+symbol_rate) _coordinate (327, 930) _rotation 0 variable id channel_rate _enabled True value 8*3200 _coordinate (792, 13) _rotation 0 variable_slider id channel _enabled True label Channel value saved_channel min 1 max 120 num_steps 119 style wx.SL_HORIZONTAL converver int_converter grid_pos 0, 1, 1, 1 notebook _coordinate (376, 120) _rotation 0 variable_slider id rx_gain _enabled True label Analog Gain value saved_rx_gain min 0 max 100 num_steps 100 style wx.SL_HORIZONTAL converver int_converter grid_pos 0, 4, 1, 1 notebook _coordinate (658, 122) _rotation 0 variable_slider id offset _enabled True label Freq. Offset value saved_offset min -12.5e3 max 12.5e3 num_steps 100 style wx.SL_HORIZONTAL converver float_converter grid_pos 0, 3, 1, 1 notebook _coordinate (518, 118) _rotation 0 analog_quadrature_demod_cf id fm_demod _enabled True gain demod_k _coordinate (599, 774) _rotation 0 variable id baseband_rate _enabled True value 16000 _coordinate (1019, 17) _rotation 0 variable id nchan_taps _enabled True value len(channel_taps) _coordinate (412, 931) _rotation 0 variable id ma_ntaps _enabled True value int(channel_rate/symbol_rate) _coordinate (850, 863) _rotation 0 variable id bb_interp _enabled True value 5 _coordinate (938, 862) _rotation 0 virtual_sink id virtual_sink_0 _enabled True stream_id baseband _coordinate (1100, 774) _rotation 0 blks2_rational_resampler_xxx id resampler _enabled True type fff decim bb_decim interp bb_interp taps [1.0/ma_ntaps,]*ma_ntaps*bb_interp fractional_bw 0 _coordinate (851, 750) _rotation 0 variable id bb_decim _enabled True value 8 _coordinate (1027, 864) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0_0 _enabled True type float title Baseband samp_rate 16e3 v_scale 1 v_offset 0 t_scale 40.0/16e3 ac_couple False xy_mode False num_inputs 1 win_size grid_pos 0, 0, 1, 1 notebook displays, 1 _coordinate (851, 586) _rotation 180 virtual_source id virtual_source_0 _enabled True stream_id baseband _coordinate (79, 1186) _rotation 0 pager_slicer_fb id pager_slicer_fb_0 _enabled True alpha 1e-6 _coordinate (304, 1186) _rotation 0 wxgui_scopesink2 id wxgui_scopesink2_0 _enabled False type float title Slicer Output samp_rate baseband_rate v_scale 1 v_offset 0 t_scale 40.0/baseband_rate ac_couple False xy_mode False num_inputs 1 win_size grid_pos 1,0,1,1 notebook displays, 1 _coordinate (75, 1044) _rotation 180 blocks_char_to_float id blocks_char_to_float_0 _enabled False _coordinate (325, 1088) _rotation 180 pager_flex_sync id pager_flex_sync_0 _enabled True _coordinate (529, 1139) _rotation 0 pager_flex_deinterleave id pager_flex_deinterleave_0 _enabled True _coordinate (777, 1116) _rotation 0 blocks_null_sink id blocks_null_sink_0 _enabled True type int vlen 1 _coordinate (1042, 1116) _rotation 0 pager_flex_deinterleave id pager_flex_deinterleave_0_1_0 _enabled True _coordinate (778, 1168) _rotation 0 pager_flex_deinterleave id pager_flex_deinterleave_0_1 _enabled True _coordinate (776, 1225) _rotation 0 pager_flex_deinterleave id pager_flex_deinterleave_0_0 _enabled True _coordinate (776, 1273) _rotation 0 blocks_null_sink id blocks_null_sink_0_0 _enabled True type int vlen 1 _coordinate (1042, 1168) _rotation 0 blocks_null_sink id blocks_null_sink_0_1 _enabled True type int vlen 1 _coordinate (1041, 1225) _rotation 0 blocks_null_sink id blocks_null_sink_0_2 _enabled True type int vlen 1 _coordinate (1040, 1273) _rotation 0 filter_freq_xlating_fir_filter_xxx_0 wxgui_fftsink2_1 0 0 usrp_source filter_freq_xlating_fir_filter_xxx_0 0 0 usrp_source wxgui_fftsink2_0 0 0 filter_freq_xlating_fir_filter_xxx_0 fm_demod 0 0 resampler wxgui_scopesink2_0_0 0 0 fm_demod resampler 0 0 resampler virtual_sink_0 0 0 pager_slicer_fb_0 pager_flex_sync_0 0 0 virtual_source_0 pager_slicer_fb_0 0 0 pager_slicer_fb_0 blocks_char_to_float_0 0 0 blocks_char_to_float_0 wxgui_scopesink2_0 0 0 pager_flex_sync_0 pager_flex_deinterleave_0_1_0 1 0 pager_flex_sync_0 pager_flex_deinterleave_0_1 2 0 pager_flex_sync_0 pager_flex_deinterleave_0 0 0 pager_flex_sync_0 pager_flex_deinterleave_0_0 3 0 pager_flex_deinterleave_0 blocks_null_sink_0 0 0 pager_flex_deinterleave_0_1_0 blocks_null_sink_0_0 0 0 pager_flex_deinterleave_0_1 blocks_null_sink_0_1 0 0 pager_flex_deinterleave_0_0 blocks_null_sink_0_2 0 0 gnuradio-3.7.2.1/gr-pager/gnuradio-pager.pc.in0000664000175000017500000000042012207440367020666 0ustar jcorganjcorganprefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: gnuradio-pager Description: GNU Radio blocks implementing a FLEX pager decoder Requires: gnuradio-runtime Version: @LIBVER@ Libs: -L${libdir} -lgnuradio-pager Cflags: -I${includedir} gnuradio-3.7.2.1/dtools/0000755000175000017500000000000011744612271014633 5ustar jcorganjcorgangnuradio-3.7.2.1/dtools/README0000644000175000017500000000173111744612271015515 0ustar jcorganjcorgan# # Copyright 2006 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # This is a collection of tools that are useful for building tarball distributions of GNU Radio. They're probably not of general interest. To use, add dtools/bin to PATH and dtools/python to PYTHONPATH gnuradio-3.7.2.1/dtools/bin/0000755000175000017500000000000011744612271015403 5ustar jcorganjcorgangnuradio-3.7.2.1/dtools/bin/install-tbb0000755000175000017500000000452611744612271017553 0ustar jcorganjcorgan#!/usr/bin/env python """ Install the release and debug libs and includes under --prefix """ from optparse import OptionParser import os import os.path import glob default_prefix="/usr/local" pkgconfig_filename = "tbb.pc" pkgconfig_file_contents = """\ prefix=%s exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: tbb Description: Intel Threading Building Blocks Requires: Version: 2.0 Libs: -L${libdir} -ltbb -ltbbmalloc Cflags: -I${includedir} """ debug_pkgconfig_filename = "tbb_debug.pc" debug_pkgconfig_file_contents = """\ prefix=%s exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: tbb Description: Intel Threading Building Blocks Requires: Version: 2.0 Libs: -L${libdir} -ltbb_debug -ltbbmalloc_debug Cflags: -I${includedir} """ def main(): parser = OptionParser() parser.add_option('','--prefix', default=default_prefix, help="install architecture-independent files in PREFIX [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 prefix = options.prefix # are we installing 64-bit libs? is_64bit = False files = glob.glob('build/*_em64t_*_release') # print "files: ", files if len(files) != 0: is_64bit = True # FIXME add 32 and 64-bit PPC support if is_64bit: lib = 'lib64' else: lib = 'lib' os.system('install -d ' + os.path.join(prefix, 'include/tbb')) os.system('install -d ' + os.path.join(prefix, 'include/tbb/machine')) os.system('install -d ' + os.path.join(prefix, lib)) os.system('install -d ' + os.path.join(prefix, lib, 'pkgconfig')) os.system('install -t ' + os.path.join(prefix, lib) + ' build/linux*release/*.so*') os.system('install -t ' + os.path.join(prefix, lib) + ' build/linux*debug/*.so*') os.system('install -t ' + os.path.join(prefix, 'include/tbb') + ' include/tbb/*.h') os.system('install -t ' + os.path.join(prefix, 'include/tbb/machine') + ' include/tbb/machine/*.h') f = open(os.path.join(prefix, lib, 'pkgconfig', pkgconfig_filename), 'w') f.write(pkgconfig_file_contents % (prefix,)) f.close() f = open(os.path.join(prefix, lib, 'pkgconfig', debug_pkgconfig_filename), 'w') f.write(debug_pkgconfig_file_contents % (prefix,)) f.close() if __name__ == "__main__": main() gnuradio-3.7.2.1/dtools/bin/make-upload0000755000175000017500000000064611700377700017533 0ustar jcorganjcorgan#!/bin/bash read -s -p "GPG Passphrase: " passphrase for file in "$@" do ( echo "version: 1.1" echo "directory: gnuradio" echo "filename: $file" )> $file.directive echo "$passphrase" | gpg --passphrase-fd 0 --clearsign $file.directive rm $file.directive echo "$passphrase" | gpg --passphrase-fd 0 -b $file done passphrase="XYZabcdefhghakdsj;lasjdf;ajfdiuiwjr;lajv;laoisfuaoieurlkajdsflkajsdfoiuew" gnuradio-3.7.2.1/dtools/bin/update_fsf_address0000755000175000017500000001036111744612271021157 0ustar jcorganjcorgan#!/usr/bin/env python # # Copyright 2006 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # import re import os import os.path import sys from optparse import OptionParser dry_run = False modified_files = [] dirs_to_ignore = ('CVS', '.svn', '.deps', '.libs') extensions_to_ignore = ('.o', '.lo', '.a', '.la', '.lai', '.so', '.soT', '.pyc', '.pyo', '.ko', '.fasl', '.rwbak', '.tar', '.gz', '.log', '.eps', '.ps', '.pdf', '.png', '.jpg', '.jpeg', '.bmp', '.dat', '.ihx', '.diff', '.lib', '.lst', '.rel', '.sym', '.asm', '.rst', 'mem', '.map', # sdcc output '.rbf', '.esf', '.qpf', '.psf', '.quartus', '.bsf', '.cmp' # quartus ) def destructively_remove(list, predicate): """ Destructively remove elements from LIST for which PREDICATE is true """ for i in range(len(list)): if predicate(list[i]): del list[i] destructively_remove(list, predicate) return def expunge_unwanted_dirnames(dirnames): """ Destructively remove directory names that we don't want to visit. This is a _very_ non-functional approach to programming... """ destructively_remove(dirnames, lambda d: d in dirs_to_ignore) def expunge_unwanted_filenames(filenames): """ Destructively remove filenames that we don't want to visit. This is a _very_ non-functional approach to programming... """ destructively_remove(filenames, lambda f: f.endswith('~') or os.path.splitext(f)[1] in extensions_to_ignore) def walk_directory(dirname): for dirpath, dirnames, filenames in os.walk(dirname): expunge_unwanted_dirnames(dirnames) expunge_unwanted_filenames(filenames) for f in filenames: update_one(os.path.join(dirpath, f)) addr_pattern = re.compile(r'\b59 Temple Place(,| *-) *Suite 330\b', re.IGNORECASE) addr_replacement = '51 Franklin Street' zip_pattern = re.compile(r'\b02111-1307\b') zip_replacement = '02110-1301' def update_one(filename): f = open(filename, 'r') s = f.read() f.close() t = s t = addr_pattern.sub(addr_replacement, t) t = zip_pattern.sub(zip_replacement, t) if s != t: modified_files.append(filename) if not dry_run: f = open(filename, 'w') f.write(t) def handle_file_or_dir(file_or_dir): if os.path.isfile(file_or_dir): update_one(file_or_dir) elif os.path.isdir(file_or_dir): walk_directory(file_or_dir) else: pass # ignore the other cases def main(): global dry_run usage = '%prog: [options] [file_or_dir...]' parser = OptionParser (usage=usage) parser.add_option('-l', '--list-modified-files', action='store_true', default=False, help='List modified files to stdout [default=%default]') parser.add_option('', '--dry-run', action='store_true', default=False, help="Don't modify any files, just report what would be modified [default=%default]") (options, args) = parser.parse_args() dry_run = options.dry_run if options.dry_run: options.list_modified_files = True for file_or_dir in args: handle_file_or_dir(file_or_dir) if options.list_modified_files: for f in modified_files: sys.stdout.write(f + '\n') if __name__ == '__main__': main() gnuradio-3.7.2.1/dtools/bin/check-tarball-h-files0000755000175000017500000000101211700377700021341 0ustar jcorganjcorgan#!/bin/sh tarball=$1 if [ "x$tarball" = "x" ] then echo "usage: $0 tarball" 1>&2 exit 1 fi path=${tarball%%.tar.gz} tar tzf $tarball \ | grep -E '\.(h|py|v|vh)$' \ | sed -e "s/$path/./" \ | sort >/tmp/tarball-h-files find . \( -name '*.h' -o -name '*.py' -o -name '*.v' -o -name '*.vh' \) -print \ | grep -v ./$path | sort >/tmp/build-h-files comm -23 /tmp/build-h-files /tmp/tarball-h-files \ | grep -Ev '(GrAtsc|_swig_|limbo|config\.h|std_paths\.h)' # rm /tmp/tarball-h-files /tmp/build-h-files gnuradio-3.7.2.1/dtools/bin/remove-whitespace0000755000175000017500000000014611744612271020761 0ustar jcorganjcorgan#!/bin/bash sed -i -e 's/\s\+$//g' $(find . -type f | grep -v '.git' | grep -v 'png' | grep -v 'eps')gnuradio-3.7.2.1/dtools/bin/fix-copyright-years0000755000175000017500000000446411700377700021253 0ustar jcorganjcorgan#!/usr/bin/env python import re import datetime import subprocess import multiprocessing def command(*args): return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0] def is_gnuradio_co_source(lines): for line in lines[:20]: if 'GNU Radio is free software' in line: return True return False def get_gnuradio_co_line(lines): for i, line in enumerate(lines[:5]): if 'Copyright' in line and 'Free Software Foundation' in line: return line, i return None def fix_co_years(files): for file in files: print file lines = open(file).readlines() if not is_gnuradio_co_source(lines): continue #extract the years from the git history years = set(map( lambda l: int(l.split()[-2]), filter( lambda l: l.startswith('Date'), command('git', 'log', file).splitlines(), ), )) #extract line and line number for co line try: line, num = get_gnuradio_co_line(lines) except: continue #extract years from co string try: co_years_str = re.match('^.*Copyright (.*) Free Software Foundation.*$', line).groups()[0] co_years = set(map(int, co_years_str.split(','))) except: print ' format error on line %d: "%s"'%(num, line); continue #update the years if missing any all_years = co_years.union(years) if all_years != co_years: print ' missing years: %s'%(', '.join(map(str, sorted(all_years - co_years)))) all_years.add(datetime.datetime.now().year) #add the current year all_years_str = ', '.join(map(str, sorted(all_years))) new_text = ''.join(lines[:num] + [line.replace(co_years_str, all_years_str)] + lines[num+1:]) open(file, 'w').write(new_text) if __name__ == "__main__": #get recursive list of files in the repo files = command('git', 'ls-tree', '--name-only', 'HEAD', '-r').splitlines() #start n+1 processes to handle the files num_procs = multiprocessing.cpu_count() procs = [multiprocessing.Process( target=lambda *files: fix_co_years(files), args=files[num::num_procs], ) for num in range(num_procs)] map(multiprocessing.Process.start, procs) map(multiprocessing.Process.join, procs) gnuradio-3.7.2.1/dtools/bin/check-imports0000755000175000017500000000012011744612271020072 0ustar jcorganjcorgan#!/bin/bash find . -name '*.py' | xargs grep -h -E '^(from|import)' | sort -u gnuradio-3.7.2.1/docs/0000755000175000017500000000000012244272666014265 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/CMakeLists.txt0000664000175000017500000000532112244272666017030 0ustar jcorganjcorgan# Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. ######################################################################## # Setup dependencies ######################################################################## find_package(Doxygen) find_package(Sphinx) ######################################################################## # Register component ######################################################################## include(GrComponent) GR_REGISTER_COMPONENT("doxygen" ENABLE_DOXYGEN DOXYGEN_FOUND) GR_REGISTER_COMPONENT("sphinx" ENABLE_SPHINX SPHINX_FOUND) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_DOXYGEN) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_COMPONENT("docs" DISPLAY_NAME "Documentation" DESCRIPTION "Doxygen generated documentation" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(doxygen) add_subdirectory(exploring-gnuradio) endif(ENABLE_DOXYGEN) ######################################################################## # Begin conditional configuration ######################################################################## if(ENABLE_SPHINX) ######################################################################## # Setup CPack components ######################################################################## include(GrPackage) CPACK_COMPONENT("docs" DISPLAY_NAME "Documentation" DESCRIPTION "Sphinx generated documentation" ) ######################################################################## # Add subdirectories ######################################################################## add_subdirectory(sphinx) endif(ENABLE_SPHINX) gnuradio-3.7.2.1/docs/ChangeLog0000644000175000017500000000157311744612271016037 0ustar jcorganjcorgan2004-11-29 Eric Blossom * exploring-gnuradio/exploring-gnuradio.xml: new. revision 1.1 # # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # gnuradio-3.7.2.1/docs/sphinx/0000755000175000017500000000000012207440367015570 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/CMakeLists.txt0000644000175000017500000000222211765410647020334 0ustar jcorganjcorgan# Copyright 2012 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. include(GrPython) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/source/conf.py.in ${CMAKE_CURRENT_BINARY_DIR}/conf.py @ONLY) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run_sphinx_build.sh.in ${CMAKE_BINARY_DIR}/run_sphinx_build.sh @ONLY) if(UNIX) #make the shell file executable execute_process(COMMAND chmod +x ${CMAKE_BINARY_DIR}/run_sphinx_build.sh) endif(UNIX) gnuradio-3.7.2.1/docs/sphinx/hieroglyph/0000755000175000017500000000000012123615457017743 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/hieroglyph/LICENSE.txt0000644000175000017500000000273111765410647021576 0ustar jcorganjcorganCopyright (c) 2011, Robert Smallshire All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Robert Smallshire nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. gnuradio-3.7.2.1/docs/sphinx/hieroglyph/errors.py0000644000175000017500000000031211765410647021632 0ustar jcorganjcorgan from sphinx.errors import ExtensionError __author__ = 'rjs' class HieroglyphError(ExtensionError): ''' An exception type specific to the Hieroglyph Sphinx extension. ''' passgnuradio-3.7.2.1/docs/sphinx/hieroglyph/README.txt0000644000175000017500000000116511765410647021451 0ustar jcorganjcorganSphinx is a popular tool for documenting Python APIs which uses reStructuredText as a its lightweight markup language. Sphinx extends restructured text with semantic markup elements for documenting Python APIs but once these are used the ratio of markup to content becomes too high and readability is compromised enough that the docstring becomes unsuitable for use with standard Python introspection mechanisms like help() or IDEs. Hieroglyph is an a Sphinx extension which automatically converts a highly readable docstring format suitable for use with help() and IDEs to the reStructuredText hieroglyphics required by Sphinx.gnuradio-3.7.2.1/docs/sphinx/hieroglyph/test/0000755000175000017500000000000011765410647020727 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/hieroglyph/test/test_nodes.py0000644000175000017500000003077311765410647023462 0ustar jcorganjcorganimport unittest from hieroglyph.nodes import Node, Arg, Raises, Except, Returns, Warning, Note __author__ = 'Robert Smallshire' class NodeTests(unittest.TestCase): def test_create_default_node(self): node = Node() self.assertEqual(node.indent, 0) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_create_with_indent(self): node = Node(indent=4) self.assertEqual(node.indent, 4) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_create_with_lines(self): node = Node(lines= ['First', 'Second', 'Third']) self.assertEqual(node.indent, 0) self.assertEqual(node.lines, ['First', 'Second', 'Third']) self.assertIsNone(node.parent) def test_repr(self): node = Node(5, ['One', 'Two', 'Three']) actual = repr(node) expected = "Node(5, ['One', 'Two', 'Three'], children=[])" self.assertEqual(expected, actual) def test_add_one_child(self): node = Node() child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Node() child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_render_rst_empty(self): node = Node() rst = node.render_rst() self.assertEqual(len(rst), 0) def test_render_rst_indent(self): node = Node(indent=4) rst = node.render_rst() self.assertEqual(len(rst), 0) def test_render_rst_lines(self): node = Node(lines= ['First', 'Second', 'Third']) rst = node.render_rst() self.assertEqual(rst, ['First', 'Second', 'Third']) def test_render_rst_indented_lines(self): node = Node(indent=3, lines= ['First', 'Second', 'Third']) rst = node.render_rst() self.assertEqual(rst, [' First', ' Second', ' Third']) def test_render_rst_with_child(self): node = Node(indent=4, lines=["Parent"]) child = Node(indent=8, lines=["Child"], parent=node) node.add_child(child) rst = node.render_rst() self.assertEqual(rst, [' Parent', ' Child']) def test_render_rst_with_children(self): node = Node(indent=4, lines=["Parent"]) child_a = Node(indent=8, lines=["ChildA"], parent=node) node.add_child(child_a) child_b = Node(indent=6, lines=["ChildB"], parent=node) node.add_child(child_b) rst = node.render_rst() self.assertEqual(rst, [' Parent', ' ChildA', ' ChildB']) class ArgTests(unittest.TestCase): def test_create(self): node = Arg(5, 10, 'foo') self.assertEqual(node.indent, 5) self.assertEqual(node.child_indent, 10) self.assertEqual(node.name, 'foo') self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_set_type(self): node = Arg(5, 10, 'foo') node.type = 'str' self.assertEqual(node.type, 'str') def test_add_one_child(self): node = Arg(5, 10, 'foo') child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Arg(5, 10, 'foo') child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_repr(self): node = Arg(5, 10, 'foo') actual = repr(node) expected = "Arg('foo', None, children=[])" self.assertEqual(expected, actual) def test_render_rst_empty(self): node = Arg(5, 10, 'bar') rst = node.render_rst() self.assertEqual(rst, [' :param bar: ', '']) def test_render_rst_with_child(self): node = Arg(5, 10, 'bar') child = Node(indent=10, lines=["Description"], parent=node) node.add_child(child) rst = node.render_rst() self.assertEqual(rst, [' :param bar: Description', '']) def test_render_rst_with_children(self): node = Arg(5, 10, 'bar') child_a = Node(indent=10, lines=["ChildA"], parent=node) node.add_child(child_a) child_b = Node(indent=10, lines=["ChildB"], parent=node) node.add_child(child_b) rst = node.render_rst() self.assertEqual(rst, [' :param bar: ChildA', ' ChildB', '']) def test_render_rst_with_type(self): node = Arg(5, 10, 'bar') node.type = 'str' rst = node.render_rst() self.assertEqual(rst, [' :param bar: ', ' :type bar: str', '']) class RaisesTests(unittest.TestCase): def test_create_default_node(self): node = Raises() self.assertEqual(node.indent, 0) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_create_with_indent(self): node = Raises(indent=4) self.assertEqual(node.indent, 4) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_repr(self): node = Raises(5) actual = repr(node) expected = "Raises(5, children=[])" self.assertEqual(expected, actual) def test_add_one_child(self): node = Raises() child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Raises() child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_render_rst_empty(self): node = Raises() rst = node.render_rst() self.assertEqual(rst, [':raises:', '']) def test_render_rst_indent(self): node = Raises(indent=5) rst = node.render_rst() self.assertEqual(rst, [' :raises:', '']) def test_render_rst_with_child(self): node = Raises(5) child = Node(indent=10, lines=["Description"], parent=node) node.add_child(child) rst = node.render_rst() self.assertEqual(rst, [' :raises:', ' Description', '']) def test_render_rst_with_children(self): node = Raises(5) child_a = Node(indent=10, lines=["ChildA"], parent=node) node.add_child(child_a) child_b = Node(indent=10, lines=["ChildB"], parent=node) node.add_child(child_b) rst = node.render_rst() self.assertEqual(rst, [' :raises:', ' ChildA', ' ChildB', '']) class ExceptTests(unittest.TestCase): def test_create(self): node = Except(5, 'FooError') self.assertEqual(node.indent, 5) self.assertEqual(node.type, 'FooError') self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_add_one_child(self): node = Except(5, 'FooError') child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Except(5, 'FooError') child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_repr(self): node = Except(5,'FooError') actual = repr(node) expected = "Except('FooError', children=[])" self.assertEqual(expected, actual) def test_render_rst_empty(self): node = Except(5, 'FooError') rst = node.render_rst() self.assertEqual(rst, [' * FooError - ', '']) def test_render_rst_indent(self): node = Except(5, 'FooError') rst = node.render_rst() self.assertEqual(rst, [' * FooError - ', '']) def test_render_rst_with_child(self): node = Except(5, 'FooError') child = Node(indent=10, lines=["Description"], parent=node) node.add_child(child) rst = node.render_rst() self.assertEqual(rst, [' * FooError - Description', '']) def test_render_rst_with_children(self): node = Except(5, 'FooError') child_a = Node(indent=10, lines=["ChildA"], parent=node) node.add_child(child_a) child_b = Node(indent=10, lines=["ChildB"], parent=node) node.add_child(child_b) rst = node.render_rst() self.assertEqual(rst, [' * FooError - ChildA', ' ChildB', '']) class ReturnsTests(unittest.TestCase): def test_create(self): node = Returns(5) self.assertEqual(node.indent, 5) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_add_one_child(self): node = Returns(5) child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Returns(5) child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_repr(self): node = Returns(5) actual = repr(node) expected = "Returns(5, children=[])" self.assertEqual(expected, actual) # TODO test_render_rst class WarningTests(unittest.TestCase): def test_create(self): node = Warning(5) self.assertEqual(node.indent, 5) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_add_one_child(self): node = Warning(5) child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Warning(5) child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_repr(self): node = Warning(5) actual = repr(node) expected = "Warning(5, children=[])" self.assertEqual(expected, actual) # TODO test_render_rst class NoteTests(unittest.TestCase): def test_create(self): node = Note(5) self.assertEqual(node.indent, 5) self.assertEqual(node.lines, []) self.assertIsNone(node.parent) def test_add_one_child(self): node = Note(5) child = Node(parent=node) node.add_child(child) self.assertIs(node.children[0], child) def test_add_two_children(self): node = Note(5) child0 = Node(parent=node) child1 = Node(parent=node) node.add_child(child0) node.add_child(child1) self.assertIs(node.children[0], child0) self.assertIs(node.children[1], child1) def test_repr(self): node = Note(5) actual = repr(node) expected = "Note(5, children=[])" self.assertEqual(expected, actual) # TODO test_render_rst gnuradio-3.7.2.1/docs/sphinx/hieroglyph/test/test_hierglyph.py0000644000175000017500000002255011765410647024337 0ustar jcorganjcorganimport unittest from hieroglyph.hieroglyph import first_paragraph_indent, gather_lines, unindent __author__ = 'Robert Smallshire' class UnindentTests(unittest.TestCase): def test_zero_lines(self): source = [] expected = [] actual = unindent(source) self.assertEqual(actual, expected) def test_one_zero_indent_line(self): source = ["First line"] expected = [(0, "First line")] actual = unindent(source) self.assertEqual(actual, expected) def test_two_zero_indent_lines(self): source = ["First line", "Second line"] expected = [(0, "First line"), (0, "Second line")] actual = unindent(source) self.assertEqual(actual, expected) def test_two_indented_lines(self): source = [" First line", " Second line"] expected = [(4, "First line"), (6, "Second line")] actual = unindent(source) self.assertEqual(actual, expected) def test_whitespace_line(self): source = [" "] expected = [(4, "")] actual = unindent(source) self.assertEqual(actual, expected) def test_tab_line(self): source = ["\tHello"] expected = [(1, "Hello")] actual = unindent(source) self.assertEqual(actual, expected) class FirstParagraphIndentTests(unittest.TestCase): def test_zero_lines(self): source = [] expected = [] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_single_line_non_indented_comment(self): source = [(0, "A single line comment")] expected = [(0, "A single line comment")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_single_line_indented_comment(self): source = [(4, "A single line comment")] expected = [(4, "A single line comment")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_double_line_non_indented_comment(self): source = [(0, "The first line"), (0, "The second line")] expected = [(0, "The first line"), (0, "The second line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_double_line_indented_comment(self): source = [(4, "The first line"), (4, "The second line")] expected = [(4, "The first line"), (4, "The second line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_first_line_indent(self): source = [(4, "The first line"), (0, "The second line")] expected = [(4, "The first line"), (0, "The second line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_first_line_non_indent(self): source = [(0, "The first line"), (4, "The second line")] expected = [(4, "The first line"), (4, "The second line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_increasing_indent(self): source = [(0, "The first line"), (4, "The second line"), (8, "The third line")] expected = [(4, "The first line"), (4, "The second line"), (8, "The third line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_separate_paragraphs(self): source = [(0, "This is the first paragraph"), (0, ""), (4, "This is the second paragraph")] expected = [(0, "This is the first paragraph"), (0, ""), (4, "This is the second paragraph")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_separate_paragraphs_indented(self): source = [(4, "This is the first paragraph"), (4, ""), (8, "This is the second paragraph")] expected = [(4, "This is the first paragraph"), (4, ""), (8, "This is the second paragraph")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_separated_lines_first_line_non_indented(self): source = [(0, "The first line"), (0, ""), (4, "The third line")] expected = [(0, "The first line"), (0, ""), (4, "The third line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) def test_separated_lines_first_line_indented(self): source = [(4, "The first line"), (4, ""), (4, "The third line")] expected = [(4, "The first line"), (4, ""), (4, "The third line")] actual = first_paragraph_indent(source) self.assertEqual(actual, expected) class GatherLinesTests(unittest.TestCase): def test_empty(self): source = [] expected = [] actual = gather_lines(source) self.assertEqual(actual, expected) def test_one_liner(self): source = [(0, 'One liner')] expected = [(0, ['One liner'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_two_liner(self): source = [(0, 'First line'), (0, 'Second line')] expected = [(0, ['First line', 'Second line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_separated_lines(self): source = [(0, 'First line'), (0, ''), (0, 'Third line')] expected = [(0, ['First line', '']), (0, ['Third line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_separated_multi_lines(self): source = [(0, 'First line'), (0, 'Second line'), (0, ''), (0, 'Fourth line'), (0, 'Fifth line')] expected = [(0, ['First line', 'Second line', '']), (0, ['Fourth line', 'Fifth line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_indented_lines(self): source = [(0, 'First line'), (4, 'Second line')] expected = [(0, ['First line']), (4, ['Second line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_dedented_lines(self): source = [(4, 'First line'), (0, 'Second line')] expected = [(4, ['First line']), (0, ['Second line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_indented_multi_lines(self): source = [(0, 'First line'), (0, 'Second line'), (4, 'Third line'), (4, 'Fourth line')] expected = [(0, ['First line', 'Second line']), (4, ['Third line', 'Fourth line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_dedented_multi_lines(self): source = [(4, 'First line'), (4, 'Second line'), (0, 'Third line'), (0, 'Fourth line')] expected = [(4, ['First line', 'Second line']), (0, ['Third line', 'Fourth line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_indented_separated_multi_lines(self): source = [(0, 'First line'), (0, 'Second line'), (0, ''), (4, 'Fourth line'), (4, 'Fifth line')] expected = [(0, ['First line', 'Second line', '']), (4, ['Fourth line', 'Fifth line'])] actual = gather_lines(source) self.assertEqual(actual, expected) def test_dedented_separated_multi_lines(self): source = [(4, 'First line'), (4, 'Second line'), (4, ''), (0, 'Fourth line'), (0, 'Fifth line')] expected = [(4, ['First line', 'Second line', '']), (0, ['Fourth line', 'Fifth line'])] actual = gather_lines(source) self.assertEqual(actual, expected) gnuradio-3.7.2.1/docs/sphinx/hieroglyph/test/test_comments.py0000644000175000017500000006013511765410647024172 0ustar jcorganjcorganimport unittest from hieroglyph.hieroglyph import parse_hieroglyph_text from hieroglyph.errors import HieroglyphError class CommentTests(unittest.TestCase): def test_comment1(self): source = """Fetches rows from a Bigtable. This is a continuation of the opening paragraph. Retrieves rows pertaining to the given keys from the Table instance represented by big_table. Silly things may happen if other_silly_variable is not None. Args: big_table: An open Bigtable Table instance. keys: A sequence of strings representing the key of each table row to fetch. other_silly_variable (str): Another optional variable, that has a much longer name than the other args, and which does nothing. Returns: A dict mapping keys to the corresponding table row data fetched. Each row is represented as a tuple of strings. For example: {'Serak': ('Rigel VII', 'Preparer'), 'Zim': ('Irk', 'Invader'), 'Lrrr': ('Omicron Persei 8', 'Emperor')} If a key from the keys argument is missing from the dictionary, then that row was not found in the table. Raises: IOError: An error occurred accessing the bigtable.Table object. """ expected = """ Fetches rows from a Bigtable. This is a continuation of the opening paragraph. Retrieves rows pertaining to the given keys from the Table instance represented by big_table. Silly things may happen if other_silly_variable is not None. :param big_table: An open Bigtable Table instance. :param keys: A sequence of strings representing the key of each table row to fetch. :param other_silly_variable: Another optional variable, that has a much longer name than the other args, and which does nothing. :type other_silly_variable: str :returns: A dict mapping keys to the corresponding table row data fetched. Each row is represented as a tuple of strings. For example: {'Serak': ('Rigel VII', 'Preparer'), 'Zim': ('Irk', 'Invader'), 'Lrrr': ('Omicron Persei 8', 'Emperor')} If a key from the keys argument is missing from the dictionary, then that row was not found in the table. :raises: IOError - An error occurred accessing the bigtable.Table object. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment2(self): source = """Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: predicate: An optional single argument function used to test each elements. If omitted, the bool() function is used resulting in the elements being tested directly. Returns: True if all elements in the sequence meet the predicate condition, otherwise False. Raises: ValueError: If the Queryable is closed() TypeError: If predicate is not callable. """ expected = """Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. .. note:: This method uses immediate execution. :param predicate: An optional single argument function used to test each elements. If omitted, the bool() function is used resulting in the elements being tested directly. :returns: True if all elements in the sequence meet the predicate condition, otherwise False. :raises: * ValueError - If the Queryable is closed() * TypeError - If predicate is not callable. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment3(self): source = """Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: predicate: An optional single argument function used to test each elements. If omitted, the bool() function is used resulting in the elements being tested directly. Returns: True if all elements in the sequence meet the predicate condition, otherwise False. Raises: ValueError: If the Queryable is closed() TypeError: If predicate is not callable. """ expected = """Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. .. note:: This method uses immediate execution. :param predicate: An optional single argument function used to test each elements. If omitted, the bool() function is used resulting in the elements being tested directly. :returns: True if all elements in the sequence meet the predicate condition, otherwise False. :raises: * ValueError - If the Queryable is closed() * TypeError - If predicate is not callable. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment4(self): source_lines = [u'Determine if all elements in the source sequence satisfy a condition.', u'', u'All of the source sequence will be consumed.', u'', u'Note: This method uses immediate execution.', u'', u'Args:', u' predicate: An optional single argument function used to test each', u' elements. If omitted, the bool() function is used resulting in', u' the elements being tested directly.', u'', u'Returns:', u' True if all elements in the sequence meet the predicate condition,', u' otherwise False.', u'', u'Raises:', u' ValueError: If the Queryable is closed()', u' TypeError: If predicate is not callable.', u''] expected = """Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. .. note:: This method uses immediate execution. :param predicate: An optional single argument function used to test each elements. If omitted, the bool() function is used resulting in the elements being tested directly. :returns: True if all elements in the sequence meet the predicate condition, otherwise False. :raises: * ValueError - If the Queryable is closed() * TypeError - If predicate is not callable. """ actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment5(self): source_lines = [u'An empty Queryable.', u'', u'Note: The same empty instance will be returned each time.', u'', u'Returns: A Queryable over an empty sequence.', u''] expected = """An empty Queryable. .. note:: The same empty instance will be returned each time. :returns: A Queryable over an empty sequence. """ actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment6(self): source_lines = [u'A convenience factory for creating Records.', u'', u'Args:', u' **kwargs: Each keyword argument will be used to initialise an', u' attribute with the same name as the argument and the given', u' value.', u'', u'Returns:', u' A Record which has a named attribute for each of the keyword arguments.', u''] expected = """A convenience factory for creating Records. :param \*\*kwargs: Each keyword argument will be used to initialise an attribute with the same name as the argument and the given value. :returns: A Record which has a named attribute for each of the keyword arguments. """ actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment7(self): source = """Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function. Note: This method uses deferred execution. Args: collection_selector: A unary function mapping each element of the source iterable into an intermediate sequence. The single argument of the collection_selector is the value of an element from the source sequence. The return value should be an iterable derived from that element value. The default collection_selector, which is the identity function, assumes that each element of the source sequence is itself iterable. result_selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. The single argument of the result_selector is the value of an element from the flattened intermediate sequence. The return value should be the corresponding value in the result sequence. The default result_selector is the identity function. Returns: A Queryable over a generated sequence whose elements are the result of applying the one-to-many collection_selector to each element of the source sequence, concatenating the results into an intermediate sequence, and then mapping each of those elements through the result_selector into the result sequence. Raises: ValueError: If this Queryable has been closed. TypeError: If either collection_selector or result_selector are not callable. """ expected = """ Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function. .. note:: This method uses deferred execution. :param collection_selector: A unary function mapping each element of the source iterable into an intermediate sequence. The single argument of the collection_selector is the value of an element from the source sequence. The return value should be an iterable derived from that element value. The default collection_selector, which is the identity function, assumes that each element of the source sequence is itself iterable. :param result_selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. The single argument of the result_selector is the value of an element from the flattened intermediate sequence. The return value should be the corresponding value in the result sequence. The default result_selector is the identity function. :returns: A Queryable over a generated sequence whose elements are the result of applying the one-to-many collection_selector to each element of the source sequence, concatenating the results into an intermediate sequence, and then mapping each of those elements through the result_selector into the result sequence. :raises: * ValueError - If this Queryable has been closed. * TypeError - If either collection_selector or result_selector are not callable. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment8(self): source = """A convenience factory for creating Records. Args: **kwargs: Each keyword argument will be used to initialise an attribute with the same name as the argument and the given value. Returns: A Record which has a named attribute for each of the keyword arguments. """ expected = """A convenience factory for creating Records. :param \*\*kwargs: Each keyword argument will be used to initialise an attribute with the same name as the argument and the given value. :returns: A Record which has a named attribute for each of the keyword arguments. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment9(self): source_lines = [u'Parse a single line of a tree to determine depth and node.', u'', u'Args:', u' This line is missing an argument name.', u' ', u'Returns:', u' A 2-tuple containing the tree 0 based tree depth as the first', u' element and the node description as the second element.', u'', u'Raises:', u' ValueError: If line does not have the expected form.', u''] self.assertRaises(HieroglyphError, lambda: parse_hieroglyph_text(source_lines)) def test_comment10(self): source = """ Execute the command described by concatenating the string function arguments with the p4 -s global scripting flag and return the results in a dictionary. For example, to run the command:: p4 -s fstat -T depotFile foo.h call:: p4('fstat', '-T', 'depotFile', 'foo.h') Args: args: The arguments to the p4 command as a list of objects which will be converted to strings. Returns: A dictionary of lists where each key in the dictionary is the field name from the command output, and each value is a list of output lines in order. Raises: PerforceError: If the command could not be run or if the command reported an error. """ expected = """ Execute the command described by concatenating the string function arguments with the p4 -s global scripting flag and return the results in a dictionary. For example, to run the command:: p4 -s fstat -T depotFile foo.h call:: p4('fstat', '-T', 'depotFile', 'foo.h') :param args: The arguments to the p4 command as a list of objects which will be converted to strings. :returns: A dictionary of lists where each key in the dictionary is the field name from the command output, and each value is a list of output lines in order. :raises: PerforceError - If the command could not be run or if the command reported an error. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment11(self): source = """Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function. Warning: This method may explode at short notice. Args: collection_selector: A unary function mapping each element of the source iterable into an intermediate sequence. The single argument of the collection_selector is the value of an element from the source sequence. The return value should be an iterable derived from that element value. The default collection_selector, which is the identity function, assumes that each element of the source sequence is itself iterable. result_selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. The single argument of the result_selector is the value of an element from the flattened intermediate sequence. The return value should be the corresponding value in the result sequence. The default result_selector is the identity function. Returns: A Queryable over a generated sequence whose elements are the result of applying the one-to-many collection_selector to each element of the source sequence, concatenating the results into an intermediate sequence, and then mapping each of those elements through the result_selector into the result sequence. Raises: ValueError: If this Queryable has been closed. TypeError: If either collection_selector or result_selector are not callable. """ expected = """ Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function. .. warning:: This method may explode at short notice. :param collection_selector: A unary function mapping each element of the source iterable into an intermediate sequence. The single argument of the collection_selector is the value of an element from the source sequence. The return value should be an iterable derived from that element value. The default collection_selector, which is the identity function, assumes that each element of the source sequence is itself iterable. :param result_selector: An optional unary function mapping the elements in the flattened intermediate sequence to corresponding elements of the result sequence. The single argument of the result_selector is the value of an element from the flattened intermediate sequence. The return value should be the corresponding value in the result sequence. The default result_selector is the identity function. :returns: A Queryable over a generated sequence whose elements are the result of applying the one-to-many collection_selector to each element of the source sequence, concatenating the results into an intermediate sequence, and then mapping each of those elements through the result_selector into the result sequence. :raises: * ValueError - If this Queryable has been closed. * TypeError - If either collection_selector or result_selector are not callable. """ source_lines = source.splitlines() actual_lines = parse_hieroglyph_text(source_lines) expected_lines = expected.splitlines() self.assertEqual(len(actual_lines), len(expected_lines)) for actual_line, result_line in zip(actual_lines, expected_lines): if len(actual_line.strip()) == 0: self.assertTrue(len(result_line.strip()) == 0) else: self.assertEqual(actual_line, result_line) def test_comment12(self): source = """Determine if all elements in the source sequence satisfy a condition. All of the source sequence will be consumed. Note: This method uses immediate execution. Args: predicate: An optional single argument function used to test each elements. If omitted, the bool() function is used resulting in the elements being tested directly. Returns: True if all elements in the sequence meet the predicate condition, otherwise False. Raises: This is not a proper exception description """ source_lines = source.splitlines() self.assertRaises(HieroglyphError, lambda: parse_hieroglyph_text(source_lines)) gnuradio-3.7.2.1/docs/sphinx/hieroglyph/test/__init__.py0000644000175000017500000000002511765410647023035 0ustar jcorganjcorgan__author__ = 'rjs' gnuradio-3.7.2.1/docs/sphinx/hieroglyph/hieroglyph.py0000644000175000017500000003053211765410647022477 0ustar jcorganjcorganfrom __future__ import print_function import re from errors import HieroglyphError from nodes import (Node, Raises, Except, Note, Warning, Returns, Arg, ensure_terminal_blank) __author__ = 'Robert Smallshire' def parse_hieroglyph_text(lines): '''Parse text in hieroglyph format and return a reStructuredText equivalent Args: lines: A sequence of strings representing the lines of a single docstring as read from the source by Sphinx. This string should be in a format that can be parsed by hieroglyph. Returns: A list of lines containing the transformed docstring as reStructuredText as produced by hieroglyph. Raises: RuntimeError: If the docstring cannot be parsed. ''' indent_lines = unindent(lines) indent_lines = pad_blank_lines(indent_lines) indent_lines = first_paragraph_indent(indent_lines) indent_paragraphs = gather_lines(indent_lines) parse_tree = group_paragraphs(indent_paragraphs) syntax_tree = extract_structure(parse_tree) result = syntax_tree.render_rst() ensure_terminal_blank(result) return result def unindent(lines): '''Convert an iterable of indented lines into a sequence of tuples. The first element of each tuple is the indent in number of characters, and the second element is the unindented string. Args: lines: A sequence of strings representing the lines of text in a docstring. Returns: A list of tuples where each tuple corresponds to one line of the input list. Each tuple has two entries - the first is an integer giving the size of the indent in characters, the second is the unindented text. ''' unindented_lines = [] for line in lines: unindented_line = line.lstrip() indent = len(line) - len(unindented_line) unindented_lines.append((indent, unindented_line)) return unindented_lines def pad_blank_lines(indent_texts): '''Give blank (empty) lines the same indent level as the preceding line. Args: indent_texts: An iterable of tuples each containing an integer in the first element and a string in the second element. Returns: A list of tuples each containing an integer in the first element and a string in the second element. ''' current_indent = 0 result = [] for indent, text in indent_texts: if len(text) > 0: current_indent = indent result.append((current_indent, text)) return result def extract_structure(parse_tree): '''Create an Abstract Syntax Tree representing the semantics of a parse tree. Args: parse_tree: TODO Returns: A Node with is the result of an Abstract Syntax Tree representing the docstring. Raises: HieroglyphError: In the event that the parse tree cannot be understood. ''' return convert_node(parse_tree) def convert_node(node): if node.indent == 0 and len(node.lines) == 0: return convert_children(node) if node.lines[0].startswith('Args:'): return convert_args(node) if node.lines[0].startswith('Returns:'): return convert_returns(node) if node.lines[0].startswith('Raises:'): return convert_raises(node) if node.lines[0].startswith('Note:'): return convert_note(node) if node.lines[0].startswith('Warning:'): return convert_warning(node) result = convert_children(node) result.lines = node.lines result.indent = node.indent return result def convert_children(node): converted_children = [convert_node(child) for child in node.children] result = Node() result.children = converted_children return result ARG_REGEX = re.compile(r'(\*{0,2}\w+)(\s+\((\w+)\))?\s*:\s*(.*)') def append_child_to_args_group_node(child, group_node, indent): arg = None non_empty_lines = (line for line in child.lines if line) for line in non_empty_lines: m = ARG_REGEX.match(line) if m is None: raise HieroglyphError("Invalid hieroglyph argument syntax: {0}".format(line)) param_name = m.group(1) param_type = m.group(3) param_text = m.group(4) arg = Arg(indent, child.indent, param_name) group_node.children.append(arg) arg.type = param_type if param_text is not None: arg.children.append(Node(indent, [param_text], arg)) if arg is not None: last_child = arg.children[-1] if len(arg.children) != 0 else arg for grandchild in child.children: last_child.children.append(grandchild) def convert_args(node): assert node.lines[0].startswith('Args:') group_node = Node() for child in node.children: append_child_to_args_group_node(child, group_node, node.indent) return group_node def convert_returns(node): assert node.lines[0].startswith('Returns:') returns = Returns(node.indent) returns.line = node.lines[0][8:].strip() returns.children = node.children return returns def convert_note(node): assert node.lines[0].startswith('Note:') note = Note(node.indent) note.line = node.lines[0][5:].strip() note.children = node.children return note def convert_warning(node): assert node.lines[0].startswith('Warning:') warning = Warning(node.indent) warning.line = node.lines[0][8:].strip() warning.children = node.children return warning def convert_raises(node): assert node.lines[0].startswith('Raises:') group_node = Raises(node.indent) for child in node.children: append_child_to_raise_node(child, group_node) return group_node RAISE_REGEX = re.compile(r'(\w+)\s*:\s*(.*)') def extract_exception_type_and_text(line): m = RAISE_REGEX.match(line) if m is None: raise HieroglyphError("Invalid hieroglyph exception syntax: {0}".format(line)) return (m.group(2), m.group(1)) def append_child_to_raise_node(child, group_node): exception = None non_empty_lines = (line for line in child.lines if line) for line in non_empty_lines: exception_text, exception_type = extract_exception_type_and_text(line) exception = Except(child.indent, exception_type) group_node.children.append(exception) # TODO: Could use parent here. if exception_text is not None: exception.children.append( Node(child.indent, [exception_text], exception)) if exception is not None: last_child = exception.children[-1] if len(exception.children) != 0 else exception for grandchild in child.children: last_child.children.append(grandchild) def group_paragraphs(indent_paragraphs): ''' Group paragraphs so that more indented paragraphs become children of less indented paragraphs. ''' # The tree consists of tuples of the form (indent, [children]) where the # children may be strings or other tuples root = Node(0, [], None) current_node = root previous_indent = -1 for indent, lines in indent_paragraphs: if indent > previous_indent: current_node = create_child_node(current_node, indent, lines) elif indent == previous_indent: current_node = create_sibling_node(current_node, indent, lines) elif indent < previous_indent: current_node = create_uncle_node(current_node, indent, lines) previous_indent = indent return root def create_sibling_node(current_node, indent, lines): sibling = Node(indent, lines, current_node.parent) current_node.parent.add_child(sibling) current_node = sibling return current_node def create_child_node(current_node, indent, lines): child = Node(indent, lines, current_node) current_node.add_child(child) current_node = child return current_node def create_uncle_node(current_node, indent, lines): ancestor = current_node while ancestor.indent >= indent: if ancestor.parent is None: break ancestor = ancestor.parent uncle = Node(indent, lines, ancestor) ancestor.add_child(uncle) current_node = uncle return current_node def gather_lines(indent_lines): '''Split the list of (int, str) tuples into a list of (int, [str]) tuples to group the lines into paragraphs of consistent indent. ''' return remove_empty_paragraphs(split_separated_lines(gather_lines_by_indent(indent_lines))) def gather_lines_by_indent(indent_lines): result = [] previous_indent = -1 for indent, line in indent_lines: if indent != previous_indent: paragraph = (indent, []) result.append(paragraph) else: paragraph = result[-1] paragraph[1].append(line) previous_indent = indent return result def split_separated_lines(indent_paragraphs): result = [] for indent, paragraph in indent_paragraphs: result.append((indent, [])) if len(paragraph) > 0: result[-1][1].append(paragraph[0]) if len(paragraph) > 2: for line in paragraph[1: -1]: result[-1][1].append(line) if len(line) == 0: result.append((indent, [])) if len(paragraph) > 1: result[-1][1].append(paragraph[-1]) return result def remove_empty_paragraphs(indent_paragraphs): return [(indent, paragraph) for indent, paragraph in indent_paragraphs if len(paragraph)] def first_paragraph_indent(indent_texts): '''Fix the indentation on the first paragraph. This occurs because the first line of a multi-line docstring following the opening quote usually has no indent. Args: indent_texts: The lines of the docstring as an iterable over 2-tuples each containing an integer indent level as the first element and the text as the second element. Return: A list of 2-tuples, each containing an integer indent level as the first element and the text as the second element. ''' opening_indent = determine_opening_indent(indent_texts) result = [] input = iter(indent_texts) for indent, text in input: if indent == 0: result.append((opening_indent, text)) else: result.append((indent, text)) break for indent, text in input: result.append((indent, text)) return result def determine_opening_indent(indent_texts): '''Determine the opening indent level for a docstring. The opening indent level is the indent level is the first non-zero indent level of a non-empty line in the docstring. Args: indent_texts: The lines of the docstring as an iterable over 2-tuples each containing an integer indent level as the first element and the text as the second element. Returns: The opening indent level as an integer. ''' num_lines = len(indent_texts) if num_lines < 1: return 0 assert num_lines >= 1 first_line_indent = indent_texts[0][0] if num_lines == 1: return first_line_indent assert num_lines >= 2 second_line_indent = indent_texts[1][0] second_line_text = indent_texts[1][1] if len(second_line_text) == 0: return first_line_indent return second_line_indent def rewrite_autodoc(app, what, name, obj, options, lines): '''Convert lines from Hieroglyph to Sphinx format. The function to be called by the Sphinx autodoc extension when autodoc has read and processed a docstring. This function modified its ``lines`` argument *in place* replacing Hieroglyph syntax input into Sphinx reStructuredText output. Args: apps: The Sphinx application object. what: The type of object which the docstring belongs to. One of 'module', 'class', 'exception', 'function', 'method', 'attribute' name: The fully qualified name of the object. obj: The object itself. options: The options given to the directive. An object with attributes ``inherited_members``, ``undoc_members``, ``show_inheritance`` and ``noindex`` that are ``True`` if the flag option of the same name was given to the auto directive. lines: The lines of the docstring. Will be modified *in place*. ''' lines[:] = parse_hieroglyph_text(lines) def setup(app): app.connect('autodoc-process-docstring', rewrite_autodoc) gnuradio-3.7.2.1/docs/sphinx/hieroglyph/version.py0000644000175000017500000000010611765410647022004 0ustar jcorganjcorgan'''Specification of the hieroglyph version''' __version__ = '0.6' gnuradio-3.7.2.1/docs/sphinx/hieroglyph/__init__.py0000644000175000017500000000022711765410647022062 0ustar jcorganjcorgan# We only need to expose the setup function to Sphinx from .hieroglyph import setup from .version import __version__ __author__ = 'Robert Smallshire'gnuradio-3.7.2.1/docs/sphinx/hieroglyph/nodes.py0000644000175000017500000001737211765410647021444 0ustar jcorganjcorgan__author__ = 'Robert Smallshire' class Node(object): def __init__(self, indent=None, lines=None, parent=None): if indent is not None: self.indent = indent else: self.indent = 0 if lines is not None: self.lines = lines else: self.lines = [] self._parent = parent self.children = [] parent = property(lambda self: self._parent) def add_child(self, child): assert(child.parent is self) self.children.append(child) def __repr__(self): return "Node(" + repr(self.indent) + ", " + repr(self.lines) + ", children=" + repr(self.children) + ")" def render_rst(self, *args, **kwargs): result = [] prefix = ' ' * self.indent result.extend(prefix + line for line in self.lines) for child in self.children: result.extend(child.render_rst()) return result class Arg(Node): def __init__(self, indent, child_indent, name): super(Arg, self).__init__(indent) self.child_indent = child_indent self.name = name self.type = None def __repr__(self): return "Arg(" + repr(self.name) + ", " + repr(self.type) + ", children=" + repr(self.children) + ")" def render_rst(self, *args, **kwargs): result = [] indent = ' ' * self.indent # Render the param description description = [] for child in self.children: child_lines = child.render_rst() description.extend(child_lines) dedent = self.child_indent - self.indent name = self.name.replace('*', r'\*') first_description = description[0].lstrip() if len(description) else '' if not first_description: # TODO: Emit a warning about a missing argument description pass result.append("{indent}:param {name}: {first_description}".format(indent=indent, name=name, first_description=first_description)) dedented_body = [line[dedent:] for line in description[1:]] result.extend(dedented_body) # If a type was specified render the type if self.type is not None: result.append("{indent}:type {name}: {type}".format(indent=indent, name=self.name, type=self.type)) result.append('') ensure_terminal_blank(result) return result class Raises(Node): def __init__(self, indent=None): super(Raises, self).__init__(indent=indent) def __repr__(self): return "Raises(" + repr(self.indent) + ", children=" + repr(self.children) + ")" def render_rst(self, *args, **kwargs): result = [] indent = ' ' * self.indent result.append(indent + ':raises:') for child in self.children: result.extend(child.render_rst(only_child=len(self.children) == 1)) ensure_terminal_blank(result) return result class Except(Node): def __init__(self, indent, type): super(Except, self).__init__(indent=indent) #self.child_indent = child_indent self.type = type def __repr__(self): return "Except(" + repr(self.type) + ", children=" + repr(self.children) + ")" def render_rst(self, only_child=False, *args, **kwargs): result = [] indent = ' ' * self.indent # Render the param description description = [] for child in self.children: child_lines = child.render_rst() description.extend(child_lines) #dedent = self.child_indent - self.indent bullet = '* ' if not only_child else '' first_description = description[0].lstrip() if len(description) else '' result.append("{indent}{bullet}{type} - {first_description}".format(indent=indent, bullet=bullet, type=self.type, first_description=first_description)) #dedented_body = [' ' * len(bullet) + line[dedent:] for line in description[1:]] #result.extend(dedented_body) result.extend(description[1:]) ensure_terminal_blank(result) return result class Returns(Node): def __init__(self, indent): super(Returns, self).__init__(indent=indent) self.title = 'Returns' self.line = '' def __repr__(self): return "Returns(" + str(self.indent) + ", children=" + str(self.children) + ")" def render_rst(self, *args, **kwargs): result = [] indent = ' ' * self.indent # Render the param description description = [self.line] if self.line else [] for child in self.children: child_lines = child.render_rst() description.extend(child_lines) self.render_title(description, indent, result) result.extend(description[1:]) ensure_terminal_blank(result) return result def render_title(self, description, indent, result): result.append( "{indent}:returns: {first_description}".format(indent=indent, first_description=description[0].lstrip())) class Warning(Node): def __init__(self, indent): super(Warning, self).__init__(indent=indent) def __repr__(self): return "Warning(" + repr(self.indent) + ", children=" + str(self.children) + ")" def render_rst(self, *args, **kwargs): # TODO: Factor out the commonality between this and Note below result = [] indent = ' ' * self.indent # Render the param description description = [self.line] if self.line else [] for child in self.children: child_lines = child.render_rst() description.extend(child_lines) # Fix the indent on the first line if len(description) > 1 and len(description[1].strip()) != 0: body_indent = len(description[1]) - len(description[1].strip()) else: body_indent = self.indent + 4 if len(description) > 0: description[0] = ' ' * body_indent + description[0] result.append(indent + ".. warning::") result.append(indent + '') result.extend(description) ensure_terminal_blank(result) return result class Note(Node): def __init__(self, indent): super(Note, self).__init__(indent=indent) self.line = '' def __repr__(self): return "Note(" + repr(self.indent) + ", children=" + str(self.children) + ")" def render_rst(self, *args, **kwargs): # TODO: Factor out the commonality between this and Warning above result = [] indent = ' ' * self.indent # Render the param description description = [self.line] if self.line else [] for child in self.children: child_lines = child.render_rst() description.extend(child_lines) # Fix the indent on the first line if len(description) > 1 and len(description[1].strip()) != 0: body_indent = len(description[1]) - len(description[1].strip()) else: body_indent = self.indent + 4 if len(description) > 0: description[0] = ' ' * body_indent + description[0] result.append(indent + ".. note::") result.append(indent + '') result.extend(description) ensure_terminal_blank(result) return result def ensure_terminal_blank(result): '''If the description didn't end with a blank line add one here.''' if len(result) > 0: if len(result[-1].strip()) != 0: result.append('') gnuradio-3.7.2.1/docs/sphinx/gnuradio_sphinx.py0000664000175000017500000001660112207440367021351 0ustar jcorganjcorgan""" Customizations of sphinx for gnuradio use. """ from sphinx.ext.autodoc import py_ext_sig_re from sphinx.ext.autodoc import ClassDocumenter, FunctionDocumenter, members_option from sphinx.ext.autodoc import bool_option, members_set_option, identity from sphinx.ext.autodoc import ALL # A dictionary of the number of lines to delete from the beginning of docstrings lines_to_delete = {} def setup(sp): # Fix line-breaks in signature. sp.connect('autodoc-process-signature', fix_signature) sp.connect('autodoc-process-docstring', remove_lines) # Add node to autodocument signal-processing blocks. sp.add_autodocumenter(OldBlockDocumenter) sp.add_autodocumenter(BlockDocumenter) sp.add_autodocumenter(PyBlockDocumenter) def remove_lines(app, what, name, obj, options, lines): del_lines = lines_to_delete.get(name, 0) # Don't delete any lines if this is called again. lines_to_delete[name] = 0 lines[:] = lines[del_lines:] def fix_signature(app, what, name, obj, options, signature, return_annotation): """ SWIG produces signature at the top of docstrings of the form 'blah(int arg1, float arg2) -> return_type' and if the string is long it breaks it over multiple lines. Sphinx gets confused if it is broken over multiple lines. fix_signature and remove_lines get around this problem. """ if return_annotation is not None: return if hasattr(obj, '__doc__'): docs = obj.__doc__ else: docs = None if not docs: return None doclines = docs.split('\n') del_lines = remove_linebreaks_in_signature(doclines) # match first line of docstring against signature RE match = py_ext_sig_re.match(doclines[0]) if not match: return None exmod, path, base, args, retann = match.groups() # ok, now jump over remaining empty lines and set the remaining # lines as the new doclines i = 1 while i < len(doclines) and not doclines[i].strip(): i += 1 lines_to_delete[name] = i - 1 + del_lines # format args signature = "({0})".format(args) return signature, retann def remove_linebreaks_in_signature(lines): alllines = '\n'.join(lines) alllines = alllines.lstrip() bits = alllines.split('->') if len(bits) == 1: return 0 after = '->'.join(bits[1:]) after_lines = after.split('\n') ending = None remainder = [] for line in after_lines: if line and ending is None: ending = line elif ending is not None: remainder.append(line) first_line = ' '.join([a.strip() for a in bits[0].split('\n') if a.strip()]) + ' -> ' + ending.strip() match = py_ext_sig_re.match(first_line) # If it is a signature, make the change to lines. if match: new_lines = [first_line] + remainder lines[:] = new_lines return len(bits[0].split('\n')) else: return 0 # These methods are not displayed in the documentation of blocks to # avoid redundancy. common_block_members =[ 'check_topology', 'detail', 'history', 'input_signature', 'name', 'nitems_read', 'nitems_written', 'nthreads', 'output_multiple', 'output_signature', 'relative_rate', 'set_detail', 'set_nthreads', 'start', 'stop', 'thisown', 'to_basic_block', 'unique_id', 'make', 'alias', 'is_set_max_noutput_items', 'max_noutput_items', 'max_output_buffer', 'message_ports_in', 'message_ports_out', 'min_output_buffer', 'pc_input_buffers_full', 'pc_input_buffers_full_var', 'pc_noutput_items', 'pc_noutput_items_var', 'pc_nproduced', 'pc_nproduced_var', 'pc_output_buffers_full', 'pc_output_buffers_full_var', 'pc_work_time', 'pc_work_time_var', 'processor_affinity', 'set_block_alias', 'set_max_noutput_items', 'unset_max_noutput_items', 'set_max_output_buffer', 'set_min_output_buffer', 'set_processor_affinity', 'symbol_name', 'unset_processor_affinity', 'disconnect_all', 'index', 'length', 'lock', 'primitive_connect', 'primitive_disconnect', 'primitive_message_port_register_hier_in', 'primitive_message_port_register_hier_out', 'primitive_msg_connect', 'primitive_msg_disconnect', 'to_hier_block2', 'type', 'unlock', ] class OldBlockDocumenter(FunctionDocumenter): """ Specialized Documenter subclass for gnuradio blocks. It merges together the documentation for the generator function (e.g. blocks.head) with the wrapped sptr (e.g. gr::blocks::head::sptr) to keep the documentation tidier. """ objtype = 'oldblock' directivetype = 'function' # Don't want to use this for generic functions for give low priority. priority = -10 def __init__(self, *args, **kwargs): super(OldBlockDocumenter, self).__init__(*args, **kwargs) # Get class name bits = self.name.split('.') if len(bits) != 3 or bits[0] != 'gnuradio': raise ValueError("expected name to be of form gnuradio.x.y but it is {0}".format(self.name)) sptr_name = 'gnuradio.{0}.{0}_{1}_sptr'.format(bits[1], bits[2]) # Create a Class Documenter to create documentation for the classes members. self.classdoccer = ClassDocumenter(self.directive, sptr_name, indent=self.content_indent) self.classdoccer.doc_as_attr = False self.classdoccer.real_modname = self.classdoccer.get_real_modname() self.classdoccer.options.members = ALL self.classdoccer.options.exclude_members = common_block_members self.classdoccer.parse_name() self.classdoccer.import_object() def document_members(self, *args, **kwargs): return self.classdoccer.document_members(*args, **kwargs) class BlockDocumenter(FunctionDocumenter): """ Specialized Documenter subclass for new style gnuradio blocks. It merges together the documentation for the generator function (e.g. wavelet.squash_ff) with the wrapped sptr (e.g. wavelet.squash_ff_sptr) to keep the documentation tidier. """ objtype = 'block' directivetype = 'function' # Don't want to use this for generic functions for give low priority. priority = -10 def __init__(self, *args, **kwargs): super(BlockDocumenter, self).__init__(*args, **kwargs) # Get class name sptr_name = self.name + '_sptr' # Create a Class Documenter to create documentation for the classes members. self.classdoccer = ClassDocumenter(self.directive, sptr_name, indent=self.content_indent) self.classdoccer.doc_as_attr = False self.classdoccer.real_modname = self.classdoccer.get_real_modname() self.classdoccer.options.members = ALL self.classdoccer.options.exclude_members = common_block_members self.classdoccer.parse_name() self.classdoccer.import_object() def document_members(self, *args, **kwargs): return self.classdoccer.document_members(*args, **kwargs) class PyBlockDocumenter(ClassDocumenter): """ Specialized Documenter subclass for hierarchical python gnuradio blocks. """ objtype = 'pyblock' directivetype = 'class' def __init__(self, *args, **kwargs): super(PyBlockDocumenter, self).__init__(*args, **kwargs) self.options.members = ALL self.options.exclude_members = common_block_members gnuradio-3.7.2.1/docs/sphinx/README0000644000175000017500000000641611765410647016465 0ustar jcorganjcorganINTRODUCTION The Sphinx documentation system uses the fully installed Python tree to build a set of documents (generally in HTML). In GNU Radio, the documentation system is done through Doxygen in the public header (/include/foo.h) files. Doxygen first builds its documentation files, then the swig_docs program uses Doxygen's XML output and smashed the documentation from each header file into the SWIG'd Python block. Basically, using a single documentation markup, Doxygen, we expose the documentation strings in both the Doxygen-built manual and within the Python blocks themselves. Sphinx takes this process one step farther by reading the docstrings of all Python blocks and creating its own manual. This has two benefits. First, the Sphinx documentation looks nice and is formatted in such a way that Python users of GNU Radio can easy see the module structure and hierarchy. It also not only takes the Doxygen documentation from C++, but it also allows us to take any Python files and include their documentation. The end result is two manuals: one for Python and one for C++ users without having to duplicate comments, markup, or documentation. BUILDING THE SPHINX MANUAL Building the Sphinx docs takes some manual intervention as it requires GNU Radio to already be installed. So first follow the steps to build and install GNU Radio. In the build directory, a helper file is created called run_sphinx_build.sh. This is a Linux shell script that runs the sphinx-build command with all of the normal settings and important directories preloaded. For non Linux systems, it should be easy to pull out the executable and options to run it by hand. The run_sphinx_build.sh outputs the manual into $builddir/docs/sphinx/sphinx_out. Open up the index.html file in a browser to view it. ADDING NEW CONTENT TO THE SPHINX MANUAL Although the content of the sphinx manual is automatically generated, new blocks are not automatically added to the generated documentation. The procedure for adding new content is best illustrated with two examples. 1) Adding a new C++ signal processing block gnuradio.gr.myslicer Edit file gnuradio/docs/sphinx/source/gr/index.rst and add the line > gnuradio.gr.myslicer under the "Slicing and Dicing Streams" subheading. Edit file gnuradio/docs/sphinx/source/gr/slicedice_blk.rst and add the line >.. autooldblock:: gnuradio.gr.myslicer 2) Adding a new python hierarchical block gnuradio.digital.mymod Edit file gnruadio/docs/sphinx/source/digital/index.rst and add the line > gnuradio.digital.mymod under the "Signal Processing Blocks" subheading. Edit file gnuradio/docs/sphinx/source/digital/blocks.rst and add the line >.. autopyblock:: gnuradio.digital.mymod Notice that the 'autopyblock' directive is used rather than the 'autoblock' directive. This lets sphinx know that it is displaying a python hierarchical signal processing block so that it can format it appropriately. The process for documenting objects that are not signal processing blocks is similar but rather than using the 'autooldblock', and 'autopyblock' directives the standard sphinx directives such as 'autofunction' and 'autoclass' can be used. Finally for signal processing blocks using the 3.7 style the directive 'autoblock' rather than 'autooldblock' can be used.gnuradio-3.7.2.1/docs/sphinx/run_sphinx_build.sh.in0000664000175000017500000000043712207440367022113 0ustar jcorganjcorgan#!/bin/bash echo "Creating Sphinx documentation in: @CMAKE_CURRENT_BINARY_DIR@/sphinx_out" LD_LIBRARY_PATH="@CMAKE_INSTALL_PREFIX@/lib:$LD_LIBRARY_PATH" @SPHINX_EXECUTABLE@ -b html -c @CMAKE_CURRENT_BINARY_DIR@/ @CMAKE_CURRENT_SOURCE_DIR@/source @CMAKE_CURRENT_BINARY_DIR@/sphinx_out gnuradio-3.7.2.1/docs/sphinx/source/0000755000175000017500000000000012207440367017070 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/eng_notation/0000755000175000017500000000000011765410647021562 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/eng_notation/index.rst0000644000175000017500000000027311765410647023425 0ustar jcorganjcorgangnuradio.eng_notation ===================== .. automodule:: gnuradio.eng_notation .. autofunction:: gnuradio.eng_notation.num_to_str .. autofunction:: gnuradio.eng_notation.str_to_num gnuradio-3.7.2.1/docs/sphinx/source/uhd.rst0000664000175000017500000000077712207440367020417 0ustar jcorganjcorgangnuradio.uhd ============ .. automodule:: gnuradio.uhd .. autoblock:: gnuradio.uhd.usrp_sink .. autoblock:: gnuradio.uhd.usrp_source .. autoblock:: gnuradio.uhd.amsg_source .. autoclass:: gnuradio.uhd.stream_cmd_t .. autoclass:: gnuradio.uhd.time_spec_t .. autoclass:: gnuradio.uhd.meta_range_t .. autoclass:: gnuradio.uhd.stream_args_t .. autoclass:: gnuradio.uhd.device_addr_t .. autoclass:: gnuradio.uhd.tune_request_t .. autoclass:: gnuradio.uhd.tune_result_t .. autoclass:: gnuradio.uhd.sensor_value_t gnuradio-3.7.2.1/docs/sphinx/source/pmt/0000775000175000017500000000000012207440367017672 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/pmt/any.rst0000664000175000017500000000021312207440367021207 0ustar jcorganjcorganpmt: Any ======== .. autofunction:: pmt.is_any .. autofunction:: pmt.make_any .. autofunction:: pmt.any_ref .. autofunction:: pmt.any_set gnuradio-3.7.2.1/docs/sphinx/source/pmt/symbol.rst0000664000175000017500000000024612207440367021733 0ustar jcorganjcorganpmt: Symbols ============ .. autofunction:: pmt.is_symbol .. autofunction:: pmt.string_to_symbol .. autofunction:: pmt.symbol_to_string .. autofunction:: pmt.intern gnuradio-3.7.2.1/docs/sphinx/source/pmt/misc.rst0000664000175000017500000000063012207440367021356 0ustar jcorganjcorganpmt: Misc ========= .. autofunction:: pmt.is_null .. autofunction:: pmt.cvar pmt: Generic Casts ================== .. autofunction:: pmt.to_pmt .. autofunction:: pmt.to_python .. autofunction:: pmt.pmt_to_python.pmt_to_python pmt: Constants ============== .. autofunction:: pmt.PMT_EOF .. autofunction:: pmt.PMT_EOF .. autofunction:: pmt.PMT_F .. autofunction:: pmt.PMT_NIL .. autofunction:: pmt.PMT_T gnuradio-3.7.2.1/docs/sphinx/source/pmt/number.rst0000664000175000017500000000007312207440367021714 0ustar jcorganjcorganpmt: Numbers ============ .. autofunction:: pmt.is_number gnuradio-3.7.2.1/docs/sphinx/source/pmt/integer.rst0000664000175000017500000000037412207440367022065 0ustar jcorganjcorganpmt: Integers ============= .. autofunction:: pmt.is_integer .. autofunction:: pmt.to_long .. autofunction:: pmt.from_long pmt: uint64_t ============= .. autofunction:: pmt.is_uint64 .. autofunction:: pmt.to_uint64 .. autofunction:: pmt.from_uint64 gnuradio-3.7.2.1/docs/sphinx/source/pmt/tuple.rst0000664000175000017500000000022712207440367021556 0ustar jcorganjcorganpmt: BLOBs ========== .. autofunction:: pmt.is_blob .. autofunction:: pmt.make_blob .. autofunction:: pmt.blob_data .. autofunction:: pmt.blob_length gnuradio-3.7.2.1/docs/sphinx/source/pmt/list.rst0000664000175000017500000000106712207440367021403 0ustar jcorganjcorganpmt: Lists ========== .. autofunction:: pmt.map .. autofunction:: pmt.reverse .. autofunction:: pmt.reverse_x .. autofunction:: pmt.acons .. autofunction:: pmt.nth .. autofunction:: pmt.nthcdr .. autofunction:: pmt.memq .. autofunction:: pmt.memv .. autofunction:: pmt.member .. autofunction:: pmt.subsetp .. autofunction:: pmt.list1 .. autofunction:: pmt.list2 .. autofunction:: pmt.list3 .. autofunction:: pmt.list4 .. autofunction:: pmt.list5 .. autofunction:: pmt.list6 .. autofunction:: pmt.list_add .. autofunction:: pmt.list_rm .. autofunction:: pmt.list_has gnuradio-3.7.2.1/docs/sphinx/source/pmt/pair.rst0000664000175000017500000000054512207440367021363 0ustar jcorganjcorganpmt: Pairs ========== .. autofunction:: pmt.is_pair .. autofunction:: pmt.cons .. autofunction:: pmt.car .. autofunction:: pmt.cdr .. autofunction:: pmt.set_car .. autofunction:: pmt.set_cdr .. autofunction:: pmt.caar .. autofunction:: pmt.cadddr .. autofunction:: pmt.caddr .. autofunction:: pmt.cadr .. autofunction:: pmt.cdar .. autofunction:: pmt.cddr gnuradio-3.7.2.1/docs/sphinx/source/pmt/dictionary.rst0000664000175000017500000000050512207440367022571 0ustar jcorganjcorganpmt: Dictionary =============== .. autofunction:: pmt.is_dict .. autofunction:: pmt.make_dict .. autofunction:: pmt.dict_add .. autofunction:: pmt.dict_delete .. autofunction:: pmt.dict_has_key .. autofunction:: pmt.dict_ref .. autofunction:: pmt.dict_items .. autofunction:: pmt.dict_keys .. autofunction:: pmt.dict_values gnuradio-3.7.2.1/docs/sphinx/source/pmt/index.rst0000664000175000017500000001102212207440367021527 0ustar jcorganjcorganpmt === .. automodule:: pmt Boolean ------- .. autosummary:: :nosignatures: pmt.is_bool pmt.is_true pmt.is_false pmt.from_bool pmt.to_bool Symbols ------- .. autosummary:: :nosignatures: pmt.is_symbol pmt.string_to_symbol pmt.symbol_to_string pmt.intern Numbers ------- .. autosummary:: :nosignatures: pmt.is_number Integers -------- .. autosummary:: :nosignatures: pmt.is_integer pmt.to_long pmt.from_long uint64_t --------- .. autosummary:: :nosignatures: pmt.is_uint64 pmt.to_uint64 pmt.from_uint64 Reals ----- .. autosummary:: :nosignatures: pmt.is_real pmt.to_double pmt.from_double Complex ------- .. autosummary:: :nosignatures: pmt.is_complex pmt.to_complex pmt.from_complex pmt.make_rectangular Pairs ----- .. autosummary:: :nosignatures: pmt.is_pair pmt.cons pmt.car pmt.cdr pmt.set_car pmt.set_cdr pmt.caar pmt.cadddr pmt.caddr pmt.cadr pmt.cdar pmt.cddr Tuples ------ .. autosummary:: :nosignatures: pmt.is_tuple pmt.make_tuple pmt.tuple_ref pmt.to_tuple Vectors ------- .. autosummary:: :nosignatures: pmt.is_vector pmt.make_vector pmt.vector_ref pmt.vector_set pmt.vector_fill BLOBs ----- .. autosummary:: :nosignatures: pmt.is_blob pmt.make_blob pmt.blob_data pmt.blob_length Uniform Numeric Vectors ----------------------- .. autosummary:: :nosignatures: pmt.is_uniform_vector pmt.is_u8vector pmt.is_u16vector pmt.is_u32vector pmt.is_u64vector pmt.is_s16vector pmt.is_s32vector pmt.is_s64vector pmt.is_s8vector pmt.is_c32vector pmt.is_c64vector pmt.is_f32vector pmt.is_f64vector pmt.make_u8vector pmt.make_u16vector pmt.make_u32vector pmt.make_u64vector pmt.make_s8vector pmt.make_s16vector pmt.make_s32vector pmt.make_s64vector pmt.make_c32vector pmt.make_c64vector pmt.make_f32vector pmt.make_f64vector pmt.init_u8vector pmt.init_u16vector pmt.init_u32vector pmt.init_u64vector pmt.init_s8vector pmt.init_s16vector pmt.init_s32vector pmt.init_s64vector pmt.init_c32vector pmt.init_c64vector pmt.init_f32vector pmt.init_f64vector pmt.c32vector_ref pmt.c64vector_ref pmt.f32vector_ref pmt.f64vector_ref pmt.s16vector_ref pmt.s32vector_ref pmt.s64vector_ref pmt.s8vector_ref pmt.u16vector_ref pmt.u32vector_ref pmt.u64vector_ref pmt.u8vector_ref pmt.c32vector_set pmt.c64vector_set pmt.f32vector_set pmt.f64vector_set pmt.s16vector_set pmt.s32vector_set pmt.s64vector_set pmt.s8vector_set pmt.u16vector_set pmt.u32vector_set pmt.u64vector_set pmt.u8vector_set pmt.uniform_vector_elements pmt.c32vector_elements pmt.c64vector_elements pmt.f32vector_elements pmt.f64vector_elements pmt.s16vector_elements pmt.s32vector_elements pmt.s8vector_elements pmt.u16vector_elements pmt.u32vector_elements pmt.u8vector_elements Dictionary ---------- .. autosummary:: :nosignatures: pmt.is_dict pmt.make_dict pmt.dict_add pmt.dict_delete pmt.dict_has_key pmt.dict_ref pmt.dict_items pmt.dict_keys pmt.dict_values Any --- .. autosummary:: :nosignatures: pmt.is_any pmt.make_any pmt.any_ref pmt.any_set Message Accepter ---------------- .. autosummary:: :nosignatures: pmt.is_msg_accepter pmt.make_msg_accepter pmt.msg_accepter_ref General Functions ----------------- .. autosummary:: :nosignatures: pmt.eq pmt.equal pmt.eqv pmt.length pmt.assq pmt.assv pmt_assoc Lists ----- .. autosummary:: :nosignatures: pmt.map pmt.reverse pmt.reverse_x pmt.acons pmt.nth pmt.nthcdr pmt.memq pmt.memv pmt.member pmt.subsetp pmt.list1 pmt.list2 pmt.list3 pmt.list4 pmt.list5 pmt.list6 pmt.list_add pmt.list_rm pmt.list_has Read/Write ---------- .. autosummary:: :nosignatures: pmt.is_eof_object pmt.read pmt.write pmt.write_string Serialize --------- .. autosummary:: :nosignatures: pmt.serialize pmt.deserialize pmt.dump_sizeof pmt.serialize_str pmt.deserialize_str Misc ---- .. autosummary:: :nosignatures: pmt.is_null pmt.cvar Generic Casts ------------- .. autosummary:: :nosignatures: pmt.to_pmt pmt.to_python pmt.pmt_to_python.pmt_to_python Constants -------- .. autosummary:: :nosignatures: pmt.PMT_EOF pmt.PMT_EOF pmt.PMT_F pmt.PMT_NIL pmt.PMT_T gnuradio-3.7.2.1/docs/sphinx/source/pmt/vector.rst0000664000175000017500000000554512207440367021737 0ustar jcorganjcorganpmt: Vectors ============ .. autofunction:: pmt.is_vector .. autofunction:: pmt.make_vector .. autofunction:: pmt.vector_ref .. autofunction:: pmt.vector_set .. autofunction:: pmt.vector_fill pmt: Uniform Numeric Vectors ============================ .. autofunction:: pmt.is_uniform_vector .. autofunction:: pmt.is_u8vector .. autofunction:: pmt.is_u16vector .. autofunction:: pmt.is_u32vector .. autofunction:: pmt.is_u64vector .. autofunction:: pmt.is_s16vector .. autofunction:: pmt.is_s32vector .. autofunction:: pmt.is_s64vector .. autofunction:: pmt.is_s8vector .. autofunction:: pmt.is_c32vector .. autofunction:: pmt.is_c64vector .. autofunction:: pmt.is_f32vector .. autofunction:: pmt.is_f64vector .. autofunction:: pmt.make_u8vector .. autofunction:: pmt.make_u16vector .. autofunction:: pmt.make_u32vector .. autofunction:: pmt.make_u64vector .. autofunction:: pmt.make_s8vector .. autofunction:: pmt.make_s16vector .. autofunction:: pmt.make_s32vector .. autofunction:: pmt.make_s64vector .. autofunction:: pmt.make_c32vector .. autofunction:: pmt.make_c64vector .. autofunction:: pmt.make_f32vector .. autofunction:: pmt.make_f64vector .. autofunction:: pmt.init_u8vector .. autofunction:: pmt.init_u16vector .. autofunction:: pmt.init_u32vector .. autofunction:: pmt.init_u64vector .. autofunction:: pmt.init_s8vector .. autofunction:: pmt.init_s16vector .. autofunction:: pmt.init_s32vector .. autofunction:: pmt.init_s64vector .. autofunction:: pmt.init_c32vector .. autofunction:: pmt.init_c64vector .. autofunction:: pmt.init_f32vector .. autofunction:: pmt.init_f64vector .. autofunction:: pmt.c32vector_ref .. autofunction:: pmt.c64vector_ref .. autofunction:: pmt.f32vector_ref .. autofunction:: pmt.f64vector_ref .. autofunction:: pmt.s16vector_ref .. autofunction:: pmt.s32vector_ref .. autofunction:: pmt.s64vector_ref .. autofunction:: pmt.s8vector_ref .. autofunction:: pmt.u16vector_ref .. autofunction:: pmt.u32vector_ref .. autofunction:: pmt.u64vector_ref .. autofunction:: pmt.u8vector_ref .. autofunction:: pmt.c32vector_set .. autofunction:: pmt.c64vector_set .. autofunction:: pmt.f32vector_set .. autofunction:: pmt.f64vector_set .. autofunction:: pmt.s16vector_set .. autofunction:: pmt.s32vector_set .. autofunction:: pmt.s64vector_set .. autofunction:: pmt.s8vector_set .. autofunction:: pmt.u16vector_set .. autofunction:: pmt.u32vector_set .. autofunction:: pmt.u64vector_set .. autofunction:: pmt.u8vector_set .. autofunction:: pmt.uniform_vector_elements .. autofunction:: pmt.c32vector_elements .. autofunction:: pmt.c64vector_elements .. autofunction:: pmt.f32vector_elements .. autofunction:: pmt.f64vector_elements .. autofunction:: pmt.s16vector_elements .. autofunction:: pmt.s32vector_elements .. autofunction:: pmt.s8vector_elements .. autofunction:: pmt.u16vector_elements .. autofunction:: pmt.u32vector_elements .. autofunction:: pmt.u8vector_elements gnuradio-3.7.2.1/docs/sphinx/source/pmt/real.rst0000664000175000017500000000043712207440367021353 0ustar jcorganjcorganpmt: Reals ========== .. autofunction:: pmt.is_real .. autofunction:: pmt.to_double .. autofunction:: pmt.from_double pmt: Complex ============ .. autofunction:: pmt.is_complex .. autofunction:: pmt.to_complex .. autofunction:: pmt.from_complex .. autofunction:: pmt.make_rectangular gnuradio-3.7.2.1/docs/sphinx/source/pmt/generalfunctions.rst0000664000175000017500000000076212207440367023777 0ustar jcorganjcorganpmt: General Functions ====================== pmt.map pmt.reverse pmt.reverse_x pmt.acons pmt.nth pmt.nthcdr pmt.memq pmt.memv pmt.member pmt.subsetp pmt.list1 pmt.list2 pmt.list3 pmt.list4 pmt.list5 pmt.list6 pmt.list_add pmt.list_rm pmt.list_has .. autofunction:: pmt.eq .. autofunction:: pmt.equal .. autofunction:: pmt.eqv .. autofunction:: pmt.length .. autofunction:: pmt.assq .. autofunction:: pmt.assv .. autofunction:: pmt.assoc gnuradio-3.7.2.1/docs/sphinx/source/pmt/boolean.rst0000664000175000017500000000026612207440367022047 0ustar jcorganjcorganpmt: Booleans ============= .. autofunction:: pmt.is_bool .. autofunction:: pmt.is_true .. autofunction:: pmt.is_false .. autofunction:: pmt.from_bool .. autofunction:: pmt.to_bool gnuradio-3.7.2.1/docs/sphinx/source/pmt/message_accepter.rst0000664000175000017500000000024312207440367023715 0ustar jcorganjcorganpmt: Message Accepter ===================== .. autofunction:: pmt.is_msg_accepter .. autofunction:: pmt.make_msg_accepter .. autofunction:: pmt.msg_accepter_ref gnuradio-3.7.2.1/docs/sphinx/source/pmt/readwrite.rst0000664000175000017500000000023712207440367022414 0ustar jcorganjcorganpmt: Read/Write =============== .. autofunction:: pmt.is_eof_object .. autofunction:: pmt.read .. autofunction:: pmt.write .. autofunction:: pmt.write_string gnuradio-3.7.2.1/docs/sphinx/source/pmt/serialize.rst0000664000175000017500000000031512207440367022412 0ustar jcorganjcorganpmt: Serialize ============== .. autofunction:: pmt.serialize .. autofunction:: pmt.deserialize .. autofunction:: pmt.dump_sizeof .. autofunction:: pmt.serialize_str .. autofunction:: pmt.deserialize_str gnuradio-3.7.2.1/docs/sphinx/source/fec.rst0000664000175000017500000000023012207440367020354 0ustar jcorganjcorgangnuradio.fec ============ .. automodule:: gnuradio.fec .. autoblock:: gnuradio.fec.decode_ccsds_27_fb .. autoblock:: gnuradio.fec.encode_ccsds_27_bb gnuradio-3.7.2.1/docs/sphinx/source/filter/0000775000175000017500000000000012207440367020357 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/filter/filter_blk.rst0000664000175000017500000000125512207440367023231 0ustar jcorganjcorgangnuradio.filter: Filters ======================== .. autoblock:: gnuradio.filter.adaptive_fir_ccc .. autoblock:: gnuradio.filter.adaptive_fir_ccf .. autoblock:: gnuradio.filter.dc_blocker_cc .. autoblock:: gnuradio.filter.dc_blocker_ff .. autoblock:: gnuradio.filter.fft_filter_fff .. autoblock:: gnuradio.filter.fft_filter_ccc .. autoblock:: gnuradio.filter.filter_delay_fc .. autoblock:: gnuradio.filter.hilbert_fc .. autoblock:: gnuradio.filter.iir_filter_ffd .. autopyblock:: gnuradio.filter.analysis_filterbank .. autopyblock:: gnuradio.filter.synthesis_filterbank .. autoblock:: gnuradio.filter.single_pole_iir_filter_cc .. autoblock:: gnuradio.filter.single_pole_iir_filter_ff gnuradio-3.7.2.1/docs/sphinx/source/filter/resamplers_blk.rst0000664000175000017500000000060412207440367024116 0ustar jcorganjcorgangnuradio.filter: Resamplers =========================== .. autoblock:: gnuradio.filter.fractional_interpolator_cc .. autoblock:: gnuradio.filter.fractional_interpolator_ff .. autoblock:: gnuradio.filter.fractional_resampler_cc .. autoblock:: gnuradio.filter.fractional_resampler_ff .. autoblock:: gnuradio.filter.pfb_arb_resampler_ccf .. autoblock:: gnuradio.filter.pfb_arb_resampler_fffgnuradio-3.7.2.1/docs/sphinx/source/filter/filter_design.rst0000664000175000017500000000016512207440367023731 0ustar jcorganjcorgangnuradio.filter: Digital Filter Design ====================================== .. autoclass:: gnuradio.filter.firdes gnuradio-3.7.2.1/docs/sphinx/source/filter/index.rst0000664000175000017500000000233012207440367022216 0ustar jcorganjcorgangnuradio.filter =============== .. automodule:: gnuradio.filter Channelizers ------------ .. autosummary:: :nosignatures: gnuradio.filter.pfb_channelizer_ccf gnuradio.filter.pfb_decimator_ccf gnuradio.filter.pfb_interpolator_ccf gnuradio.filter.pfb_synthesizer_ccf Filters ------- .. autosummary:: :nosignatures: gnuradio.filter.adaptive_fir_ccc gnuradio.filter.adaptive_fir_ccf gnuradio.filter.dc_blocker_cc gnuradio.filter.dc_blocker_ff gnuradio.filter.fft_filter_fff gnuradio.filter.fft_filter_ccc gnuradio.filter.filter_delay_fc gnuradio.filter.hilbert_fc gnuradio.filter.iir_filter_ffd gnuradio.filter.analysis_filterbank gnuradio.filter.synthesis_filterbank gnuradio.filter.single_pole_iir_filter_cc gnuradio.filter.single_pole_iir_filter_ff Resamplers ---------- .. autosummary:: :nosignatures: gnuradio.filter.fractional_interpolator_cc gnuradio.filter.fractional_interpolator_ff gnuradio.filter.fractional_resampler_cc gnuradio.filter.fractional_resampler_ff gnuradio.filter.pfb_arb_resampler_ccf gnuradio.filter.pfb_arb_resampler_fff Digital Filter Design --------------------- .. autosummary:: :nosignatures: gnuradio.filter.firdes gnuradio-3.7.2.1/docs/sphinx/source/filter/channelizers_blk.rst0000664000175000017500000000040712207440367024427 0ustar jcorganjcorgangnuradio.filter: Channelizers ============================= .. autoblock:: gnuradio.filter.pfb_channelizer_ccf .. autoblock:: gnuradio.filter.pfb_decimator_ccf .. autoblock:: gnuradio.filter.pfb_interpolator_ccf .. autoblock:: gnuradio.filter.pfb_synthesizer_ccfgnuradio-3.7.2.1/docs/sphinx/source/wavelet.rst0000664000175000017500000000030212207440367021266 0ustar jcorganjcorgangnuradio.wavelet ================ .. automodule:: gnuradio.wavelet .. autoblock:: gnuradio.wavelet.squash_ff .. autoblock:: gnuradio.wavelet.wavelet_ff .. autoblock:: gnuradio.wavelet.wvps_ff gnuradio-3.7.2.1/docs/sphinx/source/trellis/0000755000175000017500000000000012207440367020546 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/trellis/blks.rst0000664000175000017500000000566112207440367022245 0ustar jcorganjcorgangnuradio.trellis: Signal Processing Blocks ========================================== .. autoblock:: gnuradio.trellis.constellation_metrics_cf .. autoblock:: gnuradio.trellis.encoder_bb .. autoblock:: gnuradio.trellis.encoder_bi .. autoblock:: gnuradio.trellis.encoder_bs .. autoblock:: gnuradio.trellis.encoder_ii .. autoblock:: gnuradio.trellis.encoder_si .. autoblock:: gnuradio.trellis.encoder_ss .. autoblock:: gnuradio.trellis.metrics_c .. autoblock:: gnuradio.trellis.metrics_f .. autoblock:: gnuradio.trellis.metrics_i .. autoblock:: gnuradio.trellis.metrics_s .. autoblock:: gnuradio.trellis.pccc_decoder_b .. autoblock:: gnuradio.trellis.pccc_decoder_combined_cb .. autoblock:: gnuradio.trellis.pccc_decoder_combined_ci .. autoblock:: gnuradio.trellis.pccc_decoder_combined_cs .. autoblock:: gnuradio.trellis.pccc_decoder_combined_fb .. autoblock:: gnuradio.trellis.pccc_decoder_combined_fi .. autoblock:: gnuradio.trellis.pccc_decoder_combined_fs .. autoblock:: gnuradio.trellis.pccc_decoder_i .. autoblock:: gnuradio.trellis.pccc_decoder_s .. autoblock:: gnuradio.trellis.pccc_encoder_bb .. autoblock:: gnuradio.trellis.pccc_encoder_bi .. autoblock:: gnuradio.trellis.pccc_encoder_bs .. autoblock:: gnuradio.trellis.pccc_encoder_ii .. autoblock:: gnuradio.trellis.pccc_encoder_si .. autoblock:: gnuradio.trellis.pccc_encoder_ss .. autoblock:: gnuradio.trellis.permutation .. autoblock:: gnuradio.trellis.sccc_decoder_b .. autoblock:: gnuradio.trellis.sccc_decoder_combined_cb .. autoblock:: gnuradio.trellis.sccc_decoder_combined_ci .. autoblock:: gnuradio.trellis.sccc_decoder_combined_cs .. autoblock:: gnuradio.trellis.sccc_decoder_combined_fb .. autoblock:: gnuradio.trellis.sccc_decoder_combined_fi .. autoblock:: gnuradio.trellis.sccc_decoder_combined_fs .. autoblock:: gnuradio.trellis.sccc_decoder_i .. autoblock:: gnuradio.trellis.sccc_decoder_s .. autoblock:: gnuradio.trellis.sccc_encoder_bb .. autoblock:: gnuradio.trellis.sccc_encoder_bi .. autoblock:: gnuradio.trellis.sccc_encoder_bs .. autoblock:: gnuradio.trellis.sccc_encoder_ii .. autoblock:: gnuradio.trellis.sccc_encoder_si .. autoblock:: gnuradio.trellis.sccc_encoder_ss .. autoblock:: gnuradio.trellis.siso_combined_f .. autoblock:: gnuradio.trellis.siso_f .. autoblock:: gnuradio.trellis.viterbi_b .. autoblock:: gnuradio.trellis.viterbi_combined_cb .. autoblock:: gnuradio.trellis.viterbi_combined_ci .. autoblock:: gnuradio.trellis.viterbi_combined_cs .. autoblock:: gnuradio.trellis.viterbi_combined_fb .. autoblock:: gnuradio.trellis.viterbi_combined_fi .. autoblock:: gnuradio.trellis.viterbi_combined_fs .. autoblock:: gnuradio.trellis.viterbi_combined_ib .. autoblock:: gnuradio.trellis.viterbi_combined_ii .. autoblock:: gnuradio.trellis.viterbi_combined_is .. autoblock:: gnuradio.trellis.viterbi_combined_sb .. autoblock:: gnuradio.trellis.viterbi_combined_si .. autoblock:: gnuradio.trellis.viterbi_combined_ss .. autoblock:: gnuradio.trellis.viterbi_i .. autoblock:: gnuradio.trellis.viterbi_s gnuradio-3.7.2.1/docs/sphinx/source/trellis/index.rst0000644000175000017500000000507411765410647022423 0ustar jcorganjcorgangnuradio.trellis ================ .. automodule:: gnuradio.trellis Object Classes -------------- .. autosummary:: :nosignatures: gnuradio.trellis.fsm gnuradio.trellis.interleaver Signal Processing Blocks ------------------------ .. autosummary:: :nosignatures: gnuradio.trellis.constellation_metrics_cf gnuradio.trellis.encoder_bb gnuradio.trellis.encoder_bi gnuradio.trellis.encoder_bs gnuradio.trellis.encoder_ii gnuradio.trellis.encoder_si gnuradio.trellis.encoder_ss gnuradio.trellis.metrics_c gnuradio.trellis.metrics_f gnuradio.trellis.metrics_i gnuradio.trellis.metrics_s gnuradio.trellis.pccc_decoder_b gnuradio.trellis.pccc_decoder_combined_cb gnuradio.trellis.pccc_decoder_combined_ci gnuradio.trellis.pccc_decoder_combined_cs gnuradio.trellis.pccc_decoder_combined_fb gnuradio.trellis.pccc_decoder_combined_fi gnuradio.trellis.pccc_decoder_combined_fs gnuradio.trellis.pccc_decoder_i gnuradio.trellis.pccc_decoder_s gnuradio.trellis.pccc_encoder_bb gnuradio.trellis.pccc_encoder_bi gnuradio.trellis.pccc_encoder_bs gnuradio.trellis.pccc_encoder_ii gnuradio.trellis.pccc_encoder_si gnuradio.trellis.pccc_encoder_ss gnuradio.trellis.permutation gnuradio.trellis.sccc_decoder_b gnuradio.trellis.sccc_decoder_combined_cb gnuradio.trellis.sccc_decoder_combined_ci gnuradio.trellis.sccc_decoder_combined_cs gnuradio.trellis.sccc_decoder_combined_fb gnuradio.trellis.sccc_decoder_combined_fi gnuradio.trellis.sccc_decoder_combined_fs gnuradio.trellis.sccc_decoder_i gnuradio.trellis.sccc_decoder_s gnuradio.trellis.sccc_encoder_bb gnuradio.trellis.sccc_encoder_bi gnuradio.trellis.sccc_encoder_bs gnuradio.trellis.sccc_encoder_ii gnuradio.trellis.sccc_encoder_si gnuradio.trellis.sccc_encoder_ss gnuradio.trellis.siso_combined_f gnuradio.trellis.siso_f gnuradio.trellis.viterbi_b gnuradio.trellis.viterbi_combined_cb gnuradio.trellis.viterbi_combined_ci gnuradio.trellis.viterbi_combined_cs gnuradio.trellis.viterbi_combined_fb gnuradio.trellis.viterbi_combined_fi gnuradio.trellis.viterbi_combined_fs gnuradio.trellis.viterbi_combined_ib gnuradio.trellis.viterbi_combined_ii gnuradio.trellis.viterbi_combined_is gnuradio.trellis.viterbi_combined_sb gnuradio.trellis.viterbi_combined_si gnuradio.trellis.viterbi_combined_ss gnuradio.trellis.viterbi_i gnuradio.trellis.viterbi_s Constants --------- .. autosummary:: :nosignatures: gnuradio.trellis.TRELLIS_MIN_SUM gnuradio.trellis.TRELLIS_SUM_PRODUCT gnuradio-3.7.2.1/docs/sphinx/source/trellis/objs.rst0000644000175000017500000000022311765410647022240 0ustar jcorganjcorgangnuradio.trellis: Object Classes -------------------------------- .. autoclass:: gnuradio.trellis.fsm .. autoclass:: gnuradio.trellis.interleaver gnuradio-3.7.2.1/docs/sphinx/source/noaa.rst0000664000175000017500000000027312207440367020544 0ustar jcorganjcorgangnuradio.noaa ============== .. automodule:: gnuradio.noaa .. autoblock:: gnuradio.noaa.hrpt_decoder .. autoblock:: gnuradio.noaa.hrpt_deframer .. autoblock:: gnuradio.noaa.hrpt_pll_cf gnuradio-3.7.2.1/docs/sphinx/source/vocoder/0000755000175000017500000000000012207440367020531 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/vocoder/blks.rst0000664000175000017500000000144712207440367022226 0ustar jcorganjcorgangnuradio.vocoder ================ .. autoblock:: gnuradio.vocoder.alaw_decode_bs .. autoblock:: gnuradio.vocoder.alaw_encode_sb .. autoblock:: gnuradio.vocoder.codec2_decode_ps .. autoblock:: gnuradio.vocoder.codec2_encode_sp .. autoblock:: gnuradio.vocoder.cvsd_decode_bs .. autoblock:: gnuradio.vocoder.cvsd_encode_sb .. autoblock:: gnuradio.vocoder.g721_decode_bs .. autoblock:: gnuradio.vocoder.g721_encode_sb .. autoblock:: gnuradio.vocoder.g723_24_decode_bs .. autoblock:: gnuradio.vocoder.g723_24_encode_sb .. autoblock:: gnuradio.vocoder.g723_40_decode_bs .. autoblock:: gnuradio.vocoder.g723_40_encode_sb .. autoblock:: gnuradio.vocoder.gsm_fr_decode_ps .. autoblock:: gnuradio.vocoder.gsm_fr_encode_sp .. autoblock:: gnuradio.vocoder.ulaw_decode_bs .. autoblock:: gnuradio.vocoder.ulaw_encode_sb gnuradio-3.7.2.1/docs/sphinx/source/vocoder/index.rst0000644000175000017500000000136311765410647022403 0ustar jcorganjcorgangnuradio.vocoder ================ .. automodule:: gnuradio.vocoder .. autosummary:: :nosignatures: gnuradio.vocoder.alaw_decode_bs gnuradio.vocoder.alaw_encode_sb gnuradio.vocoder.codec2_decode_ps gnuradio.vocoder.codec2_encode_sp gnuradio.vocoder.cvsd_decode_bf gnuradio.vocoder.cvsd_decode_bs gnuradio.vocoder.cvsd_encode_fb gnuradio.vocoder.cvsd_encode_sb gnuradio.vocoder.g721_decode_bs gnuradio.vocoder.g721_encode_sb gnuradio.vocoder.g723_24_decode_bs gnuradio.vocoder.g723_24_encode_sb gnuradio.vocoder.g723_40_decode_bs gnuradio.vocoder.g723_40_encode_sb gnuradio.vocoder.gsm_fr_decode_ps gnuradio.vocoder.gsm_fr_encode_sp gnuradio.vocoder.ulaw_decode_bs gnuradio.vocoder.ulaw_encode_sb gnuradio-3.7.2.1/docs/sphinx/source/gr/0000755000175000017500000000000012207440367017500 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/gr/index.rst0000664000175000017500000000072312207440367021345 0ustar jcorganjcorgangnuradio.gr =========== .. automodule:: gnuradio.gr .. autosummary:: :nosignatures: gnuradio.gr.top_block gnuradio.gr.hier_block2 gnuradio.gr.block_detail gnuradio.gr.buffer gnuradio.gr.dispatcher gnuradio.gr.single_threaded_scheduler gnuradio.gr.prefs gnuradio.gr.message gnuradio.gr.msg_queue gnuradio.gr.enable_realtime_scheduling gnuradio.gr.feval_dd gnuradio.gr.feval_cc gnuradio.gr.feval_ll gnuradio.gr.feval gnuradio-3.7.2.1/docs/sphinx/source/gr/contents.rst0000664000175000017500000000113312207440367022067 0ustar jcorganjcorgangnuradio.gr =========== .. autoclass:: gnuradio.gr.top_block .. autoclass:: gnuradio.gr.hier_block2 .. autofunction:: gnuradio.gr.block_detail .. autofunction:: gnuradio.gr.buffer .. autofunction:: gnuradio.gr.dispatcher .. autofunction:: gnuradio.gr.single_threaded_scheduler .. autofunction:: gnuradio.gr.prefs .. autofunction:: gnuradio.gr.message .. autofunction:: gnuradio.gr.msg_queue .. autofunction:: gnuradio.gr.enable_realtime_scheduling .. autofunction:: gnuradio.gr.feval_dd .. autofunction:: gnuradio.gr.feval_cc .. autofunction:: gnuradio.gr.feval_ll .. autofunction:: gnuradio.gr.feval gnuradio-3.7.2.1/docs/sphinx/source/pyqt_plot.rst0000644000175000017500000000017311765410647021664 0ustar jcorganjcorgangnuradio.pyqt_plot ================== .. automodule:: gnuradio.pyqt_plot .. autoclass:: gnuradio.pyqt_plot.Ui_MainWindow gnuradio-3.7.2.1/docs/sphinx/source/gr_unittest/0000755000175000017500000000000011765410647021445 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/gr_unittest/index.rst0000644000175000017500000000025111765410647023304 0ustar jcorganjcorgangnuradio.gr_unittest ==================== .. automodule:: gnuradio.gr_unittest .. autoclass:: gnuradio.gr_unittest.TestCase .. autofunction:: gnuradio.gr_unittest.run gnuradio-3.7.2.1/docs/sphinx/source/audio/0000755000175000017500000000000012207440367020171 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/audio/index.rst0000664000175000017500000000020712207440367022033 0ustar jcorganjcorgangnuradio.audio ============== .. automodule:: gnuradio.audio .. autoblock:: gnuradio.audio.source .. autoblock:: gnuradio.audio.sink gnuradio-3.7.2.1/docs/sphinx/source/pager/0000755000175000017500000000000012207440367020166 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/pager/blks.rst0000664000175000017500000000052012207440367021652 0ustar jcorganjcorgangnuradio.pager: Signal Processing Blocks ======================================== .. autoblock:: gnuradio.pager.flex_deinterleave .. autopyblock:: gnuradio.pager.flex_demod .. autoblock:: gnuradio.pager.flex_frame .. autoblock:: gnuradio.pager.flex_parse .. autoblock:: gnuradio.pager.flex_sync .. autoblock:: gnuradio.pager.slicer_fb gnuradio-3.7.2.1/docs/sphinx/source/pager/index.rst0000644000175000017500000000070011765410647022032 0ustar jcorganjcorgangnuradio.pager ============== .. automodule:: gnuradio.pager Signal Processing Blocks ------------------------ .. autosummary:: :nosignatures: gnuradio.pager.flex_deinterleave gnuradio.pager.flex_demod gnuradio.pager.flex_frame gnuradio.pager.flex_parse gnuradio.pager.flex_sync gnuradio.pager.pager_flex_frame gnuradio.pager.slicer_fb Utility Functions ----------------- .. autofunction:: gnuradio.pager.queue_runner gnuradio-3.7.2.1/docs/sphinx/source/conf.py.in0000644000175000017500000001610011765410647021000 0ustar jcorganjcorgan# -*- coding: utf-8 -*- # # GNU Radio documentation build configuration file, created by # sphinx-quickstart on Sun Oct 16 22:27:51 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('@CMAKE_CURRENT_SOURCE_DIR@')) sys.path.insert(0, '@CMAKE_INSTALL_PREFIX@/@GR_PYTHON_DIR@') # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.autosummary', 'sphinx.ext.mathjax', 'gnuradio_sphinx', 'hieroglyph'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'GNU Radio' copyright = u'2012, Free Software Foundation' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '@VERSION@' # The full version, including alpha/beta/rc tags. release = '@VERSION@' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'GNURadiodoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'GNURadio.tex', u'GNU Radio Documentation', u'Free Software Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'gnuradio', u'GNU Radio Documentation', [u'Free Software Foundation'], 1) ] gnuradio-3.7.2.1/docs/sphinx/source/fft.rst0000664000175000017500000000203612207440367020404 0ustar jcorganjcorgangnuradio.fft ============ .. automodule:: gnuradio.fft .. autoblock:: gnuradio.fft.fft_vcc .. autoblock:: gnuradio.fft.fft_vfc .. autoblock:: gnuradio.fft.goertzel_fc gnuradio.fft.window =================== .. automodule:: gnuradio.fft.window .. autofunction:: gnuradio.fft.window.bartlett .. autofunction:: gnuradio.fft.window.blackman2 .. autofunction:: gnuradio.fft.window.blackman3 .. autofunction:: gnuradio.fft.window.blackman4 .. autofunction:: gnuradio.fft.window.blackmanharris .. autofunction:: gnuradio.fft.window.coswindow .. autofunction:: gnuradio.fft.window.exponential .. autofunction:: gnuradio.fft.window.flattop .. autofunction:: gnuradio.fft.window.hamming .. autofunction:: gnuradio.fft.window.hanning .. autofunction:: gnuradio.fft.window.kaiser .. autofunction:: gnuradio.fft.window.nuttall .. autofunction:: gnuradio.fft.window.nuttall_cfd .. autofunction:: gnuradio.fft.window.parzen .. autofunction:: gnuradio.fft.window.rectangular .. autofunction:: gnuradio.fft.window.riemann .. autofunction:: gnuradio.fft.window.welch gnuradio-3.7.2.1/docs/sphinx/source/analog/0000775000175000017500000000000012207440367020333 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/analog/peak_detectors_blk.rst0000664000175000017500000000014712207440367024713 0ustar jcorganjcorgangnuradio.analog: Peak Detectors =============================== .. autoblock:: gnuradio.analog.dpll_bbgnuradio-3.7.2.1/docs/sphinx/source/analog/modulators_blk.rst0000664000175000017500000000050612207440367024107 0ustar jcorganjcorgangnuradio.analog: Modulators and Demodulators ============================================ .. autoblock:: gnuradio.analog.cpfsk_bc .. autoblock:: gnuradio.analog.fmdet_cf .. autoblock:: gnuradio.analog.frequency_modulator_fc .. autoblock:: gnuradio.analog.phase_modulator_fc .. autoblock:: gnuradio.analog.quadrature_demod_cf gnuradio-3.7.2.1/docs/sphinx/source/analog/get_blocks.py0000664000175000017500000000617712207440367023034 0ustar jcorganjcorgan""" This script regenerates the gnuradio.blocks sphinx source code. """ from gnuradio import analog import sys import os doxyxml_location = os.path.abspath("../../../doxygen") xml_location = os.path.abspath("../../../../build/docs/doxygen/xml/") sys.path.append(doxyxml_location) from doxyxml import DoxyIndex, DoxyClass, DoxyFriend, DoxyFunction, DoxyFile, DoxyGroup from doxyxml import DoxyOther, base class Block(object): """ Checks if doxyxml produced objects correspond to a new style gnuradio block. """ @classmethod def includes(cls, item): if not isinstance(item, DoxyClass): return False # Check for a parsing error. if item.error(): return False is_a_block = item.has_member('make', DoxyFunction) and item.has_member('sptr', DoxyOther) return is_a_block class Group(object): """ Checks if doxyxml produced objects correspond to a group. """ @classmethod def includes(cls, item): if not isinstance(item, DoxyGroup): return False # Check for a parsing error. if item.error(): return False return True def main(): di = DoxyIndex(xml_location) blocks = di.in_category(Block) analog_blocks = [] for block in blocks: if block.name().startswith("gr::analog::"): analog_blocks.append(block) all_grouped_blocks = [] groups = di.in_category(Group) groupinfo = [] for group in groups: contains_analog_blocks = False block_list = [] members = group.members() for member in members: if member.name().startswith("gr::analog"): all_grouped_blocks.append(member) if not contains_analog_blocks: contains_analog_blocks = True groupinfo.append((group.name(), group.title, block_list)) block_list.append(member) for block in analog_blocks: if block not in all_grouped_blocks: print("Didn't find block {0}".format(block.name())) blockindex = ["""gnuradio.analog =============== .. automodule:: gnuradio.analog"""] for groupname, grouptitle, blocks in groupinfo: blockindex.append("") blockindex.append(grouptitle) blockindex.append('-'*len(grouptitle)) blockindex.append(""" .. autosummary:: :nosignatures: """) for block in blocks: blockindex.append(" gnuradio.analog.{0}".format( block.name()[len("gr::analog::"):])) grouppage = [] title = "gnuradio.analog: {0}".format(grouptitle) grouppage.append(title) grouppage.append('='*len(title)) grouppage.append('') for block in blocks: shortname = block.name()[len("gr::analog::"):] grouppage.append(".. autoblock:: gnuradio.analog.{0}".format(shortname)) text = '\n'.join(grouppage) f = open("{0}.rst".format(groupname), 'w') f.write(text) f.close() text = "\n".join(blockindex) f = open("index.rst", 'w') f.write(text) f.close() if __name__ == '__main__': main() gnuradio-3.7.2.1/docs/sphinx/source/analog/index.rst0000664000175000017500000000224112207440367022173 0ustar jcorganjcorgangnuradio.analog =============== .. automodule:: gnuradio.analog Level Controllers ----------------- .. autosummary:: :nosignatures: gnuradio.analog.agc_cc gnuradio.analog.agc2_cc gnuradio.analog.agc2_ff gnuradio.analog.agc_ff gnuradio.analog.ctcss_squelch_ff gnuradio.analog.feedforward_agc_cc gnuradio.analog.pwr_squelch_cc gnuradio.analog.pwr_squelch_ff gnuradio.analog.rail_ff gnuradio.analog.simple_squelch_cc Measurement Tools ----------------- .. autosummary:: :nosignatures: gnuradio.analog.probe_avg_mag_sqrd_c gnuradio.analog.probe_avg_mag_sqrd_cf gnuradio.analog.probe_avg_mag_sqrd_f Modulators and Demodulators --------------------------- .. autosummary:: :nosignatures: gnuradio.analog.cpfsk_bc gnuradio.analog.fmdet_cf gnuradio.analog.frequency_modulator_fc gnuradio.analog.phase_modulator_fc gnuradio.analog.quadrature_demod_cf Peak Detectors -------------- .. autosummary:: :nosignatures: gnuradio.analog.dpll_bb Synchronizers ------------- .. autosummary:: :nosignatures: gnuradio.analog.pll_carriertracking_cc gnuradio.analog.pll_freqdet_cf gnuradio.analog.pll_refout_cc gnuradio-3.7.2.1/docs/sphinx/source/analog/synchronizers_blk.rst0000664000175000017500000000031712207440367024636 0ustar jcorganjcorgangnuradio.analog: Synchronizers ============================== .. autoblock:: gnuradio.analog.pll_carriertracking_cc .. autoblock:: gnuradio.analog.pll_freqdet_cf .. autoblock:: gnuradio.analog.pll_refout_ccgnuradio-3.7.2.1/docs/sphinx/source/analog/measurement_tools_blk.rst0000664000175000017500000000034312207440367025462 0ustar jcorganjcorgangnuradio.analog: Measurement Tools ================================== .. autoblock:: gnuradio.analog.probe_avg_mag_sqrd_c .. autoblock:: gnuradio.analog.probe_avg_mag_sqrd_cf .. autoblock:: gnuradio.analog.probe_avg_mag_sqrd_fgnuradio-3.7.2.1/docs/sphinx/source/analog/level_controllers_blk.rst0000664000175000017500000000076712207440367025464 0ustar jcorganjcorgangnuradio.analog: Level Controllers ================================== .. autoblock:: gnuradio.analog.agc_cc .. autoblock:: gnuradio.analog.agc2_cc .. autoblock:: gnuradio.analog.agc2_ff .. autoblock:: gnuradio.analog.agc_ff .. autoblock:: gnuradio.analog.ctcss_squelch_ff .. autoblock:: gnuradio.analog.feedforward_agc_cc .. autoblock:: gnuradio.analog.pwr_squelch_cc .. autoblock:: gnuradio.analog.pwr_squelch_ff .. autoblock:: gnuradio.analog.rail_ff .. autoblock:: gnuradio.analog.simple_squelch_cc gnuradio-3.7.2.1/docs/sphinx/source/comedi.rst0000664000175000017500000000022112207440367021057 0ustar jcorganjcorgangnuradio.comedi =============== .. automodule:: gnuradio.comedi .. autoblock:: gnuradio.comedi.source_s .. autoblock:: gnuradio.comedi.sink_s gnuradio-3.7.2.1/docs/sphinx/source/atsc/0000755000175000017500000000000011765410647020030 5ustar jcorganjcorgangnuradio-3.7.2.1/docs/sphinx/source/atsc/blks.rst0000644000175000017500000000147211765410647021521 0ustar jcorganjcorgangnuradio.atsc: Signal Processing Blocks ======================================= .. autooldblock:: gnuradio.atsc.bit_timing_loop .. autooldblock:: gnuradio.atsc.deinterleaver .. autooldblock:: gnuradio.atsc.depad .. autooldblock:: gnuradio.atsc.derandomizer .. autooldblock:: gnuradio.atsc.ds_to_softds .. autooldblock:: gnuradio.atsc.equalizer .. autooldblock:: gnuradio.atsc.field_sync_demux .. autooldblock:: gnuradio.atsc.field_sync_mux .. autooldblock:: gnuradio.atsc.fpll .. autooldblock:: gnuradio.atsc.fs_checker .. autooldblock:: gnuradio.atsc.interleaver .. autooldblock:: gnuradio.atsc.pad .. autooldblock:: gnuradio.atsc.randomizer .. autooldblock:: gnuradio.atsc.rs_decoder .. autooldblock:: gnuradio.atsc.rs_encoder .. autooldblock:: gnuradio.atsc.trellis_encoder .. autooldblock:: gnuradio.atsc.viterbi_decoder gnuradio-3.7.2.1/docs/sphinx/source/atsc/index.rst0000644000175000017500000000313611765410647021674 0ustar jcorganjcorgangnuradio.atsc ============= .. automodule:: gnuradio.atsc Signal Processing Blocks ------------------------ .. autosummary:: :nosignatures: gnuradio.atsc.bit_timing_loop gnuradio.atsc.deinterleaver gnuradio.atsc.depad gnuradio.atsc.derandomizer gnuradio.atsc.ds_to_softds gnuradio.atsc.equalizer gnuradio.atsc.field_sync_demux gnuradio.atsc.field_sync_mux gnuradio.atsc.fpll gnuradio.atsc.fs_checker gnuradio.atsc.interleaver gnuradio.atsc.pad gnuradio.atsc.randomizer gnuradio.atsc.rs_decoder gnuradio.atsc.rs_encoder gnuradio.atsc.trellis_encoder gnuradio.atsc.viterbi_decoder Constants --------- .. autosummary:: :nosignatures: gnuradio.atsc.ATSC_DATA_SEGMENT_LENGTH gnuradio.atsc.ATSC_DATA_SEGMENT_RATE gnuradio.atsc.ATSC_DSEGS_PER_FIELD gnuradio.atsc.ATSC_MPEG_DATA_LENGTH gnuradio.atsc.ATSC_MPEG_PKT_LENGTH gnuradio.atsc.ATSC_MPEG_RS_ENCODED_LENGTH gnuradio.atsc.ATSC_SYMBOL_RATE gnuradio.atsc.MPEG_SYNC_BYTE gnuradio.atsc.MPEG_TRANSPORT_ERROR_BIT Sizes --------- .. autosummary:: :nosignatures: gnuradio.atsc.sizeof_atsc_data_segment gnuradio.atsc.sizeof_atsc_data_segment_pad gnuradio.atsc.sizeof_atsc_mpeg_packet gnuradio.atsc.sizeof_atsc_mpeg_packet_no_sync gnuradio.atsc.sizeof_atsc_mpeg_packet_no_sync_pad gnuradio.atsc.sizeof_atsc_mpeg_packet_pad gnuradio.atsc.sizeof_atsc_mpeg_packet_rs_encoded gnuradio.atsc.sizeof_atsc_mpeg_packet_rs_encoded_pad gnuradio.atsc.sizeof_atsc_soft_data_segment gnuradio.atsc.sizeof_atsc_soft_data_segment_pad gnuradio-3.7.2.1/docs/sphinx/source/index.rst0000664000175000017500000000776512207440367020752 0ustar jcorganjcorgangnuradio ======== .. automodule:: gnuradio Core Framework -------------- .. autosummary:: :nosignatures: gnuradio.gr pmt gnuradio.blocks gnuradio.analog gnuradio.digital gnuradio.audio gnuradio.channels gnuradio.comedi gnuradio.fec gnuradio.filter gnuradio.trellis gnuradio.wavelet gnuradio.fft gnuradio.gr_unittest gnuradio.qtgui gnuradio.wxgui .. toctree:: :hidden: gnuradio.gr pmt gnuradio.blocks gnuradio.analog gnuradio.digital gnuradio.audio